syntex_syntax 0.9.0

Export of libsyntax for code generation
b0VIM 7.4�U]~ericktErick-Tryzelaar-MBP.local~erickt/projects/rust/rust-syntex/syntex_syntax/src/ext/tt/macro_parser.rsutf-8
3210#"! UtpXvYi�T8O�M�ad3�X�{XU��M)(�
�
5
��I��c�
�
�
�
�
<
�	�	�	D	@	��N��vr/+
������b0,���LH�����B>����NJ&"
�������e8����use parse::attr::ParserAttr;use parse::ParseSess;use parse::lexer::*; //resolve bug?use codemap;use codemap::{BytePos, mk_sp, Span};use ast::{TtDelimited, TtSequence, TtToken};use ast::{TokenTree, Ident};use ast;use self::TokenTreeOrTokenTreeVec::*;pub use self::ParseResult::*;pub use self::NamedMatch::*;//! eof: [a $( a )* a b ·]//! Remaining input: ``//!//! - - - Advance over a `b`. - - -//!//! next: [a $( a )* · a b]  [a $( · a )* a b]//! Finish/Repeat (first item)//! cur: [a $( a · )* a b]  next: [a $( a )* a · b]//! Remaining input: `b`//!//! - - - Advance over an `a`. - - - (this looks exactly like the last step)//!//! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]//! Finish/Repeat (first item)//! cur: [a $( a · )* a b]  next: [a $( a )* a · b]//! Remaining input: `a b`//!//! - - - Advance over an `a`. - - - (this looks exactly like the last step)//!//! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]//! Finish/Repeat (first item)//! cur: [a $( a · )* a b]  next: [a $( a )* a · b]//! Remaining input: `a a b`//!//! - - - Advance over an `a`. - - -//!//! next: [a $( · a )* a b]  [a $( a )* · a b].//! Descend/Skip (first item).//! cur: [a · $( a )* a b]//! Remaining input: `a a a b`//!//! - - - Advance over an `a`. - - -//!//! next_eis: [· a $( a )* a b]//! Remaining input: `a a a a b`//!//! Example: Start parsing `a a a a b` against [· a $( a )* a b].//!//! real Rust parser when no `cur_eis` items remain//! repetitions indicated by Kleene stars. It only advances or calls out to the//! on the a particular token. Most of the logic concerns moving the · through the//! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting//! the macro invocation is now over, `bb_eis` with items that are waiting on//! As it processes them, it fills up `eof_eis` with items that would be valid if//!//! of items consistent with the current position in the input string: `cur_eis`.//! The parser walks through the input a character at a time, maintaining a list//!//! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.//! A 'position' is a dot in the middle of a matcher, usually represented as a//!//! Quick intro to how the parser works://!//! overhead)//! and require more memory to keep around old items, but it would also save//! construct the resulting `NamedMatch`es at the very end. It'd be a pain,//! lower. (In order to prevent the pathological case, we'd need to lazily//! easier fit for Macro-by-Example-style rules, and I think the overhead is//! pathological cases, is worse than traditional Earley parsing, but it's an//! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in//! token: instead, there's a set of current Earley items and a set of next//! completer or predictor rules, and therefore no need to store one column per//! commits to fully when it hits one in a grammar). This means that there are no//! only by calling out to the main rust parser for named nonterminals (which it//! This is an Earley-like parser, without support for in-grammar nonterminals,// except according to those terms.// option. This file may not be copied, modified, or distributed// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or//// http://rust-lang.org/COPYRIGHT.// file at the top-level directory of this distribution and at// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHTadT�M���d7���r4�
]
<


����rD2$�������0�
�
�
�
�
�
M


