Skip to content

Commit 16f8f54

Browse files
authored
Rollup merge of rust-lang#64689 - matklad:refactor-mbe, r=petrochenkov
Refactor macro by example This doesn't do anything useful yet, and just moves code around and restricts visibility
2 parents 4ac9261 + 81fe857 commit 16f8f54

File tree

10 files changed

+297
-294
lines changed

10 files changed

+297
-294
lines changed

src/librustc_resolve/macros.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use syntax::ext::base::{self, InvocationRes, Indeterminate, SpecialDerives};
1818
use syntax::ext::base::{MacroKind, SyntaxExtension};
1919
use syntax::ext::expand::{AstFragment, AstFragmentKind, Invocation, InvocationKind};
2020
use syntax::ext::hygiene::{self, ExpnId, ExpnData, ExpnKind};
21-
use syntax::ext::tt::macro_rules;
21+
use syntax::ext::compile_declarative_macro;
2222
use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
2323
use syntax::feature_gate::GateIssue;
2424
use syntax::symbol::{Symbol, kw, sym};
@@ -843,7 +843,7 @@ impl<'a> Resolver<'a> {
843843
/// Compile the macro into a `SyntaxExtension` and possibly replace it with a pre-defined
844844
/// extension partially or entirely for built-in macros and legacy plugin macros.
845845
crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
846-
let mut result = macro_rules::compile(
846+
let mut result = compile_declarative_macro(
847847
&self.session.parse_sess, self.session.features_untracked(), item, edition
848848
);
849849

src/libsyntax/ext/expand.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::config::StripUnconfigured;
66
use crate::ext::base::*;
77
use crate::ext::proc_macro::{collect_derives, MarkAttrs};
88
use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
9-
use crate::ext::tt::macro_rules::annotate_err_with_kind;
9+
use crate::ext::mbe::macro_rules::annotate_err_with_kind;
1010
use crate::ext::placeholders::{placeholder, PlaceholderExpander};
1111
use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
1212
use crate::mut_visit::*;
@@ -115,8 +115,8 @@ macro_rules! ast_fragments {
115115
}
116116
}
117117

118-
impl<'a> MacResult for crate::ext::tt::macro_rules::ParserAnyMacro<'a> {
119-
$(fn $make_ast(self: Box<crate::ext::tt::macro_rules::ParserAnyMacro<'a>>)
118+
impl<'a> MacResult for crate::ext::mbe::macro_rules::ParserAnyMacro<'a> {
119+
$(fn $make_ast(self: Box<crate::ext::mbe::macro_rules::ParserAnyMacro<'a>>)
120120
-> Option<$AstTy> {
121121
Some(self.make(AstFragmentKind::$Kind).$make_ast())
122122
})*

src/libsyntax/ext/mbe.rs

+166
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
//! This module implements declarative macros: old `macro_rules` and the newer
2+
//! `macro`. Declarative macros are also known as "macro by example", and that's
3+
//! why we call this module `mbe`. For external documentation, prefer the
4+
//! official terminology: "declarative macros".
5+
6+
crate mod transcribe;
7+
crate mod macro_check;
8+
crate mod macro_parser;
9+
crate mod macro_rules;
10+
crate mod quoted;
11+
12+
use crate::ast;
13+
use crate::parse::token::{self, Token, TokenKind};
14+
use crate::tokenstream::{DelimSpan};
15+
16+
use syntax_pos::{BytePos, Span};
17+
18+
use rustc_data_structures::sync::Lrc;
19+
20+
/// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
21+
/// that the delimiter itself might be `NoDelim`.
22+
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
23+
struct Delimited {
24+
delim: token::DelimToken,
25+
tts: Vec<TokenTree>,
26+
}
27+
28+
impl Delimited {
29+
/// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
30+
fn open_tt(&self, span: Span) -> TokenTree {
31+
let open_span = if span.is_dummy() {
32+
span
33+
} else {
34+
span.with_hi(span.lo() + BytePos(self.delim.len() as u32))
35+
};
36+
TokenTree::token(token::OpenDelim(self.delim), open_span)
37+
}
38+
39+
/// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
40+
fn close_tt(&self, span: Span) -> TokenTree {
41+
let close_span = if span.is_dummy() {
42+
span
43+
} else {
44+
span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
45+
};
46+
TokenTree::token(token::CloseDelim(self.delim), close_span)
47+
}
48+
}
49+
50+
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
51+
struct SequenceRepetition {
52+
/// The sequence of token trees
53+
tts: Vec<TokenTree>,
54+
/// The optional separator
55+
separator: Option<Token>,
56+
/// Whether the sequence can be repeated zero (*), or one or more times (+)
57+
kleene: KleeneToken,
58+
/// The number of `Match`s that appear in the sequence (and subsequences)
59+
num_captures: usize,
60+
}
61+
62+
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
63+
struct KleeneToken {
64+
span: Span,
65+
op: KleeneOp,
66+
}
67+
68+
impl KleeneToken {
69+
fn new(op: KleeneOp, span: Span) -> KleeneToken {
70+
KleeneToken { span, op }
71+
}
72+
}
73+
74+
/// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
75+
/// for token sequences.
76+
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
77+
enum KleeneOp {
78+
/// Kleene star (`*`) for zero or more repetitions
79+
ZeroOrMore,
80+
/// Kleene plus (`+`) for one or more repetitions
81+
OneOrMore,
82+
/// Kleene optional (`?`) for zero or one reptitions
83+
ZeroOrOne,
84+
}
85+
86+
/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
87+
/// are "first-class" token trees. Useful for parsing macros.
88+
#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
89+
enum TokenTree {
90+
Token(Token),
91+
Delimited(DelimSpan, Lrc<Delimited>),
92+
/// A kleene-style repetition sequence
93+
Sequence(DelimSpan, Lrc<SequenceRepetition>),
94+
/// e.g., `$var`
95+
MetaVar(Span, ast::Ident),
96+
/// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
97+
MetaVarDecl(
98+
Span,
99+
ast::Ident, /* name to bind */
100+
ast::Ident, /* kind of nonterminal */
101+
),
102+
}
103+
104+
impl TokenTree {
105+
/// Return the number of tokens in the tree.
106+
fn len(&self) -> usize {
107+
match *self {
108+
TokenTree::Delimited(_, ref delimed) => match delimed.delim {
109+
token::NoDelim => delimed.tts.len(),
110+
_ => delimed.tts.len() + 2,
111+
},
112+
TokenTree::Sequence(_, ref seq) => seq.tts.len(),
113+
_ => 0,
114+
}
115+
}
116+
117+
/// Returns `true` if the given token tree is delimited.
118+
fn is_delimited(&self) -> bool {
119+
match *self {
120+
TokenTree::Delimited(..) => true,
121+
_ => false,
122+
}
123+
}
124+
125+
/// Returns `true` if the given token tree is a token of the given kind.
126+
fn is_token(&self, expected_kind: &TokenKind) -> bool {
127+
match self {
128+
TokenTree::Token(Token { kind: actual_kind, .. }) => actual_kind == expected_kind,
129+
_ => false,
130+
}
131+
}
132+
133+
/// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
134+
fn get_tt(&self, index: usize) -> TokenTree {
135+
match (self, index) {
136+
(&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
137+
delimed.tts[index].clone()
138+
}
139+
(&TokenTree::Delimited(span, ref delimed), _) => {
140+
if index == 0 {
141+
return delimed.open_tt(span.open);
142+
}
143+
if index == delimed.tts.len() + 1 {
144+
return delimed.close_tt(span.close);
145+
}
146+
delimed.tts[index - 1].clone()
147+
}
148+
(&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
149+
_ => panic!("Cannot expand a token tree"),
150+
}
151+
}
152+
153+
/// Retrieves the `TokenTree`'s span.
154+
fn span(&self) -> Span {
155+
match *self {
156+
TokenTree::Token(Token { span, .. })
157+
| TokenTree::MetaVar(span, _)
158+
| TokenTree::MetaVarDecl(span, _, _) => span,
159+
TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(),
160+
}
161+
}
162+
163+
fn token(kind: TokenKind, span: Span) -> TokenTree {
164+
TokenTree::Token(Token::new(kind, span))
165+
}
166+
}

src/libsyntax/ext/tt/macro_check.rs renamed to src/libsyntax/ext/mbe/macro_check.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@
106106
//! bound.
107107
use crate::ast::NodeId;
108108
use crate::early_buffered_lints::BufferedEarlyLintId;
109-
use crate::ext::tt::quoted::{KleeneToken, TokenTree};
109+
use crate::ext::mbe::{KleeneToken, TokenTree};
110110
use crate::parse::token::TokenKind;
111111
use crate::parse::token::{DelimToken, Token};
112112
use crate::parse::ParseSess;
@@ -196,7 +196,7 @@ struct MacroState<'a> {
196196
/// - `node_id` is used to emit lints
197197
/// - `span` is used when no spans are available
198198
/// - `lhses` and `rhses` should have the same length and represent the macro definition
199-
pub fn check_meta_variables(
199+
pub(super) fn check_meta_variables(
200200
sess: &ParseSess,
201201
node_id: NodeId,
202202
span: Span,

src/libsyntax/ext/tt/macro_parser.rs renamed to src/libsyntax/ext/mbe/macro_parser.rs

+13-13
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,12 @@
7070
//! eof: [a $( a )* a b ·]
7171
//! ```
7272
73-
pub use NamedMatch::*;
74-
pub use ParseResult::*;
73+
crate use NamedMatch::*;
74+
crate use ParseResult::*;
7575
use TokenTreeOrTokenTreeSlice::*;
7676

7777
use crate::ast::{Ident, Name};
78-
use crate::ext::tt::quoted::{self, TokenTree};
78+
use crate::ext::mbe::{self, TokenTree};
7979
use crate::parse::{Directory, ParseSess};
8080
use crate::parse::parser::{Parser, PathStyle};
8181
use crate::parse::token::{self, DocComment, Nonterminal, Token};
@@ -195,7 +195,7 @@ struct MatcherPos<'root, 'tt> {
195195
// `None`.
196196

197197
/// The KleeneOp of this sequence if we are in a repetition.
198-
seq_op: Option<quoted::KleeneOp>,
198+
seq_op: Option<mbe::KleeneOp>,
199199

200200
/// The separator if we are in a repetition.
201201
sep: Option<Token>,
@@ -267,7 +267,7 @@ impl<'root, 'tt> DerefMut for MatcherPosHandle<'root, 'tt> {
267267
}
268268

269269
/// Represents the possible results of an attempted parse.
270-
pub enum ParseResult<T> {
270+
crate enum ParseResult<T> {
271271
/// Parsed successfully.
272272
Success(T),
273273
/// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
@@ -279,10 +279,10 @@ pub enum ParseResult<T> {
279279

280280
/// A `ParseResult` where the `Success` variant contains a mapping of `Ident`s to `NamedMatch`es.
281281
/// This represents the mapping of metavars to the token trees they bind to.
282-
pub type NamedParseResult = ParseResult<FxHashMap<Ident, NamedMatch>>;
282+
crate type NamedParseResult = ParseResult<FxHashMap<Ident, NamedMatch>>;
283283

284284
/// Count how many metavars are named in the given matcher `ms`.
285-
pub fn count_names(ms: &[TokenTree]) -> usize {
285+
pub(super) fn count_names(ms: &[TokenTree]) -> usize {
286286
ms.iter().fold(0, |count, elt| {
287287
count + match *elt {
288288
TokenTree::Sequence(_, ref seq) => seq.num_captures,
@@ -352,7 +352,7 @@ fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree], open: Span) -> MatcherP
352352
/// only on the nesting depth of `ast::TTSeq`s in the originating
353353
/// token tree it was derived from.
354354
#[derive(Debug, Clone)]
355-
pub enum NamedMatch {
355+
crate enum NamedMatch {
356356
MatchedSeq(Lrc<NamedMatchVec>, DelimSpan),
357357
MatchedNonterminal(Lrc<Nonterminal>),
358358
}
@@ -415,7 +415,7 @@ fn nameize<I: Iterator<Item = NamedMatch>>(
415415

416416
/// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
417417
/// other tokens, this is "unexpected token...".
418-
pub fn parse_failure_msg(tok: &Token) -> String {
418+
crate fn parse_failure_msg(tok: &Token) -> String {
419419
match tok.kind {
420420
token::Eof => "unexpected end of macro invocation".to_string(),
421421
_ => format!(
@@ -532,7 +532,7 @@ fn inner_parse_loop<'root, 'tt>(
532532
}
533533
// We don't need a separator. Move the "dot" back to the beginning of the matcher
534534
// and try to match again UNLESS we are only allowed to have _one_ repetition.
535-
else if item.seq_op != Some(quoted::KleeneOp::ZeroOrOne) {
535+
else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) {
536536
item.match_cur = item.match_lo;
537537
item.idx = 0;
538538
cur_items.push(item);
@@ -555,8 +555,8 @@ fn inner_parse_loop<'root, 'tt>(
555555
// implicitly disallowing OneOrMore from having 0 matches here. Thus, that will
556556
// result in a "no rules expected token" error by virtue of this matcher not
557557
// working.
558-
if seq.kleene.op == quoted::KleeneOp::ZeroOrMore
559-
|| seq.kleene.op == quoted::KleeneOp::ZeroOrOne
558+
if seq.kleene.op == mbe::KleeneOp::ZeroOrMore
559+
|| seq.kleene.op == mbe::KleeneOp::ZeroOrOne
560560
{
561561
let mut new_item = item.clone();
562562
new_item.match_cur += seq.num_captures;
@@ -648,7 +648,7 @@ fn inner_parse_loop<'root, 'tt>(
648648
/// - `directory`: Information about the file locations (needed for the black-box parser)
649649
/// - `recurse_into_modules`: Whether or not to recurse into modules (needed for the black-box
650650
/// parser)
651-
pub fn parse(
651+
pub(super) fn parse(
652652
sess: &ParseSess,
653653
tts: TokenStream,
654654
ms: &[TokenTree],

0 commit comments

Comments
 (0)