2017-07-23 11:55:52 +02:00
|
|
|
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
|
2012-12-03 16:48:01 -08:00
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
2017-07-23 11:55:52 +02:00
|
|
|
//! This is an NFA-based parser, which calls out to the main rust parser for named nonterminals
|
|
|
|
//! (which it commits to fully when it hits one in a grammar). There's a set of current NFA threads
|
|
|
|
//! and a set of next ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
|
|
|
|
//! pathological cases, is worse than traditional use of NFA or Earley parsing, but it's an easier
|
|
|
|
//! fit for Macro-by-Example-style rules.
|
|
|
|
//!
|
|
|
|
//! (In order to prevent the pathological case, we'd need to lazily construct the resulting
|
|
|
|
//! `NamedMatch`es at the very end. It'd be a pain, and require more memory to keep around old
|
|
|
|
//! items, but it would also save overhead)
|
|
|
|
//!
|
|
|
|
//! We don't say this parser uses the Earley algorithm, because it's unnecessarily innacurate.
|
|
|
|
//! The macro parser restricts itself to the features of finite state automata. Earley parsers
|
|
|
|
//! can be described as an extension of NFAs with completion rules, prediction rules, and recursion.
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
|
|
|
//! Quick intro to how the parser works:
|
|
|
|
//!
|
|
|
|
//! A 'position' is a dot in the middle of a matcher, usually represented as a
|
|
|
|
//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
|
|
|
|
//!
|
|
|
|
//! The parser walks through the input a character at a time, maintaining a list
|
2017-07-23 11:55:52 +02:00
|
|
|
//! of threads consistent with the current position in the input string: `cur_items`.
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-07-23 11:55:52 +02:00
|
|
|
//! As it processes them, it fills up `eof_items` with threads that would be valid if
|
|
|
|
//! the macro invocation is now over, `bb_items` with threads that are waiting on
|
|
|
|
//! a Rust nonterminal like `$e:expr`, and `next_items` with threads that are waiting
|
2015-10-07 23:11:25 +01:00
|
|
|
//! on a particular token. Most of the logic concerns moving the · through the
|
2017-07-23 11:55:52 +02:00
|
|
|
//! repetitions indicated by Kleene stars. The rules for moving the · without
|
|
|
|
//! consuming any input are called epsilon transitions. It only advances or calls
|
|
|
|
//! out to the real Rust parser when no `cur_items` threads remain.
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Example:
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! ```text, ignore
|
|
|
|
//! Start parsing a a a a b against [· a $( a )* a b].
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: a a a a b
|
2017-07-23 11:55:52 +02:00
|
|
|
//! next: [· a $( a )* a b]
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! - - - Advance over an a. - - -
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: a a a b
|
2014-06-09 13:12:30 -07:00
|
|
|
//! cur: [a · $( a )* a b]
|
|
|
|
//! Descend/Skip (first item).
|
|
|
|
//! next: [a $( · a )* a b] [a $( a )* · a b].
|
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! - - - Advance over an a. - - -
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: a a b
|
2017-07-23 11:55:52 +02:00
|
|
|
//! cur: [a $( a · )* a b] [a $( a )* a · b]
|
|
|
|
//! Follow epsilon transition: Finish/Repeat (first item)
|
2014-06-09 13:12:30 -07:00
|
|
|
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
|
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! - - - Advance over an a. - - - (this looks exactly like the last step)
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: a b
|
2017-07-23 11:55:52 +02:00
|
|
|
//! cur: [a $( a · )* a b] [a $( a )* a · b]
|
|
|
|
//! Follow epsilon transition: Finish/Repeat (first item)
|
2014-06-09 13:12:30 -07:00
|
|
|
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
|
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! - - - Advance over an a. - - - (this looks exactly like the last step)
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: b
|
2017-07-23 11:55:52 +02:00
|
|
|
//! cur: [a $( a · )* a b] [a $( a )* a · b]
|
|
|
|
//! Follow epsilon transition: Finish/Repeat (first item)
|
|
|
|
//! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! - - - Advance over a b. - - -
|
2014-06-09 13:12:30 -07:00
|
|
|
//!
|
2017-05-13 21:40:06 +02:00
|
|
|
//! Remaining input: ''
|
2014-06-09 13:12:30 -07:00
|
|
|
//! eof: [a $( a )* a b ·]
|
2017-05-13 21:40:06 +02:00
|
|
|
//! ```
|
2014-06-09 13:12:30 -07:00
|
|
|
|
2014-11-06 00:05:53 -08:00
|
|
|
pub use self::NamedMatch::*;
|
|
|
|
pub use self::ParseResult::*;
|
|
|
|
use self::TokenTreeOrTokenTreeVec::*;
|
2013-05-17 15:28:44 -07:00
|
|
|
|
2016-08-07 02:19:10 +00:00
|
|
|
use ast::Ident;
|
2017-03-15 00:22:48 +00:00
|
|
|
use syntax_pos::{self, BytePos, Span};
|
2016-06-21 18:08:13 -04:00
|
|
|
use codemap::Spanned;
|
2015-12-21 10:00:43 +13:00
|
|
|
use errors::FatalError;
|
2017-02-21 05:05:59 +00:00
|
|
|
use ext::tt::quoted::{self, TokenTree};
|
2016-12-07 00:28:51 +00:00
|
|
|
use parse::{Directory, ParseSess};
|
2018-01-19 19:00:29 -06:00
|
|
|
use parse::parser::{Parser, PathStyle};
|
|
|
|
use parse::token::{self, DocComment, Nonterminal, Token};
|
2014-10-28 11:05:28 +11:00
|
|
|
use print::pprust;
|
2017-02-26 03:25:22 +00:00
|
|
|
use symbol::keywords;
|
2017-02-21 05:05:59 +00:00
|
|
|
use tokenstream::TokenStream;
|
2016-10-21 19:25:16 +11:00
|
|
|
use util::small_vector::SmallVector;
|
2012-12-23 17:41:37 -05:00
|
|
|
|
2014-10-06 23:00:56 +01:00
|
|
|
use std::mem;
|
2014-03-27 16:52:27 +02:00
|
|
|
use std::rc::Rc;
|
2014-05-29 19:03:06 -07:00
|
|
|
use std::collections::HashMap;
|
2018-01-19 19:00:29 -06:00
|
|
|
use std::collections::hash_map::Entry::{Occupied, Vacant};
|
2012-06-12 10:59:50 -07:00
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
// To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body.
|
2012-06-12 10:59:50 -07:00
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Either a sequence of token trees or a single one. This is used as the representation of the
|
|
|
|
/// sequence of tokens that make up a matcher.
|
2015-01-03 22:54:18 -05:00
|
|
|
#[derive(Clone)]
|
2014-11-02 12:21:16 +01:00
|
|
|
enum TokenTreeOrTokenTreeVec {
|
2017-02-21 05:05:59 +00:00
|
|
|
Tt(TokenTree),
|
|
|
|
TtSeq(Vec<TokenTree>),
|
2014-11-02 12:21:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TokenTreeOrTokenTreeVec {
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Returns the number of constituent token trees of `self`.
|
2015-01-17 23:33:05 +00:00
|
|
|
fn len(&self) -> usize {
|
2015-11-17 23:24:49 +09:00
|
|
|
match *self {
|
|
|
|
TtSeq(ref v) => v.len(),
|
|
|
|
Tt(ref tt) => tt.len(),
|
2014-11-02 12:21:16 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The the `index`-th token tree of `self`.
|
2017-02-21 05:05:59 +00:00
|
|
|
fn get_tt(&self, index: usize) -> TokenTree {
|
2015-11-17 23:24:49 +09:00
|
|
|
match *self {
|
|
|
|
TtSeq(ref v) => v[index].clone(),
|
|
|
|
Tt(ref tt) => tt.get_tt(index),
|
2014-11-02 12:21:16 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`.
|
|
|
|
///
|
|
|
|
/// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have
|
|
|
|
/// descended into.
|
2015-01-03 22:54:18 -05:00
|
|
|
#[derive(Clone)]
|
2014-10-06 23:00:56 +01:00
|
|
|
struct MatcherTtFrame {
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The "parent" matcher that we are descending into.
|
2014-11-02 12:21:16 +01:00
|
|
|
elts: TokenTreeOrTokenTreeVec,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The position of the "dot" in `elts` at the time we descended.
|
2015-01-17 23:33:05 +00:00
|
|
|
idx: usize,
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Represents a single "position" (aka "matcher position", aka "item"), as described in the module
|
|
|
|
/// documentation.
|
2015-01-03 22:54:18 -05:00
|
|
|
#[derive(Clone)]
|
2016-11-11 16:28:47 -07:00
|
|
|
struct MatcherPos {
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The token or sequence of tokens that make up the matcher
|
2014-11-02 12:21:16 +01:00
|
|
|
top_elts: TokenTreeOrTokenTreeVec,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The position of the "dot" in this matcher
|
2015-01-17 23:33:05 +00:00
|
|
|
idx: usize,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The beginning position in the source that the beginning of this matcher corresponds to. In
|
|
|
|
/// other words, the token in the source at `sp_lo` is matched against the first token of the
|
|
|
|
/// matcher.
|
|
|
|
sp_lo: BytePos,
|
|
|
|
|
|
|
|
/// For each named metavar in the matcher, we keep track of token trees matched against the
|
|
|
|
/// metavar by the black box parser. In particular, there may be more than one match per
|
|
|
|
/// metavar if we are in a repetition (each repetition matches each of the variables).
|
|
|
|
/// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the
|
|
|
|
/// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of
|
|
|
|
/// the current position of the `self` matcher position in the shared `matches` list.
|
2018-01-24 22:59:11 -06:00
|
|
|
///
|
|
|
|
/// Also, note that while we are descending into a sequence, matchers are given their own
|
|
|
|
/// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add
|
|
|
|
/// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep`
|
|
|
|
/// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one
|
|
|
|
/// wants the shared `matches`, one should use `up.matches`.
|
2017-06-08 05:51:32 -06:00
|
|
|
matches: Vec<Rc<Vec<NamedMatch>>>,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The position in `matches` corresponding to the first metavar in this matcher's sequence of
|
|
|
|
/// token trees. In other words, the first metavar in the first token of `top_elts` corresponds
|
|
|
|
/// to `matches[match_lo]`.
|
2015-01-17 23:33:05 +00:00
|
|
|
match_lo: usize,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// The position in `matches` corresponding to the metavar we are currently trying to match
|
|
|
|
/// against the source token stream. `match_lo <= match_cur <= match_hi`.
|
2015-01-17 23:33:05 +00:00
|
|
|
match_cur: usize,
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar
|
|
|
|
/// in this matcher.
|
2015-01-17 23:33:05 +00:00
|
|
|
match_hi: usize,
|
2018-01-24 22:03:57 -06:00
|
|
|
|
|
|
|
// Specifically used if we are matching a repetition. If we aren't both should be `None`.
|
|
|
|
/// The separator if we are in a repetition
|
|
|
|
sep: Option<Token>,
|
|
|
|
/// The "parent" matcher position if we are in a repetition. That is, the matcher position just
|
|
|
|
/// before we enter the sequence.
|
|
|
|
up: Option<Box<MatcherPos>>,
|
|
|
|
|
|
|
|
// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from
|
|
|
|
// a delimited token tree (e.g. something wrapped in `(` `)`) or to get the contents of a doc
|
|
|
|
// comment...
|
|
|
|
/// When matching against matchers with nested delimited submatchers (e.g. `pat ( pat ( .. )
|
|
|
|
/// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does
|
|
|
|
/// that where the bottom of the stack is the outermost matcher.
|
|
|
|
// Also, throughout the comments, this "descent" is often referred to as "unzipping"...
|
|
|
|
stack: Vec<MatcherTtFrame>,
|
2013-02-21 00:16:31 -08:00
|
|
|
}
|
2012-06-12 10:59:50 -07:00
|
|
|
|
2017-06-08 05:51:32 -06:00
|
|
|
impl MatcherPos {
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Add `m` as a named match for the `idx`-th metavar.
|
2017-06-08 05:51:32 -06:00
|
|
|
fn push_match(&mut self, idx: usize, m: NamedMatch) {
|
|
|
|
let matches = Rc::make_mut(&mut self.matches[idx]);
|
|
|
|
matches.push(m);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Represents the possible results of an attempted parse.
|
|
|
|
pub enum ParseResult<T> {
|
|
|
|
/// Parsed successfully.
|
|
|
|
Success(T),
|
|
|
|
/// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
|
|
|
|
/// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
|
|
|
|
Failure(syntax_pos::Span, Token),
|
|
|
|
/// Fatal error (malformed macro?). Abort compilation.
|
|
|
|
Error(syntax_pos::Span, String),
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A `ParseResult` where the `Success` variant contains a mapping of `Ident`s to `NamedMatch`es.
|
|
|
|
/// This represents the mapping of metavars to the token trees they bind to.
|
2016-11-07 19:40:00 -07:00
|
|
|
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Count how many metavars are named in the given matcher `ms`.
|
2017-02-21 05:05:59 +00:00
|
|
|
pub fn count_names(ms: &[TokenTree]) -> usize {
|
2014-10-06 23:00:56 +01:00
|
|
|
ms.iter().fold(0, |count, elt| {
|
2015-11-17 23:24:49 +09:00
|
|
|
count + match *elt {
|
2017-03-28 05:32:43 +00:00
|
|
|
TokenTree::Sequence(_, ref seq) => seq.num_captures,
|
|
|
|
TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
|
|
|
|
TokenTree::MetaVar(..) => 0,
|
|
|
|
TokenTree::MetaVarDecl(..) => 1,
|
2016-08-26 19:23:42 +03:00
|
|
|
TokenTree::Token(..) => 0,
|
2012-07-23 15:34:43 -07:00
|
|
|
}
|
2014-10-06 23:00:56 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Initialize `len` empty shared `Vec`s to be used to store matches of metavars.
|
|
|
|
fn create_matches(len: usize) -> Vec<Rc<Vec<NamedMatch>>> {
|
|
|
|
(0..len).into_iter().map(|_| Rc::new(Vec::new())).collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generate the top-level matcher position in which the "dot" is before the first token of the
|
|
|
|
/// matcher `ms` and we are going to start matching at position `lo` in the source.
|
2017-02-21 05:05:59 +00:00
|
|
|
fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
|
2015-02-18 14:48:57 -05:00
|
|
|
let match_idx_hi = count_names(&ms[..]);
|
2016-11-11 16:28:47 -07:00
|
|
|
let matches = create_matches(match_idx_hi);
|
2015-04-15 20:56:16 -07:00
|
|
|
Box::new(MatcherPos {
|
2018-01-24 22:03:57 -06:00
|
|
|
// Start with the top level matcher given to us
|
|
|
|
top_elts: TtSeq(ms), // "elts" is an abbr. for "elements"
|
|
|
|
// The "dot" is before the first token of the matcher
|
2015-01-28 01:01:48 +00:00
|
|
|
idx: 0,
|
2018-01-24 22:03:57 -06:00
|
|
|
// We start matching with byte `lo` in the source code
|
|
|
|
sp_lo: lo,
|
|
|
|
|
|
|
|
// Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`.
|
|
|
|
// `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since
|
|
|
|
// we haven't actually matched anything yet.
|
2017-08-06 22:54:09 -07:00
|
|
|
matches,
|
2015-01-28 01:01:48 +00:00
|
|
|
match_lo: 0,
|
|
|
|
match_cur: 0,
|
2013-02-21 00:16:31 -08:00
|
|
|
match_hi: match_idx_hi,
|
2018-01-24 22:03:57 -06:00
|
|
|
|
|
|
|
// Haven't descended into any delimiters, so empty stack
|
|
|
|
stack: vec![],
|
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// Haven't descended into any sequences, so both of these are `None`.
|
2018-01-24 22:03:57 -06:00
|
|
|
sep: None,
|
|
|
|
up: None,
|
2015-04-15 20:56:16 -07:00
|
|
|
})
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
|
2017-05-12 20:05:39 +02:00
|
|
|
/// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
|
2014-06-09 13:12:30 -07:00
|
|
|
/// so it is associated with a single ident in a parse, and all
|
2017-05-12 20:05:39 +02:00
|
|
|
/// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
|
|
|
|
/// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
|
|
|
|
/// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
|
2014-06-09 13:12:30 -07:00
|
|
|
///
|
2017-05-12 20:05:39 +02:00
|
|
|
/// The in-memory structure of a particular `NamedMatch` represents the match
|
2014-10-06 23:00:56 +01:00
|
|
|
/// that occurred when a particular subset of a matcher was applied to a
|
|
|
|
/// particular token tree.
|
2014-06-09 13:12:30 -07:00
|
|
|
///
|
2017-05-12 20:05:39 +02:00
|
|
|
/// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
|
|
|
|
/// the `MatchedNonterminal`s, will depend on the token tree it was applied
|
|
|
|
/// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
|
|
|
|
/// token tree. The depth of the `NamedMatch` structure will therefore depend
|
2014-10-07 00:18:24 +01:00
|
|
|
/// only on the nesting depth of `ast::TTSeq`s in the originating
|
|
|
|
/// token tree it was derived from.
|
2017-06-08 05:51:32 -06:00
|
|
|
#[derive(Debug, Clone)]
|
2014-01-09 15:05:33 +02:00
|
|
|
pub enum NamedMatch {
|
2017-06-08 05:51:32 -06:00
|
|
|
MatchedSeq(Rc<Vec<NamedMatch>>, syntax_pos::Span),
|
2018-01-19 19:00:29 -06:00
|
|
|
MatchedNonterminal(Rc<Nonterminal>),
|
2012-07-27 19:14:46 -07:00
|
|
|
}
|
2012-06-12 10:59:50 -07:00
|
|
|
|
2018-01-19 19:00:29 -06:00
|
|
|
fn nameize<I: Iterator<Item = NamedMatch>>(
|
|
|
|
sess: &ParseSess,
|
|
|
|
ms: &[TokenTree],
|
|
|
|
mut res: I,
|
|
|
|
) -> NamedParseResult {
|
|
|
|
fn n_rec<I: Iterator<Item = NamedMatch>>(
|
|
|
|
sess: &ParseSess,
|
|
|
|
m: &TokenTree,
|
|
|
|
res: &mut I,
|
|
|
|
ret_val: &mut HashMap<Ident, Rc<NamedMatch>>,
|
|
|
|
) -> Result<(), (syntax_pos::Span, String)> {
|
2015-11-17 23:24:49 +09:00
|
|
|
match *m {
|
2018-01-19 19:00:29 -06:00
|
|
|
TokenTree::Sequence(_, ref seq) => for next_m in &seq.tts {
|
|
|
|
n_rec(sess, next_m, res.by_ref(), ret_val)?
|
|
|
|
},
|
|
|
|
TokenTree::Delimited(_, ref delim) => for next_m in &delim.tts {
|
|
|
|
n_rec(sess, next_m, res.by_ref(), ret_val)?;
|
|
|
|
},
|
2017-02-26 03:25:22 +00:00
|
|
|
TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
|
|
|
|
if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
|
|
|
|
return Err((span, "missing fragment specifier".to_string()));
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
|
|
|
}
|
2017-01-30 23:48:14 +00:00
|
|
|
TokenTree::MetaVarDecl(sp, bind_name, _) => {
|
2016-08-07 02:19:10 +00:00
|
|
|
match ret_val.entry(bind_name) {
|
2014-10-06 23:00:56 +01:00
|
|
|
Vacant(spot) => {
|
2017-06-08 05:51:32 -06:00
|
|
|
// FIXME(simulacrum): Don't construct Rc here
|
|
|
|
spot.insert(Rc::new(res.next().unwrap()));
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
|
|
|
Occupied(..) => {
|
2015-11-25 20:58:57 +01:00
|
|
|
return Err((sp, format!("duplicated bind name: {}", bind_name)))
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
|
|
|
}
|
2012-06-27 15:29:35 -07:00
|
|
|
}
|
2017-03-28 05:32:43 +00:00
|
|
|
TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
|
2012-06-27 15:29:35 -07:00
|
|
|
}
|
2015-11-25 20:58:57 +01:00
|
|
|
|
|
|
|
Ok(())
|
2012-06-27 15:29:35 -07:00
|
|
|
}
|
2015-11-25 20:58:57 +01:00
|
|
|
|
2013-04-03 09:28:36 -04:00
|
|
|
let mut ret_val = HashMap::new();
|
2015-11-25 20:58:57 +01:00
|
|
|
for m in ms {
|
2017-02-26 03:25:22 +00:00
|
|
|
match n_rec(sess, m, res.by_ref(), &mut ret_val) {
|
2018-01-19 19:00:29 -06:00
|
|
|
Ok(_) => {}
|
2015-11-25 20:58:57 +01:00
|
|
|
Err((sp, msg)) => return Error(sp, msg),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Success(ret_val)
|
2012-06-27 15:29:35 -07:00
|
|
|
}
|
|
|
|
|
2016-10-21 12:01:06 +11:00
|
|
|
pub fn parse_failure_msg(tok: Token) -> String {
|
|
|
|
match tok {
|
|
|
|
token::Eof => "unexpected end of macro invocation".to_string(),
|
2018-01-19 19:00:29 -06:00
|
|
|
_ => format!(
|
|
|
|
"no rules expected the token `{}`",
|
|
|
|
pprust::token_to_string(&tok)
|
|
|
|
),
|
2016-10-21 12:01:06 +11:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-11 16:28:47 -07:00
|
|
|
/// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
|
2018-01-19 19:00:29 -06:00
|
|
|
fn token_name_eq(t1: &Token, t2: &Token) -> bool {
|
2017-05-15 09:26:26 +00:00
|
|
|
if let (Some(id1), Some(id2)) = (t1.ident(), t2.ident()) {
|
|
|
|
id1.name == id2.name
|
|
|
|
} else if let (&token::Lifetime(id1), &token::Lifetime(id2)) = (t1, t2) {
|
|
|
|
id1.name == id2.name
|
|
|
|
} else {
|
|
|
|
*t1 == *t2
|
2013-09-05 14:14:31 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
/// Process the matcher positions of `cur_items` until it is empty. In the process, this will
|
|
|
|
/// produce more items in `next_items`, `eof_items`, and `bb_items`.
|
|
|
|
///
|
|
|
|
/// For more info about the how this happens, see the module-level doc comments and the inline
|
|
|
|
/// comments of this function.
|
|
|
|
///
|
|
|
|
/// # Parameters
|
|
|
|
///
|
|
|
|
/// - `sess`: the parsing session into which errors are emitted.
|
|
|
|
/// - `cur_items`: the set of current items to be processed. This should be empty by the end of a
|
|
|
|
/// successful execution of this function.
|
|
|
|
/// - `next_items`: the set of newly generated items. These are used to replenish `cur_items` in
|
|
|
|
/// the function `parse`.
|
|
|
|
/// - `eof_items`: the set of items that would be valid if this was the EOF.
|
|
|
|
/// - `bb_items`: the set of items that are waiting for the black-box parser.
|
|
|
|
/// - `token`: the current token of the parser.
|
|
|
|
/// - `span`: the `Span` in the source code corresponding to the token trees we are trying to match
|
|
|
|
/// against the matcher positions in `cur_items`.
|
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
///
|
|
|
|
/// A `ParseResult`. Note that matches are kept track of through the items generated.
|
2018-01-19 19:00:29 -06:00
|
|
|
fn inner_parse_loop(
|
|
|
|
sess: &ParseSess,
|
|
|
|
cur_items: &mut SmallVector<Box<MatcherPos>>,
|
|
|
|
next_items: &mut Vec<Box<MatcherPos>>,
|
|
|
|
eof_items: &mut SmallVector<Box<MatcherPos>>,
|
|
|
|
bb_items: &mut SmallVector<Box<MatcherPos>>,
|
|
|
|
token: &Token,
|
|
|
|
span: syntax_pos::Span,
|
|
|
|
) -> ParseResult<()> {
|
2018-01-24 22:59:11 -06:00
|
|
|
// Pop items from `cur_items` until it is empty.
|
2017-07-23 11:55:52 +02:00
|
|
|
while let Some(mut item) = cur_items.pop() {
|
2018-01-24 22:59:11 -06:00
|
|
|
// When unzipped trees end, remove them. This corresponds to backtracking out of a
|
|
|
|
// delimited submatcher into which we already descended. In backtracking out again, we need
|
|
|
|
// to advance the "dot" past the delimiters in the outer matcher.
|
2017-07-23 11:55:52 +02:00
|
|
|
while item.idx >= item.top_elts.len() {
|
|
|
|
match item.stack.pop() {
|
2016-11-11 16:28:47 -07:00
|
|
|
Some(MatcherTtFrame { elts, idx }) => {
|
2017-07-23 11:55:52 +02:00
|
|
|
item.top_elts = elts;
|
|
|
|
item.idx = idx + 1;
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
2018-01-19 19:00:29 -06:00
|
|
|
None => break,
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
2014-10-06 23:00:56 +01:00
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// Get the current position of the "dot" (`idx`) in `item` and the number of token trees in
|
|
|
|
// the matcher (`len`).
|
2017-07-23 11:55:52 +02:00
|
|
|
let idx = item.idx;
|
|
|
|
let len = item.top_elts.len();
|
2016-11-11 16:28:47 -07:00
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// If `idx >= len`, then we are at or past the end of the matcher of `item`.
|
2016-11-11 16:28:47 -07:00
|
|
|
if idx >= len {
|
2018-01-24 22:59:11 -06:00
|
|
|
// We are repeating iff there is a parent. If the matcher is inside of a repetition,
|
|
|
|
// then we could be at the end of a sequence or at the beginning of the next
|
|
|
|
// repetition.
|
2017-07-23 11:55:52 +02:00
|
|
|
if item.up.is_some() {
|
2018-01-24 22:59:11 -06:00
|
|
|
// At this point, regardless of whether there is a separator, we should add all
|
|
|
|
// matches from the complete repetition of the sequence to the shared, top-level
|
|
|
|
// `matches` list (actually, `up.matches`, which could itself not be the top-level,
|
|
|
|
// but anyway...). Moreover, we add another item to `cur_items` in which the "dot"
|
|
|
|
// is at the end of the `up` matcher. This ensures that the "dot" in the `up`
|
|
|
|
// matcher is also advanced sufficiently.
|
|
|
|
//
|
|
|
|
// NOTE: removing the condition `idx == len` allows trailing separators.
|
2016-11-11 16:28:47 -07:00
|
|
|
if idx == len {
|
2018-01-24 22:59:11 -06:00
|
|
|
// Get the `up` matcher
|
2017-07-23 11:55:52 +02:00
|
|
|
let mut new_pos = item.up.clone().unwrap();
|
2016-11-11 16:28:47 -07:00
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// Add matches from this repetition to the `matches` of `up`
|
2017-07-23 11:55:52 +02:00
|
|
|
for idx in item.match_lo..item.match_hi {
|
|
|
|
let sub = item.matches[idx].clone();
|
2017-07-31 23:04:34 +03:00
|
|
|
let span = span.with_lo(item.sp_lo);
|
|
|
|
new_pos.push_match(idx, MatchedSeq(sub, span));
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// Move the "dot" past the repetition in `up`
|
2017-07-23 11:55:52 +02:00
|
|
|
new_pos.match_cur = item.match_hi;
|
2016-11-11 16:28:47 -07:00
|
|
|
new_pos.idx += 1;
|
2017-07-23 11:55:52 +02:00
|
|
|
cur_items.push(new_pos);
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
2012-07-23 15:34:43 -07:00
|
|
|
|
2018-01-24 22:59:11 -06:00
|
|
|
// Check if we need a separator.
|
2017-07-23 11:55:52 +02:00
|
|
|
if idx == len && item.sep.is_some() {
|
2018-01-24 22:59:11 -06:00
|
|
|
// We have a separator, and it is the current token. We can advance past the
|
|
|
|
// separator token.
|
2018-01-19 19:00:29 -06:00
|
|
|
if item.sep
|
|
|
|
.as_ref()
|
|
|
|
.map(|sep| token_name_eq(token, sep))
|
|
|
|
.unwrap_or(false)
|
|
|
|
{
|
2017-07-23 11:55:52 +02:00
|
|
|
item.idx += 1;
|
|
|
|
next_items.push(item);
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
2018-01-24 22:59:11 -06:00
|
|
|
}
|
|
|
|
// We don't need a separator. Move the "dot" back to the beginning of the matcher
|
|
|
|
// and try to match again.
|
|
|
|
else {
|
2017-07-23 11:55:52 +02:00
|
|
|
item.match_cur = item.match_lo;
|
|
|
|
item.idx = 0;
|
|
|
|
cur_items.push(item);
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
2018-01-24 22:59:11 -06:00
|
|
|
}
|
|
|
|
// If we are not in a repetition, then being at the end of a matcher means that we have
|
|
|
|
// reached the potential end of the input.
|
|
|
|
else {
|
2017-07-23 11:55:52 +02:00
|
|
|
eof_items.push(item);
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
|
|
|
} else {
|
2017-07-23 11:55:52 +02:00
|
|
|
match item.top_elts.get_tt(idx) {
|
2016-11-11 16:28:47 -07:00
|
|
|
/* need to descend into sequence */
|
|
|
|
TokenTree::Sequence(sp, seq) => {
|
2017-01-29 08:38:44 +00:00
|
|
|
if seq.op == quoted::KleeneOp::ZeroOrMore {
|
2016-11-11 16:28:47 -07:00
|
|
|
// Examine the case where there are 0 matches of this sequence
|
2017-07-23 11:55:52 +02:00
|
|
|
let mut new_item = item.clone();
|
|
|
|
new_item.match_cur += seq.num_captures;
|
|
|
|
new_item.idx += 1;
|
|
|
|
for idx in item.match_cur..item.match_cur + seq.num_captures {
|
|
|
|
new_item.push_match(idx, MatchedSeq(Rc::new(vec![]), sp));
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
2017-07-23 11:55:52 +02:00
|
|
|
cur_items.push(new_item);
|
2014-10-06 23:15:12 -07:00
|
|
|
}
|
2016-11-11 16:28:47 -07:00
|
|
|
|
|
|
|
// Examine the case where there is at least one match of this sequence
|
2017-07-23 11:55:52 +02:00
|
|
|
let matches = create_matches(item.matches.len());
|
|
|
|
cur_items.push(Box::new(MatcherPos {
|
2016-11-11 16:28:47 -07:00
|
|
|
stack: vec![],
|
|
|
|
sep: seq.separator.clone(),
|
|
|
|
idx: 0,
|
2017-08-06 22:54:09 -07:00
|
|
|
matches,
|
2017-07-23 11:55:52 +02:00
|
|
|
match_lo: item.match_cur,
|
|
|
|
match_cur: item.match_cur,
|
|
|
|
match_hi: item.match_cur + seq.num_captures,
|
|
|
|
up: Some(item),
|
2017-07-31 23:04:34 +03:00
|
|
|
sp_lo: sp.lo(),
|
2016-11-11 16:28:47 -07:00
|
|
|
top_elts: Tt(TokenTree::Sequence(sp, seq)),
|
|
|
|
}));
|
|
|
|
}
|
2017-02-26 03:25:22 +00:00
|
|
|
TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
|
|
|
|
if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
|
|
|
|
return Error(span, "missing fragment specifier".to_string());
|
|
|
|
}
|
|
|
|
}
|
2017-06-26 22:23:59 +08:00
|
|
|
TokenTree::MetaVarDecl(_, _, id) => {
|
2016-11-11 16:28:47 -07:00
|
|
|
// Built-in nonterminals never start with these tokens,
|
|
|
|
// so we can eliminate them from consideration.
|
2017-06-26 22:23:59 +08:00
|
|
|
if may_begin_with(&*id.name.as_str(), token) {
|
2017-07-23 11:55:52 +02:00
|
|
|
bb_items.push(item);
|
2014-10-06 23:00:56 +01:00
|
|
|
}
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
|
|
|
seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
|
2017-07-23 11:55:52 +02:00
|
|
|
let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
|
|
|
|
let idx = item.idx;
|
|
|
|
item.stack.push(MatcherTtFrame {
|
2016-11-11 16:28:47 -07:00
|
|
|
elts: lower_elts,
|
2017-08-06 22:54:09 -07:00
|
|
|
idx,
|
2016-11-11 16:28:47 -07:00
|
|
|
});
|
2017-07-23 11:55:52 +02:00
|
|
|
item.idx = 0;
|
|
|
|
cur_items.push(item);
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
2017-03-28 05:32:43 +00:00
|
|
|
TokenTree::Token(_, ref t) if token_name_eq(t, token) => {
|
2017-07-23 11:55:52 +02:00
|
|
|
item.idx += 1;
|
|
|
|
next_items.push(item);
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
2017-03-28 05:32:43 +00:00
|
|
|
TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
}
|
2016-11-11 16:28:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
Success(())
|
|
|
|
}
|
|
|
|
|
2018-01-24 22:03:57 -06:00
|
|
|
/// Use the given sequence of token trees (`ms`) as a matcher. Match the given token stream `tts`
|
|
|
|
/// against it and return the match.
|
2018-01-19 20:47:39 -06:00
|
|
|
///
|
|
|
|
/// # Parameters
|
|
|
|
///
|
|
|
|
/// - `sess`: The session into which errors are emitted
|
2018-01-24 22:03:57 -06:00
|
|
|
/// - `tts`: The tokenstream we are matching against the pattern `ms`
|
|
|
|
/// - `ms`: A sequence of token trees representing a pattern against which we are matching
|
2018-01-19 20:47:39 -06:00
|
|
|
/// - `directory`: Information about the file locations (needed for the black-box parser)
|
|
|
|
/// - `recurse_into_modules`: Whether or not to recurse into modules (needed for the black-box
|
|
|
|
/// parser)
|
2018-01-19 19:00:29 -06:00
|
|
|
pub fn parse(
|
|
|
|
sess: &ParseSess,
|
|
|
|
tts: TokenStream,
|
|
|
|
ms: &[TokenTree],
|
|
|
|
directory: Option<Directory>,
|
|
|
|
recurse_into_modules: bool,
|
|
|
|
) -> NamedParseResult {
|
2018-01-19 20:47:39 -06:00
|
|
|
// Create a parser that can be used for the "black box" parts.
|
2017-05-18 10:37:24 +12:00
|
|
|
let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
|
2018-01-19 20:47:39 -06:00
|
|
|
|
|
|
|
// A queue of possible matcher positions. We initialize it with the matcher position in which
|
2018-01-24 22:03:57 -06:00
|
|
|
// the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then
|
2018-01-19 20:47:39 -06:00
|
|
|
// processes all of these possible matcher positions and produces posible next positions into
|
2018-01-24 22:03:57 -06:00
|
|
|
// `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items`
|
|
|
|
// and we start over again.
|
2017-07-31 23:04:34 +03:00
|
|
|
let mut cur_items = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo()));
|
2018-01-19 20:47:39 -06:00
|
|
|
let mut next_items = Vec::new();
|
2016-11-11 16:28:47 -07:00
|
|
|
|
|
|
|
loop {
|
2018-01-19 20:47:39 -06:00
|
|
|
// Matcher positions black-box parsed by parser.rs (`parser`)
|
|
|
|
let mut bb_items = SmallVector::new();
|
|
|
|
|
|
|
|
// Matcher positions that would be valid if the macro invocation was over now
|
2017-07-23 11:55:52 +02:00
|
|
|
let mut eof_items = SmallVector::new();
|
|
|
|
assert!(next_items.is_empty());
|
2016-11-11 16:28:47 -07:00
|
|
|
|
2018-01-19 20:47:39 -06:00
|
|
|
// Process `cur_items` until either we have finished the input or we need to get some
|
|
|
|
// parsing from the black-box parser done. The result is that `next_items` will contain a
|
|
|
|
// bunch of possible next matcher positions in `next_items`.
|
2018-01-19 19:00:29 -06:00
|
|
|
match inner_parse_loop(
|
|
|
|
sess,
|
|
|
|
&mut cur_items,
|
|
|
|
&mut next_items,
|
|
|
|
&mut eof_items,
|
|
|
|
&mut bb_items,
|
|
|
|
&parser.token,
|
|
|
|
parser.span,
|
|
|
|
) {
|
|
|
|
Success(_) => {}
|
2016-11-11 16:28:47 -07:00
|
|
|
Failure(sp, tok) => return Failure(sp, tok),
|
|
|
|
Error(sp, msg) => return Error(sp, msg),
|
|
|
|
}
|
|
|
|
|
2017-07-23 11:55:52 +02:00
|
|
|
// inner parse loop handled all cur_items, so it's empty
|
|
|
|
assert!(cur_items.is_empty());
|
2012-06-12 10:59:50 -07:00
|
|
|
|
2018-01-19 20:47:39 -06:00
|
|
|
// We need to do some post processing after the `inner_parser_loop`.
|
|
|
|
//
|
|
|
|
// Error messages here could be improved with links to original rules.
|
|
|
|
|
|
|
|
// If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise,
|
|
|
|
// either the parse is ambiguous (which should never happen) or their is a syntax error.
|
2016-11-06 19:37:56 -07:00
|
|
|
if token_name_eq(&parser.token, &token::Eof) {
|
2017-07-23 11:55:52 +02:00
|
|
|
if eof_items.len() == 1 {
|
2018-01-19 19:00:29 -06:00
|
|
|
let matches = eof_items[0]
|
|
|
|
.matches
|
|
|
|
.iter_mut()
|
|
|
|
.map(|dv| Rc::make_mut(dv).pop().unwrap());
|
2017-02-26 03:25:22 +00:00
|
|
|
return nameize(sess, ms, matches);
|
2017-07-23 11:55:52 +02:00
|
|
|
} else if eof_items.len() > 1 {
|
2018-01-19 19:00:29 -06:00
|
|
|
return Error(
|
|
|
|
parser.span,
|
|
|
|
"ambiguity: multiple successful parses".to_string(),
|
|
|
|
);
|
2012-06-12 10:59:50 -07:00
|
|
|
} else {
|
2016-11-06 19:37:56 -07:00
|
|
|
return Failure(parser.span, token::Eof);
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
2018-01-19 20:47:39 -06:00
|
|
|
}
|
|
|
|
// Another possibility is that we need to call out to parse some rust nonterminal
|
|
|
|
// (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong.
|
|
|
|
else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
|
2018-01-19 19:00:29 -06:00
|
|
|
let nts = bb_items
|
|
|
|
.iter()
|
|
|
|
.map(|item| match item.top_elts.get_tt(item.idx) {
|
|
|
|
TokenTree::MetaVarDecl(_, bind, name) => format!("{} ('{}')", name, bind),
|
|
|
|
_ => panic!(),
|
|
|
|
})
|
|
|
|
.collect::<Vec<String>>()
|
|
|
|
.join(" or ");
|
|
|
|
|
|
|
|
return Error(
|
|
|
|
parser.span,
|
|
|
|
format!(
|
|
|
|
"local ambiguity: multiple parsing options: {}",
|
|
|
|
match next_items.len() {
|
|
|
|
0 => format!("built-in NTs {}.", nts),
|
|
|
|
1 => format!("built-in NTs {} or 1 other option.", nts),
|
|
|
|
n => format!("built-in NTs {} or {} other options.", nts, n),
|
|
|
|
}
|
|
|
|
),
|
|
|
|
);
|
2018-01-19 20:47:39 -06:00
|
|
|
}
|
|
|
|
// If there are no posible next positions AND we aren't waiting for the black-box parser,
|
|
|
|
// then their is a syntax error.
|
|
|
|
else if bb_items.is_empty() && next_items.is_empty() {
|
2016-11-12 07:41:47 -07:00
|
|
|
return Failure(parser.span, parser.token);
|
2018-01-19 20:47:39 -06:00
|
|
|
}
|
|
|
|
// Dump all possible `next_items` into `cur_items` for the next iteration.
|
|
|
|
else if !next_items.is_empty() {
|
|
|
|
// Now process the next token
|
2017-07-23 11:55:52 +02:00
|
|
|
cur_items.extend(next_items.drain(..));
|
2016-11-12 07:41:47 -07:00
|
|
|
parser.bump();
|
2018-01-19 20:47:39 -06:00
|
|
|
}
|
|
|
|
// Finally, we have the case where we need to call the black-box parser to get some
|
|
|
|
// nonterminal.
|
|
|
|
else {
|
|
|
|
assert_eq!(bb_items.len(), 1);
|
|
|
|
|
2017-07-23 11:55:52 +02:00
|
|
|
let mut item = bb_items.pop().unwrap();
|
|
|
|
if let TokenTree::MetaVarDecl(span, _, ident) = item.top_elts.get_tt(item.idx) {
|
|
|
|
let match_cur = item.match_cur;
|
2018-01-19 19:00:29 -06:00
|
|
|
item.push_match(
|
|
|
|
match_cur,
|
|
|
|
MatchedNonterminal(Rc::new(parse_nt(&mut parser, span, &ident.name.as_str()))),
|
|
|
|
);
|
2017-07-23 11:55:52 +02:00
|
|
|
item.idx += 1;
|
|
|
|
item.match_cur += 1;
|
2016-11-12 07:41:47 -07:00
|
|
|
} else {
|
|
|
|
unreachable!()
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
2017-07-23 11:55:52 +02:00
|
|
|
cur_items.push(item);
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
|
2017-07-23 11:55:52 +02:00
|
|
|
assert!(!cur_items.is_empty());
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-26 22:23:59 +08:00
|
|
|
/// Checks whether a non-terminal may begin with a particular token.
|
|
|
|
///
|
|
|
|
/// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that
|
|
|
|
/// token. Be conservative (return true) if not sure.
|
|
|
|
fn may_begin_with(name: &str, token: &Token) -> bool {
|
|
|
|
/// Checks whether the non-terminal may contain a single (non-keyword) identifier.
|
|
|
|
fn may_be_ident(nt: &token::Nonterminal) -> bool {
|
|
|
|
match *nt {
|
|
|
|
token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false,
|
|
|
|
_ => true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
match name {
|
|
|
|
"expr" => token.can_begin_expr(),
|
|
|
|
"ty" => token.can_begin_type(),
|
|
|
|
"ident" => token.is_ident(),
|
2018-01-19 19:00:29 -06:00
|
|
|
"vis" => match *token {
|
|
|
|
// The follow-set of :vis + "priv" keyword + interpolated
|
2017-06-26 22:23:59 +08:00
|
|
|
Token::Comma | Token::Ident(_) | Token::Interpolated(_) => true,
|
|
|
|
_ => token.can_begin_type(),
|
|
|
|
},
|
|
|
|
"block" => match *token {
|
|
|
|
Token::OpenDelim(token::Brace) => true,
|
|
|
|
Token::Interpolated(ref nt) => match nt.0 {
|
2018-01-19 19:00:29 -06:00
|
|
|
token::NtItem(_)
|
|
|
|
| token::NtPat(_)
|
|
|
|
| token::NtTy(_)
|
|
|
|
| token::NtIdent(_)
|
|
|
|
| token::NtMeta(_)
|
|
|
|
| token::NtPath(_)
|
|
|
|
| token::NtVis(_) => false, // none of these may start with '{'.
|
2017-06-26 22:23:59 +08:00
|
|
|
_ => true,
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
"path" | "meta" => match *token {
|
|
|
|
Token::ModSep | Token::Ident(_) => true,
|
|
|
|
Token::Interpolated(ref nt) => match nt.0 {
|
|
|
|
token::NtPath(_) | token::NtMeta(_) => true,
|
|
|
|
_ => may_be_ident(&nt.0),
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
"pat" => match *token {
|
|
|
|
Token::Ident(_) | // box, ref, mut, and other identifiers (can stricten)
|
|
|
|
Token::OpenDelim(token::Paren) | // tuple pattern
|
|
|
|
Token::OpenDelim(token::Bracket) | // slice pattern
|
|
|
|
Token::BinOp(token::And) | // reference
|
|
|
|
Token::BinOp(token::Minus) | // negative literal
|
|
|
|
Token::AndAnd | // double reference
|
|
|
|
Token::Literal(..) | // literal
|
|
|
|
Token::DotDot | // range pattern (future compat)
|
|
|
|
Token::DotDotDot | // range pattern (future compat)
|
|
|
|
Token::ModSep | // path
|
|
|
|
Token::Lt | // path (UFCS constant)
|
|
|
|
Token::BinOp(token::Shl) | // path (double UFCS)
|
|
|
|
Token::Underscore => true, // placeholder
|
|
|
|
Token::Interpolated(ref nt) => may_be_ident(&nt.0),
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
_ => match *token {
|
|
|
|
token::CloseDelim(_) => false,
|
|
|
|
_ => true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-19 20:47:39 -06:00
|
|
|
/// A call to the "black-box" parser to parse some rust nonterminal.
|
|
|
|
///
|
|
|
|
/// # Parameters
|
|
|
|
///
|
|
|
|
/// - `p`: the "black-box" parser to use
|
|
|
|
/// - `sp`: the `Span` we want to parse
|
|
|
|
/// - `name`: the name of the metavar _matcher_ we want to match (e.g. `tt`, `ident`, `block`,
|
|
|
|
/// etc...)
|
|
|
|
///
|
|
|
|
/// # Returns
|
|
|
|
///
|
|
|
|
/// The parsed nonterminal.
|
2016-11-11 16:28:47 -07:00
|
|
|
fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
|
2017-05-13 21:40:06 +02:00
|
|
|
if name == "tt" {
|
2017-05-12 20:05:39 +02:00
|
|
|
return token::NtTT(p.parse_token_tree());
|
2015-01-02 23:00:06 +01:00
|
|
|
}
|
|
|
|
// check at the beginning and the parser checks after each bump
|
2017-03-29 07:17:18 +00:00
|
|
|
p.process_potential_macro_variable();
|
2012-08-06 12:34:08 -07:00
|
|
|
match name {
|
2015-11-10 16:08:26 -08:00
|
|
|
"item" => match panictry!(p.parse_item()) {
|
2015-08-15 19:37:25 +02:00
|
|
|
Some(i) => token::NtItem(i),
|
2015-12-21 10:00:43 +13:00
|
|
|
None => {
|
|
|
|
p.fatal("expected an item keyword").emit();
|
2018-01-21 12:47:58 +01:00
|
|
|
FatalError.raise();
|
2015-12-21 10:00:43 +13:00
|
|
|
}
|
2015-08-15 19:37:25 +02:00
|
|
|
},
|
|
|
|
"block" => token::NtBlock(panictry!(p.parse_block())),
|
2015-11-10 16:08:26 -08:00
|
|
|
"stmt" => match panictry!(p.parse_stmt()) {
|
2016-11-02 03:03:55 +00:00
|
|
|
Some(s) => token::NtStmt(s),
|
2015-12-21 10:00:43 +13:00
|
|
|
None => {
|
|
|
|
p.fatal("expected a statement").emit();
|
2018-01-21 12:47:58 +01:00
|
|
|
FatalError.raise();
|
2015-12-21 10:00:43 +13:00
|
|
|
}
|
2015-08-15 19:37:25 +02:00
|
|
|
},
|
2015-11-10 16:08:26 -08:00
|
|
|
"pat" => token::NtPat(panictry!(p.parse_pat())),
|
|
|
|
"expr" => token::NtExpr(panictry!(p.parse_expr())),
|
2017-03-17 00:47:32 +03:00
|
|
|
"ty" => token::NtTy(panictry!(p.parse_ty())),
|
2015-08-15 19:37:25 +02:00
|
|
|
// this could be handled like a token, since it is one
|
|
|
|
"ident" => match p.token {
|
2016-04-16 04:12:02 +03:00
|
|
|
token::Ident(sn) => {
|
2015-12-31 12:11:53 +13:00
|
|
|
p.bump();
|
2018-01-19 19:00:29 -06:00
|
|
|
token::NtIdent(Spanned::<Ident> {
|
|
|
|
node: sn,
|
|
|
|
span: p.prev_span,
|
|
|
|
})
|
2015-12-15 17:31:54 +13:00
|
|
|
}
|
2015-08-15 19:37:25 +02:00
|
|
|
_ => {
|
|
|
|
let token_str = pprust::token_to_string(&p.token);
|
2018-01-19 19:00:29 -06:00
|
|
|
p.fatal(&format!("expected ident, found {}", &token_str[..]))
|
|
|
|
.emit();
|
2018-01-21 12:47:58 +01:00
|
|
|
FatalError.raise()
|
2015-08-15 19:37:25 +02:00
|
|
|
}
|
|
|
|
},
|
2017-08-11 02:30:08 +03:00
|
|
|
"path" => token::NtPath(panictry!(p.parse_path_common(PathStyle::Type, false))),
|
2015-10-23 19:02:38 -07:00
|
|
|
"meta" => token::NtMeta(panictry!(p.parse_meta_item())),
|
2016-04-25 02:04:01 +10:00
|
|
|
"vis" => token::NtVis(panictry!(p.parse_visibility(true))),
|
2017-05-11 22:59:48 +00:00
|
|
|
"lifetime" => token::NtLifetime(p.expect_lifetime()),
|
2016-05-18 15:08:19 +02:00
|
|
|
// this is not supposed to happen, since it has been checked
|
|
|
|
// when compiling the macro.
|
2018-01-19 19:00:29 -06:00
|
|
|
_ => p.span_bug(sp, "invalid fragment specifier"),
|
2012-06-12 10:59:50 -07:00
|
|
|
}
|
|
|
|
}
|