pub use self::NamedMatch::*;
pub use self::ParseResult::*;
use self::TokenTreeOrTokenTreeVec::*;
use crate::ast::Ident;
use crate::codemap::Spanned;
use crate::errors::FatalError;
use crate::ext::tt::quoted::{self, TokenTree};
use crate::parse::parser::{Parser, PathStyle};
use crate::parse::token::{self, DocComment, Nonterminal, Token};
use crate::parse::{Directory, ParseSess};
use crate::print::pprust;
use crate::symbol::keywords;
use crate::syntax_pos::{self, BytePos, Span};
use crate::tokenstream::TokenStream;
use crate::util::small_vector::SmallVector;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
#[derive(Clone)]
enum TokenTreeOrTokenTreeVec {
Tt(TokenTree),
TtSeq(Vec<TokenTree>),
}
impl TokenTreeOrTokenTreeVec {
fn len(&self) -> usize {
match *self {
TtSeq(ref v) => v.len(),
Tt(ref tt) => tt.len(),
}
}
fn get_tt(&self, index: usize) -> TokenTree {
match *self {
TtSeq(ref v) => v[index].clone(),
Tt(ref tt) => tt.get_tt(index),
}
}
}
#[derive(Clone)]
struct MatcherTtFrame {
elts: TokenTreeOrTokenTreeVec,
idx: usize,
}
#[derive(Clone)]
struct MatcherPos {
stack: Vec<MatcherTtFrame>,
top_elts: TokenTreeOrTokenTreeVec,
sep: Option<Token>,
idx: usize,
up: Option<Box<MatcherPos>>,
matches: Vec<Vec<Rc<NamedMatch>>>,
match_lo: usize,
match_cur: usize,
match_hi: usize,
sp_lo: BytePos,
}
pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
pub fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, |count, elt| {
count
+ match *elt {
TokenTree::Sequence(_, ref seq) => seq.num_captures,
TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
TokenTree::MetaVarDecl(..) => 1,
TokenTree::Token(..) => 0,
}
})
}
fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
let match_idx_hi = count_names(&ms[..]);
let matches = create_matches(match_idx_hi);
Box::new(MatcherPos {
stack: vec![],
top_elts: TtSeq(ms),
sep: None,
idx: 0,
up: None,
matches: matches,
match_lo: 0,
match_cur: 0,
match_hi: match_idx_hi,
sp_lo: lo,
})
}
pub enum NamedMatch {
MatchedSeq(Vec<Rc<NamedMatch>>, syntax_pos::Span),
MatchedNonterminal(Rc<Nonterminal>),
}
fn nameize<I: Iterator<Item = Rc<NamedMatch>>>(
sess: &ParseSess,
ms: &[TokenTree],
mut res: I,
) -> NamedParseResult {
fn n_rec<I: Iterator<Item = Rc<NamedMatch>>>(
sess: &ParseSess,
m: &TokenTree,
res: &mut I,
ret_val: &mut HashMap<Ident, Rc<NamedMatch>>,
) -> Result<(), (syntax_pos::Span, String)> {
match *m {
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)?;
}
}
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()));
}
}
TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val.entry(bind_name) {
Vacant(spot) => {
spot.insert(res.next().unwrap());
}
Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))),
},
TokenTree::Token(..) => (),
}
Ok(())
}
let mut ret_val = HashMap::new();
for m in ms {
match n_rec(sess, m, res.by_ref(), &mut ret_val) {
Ok(_) => {}
Err((sp, msg)) => return Error(sp, msg),
}
}
Success(ret_val)
}
pub enum ParseResult<T> {
Success(T),
Failure(syntax_pos::Span, Token),
Error(syntax_pos::Span, String),
}
pub fn parse_failure_msg(tok: Token) -> String {
match tok {
token::Eof => "unexpected end of macro invocation".to_string(),
_ => format!(
"no rules expected the token `{}`",
pprust::token_to_string(&tok)
),
}
}
fn token_name_eq(t1: &Token, t2: &Token) -> bool {
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
}
}
fn create_matches(len: usize) -> Vec<Vec<Rc<NamedMatch>>> {
(0..len).into_iter().map(|_| Vec::new()).collect()
}
fn inner_parse_loop(
sess: &ParseSess,
cur_eis: &mut SmallVector<Box<MatcherPos>>,
next_eis: &mut Vec<Box<MatcherPos>>,
eof_eis: &mut SmallVector<Box<MatcherPos>>,
bb_eis: &mut SmallVector<Box<MatcherPos>>,
token: &Token,
span: syntax_pos::Span,
) -> ParseResult<()> {
while let Some(mut ei) = cur_eis.pop() {
while ei.idx >= ei.top_elts.len() {
match ei.stack.pop() {
Some(MatcherTtFrame { elts, idx }) => {
ei.top_elts = elts;
ei.idx = idx + 1;
}
None => break,
}
}
let idx = ei.idx;
let len = ei.top_elts.len();
if idx >= len {
if ei.up.is_some() {
if idx == len {
let mut new_pos = ei.up.clone().unwrap();
for idx in ei.match_lo..ei.match_hi {
let sub = ei.matches[idx].clone();
new_pos.matches[idx].push(Rc::new(MatchedSeq(
sub,
Span {
lo: ei.sp_lo,
..span
},
)));
}
new_pos.match_cur = ei.match_hi;
new_pos.idx += 1;
cur_eis.push(new_pos);
}
if idx == len && ei.sep.is_some() {
if ei
.sep
.as_ref()
.map(|sep| token_name_eq(token, sep))
.unwrap_or(false)
{
ei.idx += 1;
next_eis.push(ei);
}
} else {
ei.match_cur = ei.match_lo;
ei.idx = 0;
cur_eis.push(ei);
}
} else {
eof_eis.push(ei);
}
} else {
match ei.top_elts.get_tt(idx) {
TokenTree::Sequence(sp, seq) => {
if seq.op == quoted::KleeneOp::ZeroOrMore {
let mut new_ei = ei.clone();
new_ei.match_cur += seq.num_captures;
new_ei.idx += 1;
for idx in ei.match_cur..ei.match_cur + seq.num_captures {
new_ei.matches[idx].push(Rc::new(MatchedSeq(vec![], sp)));
}
cur_eis.push(new_ei);
}
let matches = create_matches(ei.matches.len());
cur_eis.push(Box::new(MatcherPos {
stack: vec![],
sep: seq.separator.clone(),
idx: 0,
matches: matches,
match_lo: ei.match_cur,
match_cur: ei.match_cur,
match_hi: ei.match_cur + seq.num_captures,
up: Some(ei),
sp_lo: sp.lo,
top_elts: Tt(TokenTree::Sequence(sp, seq)),
}));
}
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());
}
}
TokenTree::MetaVarDecl(..) => {
match *token {
token::CloseDelim(_) => {}
_ => bb_eis.push(ei),
}
}
seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));
let idx = ei.idx;
ei.stack.push(MatcherTtFrame {
elts: lower_elts,
idx: idx,
});
ei.idx = 0;
cur_eis.push(ei);
}
TokenTree::Token(_, ref t) => {
if token_name_eq(t, token) {
ei.idx += 1;
next_eis.push(ei);
}
}
}
}
}
Success(())
}
pub fn parse(
sess: &ParseSess,
tts: TokenStream,
ms: &[TokenTree],
directory: Option<Directory>,
recurse_into_modules: bool,
) -> NamedParseResult {
let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
let mut cur_eis = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo));
let mut next_eis = Vec::new();
loop {
let mut bb_eis = SmallVector::new(); let mut eof_eis = SmallVector::new();
assert!(next_eis.is_empty());
match inner_parse_loop(
sess,
&mut cur_eis,
&mut next_eis,
&mut eof_eis,
&mut bb_eis,
&parser.token,
parser.span,
) {
Success(_) => {}
Failure(sp, tok) => return Failure(sp, tok),
Error(sp, msg) => return Error(sp, msg),
}
assert!(cur_eis.is_empty());
if token_name_eq(&parser.token, &token::Eof) {
if eof_eis.len() == 1 {
let matches = eof_eis[0].matches.iter_mut().map(|dv| dv.pop().unwrap());
return nameize(sess, ms, matches);
} else if eof_eis.len() > 1 {
return Error(
parser.span,
"ambiguity: multiple successful parses".to_string(),
);
} else {
return Failure(parser.span, token::Eof);
}
} else if (!bb_eis.is_empty() && !next_eis.is_empty()) || bb_eis.len() > 1 {
let nts = bb_eis
.iter()
.map(|ei| match ei.top_elts.get_tt(ei.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_eis.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),
}
),
);
} else if bb_eis.is_empty() && next_eis.is_empty() {
return Failure(parser.span, parser.token);
} else if !next_eis.is_empty() {
cur_eis.extend(next_eis.drain(..));
parser.bump();
} else
{
let mut ei = bb_eis.pop().unwrap();
if let TokenTree::MetaVarDecl(span, _, ident) = ei.top_elts.get_tt(ei.idx) {
let match_cur = ei.match_cur;
ei.matches[match_cur].push(Rc::new(MatchedNonterminal(Rc::new(parse_nt(
&mut parser,
span,
&ident.name.as_str(),
)))));
ei.idx += 1;
ei.match_cur += 1;
} else {
unreachable!()
}
cur_eis.push(ei);
}
assert!(!cur_eis.is_empty());
}
}
fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
if name == "tt" {
return token::NtTT(p.parse_token_tree());
}
p.process_potential_macro_variable();
match name {
"item" => match panictry!(p.parse_item()) {
Some(i) => token::NtItem(i),
None => {
p.fatal("expected an item keyword").emit();
panic!(FatalError);
}
},
"block" => token::NtBlock(panictry!(p.parse_block())),
"stmt" => match panictry!(p.parse_stmt()) {
Some(s) => token::NtStmt(s),
None => {
p.fatal("expected a statement").emit();
panic!(FatalError);
}
},
"pat" => token::NtPat(panictry!(p.parse_pat())),
"expr" => token::NtExpr(panictry!(p.parse_expr())),
"ty" => token::NtTy(panictry!(p.parse_ty())),
"ident" => match p.token {
token::Ident(sn) => {
p.bump();
token::NtIdent(Spanned::<Ident> {
node: sn,
span: p.prev_span,
})
}
_ => {
let token_str = pprust::token_to_string(&p.token);
p.fatal(&format!("expected ident, found {}", &token_str[..]))
.emit();
panic!(FatalError)
}
},
"path" => token::NtPath(panictry!(p.parse_path(PathStyle::Type))),
"meta" => token::NtMeta(panictry!(p.parse_meta_item())),
"vis" => token::NtVis(panictry!(p.parse_visibility(true))),
_ => p.span_bug(sp, "invalid fragment specifier"),
}
}