diff --git a/compiler/rustc_builtin_macros/src/concat.rs b/compiler/rustc_builtin_macros/src/concat.rs index c200539e12872..f59849a03d6ce 100644 --- a/compiler/rustc_builtin_macros/src/concat.rs +++ b/compiler/rustc_builtin_macros/src/concat.rs @@ -24,6 +24,8 @@ pub(crate) fn expand_concat( let mut guar = None; for e in es { match e.kind { + // For consistent user experience, please keep this in sync with the handling of + // literals in `rustc_expand::mbe::metavar_expr` `${concat()}`! ExprKind::Lit(token_lit) => match LitKind::from_token_lit(token_lit) { Ok(LitKind::Str(s, _) | LitKind::Float(s, _)) => { accumulator.push_str(s.as_str()); diff --git a/compiler/rustc_expand/messages.ftl b/compiler/rustc_expand/messages.ftl index 3fc0fa0619145..eca7482b9bd94 100644 --- a/compiler/rustc_expand/messages.ftl +++ b/compiler/rustc_expand/messages.ftl @@ -133,6 +133,58 @@ expand_module_multiple_candidates = expand_must_repeat_once = this must repeat at least once +expand_mve_concat_invalid_in = + invalid item within a {"`${concat(..)}`"} expression + .metavar_label = expanding this metavariable + .float_lit = float literals cannot be concatenated + .c_str_lit = C string literals cannot be concatenated + .b_str_lit = byte literals cannot be concatenated + .raw_ident = raw identifiers cannot be concatenated + .unsupported = unsupported input for `concat(..)` + .valid_types = `concat` can join {$valid} + .expected_metavar = expected an identifier + .expected_metavar_dollar = `$` indicates the start of a metavariable + .invalid_metavar = expanding something + .valid_metavars = {"`${concat(..)}`"} can join metavariables of type {$valid} + +expand_mve_concat_invalid_out = + invalid item within a {"`${concat(..)}`"} would produce an invalid identifier + .label = todo + +expand_mve_expected_ident = + expected an identifier + .not_ident = not a valid identifier + .expr_name = expected a metavariable expression name: `{"${expr( /* ... */ )}"}` + .expr_name_note = valid metavariable expressions are {$valid_expr_list} + .ignore_expr_note = `ignore` takes a metavariable argument + .count_expr_note = `count` takes a metavariable argument + +expand_mve_extra_tokens = + unexpected trailing tokens + .label = for this metavariable expression + .range = the `{$name}` metavariable expression takes between {$min_or_exact_args} and {$max_args} arguments + .exact = the `{$name}` metavariable expression takes {$min_or_exact_args -> + [zero] no arguments + [one] a single argument + *[other] {$min_or_exact_args} arguments + } + .suggestion = try removing {$extra_count -> + [one] this token + *[other] these tokens + } + +expand_mve_missing_paren = + expected `(` + .label = for this this metavariable expression + .unexpected = unexpected token + .note = metavariable expressions use function-like parentheses syntax + .suggestion = try adding parentheses + +expand_mve_unrecognized_expr = + unrecognized metavariable expression + .label = not a valid metavariable expression + .note = valid metavariable expressions are {$valid_expr_list} + expand_mve_unrecognized_var = variable `{$key}` is not recognized in meta-variable expression diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index fdbc65aff688c..0a3ab3d3f3221 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -496,6 +496,127 @@ pub(crate) use metavar_exprs::*; mod metavar_exprs { use super::*; + #[derive(Diagnostic, Default)] + #[diag(expand_mve_extra_tokens)] + pub(crate) struct MveExtraTokens { + #[primary_span] + #[suggestion(code = "", applicability = "machine-applicable")] + pub span: Span, + #[label] + pub ident_span: Span, + pub extra_count: usize, + + // The rest is only used for specific diagnostics and can be default if neither + // `note` is `Some`. + #[note(expand_exact)] + pub exact_args_note: Option<()>, + #[note(expand_range)] + pub range_args_note: Option<()>, + pub min_or_exact_args: usize, + pub max_args: usize, + pub name: &'static str, + } + + #[derive(Diagnostic)] + #[note] + #[diag(expand_mve_missing_paren)] + pub(crate) struct MveMissingParen { + #[primary_span] + #[label] + pub ident_span: Span, + #[label(expand_unexpected)] + pub unexpected_span: Option, + #[suggestion(code = "( /* ... */ )", applicability = "has-placeholders")] + pub insert_span: Option, + } + + #[derive(Diagnostic)] + #[note] + #[diag(expand_mve_unrecognized_expr)] + pub(crate) struct MveUnrecognizedExpr { + #[primary_span] + #[label] + pub span: Span, + pub valid_expr_list: &'static str, + } + + #[derive(Diagnostic)] + #[diag(expand_mve_concat_invalid_in)] + pub(crate) struct MveConcatInvalidTy { + #[primary_span] + // #[label] + pub span: Span, + #[label(expand_metavar_label)] + pub metavar_span: Option, + #[subdiagnostic] + pub reason: MveConcatInvalidTyReason, + pub valid: &'static str, + } + + // TODO: can these be labels rather than notes? + #[derive(Subdiagnostic)] + pub(crate) enum MveConcatInvalidTyReason { + InvalidIdent, + #[note(expand_float_lit)] + #[note(expand_valid_types)] + FloatLit, + #[note(expand_c_str_lit)] + #[note(expand_valid_types)] + CStrLit, + #[note(expand_b_str_lit)] + #[note(expand_valid_types)] + ByteStrLit, + #[note(expand_expected_metavar)] + #[label(expand_expected_metavar_dollar)] + ExpectedMetavarIdent { + #[primary_span] + dollar: Span, + }, + #[note(expand_raw_ident)] + RawIdentifier, + #[note(expand_unsupported)] + #[note(expand_valid_types)] + UnsupportedInput, + #[note(expand_invalid_metavar)] + #[note(expand_valid_metavars)] + InvalidMetavarTy, + /// Nothing to point out because an error was already emitted. + InvalidLiteral, + } + + #[derive(Diagnostic)] + #[note] + #[diag(expand_mve_concat_invalid_out)] + pub(crate) struct MveConcatInvalidOut { + #[primary_span] + #[label] + pub span: Span, + } + + #[derive(Diagnostic)] + #[diag(expand_mve_expected_ident)] + pub(crate) struct MveExpectedIdent { + #[primary_span] + pub span: Span, + #[label(expand_not_ident)] + pub not_ident_label: Option, + /// This error is reused a handful of places, the context here tells us how to customize + /// the message. + #[subdiagnostic] + pub context: MveExpectedIdentContext, + } + + #[derive(Subdiagnostic)] + pub(crate) enum MveExpectedIdentContext { + #[note(expand_expr_name)] + #[note(expand_expr_name_note)] + ExprName { valid_expr_list: &'static str }, + #[note(expand_ignore_expr_note)] + Ignore, + #[note(expand_count_expr_note)] + Count, + } + #[derive(Diagnostic)] #[diag(expand_mve_unrecognized_var)] pub(crate) struct MveUnrecognizedVar { diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index ffd3548019a8e..ef45af892575d 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -1,14 +1,41 @@ -use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, Token, TokenKind}; +use rustc_ast::token::{self, Delimiter, IdentIsRaw, Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree}; -use rustc_ast::{LitIntType, LitKind}; +use rustc_ast::{self as ast, LitIntType, LitKind}; use rustc_ast_pretty::pprust; -use rustc_errors::{Applicability, PResult}; +use rustc_errors::{DiagCtxtHandle, PResult}; +use rustc_lexer::is_id_continue; use rustc_macros::{Decodable, Encodable}; +use rustc_session::errors::create_lit_error; use rustc_session::parse::ParseSess; use rustc_span::{Ident, Span, Symbol}; -pub(crate) const RAW_IDENT_ERR: &str = "`${concat(..)}` currently does not support raw identifiers"; -pub(crate) const UNSUPPORTED_CONCAT_ELEM_ERR: &str = "expected identifier or string literal"; +use crate::errors::{self, MveConcatInvalidTyReason, MveExpectedIdentContext}; + +pub(crate) const VALID_EXPR_CONCAT_TYPES: &str = + "metavariables, identifiers, string literals, and integer literals"; + +/// Argument specification for a metavariable expression +#[derive(Clone, Copy)] +enum ArgSpec { + /// Any number of args + Any, + /// Between n and m args (inclusive) + Between(usize, usize), + /// Exactly n args + Exact(usize), +} + +/// Map of `(name, max_arg_count, variable_count)`. +const EXPR_NAME_ARG_MAP: &[(&str, ArgSpec)] = &[ + ("concat", ArgSpec::Any), + ("count", ArgSpec::Between(1, 2)), + ("ignore", ArgSpec::Exact(1)), + ("index", ArgSpec::Between(0, 1)), + ("len", ArgSpec::Between(0, 1)), +]; + +/// List of the above for diagnostics +const VALID_METAVAR_EXPR_NAMES: &str = "`count`, `ignore`, `index`, `len`, and `concat`"; /// A meta-variable expression, for expansions based on properties of meta-variables. #[derive(Debug, PartialEq, Encodable, Decodable)] @@ -39,35 +66,60 @@ impl MetaVarExpr { psess: &'psess ParseSess, ) -> PResult<'psess, MetaVarExpr> { let mut iter = input.iter(); - let ident = parse_ident(&mut iter, psess, outer_span)?; - let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = iter.next() else { - let msg = "meta-variable expression parameter must be wrapped in parentheses"; - return Err(psess.dcx().struct_span_err(ident.span, msg)); + let ident = parse_ident( + &mut iter, + psess, + outer_span, + MveExpectedIdentContext::ExprName { valid_expr_list: VALID_METAVAR_EXPR_NAMES }, + )?; + + let next = iter.next(); + let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = next else { + // No `()`; wrong or no delimiters. Point at a problematic span or a place to + // add parens if it makes sense. + let (unexpected_span, insert_span) = match next { + Some(TokenTree::Delimited(..)) => (None, None), + Some(tt) => (Some(tt.span()), None), + None => (None, Some(ident.span.shrink_to_hi())), + }; + let err = + errors::MveMissingParen { ident_span: ident.span, unexpected_span, insert_span }; + return Err(psess.dcx().create_err(err)); }; - check_trailing_token(&mut iter, psess)?; + + // Ensure there are no trailing tokens in the braces, e.g. `${foo() extra}` + if iter.peek().is_some() { + let span = iter_span(&iter).expect("checked is_some above"); + let err = errors::MveExtraTokens { + span, + ident_span: ident.span, + extra_count: iter.count(), + ..Default::default() + }; + return Err(psess.dcx().create_err(err)); + } + let mut iter = args.iter(); let rslt = match ident.as_str() { "concat" => parse_concat(&mut iter, psess, outer_span, ident.span)?, "count" => parse_count(&mut iter, psess, ident.span)?, "ignore" => { eat_dollar(&mut iter, psess, ident.span)?; - MetaVarExpr::Ignore(parse_ident(&mut iter, psess, ident.span)?) + let ident = + parse_ident(&mut iter, psess, outer_span, MveExpectedIdentContext::Ignore)?; + MetaVarExpr::Ignore(ident) } "index" => MetaVarExpr::Index(parse_depth(&mut iter, psess, ident.span)?), "len" => MetaVarExpr::Len(parse_depth(&mut iter, psess, ident.span)?), _ => { - let err_msg = "unrecognized meta-variable expression"; - let mut err = psess.dcx().struct_span_err(ident.span, err_msg); - err.span_suggestion( - ident.span, - "supported expressions are count, ignore, index and len", - "", - Applicability::MachineApplicable, - ); - return Err(err); + let err = errors::MveUnrecognizedExpr { + span: ident.span, + valid_expr_list: VALID_METAVAR_EXPR_NAMES, + }; + return Err(psess.dcx().create_err(err)); } }; - check_trailing_token(&mut iter, psess)?; + check_trailing_tokens(&mut iter, psess, ident)?; Ok(rslt) } @@ -87,20 +139,51 @@ impl MetaVarExpr { } } -// Checks if there are any remaining tokens. For example, `${ignore(ident ... a b c ...)}` -fn check_trailing_token<'psess>( +/// Checks if there are any remaining tokens (for example, `${ignore($valid, extra)}`) and create +/// a diag with the correct arg count if so. +fn check_trailing_tokens<'psess>( iter: &mut TokenStreamIter<'_>, psess: &'psess ParseSess, + ident: Ident, ) -> PResult<'psess, ()> { - if let Some(tt) = iter.next() { - let mut diag = psess - .dcx() - .struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt))); - diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens"); - Err(diag) - } else { - Ok(()) + if iter.peek().is_none() { + // All tokens consumed, as expected + return Ok(()); } + + let (name, spec) = EXPR_NAME_ARG_MAP + .iter() + .find(|(name, _)| *name == ident.as_str()) + .expect("called with an invalid name"); + + let (min_or_exact_args, max_args) = match *spec { + // For expressions like `concat`, all tokens should be consumed already + ArgSpec::Any => panic!("{name} takes unlimited tokens but didn't eat them all"), + ArgSpec::Between(min, max) => (min, Some(max)), + ArgSpec::Exact(n) => (n, None), + }; + + let err = errors::MveExtraTokens { + span: iter_span(iter).expect("checked is_none above"), + ident_span: ident.span, + extra_count: iter.count(), + + exact_args_note: if max_args.is_some() { None } else { Some(()) }, + range_args_note: if max_args.is_some() { Some(()) } else { None }, + min_or_exact_args, + max_args: max_args.unwrap_or_default(), + name, + }; + Err(psess.dcx().create_err(err)) +} + +/// Returns a span encompassing all tokens in the iterator if there is at least one item. +fn iter_span(iter: &TokenStreamIter<'_>) -> Option { + let mut iter = iter.clone(); // cloning is cheap + let first_sp = iter.next()?.span(); + let last_sp = iter.last().map(TokenTree::span).unwrap_or(first_sp); + let span = first_sp.with_hi(last_sp.hi()); + Some(span) } /// Indicates what is placed in a `concat` parameter. For example, literals @@ -109,7 +192,7 @@ fn check_trailing_token<'psess>( pub(crate) enum MetaVarExprConcatElem { /// Identifier WITHOUT a preceding dollar sign, which means that this identifier should be /// interpreted as a literal. - Ident(Ident), + Ident(String), /// For example, a number or a string. Literal(Symbol), /// Identifier WITH a preceding dollar sign, which means that this identifier should be @@ -125,30 +208,50 @@ fn parse_concat<'psess>( expr_ident_span: Span, ) -> PResult<'psess, MetaVarExpr> { let mut result = Vec::new(); + let dcx = psess.dcx(); loop { - let is_var = try_eat_dollar(iter); - let token = parse_token(iter, psess, outer_span)?; - let element = if is_var { - MetaVarExprConcatElem::Var(parse_ident_from_token(psess, token)?) - } else if let TokenKind::Literal(Lit { kind: token::LitKind::Str, symbol, suffix: None }) = - token.kind - { - MetaVarExprConcatElem::Literal(symbol) - } else { - match parse_ident_from_token(psess, token) { - Err(err) => { - err.cancel(); - return Err(psess - .dcx() - .struct_span_err(token.span, UNSUPPORTED_CONCAT_ELEM_ERR)); - } - Ok(elem) => MetaVarExprConcatElem::Ident(elem), + let dollar = try_eat_dollar(iter); + let Some(tt) = iter.next() else { + // May be hit only with the first iteration (peek is otherwise checked at the end). + break; + }; + + let make_err = |reason| { + let err = errors::MveConcatInvalidTy { + span: tt.span(), + metavar_span: None, + reason, + valid: VALID_EXPR_CONCAT_TYPES, + }; + Err(dcx.create_err(err)) + }; + + let token = match tt { + TokenTree::Token(token, _) => *token, + TokenTree::Delimited(..) => { + return make_err(MveConcatInvalidTyReason::UnsupportedInput); } }; + + let element = if let Some(dollar) = dollar { + // Expecting a metavar + let Some((ident, _)) = token.ident() else { + return make_err(MveConcatInvalidTyReason::ExpectedMetavarIdent { dollar }); + }; + + // Variables get passed untouched + MetaVarExprConcatElem::Var(ident) + } else { + MetaVarExprConcatElem::Ident(parse_tok_for_concat(psess, token)?) + }; + result.push(element); + if iter.peek().is_none() { + // break before trying to eat the comma break; } + if !try_eat_comma(iter) { return Err(psess.dcx().struct_span_err(outer_span, "expected comma")); } @@ -168,7 +271,7 @@ fn parse_count<'psess>( span: Span, ) -> PResult<'psess, MetaVarExpr> { eat_dollar(iter, psess, span)?; - let ident = parse_ident(iter, psess, span)?; + let ident = parse_ident(iter, psess, span, MveExpectedIdentContext::Count)?; let depth = if try_eat_comma(iter) { if iter.peek().is_none() { return Err(psess.dcx().struct_span_err( @@ -206,51 +309,94 @@ fn parse_depth<'psess>( } } -/// Parses an generic ident -fn parse_ident<'psess>( - iter: &mut TokenStreamIter<'_>, +/// Validate that a token can be concatenated as an identifier, then stringify it. +pub(super) fn parse_tok_for_concat<'psess>( psess: &'psess ParseSess, - fallback_span: Span, -) -> PResult<'psess, Ident> { - let token = parse_token(iter, psess, fallback_span)?; - parse_ident_from_token(psess, token) -} + token: Token, +) -> PResult<'psess, String> { + let dcx = psess.dcx(); + let make_err = |reason| { + let err = errors::MveConcatInvalidTy { + span: token.span, + metavar_span: None, + reason, + valid: VALID_EXPR_CONCAT_TYPES, + }; + Err(dcx.create_err(err)) + }; -fn parse_ident_from_token<'psess>( - psess: &'psess ParseSess, - token: &Token, -) -> PResult<'psess, Ident> { - if let Some((elem, is_raw)) = token.ident() { - if let IdentIsRaw::Yes = is_raw { - return Err(psess.dcx().struct_span_err(elem.span, RAW_IDENT_ERR)); + let elem = if let TokenKind::Literal(lit) = token.kind { + // Preprocess with `from_token_lit` to handle unescaping, float / int literal suffix + // stripping. + // + // For consistent user experience, please keep this in sync with the handling of + // literals in `rustc_builtin_macros::concat`! + let s = match ast::LitKind::from_token_lit(lit.clone()) { + Ok(ast::LitKind::Str(s, _)) => s.to_string(), + Ok(ast::LitKind::Float(..)) => { + return make_err(MveConcatInvalidTyReason::FloatLit); + } + Ok(ast::LitKind::Char(c)) => c.to_string(), + Ok(ast::LitKind::Int(i, _)) => i.to_string(), + Ok(ast::LitKind::Bool(b)) => b.to_string(), + Ok(ast::LitKind::CStr(..)) => return make_err(MveConcatInvalidTyReason::CStrLit), + Ok(ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..)) => { + return make_err(MveConcatInvalidTyReason::ByteStrLit); + } + Ok(ast::LitKind::Err(_guarantee)) => { + // REVIEW: a diagnostic was already emitted, should we just break? + return make_err(MveConcatInvalidTyReason::InvalidLiteral); + } + Err(err) => return Err(create_lit_error(psess, err, lit, token.span)), + }; + + if !s.chars().all(|ch| is_id_continue(ch)) { + // Check that all characters are valid in the middle of an identifier. This doesn't + // guarantee that the final identifier is valid (we still need to check it later), + // but it allows us to catch errors with specific arguments before expansion time; + // for example, string literal "foo.bar" gets flagged before the macro is invoked. + return make_err(MveConcatInvalidTyReason::InvalidIdent); } - return Ok(elem); - } - let token_str = pprust::token_to_string(token); - let mut err = psess - .dcx() - .struct_span_err(token.span, format!("expected identifier, found `{token_str}`")); - err.span_suggestion( - token.span, - format!("try removing `{token_str}`"), - "", - Applicability::MaybeIncorrect, - ); - Err(err) + + s + } else if let Some((elem, is_raw)) = token.ident() { + if is_raw == IdentIsRaw::Yes { + return make_err(MveConcatInvalidTyReason::RawIdentifier); + } + elem.as_str().to_string() + } else { + return make_err(MveConcatInvalidTyReason::UnsupportedInput); + }; + + Ok(elem) } -fn parse_token<'psess, 't>( - iter: &mut TokenStreamIter<'t>, +/// Tries to parse a generic ident. If this fails, create a missing identifier diagnostic with +/// `context` explanation. +fn parse_ident<'psess>( + iter: &mut TokenStreamIter<'_>, psess: &'psess ParseSess, fallback_span: Span, -) -> PResult<'psess, &'t Token> { + context: MveExpectedIdentContext, +) -> PResult<'psess, Ident> { let Some(tt) = iter.next() else { - return Err(psess.dcx().struct_span_err(fallback_span, UNSUPPORTED_CONCAT_ELEM_ERR)); + let err = errors::MveExpectedIdent { span: fallback_span, not_ident_label: None, context }; + return Err(psess.dcx().create_err(err)); }; + let TokenTree::Token(token, _) = tt else { - return Err(psess.dcx().struct_span_err(tt.span(), UNSUPPORTED_CONCAT_ELEM_ERR)); + let span = tt.span(); + let err = errors::MveExpectedIdent { span, not_ident_label: Some(span), context }; + return Err(psess.dcx().create_err(err)); + }; + + let Some((elem, _)) = token.ident() else { + let span = token.span; + let err = errors::MveExpectedIdent { span, not_ident_label: Some(span), context }; + return Err(psess.dcx().create_err(err)); }; - Ok(token) + + Ok(elem) } /// Tries to move the iterator forward returning `true` if there is a comma. If not, then the @@ -263,14 +409,14 @@ fn try_eat_comma(iter: &mut TokenStreamIter<'_>) -> bool { false } -/// Tries to move the iterator forward returning `true` if there is a dollar sign. If not, then the -/// iterator is not modified and the result is `false`. -fn try_eat_dollar(iter: &mut TokenStreamIter<'_>) -> bool { - if let Some(TokenTree::Token(Token { kind: token::Dollar, .. }, _)) = iter.peek() { +/// Tries to move the iterator forward returning `Some(dollar_span)` if there is a dollar sign. If +/// not, then the iterator is not modified and the result is `None`. +fn try_eat_dollar(iter: &mut TokenStreamIter<'_>) -> Option { + if let Some(TokenTree::Token(Token { kind: token::Dollar, span }, _)) = iter.peek() { let _ = iter.next(); - return true; + return Some(*span); } - false + None } /// Expects that the next item is a dollar sign. @@ -279,7 +425,7 @@ fn eat_dollar<'psess>( psess: &'psess ParseSess, span: Span, ) -> PResult<'psess, ()> { - if try_eat_dollar(iter) { + if try_eat_dollar(iter).is_some() { return Ok(()); } Err(psess.dcx().struct_span_err( diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 174844d6ad639..009ee6c27c457 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -16,15 +16,18 @@ use rustc_span::{ }; use smallvec::{SmallVec, smallvec}; +use super::metavar_expr::parse_tok_for_concat; use crate::errors::{ - CountRepetitionMisplaced, MetaVarsDifSeqMatchers, MustRepeatOnce, MveUnrecognizedVar, + self, CountRepetitionMisplaced, MetaVarsDifSeqMatchers, MustRepeatOnce, MveUnrecognizedVar, NoSyntaxVarsExprRepeat, VarStillRepeating, }; use crate::mbe::macro_parser::NamedMatch; use crate::mbe::macro_parser::NamedMatch::*; -use crate::mbe::metavar_expr::{MetaVarExprConcatElem, RAW_IDENT_ERR}; +use crate::mbe::metavar_expr::{MetaVarExprConcatElem, VALID_EXPR_CONCAT_TYPES}; use crate::mbe::{self, KleeneOp, MetaVarExpr}; +const VALID_METAVAR_CONCAT_TYPES: &str = "`ident`, `literal`, and `tt`"; + /// Context needed to perform transcription of metavariable expressions. struct TranscrCtx<'psess, 'itp> { psess: &'psess ParseSess, @@ -545,9 +548,10 @@ fn metavar_expr_concat<'tx>( let dcx = tscx.psess.dcx(); let mut concatenated = String::new(); for element in elements.into_iter() { - let symbol = match element { - MetaVarExprConcatElem::Ident(elem) => elem.name, - MetaVarExprConcatElem::Literal(elem) => *elem, + let tmp_sym; + let sym_str = match element { + MetaVarExprConcatElem::Ident(elem) => elem.as_str(), + MetaVarExprConcatElem::Literal(elem) => elem.as_str(), MetaVarExprConcatElem::Var(ident) => { match matched_from_ident(dcx, *ident, tscx.interp)? { NamedMatch::MatchedSeq(named_matches) => { @@ -557,16 +561,20 @@ fn metavar_expr_concat<'tx>( match &named_matches[*curr_idx] { // FIXME(c410-f3r) Nested repetitions are unimplemented MatchedSeq(_) => unimplemented!(), - MatchedSingle(pnr) => extract_symbol_from_pnr(dcx, pnr, ident.span)?, + MatchedSingle(pnr) => { + tmp_sym = extract_symbol_from_pnr(tscx, pnr, ident.span)?; + tmp_sym.as_str() + } } } NamedMatch::MatchedSingle(pnr) => { - extract_symbol_from_pnr(dcx, pnr, ident.span)? + tmp_sym = extract_symbol_from_pnr(tscx, pnr, ident.span)?; + tmp_sym.as_str() } } } }; - concatenated.push_str(symbol.as_str()); + concatenated.push_str(sym_str); } let symbol = nfc_normalize(&concatenated); let concatenated_span = tscx.visited_dspan(dspan); @@ -900,46 +908,37 @@ fn out_of_bounds_err<'a>(dcx: DiagCtxtHandle<'a>, max: usize, span: Span, ty: &s } /// Extracts an metavariable symbol that can be an identifier, a token tree or a literal. -fn extract_symbol_from_pnr<'a>( - dcx: DiagCtxtHandle<'a>, +fn extract_symbol_from_pnr<'tx>( + tscx: &mut TranscrCtx<'tx, '_>, pnr: &ParseNtResult, - span_err: Span, -) -> PResult<'a, Symbol> { - match pnr { - ParseNtResult::Ident(nt_ident, is_raw) => { - if let IdentIsRaw::Yes = is_raw { - Err(dcx.struct_span_err(span_err, RAW_IDENT_ERR)) - } else { - Ok(nt_ident.name) - } - } - ParseNtResult::Tt(TokenTree::Token( - Token { kind: TokenKind::Ident(symbol, is_raw), .. }, - _, - )) => { - if let IdentIsRaw::Yes = is_raw { - Err(dcx.struct_span_err(span_err, RAW_IDENT_ERR)) - } else { - Ok(*symbol) - } + metavar_span: Span, +) -> PResult<'tx, String> { + // Reconstruct a `Token` so we can share logic with expression parsing. + let token = match pnr { + ParseNtResult::Tt(TokenTree::Token(tok, _)) => *tok, + ParseNtResult::Ident(Ident { name, span }, ident_is_raw) => { + Token { kind: TokenKind::Ident(*name, *ident_is_raw), span: *span } + } + + ParseNtResult::Literal(l) if let ExprKind::Lit(lit) = l.kind => { + Token { kind: TokenKind::Literal(lit), span: l.span } + } + _ => { + let err = errors::MveConcatInvalidTy { + span: pnr.span(), + metavar_span: Some(metavar_span), + reason: errors::MveConcatInvalidTyReason::InvalidMetavarTy, + valid: VALID_METAVAR_CONCAT_TYPES, + }; + return Err(tscx.psess.dcx().create_err(err)); } - ParseNtResult::Tt(TokenTree::Token( - Token { - kind: TokenKind::Literal(Lit { kind: LitKind::Str, symbol, suffix: None }), - .. - }, - _, - )) => Ok(*symbol), - ParseNtResult::Literal(expr) - if let ExprKind::Lit(Lit { kind: LitKind::Str, symbol, suffix: None }) = &expr.kind => - { - Ok(*symbol) - } - _ => Err(dcx - .struct_err( - "metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt`", - ) - .with_note("currently only string literals are supported") - .with_span(span_err)), - } + }; + + parse_tok_for_concat(tscx.psess, token) + // _ => Err(dcx + // .struct_err( + // "metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt`", + // ) + // .with_note("currently only string literals are supported") + // .with_span(span_err)), } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index cfc0399b0ca96..48d234e82fa59 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1657,3 +1657,24 @@ pub enum ParseNtResult { Path(P), Vis(P), } + +impl ParseNtResult { + #[inline] + pub fn span(&self) -> Span { + match self { + ParseNtResult::Tt(token_tree) => token_tree.span(), + ParseNtResult::Ident(ident, ..) => ident.span, + ParseNtResult::Lifetime(ident, ..) => ident.span, + ParseNtResult::Item(item) => item.span, + ParseNtResult::Block(block) => block.span, + ParseNtResult::Stmt(stmt) => stmt.span, + ParseNtResult::Pat(pat, ..) => pat.span, + ParseNtResult::Expr(expr, ..) => expr.span, + ParseNtResult::Literal(expr) => expr.span, + ParseNtResult::Ty(ty) => ty.span, + ParseNtResult::Meta(attr_item) => attr_item.span(), + ParseNtResult::Path(path) => path.span, + ParseNtResult::Vis(visibility) => visibility.span, + } + } +} diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index bf95014843d23..f9196abb3039f 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -378,12 +378,18 @@ pub(crate) struct UnsupportedCrateTypeForTarget<'a> { pub(crate) target_triple: &'a TargetTuple, } +/// Emit an error related to a literal. pub fn report_lit_error( psess: &ParseSess, err: LitError, lit: token::Lit, span: Span, ) -> ErrorGuaranteed { + create_lit_error(psess, err, lit, span).emit() +} + +/// Build an error related to a literal. +pub fn create_lit_error(psess: &ParseSess, err: LitError, lit: token::Lit, span: Span) -> Diag<'_> { // Checks if `s` looks like i32 or u1234 etc. fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit()) @@ -414,32 +420,32 @@ pub fn report_lit_error( let dcx = psess.dcx(); match err { LitError::InvalidSuffix(suffix) => { - dcx.emit_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix }) + dcx.create_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix }) } LitError::InvalidIntSuffix(suffix) => { let suf = suffix.as_str(); if looks_like_width_suffix(&['i', 'u'], suf) { // If it looks like a width, try to be helpful. - dcx.emit_err(InvalidIntLiteralWidth { span, width: suf[1..].into() }) + dcx.create_err(InvalidIntLiteralWidth { span, width: suf[1..].into() }) } else if let Some(fixed) = fix_base_capitalisation(lit.symbol.as_str(), suf) { - dcx.emit_err(InvalidNumLiteralBasePrefix { span, fixed }) + dcx.create_err(InvalidNumLiteralBasePrefix { span, fixed }) } else { - dcx.emit_err(InvalidNumLiteralSuffix { span, suffix: suf.to_string() }) + dcx.create_err(InvalidNumLiteralSuffix { span, suffix: suf.to_string() }) } } LitError::InvalidFloatSuffix(suffix) => { let suf = suffix.as_str(); if looks_like_width_suffix(&['f'], suf) { // If it looks like a width, try to be helpful. - dcx.emit_err(InvalidFloatLiteralWidth { span, width: suf[1..].to_string() }) + dcx.create_err(InvalidFloatLiteralWidth { span, width: suf[1..].to_string() }) } else { - dcx.emit_err(InvalidFloatLiteralSuffix { span, suffix: suf.to_string() }) + dcx.create_err(InvalidFloatLiteralSuffix { span, suffix: suf.to_string() }) } } LitError::NonDecimalFloat(base) => match base { - 16 => dcx.emit_err(HexadecimalFloatLiteralNotSupported { span }), - 8 => dcx.emit_err(OctalFloatLiteralNotSupported { span }), - 2 => dcx.emit_err(BinaryFloatLiteralNotSupported { span }), + 16 => dcx.create_err(HexadecimalFloatLiteralNotSupported { span }), + 8 => dcx.create_err(OctalFloatLiteralNotSupported { span }), + 2 => dcx.create_err(BinaryFloatLiteralNotSupported { span }), _ => unreachable!(), }, LitError::IntTooLarge(base) => { @@ -450,7 +456,7 @@ pub fn report_lit_error( 16 => format!("{max:#x}"), _ => format!("{max}"), }; - dcx.emit_err(IntLiteralTooLarge { span, limit }) + dcx.create_err(IntLiteralTooLarge { span, limit }) } } } diff --git a/tests/ui/macros/macro-metavar-expr-concat/empty-input.stderr b/tests/ui/macros/macro-metavar-expr-concat/empty-input.stderr index e95032dd2478d..c98cd8c1f26d9 100644 --- a/tests/ui/macros/macro-metavar-expr-concat/empty-input.stderr +++ b/tests/ui/macros/macro-metavar-expr-concat/empty-input.stderr @@ -1,8 +1,8 @@ -error: expected identifier or string literal - --> $DIR/empty-input.rs:6:14 +error: `concat` must have at least two elements + --> $DIR/empty-input.rs:6:15 | LL | () => { ${concat()} } - | ^^^^^^^^^^ + | ^^^^^^ error: expected expression, found `$` --> $DIR/empty-input.rs:6:13 diff --git a/tests/ui/macros/metavar-expressions/concat-allowed-operations.rs b/tests/ui/macros/metavar-expressions/concat-allowed-operations.rs index 695a752fe17d4..837687ffeb83e 100644 --- a/tests/ui/macros/metavar-expressions/concat-allowed-operations.rs +++ b/tests/ui/macros/metavar-expressions/concat-allowed-operations.rs @@ -38,7 +38,14 @@ macro_rules! without_dollar_sign_is_an_ident { } macro_rules! combinations { - ($ident:ident, $literal:literal, $tt_ident:tt, $tt_literal:tt) => {{ + ( + $ident:ident, + $literal:literal, + $char:literal, + $tt_ident:tt, + $tt_literal:tt, + $tt_char:tt + ) => {{ // tt ident let ${concat($tt_ident, b)} = (); let ${concat($tt_ident, _b)} = (); @@ -89,17 +96,39 @@ macro_rules! combinations { let ${concat($literal, $tt_literal)} = (); let ${concat($literal, $ident)} = (); let ${concat($literal, $literal)} = (); + + // char literal (adhoc) + let ${concat('a', b)} = (); + let ${concat('a', _b)} = (); + let ${concat('a', 'b')} = (); + let ${concat('a', $tt_ident)} = (); + let ${concat('a', $tt_literal)} = (); + let ${concat('a', $ident)} = (); + let ${concat('a', $literal)} = (); + // char literal (param) + let ${concat($literal, b)} = (); + let ${concat($literal, _b)} = (); + let ${concat($literal, 'b')} = (); + let ${concat($literal, $tt_ident)} = (); + let ${concat($literal, $tt_literal)} = (); + let ${concat($literal, $ident)} = (); + let ${concat($literal, $literal)} = (); }}; } +macro_rules! stripped_suffixes { + ($x:literal) => { + assert_eq!(stringify!(${concat("a", 40u32)}), "a40"); + // TODO + // assert_eq!(stringify!(${concat("a", $x)}), "a100"); + }; +} + fn main() { create_things!(behold); behold_separated_idents_in_a_fn(); let _ = behold_separated_idents_in_a_module::FOO; - let _ = behold_separated_idents_in_a_struct { - foo: 1, - behold_separated_idents_in_a_field: 2, - }; + let _ = behold_separated_idents_in_a_struct { foo: 1, behold_separated_idents_in_a_field: 2 }; many_idents!(A, C); assert_eq!(ABCD, 1); @@ -111,5 +140,7 @@ fn main() { assert_eq!(VARident, 1); assert_eq!(VAR_123, 2); - combinations!(_hello, "a", b, "b"); + combinations!(_hello, "a", 'a', b, "b", 'b'); + + stripped_suffixes!(100u32); } diff --git a/tests/ui/macros/metavar-expressions/concat-raw-identifiers.rs b/tests/ui/macros/metavar-expressions/concat-raw-identifiers.rs index b1cb2141cc42f..aedf1038daa08 100644 --- a/tests/ui/macros/metavar-expressions/concat-raw-identifiers.rs +++ b/tests/ui/macros/metavar-expressions/concat-raw-identifiers.rs @@ -3,60 +3,60 @@ macro_rules! idents_01 { ($rhs:ident) => { let ${concat(abc, $rhs)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! idents_10 { ($lhs:ident) => { let ${concat($lhs, abc)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! idents_11 { ($lhs:ident, $rhs:ident) => { let ${concat($lhs, $rhs)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers - //~| ERROR `${concat(..)}` currently does not support raw identifiers - //~| ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression + //~| ERROR invalid item within a `${concat(..)}` expression + //~| ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! no_params { () => { let ${concat(r#abc, abc)}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression //~| ERROR expected pattern, found `$` let ${concat(abc, r#abc)}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat(r#abc, r#abc)}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! tts_01 { ($rhs:tt) => { let ${concat(abc, $rhs)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! tts_10 { ($lhs:tt) => { let ${concat($lhs, abc)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression }; } macro_rules! tts_11 { ($lhs:tt, $rhs:tt) => { let ${concat($lhs, $rhs)}: () = (); - //~^ ERROR `${concat(..)}` currently does not support raw identifiers - //~| ERROR `${concat(..)}` currently does not support raw identifiers - //~| ERROR `${concat(..)}` currently does not support raw identifiers + //~^ ERROR invalid item within a `${concat(..)}` expression + //~| ERROR invalid item within a `${concat(..)}` expression + //~| ERROR invalid item within a `${concat(..)}` expression }; } diff --git a/tests/ui/macros/metavar-expressions/concat-raw-identifiers.stderr b/tests/ui/macros/metavar-expressions/concat-raw-identifiers.stderr index 7abab6a510358..f3211bf658b03 100644 --- a/tests/ui/macros/metavar-expressions/concat-raw-identifiers.stderr +++ b/tests/ui/macros/metavar-expressions/concat-raw-identifiers.stderr @@ -1,84 +1,106 @@ -error: expected identifier or string literal +error: invalid item within a `${concat(..)}` expression --> $DIR/concat-raw-identifiers.rs:28:22 | LL | let ${concat(r#abc, abc)}: () = (); | ^^^^^ + | + = note: raw identifiers cannot be concatenated -error: expected identifier or string literal +error: invalid item within a `${concat(..)}` expression --> $DIR/concat-raw-identifiers.rs:32:27 | LL | let ${concat(abc, r#abc)}: () = (); | ^^^^^ + | + = note: raw identifiers cannot be concatenated -error: expected identifier or string literal +error: invalid item within a `${concat(..)}` expression --> $DIR/concat-raw-identifiers.rs:35:22 | LL | let ${concat(r#abc, r#abc)}: () = (); | ^^^^^ + | + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:5:28 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:64:16 | -LL | let ${concat(abc, $rhs)}: () = (); - | ^^^ +LL | idents_01!(r#_c); + | ^^^^ + | + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:12:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:66:16 + | +LL | idents_10!(r#_c); + | ^^^^ | -LL | let ${concat($lhs, abc)}: () = (); - | ^^^ + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:19:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:68:16 + | +LL | idents_11!(r#_c, d); + | ^^^^ | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:19:29 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:69:20 | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ +LL | idents_11!(_e, r#f); + | ^^^ + | + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:19:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:70:16 | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ +LL | idents_11!(r#_g, r#h); + | ^^^^ | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:42:28 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:72:13 + | +LL | tts_01!(r#_c); + | ^^^^ | -LL | let ${concat(abc, $rhs)}: () = (); - | ^^^ + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:49:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:74:13 + | +LL | tts_10!(r#_c); + | ^^^^ | -LL | let ${concat($lhs, abc)}: () = (); - | ^^^ + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:56:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:76:13 | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ +LL | tts_11!(r#_c, d); + | ^^^^ + | + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:56:29 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:77:17 + | +LL | tts_11!(_e, r#f); + | ^^^ | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ + = note: raw identifiers cannot be concatenated -error: `${concat(..)}` currently does not support raw identifiers - --> $DIR/concat-raw-identifiers.rs:56:23 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-raw-identifiers.rs:78:13 | -LL | let ${concat($lhs, $rhs)}: () = (); - | ^^^ +LL | tts_11!(r#_g, r#h); + | ^^^^ | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: raw identifiers cannot be concatenated error: expected pattern, found `$` --> $DIR/concat-raw-identifiers.rs:28:13 diff --git a/tests/ui/macros/metavar-expressions/concat-trace-errors.rs b/tests/ui/macros/metavar-expressions/concat-trace-errors.rs index 45407f5e86d56..8636b0b1edf10 100644 --- a/tests/ui/macros/metavar-expressions/concat-trace-errors.rs +++ b/tests/ui/macros/metavar-expressions/concat-trace-errors.rs @@ -7,8 +7,11 @@ macro_rules! pre_expansion { ($a:ident) => { ${concat("hi", " bye ")}; + //~^ ERROR invalid item within a `${concat(..)}` expression ${concat("hi", "-", "bye")}; + //~^ ERROR invalid item within a `${concat(..)}` expression ${concat($a, "-")}; + //~^ ERROR invalid item within a `${concat(..)}` expression } } diff --git a/tests/ui/macros/metavar-expressions/concat-trace-errors.stderr b/tests/ui/macros/metavar-expressions/concat-trace-errors.stderr index dac8b58a15ce2..e16d8e9e1b0ca 100644 --- a/tests/ui/macros/metavar-expressions/concat-trace-errors.stderr +++ b/tests/ui/macros/metavar-expressions/concat-trace-errors.stderr @@ -1,24 +1,32 @@ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-trace-errors.rs:17:24 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-trace-errors.rs:9:24 | -LL | const _: () = ${concat("hi", $a, "bye")}; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | post_expansion!("!"); - | -------------------- in this macro invocation +LL | ${concat("hi", " bye ")}; + | ^^^^^^^ + +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-trace-errors.rs:11:24 | - = note: this error originates in the macro `post_expansion` (in Nightly builds, run with -Z macro-backtrace for more info) +LL | ${concat("hi", "-", "bye")}; + | ^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-trace-errors.rs:26:24 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-trace-errors.rs:13:22 | -LL | const _: () = ${concat($a, $b, $c, $d, $e)}; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | post_expansion_many!(a, b, c, ".d", e); - | -------------------------------------- in this macro invocation +LL | ${concat($a, "-")}; + | ^^^ + +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-trace-errors.rs:25:17 | - = note: this error originates in the macro `post_expansion_many` (in Nightly builds, run with -Z macro-backtrace for more info) +LL | post_expansion!("!"); + | ^^^ + +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-trace-errors.rs:34:31 + | +LL | post_expansion_many!(a, b, c, ".d", e); + | ^^^^ -error: aborting due to 2 previous errors +error: aborting due to 5 previous errors diff --git a/tests/ui/macros/metavar-expressions/concat-usage-errors.rs b/tests/ui/macros/metavar-expressions/concat-usage-errors.rs index 7d8756de9e20b..7dfa76e4f9bbf 100644 --- a/tests/ui/macros/metavar-expressions/concat-usage-errors.rs +++ b/tests/ui/macros/metavar-expressions/concat-usage-errors.rs @@ -5,13 +5,13 @@ macro_rules! syntax_errors { ($ex:expr) => { ${concat()} - //~^ ERROR expected identifier + //~^ ERROR `concat` must have at least two elements ${concat(aaaa)} //~^ ERROR `concat` must have at least two elements ${concat(aaaa,)} - //~^ ERROR expected identifier + //~^ ERROR `concat` must have at least two elements ${concat(_, aaaa)} @@ -22,13 +22,12 @@ macro_rules! syntax_errors { //~^ ERROR `concat` must have at least two elements ${concat($ex, aaaa)} - //~^ ERROR metavariables of `${concat(..)}` must be of type + //~^ ERROR invalid item within a `${concat(..)}` expression ${concat($ex, aaaa 123)} //~^ ERROR expected comma ${concat($ex, aaaa,)} - //~^ ERROR expected identifier }; } @@ -55,7 +54,8 @@ macro_rules! starting_valid_unicode { macro_rules! starting_invalid_unicode { ($ident:ident) => {{ let ${concat("\u{00BD}", $ident)}: () = (); - //~^ ERROR `${concat(..)}` is not generating a valid identifier + //~^ ERROR invalid item within a `${concat(..)}` expression + //~| ERROR expected pattern }}; } @@ -74,7 +74,8 @@ macro_rules! ending_valid_unicode { macro_rules! ending_invalid_unicode { ($ident:ident) => {{ let ${concat($ident, "\u{00BD}")}: () = (); - //~^ ERROR `${concat(..)}` is not generating a valid identifier + //~^ ERROR invalid item within a `${concat(..)}` expression + //~| ERROR expected pattern }}; } @@ -87,36 +88,28 @@ macro_rules! empty { macro_rules! unsupported_literals { ($ident:ident) => {{ - let ${concat(_a, 'b')}: () = (); - //~^ ERROR expected identifier or string literal - //~| ERROR expected pattern - let ${concat(_a, 1)}: () = (); - //~^ ERROR expected identifier or string literal let ${concat(_a, 1.5)}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression + //~| ERROR expected pattern let ${concat(_a, c"hi")}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat(_a, b"hi")}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat(_a, b'b')}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat(_a, b'b')}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression - let ${concat($ident, 'b')}: () = (); - //~^ ERROR expected identifier or string literal - let ${concat($ident, 1)}: () = (); - //~^ ERROR expected identifier or string literal let ${concat($ident, 1.5)}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat($ident, c"hi")}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat($ident, b"hi")}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat($ident, b'b')}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression let ${concat($ident, b'b')}: () = (); - //~^ ERROR expected identifier or string literal + //~^ ERROR invalid item within a `${concat(..)}` expression }}; } diff --git a/tests/ui/macros/metavar-expressions/concat-usage-errors.stderr b/tests/ui/macros/metavar-expressions/concat-usage-errors.stderr index 8be3e792ec3f2..93615fa90eb0e 100644 --- a/tests/ui/macros/metavar-expressions/concat-usage-errors.stderr +++ b/tests/ui/macros/metavar-expressions/concat-usage-errors.stderr @@ -1,8 +1,8 @@ -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:7:10 +error: `concat` must have at least two elements + --> $DIR/concat-usage-errors.rs:7:11 | LL | ${concat()} - | ^^^^^^^^^^ + | ^^^^^^ error: `concat` must have at least two elements --> $DIR/concat-usage-errors.rs:10:11 @@ -10,11 +10,11 @@ error: `concat` must have at least two elements LL | ${concat(aaaa)} | ^^^^^^ -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:13:10 +error: `concat` must have at least two elements + --> $DIR/concat-usage-errors.rs:13:11 | LL | ${concat(aaaa,)} - | ^^^^^^^^^^^^^^^ + | ^^^^^^ error: expected comma --> $DIR/concat-usage-errors.rs:18:10 @@ -34,112 +34,128 @@ error: expected comma LL | ${concat($ex, aaaa 123)} | ^^^^^^^^^^^^^^^^^^^^^^^ -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:30:10 - | -LL | ${concat($ex, aaaa,)} - | ^^^^^^^^^^^^^^^^^^^^ - -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:90:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:56:22 | -LL | let ${concat(_a, 'b')}: () = (); - | ^^^ +LL | let ${concat("\u{00BD}", $ident)}: () = (); + | ^^^^^^^^^^ -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:93:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:76:30 | -LL | let ${concat(_a, 1)}: () = (); - | ^ +LL | let ${concat($ident, "\u{00BD}")}: () = (); + | ^^^^^^^^^^ -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:95:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:91:26 | LL | let ${concat(_a, 1.5)}: () = (); | ^^^ + | + = note: float literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:97:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:94:26 | LL | let ${concat(_a, c"hi")}: () = (); | ^^^^^ + | + = note: C string literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:99:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:96:26 | LL | let ${concat(_a, b"hi")}: () = (); | ^^^^^ + | + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:101:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:98:26 | LL | let ${concat(_a, b'b')}: () = (); | ^^^^ + | + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:103:26 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:100:26 | LL | let ${concat(_a, b'b')}: () = (); | ^^^^ - -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:106:30 - | -LL | let ${concat($ident, 'b')}: () = (); - | ^^^ - -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:108:30 | -LL | let ${concat($ident, 1)}: () = (); - | ^ + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:110:30 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:103:30 | LL | let ${concat($ident, 1.5)}: () = (); | ^^^ + | + = note: float literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:112:30 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:105:30 | LL | let ${concat($ident, c"hi")}: () = (); | ^^^^^ + | + = note: C string literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:114:30 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:107:30 | LL | let ${concat($ident, b"hi")}: () = (); | ^^^^^ + | + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:116:30 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:109:30 | LL | let ${concat($ident, b'b')}: () = (); | ^^^^ + | + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: expected identifier or string literal - --> $DIR/concat-usage-errors.rs:118:30 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:111:30 | LL | let ${concat($ident, b'b')}: () = (); | ^^^^ + | + = note: byte literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:24:19 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:150:20 | LL | ${concat($ex, aaaa)} - | ^^ + | -- expanding this metavariable +... +LL | syntax_errors!(1); + | ^ | - = note: currently only string literals are supported + = note: expanding something + = note: `${concat(..)}` can join metavariables of type `ident`, `literal`, and `tt` error: variable `foo` is not recognized in meta-variable expression - --> $DIR/concat-usage-errors.rs:37:30 + --> $DIR/concat-usage-errors.rs:36:30 | LL | const ${concat(FOO, $foo)}: i32 = 2; | ^^^ error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:44:14 + --> $DIR/concat-usage-errors.rs:43:14 | LL | let ${concat("1", $ident)}: () = (); | ^^^^^^^^^^^^^^^^^^^^^ @@ -149,22 +165,22 @@ LL | starting_number!(_abc); | = note: this error originates in the macro `starting_number` (in Nightly builds, run with -Z macro-backtrace for more info) -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:57:14 +error: expected pattern, found `$` + --> $DIR/concat-usage-errors.rs:56:13 | LL | let ${concat("\u{00BD}", $ident)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^ expected pattern ... LL | starting_invalid_unicode!(_abc); | ------------------------------- in this macro invocation | = note: this error originates in the macro `starting_invalid_unicode` (in Nightly builds, run with -Z macro-backtrace for more info) -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:76:14 +error: expected pattern, found `$` + --> $DIR/concat-usage-errors.rs:76:13 | LL | let ${concat($ident, "\u{00BD}")}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^ expected pattern ... LL | ending_invalid_unicode!(_abc); | ----------------------------- in this macro invocation @@ -172,9 +188,9 @@ LL | ending_invalid_unicode!(_abc); = note: this error originates in the macro `ending_invalid_unicode` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected pattern, found `$` - --> $DIR/concat-usage-errors.rs:90:13 + --> $DIR/concat-usage-errors.rs:91:13 | -LL | let ${concat(_a, 'b')}: () = (); +LL | let ${concat(_a, 1.5)}: () = (); | ^ expected pattern ... LL | unsupported_literals!(_abc); @@ -183,7 +199,7 @@ LL | unsupported_literals!(_abc); = note: this error originates in the macro `unsupported_literals` (in Nightly builds, run with -Z macro-backtrace for more info) error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:83:14 + --> $DIR/concat-usage-errors.rs:84:14 | LL | let ${concat("", "")}: () = (); | ^^^^^^^^^^^^^^^^ @@ -193,152 +209,117 @@ LL | empty!(); | = note: this error originates in the macro `empty` (in Nightly builds, run with -Z macro-backtrace for more info) -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:165:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("\u{00BD}"); - | ------------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^^^^^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:167:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | bad_literal_string!("\x41"); - | --------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 - | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("🤷"); - | ------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:168:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("d[-_-]b"); - | ------------------------------ in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^^^^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:170:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("-1"); - | ------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:171:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("1.0"); - | -------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^^ -error: `${concat(..)}` is not generating a valid identifier - --> $DIR/concat-usage-errors.rs:125:16 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:172:25 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^^^^^^^^^^^^^^^^^^ -... LL | bad_literal_string!("'1'"); - | -------------------------- in this macro invocation - | - = note: this error originates in the macro `bad_literal_string` (in Nightly builds, run with -Z macro-backtrace for more info) - -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:138:31 - | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^ - | - = note: currently only string literals are supported + | ^^^^^ -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:138:31 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:175:29 | LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^ + | ------- expanding this metavariable +... +LL | bad_literal_non_string!(-1); + | ^^ | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: expanding something + = note: `${concat(..)}` can join metavariables of type `ident`, `literal`, and `tt` -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:138:31 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:176:29 | -LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^ +LL | bad_literal_non_string!(1.0); + | ^^^ | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: float literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:138:31 +error[E0428]: the name `_foo1` is defined multiple times + --> $DIR/concat-usage-errors.rs:131:9 | LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^ + | ^^^^^^^ + | | + | `_foo1` redefined here + | previous definition of the value `_foo1` here +... +LL | bad_literal_non_string!(1); + | -------------------------- in this macro invocation | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: `_foo1` must be defined only once in the value namespace of this block + = note: this error originates in the macro `bad_literal_non_string` (in Nightly builds, run with -Z macro-backtrace for more info) -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:138:31 +error[E0428]: the name `_foo1` is defined multiple times + --> $DIR/concat-usage-errors.rs:142:9 | LL | const ${concat(_foo, $literal)}: () = (); - | ^^^^^^^ - | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:149:31 - | + | ------- previous definition of the value `_foo1` here +... LL | const ${concat(_foo, $tt)}: () = (); - | ^^ + | ^^^^^^^ `_foo1` redefined here +... +LL | bad_tt_literal!(1); + | ------------------ in this macro invocation | - = note: currently only string literals are supported + = note: `_foo1` must be defined only once in the value namespace of this block + = note: this error originates in the macro `bad_tt_literal` (in Nightly builds, run with -Z macro-backtrace for more info) -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:149:31 +error: invalid item within a `${concat(..)}` expression + --> $DIR/concat-usage-errors.rs:181:21 | -LL | const ${concat(_foo, $tt)}: () = (); - | ^^ +LL | bad_tt_literal!(1.0); + | ^^^ | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: float literals cannot be concatenated + = note: `concat` can join metavariables, identifiers, string literals, and integer literals -error: metavariables of `${concat(..)}` must be of type `ident`, `literal` or `tt` - --> $DIR/concat-usage-errors.rs:149:31 +error[E0428]: the name `_foo1` is defined multiple times + --> $DIR/concat-usage-errors.rs:142:9 | +LL | const ${concat(_foo, $literal)}: () = (); + | ------- previous definition of the value `_foo1` here +... LL | const ${concat(_foo, $tt)}: () = (); - | ^^ + | ^^^^^^^ `_foo1` redefined here +... +LL | bad_tt_literal!('1'); + | -------------------- in this macro invocation | - = note: currently only string literals are supported - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: `_foo1` must be defined only once in the value namespace of this block + = note: this error originates in the macro `bad_tt_literal` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 43 previous errors +error: aborting due to 37 previous errors +For more information about this error, try `rustc --explain E0428`. diff --git a/tests/ui/macros/metavar-expressions/syntax-errors.rs b/tests/ui/macros/metavar-expressions/syntax-errors.rs index 8fc76a74baa42..182e889adb28b 100644 --- a/tests/ui/macros/metavar-expressions/syntax-errors.rs +++ b/tests/ui/macros/metavar-expressions/syntax-errors.rs @@ -18,74 +18,86 @@ macro_rules! metavar_in_the_lhs { }; } -macro_rules! metavar_token_without_ident { - ( $( $i:ident ),* ) => { ${ ignore() } }; - //~^ ERROR meta-variable expressions must be referenced using a dollar sign -} - -macro_rules! metavar_with_literal_suffix { +macro_rules! mve_with_literal_suffix { ( $( $i:ident ),* ) => { ${ index(1u32) } }; //~^ ERROR only unsuffixes integer literals are supported in meta-variable expressions } macro_rules! mve_without_parens { ( $( $i:ident ),* ) => { ${ count } }; - //~^ ERROR meta-variable expression parameter must be wrapped in parentheses + //~^ ERROR expected `(` } #[rustfmt::skip] macro_rules! empty_expression { () => { ${} }; - //~^ ERROR expected identifier or string literal + //~^ ERROR expected an identifier } #[rustfmt::skip] macro_rules! open_brackets_with_lit { () => { ${ "hi" } }; - //~^ ERROR expected identifier + //~^ ERROR expected an identifier } +macro_rules! mvs_missing_paren { + ( $( $i:ident ),* ) => { ${ count $i ($i) } }; + //~^ ERROR expected `(` +} + +macro_rules! mve_wrong_delim { + ( $( $i:ident ),* ) => { ${ count{i} } }; + //~^ ERROR expected `(` +} + +macro_rules! invalid_metavar { + () => { ${ignore($123)} } + //~^ ERROR expected an identifier +} + macro_rules! mve_wrong_delim { ( $( $i:ident ),* ) => { ${ count{i} } }; - //~^ ERROR meta-variable expression parameter must be wrapped in parentheses + //~^ ERROR expected `(` } macro_rules! invalid_metavar { () => { ${ignore($123)} } - //~^ ERROR expected identifier, found `123` + //~^ ERROR expected an identifier } #[rustfmt::skip] macro_rules! open_brackets_with_group { ( $( $i:ident ),* ) => { ${ {} } }; - //~^ ERROR expected identifier + //~^ ERROR expected an identifier } macro_rules! extra_garbage_after_metavar { ( $( $i:ident ),* ) => { ${count() a b c} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${count($i a b c)} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${count($i, 1 a b c)} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${count($i) a b c} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${ignore($i) a b c} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${ignore($i a b c)} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${index() a b c} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${index(1 a b c)} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${index() a b c} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens ${index(1 a b c)} - //~^ ERROR unexpected token: a + //~^ ERROR unexpected trailing tokens + ${index(1, a b c)} + //~^ ERROR unexpected trailing tokens }; } @@ -109,9 +121,14 @@ macro_rules! unknown_ignore_ident { }; } +macro_rules! ignore_no_ident { + ( $( $i:ident ),* ) => { ${ ignore() } }; + //~^ ERROR meta-variable expressions must be referenced using a dollar sign +} + macro_rules! unknown_metavar { ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; - //~^ ERROR unrecognized meta-variable expression + //~^ ERROR unrecognized metavariable expression } fn main() {} diff --git a/tests/ui/macros/metavar-expressions/syntax-errors.stderr b/tests/ui/macros/metavar-expressions/syntax-errors.stderr index 20d2358facc2b..e66832f9281c5 100644 --- a/tests/ui/macros/metavar-expressions/syntax-errors.stderr +++ b/tests/ui/macros/metavar-expressions/syntax-errors.stderr @@ -28,197 +28,222 @@ error: expected one of: `*`, `+`, or `?` LL | ( ${ len() } ) => { | ^^^^^^^^^ -error: meta-variables within meta-variable expressions must be referenced using a dollar sign - --> $DIR/syntax-errors.rs:22:33 - | -LL | ( $( $i:ident ),* ) => { ${ ignore() } }; - | ^^^^^^ - error: only unsuffixes integer literals are supported in meta-variable expressions - --> $DIR/syntax-errors.rs:27:33 + --> $DIR/syntax-errors.rs:22:33 | LL | ( $( $i:ident ),* ) => { ${ index(1u32) } }; | ^^^^^ -error: meta-variable expression parameter must be wrapped in parentheses - --> $DIR/syntax-errors.rs:32:33 +error: expected `(` + --> $DIR/syntax-errors.rs:27:33 | LL | ( $( $i:ident ),* ) => { ${ count } }; - | ^^^^^ + | ^^^^^- help: try adding parentheses: `( /* ... */ )` + | | + | for this this metavariable expression + | + = note: metavariable expressions use function-like parentheses syntax + +error: expected `(` + --> $DIR/syntax-errors.rs:44:33 + | +LL | ( $( $i:ident ),* ) => { ${ count $i ($i) } }; + | ^^^^^ - unexpected token + | | + | for this this metavariable expression + | + = note: metavariable expressions use function-like parentheses syntax -error: meta-variable expression parameter must be wrapped in parentheses +error: expected `(` --> $DIR/syntax-errors.rs:49:33 | LL | ( $( $i:ident ),* ) => { ${ count{i} } }; - | ^^^^^ + | ^^^^^ for this this metavariable expression + | + = note: metavariable expressions use function-like parentheses syntax -error: expected identifier, found `123` +error: expected an identifier --> $DIR/syntax-errors.rs:54:23 | LL | () => { ${ignore($123)} } - | ^^^ help: try removing `123` + | ^^^ not a valid identifier + | + = note: `ignore` takes a metavariable argument -error: unexpected token: a - --> $DIR/syntax-errors.rs:66:19 +error: expected `(` + --> $DIR/syntax-errors.rs:59:33 | -LL | ${count() a b c} - | ^ +LL | ( $( $i:ident ),* ) => { ${ count{i} } }; + | ^^^^^ for this this metavariable expression + | + = note: metavariable expressions use function-like parentheses syntax + +error: expected an identifier + --> $DIR/syntax-errors.rs:64:23 | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:66:19 +LL | () => { ${ignore($123)} } + | ^^^ not a valid identifier + | + = note: `ignore` takes a metavariable argument + +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:76:19 | LL | ${count() a b c} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression -error: unexpected token: a - --> $DIR/syntax-errors.rs:68:20 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:78:20 | LL | ${count($i a b c)} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:68:20 + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression | -LL | ${count($i a b c)} - | ^ + = note: the `count` metavariable expression takes between 1 and 2 arguments -error: unexpected token: a - --> $DIR/syntax-errors.rs:70:23 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:80:23 | LL | ${count($i, 1 a b c)} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:70:23 + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression | -LL | ${count($i, 1 a b c)} - | ^ + = note: the `count` metavariable expression takes between 1 and 2 arguments -error: unexpected token: a - --> $DIR/syntax-errors.rs:72:21 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:82:21 | LL | ${count($i) a b c} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:72:21 - | -LL | ${count($i) a b c} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression -error: unexpected token: a - --> $DIR/syntax-errors.rs:75:22 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:85:22 | LL | ${ignore($i) a b c} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:75:22 - | -LL | ${ignore($i) a b c} - | ^ + | ------ ^^^^^ help: try removing these tokens + | | + | for this metavariable expression -error: unexpected token: a - --> $DIR/syntax-errors.rs:77:21 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:87:21 | LL | ${ignore($i a b c)} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:77:21 + | ------ ^^^^^ help: try removing these tokens + | | + | for this metavariable expression | -LL | ${ignore($i a b c)} - | ^ + = note: the `ignore` metavariable expression takes a single argument -error: unexpected token: a - --> $DIR/syntax-errors.rs:80:19 - | -LL | ${index() a b c} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:80:19 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:90:19 | LL | ${index() a b c} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression -error: unexpected token: a - --> $DIR/syntax-errors.rs:82:19 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:92:19 | LL | ${index(1 a b c)} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:82:19 - | -LL | ${index(1 a b c)} - | ^ + = note: the `index` metavariable expression takes between 0 and 1 arguments -error: unexpected token: a - --> $DIR/syntax-errors.rs:85:19 - | -LL | ${index() a b c} - | ^ - | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:85:19 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:95:19 | LL | ${index() a b c} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression -error: unexpected token: a - --> $DIR/syntax-errors.rs:87:19 +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:97:19 | LL | ${index(1 a b c)} - | ^ + | ----- ^^^^^ help: try removing these tokens + | | + | for this metavariable expression | -note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:87:19 + = note: the `index` metavariable expression takes between 0 and 1 arguments + +error: unexpected trailing tokens + --> $DIR/syntax-errors.rs:99:18 | -LL | ${index(1 a b c)} - | ^ +LL | ${index(1, a b c)} + | ----- ^^^^^^^ help: try removing these tokens + | | + | for this metavariable expression + | + = note: the `index` metavariable expression takes between 0 and 1 arguments error: meta-variable expression depth must be a literal - --> $DIR/syntax-errors.rs:94:33 + --> $DIR/syntax-errors.rs:106:33 | LL | ( $( $i:ident ),* ) => { ${ index(IDX) } }; | ^^^^^ error: meta-variables within meta-variable expressions must be referenced using a dollar sign - --> $DIR/syntax-errors.rs:100:11 + --> $DIR/syntax-errors.rs:112:11 | LL | ${count(foo)} | ^^^^^ error: meta-variables within meta-variable expressions must be referenced using a dollar sign - --> $DIR/syntax-errors.rs:107:11 + --> $DIR/syntax-errors.rs:119:11 | LL | ${ignore(bar)} | ^^^^^^ -error: unrecognized meta-variable expression - --> $DIR/syntax-errors.rs:113:33 +error: meta-variables within meta-variable expressions must be referenced using a dollar sign + --> $DIR/syntax-errors.rs:125:33 + | +LL | ( $( $i:ident ),* ) => { ${ ignore() } }; + | ^^^^^^ + +error: unrecognized metavariable expression + --> $DIR/syntax-errors.rs:130:33 | LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; - | ^^^^^^^^^^^^^^ help: supported expressions are count, ignore, index and len + | ^^^^^^^^^^^^^^ not a valid metavariable expression + | + = note: valid metavariable expressions are `count`, `ignore`, `index`, `len`, and `concat` -error: expected identifier or string literal - --> $DIR/syntax-errors.rs:38:14 +error: expected an identifier + --> $DIR/syntax-errors.rs:33:14 | LL | () => { ${} }; | ^^ + | + = note: expected a metavariable expression name: `${expr( /* ... */ )}` + = note: valid metavariable expressions are `count`, `ignore`, `index`, `len`, and `concat` -error: expected identifier, found `"hi"` - --> $DIR/syntax-errors.rs:44:17 +error: expected an identifier + --> $DIR/syntax-errors.rs:39:17 | LL | () => { ${ "hi" } }; - | ^^^^ help: try removing `"hi"` + | ^^^^ not a valid identifier + | + = note: expected a metavariable expression name: `${expr( /* ... */ )}` + = note: valid metavariable expressions are `count`, `ignore`, `index`, `len`, and `concat` -error: expected identifier or string literal - --> $DIR/syntax-errors.rs:60:33 +error: expected an identifier + --> $DIR/syntax-errors.rs:70:33 | LL | ( $( $i:ident ),* ) => { ${ {} } }; - | ^^ + | ^^ not a valid identifier + | + = note: expected a metavariable expression name: `${expr( /* ... */ )}` + = note: valid metavariable expressions are `count`, `ignore`, `index`, `len`, and `concat` -error: aborting due to 25 previous errors +error: aborting due to 29 previous errors