�	�	�	z	=		����U,��xi*�����>6��0������}    }      }                             and `item`"))                             `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \                            "valid fragment specifiers are `ident`, `block`, \                            &format!("invalid fragment specifier `{}`", name),          panic!(p.span_fatal_help(sp,      _ => {      "meta" => token::NtMeta(p.parse_meta_item()),      }        token::NtPath(Box::new(panictry!(p.parse_path(LifetimeAndTypesWithoutColons))))      "path" => {      },        }                             &token_str[..])))            panic!(p.fatal(&format!("expected ident, found {}",            let token_str = pprust::token_to_string(&p.token);        _ => {        token::Ident(sn,b) => { panictry!(p.bump()); token::NtIdent(Box::new(sn),b) }      "ident" => match p.token {      // this could be handled like a token, since it is one      "ty" => token::NtTy(p.parse_ty()),      "expr" => token::NtExpr(p.parse_expr()),      "pat" => token::NtPat(p.parse_pat()),      },        None => panic!(p.fatal("expected a statement"))        Some(s) => token::NtStmt(s),      "stmt" => match p.parse_stmt() {      "block" => token::NtBlock(panictry!(p.parse_block())),      },        None => panic!(p.fatal("expected an item keyword"))        Some(i) => token::NtItem(i),      "item" => match p.parse_item() {    match name {    panictry!(p.check_unknown_macro_variable());    // check at the beginning and the parser checks after each bump    }        _ => {}        }            return res;            p.quote_depth -= 1;            let res = token::NtTT(P(panictry!(p.parse_token_tree())));            p.quote_depth += 1; //but in theory, non-quoted tts might be useful        "tt" => {    match name {pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal {}    }        assert!(!cur_eis.is_empty());        }            }                }                    let _ = rdr.next_token();                for _ in 0..rust_parser.tokens_consumed {                cur_eis.push(ei);                }                  _ => panic!()                  }                    ei.match_cur += 1;                    ei.idx += 1;                        parse_nt(&mut rust_parser, span, &ident.name.as_str()))));                    (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal(                    let match_cur = ei.match_cur;                  TtToken(span, MatchNt(_, ident, _, _)) => {                match ei.top_elts.get_tt(ei.idx) {                let mut ei = bb_eis.pop().unwrap();                let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone()));            } else /* bb_eis.len() == 1 */ {                rdr.next_token();                }                    cur_eis.push(next_eis.pop().unwrap());                while !next_eis.is_empty() {ad+�O��b7���w@�
�
�
b
E
/
��fB
���v	�
e
;

�	�	�	p	F	0		��tC)����lH ���i?��}o^"���Q��o-��y*����                /* Now process the next token */            } else if !next_eis.is_empty() {                            pprust::token_to_string(&tok)).to_string());                return Failure(sp, format!("no rules expected the token `{}`",            } else if bb_eis.is_empty() && next_eis.is_empty() {                    nts, next_eis.len()).to_string());                     built-in NTs {} or {} other options.",                    "local ambiguity: multiple parsing options: \                return Error(sp, format!(                    } }).collect::<Vec<String>>().connect(" or ");                      _ => panic!()                      }                        format!("{} ('{}')", name, bind)                      TtToken(_, MatchNt(bind, name, _, _)) => {                    match ei.top_elts.get_tt(ei.idx) {                let nts = bb_eis.iter().map(|ei| {                || bb_eis.len() > 1 {            if (!bb_eis.is_empty() && !next_eis.is_empty())        } else {            }                return Failure(sp, "unexpected end of macro invocation".to_string());            } else {                return Error(sp, "ambiguity: multiple successful parses".to_string());            } else if eof_eis.len() > 1 {                return Success(nameize(sess, ms, &v[..]));                }                    v.push(dv.pop().unwrap());                for dv in &mut (&mut eof_eis[0]).matches {                let mut v = Vec::new();            if eof_eis.len() == 1 {        if token_name_eq(&tok, &token::Eof) {        /* error messages here could be improved with links to orig. rules */        }            }                }                    }                        }                            next_eis.push(ei_t);                            ei_t.idx += 1;                        if token_name_eq(t,&tok) {                        let mut ei_t = ei.clone();                    TtToken(_, ref t) => {                    }                        cur_eis.push(ei);                        ei.idx = 0;                        });                            idx: idx,                            elts: lower_elts,                        ei.stack.push(MatcherTtFrame {                        let idx = ei.idx;                        let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));                    seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => {                    }                        return Error(sp, "Cannot transcribe in macro LHS".to_string())                    TtToken(sp, SubstNt(..)) => {                    }                        }                            _ => bb_eis.push(ei),                            token::CloseDelim(_) => {},                        match tok {                        // so we can eliminate them from consideration.                        // Built-in nonterminals never start with these tokens,                    TtToken(_, MatchNt(..)) => {                    }                        }));                            top_elts: Tt(TtSequence(sp, seq)),                            sp_lo: sp.lo,                            up: Some(ei_t),                            match_hi: ei_t.match_cur + seq.num_captures,                            match_cur: ei_t.match_cur,                            match_lo: ei_t.match_cur,                            matches: matches,                            idx: 0,                            sep: seq.separator.clone(),                            stack: vec![],                        cur_eis.push(Box::new(MatcherPos {                        let ei_t = ei;                            .map(|_| Vec::new()).collect();adOCv��eS@43%���mYXG(�
�
�
�
�
�
r
M
C
=
<


�������eT<	����~nM&�
�
�
�
�
�
z
^
5


�	�	�	z	h	Z	9	/	(	&	%	��t)������xbB0)'&��K��k"�k&��ts])��CB    fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>],            -> HashMap<Ident, Rc<NamedMatch>> {pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>])}    MatchedNonterminal(Nonterminal)    MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),pub enum NamedMatch {/// token tree it was derived from./// only on the nesting depth of `ast::TTSeq`s in the originating/// token tree. The depth of the NamedMatch structure will therefore depend/// each MatchedSeq corresponds to a single TTSeq in the originating/// `MatchedNonterminal`s, will depend on the token tree it was applied to:/// The width of each MatchedSeq in the NamedMatch, and the identity of the////// particular token tree./// that occurred when a particular subset of a matcher was applied to a/// The in-memory structure of a particular NamedMatch represents the match////// single token::MATCH_NONTERMINAL in the TokenTree that produced it./// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a/// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type/// so it is associated with a single ident in a parse, and all/// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL:}    })        sp_lo: lo        match_hi: match_idx_hi,        match_cur: 0,        match_lo: 0,        matches: matches,        up: None,        idx: 0,        sep: sep,        top_elts: TtSeq(ms),        stack: vec![],    Box::new(MatcherPos {    let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect();    let match_idx_hi = count_names(&ms[..]);                           -> Box<MatcherPos> {pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos)}    })        }            &TtToken(_, _) => 0,            }                1            &TtToken(_, MatchNt(..)) => {            }                count_names(&delim.tts)            &TtDelimited(_, ref delim) => {            }                seq.num_captures            &TtSequence(_, ref seq) => {        count + match elt {    ms.iter().fold(0, |count, elt| {pub fn count_names(ms: &[TokenTree]) -> usize {}    sp_lo: BytePos,    match_hi: usize,    match_cur: usize,    match_lo: usize,    matches: Vec<Vec<Rc<NamedMatch>>>,    up: Option<Box<MatcherPos>>,    idx: usize,    sep: Option<Token>,    top_elts: TokenTreeOrTokenTreeVec,    stack: Vec<MatcherTtFrame>,pub struct MatcherPos {#[derive(Clone)]}    idx: usize,    elts: TokenTreeOrTokenTreeVec,struct MatcherTtFrame {#[derive(Clone)]/// an unzipping of `TokenTree`s}    }        }            &Tt(ref tt) => tt.get_tt(index),            &TtSeq(ref v) => v[index].clone(),        match self {    fn get_tt(&self, index: usize) -> TokenTree {    }        }            &Tt(ref tt) => tt.len(),            &TtSeq(ref v) => v.len(),        match self {    fn len(&self) -> usize {impl TokenTreeOrTokenTreeVec {}    TtSeq(Rc<Vec<ast::TokenTree>>),    Tt(ast::TokenTree),enum TokenTreeOrTokenTreeVec {#[derive(Clone)]// a nonempty body.// To avoid costly uniqueness checks, we require that `MatchSeq` always hasuse std::collections::hash_map::Entry::{Vacant, Occupied};use std::collections::HashMap;use std::rc::Rc;use std::mem;use ptr::P;use print::pprust;use parse::token;use parse::token::{Token, Nonterminal};use parse::token::{Eof, DocComment, MatchNt, SubstNt};use parse::parser::{LifetimeAndTypesWithoutColons, Parser};ad�i��wN���cQC�
�
y
V
@

��p4�����_J�
�
�
�
�
�
�
�
�
A
�	�	�	�	�	\	#	���uY
��gS�������^>���i,���v8����i/���t8���                    }                        ei.idx = idx + 1;                        ei.top_elts = elts;                    Some(MatcherTtFrame { elts, idx }) => {                match ei.stack.pop() {            while ei.idx >= ei.top_elts.len() {            // When unzipped trees end, remove them            };                Some(ei) => ei,                None => break, /* for each Earley Item */            let mut ei = match cur_eis.pop() {        loop {        /* we append new items to this while we go */        let TokenAndSpan { tok, sp } = rdr.peek();        let mut eof_eis = Vec::new();        let mut next_eis = Vec::new(); // or proceed normally        let mut bb_eis = Vec::new(); // black-box parsed by parser.rs    loop {                                     rdr.peek().sp.lo));                                     None,                                                .collect()),                                                .cloned()    cur_eis.push(initial_matcher_pos(Rc::new(ms.iter()    let mut cur_eis = Vec::new();             -> NamedParseResult {             ms: &[TokenTree])             mut rdr: TtReader,             cfg: ast::CrateConfig,pub fn parse(sess: &ParseSess,}    }        _ => *t1 == *t2            id1.name == id2.name,        | (&token::Lifetime(id1),&token::Lifetime(id2)) =>        (&token::Ident(id1,_),&token::Ident(id2,_))    match (t1,t2) {pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {/// unhygienic comparison)/// Perform a token equality check, ignoring syntax context (that is, an}    }        }            panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))        Error(sp, str) => {        }            panic!(sess.span_diagnostic.span_fatal(sp, &str[..]))        Failure(sp, str) => {        Success(m) => m,    match parse(sess, cfg, rdr, &ms[..]) {                     -> HashMap<Ident, Rc<NamedMatch>> {                     ms: Vec<TokenTree> )                     rdr: TtReader,                     cfg: ast::CrateConfig,pub fn parse_or_else(sess: &ParseSess,pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>;pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;}    Error(codemap::Span, String)    Failure(codemap::Span, String),    Success(T),pub enum ParseResult<T> {}    ret_val    for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) }    let mut idx = 0;    let mut ret_val = HashMap::new();    }        }            &TtToken(_, _) => (),            &TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"),            }                }                    }                                               bind_name)))                                       &format!("duplicated bind name: {}",                           .span_fatal(sp,                        panic!(p_s.span_diagnostic                    Occupied(..) => {                    }                        *idx += 1;                        spot.insert(res[*idx].clone());                    Vacant(spot) => {                match ret_val.entry(bind_name) {            &TtToken(sp, MatchNt(bind_name, _, _, _)) => {            }                }                    n_rec(p_s, next_m, res, ret_val, idx)                for next_m in &delim.tts {            &TtDelimited(_, ref delim) => {            }                }                    n_rec(p_s, next_m, res, ret_val, idx)                for next_m in &seq.tts {            &TtSequence(_, ref seq) => {        match m {             ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) {ad�T�����vuP4��ONM�
�
o
n
,
+
���]���Y�
�
=
#
"
�	�	�	z	y	J	I	���1��R��pR8���g7����q9��Z-��0����                        let matches: Vec<_> = (0..ei.matches.len())                        }                            cur_eis.push(new_ei);                            }                                (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp)));                            for idx in ei.match_cur..ei.match_cur + seq.num_captures {                            //we specifically matched zero repeats.                            new_ei.idx += 1;                            new_ei.match_cur += seq.num_captures;                            let mut new_ei = ei.clone();                        if seq.op == ast::ZeroOrMore {                    TtSequence(sp, seq) => {                    /* need to descend into sequence */                match ei.top_elts.get_tt(idx) {            } else {                }                    eof_eis.push(ei);                } else {                    }                        }                            cur_eis.push(ei_t);                            ei_t.idx = 0;                            ei_t.match_cur = ei_t.match_lo;                            let mut ei_t = ei;                        _ => { // we don't need a separator                        }                            }                                next_eis.push(ei_t);                                ei_t.idx += 1;                                // ei_t.match_cur = ei_t.match_lo;                                let mut ei_t = ei.clone();                            if token_name_eq(&tok, t) { //pass the separator                            // idents, it shouldn't matter.                            // though in this case, if the separators are never legal                            // i'm conflicted about whether this should be hygienic....                        Some(ref t) if idx == len => { // we need a separator                    match ei.sep {                    // the *_t vars are workarounds for the lack of unary move                    // can we go around again?                    }                        cur_eis.push(new_pos);                        new_pos.idx += 1;                        new_pos.match_cur = ei.match_hi;                        }                                                                       sp.hi))));                                   .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,                            (&mut new_pos.matches[idx])                            let sub = (ei.matches[idx]).clone();                        for idx in ei.match_lo..ei.match_hi {                        // Only touch the binders we have actually bound                        // most of the time.                        // doing a lot of array work that will get thrown away                        // I bet this is a perf problem: we're preemptively                        // each tree as a subtree.                        // update matches (the MBE "parse tree") by appending                        let mut new_pos = ei.up.clone().unwrap();                        // pop from the matcher position                    if idx == len {                    // (remove this condition to make trailing seps ok)                    // disregard separator, try to go up                    // parent (the top level is just a container)                    // hack: a matcher sequence is repeating iff it has a                if ei.up.is_some() {                // can't move out of `match`es, so:            if idx >= len {            /* at end of sequence */            let len = ei.top_elts.len();            let idx = ei.idx;            }                }                    None => break