Repository: rust
Issue: Panic about invalid identifier `"SomeIdentifier::Something"` from proc macro produces ICE at call-side code
Labels: I-ICE,T-compiler,C-bug

<!--
Thank you for finding an Internal Compiler Error! 🧊  If possible, try to provide
a minimal verifiable example. You can read "Rust Bug Minimization Patterns" for
how to create smaller examples.

http://blog.pnkfx.org/blog/2019/11/18/rust-bug-minimization-patterns/

-->

### Code

I'm not sure if this is actually a ICE or not, but I decided to write a post to give more experienced people a chance to figure it out.


Crate with proc_macro. Cargo.toml and actually code.
```
[package]
name = "procedural_macros"
version = "0.1.0"
authors = ["Me <name>"]
edition = "2018"

[lib]
name = "procedural_macros"
proc-macro = true

# ===== Dependencies =====

[dependencies.proc-macro2]
version = "^1.0"

[dependencies.quote]
version = "^1.0"

[dependencies.syn]
version = "^1.0"
features = ["visit"]
```

```Rust
extern crate proc_macro;
extern crate quote;

use proc_macro::{TokenStream};
use proc_macro2 as pm2;

use syn::parse::{Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::{parse_macro_input, Expr, Ident, Token};
use quote::ToTokens;

struct SimplePgQuery {
    model: Ident,
    executor: Expr,
    params: Vec<(Expr, Expr, usize)>,
}

impl Parse for SimplePgQuery {
    fn parse(input: ParseStream) -> Result<Self> {
        let model: Ident = input.parse()?;
        input.parse::<Token![,]>()?;

        let executor: Expr = input.parse()?;
        input.parse::<Token![,]>()?;

        let mut params = vec![];
        let mut counter = 1;
        for m in Punctuated::<Expr, Token![,]>::parse_terminated(input)?.iter() {

            let tmp_s = m.to_token_stream().to_string();
            let mut strings = vec![];
            for s in tmp_s.split('=') {
                   strings.push(s);
            }
            let column_name = Expr::Verbatim(strings.get(0).unwrap().parse()?);
            let value = Expr::Verbatim(strings.get(1).unwrap().parse()?);
            counter += 1;

            params.push((column_name, value, counter));
        }
        Ok(SimplePgQuery { model, executor, params, })
    }
}

#[proc_macro]
pub fn pg_query(input: TokenStream) -> TokenStream {
    let SimplePgQuery { model, executor, params} = parse_macro_input!(input);

    let table_name_ident = pm2::Ident::new(&format!("{}::TABLE_NAME", model.to_string()), pm2::Span::call_site());
    let select_from_clause = quote::quote!(
        "SELECT * FROM ", #table_name_ident,
    );
    let mut add_c = pm2::TokenStream::new();
    let mut and_clause = pm2::TokenStream::new();
    let params_len = params.len();
    for p in params {

        let (field_name, field_val) = (p.0, p.1);

        let _num = p.2.to_string();
        let num = quote::quote!(#_num);

        if p.2 - 1 != params_len {
            and_clause = quote::quote!(#and_clause #field_name = $#num AND);
        } else {
            and_clause = quote::quote!(#and_clause #field_name = $#num);
        }

        add_c = quote::quote!(#add_c .add_c(#field_val));
    }

    let with_brackets = pm2::Group::new(
        pm2::Delimiter::Parenthesis,
        quote::quote!(#select_from_clause #and_clause)
    );

    let finalized_clause = quote::quote!(
        concatcp! #with_brackets
    );

    let expanded = quote::quote!({
        use $crate::shared::helper_traits::ChainedArguments as _;

        sqlx::query_as_with::<_, #model, _>(
            #finalized_clause,
            sqlx::postgres::PgArguments::default() #add_c,
        )
            .fetch_optional(#executor).await
    });

    let result = TokenStream::from(expanded);
    eprintln!("{:}", result);
    result
}

```

Project has structure like
my_project
|__procedural_macros
    |__ src
|__ src // code below written here 

