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