pub use GenericArgs::*;
pub use UnsafeSource::*;
pub use crate::symbol::{Ident, Symbol as Name};
pub use crate::util::parser::ExprPrecedence;
use crate::ext::hygiene::{Mark, SyntaxContext};
use crate::print::pprust;
use crate::ptr::P;
use crate::source_map::{dummy_spanned, respan, Spanned};
use crate::symbol::{keywords, Symbol};
use crate::tokenstream::TokenStream;
use crate::ThinVec;
use rustc_data_structures::indexed_vec::Idx;
#[cfg(target_arch = "x86_64")]
use rustc_data_structures::static_assert;
use rustc_target::spec::abi::Abi;
use syntax_pos::{Span, DUMMY_SP};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
use serialize::{self, Decoder, Encoder};
use std::fmt;
pub use rustc_target::abi::FloatTy;
#[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
pub struct Label {
pub ident: Ident,
}
impl fmt::Debug for Label {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "label({:?})", self.ident)
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
pub struct Lifetime {
pub id: NodeId,
pub ident: Ident,
}
impl fmt::Debug for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"lifetime({}: {})",
self.id,
pprust::lifetime_to_string(self)
)
}
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Path {
pub span: Span,
pub segments: Vec<PathSegment>,
}
impl PartialEq<Symbol> for Path {
fn eq(&self, symbol: &Symbol) -> bool {
self.segments.len() == 1 && {
let name = self.segments[0].ident.name;
debug_assert!(!symbol.is_gensymed());
debug_assert!(!name.is_gensymed());
name == *symbol
}
}
}
impl<'a> PartialEq<&'a str> for Path {
fn eq(&self, string: &&'a str) -> bool {
self.segments.len() == 1 && self.segments[0].ident.name == *string
}
}
impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "path({})", pprust::path_to_string(self))
}
}
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(ident: Ident) -> Path {
Path {
segments: vec![PathSegment::from_ident(ident)],
span: ident.span,
}
}
pub fn is_global(&self) -> bool {
!self.segments.is_empty() && self.segments[0].ident.name == keywords::PathRoot.name()
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct PathSegment {
pub ident: Ident,
pub id: NodeId,
pub args: Option<P<GenericArgs>>,
}
impl PathSegment {
pub fn from_ident(ident: Ident) -> Self {
PathSegment { ident, id: DUMMY_NODE_ID, args: None }
}
pub fn path_root(span: Span) -> Self {
PathSegment::from_ident(Ident::new(keywords::PathRoot.name(), span))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericArgs {
AngleBracketed(AngleBracketedArgs),
Parenthesized(ParenthesizedArgs),
}
impl GenericArgs {
pub fn is_parenthesized(&self) -> bool {
match *self {
Parenthesized(..) => true,
_ => false,
}
}
pub fn is_angle_bracketed(&self) -> bool {
match *self {
AngleBracketed(..) => true,
_ => false,
}
}
pub fn span(&self) -> Span {
match *self {
AngleBracketed(ref data) => data.span,
Parenthesized(ref data) => data.span,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericArg {
Lifetime(Lifetime),
Type(P<Ty>),
Const(AnonConst),
}
impl GenericArg {
pub fn span(&self) -> Span {
match self {
GenericArg::Lifetime(lt) => lt.ident.span,
GenericArg::Type(ty) => ty.span,
GenericArg::Const(ct) => ct.value.span,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
pub struct AngleBracketedArgs {
pub span: Span,
pub args: Vec<GenericArg>,
pub bindings: Vec<TypeBinding>,
}
impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
fn into(self) -> Option<P<GenericArgs>> {
Some(P(GenericArgs::AngleBracketed(self)))
}
}
impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
fn into(self) -> Option<P<GenericArgs>> {
Some(P(GenericArgs::Parenthesized(self)))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ParenthesizedArgs {
pub span: Span,
pub inputs: Vec<P<Ty>>,
pub output: Option<P<Ty>>,
}
impl ParenthesizedArgs {
pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
AngleBracketedArgs {
span: self.span,
args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
bindings: vec![],
}
}
}
mod node_id_inner {
use rustc_data_structures::indexed_vec::Idx;
use rustc_data_structures::newtype_index;
newtype_index! {
pub struct NodeId {
ENCODABLE = custom
DEBUG_FORMAT = "NodeId({})"
}
}
}
pub use node_id_inner::NodeId;
impl NodeId {
pub fn placeholder_from_mark(mark: Mark) -> Self {
NodeId::from_u32(mark.as_u32())
}
pub fn placeholder_to_mark(self) -> Mark {
Mark::from_u32(self.as_u32())
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.as_u32(), f)
}
}
impl serialize::UseSpecializedEncodable for NodeId {
fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u32(self.as_u32())
}
}
impl serialize::UseSpecializedDecodable for NodeId {
fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
d.read_u32().map(NodeId::from_u32)
}
}
pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitBoundModifier {
None,
Maybe,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericBound {
Trait(PolyTraitRef, TraitBoundModifier),
Outlives(Lifetime),
}
impl GenericBound {
pub fn span(&self) -> Span {
match self {
&GenericBound::Trait(ref t, ..) => t.span,
&GenericBound::Outlives(ref l) => l.ident.span,
}
}
}
pub type GenericBounds = Vec<GenericBound>;
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum ParamKindOrd {
Lifetime,
Type,
Const,
}
impl fmt::Display for ParamKindOrd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParamKindOrd::Lifetime => "lifetime".fmt(f),
ParamKindOrd::Type => "type".fmt(f),
ParamKindOrd::Const => "const".fmt(f),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericParamKind {
Lifetime,
Type { default: Option<P<Ty>> },
Const { ty: P<Ty> },
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct GenericParam {
pub id: NodeId,
pub ident: Ident,
pub attrs: ThinVec<Attribute>,
pub bounds: GenericBounds,
pub kind: GenericParamKind,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Generics {
pub params: Vec<GenericParam>,
pub where_clause: WhereClause,
pub span: Span,
}
impl Default for Generics {
fn default() -> Generics {
Generics {
params: Vec::new(),
where_clause: WhereClause {
id: DUMMY_NODE_ID,
predicates: Vec::new(),
span: DUMMY_SP,
},
span: DUMMY_SP,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereClause {
pub id: NodeId,
pub predicates: Vec<WherePredicate>,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum WherePredicate {
BoundPredicate(WhereBoundPredicate),
RegionPredicate(WhereRegionPredicate),
EqPredicate(WhereEqPredicate),
}
impl WherePredicate {
pub fn span(&self) -> Span {
match self {
&WherePredicate::BoundPredicate(ref p) => p.span,
&WherePredicate::RegionPredicate(ref p) => p.span,
&WherePredicate::EqPredicate(ref p) => p.span,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereBoundPredicate {
pub span: Span,
pub bound_generic_params: Vec<GenericParam>,
pub bounded_ty: P<Ty>,
pub bounds: GenericBounds,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
pub bounds: GenericBounds,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
pub lhs_ty: P<Ty>,
pub rhs_ty: P<Ty>,
}
pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Crate {
pub module: Mod,
pub attrs: Vec<Attribute>,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum NestedMetaItem {
MetaItem(MetaItem),
Literal(Lit),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MetaItem {
pub path: Path,
pub node: MetaItemKind,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum MetaItemKind {
Word,
List(Vec<NestedMetaItem>),
NameValue(Lit),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Block {
pub stmts: Vec<Stmt>,
pub id: NodeId,
pub rules: BlockCheckMode,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Pat {
pub id: NodeId,
pub node: PatKind,
pub span: Span,
}
impl fmt::Debug for Pat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "pat({}: {})", self.id, pprust::pat_to_string(self))
}
}
impl Pat {
pub(super) fn to_ty(&self) -> Option<P<Ty>> {
let node = match &self.node {
PatKind::Wild => TyKind::Infer,
PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
TyKind::Path(None, Path::from_ident(*ident))
}
PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
PatKind::Ref(pat, mutbl) => pat
.to_ty()
.map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
PatKind::Slice(pats, None, _) if pats.len() == 1 => {
pats[0].to_ty().map(TyKind::Slice)?
}
PatKind::Tuple(pats, None) => {
let mut tys = Vec::with_capacity(pats.len());
for pat in pats {
tys.push(pat.to_ty()?);
}
TyKind::Tup(tys)
}
_ => return None,
};
Some(P(Ty {
node,
id: self.id,
span: self.span,
}))
}
pub fn walk<F>(&self, it: &mut F) -> bool
where
F: FnMut(&Pat) -> bool,
{
if !it(self) {
return false;
}
match self.node {
PatKind::Ident(_, _, Some(ref p)) => p.walk(it),
PatKind::Struct(_, ref fields, _) => fields.iter().all(|field| field.node.pat.walk(it)),
PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
s.iter().all(|p| p.walk(it))
}
PatKind::Box(ref s) | PatKind::Ref(ref s, _) | PatKind::Paren(ref s) => s.walk(it),
PatKind::Slice(ref before, ref slice, ref after) => {
before.iter().all(|p| p.walk(it))
&& slice.iter().all(|p| p.walk(it))
&& after.iter().all(|p| p.walk(it))
}
PatKind::Wild
| PatKind::Lit(_)
| PatKind::Range(..)
| PatKind::Ident(..)
| PatKind::Path(..)
| PatKind::Mac(_) => true,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FieldPat {
pub ident: Ident,
pub pat: P<Pat>,
pub is_shorthand: bool,
pub attrs: ThinVec<Attribute>,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BindingMode {
ByRef(Mutability),
ByValue(Mutability),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeEnd {
Included(RangeSyntax),
Excluded,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeSyntax {
DotDotDot,
DotDotEq,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum PatKind {
Wild,
Ident(BindingMode, Ident, Option<P<Pat>>),
Struct(Path, Vec<Spanned<FieldPat>>, bool),
TupleStruct(Path, Vec<P<Pat>>, Option<usize>),
Path(Option<QSelf>, Path),
Tuple(Vec<P<Pat>>, Option<usize>),
Box(P<Pat>),
Ref(P<Pat>, Mutability),
Lit(P<Expr>),
Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
Slice(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>),
Paren(P<Pat>),
Mac(Mac),
}
#[derive(
Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Debug, Copy,
)]
pub enum Mutability {
Mutable,
Immutable,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, 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 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 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, RustcEncodable, RustcDecodable, 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 => "-",
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Stmt {
pub id: NodeId,
pub node: StmtKind,
pub span: Span,
}
impl Stmt {
pub fn add_trailing_semicolon(mut self) -> Self {
self.node = match self.node {
StmtKind::Expr(expr) => StmtKind::Semi(expr),
StmtKind::Mac(mac) => {
StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
}
node => node,
};
self
}
pub fn is_item(&self) -> bool {
match self.node {
StmtKind::Item(_) => true,
_ => false,
}
}
pub fn is_expr(&self) -> bool {
match self.node {
StmtKind::Expr(_) => true,
_ => false,
}
}
}
impl fmt::Debug for Stmt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"stmt({}: {})",
self.id.to_string(),
pprust::stmt_to_string(self)
)
}
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub enum StmtKind {
Local(P<Local>),
Item(P<Item>),
Expr(P<Expr>),
Semi(P<Expr>),
Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
}
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum MacStmtStyle {
Semicolon,
Braces,
NoBraces,
}
#[derive(Clone, RustcEncodable, RustcDecodable, 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: ThinVec<Attribute>,
pub source: LocalSource,
}
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
pub enum LocalSource {
Normal,
AsyncFn,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Arm {
pub attrs: Vec<Attribute>,
pub pats: Vec<P<Pat>>,
pub guard: Option<Guard>,
pub body: P<Expr>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum Guard {
If(P<Expr>),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Field {
pub ident: Ident,
pub expr: P<Expr>,
pub span: Span,
pub is_shorthand: bool,
pub attrs: ThinVec<Attribute>,
}
pub type SpannedIdent = Spanned<Ident>;
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BlockCheckMode {
Default,
Unsafe(UnsafeSource),
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum UnsafeSource {
CompilerGenerated,
UserProvided,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct AnonConst {
pub id: NodeId,
pub value: P<Expr>,
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Expr {
pub id: NodeId,
pub node: ExprKind,
pub span: Span,
pub attrs: ThinVec<Attribute>,
}
#[cfg(target_arch = "x86_64")]
static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::<Expr>() == 96);
impl Expr {
pub fn returns(&self) -> bool {
if let ExprKind::Block(ref block, _) = self.node {
match block.stmts.last().map(|last_stmt| &last_stmt.node) {
Some(&StmtKind::Expr(_)) => true,
Some(&StmtKind::Semi(ref expr)) => {
if let ExprKind::Ret(_) = expr.node {
true
} else {
false
}
}
_ => false,
}
} else {
true
}
}
fn to_bound(&self) -> Option<GenericBound> {
match &self.node {
ExprKind::Path(None, path) => Some(GenericBound::Trait(
PolyTraitRef::new(Vec::new(), path.clone(), self.span),
TraitBoundModifier::None,
)),
_ => None,
}
}
pub(super) fn to_ty(&self) -> Option<P<Ty>> {
let node = match &self.node {
ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
ExprKind::AddrOf(mutbl, expr) => expr
.to_ty()
.map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
ExprKind::Repeat(expr, expr_len) => {
expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
}
ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
ExprKind::Tup(exprs) => {
let tys = exprs
.iter()
.map(|expr| expr.to_ty())
.collect::<Option<Vec<_>>>()?;
TyKind::Tup(tys)
}
ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
} else {
return None;
}
}
_ => return None,
};
Some(P(Ty {
node,
id: self.id,
span: self.span,
}))
}
pub fn precedence(&self) -> ExprPrecedence {
match self.node {
ExprKind::Box(_) => ExprPrecedence::Box,
ExprKind::ObsoleteInPlace(..) => ExprPrecedence::ObsoleteInPlace,
ExprKind::Array(_) => ExprPrecedence::Array,
ExprKind::Call(..) => ExprPrecedence::Call,
ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
ExprKind::Tup(_) => ExprPrecedence::Tup,
ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
ExprKind::Unary(..) => ExprPrecedence::Unary,
ExprKind::Lit(_) => ExprPrecedence::Lit,
ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
ExprKind::If(..) => ExprPrecedence::If,
ExprKind::IfLet(..) => ExprPrecedence::IfLet,
ExprKind::While(..) => ExprPrecedence::While,
ExprKind::WhileLet(..) => ExprPrecedence::WhileLet,
ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
ExprKind::Loop(..) => ExprPrecedence::Loop,
ExprKind::Match(..) => ExprPrecedence::Match,
ExprKind::Closure(..) => ExprPrecedence::Closure,
ExprKind::Block(..) => ExprPrecedence::Block,
ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
ExprKind::Async(..) => ExprPrecedence::Async,
ExprKind::Assign(..) => ExprPrecedence::Assign,
ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
ExprKind::Field(..) => ExprPrecedence::Field,
ExprKind::Index(..) => ExprPrecedence::Index,
ExprKind::Range(..) => ExprPrecedence::Range,
ExprKind::Path(..) => ExprPrecedence::Path,
ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
ExprKind::Break(..) => ExprPrecedence::Break,
ExprKind::Continue(..) => ExprPrecedence::Continue,
ExprKind::Ret(..) => ExprPrecedence::Ret,
ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
ExprKind::Mac(..) => ExprPrecedence::Mac,
ExprKind::Struct(..) => ExprPrecedence::Struct,
ExprKind::Repeat(..) => ExprPrecedence::Repeat,
ExprKind::Paren(..) => ExprPrecedence::Paren,
ExprKind::Try(..) => ExprPrecedence::Try,
ExprKind::Yield(..) => ExprPrecedence::Yield,
ExprKind::Err => ExprPrecedence::Err,
}
}
}
impl fmt::Debug for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "expr({}: {})", self.id, pprust::expr_to_string(self))
}
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeLimits {
HalfOpen,
Closed,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ExprKind {
Box(P<Expr>),
ObsoleteInPlace(P<Expr>, P<Expr>),
Array(Vec<P<Expr>>),
Call(P<Expr>, Vec<P<Expr>>),
MethodCall(PathSegment, Vec<P<Expr>>),
Tup(Vec<P<Expr>>),
Binary(BinOp, P<Expr>, P<Expr>),
Unary(UnOp, P<Expr>),
Lit(Lit),
Cast(P<Expr>, P<Ty>),
Type(P<Expr>, P<Ty>),
If(P<Expr>, P<Block>, Option<P<Expr>>),
IfLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<P<Expr>>),
While(P<Expr>, P<Block>, Option<Label>),
WhileLet(Vec<P<Pat>>, P<Expr>, P<Block>, Option<Label>),
ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
Loop(P<Block>, Option<Label>),
Match(P<Expr>, Vec<Arm>),
Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
Block(P<Block>, Option<Label>),
Async(CaptureBy, NodeId, P<Block>),
TryBlock(P<Block>),
Assign(P<Expr>, P<Expr>),
AssignOp(BinOp, P<Expr>, P<Expr>),
Field(P<Expr>, Ident),
Index(P<Expr>, P<Expr>),
Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
Path(Option<QSelf>, Path),
AddrOf(Mutability, P<Expr>),
Break(Option<Label>, Option<P<Expr>>),
Continue(Option<Label>),
Ret(Option<P<Expr>>),
InlineAsm(P<InlineAsm>),
Mac(Mac),
Struct(Path, Vec<Field>, Option<P<Expr>>),
Repeat(P<Expr>, AnonConst),
Paren(P<Expr>),
Try(P<Expr>),
Yield(Option<P<Expr>>),
Err,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct QSelf {
pub ty: P<Ty>,
pub path_span: Span,
pub position: usize,
}
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum CaptureBy {
Value,
Ref,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum Movability {
Static,
Movable,
}
pub type Mac = Spanned<Mac_>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mac_ {
pub path: Path,
pub delim: MacDelimiter,
pub tts: TokenStream,
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub enum MacDelimiter {
Parenthesis,
Bracket,
Brace,
}
impl Mac_ {
pub fn stream(&self) -> TokenStream {
self.tts.clone()
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MacroDef {
pub tokens: TokenStream,
pub legacy: bool,
}
impl MacroDef {
pub fn stream(&self) -> TokenStream {
self.tokens.clone().into()
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
pub enum StrStyle {
Cooked,
Raw(u16),
}
pub type Lit = Spanned<LitKind>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq)]
pub enum LitIntType {
Signed(IntTy),
Unsigned(UintTy),
Unsuffixed,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq)]
pub enum LitKind {
Str(Symbol, StrStyle),
ByteStr(Lrc<Vec<u8>>),
Byte(u8),
Char(char),
Int(u128, LitIntType),
Float(Symbol, FloatTy),
FloatUnsuffixed(Symbol),
Bool(bool),
Err(Symbol),
}
impl LitKind {
pub fn is_str(&self) -> bool {
match *self {
LitKind::Str(..) => true,
_ => false,
}
}
pub fn is_bytestr(&self) -> bool {
match self {
LitKind::ByteStr(_) => true,
_ => false,
}
}
pub fn is_numeric(&self) -> bool {
match *self {
LitKind::Int(..) | LitKind::Float(..) | LitKind::FloatUnsuffixed(..) => true,
_ => false,
}
}
pub fn is_unsuffixed(&self) -> bool {
match *self {
LitKind::Str(..)
| LitKind::ByteStr(..)
| LitKind::Byte(..)
| LitKind::Char(..)
| LitKind::Err(..)
| LitKind::Int(_, LitIntType::Unsuffixed)
| LitKind::FloatUnsuffixed(..)
| LitKind::Bool(..) => true,
LitKind::Int(_, LitIntType::Signed(..))
| LitKind::Int(_, LitIntType::Unsigned(..))
| LitKind::Float(..) => false,
}
}
pub fn is_suffixed(&self) -> bool {
!self.is_unsuffixed()
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MutTy {
pub ty: P<Ty>,
pub mutbl: Mutability,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MethodSig {
pub header: FnHeader,
pub decl: P<FnDecl>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitItem {
pub id: NodeId,
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub generics: Generics,
pub node: TraitItemKind,
pub span: Span,
pub tokens: Option<TokenStream>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitItemKind {
Const(P<Ty>, Option<P<Expr>>),
Method(MethodSig, Option<P<Block>>),
Type(GenericBounds, Option<P<Ty>>),
Macro(Mac),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ImplItem {
pub id: NodeId,
pub ident: Ident,
pub vis: Visibility,
pub defaultness: Defaultness,
pub attrs: Vec<Attribute>,
pub generics: Generics,
pub node: ImplItemKind,
pub span: Span,
pub tokens: Option<TokenStream>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ImplItemKind {
Const(P<Ty>, P<Expr>),
Method(MethodSig, P<Block>),
Type(P<Ty>),
Existential(GenericBounds),
Macro(Mac),
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
pub enum IntTy {
Isize,
I8,
I16,
I32,
I64,
I128,
}
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::Isize => "isize",
IntTy::I8 => "i8",
IntTy::I16 => "i16",
IntTy::I32 => "i32",
IntTy::I64 => "i64",
IntTy::I128 => "i128",
}
}
pub fn val_to_string(&self, val: i128) -> String {
format!("{}{}", val as u128, self.ty_to_string())
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
IntTy::Isize => return None,
IntTy::I8 => 8,
IntTy::I16 => 16,
IntTy::I32 => 32,
IntTy::I64 => 64,
IntTy::I128 => 128,
})
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Copy)]
pub enum UintTy {
Usize,
U8,
U16,
U32,
U64,
U128,
}
impl UintTy {
pub fn ty_to_string(&self) -> &'static str {
match *self {
UintTy::Usize => "usize",
UintTy::U8 => "u8",
UintTy::U16 => "u16",
UintTy::U32 => "u32",
UintTy::U64 => "u64",
UintTy::U128 => "u128",
}
}
pub fn val_to_string(&self, val: u128) -> String {
format!("{}{}", val, self.ty_to_string())
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
UintTy::Usize => return None,
UintTy::U8 => 8,
UintTy::U16 => 16,
UintTy::U32 => 32,
UintTy::U64 => 64,
UintTy::U128 => 128,
})
}
}
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, RustcEncodable, RustcDecodable, Debug)]
pub struct TypeBinding {
pub id: NodeId,
pub ident: Ident,
pub ty: P<Ty>,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Ty {
pub id: NodeId,
pub node: TyKind,
pub span: Span,
}
impl fmt::Debug for Ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "type({})", pprust::ty_to_string(self))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct BareFnTy {
pub unsafety: Unsafety,
pub abi: Abi,
pub generic_params: Vec<GenericParam>,
pub decl: P<FnDecl>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum TyKind {
Slice(P<Ty>),
Array(P<Ty>, AnonConst),
Ptr(MutTy),
Rptr(Option<Lifetime>, MutTy),
BareFn(P<BareFnTy>),
Never,
Tup(Vec<P<Ty>>),
Path(Option<QSelf>, Path),
TraitObject(GenericBounds, TraitObjectSyntax),
ImplTrait(NodeId, GenericBounds),
Paren(P<Ty>),
Typeof(AnonConst),
Infer,
ImplicitSelf,
Mac(Mac),
Err,
CVarArgs,
}
impl TyKind {
pub fn is_implicit_self(&self) -> bool {
if let TyKind::ImplicitSelf = *self {
true
} else {
false
}
}
pub fn is_unit(&self) -> bool {
if let TyKind::Tup(ref tys) = *self {
tys.is_empty()
} else {
false
}
}
}
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitObjectSyntax {
Dyn,
None,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum AsmDialect {
Att,
Intel,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsmOutput {
pub constraint: Symbol,
pub expr: P<Expr>,
pub is_rw: bool,
pub is_indirect: bool,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsm {
pub asm: Symbol,
pub asm_str_style: StrStyle,
pub outputs: Vec<InlineAsmOutput>,
pub inputs: Vec<(Symbol, P<Expr>)>,
pub clobbers: Vec<Symbol>,
pub volatile: bool,
pub alignstack: bool,
pub dialect: AsmDialect,
pub ctxt: SyntaxContext,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Arg {
pub ty: P<Ty>,
pub pat: P<Pat>,
pub id: NodeId,
pub source: ArgSource,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ArgSource {
Normal,
AsyncFn(P<Pat>),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum SelfKind {
Value(Mutability),
Region(Option<Lifetime>, Mutability),
Explicit(P<Ty>, Mutability),
}
pub type ExplicitSelf = Spanned<SelfKind>;
impl Arg {
pub fn to_self(&self) -> Option<ExplicitSelf> {
if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.node {
if ident.name == keywords::SelfLower.name() {
return match self.ty.node {
TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.node.is_implicit_self() => {
Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
}
_ => Some(respan(
self.pat.span.to(self.ty.span),
SelfKind::Explicit(self.ty.clone(), mutbl),
)),
};
}
}
None
}
pub fn is_self(&self) -> bool {
if let PatKind::Ident(_, ident, _) = self.pat.node {
ident.name == keywords::SelfLower.name()
} else {
false
}
}
pub fn from_self(eself: ExplicitSelf, eself_ident: Ident) -> Arg {
let span = eself.span.to(eself_ident.span);
let infer_ty = P(Ty {
id: DUMMY_NODE_ID,
node: TyKind::ImplicitSelf,
span,
});
let arg = |mutbl, ty| Arg {
pat: P(Pat {
id: DUMMY_NODE_ID,
node: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
span,
}),
ty,
id: DUMMY_NODE_ID,
source: ArgSource::Normal,
};
match eself.node {
SelfKind::Explicit(ty, mutbl) => arg(mutbl, ty),
SelfKind::Value(mutbl) => arg(mutbl, infer_ty),
SelfKind::Region(lt, mutbl) => arg(
Mutability::Immutable,
P(Ty {
id: DUMMY_NODE_ID,
node: TyKind::Rptr(
lt,
MutTy {
ty: infer_ty,
mutbl: mutbl,
},
),
span,
}),
),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FnDecl {
pub inputs: Vec<Arg>,
pub output: FunctionRetTy,
pub c_variadic: bool,
}
impl FnDecl {
pub fn get_self(&self) -> Option<ExplicitSelf> {
self.inputs.get(0).and_then(Arg::to_self)
}
pub fn has_self(&self) -> bool {
self.inputs.get(0).map(Arg::is_self).unwrap_or(false)
}
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum IsAuto {
Yes,
No,
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum Unsafety {
Unsafe,
Normal,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct AsyncArgument {
pub ident: Ident,
pub arg: Arg,
pub stmt: Stmt,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum IsAsync {
Async {
closure_id: NodeId,
return_impl_trait_id: NodeId,
arguments: Vec<AsyncArgument>,
},
NotAsync,
}
impl IsAsync {
pub fn is_async(&self) -> bool {
if let IsAsync::Async { .. } = *self {
true
} else {
false
}
}
pub fn opt_return_id(&self) -> Option<NodeId> {
match self {
IsAsync::Async {
return_impl_trait_id,
..
} => Some(*return_impl_trait_id),
IsAsync::NotAsync => None,
}
}
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum Constness {
Const,
NotConst,
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable)]
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, RustcEncodable, RustcDecodable, Debug)]
pub enum FunctionRetTy {
Default(Span),
Ty(P<Ty>),
}
impl FunctionRetTy {
pub fn span(&self) -> Span {
match *self {
FunctionRetTy::Default(span) => span,
FunctionRetTy::Ty(ref ty) => ty.span,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mod {
pub inner: Span,
pub items: Vec<P<Item>>,
pub inline: bool,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ForeignMod {
pub abi: Abi,
pub items: Vec<ForeignItem>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
pub struct GlobalAsm {
pub asm: Symbol,
pub ctxt: SyntaxContext,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct EnumDef {
pub variants: Vec<Variant>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Variant_ {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub data: VariantData,
pub disr_expr: Option<AnonConst>,
}
pub type Variant = Spanned<Variant_>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum UseTreeKind {
Simple(Option<Ident>, NodeId, NodeId),
Nested(Vec<(UseTree, NodeId)>),
Glob,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct UseTree {
pub prefix: Path,
pub kind: UseTreeKind,
pub span: Span,
}
impl UseTree {
pub fn ident(&self) -> Ident {
match self.kind {
UseTreeKind::Simple(Some(rename), ..) => rename,
UseTreeKind::Simple(None, ..) => {
self.prefix
.segments
.last()
.expect("empty prefix in a simple import")
.ident
}
_ => panic!("`UseTree::ident` can only be used on a simple import"),
}
}
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum AttrStyle {
Outer,
Inner,
}
#[derive(
Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, PartialOrd, Ord, Copy,
)]
pub struct AttrId(pub usize);
impl Idx for AttrId {
fn new(idx: usize) -> Self {
AttrId(idx)
}
fn index(self) -> usize {
self.0
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Attribute {
pub id: AttrId,
pub style: AttrStyle,
pub path: Path,
pub tokens: TokenStream,
pub is_sugared_doc: bool,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitRef {
pub path: Path,
pub ref_id: NodeId,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct PolyTraitRef {
pub bound_generic_params: Vec<GenericParam>,
pub trait_ref: TraitRef,
pub span: Span,
}
impl PolyTraitRef {
pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
PolyTraitRef {
bound_generic_params: generic_params,
trait_ref: TraitRef {
path: path,
ref_id: DUMMY_NODE_ID,
},
span,
}
}
}
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum CrateSugar {
PubCrate,
JustCrate,
}
pub type Visibility = Spanned<VisibilityKind>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum VisibilityKind {
Public,
Crate(CrateSugar),
Restricted { path: P<Path>, id: NodeId },
Inherited,
}
impl VisibilityKind {
pub fn is_pub(&self) -> bool {
if let VisibilityKind::Public = *self {
true
} else {
false
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, Debug)]
pub enum VariantData {
Struct(Vec<StructField>, bool),
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 ctor_id(&self) -> Option<NodeId> {
match *self {
VariantData::Struct(..) => None,
VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Item {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub node: ItemKind,
pub vis: Visibility,
pub span: Span,
pub tokens: Option<TokenStream>,
}
impl Item {
pub fn span_with_attributes(&self) -> Span {
self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FnHeader {
pub unsafety: Unsafety,
pub asyncness: Spanned<IsAsync>,
pub constness: Spanned<Constness>,
pub abi: Abi,
}
impl Default for FnHeader {
fn default() -> FnHeader {
FnHeader {
unsafety: Unsafety::Normal,
asyncness: dummy_spanned(IsAsync::NotAsync),
constness: dummy_spanned(Constness::NotConst),
abi: Abi::Rust,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ItemKind {
ExternCrate(Option<Name>),
Use(P<UseTree>),
Static(P<Ty>, Mutability, P<Expr>),
Const(P<Ty>, P<Expr>),
Fn(P<FnDecl>, FnHeader, Generics, P<Block>),
Mod(Mod),
ForeignMod(ForeignMod),
GlobalAsm(P<GlobalAsm>),
Ty(P<Ty>, Generics),
Existential(GenericBounds, Generics),
Enum(EnumDef, Generics),
Struct(VariantData, Generics),
Union(VariantData, Generics),
Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
TraitAlias(Generics, GenericBounds),
Impl(
Unsafety,
ImplPolarity,
Defaultness,
Generics,
Option<TraitRef>,
P<Ty>,
Vec<ImplItem>,
),
Mac(Mac),
MacroDef(MacroDef),
}
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::GlobalAsm(..) => "global asm",
ItemKind::Ty(..) => "type alias",
ItemKind::Existential(..) => "existential type",
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Union(..) => "union",
ItemKind::Trait(..) => "trait",
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, 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, RustcEncodable, RustcDecodable, Debug)]
pub enum ForeignItemKind {
Fn(P<FnDecl>, Generics),
Static(P<Ty>, Mutability),
Ty,
Macro(Mac),
}
impl ForeignItemKind {
pub fn descriptive_variant(&self) -> &str {
match *self {
ForeignItemKind::Fn(..) => "foreign function",
ForeignItemKind::Static(..) => "foreign static item",
ForeignItemKind::Ty => "foreign type",
ForeignItemKind::Macro(..) => "macro in foreign module",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serialize;
#[test]
fn check_asts_encodable() {
fn assert_encodable<T: serialize::Encodable>() {}
assert_encodable::<Crate>();
}
}