pub use self::TyParamBound::*;
pub use self::UnsafeSource::*;
pub use self::ViewPath_::*;
pub use self::PathParameters::*;
use attr::ThinAttributes;
use codemap::{Span, Spanned, DUMMY_SP, ExpnId};
use abi::Abi;
use errors;
use ext::base;
use ext::tt::macro_parser;
use parse::token::InternedString;
use parse::token;
use parse::lexer;
use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
use print::pprust;
use ptr::P;
use std::fmt;
use std::rc::Rc;
use std::hash::{Hash, Hasher};
use serialize::{Encodable, Decodable, Encoder, Decoder};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Name(pub u32);
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
pub struct SyntaxContext(pub u32);
#[derive(Clone, Copy, Eq)]
pub struct Ident {
pub name: Name,
pub ctxt: SyntaxContext
}
impl Name {
pub fn as_str(self) -> token::InternedString {
token::InternedString::new_from_name(self)
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self, self.0)
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl Encodable for Name {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_str(&self.as_str())
}
}
impl Decodable for Name {
fn decode<D: Decoder>(d: &mut D) -> Result<Name, D::Error> {
Ok(token::intern(&d.read_str()?[..]))
}
}
pub const EMPTY_CTXT : SyntaxContext = SyntaxContext(0);
impl Ident {
pub fn new(name: Name, ctxt: SyntaxContext) -> Ident {
Ident {name: name, ctxt: ctxt}
}
pub fn with_empty_ctxt(name: Name) -> Ident {
Ident {name: name, ctxt: EMPTY_CTXT}
}
}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
if self.ctxt != other.ctxt {
panic!("idents with different contexts are compared with operator `==`: \
{:?}, {:?}.", self, other);
}
self.name == other.name
}
}
impl Hash for Ident {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state)
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}#{}", self.name, self.ctxt.0)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
impl Encodable for Ident {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
self.name.encode(s)
}
}
impl Decodable for Ident {
fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
Ok(Ident::with_empty_ctxt(Name::decode(d)?))
}
}
pub type Mrk = u32;
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub struct Lifetime {
pub id: NodeId,
pub span: Span,
pub name: Name
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct LifetimeDef {
pub lifetime: Lifetime,
pub bounds: Vec<Lifetime>
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub struct Path {
pub span: Span,
pub global: bool,
pub segments: Vec<PathSegment>,
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", pprust::path_to_string(self))
}
}
impl Path {
pub fn from_ident(s: Span, identifier: Ident) -> Path {
Path {
span: s,
global: false,
segments: vec!(
PathSegment {
identifier: identifier,
parameters: PathParameters::none()
}
),
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct PathSegment {
pub identifier: Ident,
pub parameters: PathParameters,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum PathParameters {
AngleBracketed(AngleBracketedParameterData),
Parenthesized(ParenthesizedParameterData),
}
impl PathParameters {
pub fn none() -> PathParameters {
PathParameters::AngleBracketed(AngleBracketedParameterData {
lifetimes: Vec::new(),
types: P::empty(),
bindings: P::empty(),
})
}
pub fn is_empty(&self) -> bool {
match *self {
PathParameters::AngleBracketed(ref data) => data.is_empty(),
PathParameters::Parenthesized(..) => false,
}
}
pub fn has_lifetimes(&self) -> bool {
match *self {
PathParameters::AngleBracketed(ref data) => !data.lifetimes.is_empty(),
PathParameters::Parenthesized(_) => false,
}
}
pub fn has_types(&self) -> bool {
match *self {
PathParameters::AngleBracketed(ref data) => !data.types.is_empty(),
PathParameters::Parenthesized(..) => true,
}
}
pub fn types(&self) -> Vec<&P<Ty>> {
match *self {
PathParameters::AngleBracketed(ref data) => {
data.types.iter().collect()
}
PathParameters::Parenthesized(ref data) => {
data.inputs.iter()
.chain(data.output.iter())
.collect()
}
}
}
pub fn lifetimes(&self) -> Vec<&Lifetime> {
match *self {
PathParameters::AngleBracketed(ref data) => {
data.lifetimes.iter().collect()
}
PathParameters::Parenthesized(_) => {
Vec::new()
}
}
}
pub fn bindings(&self) -> Vec<&TypeBinding> {
match *self {
PathParameters::AngleBracketed(ref data) => {
data.bindings.iter().collect()
}
PathParameters::Parenthesized(_) => {
Vec::new()
}
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct AngleBracketedParameterData {
pub lifetimes: Vec<Lifetime>,
pub types: P<[P<Ty>]>,
pub bindings: P<[TypeBinding]>,
}
impl AngleBracketedParameterData {
fn is_empty(&self) -> bool {
self.lifetimes.is_empty() && self.types.is_empty() && self.bindings.is_empty()
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct ParenthesizedParameterData {
pub span: Span,
pub inputs: Vec<P<Ty>>,
pub output: Option<P<Ty>>,
}
pub type CrateNum = u32;
pub type NodeId = u32;
pub const CRATE_NODE_ID: NodeId = 0;
pub const DUMMY_NODE_ID: NodeId = !0;
pub trait NodeIdAssigner {
fn next_node_id(&self) -> NodeId;
fn peek_node_id(&self) -> NodeId;
fn diagnostic(&self) -> &errors::Handler {
panic!("this ID assigner cannot emit diagnostics")
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum TyParamBound {
TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
RegionTyParamBound(Lifetime)
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum TraitBoundModifier {
None,
Maybe,
}
pub type TyParamBounds = P<[TyParamBound]>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct TyParam {
pub ident: Ident,
pub id: NodeId,
pub bounds: TyParamBounds,
pub default: Option<P<Ty>>,
pub span: Span
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Generics {
pub lifetimes: Vec<LifetimeDef>,
pub ty_params: P<[TyParam]>,
pub where_clause: WhereClause,
}
impl Generics {
pub fn is_lt_parameterized(&self) -> bool {
!self.lifetimes.is_empty()
}
pub fn is_type_parameterized(&self) -> bool {
!self.ty_params.is_empty()
}
pub fn is_parameterized(&self) -> bool {
self.is_lt_parameterized() || self.is_type_parameterized()
}
}
impl Default for Generics {
fn default() -> Generics {
Generics {
lifetimes: Vec::new(),
ty_params: P::empty(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
}
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct WhereClause {
pub id: NodeId,
pub predicates: Vec<WherePredicate>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum WherePredicate {
BoundPredicate(WhereBoundPredicate),
RegionPredicate(WhereRegionPredicate),
EqPredicate(WhereEqPredicate),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct WhereBoundPredicate {
pub span: Span,
pub bound_lifetimes: Vec<LifetimeDef>,
pub bounded_ty: P<Ty>,
pub bounds: TyParamBounds,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
pub bounds: Vec<Lifetime>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
pub path: Path,
pub ty: P<Ty>,
}
pub type CrateConfig = Vec<P<MetaItem>>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Crate {
pub module: Mod,
pub attrs: Vec<Attribute>,
pub config: CrateConfig,
pub span: Span,
pub exported_macros: Vec<MacroDef>,
}
pub type MetaItem = Spanned<MetaItemKind>;
#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum MetaItemKind {
Word(InternedString),
List(InternedString, Vec<P<MetaItem>>),
NameValue(InternedString, Lit),
}
impl PartialEq for MetaItemKind {
fn eq(&self, other: &MetaItemKind) -> bool {
use self::MetaItemKind::*;
match *self {
Word(ref ns) => match *other {
Word(ref no) => (*ns) == (*no),
_ => false
},
NameValue(ref ns, ref vs) => match *other {
NameValue(ref no, ref vo) => {
(*ns) == (*no) && vs.node == vo.node
}
_ => false
},
List(ref ns, ref miss) => match *other {
List(ref no, ref miso) => {
ns == no &&
miss.iter().all(|mi| miso.iter().any(|x| x.node == mi.node))
}
_ => false
}
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Block {
pub stmts: Vec<Stmt>,
pub expr: Option<P<Expr>>,
pub id: NodeId,
pub rules: BlockCheckMode,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub struct Pat {
pub id: NodeId,
pub node: PatKind,
pub span: Span,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct FieldPat {
pub ident: Ident,
pub pat: P<Pat>,
pub is_shorthand: bool,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum BindingMode {
ByRef(Mutability),
ByValue(Mutability),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum PatKind {
Wild,
Ident(BindingMode, SpannedIdent, Option<P<Pat>>),
Struct(Path, Vec<Spanned<FieldPat>>, bool),
TupleStruct(Path, Option<Vec<P<Pat>>>),
Path(Path),
QPath(QSelf, Path),
Tup(Vec<P<Pat>>),
Box(P<Pat>),
Ref(P<Pat>, Mutability),
Lit(P<Expr>),
Range(P<Expr>, P<Expr>),
Vec(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
Mac(Mac),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum Mutability {
Mutable,
Immutable,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum BinOpKind {
Add,
Sub,
Mul,
Div,
Rem,
And,
Or,
BitXor,
BitAnd,
BitOr,
Shl,
Shr,
Eq,
Lt,
Le,
Ne,
Ge,
Gt,
}
impl BinOpKind {
pub fn to_string(&self) -> &'static str {
use self::BinOpKind::*;
match *self {
Add => "+",
Sub => "-",
Mul => "*",
Div => "/",
Rem => "%",
And => "&&",
Or => "||",
BitXor => "^",
BitAnd => "&",
BitOr => "|",
Shl => "<<",
Shr => ">>",
Eq => "==",
Lt => "<",
Le => "<=",
Ne => "!=",
Ge => ">=",
Gt => ">",
}
}
pub fn lazy(&self) -> bool {
match *self {
BinOpKind::And | BinOpKind::Or => true,
_ => false
}
}
pub fn is_shift(&self) -> bool {
match *self {
BinOpKind::Shl | BinOpKind::Shr => true,
_ => false
}
}
pub fn is_comparison(&self) -> bool {
use self::BinOpKind::*;
match *self {
Eq | Lt | Le | Ne | Gt | Ge =>
true,
And | Or | Add | Sub | Mul | Div | Rem |
BitXor | BitAnd | BitOr | Shl | Shr =>
false,
}
}
pub fn is_by_value(&self) -> bool {
!self.is_comparison()
}
}
pub type BinOp = Spanned<BinOpKind>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum UnOp {
Deref,
Not,
Neg,
}
impl UnOp {
pub fn is_by_value(u: UnOp) -> bool {
match u {
UnOp::Neg | UnOp::Not => true,
_ => false,
}
}
pub fn to_string(op: UnOp) -> &'static str {
match op {
UnOp::Deref => "*",
UnOp::Not => "!",
UnOp::Neg => "-",
}
}
}
pub type Stmt = Spanned<StmtKind>;
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub enum StmtKind {
Decl(P<Decl>, NodeId),
Expr(P<Expr>, NodeId),
Semi(P<Expr>, NodeId),
Mac(P<Mac>, MacStmtStyle, ThinAttributes),
}
impl StmtKind {
pub fn id(&self) -> Option<NodeId> {
match *self {
StmtKind::Decl(_, id) => Some(id),
StmtKind::Expr(_, id) => Some(id),
StmtKind::Semi(_, id) => Some(id),
StmtKind::Mac(..) => None,
}
}
pub fn attrs(&self) -> &[Attribute] {
match *self {
StmtKind::Decl(ref d, _) => d.attrs(),
StmtKind::Expr(ref e, _) |
StmtKind::Semi(ref e, _) => e.attrs(),
StmtKind::Mac(_, _, Some(ref b)) => b,
StmtKind::Mac(_, _, None) => &[],
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum MacStmtStyle {
Semicolon,
Braces,
NoBraces,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Local {
pub pat: P<Pat>,
pub ty: Option<P<Ty>>,
pub init: Option<P<Expr>>,
pub id: NodeId,
pub span: Span,
pub attrs: ThinAttributes,
}
impl Local {
pub fn attrs(&self) -> &[Attribute] {
match self.attrs {
Some(ref b) => b,
None => &[],
}
}
}
pub type Decl = Spanned<DeclKind>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum DeclKind {
Local(P<Local>),
Item(P<Item>),
}
impl Decl {
pub fn attrs(&self) -> &[Attribute] {
match self.node {
DeclKind::Local(ref l) => l.attrs(),
DeclKind::Item(ref i) => i.attrs(),
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Arm {
pub attrs: Vec<Attribute>,
pub pats: Vec<P<Pat>>,
pub guard: Option<P<Expr>>,
pub body: P<Expr>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Field {
pub ident: SpannedIdent,
pub expr: P<Expr>,
pub span: Span,
}
pub type SpannedIdent = Spanned<Ident>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum BlockCheckMode {
Default,
Unsafe(UnsafeSource),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum UnsafeSource {
CompilerGenerated,
UserProvided,
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash,)]
pub struct Expr {
pub id: NodeId,
pub node: ExprKind,
pub span: Span,
pub attrs: ThinAttributes
}
impl Expr {
pub fn attrs(&self) -> &[Attribute] {
match self.attrs {
Some(ref b) => b,
None => &[],
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum RangeLimits {
HalfOpen,
Closed,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum ExprKind {
Box(P<Expr>),
InPlace(P<Expr>, P<Expr>),
Vec(Vec<P<Expr>>),
Call(P<Expr>, Vec<P<Expr>>),
MethodCall(SpannedIdent, Vec<P<Ty>>, Vec<P<Expr>>),
Tup(Vec<P<Expr>>),
Binary(BinOp, P<Expr>, P<Expr>),
Unary(UnOp, P<Expr>),
Lit(P<Lit>),
Cast(P<Expr>, P<Ty>),
Type(P<Expr>, P<Ty>),
If(P<Expr>, P<Block>, Option<P<Expr>>),
IfLet(P<Pat>, P<Expr>, P<Block>, Option<P<Expr>>),
While(P<Expr>, P<Block>, Option<Ident>),
WhileLet(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Ident>),
Loop(P<Block>, Option<Ident>),
Match(P<Expr>, Vec<Arm>),
Closure(CaptureBy, P<FnDecl>, P<Block>),
Block(P<Block>),
Assign(P<Expr>, P<Expr>),
AssignOp(BinOp, P<Expr>, P<Expr>),
Field(P<Expr>, SpannedIdent),
TupField(P<Expr>, Spanned<usize>),
Index(P<Expr>, P<Expr>),
Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
Path(Option<QSelf>, Path),
AddrOf(Mutability, P<Expr>),
Break(Option<SpannedIdent>),
Again(Option<SpannedIdent>),
Ret(Option<P<Expr>>),
InlineAsm(InlineAsm),
Mac(Mac),
Struct(Path, Vec<Field>, Option<P<Expr>>),
Repeat(P<Expr>, P<Expr>),
Paren(P<Expr>),
Try(P<Expr>),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct QSelf {
pub ty: P<Ty>,
pub position: usize
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum CaptureBy {
Value,
Ref,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Delimited {
pub delim: token::DelimToken,
pub open_span: Span,
pub tts: Vec<TokenTree>,
pub close_span: Span,
}
impl Delimited {
pub fn open_token(&self) -> token::Token {
token::OpenDelim(self.delim)
}
pub fn close_token(&self) -> token::Token {
token::CloseDelim(self.delim)
}
pub fn open_tt(&self) -> TokenTree {
TokenTree::Token(self.open_span, self.open_token())
}
pub fn close_tt(&self) -> TokenTree {
TokenTree::Token(self.close_span, self.close_token())
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct SequenceRepetition {
pub tts: Vec<TokenTree>,
pub separator: Option<token::Token>,
pub op: KleeneOp,
pub num_captures: usize,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum KleeneOp {
ZeroOrMore,
OneOrMore,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum TokenTree {
Token(Span, token::Token),
Delimited(Span, Rc<Delimited>),
Sequence(Span, Rc<SequenceRepetition>),
}
impl TokenTree {
pub fn len(&self) -> usize {
match *self {
TokenTree::Token(_, token::DocComment(name)) => {
match doc_comment_style(&name.as_str()) {
AttrStyle::Outer => 2,
AttrStyle::Inner => 3
}
}
TokenTree::Token(_, token::SpecialVarNt(..)) => 2,
TokenTree::Token(_, token::MatchNt(..)) => 3,
TokenTree::Delimited(_, ref delimed) => {
delimed.tts.len() + 2
}
TokenTree::Sequence(_, ref seq) => {
seq.tts.len()
}
TokenTree::Token(..) => 0
}
}
pub fn get_tt(&self, index: usize) -> TokenTree {
match (self, index) {
(&TokenTree::Token(sp, token::DocComment(_)), 0) => {
TokenTree::Token(sp, token::Pound)
}
(&TokenTree::Token(sp, token::DocComment(name)), 1)
if doc_comment_style(&name.as_str()) == AttrStyle::Inner => {
TokenTree::Token(sp, token::Not)
}
(&TokenTree::Token(sp, token::DocComment(name)), _) => {
let stripped = strip_doc_comment_decoration(&name.as_str());
let num_of_hashes = stripped.chars().scan(0, |cnt, x| {
*cnt = if x == '"' {
1
} else if *cnt != 0 && x == '#' {
*cnt + 1
} else {
0
};
Some(*cnt)
}).max().unwrap_or(0);
TokenTree::Delimited(sp, Rc::new(Delimited {
delim: token::Bracket,
open_span: sp,
tts: vec![TokenTree::Token(sp, token::Ident(token::str_to_ident("doc"),
token::Plain)),
TokenTree::Token(sp, token::Eq),
TokenTree::Token(sp, token::Literal(
token::StrRaw(token::intern(&stripped), num_of_hashes), None))],
close_span: sp,
}))
}
(&TokenTree::Delimited(_, ref delimed), _) => {
if index == 0 {
return delimed.open_tt();
}
if index == delimed.tts.len() + 1 {
return delimed.close_tt();
}
delimed.tts[index - 1].clone()
}
(&TokenTree::Token(sp, token::SpecialVarNt(var)), _) => {
let v = [TokenTree::Token(sp, token::Dollar),
TokenTree::Token(sp, token::Ident(token::str_to_ident(var.as_str()),
token::Plain))];
v[index].clone()
}
(&TokenTree::Token(sp, token::MatchNt(name, kind, name_st, kind_st)), _) => {
let v = [TokenTree::Token(sp, token::SubstNt(name, name_st)),
TokenTree::Token(sp, token::Colon),
TokenTree::Token(sp, token::Ident(kind, kind_st))];
v[index].clone()
}
(&TokenTree::Sequence(_, ref seq), _) => {
seq.tts[index].clone()
}
_ => panic!("Cannot expand a token tree")
}
}
pub fn get_span(&self) -> Span {
match *self {
TokenTree::Token(span, _) => span,
TokenTree::Delimited(span, _) => span,
TokenTree::Sequence(span, _) => span,
}
}
pub fn parse(cx: &base::ExtCtxt, mtch: &[TokenTree], tts: &[TokenTree])
-> macro_parser::NamedParseResult {
let arg_rdr = lexer::new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic,
None,
None,
tts.iter().cloned().collect(),
true);
macro_parser::parse(cx.parse_sess(), cx.cfg(), arg_rdr, mtch)
}
}
pub type Mac = Spanned<Mac_>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Mac_ {
pub path: Path,
pub tts: Vec<TokenTree>,
pub ctxt: SyntaxContext,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum StrStyle {
Cooked,
Raw(usize)
}
pub type Lit = Spanned<LitKind>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum LitIntType {
Signed(IntTy),
Unsigned(UintTy),
Unsuffixed,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum LitKind {
Str(InternedString, StrStyle),
ByteStr(Rc<Vec<u8>>),
Byte(u8),
Char(char),
Int(u64, LitIntType),
Float(InternedString, FloatTy),
FloatUnsuffixed(InternedString),
Bool(bool),
}
impl LitKind {
pub fn is_str(&self) -> bool {
match *self {
LitKind::Str(..) => true,
_ => false,
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct MutTy {
pub ty: P<Ty>,
pub mutbl: Mutability,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct MethodSig {
pub unsafety: Unsafety,
pub constness: Constness,
pub abi: Abi,
pub decl: P<FnDecl>,
pub generics: Generics,
pub explicit_self: ExplicitSelf,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct TraitItem {
pub id: NodeId,
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub node: TraitItemKind,
pub span: Span,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum TraitItemKind {
Const(P<Ty>, Option<P<Expr>>),
Method(MethodSig, Option<P<Block>>),
Type(TyParamBounds, Option<P<Ty>>),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct ImplItem {
pub id: NodeId,
pub ident: Ident,
pub vis: Visibility,
pub defaultness: Defaultness,
pub attrs: Vec<Attribute>,
pub node: ImplItemKind,
pub span: Span,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum ImplItemKind {
Const(P<Ty>, P<Expr>),
Method(MethodSig, P<Block>),
Type(P<Ty>),
Macro(Mac),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum IntTy {
Is,
I8,
I16,
I32,
I64,
}
impl fmt::Debug for IntTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for IntTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.ty_to_string())
}
}
impl IntTy {
pub fn ty_to_string(&self) -> &'static str {
match *self {
IntTy::Is => "isize",
IntTy::I8 => "i8",
IntTy::I16 => "i16",
IntTy::I32 => "i32",
IntTy::I64 => "i64"
}
}
pub fn val_to_string(&self, val: i64) -> String {
format!("{}{}", val as u64, self.ty_to_string())
}
pub fn ty_max(&self) -> u64 {
match *self {
IntTy::I8 => 0x80,
IntTy::I16 => 0x8000,
IntTy::Is | IntTy::I32 => 0x80000000, IntTy::I64 => 0x8000000000000000
}
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
IntTy::Is => return None,
IntTy::I8 => 8,
IntTy::I16 => 16,
IntTy::I32 => 32,
IntTy::I64 => 64,
})
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum UintTy {
Us,
U8,
U16,
U32,
U64,
}
impl UintTy {
pub fn ty_to_string(&self) -> &'static str {
match *self {
UintTy::Us => "usize",
UintTy::U8 => "u8",
UintTy::U16 => "u16",
UintTy::U32 => "u32",
UintTy::U64 => "u64"
}
}
pub fn val_to_string(&self, val: u64) -> String {
format!("{}{}", val, self.ty_to_string())
}
pub fn ty_max(&self) -> u64 {
match *self {
UintTy::U8 => 0xff,
UintTy::U16 => 0xffff,
UintTy::Us | UintTy::U32 => 0xffffffff, UintTy::U64 => 0xffffffffffffffff
}
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
UintTy::Us => return None,
UintTy::U8 => 8,
UintTy::U16 => 16,
UintTy::U32 => 32,
UintTy::U64 => 64,
})
}
}
impl fmt::Debug for UintTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for UintTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.ty_to_string())
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
pub enum FloatTy {
F32,
F64,
}
impl fmt::Debug for FloatTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for FloatTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.ty_to_string())
}
}
impl FloatTy {
pub fn ty_to_string(&self) -> &'static str {
match *self {
FloatTy::F32 => "f32",
FloatTy::F64 => "f64",
}
}
pub fn bit_width(&self) -> usize {
match *self {
FloatTy::F32 => 32,
FloatTy::F64 => 64,
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct TypeBinding {
pub id: NodeId,
pub ident: Ident,
pub ty: P<Ty>,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub struct Ty {
pub id: NodeId,
pub node: TyKind,
pub span: Span,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct BareFnTy {
pub unsafety: Unsafety,
pub abi: Abi,
pub lifetimes: Vec<LifetimeDef>,
pub decl: P<FnDecl>
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum TyKind {
Vec(P<Ty>),
FixedLengthVec(P<Ty>, P<Expr>),
Ptr(MutTy),
Rptr(Option<Lifetime>, MutTy),
BareFn(P<BareFnTy>),
Tup(Vec<P<Ty>> ),
Path(Option<QSelf>, Path),
ObjectSum(P<Ty>, TyParamBounds),
PolyTraitRef(TyParamBounds),
Paren(P<Ty>),
Typeof(P<Expr>),
Infer,
Mac(Mac),
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum AsmDialect {
Att,
Intel,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct InlineAsmOutput {
pub constraint: InternedString,
pub expr: P<Expr>,
pub is_rw: bool,
pub is_indirect: bool,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct InlineAsm {
pub asm: InternedString,
pub asm_str_style: StrStyle,
pub outputs: Vec<InlineAsmOutput>,
pub inputs: Vec<(InternedString, P<Expr>)>,
pub clobbers: Vec<InternedString>,
pub volatile: bool,
pub alignstack: bool,
pub dialect: AsmDialect,
pub expn_id: ExpnId,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Arg {
pub ty: P<Ty>,
pub pat: P<Pat>,
pub id: NodeId,
}
impl Arg {
pub fn new_self(span: Span, mutability: Mutability, self_ident: Ident) -> Arg {
let path = Spanned{span:span,node:self_ident};
Arg {
ty: P(Ty {
id: DUMMY_NODE_ID,
node: TyKind::Infer,
span: DUMMY_SP,
}),
pat: P(Pat {
id: DUMMY_NODE_ID,
node: PatKind::Ident(BindingMode::ByValue(mutability), path, None),
span: span
}),
id: DUMMY_NODE_ID
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct FnDecl {
pub inputs: Vec<Arg>,
pub output: FunctionRetTy,
pub variadic: bool
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum Unsafety {
Unsafe,
Normal,
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum Constness {
Const,
NotConst,
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum Defaultness {
Default,
Final,
}
impl fmt::Display for Unsafety {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(match *self {
Unsafety::Normal => "normal",
Unsafety::Unsafe => "unsafe",
}, f)
}
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
pub enum ImplPolarity {
Positive,
Negative,
}
impl fmt::Debug for ImplPolarity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ImplPolarity::Positive => "positive".fmt(f),
ImplPolarity::Negative => "negative".fmt(f),
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum FunctionRetTy {
None(Span),
Default(Span),
Ty(P<Ty>),
}
impl FunctionRetTy {
pub fn span(&self) -> Span {
match *self {
FunctionRetTy::None(span) => span,
FunctionRetTy::Default(span) => span,
FunctionRetTy::Ty(ref ty) => ty.span,
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum SelfKind {
Static,
Value(Ident),
Region(Option<Lifetime>, Mutability, Ident),
Explicit(P<Ty>, Ident),
}
pub type ExplicitSelf = Spanned<SelfKind>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Mod {
pub inner: Span,
pub items: Vec<P<Item>>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct ForeignMod {
pub abi: Abi,
pub items: Vec<ForeignItem>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct EnumDef {
pub variants: Vec<Variant>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Variant_ {
pub name: Ident,
pub attrs: Vec<Attribute>,
pub data: VariantData,
pub disr_expr: Option<P<Expr>>,
}
pub type Variant = Spanned<Variant_>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum PathListItemKind {
Ident {
name: Ident,
rename: Option<Ident>,
id: NodeId
},
Mod {
rename: Option<Ident>,
id: NodeId
}
}
impl PathListItemKind {
pub fn id(&self) -> NodeId {
match *self {
PathListItemKind::Ident { id, .. } | PathListItemKind::Mod { id, .. } => id
}
}
pub fn name(&self) -> Option<Ident> {
match *self {
PathListItemKind::Ident { name, .. } => Some(name),
PathListItemKind::Mod { .. } => None,
}
}
pub fn rename(&self) -> Option<Ident> {
match *self {
PathListItemKind::Ident { rename, .. } | PathListItemKind::Mod { rename, .. } => rename
}
}
}
pub type PathListItem = Spanned<PathListItemKind>;
pub type ViewPath = Spanned<ViewPath_>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum ViewPath_ {
ViewPathSimple(Ident, Path),
ViewPathGlob(Path),
ViewPathList(Path, Vec<PathListItem>)
}
pub type Attribute = Spanned<Attribute_>;
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum AttrStyle {
Outer,
Inner,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub struct AttrId(pub usize);
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Attribute_ {
pub id: AttrId,
pub style: AttrStyle,
pub value: P<MetaItem>,
pub is_sugared_doc: bool,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct TraitRef {
pub path: Path,
pub ref_id: NodeId,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct PolyTraitRef {
pub bound_lifetimes: Vec<LifetimeDef>,
pub trait_ref: TraitRef,
pub span: Span,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum Visibility {
Public,
Crate(Span),
Restricted { path: P<Path>, id: NodeId },
Inherited,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct StructField {
pub span: Span,
pub ident: Option<Ident>,
pub vis: Visibility,
pub id: NodeId,
pub ty: P<Ty>,
pub attrs: Vec<Attribute>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum VariantData {
Struct(Vec<StructField>, NodeId),
Tuple(Vec<StructField>, NodeId),
Unit(NodeId),
}
impl VariantData {
pub fn fields(&self) -> &[StructField] {
match *self {
VariantData::Struct(ref fields, _) | VariantData::Tuple(ref fields, _) => fields,
_ => &[],
}
}
pub fn id(&self) -> NodeId {
match *self {
VariantData::Struct(_, id) | VariantData::Tuple(_, id) | VariantData::Unit(id) => id
}
}
pub fn is_struct(&self) -> bool {
if let VariantData::Struct(..) = *self { true } else { false }
}
pub fn is_tuple(&self) -> bool {
if let VariantData::Tuple(..) = *self { true } else { false }
}
pub fn is_unit(&self) -> bool {
if let VariantData::Unit(..) = *self { true } else { false }
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Item {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub node: ItemKind,
pub vis: Visibility,
pub span: Span,
}
impl Item {
pub fn attrs(&self) -> &[Attribute] {
&self.attrs
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum ItemKind {
ExternCrate(Option<Name>),
Use(P<ViewPath>),
Static(P<Ty>, Mutability, P<Expr>),
Const(P<Ty>, P<Expr>),
Fn(P<FnDecl>, Unsafety, Constness, Abi, Generics, P<Block>),
Mod(Mod),
ForeignMod(ForeignMod),
Ty(P<Ty>, Generics),
Enum(EnumDef, Generics),
Struct(VariantData, Generics),
Trait(Unsafety,
Generics,
TyParamBounds,
Vec<TraitItem>),
DefaultImpl(Unsafety, TraitRef),
Impl(Unsafety,
ImplPolarity,
Generics,
Option<TraitRef>, P<Ty>, Vec<ImplItem>),
Mac(Mac),
}
impl ItemKind {
pub fn descriptive_variant(&self) -> &str {
match *self {
ItemKind::ExternCrate(..) => "extern crate",
ItemKind::Use(..) => "use",
ItemKind::Static(..) => "static item",
ItemKind::Const(..) => "constant item",
ItemKind::Fn(..) => "function",
ItemKind::Mod(..) => "module",
ItemKind::ForeignMod(..) => "foreign module",
ItemKind::Ty(..) => "type alias",
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Trait(..) => "trait",
ItemKind::Mac(..) |
ItemKind::Impl(..) |
ItemKind::DefaultImpl(..) => "item"
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct ForeignItem {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub node: ForeignItemKind,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub enum ForeignItemKind {
Fn(P<FnDecl>, Generics),
Static(P<Ty>, bool),
}
impl ForeignItemKind {
pub fn descriptive_variant(&self) -> &str {
match *self {
ForeignItemKind::Fn(..) => "foreign function",
ForeignItemKind::Static(..) => "foreign static item"
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct MacroDef {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub imported_from: Option<Ident>,
pub export: bool,
pub use_locally: bool,
pub allow_internal_unstable: bool,
pub body: Vec<TokenTree>,
}
#[cfg(test)]
mod tests {
use serialize;
use super::*;
#[test]
fn check_asts_encodable() {
fn assert_encodable<T: serialize::Encodable>() {}
assert_encodable::<Crate>();
}
}