]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_parser.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[rust.git] / src / libsyntax / ext / tt / macro_parser.rs
1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This is an NFA-based parser, which calls out to the main rust parser for named nonterminals
12 //! (which it commits to fully when it hits one in a grammar). There's a set of current NFA threads
13 //! and a set of next ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
14 //! pathological cases, is worse than traditional use of NFA or Earley parsing, but it's an easier
15 //! fit for Macro-by-Example-style rules.
16 //!
17 //! (In order to prevent the pathological case, we'd need to lazily construct the resulting
18 //! `NamedMatch`es at the very end. It'd be a pain, and require more memory to keep around old
19 //! items, but it would also save overhead)
20 //!
21 //! We don't say this parser uses the Earley algorithm, because it's unnecessarily innacurate.
22 //! The macro parser restricts itself to the features of finite state automata. Earley parsers
23 //! can be described as an extension of NFAs with completion rules, prediction rules, and recursion.
24 //!
25 //! Quick intro to how the parser works:
26 //!
27 //! A 'position' is a dot in the middle of a matcher, usually represented as a
28 //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
29 //!
30 //! The parser walks through the input a character at a time, maintaining a list
31 //! of threads consistent with the current position in the input string: `cur_items`.
32 //!
33 //! As it processes them, it fills up `eof_items` with threads that would be valid if
34 //! the macro invocation is now over, `bb_items` with threads that are waiting on
35 //! a Rust nonterminal like `$e:expr`, and `next_items` with threads that are waiting
36 //! on a particular token. Most of the logic concerns moving the · through the
37 //! repetitions indicated by Kleene stars. The rules for moving the · without
38 //! consuming any input are called epsilon transitions. It only advances or calls
39 //! out to the real Rust parser when no `cur_items` threads remain.
40 //!
41 //! Example:
42 //!
43 //! ```text, ignore
44 //! Start parsing a a a a b against [· a $( a )* a b].
45 //!
46 //! Remaining input: a a a a b
47 //! next: [· a $( a )* a b]
48 //!
49 //! - - - Advance over an a. - - -
50 //!
51 //! Remaining input: a a a b
52 //! cur: [a · $( a )* a b]
53 //! Descend/Skip (first item).
54 //! next: [a $( · a )* a b]  [a $( a )* · a b].
55 //!
56 //! - - - Advance over an a. - - -
57 //!
58 //! Remaining input: a a b
59 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
60 //! Follow epsilon transition: Finish/Repeat (first item)
61 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
62 //!
63 //! - - - Advance over an a. - - - (this looks exactly like the last step)
64 //!
65 //! Remaining input: a b
66 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
67 //! Follow epsilon transition: Finish/Repeat (first item)
68 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
69 //!
70 //! - - - Advance over an a. - - - (this looks exactly like the last step)
71 //!
72 //! Remaining input: b
73 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
74 //! Follow epsilon transition: Finish/Repeat (first item)
75 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
76 //!
77 //! - - - Advance over a b. - - -
78 //!
79 //! Remaining input: ''
80 //! eof: [a $( a )* a b ·]
81 //! ```
82
83 pub use self::NamedMatch::*;
84 pub use self::ParseResult::*;
85 use self::TokenTreeOrTokenTreeVec::*;
86
87 use ast::Ident;
88 use syntax_pos::{self, BytePos, Span};
89 use codemap::Spanned;
90 use errors::FatalError;
91 use ext::tt::quoted::{self, TokenTree};
92 use parse::{Directory, ParseSess};
93 use parse::parser::{PathStyle, Parser};
94 use parse::token::{self, DocComment, Token, Nonterminal};
95 use print::pprust;
96 use symbol::keywords;
97 use tokenstream::TokenStream;
98 use util::small_vector::SmallVector;
99
100 use std::mem;
101 use std::rc::Rc;
102 use std::collections::HashMap;
103 use std::collections::hash_map::Entry::{Vacant, Occupied};
104
105 // To avoid costly uniqueness checks, we require that `MatchSeq` always has
106 // a nonempty body.
107
108 #[derive(Clone)]
109 enum TokenTreeOrTokenTreeVec {
110     Tt(TokenTree),
111     TtSeq(Vec<TokenTree>),
112 }
113
114 impl TokenTreeOrTokenTreeVec {
115     fn len(&self) -> usize {
116         match *self {
117             TtSeq(ref v) => v.len(),
118             Tt(ref tt) => tt.len(),
119         }
120     }
121
122     fn get_tt(&self, index: usize) -> TokenTree {
123         match *self {
124             TtSeq(ref v) => v[index].clone(),
125             Tt(ref tt) => tt.get_tt(index),
126         }
127     }
128 }
129
130 /// an unzipping of `TokenTree`s
131 #[derive(Clone)]
132 struct MatcherTtFrame {
133     elts: TokenTreeOrTokenTreeVec,
134     idx: usize,
135 }
136
137 #[derive(Clone)]
138 struct MatcherPos {
139     stack: Vec<MatcherTtFrame>,
140     top_elts: TokenTreeOrTokenTreeVec,
141     sep: Option<Token>,
142     idx: usize,
143     up: Option<Box<MatcherPos>>,
144     matches: Vec<Rc<Vec<NamedMatch>>>,
145     match_lo: usize,
146     match_cur: usize,
147     match_hi: usize,
148     sp_lo: BytePos,
149 }
150
151 impl MatcherPos {
152     fn push_match(&mut self, idx: usize, m: NamedMatch) {
153         let matches = Rc::make_mut(&mut self.matches[idx]);
154         matches.push(m);
155     }
156 }
157
158 pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
159
160 pub fn count_names(ms: &[TokenTree]) -> usize {
161     ms.iter().fold(0, |count, elt| {
162         count + match *elt {
163             TokenTree::Sequence(_, ref seq) => seq.num_captures,
164             TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
165             TokenTree::MetaVar(..) => 0,
166             TokenTree::MetaVarDecl(..) => 1,
167             TokenTree::Token(..) => 0,
168         }
169     })
170 }
171
172 fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
173     let match_idx_hi = count_names(&ms[..]);
174     let matches = create_matches(match_idx_hi);
175     Box::new(MatcherPos {
176         stack: vec![],
177         top_elts: TtSeq(ms),
178         sep: None,
179         idx: 0,
180         up: None,
181         matches: matches,
182         match_lo: 0,
183         match_cur: 0,
184         match_hi: match_idx_hi,
185         sp_lo: lo
186     })
187 }
188
189 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
190 /// so it is associated with a single ident in a parse, and all
191 /// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
192 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
193 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
194 ///
195 /// The in-memory structure of a particular `NamedMatch` represents the match
196 /// that occurred when a particular subset of a matcher was applied to a
197 /// particular token tree.
198 ///
199 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
200 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
201 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
202 /// token tree. The depth of the `NamedMatch` structure will therefore depend
203 /// only on the nesting depth of `ast::TTSeq`s in the originating
204 /// token tree it was derived from.
205
206 #[derive(Debug, Clone)]
207 pub enum NamedMatch {
208     MatchedSeq(Rc<Vec<NamedMatch>>, syntax_pos::Span),
209     MatchedNonterminal(Rc<Nonterminal>)
210 }
211
212 fn nameize<I: Iterator<Item=NamedMatch>>(sess: &ParseSess, ms: &[TokenTree], mut res: I)
213                                              -> NamedParseResult {
214     fn n_rec<I: Iterator<Item=NamedMatch>>(sess: &ParseSess, m: &TokenTree, res: &mut I,
215              ret_val: &mut HashMap<Ident, Rc<NamedMatch>>)
216              -> Result<(), (syntax_pos::Span, String)> {
217         match *m {
218             TokenTree::Sequence(_, ref seq) => {
219                 for next_m in &seq.tts {
220                     n_rec(sess, next_m, res.by_ref(), ret_val)?
221                 }
222             }
223             TokenTree::Delimited(_, ref delim) => {
224                 for next_m in &delim.tts {
225                     n_rec(sess, next_m, res.by_ref(), ret_val)?;
226                 }
227             }
228             TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
229                 if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
230                     return Err((span, "missing fragment specifier".to_string()));
231                 }
232             }
233             TokenTree::MetaVarDecl(sp, bind_name, _) => {
234                 match ret_val.entry(bind_name) {
235                     Vacant(spot) => {
236                         // FIXME(simulacrum): Don't construct Rc here
237                         spot.insert(Rc::new(res.next().unwrap()));
238                     }
239                     Occupied(..) => {
240                         return Err((sp, format!("duplicated bind name: {}", bind_name)))
241                     }
242                 }
243             }
244             TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
245         }
246
247         Ok(())
248     }
249
250     let mut ret_val = HashMap::new();
251     for m in ms {
252         match n_rec(sess, m, res.by_ref(), &mut ret_val) {
253             Ok(_) => {},
254             Err((sp, msg)) => return Error(sp, msg),
255         }
256     }
257
258     Success(ret_val)
259 }
260
261 pub enum ParseResult<T> {
262     Success(T),
263     /// Arm failed to match. If the second parameter is `token::Eof`, it
264     /// indicates an unexpected end of macro invocation. Otherwise, it
265     /// indicates that no rules expected the given token.
266     Failure(syntax_pos::Span, Token),
267     /// Fatal error (malformed macro?). Abort compilation.
268     Error(syntax_pos::Span, String)
269 }
270
271 pub fn parse_failure_msg(tok: Token) -> String {
272     match tok {
273         token::Eof => "unexpected end of macro invocation".to_string(),
274         _ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)),
275     }
276 }
277
278 /// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
279 fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
280     if let (Some(id1), Some(id2)) = (t1.ident(), t2.ident()) {
281         id1.name == id2.name
282     } else if let (&token::Lifetime(id1), &token::Lifetime(id2)) = (t1, t2) {
283         id1.name == id2.name
284     } else {
285         *t1 == *t2
286     }
287 }
288
289 fn create_matches(len: usize) -> Vec<Rc<Vec<NamedMatch>>> {
290     (0..len).into_iter().map(|_| Rc::new(Vec::new())).collect()
291 }
292
293 fn inner_parse_loop(sess: &ParseSess,
294                     cur_items: &mut SmallVector<Box<MatcherPos>>,
295                     next_items: &mut Vec<Box<MatcherPos>>,
296                     eof_items: &mut SmallVector<Box<MatcherPos>>,
297                     bb_items: &mut SmallVector<Box<MatcherPos>>,
298                     token: &Token,
299                     span: syntax_pos::Span)
300                     -> ParseResult<()> {
301     while let Some(mut item) = cur_items.pop() {
302         // When unzipped trees end, remove them
303         while item.idx >= item.top_elts.len() {
304             match item.stack.pop() {
305                 Some(MatcherTtFrame { elts, idx }) => {
306                     item.top_elts = elts;
307                     item.idx = idx + 1;
308                 }
309                 None => break
310             }
311         }
312
313         let idx = item.idx;
314         let len = item.top_elts.len();
315
316         // at end of sequence
317         if idx >= len {
318             // We are repeating iff there is a parent
319             if item.up.is_some() {
320                 // Disregarding the separator, add the "up" case to the tokens that should be
321                 // examined.
322                 // (remove this condition to make trailing seps ok)
323                 if idx == len {
324                     let mut new_pos = item.up.clone().unwrap();
325
326                     // update matches (the MBE "parse tree") by appending
327                     // each tree as a subtree.
328
329                     // Only touch the binders we have actually bound
330                     for idx in item.match_lo..item.match_hi {
331                         let sub = item.matches[idx].clone();
332                         new_pos.push_match(idx, MatchedSeq(sub, Span { lo: item.sp_lo, ..span }));
333                     }
334
335                     new_pos.match_cur = item.match_hi;
336                     new_pos.idx += 1;
337                     cur_items.push(new_pos);
338                 }
339
340                 // Check if we need a separator
341                 if idx == len && item.sep.is_some() {
342                     // We have a separator, and it is the current token.
343                     if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
344                         item.idx += 1;
345                         next_items.push(item);
346                     }
347                 } else { // we don't need a separator
348                     item.match_cur = item.match_lo;
349                     item.idx = 0;
350                     cur_items.push(item);
351                 }
352             } else {
353                 // We aren't repeating, so we must be potentially at the end of the input.
354                 eof_items.push(item);
355             }
356         } else {
357             match item.top_elts.get_tt(idx) {
358                 /* need to descend into sequence */
359                 TokenTree::Sequence(sp, seq) => {
360                     if seq.op == quoted::KleeneOp::ZeroOrMore {
361                         // Examine the case where there are 0 matches of this sequence
362                         let mut new_item = item.clone();
363                         new_item.match_cur += seq.num_captures;
364                         new_item.idx += 1;
365                         for idx in item.match_cur..item.match_cur + seq.num_captures {
366                             new_item.push_match(idx, MatchedSeq(Rc::new(vec![]), sp));
367                         }
368                         cur_items.push(new_item);
369                     }
370
371                     // Examine the case where there is at least one match of this sequence
372                     let matches = create_matches(item.matches.len());
373                     cur_items.push(Box::new(MatcherPos {
374                         stack: vec![],
375                         sep: seq.separator.clone(),
376                         idx: 0,
377                         matches: matches,
378                         match_lo: item.match_cur,
379                         match_cur: item.match_cur,
380                         match_hi: item.match_cur + seq.num_captures,
381                         up: Some(item),
382                         sp_lo: sp.lo,
383                         top_elts: Tt(TokenTree::Sequence(sp, seq)),
384                     }));
385                 }
386                 TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
387                     if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
388                         return Error(span, "missing fragment specifier".to_string());
389                     }
390                 }
391                 TokenTree::MetaVarDecl(_, _, id) => {
392                     // Built-in nonterminals never start with these tokens,
393                     // so we can eliminate them from consideration.
394                     if may_begin_with(&*id.name.as_str(), token) {
395                         bb_items.push(item);
396                     }
397                 }
398                 seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
399                     let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
400                     let idx = item.idx;
401                     item.stack.push(MatcherTtFrame {
402                         elts: lower_elts,
403                         idx: idx,
404                     });
405                     item.idx = 0;
406                     cur_items.push(item);
407                 }
408                 TokenTree::Token(_, ref t) if token_name_eq(t, token) => {
409                     item.idx += 1;
410                     next_items.push(item);
411                 }
412                 TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
413             }
414         }
415     }
416
417     Success(())
418 }
419
420 pub fn parse(sess: &ParseSess,
421              tts: TokenStream,
422              ms: &[TokenTree],
423              directory: Option<Directory>,
424              recurse_into_modules: bool)
425              -> NamedParseResult {
426     let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
427     let mut cur_items = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo));
428     let mut next_items = Vec::new(); // or proceed normally
429
430     loop {
431         let mut bb_items = SmallVector::new(); // black-box parsed by parser.rs
432         let mut eof_items = SmallVector::new();
433         assert!(next_items.is_empty());
434
435         match inner_parse_loop(sess, &mut cur_items, &mut next_items, &mut eof_items, &mut bb_items,
436                                &parser.token, parser.span) {
437             Success(_) => {},
438             Failure(sp, tok) => return Failure(sp, tok),
439             Error(sp, msg) => return Error(sp, msg),
440         }
441
442         // inner parse loop handled all cur_items, so it's empty
443         assert!(cur_items.is_empty());
444
445         /* error messages here could be improved with links to orig. rules */
446         if token_name_eq(&parser.token, &token::Eof) {
447             if eof_items.len() == 1 {
448                 let matches = eof_items[0].matches.iter_mut().map(|dv| {
449                     Rc::make_mut(dv).pop().unwrap()
450                 });
451                 return nameize(sess, ms, matches);
452             } else if eof_items.len() > 1 {
453                 return Error(parser.span, "ambiguity: multiple successful parses".to_string());
454             } else {
455                 return Failure(parser.span, token::Eof);
456             }
457         } else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
458             let nts = bb_items.iter().map(|item| match item.top_elts.get_tt(item.idx) {
459                 TokenTree::MetaVarDecl(_, bind, name) => {
460                     format!("{} ('{}')", name, bind)
461                 }
462                 _ => panic!()
463             }).collect::<Vec<String>>().join(" or ");
464
465             return Error(parser.span, format!(
466                 "local ambiguity: multiple parsing options: {}",
467                 match next_items.len() {
468                     0 => format!("built-in NTs {}.", nts),
469                     1 => format!("built-in NTs {} or 1 other option.", nts),
470                     n => format!("built-in NTs {} or {} other options.", nts, n),
471                 }
472             ));
473         } else if bb_items.is_empty() && next_items.is_empty() {
474             return Failure(parser.span, parser.token);
475         } else if !next_items.is_empty() {
476             /* Now process the next token */
477             cur_items.extend(next_items.drain(..));
478             parser.bump();
479         } else /* bb_items.len() == 1 */ {
480             let mut item = bb_items.pop().unwrap();
481             if let TokenTree::MetaVarDecl(span, _, ident) = item.top_elts.get_tt(item.idx) {
482                 let match_cur = item.match_cur;
483                 item.push_match(match_cur,
484                     MatchedNonterminal(Rc::new(parse_nt(&mut parser, span, &ident.name.as_str()))));
485                 item.idx += 1;
486                 item.match_cur += 1;
487             } else {
488                 unreachable!()
489             }
490             cur_items.push(item);
491         }
492
493         assert!(!cur_items.is_empty());
494     }
495 }
496
497 /// Checks whether a non-terminal may begin with a particular token.
498 ///
499 /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that
500 /// token. Be conservative (return true) if not sure.
501 fn may_begin_with(name: &str, token: &Token) -> bool {
502     /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
503     fn may_be_ident(nt: &token::Nonterminal) -> bool {
504         match *nt {
505             token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false,
506             _ => true,
507         }
508     }
509
510     match name {
511         "expr" => token.can_begin_expr(),
512         "ty" => token.can_begin_type(),
513         "ident" => token.is_ident(),
514         "vis" => match *token { // The follow-set of :vis + "priv" keyword + interpolated
515             Token::Comma | Token::Ident(_) | Token::Interpolated(_) => true,
516             _ => token.can_begin_type(),
517         },
518         "block" => match *token {
519             Token::OpenDelim(token::Brace) => true,
520             Token::Interpolated(ref nt) => match nt.0 {
521                 token::NtItem(_) |
522                 token::NtPat(_) |
523                 token::NtTy(_) |
524                 token::NtIdent(_) |
525                 token::NtMeta(_) |
526                 token::NtPath(_) |
527                 token::NtVis(_) => false, // none of these may start with '{'.
528                 _ => true,
529             },
530             _ => false,
531         },
532         "path" | "meta" => match *token {
533             Token::ModSep | Token::Ident(_) => true,
534             Token::Interpolated(ref nt) => match nt.0 {
535                 token::NtPath(_) | token::NtMeta(_) => true,
536                 _ => may_be_ident(&nt.0),
537             },
538             _ => false,
539         },
540         "pat" => match *token {
541             Token::Ident(_) |               // box, ref, mut, and other identifiers (can stricten)
542             Token::OpenDelim(token::Paren) |    // tuple pattern
543             Token::OpenDelim(token::Bracket) |  // slice pattern
544             Token::BinOp(token::And) |          // reference
545             Token::BinOp(token::Minus) |        // negative literal
546             Token::AndAnd |                     // double reference
547             Token::Literal(..) |                // literal
548             Token::DotDot |                     // range pattern (future compat)
549             Token::DotDotDot |                  // range pattern (future compat)
550             Token::ModSep |                     // path
551             Token::Lt |                         // path (UFCS constant)
552             Token::BinOp(token::Shl) |          // path (double UFCS)
553             Token::Underscore => true,          // placeholder
554             Token::Interpolated(ref nt) => may_be_ident(&nt.0),
555             _ => false,
556         },
557         _ => match *token {
558             token::CloseDelim(_) => false,
559             _ => true,
560         },
561     }
562 }
563
564 fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
565     if name == "tt" {
566         return token::NtTT(p.parse_token_tree());
567     }
568     // check at the beginning and the parser checks after each bump
569     p.process_potential_macro_variable();
570     match name {
571         "item" => match panictry!(p.parse_item()) {
572             Some(i) => token::NtItem(i),
573             None => {
574                 p.fatal("expected an item keyword").emit();
575                 panic!(FatalError);
576             }
577         },
578         "block" => token::NtBlock(panictry!(p.parse_block())),
579         "stmt" => match panictry!(p.parse_stmt()) {
580             Some(s) => token::NtStmt(s),
581             None => {
582                 p.fatal("expected a statement").emit();
583                 panic!(FatalError);
584             }
585         },
586         "pat" => token::NtPat(panictry!(p.parse_pat())),
587         "expr" => token::NtExpr(panictry!(p.parse_expr())),
588         "ty" => token::NtTy(panictry!(p.parse_ty())),
589         // this could be handled like a token, since it is one
590         "ident" => match p.token {
591             token::Ident(sn) => {
592                 p.bump();
593                 token::NtIdent(Spanned::<Ident>{node: sn, span: p.prev_span})
594             }
595             _ => {
596                 let token_str = pprust::token_to_string(&p.token);
597                 p.fatal(&format!("expected ident, found {}",
598                                  &token_str[..])).emit();
599                 panic!(FatalError)
600             }
601         },
602         "path" => {
603             token::NtPath(panictry!(p.parse_path(PathStyle::Type)))
604         },
605         "meta" => token::NtMeta(panictry!(p.parse_meta_item())),
606         "vis" => token::NtVis(panictry!(p.parse_visibility(true))),
607         // this is not supposed to happen, since it has been checked
608         // when compiling the macro.
609         _ => p.span_bug(sp, "invalid fragment specifier")
610     }
611 }