My code from another crate, which uses this proc macro
```Rust
async fn mre() {

    struct User1 {}
    impl User1 {
        pub const TABLE_NAME: &'static str = "users";
    }
    let login = "my_login".to_string();
    let email_var = "asfg@123.com".to_string();
    let s = pg_query!(User1, &mut executor, login=login, email=email_var); // there are no executor, but is does not matter
}
```

### Meta
<!--
If you're using the stable version of the compiler, you should also check if the
bug also exists in the beta or nightly versions.
-->

`rustc --version --verbose`:
```
rustc 1.53.0-nightly (07e0e2ec2 2021-03-24)
binary: rustc
commit-hash: 07e0e2ec268c140e607e1ac7f49f145612d0f597
commit-date: 2021-03-24
host: x86_64-pc-windows-msvc
release: 1.53.0-nightly
LLVM version: 12.0.0
```

### Error output

```
error: internal compiler error: unexpected panic
note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md
note: rustc 1.53.0-nightly (07e0e2ec2 2021-03-24) running on x86_64-pc-windows-msvc
note: compiler flags: -C embed-bitcode=no -C debuginfo=2 -C incremental
note: some of the compiler flags provided by cargo are hidden
query stack during panic:
end of query stack
error: proc macro panicked
   --> src\main.rs:120:13
    |
120 |     let s = pg_query!(User1, &mut executor, login=login, email=email_var);
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = help: message: `"User1::TABLE_NAME"` is not a valid identifier

error: aborting due to previous error

error: could not compile `optimeet_actix`
To learn more, run the command again with --verbose.
Process finished with exit code 101

```

<!--
Include a backtrace in the code block by setting `RUST_BACKTRACE=1` in your
environment. E.g. `RUST_BACKTRACE=1 cargo build`.
-->
<details><summary><strong>Backtrace</strong></summary>
<p>

