diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index 5244ac36bba5d..3d4c77aba7339 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -6,17 +6,17 @@ crate mod macro_check; crate mod macro_parser; crate mod macro_rules; +crate mod metavar_expr; crate mod quoted; crate mod transcribe; +use metavar_expr::MetaVarExpr; use rustc_ast::token::{self, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::DelimSpan; - +use rustc_data_structures::sync::Lrc; use rustc_span::symbol::Ident; use rustc_span::Span; -use rustc_data_structures::sync::Lrc; - /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note /// that the delimiter itself might be `NoDelim`. #[derive(Clone, PartialEq, Encodable, Decodable, Debug)] @@ -73,8 +73,8 @@ enum KleeneOp { ZeroOrOne, } -/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)` -/// are "first-class" token trees. Useful for parsing macros. +/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, `$(...)`, +/// and `${...}` are "first-class" token trees. Useful for parsing macros. #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] enum TokenTree { Token(Token), @@ -85,6 +85,8 @@ enum TokenTree { MetaVar(Span, Ident), /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros. MetaVarDecl(Span, Ident /* name to bind */, Option), + /// A meta-variable expression inside `${...}` + MetaVarExpr(DelimSpan, MetaVarExpr), } impl TokenTree { @@ -139,7 +141,9 @@ impl TokenTree { TokenTree::Token(Token { span, .. }) | TokenTree::MetaVar(span, _) | TokenTree::MetaVarDecl(span, _, _) => span, - TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), + TokenTree::Delimited(span, _) + | TokenTree::MetaVarExpr(span, _) + | TokenTree::Sequence(span, _) => span.entire(), } } diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 3497e5ad543a1..8b7fb8a4d5667 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -278,6 +278,9 @@ fn check_binders( binders.insert(name, BinderInfo { span, ops: ops.into() }); } } + // `MetaVarExpr` can not appear in the LHS of a macro arm, not even in a nested + // macro definition. + TokenTree::MetaVarExpr(..) => {} TokenTree::Delimited(_, ref del) => { for tt in &del.tts { check_binders(sess, node_id, tt, macros, binders, ops, valid); @@ -335,6 +338,7 @@ fn check_occurrences( let name = MacroRulesNormalizedIdent::new(name); check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name); } + TokenTree::MetaVarExpr(..) => {} TokenTree::Delimited(_, ref del) => { check_nested_occurrences(sess, node_id, &del.tts, macros, binders, ops, valid); } diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index dd82add08dd98..61adb4df2d178 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -280,10 +280,11 @@ pub(super) fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match *elt { - TokenTree::Sequence(_, ref seq) => seq.num_captures, TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), TokenTree::MetaVar(..) => 0, TokenTree::MetaVarDecl(..) => 1, + TokenTree::MetaVarExpr(..) => 0, + TokenTree::Sequence(_, ref seq) => seq.num_captures, TokenTree::Token(..) => 0, } }) @@ -392,7 +393,8 @@ fn nameize>( } Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), }, - TokenTree::MetaVar(..) | TokenTree::Token(..) => (), + // FIXME(c410-f3r) MetaVar and MetaVarExpr should be handled instead of being ignored. + TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) | TokenTree::Token(..) => {} } Ok(()) @@ -603,7 +605,7 @@ fn inner_parse_loop<'root, 'tt>( // rules. NOTE that this is not necessarily an error unless _all_ items in // `cur_items` end up doing this. There may still be some other matchers that do // end up working out. - TokenTree::Token(..) | TokenTree::MetaVar(..) => {} + TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) => {} } } } diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index f71fb58cf6b9f..6afb84c1ee52a 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -584,7 +584,10 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool { use mbe::TokenTree; for tt in tts { match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (), + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => (), TokenTree::Delimited(_, ref del) => { if !check_lhs_no_empty_seq(sess, &del.tts) { return false; @@ -673,7 +676,10 @@ impl FirstSets { let mut first = TokenSet::empty(); for tt in tts.iter().rev() { match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { first.replace_with(tt.clone()); } TokenTree::Delimited(span, ref delimited) => { @@ -735,7 +741,10 @@ impl FirstSets { for tt in tts.iter() { assert!(first.maybe_empty); match *tt { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { first.add_one(tt.clone()); return first; } @@ -911,7 +920,10 @@ fn check_matcher_core( // First, update `last` so that it corresponds to the set // of NT tokens that might end the sequence `... token`. match *token { - TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => { + TokenTree::Token(..) + | TokenTree::MetaVar(..) + | TokenTree::MetaVarDecl(..) + | TokenTree::MetaVarExpr(..) => { if token_can_be_followed_by_any(token) { // don't need to track tokens that work with any, last.replace_with_irrelevant(); diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs new file mode 100644 index 0000000000000..48cf4657ddc52 --- /dev/null +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -0,0 +1,180 @@ +use std::fmt::Display; +use std::str::FromStr; + +use rustc_ast::token::{self, Lit}; +use rustc_ast::tokenstream; +use rustc_ast_pretty::pprust; +use rustc_errors::{Applicability, PResult}; +use rustc_session::parse::ParseSess; + +use rustc_span::symbol::Ident; +use rustc_span::Span; + +/// A meta-variable expression, for expansions based on properties of meta-variables. +#[derive(Debug, Clone, PartialEq, Encodable, Decodable)] +crate enum MetaVarExpr { + /// The number of repetitions of an identifier, optionally limited to a number + /// of outer-most repetition depths. If the depth limit is `None` then the depth is unlimited. + Count(Ident, Option), + + /// Ignore a meta-variable for repetition without expansion. + Ignore(Ident), + + /// The index of the repetition at a particular depth, where 0 is the inner-most + /// repetition. The `usize` is the depth. + Index(usize), + + /// The length of the repetition at a particular depth, where 0 is the inner-most + /// repetition. The `usize` is the depth. + Length(usize), +} + +impl MetaVarExpr { + /// Attempt to parse a meta-variable expression from a token stream. + crate fn parse<'sess>( + input: &tokenstream::TokenStream, + sess: &'sess ParseSess, + ) -> PResult<'sess, MetaVarExpr> { + let mut tts = input.trees(); + match tts.next() { + Some(tokenstream::TokenTree::Token(token)) if let Some((ident, false)) = token.ident() => { + let Some(tokenstream::TokenTree::Delimited(_, token::Paren, args)) = tts.next() else { + let msg = "meta-variable expression paramter must be wrapped in parentheses"; + return Err(sess.span_diagnostic.struct_span_err(ident.span, msg)); + }; + let mut iter = args.trees(); + let rslt = match &*ident.as_str() { + "count" => parse_count(&mut iter, sess, ident.span)?, + "ignore" => MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?), + "index" => MetaVarExpr::Index(parse_depth(&mut iter, sess, ident.span)?), + "length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?), + _ => { + let msg = "unrecognised meta-variable expression. Supported expressions \ + are count, ignore, index and length"; + return Err(sess.span_diagnostic.struct_span_err(ident.span, msg)); + } + }; + if let Some(arg) = iter.next() { + let msg = "unexpected meta-variable expression argument"; + return Err(sess.span_diagnostic.struct_span_err(arg.span(), msg)); + } + Ok(rslt) + } + Some(tokenstream::TokenTree::Token(token)) => { + return Err(sess.span_diagnostic.struct_span_err( + token.span, + &format!( + "expected meta-variable expression, found `{}`", + pprust::token_to_string(&token), + ), + )); + } + _ => return Err(sess.span_diagnostic.struct_err("expected meta-variable expression")) + } + } + + crate fn ident(&self) -> Option<&Ident> { + match self { + MetaVarExpr::Count(ident, _) | MetaVarExpr::Ignore(ident) => Some(&ident), + MetaVarExpr::Index(..) | MetaVarExpr::Length(..) => None, + } + } +} + +/// Tries to convert a literal to an arbitrary type +fn convert_literal(lit: Lit, sess: &ParseSess, span: Span) -> PResult<'_, T> +where + T: FromStr, + ::Err: Display, +{ + if lit.suffix.is_some() { + let msg = "literal suffixes are not supported in meta-variable expressions"; + return Err(sess.span_diagnostic.struct_span_err(span, msg)); + } + lit.symbol.as_str().parse::().map_err(|e| { + sess.span_diagnostic.struct_span_err( + span, + &format!("failed to parse meta-variable expression argument: {}", e), + ) + }) +} + +/// Parse a meta-variable `count` expression: `count(ident[, depth])` +fn parse_count<'sess>( + iter: &mut tokenstream::Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, MetaVarExpr> { + let ident = parse_ident(iter, sess, span)?; + let depth = if try_eat_comma(iter) { Some(parse_depth(iter, sess, span)?) } else { None }; + Ok(MetaVarExpr::Count(ident, depth)) +} + +/// Parses the depth used by index(depth) and length(depth). +fn parse_depth<'sess>( + iter: &mut tokenstream::Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, usize> { + let Some(tt) = iter.next() else { return Ok(0) }; + let tokenstream::TokenTree::Token(token::Token { + kind: token::TokenKind::Literal(lit), + span: literal_span, + }) = tt else { + return Err(sess.span_diagnostic.struct_span_err( + span, + "meta-expression depth must be a literal" + )); + }; + convert_literal::(lit, sess, literal_span) +} + +/// Parses an generic ident +fn parse_ident<'sess>( + iter: &mut tokenstream::Cursor, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, Ident> { + let err_fn = + || sess.span_diagnostic.struct_span_err(span, "could not find an expected `ident` element"); + if let Some(tt) = iter.next() { + match tt { + tokenstream::TokenTree::Token(token) => { + if let Some((elem, false)) = token.ident() { + return Ok(elem); + } + let mut err = err_fn(); + err.span_suggestion( + token.span, + &format!("Try removing `{}`", pprust::token_to_string(&token)), + <_>::default(), + Applicability::MaybeIncorrect, + ); + return Err(err); + } + tokenstream::TokenTree::Delimited(delim_span, _, _) => { + let mut err = err_fn(); + err.span_suggestion( + delim_span.entire(), + "Try removing the delimiter", + <_>::default(), + Applicability::MaybeIncorrect, + ); + return Err(err); + } + } + } + Err(err_fn()) +} + +/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the +/// iterator is not modified and the result is `false`. +fn try_eat_comma(iter: &mut tokenstream::Cursor) -> bool { + if let Some(tokenstream::TokenTree::Token(token::Token { kind: token::Comma, .. })) = + iter.look_ahead(0) + { + let _ = iter.next(); + return true; + } + false +} diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index dedc6c618b9a4..5885af158a695 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -1,13 +1,13 @@ use crate::mbe::macro_parser; -use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree}; +use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree}; use rustc_ast::token::{self, Token}; use rustc_ast::tokenstream; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_ast_pretty::pprust; use rustc_feature::Features; -use rustc_session::parse::ParseSess; -use rustc_span::symbol::{kw, Ident}; +use rustc_session::parse::{feature_err, ParseSess}; +use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::edition::Edition; use rustc_span::{Span, SyntaxContext}; @@ -25,22 +25,22 @@ const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \ /// # Parameters /// /// - `input`: a token stream to read from, the contents of which we are parsing. -/// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a -/// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with -/// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and -/// `ident` are "matchers". They are not present in the body of a macro rule -- just in the -/// pattern, so we pass a parameter to indicate whether to expect them or not. +/// - `parsing_patterns`: `parse` can be used to parse either the "patterns" or the "body" of a +/// macro. Both take roughly the same form _except_ that: +/// - In a pattern, metavars are declared with their "matcher" type. For example `$var:expr` or +/// `$id:ident`. In this example, `expr` and `ident` are "matchers". They are not present in the +/// body of a macro rule -- just in the pattern. +/// - Metavariable expressions are only valid in the "body", not the "pattern". /// - `sess`: the parsing session. Any errors will be emitted to this session. /// - `node_id`: the NodeId of the macro we are parsing. /// - `features`: language features so we can do feature gating. -/// - `edition`: the edition of the crate defining the macro /// /// # Returns /// /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`. pub(super) fn parse( input: tokenstream::TokenStream, - expect_matchers: bool, + parsing_patterns: bool, sess: &ParseSess, node_id: NodeId, features: &Features, @@ -55,9 +55,9 @@ pub(super) fn parse( while let Some(tree) = trees.next() { // Given the parsed tree, if there is a metavar and we are expecting matchers, actually // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). - let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition); + let tree = parse_tree(tree, &mut trees, parsing_patterns, sess, node_id, features, edition); match tree { - TokenTree::MetaVar(start_sp, ident) if expect_matchers => { + TokenTree::MetaVar(start_sp, ident) if parsing_patterns => { let span = match trees.next() { Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => { match trees.next() { @@ -118,6 +118,14 @@ pub(super) fn parse( result } +/// Asks for the `macro_metavar_expr` feature if it is not already declared +fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &ParseSess, span: Span) { + if !features.macro_metavar_expr { + let msg = "meta-variable expressions are unstable"; + feature_err(&sess, sym::macro_metavar_expr, span, msg).emit(); + } +} + /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree` /// for use in parsing a macro. @@ -129,14 +137,13 @@ pub(super) fn parse( /// - `tree`: the tree we wish to convert. /// - `outer_trees`: an iterator over trees. We may need to read more tokens from it in order to finish /// converting `tree` -/// - `expect_matchers`: same as for `parse` (see above). +/// - `parsing_patterns`: same as [parse]. /// - `sess`: the parsing session. Any errors will be emitted to this session. /// - `features`: language features so we can do feature gating. -/// - `edition` - the edition of the crate defining the macro fn parse_tree( tree: tokenstream::TokenTree, outer_trees: &mut impl Iterator, - expect_matchers: bool, + parsing_patterns: bool, sess: &ParseSess, node_id: NodeId, features: &Features, @@ -158,24 +165,58 @@ fn parse_tree( } match next { - // `tree` is followed by a delimited set of token trees. This indicates the beginning - // of a repetition sequence in the macro (e.g. `$(pat)*`). - Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { - // Must have `(` not `{` or `[` - if delim != token::Paren { - let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); - let msg = format!("expected `(`, found `{}`", tok); - sess.span_diagnostic.span_err(span.entire(), &msg); + // `tree` is followed by a delimited set of token trees. + Some(tokenstream::TokenTree::Delimited(delim_span, delim, tts)) => { + if parsing_patterns { + // Meta-variable expressions are not allowed, so we must have + // `(`, not `{` or `[`. + if delim != token::Paren { + let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); + let msg = format!("expected `(`, found `{}`", tok); + sess.span_diagnostic.span_err(delim_span.entire(), &msg); + } + } else { + match delim { + token::Brace => { + // The delimiter is `{`. This indicates the beginning + // of a meta-variable expression (e.g. `${count(ident)}`). + // Try to parse the meta-variable expression. + match MetaVarExpr::parse(&tts, sess) { + Err(mut err) => { + err.emit(); + // Returns early the same read `$` to avoid spanning + // unrelated diagnostics that could be performed afterwards + return TokenTree::token(token::Dollar, span); + } + Ok(elem) => { + maybe_emit_macro_metavar_expr_feature( + features, + sess, + delim_span.entire(), + ); + return TokenTree::MetaVarExpr(delim_span, elem); + } + } + } + token::Paren => {} + _ => { + let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); + let msg = format!("expected `(` or `{{`, found `{}`", tok); + sess.span_diagnostic.span_err(delim_span.entire(), &msg); + } + } } - // Parse the contents of the sequence itself - let sequence = parse(tts, expect_matchers, sess, node_id, features, edition); + // If we didn't find a metavar expression above, then we must have a + // repetition sequence in the macro (e.g. `$(pat)*`). Parse the + // contents of the sequence itself + let sequence = parse(tts, parsing_patterns, sess, node_id, features, edition); // Get the Kleene operator and optional separator let (separator, kleene) = - parse_sep_and_kleene_op(&mut trees, span.entire(), sess); + parse_sep_and_kleene_op(&mut trees, delim_span.entire(), sess); // Count the number of captured "names" (i.e., named metavars) let name_captures = macro_parser::count_names(&sequence); TokenTree::Sequence( - span, + delim_span, Lrc::new(SequenceRepetition { tts: sequence, separator, @@ -197,7 +238,13 @@ fn parse_tree( } } - // `tree` is followed by a random token. This is an error. + // `tree` is followed by another `$`. This is an escaped `$`. + Some(tokenstream::TokenTree::Token(Token { kind: token::Dollar, span })) => { + maybe_emit_macro_metavar_expr_feature(features, sess, span); + TokenTree::token(token::Dollar, span) + } + + // `tree` is followed by some other token. This is an error. Some(tokenstream::TokenTree::Token(token)) => { let msg = format!( "expected identifier, found `{}`", @@ -221,7 +268,7 @@ fn parse_tree( span, Lrc::new(Delimited { delim, - tts: parse(tts, expect_matchers, sess, node_id, features, edition), + tts: parse(tts, parsing_patterns, sess, node_id, features, edition), }), ), } diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 01a7f7266172c..d650931760c89 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -7,9 +7,9 @@ use rustc_ast::token::{self, NtTT, Token}; use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndSpacing}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; -use rustc_errors::{pluralize, PResult}; +use rustc_errors::{pluralize, DiagnosticBuilder, PResult}; use rustc_span::hygiene::{LocalExpnId, Transparency}; -use rustc_span::symbol::MacroRulesNormalizedIdent; +use rustc_span::symbol::{sym, MacroRulesNormalizedIdent}; use rustc_span::Span; use smallvec::{smallvec, SmallVec}; @@ -255,6 +255,11 @@ pub(super) fn transcribe<'a>( } } + // Replace meta-variable expressions with the result of their expansion. + mbe::TokenTree::MetaVarExpr(sp, expr) => { + transcribe_metavar_expr(cx, expr, interp, &repeats, &mut result, &sp)?; + } + // If we are entering a new delimiter, we push its contents to the `stack` to be // processed, and we push all of the currently produced results to the `result_stack`. // We will produce all of the results of the inside of the `Delimited` and then we will @@ -352,6 +357,83 @@ impl LockstepIterSize { } } +/// Used solely by the `count` meta-variable expression, counts the outer-most repetitions at a +/// given optional nested depth. +/// +/// For example, a macro parameter of `$( { $( $foo:ident ),* } )*` called with `{ a, b } { c }`: +/// +/// * `[ $( ${count(foo)} ),* ]` will return [2, 1] with a, b = 2 and c = 1 +/// * `[ $( ${count(foo, 0)} ),* ]` will be the same as `[ $( ${count(foo)} ),* ]` +/// * `[ $( ${count(foo, 1)} ),* ]` will return an error because `${count(foo, 1)}` is +/// declared inside a single repetition and the index `1` implies two nested repetitions. +fn count_repetitions<'a>( + cx: &ExtCtxt<'a>, + depth_opt: Option, + ident: &MacroRulesNormalizedIdent, + mut matched: &NamedMatch, + repeats: &[(usize, usize)], + sp: &DelimSpan, +) -> PResult<'a, usize> { + // Recursively count the number of matches in `matched` at given depth + // (or at the top-level of `matched` if no depth is given). + fn count<'a>( + cx: &ExtCtxt<'a>, + depth_opt: Option, + matched: &NamedMatch, + sp: &DelimSpan, + system_depth: usize, + ) -> PResult<'a, usize> { + match matched { + MatchedNonterminal(_) => { + if system_depth == 0 { + return Err(cx.struct_span_err( + sp.entire(), + "`count` can not be placed inside the inner-most repetition", + )); + } + match depth_opt { + None => Ok(1), + Some(_) => Err(out_of_bounds_err(cx, system_depth, sp.entire(), "count")), + } + } + MatchedSeq(ref named_matches) => { + let new_system_depth = system_depth.wrapping_add(1); + match depth_opt { + None => named_matches + .iter() + .map(|elem| count(cx, None, elem, sp, new_system_depth)) + .sum(), + Some(0) => Ok(named_matches.len()), + Some(depth) => named_matches + .iter() + .map(|elem| count(cx, Some(depth - 1), elem, sp, new_system_depth)) + .sum(), + } + } + } + } + // `repeats` records all of the nested levels at which we are currently + // matching meta-variables. The meta-var-expr `count($x)` only counts + // matches that occur in this "subtree" of the `NamedMatch` where we + // are currently transcribing, so we need to descend to that subtree + // before we start counting. `matched` contains the various levels of the + // tree as we descend, and its final value is the subtree we are currently at. + for &(idx, _) in repeats { + match matched { + MatchedSeq(ref ads) if let Some(elem) = ads.get(idx) => matched = elem, + // We can only get here if `repeats` is more deeply nested than the + // `NamedMatch` passed in to `count_repetitions`. That would + // indicate that the RHS of the macro is more deeply nested than + // the LHS, which is an error. + _ => return Err(cx.struct_span_err( + sp.entire(), + &format!("variable `{}` does not repeat at this depth", ident), + )) + } + } + count(cx, depth_opt, matched, sp, 0) +} + /// Given a `tree`, make sure that all sequences have the same length as the matches for the /// appropriate meta-vars in `interpolations`. /// @@ -385,6 +467,90 @@ fn lockstep_iter_size( _ => LockstepIterSize::Unconstrained, } } + TokenTree::MetaVarExpr(_, ref expr) => { + let default_rslt = LockstepIterSize::Unconstrained; + let Some(ident) = expr.ident() else { return default_rslt; }; + let name = MacroRulesNormalizedIdent::new(ident.clone()); + match lookup_cur_matched(name, interpolations, repeats) { + Some(MatchedSeq(ref ads)) => { + default_rslt.with(LockstepIterSize::Constraint(ads.len(), name)) + } + _ => default_rslt, + } + } TokenTree::Token(..) => LockstepIterSize::Unconstrained, } } + +/// Used by meta-variable expressions when an user input is out of the actual declared bounds. For +/// example, index(999999) in an repetition of only three elements. +fn out_of_bounds_err<'a>( + cx: &ExtCtxt<'a>, + max: usize, + span: Span, + ty: &str, +) -> DiagnosticBuilder<'a> { + cx.struct_span_err(span, &format!("{ty} depth must be less than {max}")) +} + +fn transcribe_metavar_expr<'a>( + cx: &ExtCtxt<'a>, + expr: mbe::MetaVarExpr, + interp: &FxHashMap, + repeats: &[(usize, usize)], + result: &mut Vec, + sp: &DelimSpan, +) -> PResult<'a, ()> { + match expr { + mbe::MetaVarExpr::Count(original_ident, depth_opt) => { + let ident = MacroRulesNormalizedIdent::new(original_ident); + match interp.get(&ident) { + Some(matched) => { + let count = count_repetitions(cx, depth_opt, &ident, matched, &repeats, sp)?; + result.push( + TokenTree::token( + token::TokenKind::lit(token::Integer, sym::integer(count), None), + sp.entire(), + ) + .into(), + ); + } + None => { + return Err(cx.struct_span_err( + sp.entire(), + &format!( + "variable `{}` is not recognized in meta-variable expression", + ident + ), + )); + } + } + } + mbe::MetaVarExpr::Ignore(..) => {} + mbe::MetaVarExpr::Index(depth) => match repeats.iter().nth_back(depth) { + Some((index, _)) => { + result.push( + TokenTree::token( + token::TokenKind::lit(token::Integer, sym::integer(*index), None), + sp.entire(), + ) + .into(), + ); + } + None => return Err(out_of_bounds_err(cx, repeats.len(), sp.entire(), "index")), + }, + mbe::MetaVarExpr::Length(depth) => match repeats.iter().nth_back(depth) { + Some((_, length)) => { + result.push( + TokenTree::token( + token::TokenKind::lit(token::Integer, sym::integer(*length), None), + sp.entire(), + ) + .into(), + ); + } + None => return Err(out_of_bounds_err(cx, repeats.len(), sp.entire(), "length")), + }, + } + Ok(()) +} diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index 5545abc6024af..80c5428a37818 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -426,6 +426,8 @@ declare_features! ( (active, link_cfg, "1.14.0", Some(37406), None), /// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check. (active, lint_reasons, "1.31.0", Some(54503), None), + /// Give access to additional metadata about declarative macro meta-variables. + (active, macro_metavar_expr, "1.61.0", Some(83527), None), /// Allows `#[marker]` on certain traits allowing overlapping implementations. (active, marker_trait_attr, "1.30.0", Some(29864), None), /// A minimal, sound subset of specialization intended to be used by the diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 6767593bbc51a..c02171ae97f95 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -844,6 +844,7 @@ symbols! { macro_export, macro_lifetime_matcher, macro_literal_matcher, + macro_metavar_expr, macro_reexport, macro_use, macro_vis_matcher, diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs b/src/test/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs new file mode 100644 index 0000000000000..ab8d95a41d0d7 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs @@ -0,0 +1,271 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +fn main() { + macro_rules! one_nested_count_and_length { + ( $( [ $( $l:literal ),* ] ),* ) => { + [ + // outer-most repetition + $( + // inner-most repetition + $( + ${ignore(l)} ${index()}, ${length()}, + )* + ${count(l)}, ${index()}, ${length()}, + )* + ${count(l)}, + ] + }; + } + assert_eq!( + one_nested_count_and_length!(["foo"], ["bar", "baz"]), + [ + // # ["foo"] + + // ## inner-most repetition (first iteration) + // + // `index` is 0 because this is the first inner-most iteration. + // `length` is 1 because there is only one inner-most repetition, "foo". + 0, 1, + + // ## outer-most repetition (first iteration) + // + // `count` is 1 because of "foo", i,e, `$l` has only one repetition, + // `index` is 0 because this is the first outer-most iteration. + // `length` is 2 because there are 2 outer-most repetitions, ["foo"] and ["bar", "baz"] + 1, 0, 2, + + // # ["bar", "baz"] + + // ## inner-most repetition (first iteration) + // + // `index` is 0 because this is the first inner-most iteration + // `length` is 2 because there are repetitions, "bar" and "baz" + 0, 2, + + // ## inner-most repetition (second iteration) + // + // `index` is 1 because this is the second inner-most iteration + // `length` is 2 because there are repetitions, "bar" and "baz" + 1, 2, + + // ## outer-most repetition (second iteration) + // + // `count` is 2 because of "bar" and "baz", i,e, `$l` has two repetitions, + // `index` is 1 because this is the second outer-most iteration + // `length` is 2 because there are 2 outer-most repetitions, ["foo"] and ["bar", "baz"] + 2, 1, 2, + + // # last count + + // Because there are a total of 3 repetitions of `$l`, "foo", "bar" and "baz" + 3, + ] + ); + + // Based on the above explanation, the following macros should be straightforward + + // Grouped from the outer-most to the inner-most + macro_rules! three_nested_count { + ( $( { $( [ $( ( $( $i:ident )* ) )* ] )* } )* ) => { + &[ + $( $( $( + &[ + ${ignore(i)} ${count(i, 0)}, + ][..], + )* )* )* + + $( $( + &[ + ${ignore(i)} ${count(i, 0)}, + ${ignore(i)} ${count(i, 1)}, + ][..], + )* )* + + $( + &[ + ${ignore(i)} ${count(i, 0)}, + ${ignore(i)} ${count(i, 1)}, + ${ignore(i)} ${count(i, 2)}, + ][..], + )* + + &[ + ${count(i, 0)}, + ${count(i, 1)}, + ${count(i, 2)}, + ${count(i, 3)}, + ][..] + ][..] + } + } + assert_eq!( + three_nested_count!( + { + [ (a b c) (d e f) ] + [ (g h) (i j k l m) ] + [ (n) ] + } + { + [ (o) (p q) (r s) ] + [ (t u v w x y z) ] + } + ), + &[ + // a b c + &[3][..], + // d e f + &[3][..], + // g h + &[2][..], + // i j k l m + &[5][..], + // n + &[1][..], + // o + &[1][..], + // p q + &[2][..], + // r s + &[2][..], + // t u v w x y z + &[7][..], + + // (a b c) (d e f) + &[2, 6][..], + // (g h) (i j k l m) + &[2, 7][..], + // (n) + &[1, 1][..], + // (o) (p q) (r s) + &[3, 5][..], + // (t u v w x y z) + &[1, 7][..], + + // [ (a b c) (d e f) ] + // [ (g h) (i j k l m) ] + // [ (n) ] + &[3, 5, 14][..], + // [ (o) (p q) (r s) ] + // [ (t u v w x y z) ] + &[2, 4, 12][..], + + // { + // [ (a b c) (d e f) ] + // [ (g h) (i j k l m) ] + // [ (n) ] + // } + // { + // [ (o) (p q) (r s) ] + // [ (t u v w x y z) ] + // } + &[2, 5, 9, 26][..] + ][..] + ); + + // Grouped from the outer-most to the inner-most + macro_rules! three_nested_length { + ( $( { $( [ $( ( $( $i:ident )* ) )* ] )* } )* ) => { + &[ + $( $( $( $( + &[ + ${ignore(i)} ${length(3)}, + ${ignore(i)} ${length(2)}, + ${ignore(i)} ${length(1)}, + ${ignore(i)} ${length(0)}, + ][..], + )* )* )* )* + + $( $( $( + &[ + ${ignore(i)} ${length(2)}, + ${ignore(i)} ${length(1)}, + ${ignore(i)} ${length(0)}, + ][..], + )* )* )* + + $( $( + &[ + ${ignore(i)} ${length(1)}, + ${ignore(i)} ${length(0)}, + ][..], + )* )* + + $( + &[ + ${ignore(i)} ${length(0)}, + ][..], + )* + ][..] + } + } + assert_eq!( + three_nested_length!( + { + [ (a b c) (d e f) ] + [ (g h) (i j k l m) ] + [ (n) ] + } + { + [ (o) (p q) (r s) ] + [ (t u v w x y z) ] + } + ), + &[ + // a b c + &[2, 3, 2, 3][..], &[2, 3, 2, 3][..], &[2, 3, 2, 3][..], + // d e f + &[2, 3, 2, 3][..], &[2, 3, 2, 3][..], &[2, 3, 2, 3][..], + // g h + &[2, 3, 2, 2][..], &[2, 3, 2, 2][..], + // i j k l m + &[2, 3, 2, 5][..], &[2, 3, 2, 5][..], &[2, 3, 2, 5][..], &[2, 3, 2, 5][..], + &[2, 3, 2, 5][..], + // n + &[2, 3, 1, 1][..], + // o + &[2, 2, 3, 1][..], + // p q + &[2, 2, 3, 2][..], &[2, 2, 3, 2][..], + // r s + &[2, 2, 3, 2][..], &[2, 2, 3, 2][..], + // t u v w x y z + &[2, 2, 1, 7][..], &[2, 2, 1, 7][..], &[2, 2, 1, 7][..], &[2, 2, 1, 7][..], + &[2, 2, 1, 7][..], &[2, 2, 1, 7][..], &[2, 2, 1, 7][..], + + // (a b c) (d e f) + &[2, 3, 2][..], &[2, 3, 2][..], + // (g h) (i j k l m) + &[2, 3, 2][..], &[2, 3, 2][..], + // (n) + &[2, 3, 1][..], + // (o) (p q) (r s) + &[2, 2, 3][..], &[2, 2, 3][..], &[2, 2, 3][..], + // (t u v w x y z) + &[2, 2, 1][..], + + // [ (a b c) (d e f) ] + // [ (g h) (i j k l m) ] + // [ (n) ] + &[2, 3][..], &[2, 3][..], &[2, 3,][..], + // [ (o) (p q) (r s) ] + // [ (t u v w x y z) ] + &[2, 2][..], &[2, 2][..], + + // { + // [ (a b c) (d e f) ] + // [ (g h) (i j k l m) ] + // [ (n) ] + // } + // { + // [ (o) (p q) (r s) ] + // [ (t u v w x y z) ] + // } + &[2][..], &[2][..] + ][..] + ); + + // It is possible to say, to some degree, that count is an "amalgamation" of length (see + // each length line result and compare them with the count results) +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs b/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs new file mode 100644 index 0000000000000..24a0c56988b45 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs @@ -0,0 +1,38 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +macro_rules! nested { + ( $a:ident ) => { + macro_rules! $a { + ( $$( $b:ident ),* ) => { + $$( + macro_rules! $b { + ( $$$$( $c:ident ),* ) => { + $$$$( + fn $c() -> &'static str { stringify!($c) } + ),* + }; + } + )* + }; + } + }; +} + +macro_rules! not_nested { + ( $$ $foo:ident ) => {{ + let $foo: i32 = 1; + $foo + }}; +} + + +fn main() { + nested!(a); + a!(b); + b!(c); + assert_eq!(c(), "c"); + + assert_eq!(not_nested!($foo), 1); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs b/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs new file mode 100644 index 0000000000000..d05cd1b31bc12 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs @@ -0,0 +1,148 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +/// Count the number of idents in a macro repetition. +macro_rules! count_idents { + ( $( $i:ident ),* ) => { + ${count(i)} + }; +} + +/// Count the number of idents in a 2-dimensional macro repetition. +macro_rules! count_idents_2 { + ( $( [ $( $i:ident ),* ] ),* ) => { + ${count(i)} + }; +} + +/// Mostly counts the number of OUTER-MOST repetitions +macro_rules! count_depth_limits { + ( $( { $( [ $( $outer:ident : ( $( $inner:ident )* ) )* ] )* } )* ) => { + ( + ( + ${count(inner)}, + ${count(inner, 0)}, + ${count(inner, 1)}, + ${count(inner, 2)}, + ${count(inner, 3)}, + ), + ( + ${count(outer)}, + ${count(outer, 0)}, + ${count(outer, 1)}, + ${count(outer, 2)}, + ), + ) + }; +} + +/// Produce (index, length) pairs for literals in a macro repetition. +/// The literal is not included in the output, so this macro uses the +/// `ignore` meta-variable expression to create a non-expanding +/// repetition binding. +macro_rules! enumerate_literals { + ( $( ($l:stmt) ),* ) => { + [$( ${ignore(l)} (${index()}, ${length()}) ),*] + }; +} + +/// Produce index and length tuples for literals in a 2-dimensional +/// macro repetition. +macro_rules! enumerate_literals_2 { + ( $( [ $( ($l:literal) ),* ] ),* ) => { + [ + $( + $( + ( + ${index(1)}, + ${length(1)}, + ${index(0)}, + ${length(0)}, + $l + ), + )* + )* + ] + }; +} + +/// Generate macros that count idents and then add a constant number +/// to the count. +/// +/// This macro uses dollar escaping to make it unambiguous as to which +/// macro the repetition belongs to. +macro_rules! make_count_adders { + ( $( $i:ident, $b:literal );* ) => { + $( + macro_rules! $i { + ( $$( $$j:ident ),* ) => { + $b + $${count(j)} + }; + } + )* + }; +} + +make_count_adders! { plus_one, 1; plus_five, 5 } + +/// Generate a macro that allows selection of a particular literal +/// from a sequence of inputs by their identifier. +/// +/// This macro uses dollar escaping to make it unambiguous as to which +/// macro the repetition belongs to, and to allow expansion of an +/// identifier the name of which is not known in the definition +/// of `make_picker`. +macro_rules! make_picker { + ( $m:ident => $( $i:ident ),* ; $p:ident ) => { + macro_rules! $m { + ( $( $$ $i:literal ),* ) => { + $$ $p + }; + } + }; +} + +make_picker!(first => a, b; a); + +make_picker!(second => a, b; b); + +fn main() { + assert_eq!(count_idents!(a, b, c), 3); + assert_eq!(count_idents_2!([a, b, c], [d, e], [f]), 6); + assert_eq!( + count_depth_limits! { + { + [ A: (a b c) D: (d e f) ] + [ G: (g h) I: (i j k l m) ] + [ N: (n) ] + } + { + [ O: (o) P: (p q) R: (r s) ] + [ T: (t u v w x y z) ] + } + }, + ((26, 2, 5, 9, 26), (9, 2, 5, 9)) + ); + assert_eq!(enumerate_literals![("foo"), ("bar")], [(0, 2), (1, 2)]); + assert_eq!( + enumerate_literals_2![ + [("foo"), ("bar"), ("baz")], + [("qux"), ("quux"), ("quuz"), ("xyzzy")] + ], + [ + (0, 2, 0, 3, "foo"), + (0, 2, 1, 3, "bar"), + (0, 2, 2, 3, "baz"), + + (1, 2, 0, 4, "qux"), + (1, 2, 1, 4, "quux"), + (1, 2, 2, 4, "quuz"), + (1, 2, 3, 4, "xyzzy"), + ] + ); + assert_eq!(plus_one!(a, b, c), 4); + assert_eq!(plus_five!(a, b), 7); + assert_eq!(first!(1, 2), 1); + assert_eq!(second!(1, 2), 2); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs b/src/test/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs new file mode 100644 index 0000000000000..b954967c4fe5a --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs @@ -0,0 +1,102 @@ +// run-pass + +#![feature(macro_metavar_expr)] + +#[derive(Debug)] +struct Example<'a> { + _indexes: &'a [(u32, u32)], + _counts: &'a [u32], + _nested: Vec>, +} + +macro_rules! example { + ( $( [ $( ( $( $x:ident )* ) )* ] )* ) => { + Example { + _indexes: &[], + _counts: &[${count(x, 0)}, ${count(x, 1)}, ${count(x, 2)}], + _nested: vec![ + $( + Example { + _indexes: &[(${index()}, ${length()})], + _counts: &[${count(x, 0)}, ${count(x, 1)}], + _nested: vec![ + $( + Example { + _indexes: &[(${index(1)}, ${length(1)}), (${index()}, ${length()})], + _counts: &[${count(x)}], + _nested: vec![ + $( + Example { + _indexes: &[ + (${index(2)}, ${length(2)}), + (${index(1)}, ${length(1)}), + (${index()}, ${length()}) + ], + _counts: &[], + _nested: vec![], + ${ignore(x)} + } + ),* + ] + } + ),* + ] + } + ),* + ] + } + }; +} + +static EXPECTED: &str = concat!( + "Example { _indexes: [], _counts: [2, 4, 13], _nested: [", + concat!( + "Example { _indexes: [(0, 2)], _counts: [3, 10], _nested: [", + concat!( + "Example { _indexes: [(0, 2), (0, 3)], _counts: [4], _nested: [", + concat!( + "Example { _indexes: [(0, 2), (0, 3), (0, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (0, 3), (1, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (0, 3), (2, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (0, 3), (3, 4)], _counts: [], _nested: [] }", + ), + "] }, ", + "Example { _indexes: [(0, 2), (1, 3)], _counts: [4], _nested: [", + concat!( + "Example { _indexes: [(0, 2), (1, 3), (0, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (1, 3), (1, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (1, 3), (2, 4)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (1, 3), (3, 4)], _counts: [], _nested: [] }", + ), + "] }, ", + "Example { _indexes: [(0, 2), (2, 3)], _counts: [2], _nested: [", + concat!( + "Example { _indexes: [(0, 2), (2, 3), (0, 2)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(0, 2), (2, 3), (1, 2)], _counts: [], _nested: [] }", + ), + "] }", + ), + "] }, ", + "Example { _indexes: [(1, 2)], _counts: [1, 3], _nested: [", + concat!( + "Example { _indexes: [(1, 2), (0, 1)], _counts: [3], _nested: [", + concat!( + "Example { _indexes: [(1, 2), (0, 1), (0, 3)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(1, 2), (0, 1), (1, 3)], _counts: [], _nested: [] }, ", + "Example { _indexes: [(1, 2), (0, 1), (2, 3)], _counts: [], _nested: [] }", + ), + "] }", + ), + "] }", + ), + "] }", +); + +fn main() { + let e = example! { + [ ( A B C D ) ( E F G H ) ( I J ) ] + [ ( K L M ) ] + }; + let debug = format!("{:?}", e); + assert_eq!(debug, EXPECTED); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs b/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs new file mode 100644 index 0000000000000..d81c8628bab26 --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs @@ -0,0 +1,44 @@ +#![feature(macro_metavar_expr)] + +macro_rules! a { + ( $( { $( [ $( ( $( $foo:ident )* ) )* ] )* } )* ) => { + ( + ${count(foo, 0)}, + ${count(foo, 10)}, + //~^ ERROR count depth must be less than 4 + ) + }; +} + +macro_rules! b { + ( $( { $( [ $( $foo:ident )* ] )* } )* ) => { + ( + $( $( $( + ${ignore(foo)} + ${index(0)}, + ${index(10)}, + //~^ ERROR index depth must be less than 3 + )* )* )* + ) + }; +} + +macro_rules! c { + ( $( { $( $foo:ident )* } )* ) => { + ( + $( $( + ${ignore(foo)} + ${length(0)} + ${length(10)} + //~^ ERROR length depth must be less than 2 + )* )* + ) + }; +} + + +fn main() { + a!( { [ (a) ] [ (b c) ] } ); + b!( { [ a b ] } ); + c!( { a } ); +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr b/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr new file mode 100644 index 0000000000000..7474c03c0f98b --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr @@ -0,0 +1,20 @@ +error: count depth must be less than 4 + --> $DIR/out-of-bounds-arguments.rs:7:14 + | +LL | ${count(foo, 10)}, + | ^^^^^^^^^^^^^^^^ + +error: index depth must be less than 3 + --> $DIR/out-of-bounds-arguments.rs:19:18 + | +LL | ${index(10)}, + | ^^^^^^^^^^^ + +error: length depth must be less than 2 + --> $DIR/out-of-bounds-arguments.rs:32:18 + | +LL | ${length(10)} + | ^^^^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.rs b/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.rs new file mode 100644 index 0000000000000..33b00928b8d9d --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.rs @@ -0,0 +1,15 @@ +macro_rules! count { + ( $( $e:stmt ),* ) => { + ${ count(e) } + //~^ ERROR meta-variable expressions are unstable + }; +} + +macro_rules! a { + ( $$a:ident ) => { + //~^ ERROR meta-variable expressions are unstable + }; +} + +fn main() { +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.stderr b/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.stderr new file mode 100644 index 0000000000000..0ea056956a0be --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/requiring-feature.stderr @@ -0,0 +1,21 @@ +error[E0658]: meta-variable expressions are unstable + --> $DIR/requiring-feature.rs:3:10 + | +LL | ${ count(e) } + | ^^^^^^^^^^^^ + | + = note: see issue #83527 for more information + = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable + +error[E0658]: meta-variable expressions are unstable + --> $DIR/requiring-feature.rs:9:8 + | +LL | ( $$a:ident ) => { + | ^ + | + = note: see issue #83527 for more information + = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs new file mode 100644 index 0000000000000..26afa3c11094d --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs @@ -0,0 +1,60 @@ +#![feature(macro_metavar_expr)] + +// `curly` = Right hand side curly brackets +// `no_rhs_dollar` = No dollar sign at the right hand side meta variable "function" +// `round` = Left hand side round brackets + +macro_rules! curly__no_rhs_dollar__round { + ( $( $i:ident ),* ) => { ${ count(i) } }; +} + +macro_rules! curly__no_rhs_dollar__no_round { + ( $i:ident ) => { ${ count(i) } }; + //~^ ERROR `count` can not be placed inside the inner-most repetition +} + +macro_rules! curly__rhs_dollar__round { + ( $( $i:ident ),* ) => { ${ count($i) } }; + //~^ ERROR could not find an expected `ident` element + //~| ERROR expected expression, found `$` +} + +macro_rules! curly__rhs_dollar__no_round { + ( $i:ident ) => { ${ count($i) } }; + //~^ ERROR could not find an expected `ident` element + //~| ERROR expected expression, found `$` +} + +macro_rules! no_curly__no_rhs_dollar__round { + ( $( $i:ident ),* ) => { count(i) }; + //~^ ERROR cannot find function `count` in this scope + //~| ERROR cannot find value `i` in this scope +} + +macro_rules! no_curly__no_rhs_dollar__no_round { + ( $i:ident ) => { count(i) }; + //~^ ERROR cannot find function `count` in this scope + //~| ERROR cannot find value `i` in this scope +} + +macro_rules! no_curly__rhs_dollar__round { + ( $( $i:ident ),* ) => { count($i) }; + //~^ ERROR variable 'i' is still repeating at this depth +} + +macro_rules! no_curly__rhs_dollar__no_round { + ( $i:ident ) => { count($i) }; + //~^ ERROR cannot find function `count` in this scope +} + +fn main() { + curly__no_rhs_dollar__round!(a, b, c); + curly__no_rhs_dollar__no_round!(a); + curly__rhs_dollar__round!(a, b, c); + curly__rhs_dollar__no_round!(a); + no_curly__no_rhs_dollar__round!(a, b, c); + no_curly__no_rhs_dollar__no_round!(a); + no_curly__rhs_dollar__round!(a, b, c); + no_curly__rhs_dollar__no_round!(a); + //~^ ERROR cannot find value `a` in this scope +} diff --git a/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr new file mode 100644 index 0000000000000..4c6cf7443e8ee --- /dev/null +++ b/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr @@ -0,0 +1,110 @@ +error: could not find an expected `ident` element + --> $DIR/syntax-errors.rs:17:33 + | +LL | ( $( $i:ident ),* ) => { ${ count($i) } }; + | ^^^^^ - help: Try removing `$` + +error: could not find an expected `ident` element + --> $DIR/syntax-errors.rs:23:26 + | +LL | ( $i:ident ) => { ${ count($i) } }; + | ^^^^^ - help: Try removing `$` + +error: `count` can not be placed inside the inner-most repetition + --> $DIR/syntax-errors.rs:12:24 + | +LL | ( $i:ident ) => { ${ count(i) } }; + | ^^^^^^^^^^^^ + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:17:30 + | +LL | ( $( $i:ident ),* ) => { ${ count($i) } }; + | ^ expected expression +... +LL | curly__rhs_dollar__round!(a, b, c); + | ---------------------------------- in this macro invocation + | + = note: this error originates in the macro `curly__rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:23:23 + | +LL | ( $i:ident ) => { ${ count($i) } }; + | ^ expected expression +... +LL | curly__rhs_dollar__no_round!(a); + | ------------------------------- in this macro invocation + | + = note: this error originates in the macro `curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: variable 'i' is still repeating at this depth + --> $DIR/syntax-errors.rs:41:36 + | +LL | ( $( $i:ident ),* ) => { count($i) }; + | ^^ + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:29:30 + | +LL | ( $( $i:ident ),* ) => { count(i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__no_rhs_dollar__round!(a, b, c); + | ---------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `i` in this scope + --> $DIR/syntax-errors.rs:29:36 + | +LL | ( $( $i:ident ),* ) => { count(i) }; + | ^ not found in this scope +... +LL | no_curly__no_rhs_dollar__round!(a, b, c); + | ---------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:35:23 + | +LL | ( $i:ident ) => { count(i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__no_rhs_dollar__no_round!(a); + | ------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `i` in this scope + --> $DIR/syntax-errors.rs:35:29 + | +LL | ( $i:ident ) => { count(i) }; + | ^ not found in this scope +... +LL | no_curly__no_rhs_dollar__no_round!(a); + | ------------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find function `count` in this scope + --> $DIR/syntax-errors.rs:46:23 + | +LL | ( $i:ident ) => { count($i) }; + | ^^^^^ not found in this scope +... +LL | no_curly__rhs_dollar__no_round!(a); + | ---------------------------------- in this macro invocation + | + = note: this error originates in the macro `no_curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `a` in this scope + --> $DIR/syntax-errors.rs:58:37 + | +LL | no_curly__rhs_dollar__no_round!(a); + | ^ not found in this scope + +error: aborting due to 12 previous errors + +For more information about this error, try `rustc --explain E0425`.