]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_rules.rs
Rollup merge of #58118 - h-michael:libtest-theme-2018, r=Centril
[rust.git] / src / libsyntax / ext / tt / macro_rules.rs
1 use crate::{ast, attr};
2 use crate::edition::Edition;
3 use crate::errors::FatalError;
4 use crate::ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
5 use crate::ext::base::{NormalTT, TTMacroExpander};
6 use crate::ext::expand::{AstFragment, AstFragmentKind};
7 use crate::ext::tt::macro_parser::{Success, Error, Failure};
8 use crate::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
9 use crate::ext::tt::macro_parser::{parse, parse_failure_msg};
10 use crate::ext::tt::quoted;
11 use crate::ext::tt::transcribe::transcribe;
12 use crate::feature_gate::Features;
13 use crate::parse::{Directory, ParseSess};
14 use crate::parse::parser::Parser;
15 use crate::parse::token::{self, NtTT};
16 use crate::parse::token::Token::*;
17 use crate::symbol::Symbol;
18 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
19
20 use syntax_pos::{Span, DUMMY_SP};
21 use log::debug;
22
23 use rustc_data_structures::fx::FxHashMap;
24 use std::borrow::Cow;
25 use std::collections::hash_map::Entry;
26
27 use rustc_data_structures::sync::Lrc;
28 use crate::errors::Applicability;
29
30 const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
31     `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, \
32     `path`, `meta`, `tt`, `item` and `vis`";
33
34 pub struct ParserAnyMacro<'a> {
35     parser: Parser<'a>,
36
37     /// Span of the expansion site of the macro this parser is for
38     site_span: Span,
39     /// The ident of the macro we're parsing
40     macro_ident: ast::Ident,
41     arm_span: Span,
42 }
43
44 impl<'a> ParserAnyMacro<'a> {
45     pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
46         let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;
47         let fragment = panictry!(parser.parse_ast_fragment(kind, true).map_err(|mut e| {
48             if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") {
49                 if !e.span.is_dummy() {  // early end of macro arm (#52866)
50                     e.replace_span_with(parser.sess.source_map().next_point(parser.span));
51                 }
52                 let msg = &e.message[0];
53                 e.message[0] = (
54                     format!(
55                         "macro expansion ends with an incomplete expression: {}",
56                         msg.0.replace(", found `<eof>`", ""),
57                     ),
58                     msg.1,
59                 );
60             }
61             if e.span.is_dummy() {  // Get around lack of span in error (#30128)
62                 e.replace_span_with(site_span);
63                 if parser.sess.source_map().span_to_filename(arm_span).is_real() {
64                     e.span_label(arm_span, "in this macro arm");
65                 }
66             } else if !parser.sess.source_map().span_to_filename(parser.span).is_real() {
67                 e.span_label(site_span, "in this macro invocation");
68             }
69             e
70         }));
71
72         // We allow semicolons at the end of expressions -- e.g., the semicolon in
73         // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
74         // but `m!()` is allowed in expression positions (cf. issue #34706).
75         if kind == AstFragmentKind::Expr && parser.token == token::Semi {
76             parser.bump();
77         }
78
79         // Make sure we don't have any tokens left to parse so we don't silently drop anything.
80         let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
81         parser.ensure_complete_parse(&path, kind.name(), site_span);
82         fragment
83     }
84 }
85
86 struct MacroRulesMacroExpander {
87     name: ast::Ident,
88     lhses: Vec<quoted::TokenTree>,
89     rhses: Vec<quoted::TokenTree>,
90     valid: bool,
91 }
92
93 impl TTMacroExpander for MacroRulesMacroExpander {
94     fn expand<'cx>(
95         &self,
96         cx: &'cx mut ExtCtxt<'_>,
97         sp: Span,
98         input: TokenStream,
99         def_span: Option<Span>,
100     ) -> Box<dyn MacResult+'cx> {
101         if !self.valid {
102             return DummyResult::any(sp);
103         }
104         generic_extension(cx,
105                           sp,
106                           def_span,
107                           self.name,
108                           input,
109                           &self.lhses,
110                           &self.rhses)
111     }
112 }
113
114 fn trace_macros_note(cx: &mut ExtCtxt<'_>, sp: Span, message: String) {
115     let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
116     cx.expansions.entry(sp).or_default().push(message);
117 }
118
119 /// Given `lhses` and `rhses`, this is the new macro we create
120 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt<'_>,
121                           sp: Span,
122                           def_span: Option<Span>,
123                           name: ast::Ident,
124                           arg: TokenStream,
125                           lhses: &[quoted::TokenTree],
126                           rhses: &[quoted::TokenTree])
127                           -> Box<dyn MacResult+'cx> {
128     if cx.trace_macros() {
129         trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
130     }
131
132     // Which arm's failure should we report? (the one furthest along)
133     let mut best_fail_spot = DUMMY_SP;
134     let mut best_fail_tok = None;
135     let mut best_fail_text = None;
136
137     for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
138         let lhs_tt = match *lhs {
139             quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
140             _ => cx.span_bug(sp, "malformed macro lhs")
141         };
142
143         match TokenTree::parse(cx, lhs_tt, arg.clone()) {
144             Success(named_matches) => {
145                 let rhs = match rhses[i] {
146                     // ignore delimiters
147                     quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
148                     _ => cx.span_bug(sp, "malformed macro rhs"),
149                 };
150                 let arm_span = rhses[i].span();
151
152                 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
153                 // rhs has holes ( `$id` and `$(...)` that need filled)
154                 let mut tts = transcribe(cx, Some(named_matches), rhs);
155
156                 // Replace all the tokens for the corresponding positions in the macro, to maintain
157                 // proper positions in error reporting, while maintaining the macro_backtrace.
158                 if rhs_spans.len() == tts.len() {
159                     tts = tts.map_enumerated(|i, mut tt| {
160                         let mut sp = rhs_spans[i];
161                         sp = sp.with_ctxt(tt.span().ctxt());
162                         tt.set_span(sp);
163                         tt
164                     });
165                 }
166
167                 if cx.trace_macros() {
168                     trace_macros_note(cx, sp, format!("to `{}`", tts));
169                 }
170
171                 let directory = Directory {
172                     path: Cow::from(cx.current_expansion.module.directory.as_path()),
173                     ownership: cx.current_expansion.directory_ownership,
174                 };
175                 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
176                 p.root_module_name = cx.current_expansion.module.mod_path.last()
177                     .map(|id| id.as_str().to_string());
178
179                 p.process_potential_macro_variable();
180                 // Let the context choose how to interpret the result.
181                 // Weird, but useful for X-macros.
182                 return Box::new(ParserAnyMacro {
183                     parser: p,
184
185                     // Pass along the original expansion site and the name of the macro
186                     // so we can print a useful error message if the parse of the expanded
187                     // macro leaves unparsed tokens.
188                     site_span: sp,
189                     macro_ident: name,
190                     arm_span,
191                 })
192             }
193             Failure(sp, tok, t) => if sp.lo() >= best_fail_spot.lo() {
194                 best_fail_spot = sp;
195                 best_fail_tok = Some(tok);
196                 best_fail_text = Some(t);
197             },
198             Error(err_sp, ref msg) => {
199                 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
200             }
201         }
202     }
203
204     let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
205     let span = best_fail_spot.substitute_dummy(sp);
206     let mut err = cx.struct_span_err(span, &best_fail_msg);
207     err.span_label(span, best_fail_text.unwrap_or(&best_fail_msg));
208     if let Some(sp) = def_span {
209         if cx.source_map().span_to_filename(sp).is_real() && !sp.is_dummy() {
210             err.span_label(cx.source_map().def_span(sp), "when calling this macro");
211         }
212     }
213
214     // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
215     if let Some((arg, comma_span)) = arg.add_comma() {
216         for lhs in lhses { // try each arm's matchers
217             let lhs_tt = match *lhs {
218                 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
219                 _ => continue,
220             };
221             match TokenTree::parse(cx, lhs_tt, arg.clone()) {
222                 Success(_) => {
223                     if comma_span.is_dummy() {
224                         err.note("you might be missing a comma");
225                     } else {
226                         err.span_suggestion_short(
227                             comma_span,
228                             "missing comma here",
229                             ", ".to_string(),
230                             Applicability::MachineApplicable,
231                         );
232                     }
233                 }
234                 _ => {}
235             }
236         }
237     }
238     err.emit();
239     cx.trace_macros_diag();
240     DummyResult::any(sp)
241 }
242
243 // Note that macro-by-example's input is also matched against a token tree:
244 //                   $( $lhs:tt => $rhs:tt );+
245 //
246 // Holy self-referential!
247
248 /// Converts a `macro_rules!` invocation into a syntax extension.
249 pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
250                -> SyntaxExtension {
251     let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
252     let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
253
254     // Parse the macro_rules! invocation
255     let body = match def.node {
256         ast::ItemKind::MacroDef(ref body) => body,
257         _ => unreachable!(),
258     };
259
260     // The pattern that macro_rules matches.
261     // The grammar for macro_rules! is:
262     // $( $lhs:tt => $rhs:tt );+
263     // ...quasiquoting this would be nice.
264     // These spans won't matter, anyways
265     let argument_gram = vec![
266         quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
267             tts: vec![
268                 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
269                 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
270                 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
271             ],
272             separator: Some(if body.legacy { token::Semi } else { token::Comma }),
273             op: quoted::KleeneOp::OneOrMore,
274             num_captures: 2,
275         })),
276         // to phase into semicolon-termination instead of semicolon-separation
277         quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
278             tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
279             separator: None,
280             op: quoted::KleeneOp::ZeroOrMore,
281             num_captures: 0
282         })),
283     ];
284
285     let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
286         Success(m) => m,
287         Failure(sp, tok, t) => {
288             let s = parse_failure_msg(tok);
289             let sp = sp.substitute_dummy(def.span);
290             let mut err = sess.span_diagnostic.struct_span_fatal(sp, &s);
291             err.span_label(sp, t);
292             err.emit();
293             FatalError.raise();
294         }
295         Error(sp, s) => {
296             sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
297         }
298     };
299
300     let mut valid = true;
301
302     // Extract the arguments:
303     let lhses = match *argument_map[&lhs_nm] {
304         MatchedSeq(ref s, _) => {
305             s.iter().map(|m| {
306                 if let MatchedNonterminal(ref nt) = *m {
307                     if let NtTT(ref tt) = **nt {
308                         let tt = quoted::parse(
309                             tt.clone().into(),
310                             true,
311                             sess,
312                             features,
313                             &def.attrs,
314                             edition,
315                             def.id,
316                         )
317                         .pop()
318                         .unwrap();
319                         valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
320                         return tt;
321                     }
322                 }
323                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
324             }).collect::<Vec<quoted::TokenTree>>()
325         }
326         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
327     };
328
329     let rhses = match *argument_map[&rhs_nm] {
330         MatchedSeq(ref s, _) => {
331             s.iter().map(|m| {
332                 if let MatchedNonterminal(ref nt) = *m {
333                     if let NtTT(ref tt) = **nt {
334                         return quoted::parse(
335                             tt.clone().into(),
336                             false,
337                             sess,
338                             features,
339                             &def.attrs,
340                             edition,
341                             def.id,
342                         ).pop()
343                          .unwrap();
344                     }
345                 }
346                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
347             }).collect::<Vec<quoted::TokenTree>>()
348         }
349         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
350     };
351
352     for rhs in &rhses {
353         valid &= check_rhs(sess, rhs);
354     }
355
356     // don't abort iteration early, so that errors for multiple lhses can be reported
357     for lhs in &lhses {
358         valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
359     }
360
361     let expander: Box<_> = Box::new(MacroRulesMacroExpander {
362         name: def.ident,
363         lhses,
364         rhses,
365         valid,
366     });
367
368     if body.legacy {
369         let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
370         let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
371         let mut local_inner_macros = false;
372         if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
373             if let Some(l) = macro_export.meta_item_list() {
374                 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
375             }
376         }
377
378         let unstable_feature = attr::find_stability(&sess,
379                                                     &def.attrs, def.span).and_then(|stability| {
380             if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
381                 Some((stability.feature, issue))
382             } else {
383                 None
384             }
385         });
386
387         NormalTT {
388             expander,
389             def_info: Some((def.id, def.span)),
390             allow_internal_unstable,
391             allow_internal_unsafe,
392             local_inner_macros,
393             unstable_feature,
394             edition,
395         }
396     } else {
397         let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
398
399         SyntaxExtension::DeclMacro {
400             expander,
401             def_info: Some((def.id, def.span)),
402             is_transparent,
403             edition,
404         }
405     }
406 }
407
408 fn check_lhs_nt_follows(sess: &ParseSess,
409                         features: &Features,
410                         attrs: &[ast::Attribute],
411                         lhs: &quoted::TokenTree) -> bool {
412     // lhs is going to be like TokenTree::Delimited(...), where the
413     // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
414     if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
415         check_matcher(sess, features, attrs, &tts.tts)
416     } else {
417         let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
418         sess.span_diagnostic.span_err(lhs.span(), msg);
419         false
420     }
421     // we don't abort on errors on rejection, the driver will do that for us
422     // after parsing/expansion. we can report every error in every macro this way.
423 }
424
425 /// Check that the lhs contains no repetition which could match an empty token
426 /// tree, because then the matcher would hang indefinitely.
427 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
428     use quoted::TokenTree;
429     for tt in tts {
430         match *tt {
431             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
432             TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
433                 return false;
434             },
435             TokenTree::Sequence(span, ref seq) => {
436                 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
437                     match *seq_tt {
438                         TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
439                         TokenTree::Sequence(_, ref sub_seq) =>
440                             sub_seq.op == quoted::KleeneOp::ZeroOrMore
441                             || sub_seq.op == quoted::KleeneOp::ZeroOrOne,
442                         _ => false,
443                     }
444                 }) {
445                     let sp = span.entire();
446                     sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
447                     return false;
448                 }
449                 if !check_lhs_no_empty_seq(sess, &seq.tts) {
450                     return false;
451                 }
452             }
453         }
454     }
455
456     true
457 }
458
459 fn check_rhs(sess: &ParseSess, rhs: &quoted::TokenTree) -> bool {
460     match *rhs {
461         quoted::TokenTree::Delimited(..) => return true,
462         _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
463     }
464     false
465 }
466
467 fn check_matcher(sess: &ParseSess,
468                  features: &Features,
469                  attrs: &[ast::Attribute],
470                  matcher: &[quoted::TokenTree]) -> bool {
471     let first_sets = FirstSets::new(matcher);
472     let empty_suffix = TokenSet::empty();
473     let err = sess.span_diagnostic.err_count();
474     check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
475     err == sess.span_diagnostic.err_count()
476 }
477
478 // `The FirstSets` for a matcher is a mapping from subsequences in the
479 // matcher to the FIRST set for that subsequence.
480 //
481 // This mapping is partially precomputed via a backwards scan over the
482 // token trees of the matcher, which provides a mapping from each
483 // repetition sequence to its *first* set.
484 //
485 // (Hypothetically, sequences should be uniquely identifiable via their
486 // spans, though perhaps that is false, e.g., for macro-generated macros
487 // that do not try to inject artificial span information. My plan is
488 // to try to catch such cases ahead of time and not include them in
489 // the precomputed mapping.)
490 struct FirstSets {
491     // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
492     // span in the original matcher to the First set for the inner sequence `tt ...`.
493     //
494     // If two sequences have the same span in a matcher, then map that
495     // span to None (invalidating the mapping here and forcing the code to
496     // use a slow path).
497     first: FxHashMap<Span, Option<TokenSet>>,
498 }
499
500 impl FirstSets {
501     fn new(tts: &[quoted::TokenTree]) -> FirstSets {
502         use quoted::TokenTree;
503
504         let mut sets = FirstSets { first: FxHashMap::default() };
505         build_recur(&mut sets, tts);
506         return sets;
507
508         // walks backward over `tts`, returning the FIRST for `tts`
509         // and updating `sets` at the same time for all sequence
510         // substructure we find within `tts`.
511         fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
512             let mut first = TokenSet::empty();
513             for tt in tts.iter().rev() {
514                 match *tt {
515                     TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
516                         first.replace_with(tt.clone());
517                     }
518                     TokenTree::Delimited(span, ref delimited) => {
519                         build_recur(sets, &delimited.tts[..]);
520                         first.replace_with(delimited.open_tt(span.open));
521                     }
522                     TokenTree::Sequence(sp, ref seq_rep) => {
523                         let subfirst = build_recur(sets, &seq_rep.tts[..]);
524
525                         match sets.first.entry(sp.entire()) {
526                             Entry::Vacant(vac) => {
527                                 vac.insert(Some(subfirst.clone()));
528                             }
529                             Entry::Occupied(mut occ) => {
530                                 // if there is already an entry, then a span must have collided.
531                                 // This should not happen with typical macro_rules macros,
532                                 // but syntax extensions need not maintain distinct spans,
533                                 // so distinct syntax trees can be assigned the same span.
534                                 // In such a case, the map cannot be trusted; so mark this
535                                 // entry as unusable.
536                                 occ.insert(None);
537                             }
538                         }
539
540                         // If the sequence contents can be empty, then the first
541                         // token could be the separator token itself.
542
543                         if let (Some(ref sep), true) = (seq_rep.separator.clone(),
544                                                         subfirst.maybe_empty) {
545                             first.add_one_maybe(TokenTree::Token(sp.entire(), sep.clone()));
546                         }
547
548                         // Reverse scan: Sequence comes before `first`.
549                         if subfirst.maybe_empty
550                            || seq_rep.op == quoted::KleeneOp::ZeroOrMore
551                            || seq_rep.op == quoted::KleeneOp::ZeroOrOne
552                         {
553                             // If sequence is potentially empty, then
554                             // union them (preserving first emptiness).
555                             first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
556                         } else {
557                             // Otherwise, sequence guaranteed
558                             // non-empty; replace first.
559                             first = subfirst;
560                         }
561                     }
562                 }
563             }
564
565             first
566         }
567     }
568
569     // walks forward over `tts` until all potential FIRST tokens are
570     // identified.
571     fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
572         use quoted::TokenTree;
573
574         let mut first = TokenSet::empty();
575         for tt in tts.iter() {
576             assert!(first.maybe_empty);
577             match *tt {
578                 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
579                     first.add_one(tt.clone());
580                     return first;
581                 }
582                 TokenTree::Delimited(span, ref delimited) => {
583                     first.add_one(delimited.open_tt(span.open));
584                     return first;
585                 }
586                 TokenTree::Sequence(sp, ref seq_rep) => {
587                     match self.first.get(&sp.entire()) {
588                         Some(&Some(ref subfirst)) => {
589
590                             // If the sequence contents can be empty, then the first
591                             // token could be the separator token itself.
592
593                             if let (Some(ref sep), true) = (seq_rep.separator.clone(),
594                                                             subfirst.maybe_empty) {
595                                 first.add_one_maybe(TokenTree::Token(sp.entire(), sep.clone()));
596                             }
597
598                             assert!(first.maybe_empty);
599                             first.add_all(subfirst);
600                             if subfirst.maybe_empty
601                                || seq_rep.op == quoted::KleeneOp::ZeroOrMore
602                                || seq_rep.op == quoted::KleeneOp::ZeroOrOne
603                             {
604                                 // continue scanning for more first
605                                 // tokens, but also make sure we
606                                 // restore empty-tracking state
607                                 first.maybe_empty = true;
608                                 continue;
609                             } else {
610                                 return first;
611                             }
612                         }
613
614                         Some(&None) => {
615                             panic!("assume all sequences have (unique) spans for now");
616                         }
617
618                         None => {
619                             panic!("We missed a sequence during FirstSets construction");
620                         }
621                     }
622                 }
623             }
624         }
625
626         // we only exit the loop if `tts` was empty or if every
627         // element of `tts` matches the empty sequence.
628         assert!(first.maybe_empty);
629         first
630     }
631 }
632
633 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
634 // (for macro-by-example syntactic variables). It also carries the
635 // `maybe_empty` flag; that is true if and only if the matcher can
636 // match an empty token sequence.
637 //
638 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
639 // which has corresponding FIRST = {$a:expr, c, d}.
640 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
641 //
642 // (Notably, we must allow for *-op to occur zero times.)
643 #[derive(Clone, Debug)]
644 struct TokenSet {
645     tokens: Vec<quoted::TokenTree>,
646     maybe_empty: bool,
647 }
648
649 impl TokenSet {
650     // Returns a set for the empty sequence.
651     fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
652
653     // Returns the set `{ tok }` for the single-token (and thus
654     // non-empty) sequence [tok].
655     fn singleton(tok: quoted::TokenTree) -> Self {
656         TokenSet { tokens: vec![tok], maybe_empty: false }
657     }
658
659     // Changes self to be the set `{ tok }`.
660     // Since `tok` is always present, marks self as non-empty.
661     fn replace_with(&mut self, tok: quoted::TokenTree) {
662         self.tokens.clear();
663         self.tokens.push(tok);
664         self.maybe_empty = false;
665     }
666
667     // Changes self to be the empty set `{}`; meant for use when
668     // the particular token does not matter, but we want to
669     // record that it occurs.
670     fn replace_with_irrelevant(&mut self) {
671         self.tokens.clear();
672         self.maybe_empty = false;
673     }
674
675     // Adds `tok` to the set for `self`, marking sequence as non-empy.
676     fn add_one(&mut self, tok: quoted::TokenTree) {
677         if !self.tokens.contains(&tok) {
678             self.tokens.push(tok);
679         }
680         self.maybe_empty = false;
681     }
682
683     // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
684     fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
685         if !self.tokens.contains(&tok) {
686             self.tokens.push(tok);
687         }
688     }
689
690     // Adds all elements of `other` to this.
691     //
692     // (Since this is a set, we filter out duplicates.)
693     //
694     // If `other` is potentially empty, then preserves the previous
695     // setting of the empty flag of `self`. If `other` is guaranteed
696     // non-empty, then `self` is marked non-empty.
697     fn add_all(&mut self, other: &Self) {
698         for tok in &other.tokens {
699             if !self.tokens.contains(tok) {
700                 self.tokens.push(tok.clone());
701             }
702         }
703         if !other.maybe_empty {
704             self.maybe_empty = false;
705         }
706     }
707 }
708
709 // Checks that `matcher` is internally consistent and that it
710 // can legally by followed by a token N, for all N in `follow`.
711 // (If `follow` is empty, then it imposes no constraint on
712 // the `matcher`.)
713 //
714 // Returns the set of NT tokens that could possibly come last in
715 // `matcher`. (If `matcher` matches the empty sequence, then
716 // `maybe_empty` will be set to true.)
717 //
718 // Requires that `first_sets` is pre-computed for `matcher`;
719 // see `FirstSets::new`.
720 fn check_matcher_core(sess: &ParseSess,
721                       features: &Features,
722                       attrs: &[ast::Attribute],
723                       first_sets: &FirstSets,
724                       matcher: &[quoted::TokenTree],
725                       follow: &TokenSet) -> TokenSet {
726     use quoted::TokenTree;
727
728     let mut last = TokenSet::empty();
729
730     // 2. For each token and suffix  [T, SUFFIX] in M:
731     // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
732     // then ensure T can also be followed by any element of FOLLOW.
733     'each_token: for i in 0..matcher.len() {
734         let token = &matcher[i];
735         let suffix = &matcher[i+1..];
736
737         let build_suffix_first = || {
738             let mut s = first_sets.first(suffix);
739             if s.maybe_empty { s.add_all(follow); }
740             s
741         };
742
743         // (we build `suffix_first` on demand below; you can tell
744         // which cases are supposed to fall through by looking for the
745         // initialization of this variable.)
746         let suffix_first;
747
748         // First, update `last` so that it corresponds to the set
749         // of NT tokens that might end the sequence `... token`.
750         match *token {
751             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
752                 let can_be_followed_by_any;
753                 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
754                     let msg = format!("invalid fragment specifier `{}`", bad_frag);
755                     sess.span_diagnostic.struct_span_err(token.span(), &msg)
756                         .help(VALID_FRAGMENT_NAMES_MSG)
757                         .emit();
758                     // (This eliminates false positives and duplicates
759                     // from error messages.)
760                     can_be_followed_by_any = true;
761                 } else {
762                     can_be_followed_by_any = token_can_be_followed_by_any(token);
763                 }
764
765                 if can_be_followed_by_any {
766                     // don't need to track tokens that work with any,
767                     last.replace_with_irrelevant();
768                     // ... and don't need to check tokens that can be
769                     // followed by anything against SUFFIX.
770                     continue 'each_token;
771                 } else {
772                     last.replace_with(token.clone());
773                     suffix_first = build_suffix_first();
774                 }
775             }
776             TokenTree::Delimited(span, ref d) => {
777                 let my_suffix = TokenSet::singleton(d.close_tt(span.close));
778                 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
779                 // don't track non NT tokens
780                 last.replace_with_irrelevant();
781
782                 // also, we don't need to check delimited sequences
783                 // against SUFFIX
784                 continue 'each_token;
785             }
786             TokenTree::Sequence(sp, ref seq_rep) => {
787                 suffix_first = build_suffix_first();
788                 // The trick here: when we check the interior, we want
789                 // to include the separator (if any) as a potential
790                 // (but not guaranteed) element of FOLLOW. So in that
791                 // case, we make a temp copy of suffix and stuff
792                 // delimiter in there.
793                 //
794                 // FIXME: Should I first scan suffix_first to see if
795                 // delimiter is already in it before I go through the
796                 // work of cloning it? But then again, this way I may
797                 // get a "tighter" span?
798                 let mut new;
799                 let my_suffix = if let Some(ref u) = seq_rep.separator {
800                     new = suffix_first.clone();
801                     new.add_one_maybe(TokenTree::Token(sp.entire(), u.clone()));
802                     &new
803                 } else {
804                     &suffix_first
805                 };
806
807                 // At this point, `suffix_first` is built, and
808                 // `my_suffix` is some TokenSet that we can use
809                 // for checking the interior of `seq_rep`.
810                 let next = check_matcher_core(sess,
811                                               features,
812                                               attrs,
813                                               first_sets,
814                                               &seq_rep.tts,
815                                               my_suffix);
816                 if next.maybe_empty {
817                     last.add_all(&next);
818                 } else {
819                     last = next;
820                 }
821
822                 // the recursive call to check_matcher_core already ran the 'each_last
823                 // check below, so we can just keep going forward here.
824                 continue 'each_token;
825             }
826         }
827
828         // (`suffix_first` guaranteed initialized once reaching here.)
829
830         // Now `last` holds the complete set of NT tokens that could
831         // end the sequence before SUFFIX. Check that every one works with `suffix`.
832         'each_last: for token in &last.tokens {
833             if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
834                 for next_token in &suffix_first.tokens {
835                     match is_in_follow(next_token, &frag_spec.as_str()) {
836                         IsInFollow::Invalid(msg, help) => {
837                             sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
838                                 .help(help).emit();
839                             // don't bother reporting every source of
840                             // conflict for a particular element of `last`.
841                             continue 'each_last;
842                         }
843                         IsInFollow::Yes => {}
844                         IsInFollow::No(ref possible) => {
845                             let may_be = if last.tokens.len() == 1 &&
846                                 suffix_first.tokens.len() == 1
847                             {
848                                 "is"
849                             } else {
850                                 "may be"
851                             };
852
853                             let sp = next_token.span();
854                             let mut err = sess.span_diagnostic.struct_span_err(
855                                 sp,
856                                 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
857                                           is not allowed for `{frag}` fragments",
858                                          name=name,
859                                          frag=frag_spec,
860                                          next=quoted_tt_to_string(next_token),
861                                          may_be=may_be),
862                             );
863                             err.span_label(
864                                 sp,
865                                 format!("not allowed after `{}` fragments", frag_spec),
866                             );
867                             let msg = "allowed there are: ";
868                             match &possible[..] {
869                                 &[] => {}
870                                 &[t] => {
871                                     err.note(&format!(
872                                         "only {} is allowed after `{}` fragments",
873                                         t,
874                                         frag_spec,
875                                     ));
876                                 }
877                                 ts => {
878                                     err.note(&format!(
879                                         "{}{} or {}",
880                                         msg,
881                                         ts[..ts.len() - 1].iter().map(|s| *s)
882                                             .collect::<Vec<_>>().join(", "),
883                                         ts[ts.len() - 1],
884                                     ));
885                                 }
886                             }
887                             err.emit();
888                         }
889                     }
890                 }
891             }
892         }
893     }
894     last
895 }
896
897 fn token_can_be_followed_by_any(tok: &quoted::TokenTree) -> bool {
898     if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
899         frag_can_be_followed_by_any(&frag_spec.as_str())
900     } else {
901         // (Non NT's can always be followed by anthing in matchers.)
902         true
903     }
904 }
905
906 /// True if a fragment of type `frag` can be followed by any sort of
907 /// token.  We use this (among other things) as a useful approximation
908 /// for when `frag` can be followed by a repetition like `$(...)*` or
909 /// `$(...)+`. In general, these can be a bit tricky to reason about,
910 /// so we adopt a conservative position that says that any fragment
911 /// specifier which consumes at most one token tree can be followed by
912 /// a fragment specifier (indeed, these fragments can be followed by
913 /// ANYTHING without fear of future compatibility hazards).
914 fn frag_can_be_followed_by_any(frag: &str) -> bool {
915     match frag {
916         "item"     | // always terminated by `}` or `;`
917         "block"    | // exactly one token tree
918         "ident"    | // exactly one token tree
919         "literal"  | // exactly one token tree
920         "meta"     | // exactly one token tree
921         "lifetime" | // exactly one token tree
922         "tt" =>   // exactly one token tree
923             true,
924
925         _ =>
926             false,
927     }
928 }
929
930 enum IsInFollow {
931     Yes,
932     No(Vec<&'static str>),
933     Invalid(String, &'static str),
934 }
935
936 /// True if `frag` can legally be followed by the token `tok`. For
937 /// fragments that can consume an unbounded number of tokens, `tok`
938 /// must be within a well-defined follow set. This is intended to
939 /// guarantee future compatibility: for example, without this rule, if
940 /// we expanded `expr` to include a new binary operator, we might
941 /// break macros that were relying on that binary operator as a
942 /// separator.
943 // when changing this do not forget to update doc/book/macros.md!
944 fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> IsInFollow {
945     use quoted::TokenTree;
946
947     if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
948         // closing a token tree can never be matched by any fragment;
949         // iow, we always require that `(` and `)` match, etc.
950         IsInFollow::Yes
951     } else {
952         match frag {
953             "item" => {
954                 // since items *must* be followed by either a `;` or a `}`, we can
955                 // accept anything after them
956                 IsInFollow::Yes
957             },
958             "block" => {
959                 // anything can follow block, the braces provide an easy boundary to
960                 // maintain
961                 IsInFollow::Yes
962             },
963             "stmt" | "expr"  => {
964                 let tokens = vec!["`=>`", "`,`", "`;`"];
965                 match *tok {
966                     TokenTree::Token(_, ref tok) => match *tok {
967                         FatArrow | Comma | Semi => IsInFollow::Yes,
968                         _ => IsInFollow::No(tokens),
969                     },
970                     _ => IsInFollow::No(tokens),
971                 }
972             },
973             "pat" => {
974                 let tokens = vec!["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
975                 match *tok {
976                     TokenTree::Token(_, ref tok) => match *tok {
977                         FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
978                         Ident(i, false) if i.name == "if" || i.name == "in" => IsInFollow::Yes,
979                         _ => IsInFollow::No(tokens),
980                     },
981                     _ => IsInFollow::No(tokens),
982                 }
983             },
984             "path" | "ty" => {
985                 let tokens = vec![
986                     "`{`", "`[`", "`=>`", "`,`", "`>`","`=`", "`:`", "`;`", "`|`", "`as`",
987                     "`where`",
988                 ];
989                 match *tok {
990                     TokenTree::Token(_, ref tok) => match *tok {
991                         OpenDelim(token::DelimToken::Brace) |
992                         OpenDelim(token::DelimToken::Bracket) |
993                         Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi |
994                         BinOp(token::Or) => IsInFollow::Yes,
995                         Ident(i, false) if i.name == "as" || i.name == "where" => IsInFollow::Yes,
996                         _ => IsInFollow::No(tokens),
997                     },
998                     TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => IsInFollow::Yes,
999                     _ => IsInFollow::No(tokens),
1000                 }
1001             },
1002             "ident" | "lifetime" => {
1003                 // being a single token, idents and lifetimes are harmless
1004                 IsInFollow::Yes
1005             },
1006             "literal" => {
1007                 // literals may be of a single token, or two tokens (negative numbers)
1008                 IsInFollow::Yes
1009             },
1010             "meta" | "tt" => {
1011                 // being either a single token or a delimited sequence, tt is
1012                 // harmless
1013                 IsInFollow::Yes
1014             },
1015             "vis" => {
1016                 // Explicitly disallow `priv`, on the off chance it comes back.
1017                 let tokens = vec!["`,`", "an ident", "a type"];
1018                 match *tok {
1019                     TokenTree::Token(_, ref tok) => match *tok {
1020                         Comma => IsInFollow::Yes,
1021                         Ident(i, is_raw) if is_raw || i.name != "priv" => IsInFollow::Yes,
1022                         ref tok => if tok.can_begin_type() {
1023                             IsInFollow::Yes
1024                         } else {
1025                             IsInFollow::No(tokens)
1026                         }
1027                     },
1028                     TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
1029                                                        || frag.name == "ty"
1030                                                        || frag.name == "path" => IsInFollow::Yes,
1031                     _ => IsInFollow::No(tokens),
1032                 }
1033             },
1034             "" => IsInFollow::Yes, // keywords::Invalid
1035             _ => IsInFollow::Invalid(format!("invalid fragment specifier `{}`", frag),
1036                                      VALID_FRAGMENT_NAMES_MSG),
1037         }
1038     }
1039 }
1040
1041 fn has_legal_fragment_specifier(sess: &ParseSess,
1042                                 features: &Features,
1043                                 attrs: &[ast::Attribute],
1044                                 tok: &quoted::TokenTree) -> Result<(), String> {
1045     debug!("has_legal_fragment_specifier({:?})", tok);
1046     if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
1047         let frag_name = frag_spec.as_str();
1048         let frag_span = tok.span();
1049         if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
1050             return Err(frag_name.to_string());
1051         }
1052     }
1053     Ok(())
1054 }
1055
1056 fn is_legal_fragment_specifier(_sess: &ParseSess,
1057                                _features: &Features,
1058                                _attrs: &[ast::Attribute],
1059                                frag_name: &str,
1060                                _frag_span: Span) -> bool {
1061     /*
1062      * If new fragment specifiers are invented in nightly, `_sess`,
1063      * `_features`, `_attrs`, and `_frag_span` will be useful here
1064      * for checking against feature gates. See past versions of
1065      * this function.
1066      */
1067     match frag_name {
1068         "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
1069         "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" |
1070         "" => true,
1071         _ => false,
1072     }
1073 }
1074
1075 fn quoted_tt_to_string(tt: &quoted::TokenTree) -> String {
1076     match *tt {
1077         quoted::TokenTree::Token(_, ref tok) => crate::print::pprust::token_to_string(tok),
1078         quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1079         quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1080         _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1081                      in follow set checker"),
1082     }
1083 }