Skip to content

Commit

Permalink
pull mbe token tree definition up
Browse files Browse the repository at this point in the history
  • Loading branch information
matklad committed Sep 22, 2019
1 parent 636b354 commit 9fd75f5
Show file tree
Hide file tree
Showing 7 changed files with 243 additions and 234 deletions.
156 changes: 156 additions & 0 deletions src/libsyntax/ext/mbe.rs
Expand Up @@ -8,3 +8,159 @@ crate mod macro_check;
crate mod macro_parser;
crate mod macro_rules;
crate mod quoted;

use crate::ast;
use crate::parse::token::{self, Token, TokenKind};
use crate::tokenstream::{DelimSpan};

use syntax_pos::{BytePos, Span};

use rustc_data_structures::sync::Lrc;

/// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
/// that the delimiter itself might be `NoDelim`.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
crate struct Delimited {
crate delim: token::DelimToken,
crate tts: Vec<TokenTree>,
}

impl Delimited {
/// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
crate fn open_tt(&self, span: Span) -> TokenTree {
let open_span = if span.is_dummy() {
span
} else {
span.with_hi(span.lo() + BytePos(self.delim.len() as u32))
};
TokenTree::token(token::OpenDelim(self.delim), open_span)
}

/// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
crate fn close_tt(&self, span: Span) -> TokenTree {
let close_span = if span.is_dummy() {
span
} else {
span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
};
TokenTree::token(token::CloseDelim(self.delim), close_span)
}
}

#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
crate struct SequenceRepetition {
/// The sequence of token trees
crate tts: Vec<TokenTree>,
/// The optional separator
crate separator: Option<Token>,
/// Whether the sequence can be repeated zero (*), or one or more times (+)
crate kleene: KleeneToken,
/// The number of `Match`s that appear in the sequence (and subsequences)
crate num_captures: usize,
}

#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
crate struct KleeneToken {
crate span: Span,
crate op: KleeneOp,
}

impl KleeneToken {
crate fn new(op: KleeneOp, span: Span) -> KleeneToken {
KleeneToken { span, op }
}
}

/// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
/// for token sequences.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
crate enum KleeneOp {
/// Kleene star (`*`) for zero or more repetitions
ZeroOrMore,
/// Kleene plus (`+`) for one or more repetitions
OneOrMore,
/// Kleene optional (`?`) for zero or one reptitions
ZeroOrOne,
}

/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
/// are "first-class" token trees. Useful for parsing macros.
#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
crate enum TokenTree {
Token(Token),
Delimited(DelimSpan, Lrc<Delimited>),
/// A kleene-style repetition sequence
Sequence(DelimSpan, Lrc<SequenceRepetition>),
/// e.g., `$var`
MetaVar(Span, ast::Ident),
/// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
MetaVarDecl(
Span,
ast::Ident, /* name to bind */
ast::Ident, /* kind of nonterminal */
),
}

impl TokenTree {
/// Return the number of tokens in the tree.
crate fn len(&self) -> usize {
match *self {
TokenTree::Delimited(_, ref delimed) => match delimed.delim {
token::NoDelim => delimed.tts.len(),
_ => delimed.tts.len() + 2,
},
TokenTree::Sequence(_, ref seq) => seq.tts.len(),
_ => 0,
}
}

/// Returns `true` if the given token tree is delimited.
crate fn is_delimited(&self) -> bool {
match *self {
TokenTree::Delimited(..) => true,
_ => false,
}
}

/// Returns `true` if the given token tree is a token of the given kind.
crate fn is_token(&self, expected_kind: &TokenKind) -> bool {
match self {
TokenTree::Token(Token { kind: actual_kind, .. }) => actual_kind == expected_kind,
_ => false,
}
}

/// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
crate fn get_tt(&self, index: usize) -> TokenTree {
match (self, index) {
(&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
delimed.tts[index].clone()
}
(&TokenTree::Delimited(span, ref delimed), _) => {
if index == 0 {
return delimed.open_tt(span.open);
}
if index == delimed.tts.len() + 1 {
return delimed.close_tt(span.close);
}
delimed.tts[index - 1].clone()
}
(&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
_ => panic!("Cannot expand a token tree"),
}
}

/// Retrieves the `TokenTree`'s span.
crate fn span(&self) -> Span {
match *self {
TokenTree::Token(Token { span, .. })
| TokenTree::MetaVar(span, _)
| TokenTree::MetaVarDecl(span, _, _) => span,
TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(),
}
}

crate fn token(kind: TokenKind, span: Span) -> TokenTree {
TokenTree::Token(Token::new(kind, span))
}
}
2 changes: 1 addition & 1 deletion src/libsyntax/ext/mbe/macro_check.rs
Expand Up @@ -106,7 +106,7 @@
//! bound.
use crate::ast::NodeId;
use crate::early_buffered_lints::BufferedEarlyLintId;
use crate::ext::mbe::quoted::{KleeneToken, TokenTree};
use crate::ext::mbe::{KleeneToken, TokenTree};
use crate::parse::token::TokenKind;
use crate::parse::token::{DelimToken, Token};
use crate::parse::ParseSess;
Expand Down
10 changes: 5 additions & 5 deletions src/libsyntax/ext/mbe/macro_parser.rs
Expand Up @@ -75,7 +75,7 @@ crate use ParseResult::*;
use TokenTreeOrTokenTreeSlice::*;

use crate::ast::{Ident, Name};
use crate::ext::mbe::quoted::{self, TokenTree};
use crate::ext::mbe::{self, TokenTree};
use crate::parse::{Directory, ParseSess};
use crate::parse::parser::{Parser, PathStyle};
use crate::parse::token::{self, DocComment, Nonterminal, Token};
Expand Down Expand Up @@ -195,7 +195,7 @@ struct MatcherPos<'root, 'tt> {
// `None`.

/// The KleeneOp of this sequence if we are in a repetition.
seq_op: Option<quoted::KleeneOp>,
seq_op: Option<mbe::KleeneOp>,

/// The separator if we are in a repetition.
sep: Option<Token>,
Expand Down Expand Up @@ -532,7 +532,7 @@ fn inner_parse_loop<'root, 'tt>(
}
// We don't need a separator. Move the "dot" back to the beginning of the matcher
// and try to match again UNLESS we are only allowed to have _one_ repetition.
else if item.seq_op != Some(quoted::KleeneOp::ZeroOrOne) {
else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) {
item.match_cur = item.match_lo;
item.idx = 0;
cur_items.push(item);
Expand All @@ -555,8 +555,8 @@ fn inner_parse_loop<'root, 'tt>(
// implicitly disallowing OneOrMore from having 0 matches here. Thus, that will
// result in a "no rules expected token" error by virtue of this matcher not
// working.
if seq.kleene.op == quoted::KleeneOp::ZeroOrMore
|| seq.kleene.op == quoted::KleeneOp::ZeroOrOne
if seq.kleene.op == mbe::KleeneOp::ZeroOrMore
|| seq.kleene.op == mbe::KleeneOp::ZeroOrOne
{
let mut new_item = item.clone();
new_item.match_cur += seq.num_captures;
Expand Down

0 comments on commit 9fd75f5

Please sign in to comment.