```
C:/Users/gosha/.cargo/bin/cargo.exe test --color=always --message-format=json-diagnostic-rendered-ansi --no-run --package optimeet_actix --bin optimeet_actix test
   Compiling optimeet_actix v0.1.0 (C:\Users\gosha\CLionProjects\optimeet_actix)
thread 'rustc' panicked at '`"User1::TABLE_NAME"` is not a valid identifier', compiler\rustc_expand\src\proc_macro_server.rs:336:13
stack backtrace:
   0:     0x7ffdc51877ee - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h62553bb33d269d2e
   1:     0x7ffdc51b27cc - core::fmt::write::h187a24ff0c56237d
   2:     0x7ffdc517b208 - <std::io::IoSlice as core::fmt::Debug>::fmt::h7a51133a1941366b
   3:     0x7ffdc518ba02 - std::panicking::take_hook::ha7af702674468c4c
   4:     0x7ffdc518b4da - std::panicking::take_hook::ha7af702674468c4c
   5:     0x7ffd9424b057 - rustc_driver::report_ice::h530a14ca8f015ece
   6:     0x7ffdc518c1e5 - std::panicking::rust_panic_with_hook::hffdabf0e02906eb3
   7:     0x7ffdc518bdc1 - rust_begin_unwind
   8:     0x7ffdc518810f - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h62553bb33d269d2e
   9:     0x7ffdc518bd19 - rust_begin_unwind
  10:     0x7ffdc51e463c - std::panicking::begin_panic_fmt::h5f113f8f74763d19
  11:     0x7ffd97a1bdab - <proc_macro::Delimiter as rustc_expand::proc_macro_server::ToInternal<rustc_ast::token::DelimToken>>::to_internal::h23f7c824802ad284
  12:     0x7ffd97a6c6ca - <rustc_expand::mbe::transcribe::Frame as core::iter::traits::iterator::Iterator>::next::hc101c5ca12f7d7b4
  13:     0x7ffd97ae84be - rustc_expand::base::MacEager::ty::hf66ef54cd82a2887
  14:     0x7ffdacc4500c - proc_macro::bridge::closure::Closure::call
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\closure.rs:27
  15:     0x7ffdacc4500c - proc_macro::bridge::client::{{impl}}::new::{{closure}}
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:244
  16:     0x7ffdacc4500c - proc_macro::bridge::client::{{impl}}::with::{{closure}}
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:297
  17:     0x7ffdacc4500c - proc_macro::bridge::client::{{impl}}::with::{{closure}}::{{closure}}
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:293
  18:     0x7ffdacc4500c - proc_macro::bridge::scoped_cell::ScopedCell::replace
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\scoped_cell.rs:75
  19:     0x7ffdacc4500c - proc_macro::bridge::client::{{impl}}::with::{{closure}}
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:291
  20:     0x7ffdacc4500c - std::thread::local::LocalKey::try_with
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\library\std\src\thread\local.rs:272
  21:     0x7ffdacc4500c - std::thread::local::LocalKey::with
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\library\std\src\thread\local.rs:248
  22:     0x7ffdacc4500c - proc_macro::bridge::client::BridgeState::with
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:290
  23:     0x7ffdacc4500c - proc_macro::bridge::Bridge::with
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:329
  24:     0x7ffdacc4500c - proc_macro::bridge::client::Ident::new
                               at /rustc/07e0e2ec268c140e607e1ac7f49f145612d0f597\/library\proc_macro\src\bridge\client.rs:237
  25:     0x7ffdacc280c4 - proc_macro2::imp::Ident::new
                               at C:\Users\gosha\.cargo\registry\src\github.com-1ecc6299db9ec823\proc-macro2-1.0.24\src\wrapper.rs:668
  26:     0x7ffdacc1412c - proc_macro2::Ident::new
                               at C:\Users\gosha\.cargo\registry\src\github.com-1ecc6299db9ec823\proc-macro2-1.0.24\src\lib.rs:895
  27:     0x7ffdacaea8cf - procedural_macros::pg_query
                               at C:\Users\gosha\CLionProjects\optimeet_actix\procedural_macros\src\lib.rs:102
  28:     0x7ffdacae500e - core::ops::function::FnOnce::call_once<fn(proc_macro::TokenStream) -> proc_macro::TokenStream,tuple<proc_macro::TokenStream>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\core\src\ops\function.rs:227
  29:     0x7ffdacaecaf6 - proc_macro::bridge::client::{{impl}}::expand1::run::{{closure}}<fn(proc_macro::TokenStream) -> proc_macro::TokenStream>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:410
  30:     0x7ffdacaec14a - proc_macro::bridge::client::run_client::{{closure}}::{{closure}}<proc_macro::bridge::client::TokenStream,proc_macro::bridge::client::TokenStream,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:377
  31:     0x7ffdacae12b8 - proc_macro::bridge::scoped_cell::{{impl}}::set::{{closure}}<proc_macro::bridge::client::BridgeStateL,tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\scoped_cell.rs:80
  32:     0x7ffdacae16fc - proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>::replace<proc_macro::bridge::client::BridgeStateL,tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\scoped_cell.rs:75
  33:     0x7ffdacae1297 - proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>::set<proc_macro::bridge::client::BridgeStateL,tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\scoped_cell.rs:80
  34:     0x7ffdacaec8b0 - proc_macro::bridge::client::{{impl}}::enter::{{closure}}<tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:325
  35:     0x7ffdacae7358 - std::thread::local::LocalKey<proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>>::try_with<proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>,closure-1,tuple<>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\thread\local.rs:272
  36:     0x7ffdacae7233 - std::thread::local::LocalKey<proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>>::with<proc_macro::bridge::scoped_cell::ScopedCell<proc_macro::bridge::client::BridgeStateL>,closure-1,tuple<>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\thread\local.rs:248
  37:     0x7ffdacae6647 - proc_macro::bridge::Bridge::enter<tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:325
  38:     0x7ffdacaec077 - proc_macro::bridge::client::run_client::{{closure}}<proc_macro::bridge::client::TokenStream,proc_macro::bridge::client::TokenStream,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:370
  39:     0x7ffdacae1021 - std::panic::{{impl}}::call_once<tuple<>,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:344
  40:     0x7ffdacae5c9b - std::panicking::try::do_call<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:379
  41:     0x7ffdacae5d83 - std::panicking::try::do_catch<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
  42:     0x7ffdacae5bdb - std::panicking::try<tuple<>,std::panic::AssertUnwindSafe<closure-0>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panicking.rs:343
  43:     0x7ffdacae1054 - std::panic::catch_unwind<std::panic::AssertUnwindSafe<closure-0>,tuple<>>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\std\src\panic.rs:431
  44:     0x7ffdacaebed3 - proc_macro::bridge::client::run_client<proc_macro::bridge::client::TokenStream,proc_macro::bridge::client::TokenStream,closure-0>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:369
  45:     0x7ffdacaeca83 - proc_macro::bridge::client::{{impl}}::expand1::run<fn(proc_macro::TokenStream) -> proc_macro::TokenStream>
                               at C:\Users\gosha\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\lib\rustlib\src\rust\library\proc_macro\src\bridge\client.rs:410
  46:     0x7ffd97a6bab9 - <rustc_expand::mbe::transcribe::Frame as core::iter::traits::iterator::Iterator>::next::hc101c5ca12f7d7b4
  47:     0x7ffd97a4f8ee - <rustc_expand::proc_macro::BangProcMacro as rustc_expand::base::ProcMacro>::expand::ha6c7e4ae01d15bf2
  48:     0x7ffd97a33ce5 - rustc_expand::expand::MacroExpander::fully_expand_fragment::h546b3d6090ae35d8
  49:     0x7ffd97a31ea1 - rustc_expand::expand::MacroExpander::expand_crate::h29457354fdef570e
  50:     0x7ffd9436a57a - <rls_span::compiler::_::<impl serde::de::Deserialize for rls_span::compiler::DiagnosticSpanMacroExpansion>::deserialize::__Visitor as serde::de::Visitor>::expecting::hd5b46ca79c97c9e8
  51:     0x7ffd9438dc0e - rustc_interface::passes::BoxedResolver::to_resolver_outputs::h26a866d2af02ca21
  52:     0x7ffd94428c59 - rustc_interface::interface::try_print_query_stack::h01bfbfe9eda229d6
  53:     0x7ffd94411c13 - rustc_interface::util::commit_date_str::hf818b05ff2345c85
  54:     0x7ffd9438c997 - <rls_span::compiler::_::<impl serde::de::Deserialize for rls_span::compiler::DiagnosticSpanMacroExpansion>::deserialize::__Visitor as serde::de::Visitor>::expecting::hd5b46ca79c97c9e8
  55:     0x7ffd9439c178 - rustc_interface::queries::Queries::expansion::hd60c52385c2fe72c
  56:     0x7ffd94262681 - <rustc_middle::ty::SymbolName as core::fmt::Debug>::fmt::h898edfdbf8c7dbdf
  57:     0x7ffd942c16bc - <rustc_driver::args::Error as core::fmt::Debug>::fmt::h54d0345b5b43328e
  58:     0x7ffd942651eb - <rustc_middle::ty::SymbolName as core::fmt::Debug>::fmt::h898edfdbf8c7dbdf
  59:     0x7ffd94254034 - rustc_driver::pretty::print_after_hir_lowering::h04bf553be4aa75de
  60:     0x7ffd9426745f - <rustc_middle::ty::SymbolName as core::fmt::Debug>::fmt::h898edfdbf8c7dbdf
  61:     0x7ffd9428676d - <rustc_hir::intravisit::ErasedMap as rustc_hir::intravisit::Map>::foreign_item::he23d70bdee5d6fd3
  62:     0x7ffdc519b16a - std::sys::windows::thread::Thread::new::h485ded1a10d2ce17
  63:     0x7ffe175e7034 - BaseThreadInitThunk
  64:     0x7ffe18522651 - RtlUserThreadStart
error: internal compiler error: unexpected panic
note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md
note: rustc 1.53.0-nightly (07e0e2ec2 2021-03-24) running on x86_64-pc-windows-msvc
note: compiler flags: -C embed-bitcode=no -C debuginfo=2 -C incremental
note: some of the compiler flags provided by cargo are hidden
query stack during panic:
end of query stack
error: proc macro panicked
   --> src\main.rs:120:13
    |
120 |     let s = pg_query!(User1, &mut executor, login=login, email=email_var);
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = help: message: `"User1::TABLE_NAME"` is not a valid identifier

error: aborting due to previous error

error: could not compile `optimeet_actix`
To learn more, run the command again with --verbose.
Process finished with exit code 101
```

</p>
</details>