1
Fork 0

Remove some unnecessary indirection from AST structures

This commit is contained in:
Vadim Petrochenkov 2016-02-11 23:33:09 +03:00
parent aa1dc0975a
commit 77cc5764b9
23 changed files with 271 additions and 254 deletions

View file

@ -614,7 +614,7 @@ impl fold::Folder for ReplaceBodyWithLoop {
} }
} }
fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> { fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
match i.node { match i.node {
ast::TraitItemKind::Const(..) => { ast::TraitItemKind::Const(..) => {
self.within_static_or_const = true; self.within_static_or_const = true;
@ -626,7 +626,7 @@ impl fold::Folder for ReplaceBodyWithLoop {
} }
} }
fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> { fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
match i.node { match i.node {
ast::ImplItemKind::Const(..) => { ast::ImplItemKind::Const(..) => {
self.within_static_or_const = true; self.within_static_or_const = true;

View file

@ -561,7 +561,7 @@ impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
type_parameters: &ast::Generics, type_parameters: &ast::Generics,
trait_ref: &Option<ast::TraitRef>, trait_ref: &Option<ast::TraitRef>,
typ: &ast::Ty, typ: &ast::Ty,
impl_items: &[P<ast::ImplItem>]) { impl_items: &[ast::ImplItem]) {
let mut has_self_ref = false; let mut has_self_ref = false;
if let Some(impl_data) = self.save_ctxt.get_item_data(item) { if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
down_cast_data!(impl_data, ImplData, self, item.span); down_cast_data!(impl_data, ImplData, self, item.span);
@ -602,7 +602,7 @@ impl <'l, 'tcx> DumpCsvVisitor<'l, 'tcx> {
item: &ast::Item, item: &ast::Item,
generics: &ast::Generics, generics: &ast::Generics,
trait_refs: &ast::TyParamBounds, trait_refs: &ast::TyParamBounds,
methods: &[P<ast::TraitItem>]) { methods: &[ast::TraitItem]) {
let qualname = format!("::{}", self.tcx.map.path_to_string(item.id)); let qualname = format!("::{}", self.tcx.map.path_to_string(item.id));
let val = self.span.snippet(item.span); let val = self.span.snippet(item.span);
let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait); let sub_span = self.span.sub_span_after_keyword(item.span, keywords::Trait);

View file

@ -287,7 +287,7 @@ impl PathParameters {
} }
} }
pub fn bindings(&self) -> Vec<&P<TypeBinding>> { pub fn bindings(&self) -> Vec<&TypeBinding> {
match *self { match *self {
PathParameters::AngleBracketed(ref data) => { PathParameters::AngleBracketed(ref data) => {
data.bindings.iter().collect() data.bindings.iter().collect()
@ -308,7 +308,7 @@ pub struct AngleBracketedParameterData {
pub types: P<[P<Ty>]>, pub types: P<[P<Ty>]>,
/// Bindings (equality constraints) on associated types, if present. /// Bindings (equality constraints) on associated types, if present.
/// e.g., `Foo<A=Bar>`. /// e.g., `Foo<A=Bar>`.
pub bindings: P<[P<TypeBinding>]>, pub bindings: P<[TypeBinding]>,
} }
impl AngleBracketedParameterData { impl AngleBracketedParameterData {
@ -508,7 +508,7 @@ impl PartialEq for MetaItemKind {
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct Block { pub struct Block {
/// Statements in a block /// Statements in a block
pub stmts: Vec<P<Stmt>>, pub stmts: Vec<Stmt>,
/// An expression at the end of the block /// An expression at the end of the block
/// without a semicolon, if any /// without a semicolon, if any
pub expr: Option<P<Expr>>, pub expr: Option<P<Expr>>,
@ -1716,12 +1716,12 @@ pub struct Mod {
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct ForeignMod { pub struct ForeignMod {
pub abi: Abi, pub abi: Abi,
pub items: Vec<P<ForeignItem>>, pub items: Vec<ForeignItem>,
} }
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
pub struct EnumDef { pub struct EnumDef {
pub variants: Vec<P<Variant>>, pub variants: Vec<Variant>,
} }
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
@ -1988,7 +1988,7 @@ pub enum ItemKind {
Trait(Unsafety, Trait(Unsafety,
Generics, Generics,
TyParamBounds, TyParamBounds,
Vec<P<TraitItem>>), Vec<TraitItem>),
// Default trait implementations // Default trait implementations
/// ///
@ -2000,7 +2000,7 @@ pub enum ItemKind {
Generics, Generics,
Option<TraitRef>, // (optional) trait this impl implements Option<TraitRef>, // (optional) trait this impl implements
P<Ty>, // self P<Ty>, // self
Vec<P<ImplItem>>), Vec<ImplItem>),
/// A macro invocation (which includes macro definition) /// A macro invocation (which includes macro definition)
Mac(Mac), Mac(Mac),
} }

View file

@ -72,7 +72,7 @@ impl<'a, F> fold::Folder for Context<'a, F> where F: FnMut(&[ast::Attribute]) ->
fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> { fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
fold_opt_expr(self, expr) fold_opt_expr(self, expr)
} }
fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> { fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
fold_stmt(self, stmt) fold_stmt(self, stmt)
} }
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
@ -95,8 +95,8 @@ pub fn strip_items<'a, F>(diagnostic: &'a Handler,
} }
fn filter_foreign_item<F>(cx: &mut Context<F>, fn filter_foreign_item<F>(cx: &mut Context<F>,
item: P<ast::ForeignItem>) item: ast::ForeignItem)
-> Option<P<ast::ForeignItem>> where -> Option<ast::ForeignItem> where
F: FnMut(&[ast::Attribute]) -> bool F: FnMut(&[ast::Attribute]) -> bool
{ {
if foreign_item_in_cfg(cx, &item) { if foreign_item_in_cfg(cx, &item) {
@ -153,18 +153,15 @@ fn fold_item_kind<F>(cx: &mut Context<F>, item: ast::ItemKind) -> ast::ItemKind
if !(cx.in_cfg)(&v.node.attrs) { if !(cx.in_cfg)(&v.node.attrs) {
None None
} else { } else {
Some(v.map(|Spanned {node: ast::Variant_ {name, attrs, data, Some(Spanned {
disr_expr}, span}| { node: ast::Variant_ {
Spanned { name: v.node.name,
node: ast::Variant_ { attrs: v.node.attrs,
name: name, data: fold_struct(cx, v.node.data),
attrs: attrs, disr_expr: v.node.disr_expr,
data: fold_struct(cx, data), },
disr_expr: disr_expr, span: v.span
}, })
span: span
}
}))
} }
}); });
ast::ItemKind::Enum(ast::EnumDef { ast::ItemKind::Enum(ast::EnumDef {
@ -225,11 +222,11 @@ fn fold_expr<F>(cx: &mut Context<F>, expr: P<ast::Expr>) -> P<ast::Expr> where
}) })
} }
fn fold_stmt<F>(cx: &mut Context<F>, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> fn fold_stmt<F>(cx: &mut Context<F>, stmt: ast::Stmt) -> SmallVector<ast::Stmt>
where F: FnMut(&[ast::Attribute]) -> bool where F: FnMut(&[ast::Attribute]) -> bool
{ {
if stmt_in_cfg(cx, &stmt) { if stmt_in_cfg(cx, &stmt) {
stmt.and_then(|s| fold::noop_fold_stmt(s, cx)) fold::noop_fold_stmt(stmt, cx)
} else { } else {
SmallVector::zero() SmallVector::zero()
} }

View file

@ -82,16 +82,16 @@ impl Annotatable {
} }
} }
pub fn expect_trait_item(self) -> P<ast::TraitItem> { pub fn expect_trait_item(self) -> ast::TraitItem {
match self { match self {
Annotatable::TraitItem(i) => i, Annotatable::TraitItem(i) => i.unwrap(),
_ => panic!("expected Item") _ => panic!("expected Item")
} }
} }
pub fn expect_impl_item(self) -> P<ast::ImplItem> { pub fn expect_impl_item(self) -> ast::ImplItem {
match self { match self {
Annotatable::ImplItem(i) => i, Annotatable::ImplItem(i) => i.unwrap(),
_ => panic!("expected Item") _ => panic!("expected Item")
} }
} }
@ -204,8 +204,8 @@ impl<F> IdentMacroExpander for F
macro_rules! make_stmts_default { macro_rules! make_stmts_default {
($me:expr) => { ($me:expr) => {
$me.make_expr().map(|e| { $me.make_expr().map(|e| {
SmallVector::one(P(codemap::respan( SmallVector::one(codemap::respan(
e.span, ast::StmtKind::Expr(e, ast::DUMMY_NODE_ID)))) e.span, ast::StmtKind::Expr(e, ast::DUMMY_NODE_ID)))
}) })
} }
} }
@ -223,7 +223,7 @@ pub trait MacResult {
} }
/// Create zero or more impl items. /// Create zero or more impl items.
fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> { fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
None None
} }
@ -236,7 +236,7 @@ pub trait MacResult {
/// ///
/// By default this attempts to create an expression statement, /// By default this attempts to create an expression statement,
/// returning None if that fails. /// returning None if that fails.
fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> { fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
make_stmts_default!(self) make_stmts_default!(self)
} }
@ -273,8 +273,8 @@ make_MacEager! {
expr: P<ast::Expr>, expr: P<ast::Expr>,
pat: P<ast::Pat>, pat: P<ast::Pat>,
items: SmallVector<P<ast::Item>>, items: SmallVector<P<ast::Item>>,
impl_items: SmallVector<P<ast::ImplItem>>, impl_items: SmallVector<ast::ImplItem>,
stmts: SmallVector<P<ast::Stmt>>, stmts: SmallVector<ast::Stmt>,
ty: P<ast::Ty>, ty: P<ast::Ty>,
} }
@ -287,11 +287,11 @@ impl MacResult for MacEager {
self.items self.items
} }
fn make_impl_items(self: Box<Self>) -> Option<SmallVector<P<ast::ImplItem>>> { fn make_impl_items(self: Box<Self>) -> Option<SmallVector<ast::ImplItem>> {
self.impl_items self.impl_items
} }
fn make_stmts(self: Box<Self>) -> Option<SmallVector<P<ast::Stmt>>> { fn make_stmts(self: Box<Self>) -> Option<SmallVector<ast::Stmt>> {
match self.stmts.as_ref().map_or(0, |s| s.len()) { match self.stmts.as_ref().map_or(0, |s| s.len()) {
0 => make_stmts_default!(self), 0 => make_stmts_default!(self),
_ => self.stmts, _ => self.stmts,
@ -391,7 +391,7 @@ impl MacResult for DummyResult {
} }
} }
fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<P<ast::ImplItem>>> { fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVector<ast::ImplItem>> {
if self.expr_only { if self.expr_only {
None None
} else { } else {
@ -399,11 +399,11 @@ impl MacResult for DummyResult {
} }
} }
fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<P<ast::Stmt>>> { fn make_stmts(self: Box<DummyResult>) -> Option<SmallVector<ast::Stmt>> {
Some(SmallVector::one(P( Some(SmallVector::one(
codemap::respan(self.span, codemap::respan(self.span,
ast::StmtKind::Expr(DummyResult::raw_expr(self.span), ast::StmtKind::Expr(DummyResult::raw_expr(self.span),
ast::DUMMY_NODE_ID))))) ast::DUMMY_NODE_ID))))
} }
} }

View file

@ -34,7 +34,7 @@ pub trait AstBuilder {
idents: Vec<ast::Ident> , idents: Vec<ast::Ident> ,
lifetimes: Vec<ast::Lifetime>, lifetimes: Vec<ast::Lifetime>,
types: Vec<P<ast::Ty>>, types: Vec<P<ast::Ty>>,
bindings: Vec<P<ast::TypeBinding>> ) bindings: Vec<ast::TypeBinding> )
-> ast::Path; -> ast::Path;
fn qpath(&self, self_type: P<ast::Ty>, fn qpath(&self, self_type: P<ast::Ty>,
@ -46,7 +46,7 @@ pub trait AstBuilder {
ident: ast::Ident, ident: ast::Ident,
lifetimes: Vec<ast::Lifetime>, lifetimes: Vec<ast::Lifetime>,
types: Vec<P<ast::Ty>>, types: Vec<P<ast::Ty>>,
bindings: Vec<P<ast::TypeBinding>>) bindings: Vec<ast::TypeBinding>)
-> (ast::QSelf, ast::Path); -> (ast::QSelf, ast::Path);
// types // types
@ -88,8 +88,8 @@ pub trait AstBuilder {
-> ast::LifetimeDef; -> ast::LifetimeDef;
// statements // statements
fn stmt_expr(&self, expr: P<ast::Expr>) -> P<ast::Stmt>; fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt;
fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, ex: P<ast::Expr>) -> P<ast::Stmt>; fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, ex: P<ast::Expr>) -> ast::Stmt;
fn stmt_let_typed(&self, fn stmt_let_typed(&self,
sp: Span, sp: Span,
mutbl: bool, mutbl: bool,
@ -97,14 +97,14 @@ pub trait AstBuilder {
typ: P<ast::Ty>, typ: P<ast::Ty>,
ex: P<ast::Expr>) ex: P<ast::Expr>)
-> P<ast::Stmt>; -> P<ast::Stmt>;
fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> P<ast::Stmt>; fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt;
// blocks // blocks
fn block(&self, span: Span, stmts: Vec<P<ast::Stmt>>, fn block(&self, span: Span, stmts: Vec<ast::Stmt>,
expr: Option<P<ast::Expr>>) -> P<ast::Block>; expr: Option<P<ast::Expr>>) -> P<ast::Block>;
fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block>; fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block>;
fn block_all(&self, span: Span, fn block_all(&self, span: Span,
stmts: Vec<P<ast::Stmt>>, stmts: Vec<ast::Stmt>,
expr: Option<P<ast::Expr>>) -> P<ast::Block>; expr: Option<P<ast::Expr>>) -> P<ast::Block>;
// expressions // expressions
@ -206,9 +206,9 @@ pub trait AstBuilder {
fn lambda_expr_1(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; fn lambda_expr_1(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>;
fn lambda_stmts(&self, span: Span, ids: Vec<ast::Ident>, fn lambda_stmts(&self, span: Span, ids: Vec<ast::Ident>,
blk: Vec<P<ast::Stmt>>) -> P<ast::Expr>; blk: Vec<ast::Stmt>) -> P<ast::Expr>;
fn lambda_stmts_0(&self, span: Span, stmts: Vec<P<ast::Stmt>>) -> P<ast::Expr>; fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr>;
fn lambda_stmts_1(&self, span: Span, stmts: Vec<P<ast::Stmt>>, fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>,
ident: ast::Ident) -> P<ast::Expr>; ident: ast::Ident) -> P<ast::Expr>;
// items // items
@ -315,7 +315,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
mut idents: Vec<ast::Ident> , mut idents: Vec<ast::Ident> ,
lifetimes: Vec<ast::Lifetime>, lifetimes: Vec<ast::Lifetime>,
types: Vec<P<ast::Ty>>, types: Vec<P<ast::Ty>>,
bindings: Vec<P<ast::TypeBinding>> ) bindings: Vec<ast::TypeBinding> )
-> ast::Path { -> ast::Path {
let last_identifier = idents.pop().unwrap(); let last_identifier = idents.pop().unwrap();
let mut segments: Vec<ast::PathSegment> = idents.into_iter() let mut segments: Vec<ast::PathSegment> = idents.into_iter()
@ -360,7 +360,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
ident: ast::Ident, ident: ast::Ident,
lifetimes: Vec<ast::Lifetime>, lifetimes: Vec<ast::Lifetime>,
types: Vec<P<ast::Ty>>, types: Vec<P<ast::Ty>>,
bindings: Vec<P<ast::TypeBinding>>) bindings: Vec<ast::TypeBinding>)
-> (ast::QSelf, ast::Path) { -> (ast::QSelf, ast::Path) {
let mut path = trait_path; let mut path = trait_path;
path.segments.push(ast::PathSegment { path.segments.push(ast::PathSegment {
@ -505,12 +505,12 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
} }
} }
fn stmt_expr(&self, expr: P<ast::Expr>) -> P<ast::Stmt> { fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt {
P(respan(expr.span, ast::StmtKind::Semi(expr, ast::DUMMY_NODE_ID))) respan(expr.span, ast::StmtKind::Semi(expr, ast::DUMMY_NODE_ID))
} }
fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident, fn stmt_let(&self, sp: Span, mutbl: bool, ident: ast::Ident,
ex: P<ast::Expr>) -> P<ast::Stmt> { ex: P<ast::Expr>) -> ast::Stmt {
let pat = if mutbl { let pat = if mutbl {
let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable); let binding_mode = ast::BindingMode::ByValue(ast::Mutability::Mutable);
self.pat_ident_binding_mode(sp, ident, binding_mode) self.pat_ident_binding_mode(sp, ident, binding_mode)
@ -526,7 +526,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
attrs: None, attrs: None,
}); });
let decl = respan(sp, ast::DeclKind::Local(local)); let decl = respan(sp, ast::DeclKind::Local(local));
P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))) respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))
} }
fn stmt_let_typed(&self, fn stmt_let_typed(&self,
@ -554,14 +554,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))) P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID)))
} }
fn block(&self, span: Span, stmts: Vec<P<ast::Stmt>>, fn block(&self, span: Span, stmts: Vec<ast::Stmt>,
expr: Option<P<Expr>>) -> P<ast::Block> { expr: Option<P<Expr>>) -> P<ast::Block> {
self.block_all(span, stmts, expr) self.block_all(span, stmts, expr)
} }
fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> P<ast::Stmt> { fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> ast::Stmt {
let decl = respan(sp, ast::DeclKind::Item(item)); let decl = respan(sp, ast::DeclKind::Item(item));
P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))) respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))
} }
fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> { fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> {
@ -569,7 +569,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
} }
fn block_all(&self, fn block_all(&self,
span: Span, span: Span,
stmts: Vec<P<ast::Stmt>>, stmts: Vec<ast::Stmt>,
expr: Option<P<ast::Expr>>) -> P<ast::Block> { expr: Option<P<ast::Expr>>) -> P<ast::Block> {
P(ast::Block { P(ast::Block {
stmts: stmts, stmts: stmts,
@ -923,14 +923,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> {
fn lambda_stmts(&self, fn lambda_stmts(&self,
span: Span, span: Span,
ids: Vec<ast::Ident>, ids: Vec<ast::Ident>,
stmts: Vec<P<ast::Stmt>>) stmts: Vec<ast::Stmt>)
-> P<ast::Expr> { -> P<ast::Expr> {
self.lambda(span, ids, self.block(span, stmts, None)) self.lambda(span, ids, self.block(span, stmts, None))
} }
fn lambda_stmts_0(&self, span: Span, stmts: Vec<P<ast::Stmt>>) -> P<ast::Expr> { fn lambda_stmts_0(&self, span: Span, stmts: Vec<ast::Stmt>) -> P<ast::Expr> {
self.lambda0(span, self.block(span, stmts, None)) self.lambda0(span, self.block(span, stmts, None))
} }
fn lambda_stmts_1(&self, span: Span, stmts: Vec<P<ast::Stmt>>, fn lambda_stmts_1(&self, span: Span, stmts: Vec<ast::Stmt>,
ident: ast::Ident) -> P<ast::Expr> { ident: ast::Ident) -> P<ast::Expr> {
self.lambda1(span, self.block(span, stmts, None), ident) self.lambda1(span, self.block(span, stmts, None), ident)
} }

View file

@ -503,8 +503,7 @@ pub fn expand_item_mac(it: P<ast::Item>,
} }
/// Expand a stmt /// Expand a stmt
fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> { fn expand_stmt(stmt: Stmt, fld: &mut MacroExpander) -> SmallVector<Stmt> {
let stmt = stmt.and_then(|stmt| stmt);
let (mac, style, attrs) = match stmt.node { let (mac, style, attrs) = match stmt.node {
StmtKind::Mac(mac, style, attrs) => (mac, style, attrs), StmtKind::Mac(mac, style, attrs) => (mac, style, attrs),
_ => return expand_non_macro_stmt(stmt, fld) _ => return expand_non_macro_stmt(stmt, fld)
@ -514,7 +513,7 @@ fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
drop(attrs); drop(attrs);
let maybe_new_items = let maybe_new_items =
expand_mac_invoc(mac.and_then(|m| m), stmt.span, expand_mac_invoc(mac.unwrap(), stmt.span,
|r| r.make_stmts(), |r| r.make_stmts(),
|stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)), |stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)),
fld); fld);
@ -535,15 +534,13 @@ fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
// semicolon to the final statement produced by expansion. // semicolon to the final statement produced by expansion.
if style == MacStmtStyle::Semicolon { if style == MacStmtStyle::Semicolon {
if let Some(stmt) = fully_expanded.pop() { if let Some(stmt) = fully_expanded.pop() {
let new_stmt = stmt.map(|Spanned {node, span}| { let new_stmt = Spanned {
Spanned { node: match stmt.node {
node: match node { StmtKind::Expr(e, stmt_id) => StmtKind::Semi(e, stmt_id),
StmtKind::Expr(e, stmt_id) => StmtKind::Semi(e, stmt_id), _ => stmt.node /* might already have a semi */
_ => node /* might already have a semi */ },
}, span: stmt.span
span: span };
}
});
fully_expanded.push(new_stmt); fully_expanded.push(new_stmt);
} }
} }
@ -554,7 +551,7 @@ fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
// expand a non-macro stmt. this is essentially the fallthrough for // expand a non-macro stmt. this is essentially the fallthrough for
// expand_stmt, above. // expand_stmt, above.
fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander) fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander)
-> SmallVector<P<Stmt>> { -> SmallVector<Stmt> {
// is it a let? // is it a let?
match node { match node {
StmtKind::Decl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl { StmtKind::Decl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
@ -594,14 +591,14 @@ fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroE
attrs: fold::fold_thin_attrs(attrs, fld), attrs: fold::fold_thin_attrs(attrs, fld),
} }
}); });
SmallVector::one(P(Spanned { SmallVector::one(Spanned {
node: StmtKind::Decl(P(Spanned { node: StmtKind::Decl(P(Spanned {
node: DeclKind::Local(rewritten_local), node: DeclKind::Local(rewritten_local),
span: span span: span
}), }),
node_id), node_id),
span: stmt_span span: stmt_span
})) })
} }
_ => { _ => {
noop_fold_stmt(Spanned { noop_fold_stmt(Spanned {
@ -919,24 +916,28 @@ fn expand_annotatable(a: Annotatable,
}, },
Annotatable::TraitItem(it) => match it.node { Annotatable::TraitItem(it) => match it.node {
ast::TraitItemKind::Method(_, Some(_)) => SmallVector::one(it.map(|ti| ast::TraitItem { ast::TraitItemKind::Method(_, Some(_)) => {
id: ti.id, let ti = it.unwrap();
ident: ti.ident, SmallVector::one(ast::TraitItem {
attrs: ti.attrs, id: ti.id,
node: match ti.node { ident: ti.ident,
ast::TraitItemKind::Method(sig, Some(body)) => { attrs: ti.attrs,
let (sig, body) = expand_and_rename_method(sig, body, fld); node: match ti.node {
ast::TraitItemKind::Method(sig, Some(body)) ast::TraitItemKind::Method(sig, Some(body)) => {
} let (sig, body) = expand_and_rename_method(sig, body, fld);
_ => unreachable!() ast::TraitItemKind::Method(sig, Some(body))
}, }
span: fld.new_span(ti.span) _ => unreachable!()
})), },
_ => fold::noop_fold_trait_item(it, fld) span: fld.new_span(ti.span)
}.into_iter().map(Annotatable::TraitItem).collect(), })
}
_ => fold::noop_fold_trait_item(it.unwrap(), fld)
}.into_iter().map(|ti| Annotatable::TraitItem(P(ti))).collect(),
Annotatable::ImplItem(ii) => { Annotatable::ImplItem(ii) => {
expand_impl_item(ii, fld).into_iter().map(Annotatable::ImplItem).collect() expand_impl_item(ii.unwrap(), fld).into_iter().
map(|ii| Annotatable::ImplItem(P(ii))).collect()
} }
}; };
@ -1052,10 +1053,10 @@ fn expand_item_multi_modifier(mut it: Annotatable,
expand_item_multi_modifier(it, fld) expand_item_multi_modifier(it, fld)
} }
fn expand_impl_item(ii: P<ast::ImplItem>, fld: &mut MacroExpander) fn expand_impl_item(ii: ast::ImplItem, fld: &mut MacroExpander)
-> SmallVector<P<ast::ImplItem>> { -> SmallVector<ast::ImplItem> {
match ii.node { match ii.node {
ast::ImplItemKind::Method(..) => SmallVector::one(ii.map(|ii| ast::ImplItem { ast::ImplItemKind::Method(..) => SmallVector::one(ast::ImplItem {
id: ii.id, id: ii.id,
ident: ii.ident, ident: ii.ident,
attrs: ii.attrs, attrs: ii.attrs,
@ -1068,12 +1069,12 @@ fn expand_impl_item(ii: P<ast::ImplItem>, fld: &mut MacroExpander)
_ => unreachable!() _ => unreachable!()
}, },
span: fld.new_span(ii.span) span: fld.new_span(ii.span)
})), }),
ast::ImplItemKind::Macro(_) => { ast::ImplItemKind::Macro(_) => {
let (span, mac) = ii.and_then(|ii| match ii.node { let (span, mac) = match ii.node {
ast::ImplItemKind::Macro(mac) => (ii.span, mac), ast::ImplItemKind::Macro(mac) => (ii.span, mac),
_ => unreachable!() _ => unreachable!()
}); };
let maybe_new_items = let maybe_new_items =
expand_mac_invoc(mac, span, expand_mac_invoc(mac, span,
|r| r.make_impl_items(), |r| r.make_impl_items(),
@ -1198,7 +1199,7 @@ impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
expand_item_kind(item, self) expand_item_kind(item, self)
} }
fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> { fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
expand_stmt(stmt, self) expand_stmt(stmt, self)
} }
@ -1210,13 +1211,13 @@ impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
expand_arm(arm, self) expand_arm(arm, self)
} }
fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> { fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
expand_annotatable(Annotatable::TraitItem(i), self) expand_annotatable(Annotatable::TraitItem(P(i)), self)
.into_iter().map(|i| i.expect_trait_item()).collect() .into_iter().map(|i| i.expect_trait_item()).collect()
} }
fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> { fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
expand_annotatable(Annotatable::ImplItem(i), self) expand_annotatable(Annotatable::ImplItem(P(i)), self)
.into_iter().map(|i| i.expect_impl_item()).collect() .into_iter().map(|i| i.expect_impl_item()).collect()
} }
@ -1359,7 +1360,7 @@ fn mark_pat(pat: P<ast::Pat>, m: Mrk) -> P<ast::Pat> {
} }
// apply a given mark to the given stmt. Used following the expansion of a macro. // apply a given mark to the given stmt. Used following the expansion of a macro.
fn mark_stmt(stmt: P<ast::Stmt>, m: Mrk) -> P<ast::Stmt> { fn mark_stmt(stmt: ast::Stmt, m: Mrk) -> ast::Stmt {
Marker{mark:m}.fold_stmt(stmt) Marker{mark:m}.fold_stmt(stmt)
.expect_one("marking a stmt didn't return exactly one stmt") .expect_one("marking a stmt didn't return exactly one stmt")
} }
@ -1371,7 +1372,7 @@ fn mark_item(expr: P<ast::Item>, m: Mrk) -> P<ast::Item> {
} }
// apply a given mark to the given item. Used following the expansion of a macro. // apply a given mark to the given item. Used following the expansion of a macro.
fn mark_impl_item(ii: P<ast::ImplItem>, m: Mrk) -> P<ast::ImplItem> { fn mark_impl_item(ii: ast::ImplItem, m: Mrk) -> ast::ImplItem {
Marker{mark:m}.fold_impl_item(ii) Marker{mark:m}.fold_impl_item(ii)
.expect_one("marking an impl item didn't return exactly one impl item") .expect_one("marking an impl item didn't return exactly one impl item")
} }

View file

@ -114,22 +114,24 @@ pub mod rt {
} }
} }
impl ToTokens for P<ast::ImplItem> { impl ToTokens for ast::ImplItem {
fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
vec![TokenTree::Token(self.span, token::Interpolated(token::NtImplItem(self.clone())))] vec![TokenTree::Token(self.span,
token::Interpolated(token::NtImplItem(P(self.clone()))))]
} }
} }
impl ToTokens for P<ast::TraitItem> { impl ToTokens for ast::TraitItem {
fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
vec![TokenTree::Token(self.span, token::Interpolated(token::NtTraitItem(self.clone())))] vec![TokenTree::Token(self.span,
token::Interpolated(token::NtTraitItem(P(self.clone()))))]
} }
} }
impl ToTokens for P<ast::Stmt> { impl ToTokens for ast::Stmt {
fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> { fn to_tokens(&self, _cx: &ExtCtxt) -> Vec<TokenTree> {
let mut tts = vec![ let mut tts = vec![
TokenTree::Token(self.span, token::Interpolated(token::NtStmt(self.clone()))) TokenTree::Token(self.span, token::Interpolated(token::NtStmt(P(self.clone()))))
]; ];
// Some statements require a trailing semicolon. // Some statements require a trailing semicolon.
@ -312,7 +314,7 @@ pub mod rt {
pub trait ExtParseUtils { pub trait ExtParseUtils {
fn parse_item(&self, s: String) -> P<ast::Item>; fn parse_item(&self, s: String) -> P<ast::Item>;
fn parse_expr(&self, s: String) -> P<ast::Expr>; fn parse_expr(&self, s: String) -> P<ast::Expr>;
fn parse_stmt(&self, s: String) -> P<ast::Stmt>; fn parse_stmt(&self, s: String) -> ast::Stmt;
fn parse_tts(&self, s: String) -> Vec<TokenTree>; fn parse_tts(&self, s: String) -> Vec<TokenTree>;
} }
@ -326,7 +328,7 @@ pub mod rt {
self.parse_sess()).expect("parse error") self.parse_sess()).expect("parse error")
} }
fn parse_stmt(&self, s: String) -> P<ast::Stmt> { fn parse_stmt(&self, s: String) -> ast::Stmt {
parse::parse_stmt_from_source_str("<quote expansion>".to_string(), parse::parse_stmt_from_source_str("<quote expansion>".to_string(),
s, s,
self.cfg(), self.cfg(),
@ -371,7 +373,7 @@ pub fn parse_ty_panic(parser: &mut Parser) -> P<Ty> {
panictry!(parser.parse_ty()) panictry!(parser.parse_ty())
} }
pub fn parse_stmt_panic(parser: &mut Parser) -> Option<P<Stmt>> { pub fn parse_stmt_panic(parser: &mut Parser) -> Option<Stmt> {
panictry!(parser.parse_stmt()) panictry!(parser.parse_stmt())
} }
@ -710,7 +712,7 @@ fn expr_mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> {
mk_token_path(cx, sp, name) mk_token_path(cx, sp, name)
} }
fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<P<ast::Stmt>> { fn statements_mk_tt(cx: &ExtCtxt, tt: &TokenTree, matcher: bool) -> Vec<ast::Stmt> {
match *tt { match *tt {
TokenTree::Token(sp, SubstNt(ident, _)) => { TokenTree::Token(sp, SubstNt(ident, _)) => {
// tt.extend($ident.to_tokens(ext_cx)) // tt.extend($ident.to_tokens(ext_cx))
@ -831,7 +833,7 @@ fn parse_arguments_to_quote(cx: &ExtCtxt, tts: &[TokenTree])
(cx_expr, tts) (cx_expr, tts)
} }
fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<P<ast::Stmt>> { fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<ast::Stmt> {
// We also bind a single value, sp, to ext_cx.call_site() // We also bind a single value, sp, to ext_cx.call_site()
// //
// This causes every span in a token-tree quote to be attributed to the // This causes every span in a token-tree quote to be attributed to the
@ -872,7 +874,7 @@ fn mk_stmts_let(cx: &ExtCtxt, sp: Span) -> Vec<P<ast::Stmt>> {
vec!(stmt_let_sp, stmt_let_tt) vec!(stmt_let_sp, stmt_let_tt)
} }
fn statements_mk_tts(cx: &ExtCtxt, tts: &[TokenTree], matcher: bool) -> Vec<P<ast::Stmt>> { fn statements_mk_tts(cx: &ExtCtxt, tts: &[TokenTree], matcher: bool) -> Vec<ast::Stmt> {
let mut ss = Vec::new(); let mut ss = Vec::new();
for tt in tts { for tt in tts {
ss.extend(statements_mk_tt(cx, tt, matcher)); ss.extend(statements_mk_tt(cx, tt, matcher));

View file

@ -523,7 +523,7 @@ pub fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
}, },
"block" => token::NtBlock(panictry!(p.parse_block())), "block" => token::NtBlock(panictry!(p.parse_block())),
"stmt" => match panictry!(p.parse_stmt()) { "stmt" => match panictry!(p.parse_stmt()) {
Some(s) => token::NtStmt(s), Some(s) => token::NtStmt(P(s)),
None => { None => {
p.fatal("expected a statement").emit(); p.fatal("expected a statement").emit();
panic!(FatalError); panic!(FatalError);

View file

@ -87,7 +87,7 @@ impl<'a> MacResult for ParserAnyMacro<'a> {
} }
fn make_impl_items(self: Box<ParserAnyMacro<'a>>) fn make_impl_items(self: Box<ParserAnyMacro<'a>>)
-> Option<SmallVector<P<ast::ImplItem>>> { -> Option<SmallVector<ast::ImplItem>> {
let mut ret = SmallVector::zero(); let mut ret = SmallVector::zero();
loop { loop {
let mut parser = self.parser.borrow_mut(); let mut parser = self.parser.borrow_mut();
@ -101,7 +101,7 @@ impl<'a> MacResult for ParserAnyMacro<'a> {
} }
fn make_stmts(self: Box<ParserAnyMacro<'a>>) fn make_stmts(self: Box<ParserAnyMacro<'a>>)
-> Option<SmallVector<P<ast::Stmt>>> { -> Option<SmallVector<ast::Stmt>> {
let mut ret = SmallVector::zero(); let mut ret = SmallVector::zero();
loop { loop {
let mut parser = self.parser.borrow_mut(); let mut parser = self.parser.borrow_mut();

View file

@ -55,7 +55,7 @@ pub trait Folder : Sized {
noop_fold_view_path(view_path, self) noop_fold_view_path(view_path, self)
} }
fn fold_foreign_item(&mut self, ni: P<ForeignItem>) -> P<ForeignItem> { fn fold_foreign_item(&mut self, ni: ForeignItem) -> ForeignItem {
noop_fold_foreign_item(ni, self) noop_fold_foreign_item(ni, self)
} }
@ -75,11 +75,11 @@ pub trait Folder : Sized {
noop_fold_item_kind(i, self) noop_fold_item_kind(i, self)
} }
fn fold_trait_item(&mut self, i: P<TraitItem>) -> SmallVector<P<TraitItem>> { fn fold_trait_item(&mut self, i: TraitItem) -> SmallVector<TraitItem> {
noop_fold_trait_item(i, self) noop_fold_trait_item(i, self)
} }
fn fold_impl_item(&mut self, i: P<ImplItem>) -> SmallVector<P<ImplItem>> { fn fold_impl_item(&mut self, i: ImplItem) -> SmallVector<ImplItem> {
noop_fold_impl_item(i, self) noop_fold_impl_item(i, self)
} }
@ -91,8 +91,8 @@ pub trait Folder : Sized {
noop_fold_block(b, self) noop_fold_block(b, self)
} }
fn fold_stmt(&mut self, s: P<Stmt>) -> SmallVector<P<Stmt>> { fn fold_stmt(&mut self, s: Stmt) -> SmallVector<Stmt> {
s.and_then(|s| noop_fold_stmt(s, self)) noop_fold_stmt(s, self)
} }
fn fold_arm(&mut self, a: Arm) -> Arm { fn fold_arm(&mut self, a: Arm) -> Arm {
@ -123,7 +123,7 @@ pub trait Folder : Sized {
noop_fold_ty(t, self) noop_fold_ty(t, self)
} }
fn fold_ty_binding(&mut self, t: P<TypeBinding>) -> P<TypeBinding> { fn fold_ty_binding(&mut self, t: TypeBinding) -> TypeBinding {
noop_fold_ty_binding(t, self) noop_fold_ty_binding(t, self)
} }
@ -135,7 +135,7 @@ pub trait Folder : Sized {
noop_fold_foreign_mod(nm, self) noop_fold_foreign_mod(nm, self)
} }
fn fold_variant(&mut self, v: P<Variant>) -> P<Variant> { fn fold_variant(&mut self, v: Variant) -> Variant {
noop_fold_variant(v, self) noop_fold_variant(v, self)
} }
@ -367,13 +367,13 @@ pub fn noop_fold_decl<T: Folder>(d: P<Decl>, fld: &mut T) -> SmallVector<P<Decl>
}) })
} }
pub fn noop_fold_ty_binding<T: Folder>(b: P<TypeBinding>, fld: &mut T) -> P<TypeBinding> { pub fn noop_fold_ty_binding<T: Folder>(b: TypeBinding, fld: &mut T) -> TypeBinding {
b.map(|TypeBinding { id, ident, ty, span }| TypeBinding { TypeBinding {
id: fld.new_id(id), id: fld.new_id(b.id),
ident: ident, ident: b.ident,
ty: fld.fold_ty(ty), ty: fld.fold_ty(b.ty),
span: fld.new_span(span), span: fld.new_span(b.span),
}) }
} }
pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> { pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
@ -434,16 +434,16 @@ pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, items}: ForeignMod,
} }
} }
pub fn noop_fold_variant<T: Folder>(v: P<Variant>, fld: &mut T) -> P<Variant> { pub fn noop_fold_variant<T: Folder>(v: Variant, fld: &mut T) -> Variant {
v.map(|Spanned {node: Variant_ {name, attrs, data, disr_expr}, span}| Spanned { Spanned {
node: Variant_ { node: Variant_ {
name: name, name: v.node.name,
attrs: fold_attrs(attrs, fld), attrs: fold_attrs(v.node.attrs, fld),
data: fld.fold_variant_data(data), data: fld.fold_variant_data(v.node.data),
disr_expr: disr_expr.map(|e| fld.fold_expr(e)), disr_expr: v.node.disr_expr.map(|e| fld.fold_expr(e)),
}, },
span: fld.new_span(span), span: fld.new_span(v.span),
}) }
} }
pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident { pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident {
@ -653,11 +653,11 @@ pub fn noop_fold_interpolated<T: Folder>(nt: token::Nonterminal, fld: &mut T)
.expect_one("expected fold to produce exactly one item")), .expect_one("expected fold to produce exactly one item")),
token::NtBlock(block) => token::NtBlock(fld.fold_block(block)), token::NtBlock(block) => token::NtBlock(fld.fold_block(block)),
token::NtStmt(stmt) => token::NtStmt(stmt) =>
token::NtStmt(fld.fold_stmt(stmt) token::NtStmt(stmt.map(|stmt| fld.fold_stmt(stmt)
// this is probably okay, because the only folds likely // this is probably okay, because the only folds likely
// to peek inside interpolated nodes will be renamings/markings, // to peek inside interpolated nodes will be renamings/markings,
// which map single items to single items // which map single items to single items
.expect_one("expected fold to produce exactly one statement")), .expect_one("expected fold to produce exactly one statement"))),
token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)), token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)),
token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)), token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)),
token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)), token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)),
@ -669,11 +669,11 @@ pub fn noop_fold_interpolated<T: Folder>(nt: token::Nonterminal, fld: &mut T)
token::NtTT(tt) => token::NtTT(P(fld.fold_tt(&tt))), token::NtTT(tt) => token::NtTT(P(fld.fold_tt(&tt))),
token::NtArm(arm) => token::NtArm(fld.fold_arm(arm)), token::NtArm(arm) => token::NtArm(fld.fold_arm(arm)),
token::NtImplItem(arm) => token::NtImplItem(arm) =>
token::NtImplItem(fld.fold_impl_item(arm) token::NtImplItem(arm.map(|arm| fld.fold_impl_item(arm)
.expect_one("expected fold to produce exactly one item")), .expect_one("expected fold to produce exactly one item"))),
token::NtTraitItem(arm) => token::NtTraitItem(arm) =>
token::NtTraitItem(fld.fold_trait_item(arm) token::NtTraitItem(arm.map(|arm| fld.fold_trait_item(arm)
.expect_one("expected fold to produce exactly one item")), .expect_one("expected fold to produce exactly one item"))),
token::NtGenerics(generics) => token::NtGenerics(fld.fold_generics(generics)), token::NtGenerics(generics) => token::NtGenerics(fld.fold_generics(generics)),
token::NtWhereClause(where_clause) => token::NtWhereClause(where_clause) =>
token::NtWhereClause(fld.fold_where_clause(where_clause)), token::NtWhereClause(fld.fold_where_clause(where_clause)),
@ -962,13 +962,13 @@ pub fn noop_fold_item_kind<T: Folder>(i: ItemKind, folder: &mut T) -> ItemKind {
} }
} }
pub fn noop_fold_trait_item<T: Folder>(i: P<TraitItem>, folder: &mut T) pub fn noop_fold_trait_item<T: Folder>(i: TraitItem, folder: &mut T)
-> SmallVector<P<TraitItem>> { -> SmallVector<TraitItem> {
SmallVector::one(i.map(|TraitItem {id, ident, attrs, node, span}| TraitItem { SmallVector::one(TraitItem {
id: folder.new_id(id), id: folder.new_id(i.id),
ident: folder.fold_ident(ident), ident: folder.fold_ident(i.ident),
attrs: fold_attrs(attrs, folder), attrs: fold_attrs(i.attrs, folder),
node: match node { node: match i.node {
TraitItemKind::Const(ty, default) => { TraitItemKind::Const(ty, default) => {
TraitItemKind::Const(folder.fold_ty(ty), TraitItemKind::Const(folder.fold_ty(ty),
default.map(|x| folder.fold_expr(x))) default.map(|x| folder.fold_expr(x)))
@ -982,18 +982,18 @@ pub fn noop_fold_trait_item<T: Folder>(i: P<TraitItem>, folder: &mut T)
default.map(|x| folder.fold_ty(x))) default.map(|x| folder.fold_ty(x)))
} }
}, },
span: folder.new_span(span) span: folder.new_span(i.span)
})) })
} }
pub fn noop_fold_impl_item<T: Folder>(i: P<ImplItem>, folder: &mut T) pub fn noop_fold_impl_item<T: Folder>(i: ImplItem, folder: &mut T)
-> SmallVector<P<ImplItem>> { -> SmallVector<ImplItem> {
SmallVector::one(i.map(|ImplItem {id, ident, attrs, node, vis, span}| ImplItem { SmallVector::one(ImplItem {
id: folder.new_id(id), id: folder.new_id(i.id),
ident: folder.fold_ident(ident), ident: folder.fold_ident(i.ident),
attrs: fold_attrs(attrs, folder), attrs: fold_attrs(i.attrs, folder),
vis: vis, vis: i.vis,
node: match node { node: match i.node {
ast::ImplItemKind::Const(ty, expr) => { ast::ImplItemKind::Const(ty, expr) => {
ast::ImplItemKind::Const(folder.fold_ty(ty), folder.fold_expr(expr)) ast::ImplItemKind::Const(folder.fold_ty(ty), folder.fold_expr(expr))
} }
@ -1004,8 +1004,8 @@ pub fn noop_fold_impl_item<T: Folder>(i: P<ImplItem>, folder: &mut T)
ast::ImplItemKind::Type(ty) => ast::ImplItemKind::Type(folder.fold_ty(ty)), ast::ImplItemKind::Type(ty) => ast::ImplItemKind::Type(folder.fold_ty(ty)),
ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac)) ast::ImplItemKind::Macro(mac) => ast::ImplItemKind::Macro(folder.fold_mac(mac))
}, },
span: folder.new_span(span) span: folder.new_span(i.span)
})) })
} }
pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod { pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod {
@ -1086,12 +1086,12 @@ pub fn noop_fold_item_simple<T: Folder>(Item {id, ident, attrs, node, vis, span}
} }
} }
pub fn noop_fold_foreign_item<T: Folder>(ni: P<ForeignItem>, folder: &mut T) -> P<ForeignItem> { pub fn noop_fold_foreign_item<T: Folder>(ni: ForeignItem, folder: &mut T) -> ForeignItem {
ni.map(|ForeignItem {id, ident, attrs, node, span, vis}| ForeignItem { ForeignItem {
id: folder.new_id(id), id: folder.new_id(ni.id),
ident: folder.fold_ident(ident), ident: folder.fold_ident(ni.ident),
attrs: fold_attrs(attrs, folder), attrs: fold_attrs(ni.attrs, folder),
node: match node { node: match ni.node {
ForeignItemKind::Fn(fdec, generics) => { ForeignItemKind::Fn(fdec, generics) => {
ForeignItemKind::Fn(folder.fold_fn_decl(fdec), folder.fold_generics(generics)) ForeignItemKind::Fn(folder.fold_fn_decl(fdec), folder.fold_generics(generics))
} }
@ -1099,9 +1099,9 @@ pub fn noop_fold_foreign_item<T: Folder>(ni: P<ForeignItem>, folder: &mut T) ->
ForeignItemKind::Static(folder.fold_ty(t), m) ForeignItemKind::Static(folder.fold_ty(t), m)
} }
}, },
vis: vis, vis: ni.vis,
span: folder.new_span(span) span: folder.new_span(ni.span)
}) }
} }
pub fn noop_fold_method_sig<T: Folder>(sig: MethodSig, folder: &mut T) -> MethodSig { pub fn noop_fold_method_sig<T: Folder>(sig: MethodSig, folder: &mut T) -> MethodSig {
@ -1344,23 +1344,23 @@ pub fn noop_fold_exprs<T: Folder>(es: Vec<P<Expr>>, folder: &mut T) -> Vec<P<Exp
} }
pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T) pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T)
-> SmallVector<P<Stmt>> { -> SmallVector<Stmt> {
let span = folder.new_span(span); let span = folder.new_span(span);
match node { match node {
StmtKind::Decl(d, id) => { StmtKind::Decl(d, id) => {
let id = folder.new_id(id); let id = folder.new_id(id);
folder.fold_decl(d).into_iter().map(|d| P(Spanned { folder.fold_decl(d).into_iter().map(|d| Spanned {
node: StmtKind::Decl(d, id), node: StmtKind::Decl(d, id),
span: span span: span
})).collect() }).collect()
} }
StmtKind::Expr(e, id) => { StmtKind::Expr(e, id) => {
let id = folder.new_id(id); let id = folder.new_id(id);
if let Some(e) = folder.fold_opt_expr(e) { if let Some(e) = folder.fold_opt_expr(e) {
SmallVector::one(P(Spanned { SmallVector::one(Spanned {
node: StmtKind::Expr(e, id), node: StmtKind::Expr(e, id),
span: span span: span
})) })
} else { } else {
SmallVector::zero() SmallVector::zero()
} }
@ -1368,20 +1368,20 @@ pub fn noop_fold_stmt<T: Folder>(Spanned {node, span}: Stmt, folder: &mut T)
StmtKind::Semi(e, id) => { StmtKind::Semi(e, id) => {
let id = folder.new_id(id); let id = folder.new_id(id);
if let Some(e) = folder.fold_opt_expr(e) { if let Some(e) = folder.fold_opt_expr(e) {
SmallVector::one(P(Spanned { SmallVector::one(Spanned {
node: StmtKind::Semi(e, id), node: StmtKind::Semi(e, id),
span: span span: span
})) })
} else { } else {
SmallVector::zero() SmallVector::zero()
} }
} }
StmtKind::Mac(mac, semi, attrs) => SmallVector::one(P(Spanned { StmtKind::Mac(mac, semi, attrs) => SmallVector::one(Spanned {
node: StmtKind::Mac(mac.map(|m| folder.fold_mac(m)), node: StmtKind::Mac(mac.map(|m| folder.fold_mac(m)),
semi, semi,
attrs.map_thin_attrs(|v| fold_attrs(v, folder))), attrs.map_thin_attrs(|v| fold_attrs(v, folder))),
span: span span: span
})) })
} }
} }

View file

@ -144,7 +144,7 @@ pub fn parse_stmt_from_source_str(name: String,
source: String, source: String,
cfg: ast::CrateConfig, cfg: ast::CrateConfig,
sess: &ParseSess) sess: &ParseSess)
-> Option<P<ast::Stmt>> { -> Option<ast::Stmt> {
let mut p = new_parser_from_source_str( let mut p = new_parser_from_source_str(
sess, sess,
cfg, cfg,
@ -866,7 +866,7 @@ mod tests {
#[test] fn parse_stmt_1 () { #[test] fn parse_stmt_1 () {
assert!(string_to_stmt("b;".to_string()) == assert!(string_to_stmt("b;".to_string()) ==
Some(P(Spanned{ Some(Spanned{
node: ast::StmtKind::Expr(P(ast::Expr { node: ast::StmtKind::Expr(P(ast::Expr {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, ast::Path { node: ast::ExprKind::Path(None, ast::Path {
@ -882,7 +882,7 @@ mod tests {
span: sp(0,1), span: sp(0,1),
attrs: None}), attrs: None}),
ast::DUMMY_NODE_ID), ast::DUMMY_NODE_ID),
span: sp(0,1)}))) span: sp(0,1)}))
} }
@ -957,7 +957,7 @@ mod tests {
} }
}, },
P(ast::Block { P(ast::Block {
stmts: vec!(P(Spanned{ stmts: vec!(Spanned{
node: ast::StmtKind::Semi(P(ast::Expr{ node: ast::StmtKind::Semi(P(ast::Expr{
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::Path(None, node: ast::ExprKind::Path(None,
@ -977,7 +977,7 @@ mod tests {
span: sp(17,18), span: sp(17,18),
attrs: None,}), attrs: None,}),
ast::DUMMY_NODE_ID), ast::DUMMY_NODE_ID),
span: sp(17,19)})), span: sp(17,19)}),
expr: None, expr: None,
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
rules: ast::BlockCheckMode::Default, // no idea rules: ast::BlockCheckMode::Default, // no idea

View file

@ -179,6 +179,19 @@ macro_rules! maybe_whole {
} }
} }
); );
(no_clone_from_p $p:expr, $constructor:ident) => (
{
let found = match ($p).token {
token::Interpolated(token::$constructor(_)) => {
Some(($p).bump_and_get())
}
_ => None
};
if let Some(token::Interpolated(token::$constructor(x))) = found {
return Ok(x.unwrap());
}
}
);
(deref $p:expr, $constructor:ident) => ( (deref $p:expr, $constructor:ident) => (
{ {
let found = match ($p).token { let found = match ($p).token {
@ -1174,13 +1187,13 @@ impl<'a> Parser<'a> {
} }
/// Parse the items in a trait declaration /// Parse the items in a trait declaration
pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> { pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<TraitItem>> {
self.parse_unspanned_seq( self.parse_unspanned_seq(
&token::OpenDelim(token::Brace), &token::OpenDelim(token::Brace),
&token::CloseDelim(token::Brace), &token::CloseDelim(token::Brace),
seq_sep_none(), seq_sep_none(),
|p| -> PResult<'a, P<TraitItem>> { |p| -> PResult<'a, TraitItem> {
maybe_whole!(no_clone p, NtTraitItem); maybe_whole!(no_clone_from_p p, NtTraitItem);
let mut attrs = try!(p.parse_outer_attributes()); let mut attrs = try!(p.parse_outer_attributes());
let lo = p.span.lo; let lo = p.span.lo;
@ -1249,13 +1262,13 @@ impl<'a> Parser<'a> {
(ident, ast::TraitItemKind::Method(sig, body)) (ident, ast::TraitItemKind::Method(sig, body))
}; };
Ok(P(TraitItem { Ok(TraitItem {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
ident: name, ident: name,
attrs: attrs, attrs: attrs,
node: node, node: node,
span: mk_sp(lo, p.last_span.hi), span: mk_sp(lo, p.last_span.hi),
})) })
}) })
} }
@ -3661,8 +3674,8 @@ impl<'a> Parser<'a> {
} }
/// Parse a statement. may include decl. /// Parse a statement. may include decl.
pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> { pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
Ok(try!(self.parse_stmt_()).map(P)) Ok(try!(self.parse_stmt_()))
} }
fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> { fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
@ -3846,10 +3859,10 @@ impl<'a> Parser<'a> {
// expr depending on whether a semicolon follows // expr depending on whether a semicolon follows
match self.token { match self.token {
token::Semi => { token::Semi => {
stmts.push(P(Spanned { stmts.push(Spanned {
node: StmtKind::Mac(mac, MacStmtStyle::Semicolon, attrs), node: StmtKind::Mac(mac, MacStmtStyle::Semicolon, attrs),
span: mk_sp(span.lo, self.span.hi), span: mk_sp(span.lo, self.span.hi),
})); });
self.bump(); self.bump();
} }
_ => { _ => {
@ -3871,10 +3884,10 @@ impl<'a> Parser<'a> {
// statement macro; might be an expr // statement macro; might be an expr
match self.token { match self.token {
token::Semi => { token::Semi => {
stmts.push(P(Spanned { stmts.push(Spanned {
node: StmtKind::Mac(m, MacStmtStyle::Semicolon, attrs), node: StmtKind::Mac(m, MacStmtStyle::Semicolon, attrs),
span: mk_sp(span.lo, self.span.hi), span: mk_sp(span.lo, self.span.hi),
})); });
self.bump(); self.bump();
} }
token::CloseDelim(token::Brace) => { token::CloseDelim(token::Brace) => {
@ -3885,10 +3898,10 @@ impl<'a> Parser<'a> {
attrs)); attrs));
} }
_ => { _ => {
stmts.push(P(Spanned { stmts.push(Spanned {
node: StmtKind::Mac(m, style, attrs), node: StmtKind::Mac(m, style, attrs),
span: span span: span
})); });
} }
} }
} }
@ -3899,10 +3912,10 @@ impl<'a> Parser<'a> {
hi = self.last_span.hi; hi = self.last_span.hi;
} }
stmts.push(P(Spanned { stmts.push(Spanned {
node: node, node: node,
span: mk_sp(span.lo, hi) span: mk_sp(span.lo, hi)
})); });
} }
} }
} }
@ -3920,7 +3933,7 @@ impl<'a> Parser<'a> {
&mut self, &mut self,
e: P<Expr>, e: P<Expr>,
span: Span, span: Span,
stmts: &mut Vec<P<Stmt>>, stmts: &mut Vec<Stmt>,
last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> { last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
// expression without semicolon // expression without semicolon
if classify::expr_requires_semi_to_be_stmt(&*e) { if classify::expr_requires_semi_to_be_stmt(&*e) {
@ -3937,17 +3950,17 @@ impl<'a> Parser<'a> {
hi: self.last_span.hi, hi: self.last_span.hi,
expn_id: span.expn_id, expn_id: span.expn_id,
}; };
stmts.push(P(Spanned { stmts.push(Spanned {
node: StmtKind::Semi(e, ast::DUMMY_NODE_ID), node: StmtKind::Semi(e, ast::DUMMY_NODE_ID),
span: span_with_semi, span: span_with_semi,
})); });
} }
token::CloseDelim(token::Brace) => *last_block_expr = Some(e), token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
_ => { _ => {
stmts.push(P(Spanned { stmts.push(Spanned {
node: StmtKind::Expr(e, ast::DUMMY_NODE_ID), node: StmtKind::Expr(e, ast::DUMMY_NODE_ID),
span: span span: span
})); });
} }
} }
Ok(()) Ok(())
@ -4080,7 +4093,7 @@ impl<'a> Parser<'a> {
fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>, fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
Vec<P<Ty>>, Vec<P<Ty>>,
Vec<P<TypeBinding>>)> { Vec<TypeBinding>)> {
let span_lo = self.span.lo; let span_lo = self.span.lo;
let lifetimes = try!(self.parse_lifetimes(token::Comma)); let lifetimes = try!(self.parse_lifetimes(token::Comma));
@ -4146,11 +4159,11 @@ impl<'a> Parser<'a> {
let ty = try!(p.parse_ty()); let ty = try!(p.parse_ty());
let hi = ty.span.hi; let hi = ty.span.hi;
let span = mk_sp(lo, hi); let span = mk_sp(lo, hi);
return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID, return Ok(TypeBinding{id: ast::DUMMY_NODE_ID,
ident: ident, ident: ident,
ty: ty, ty: ty,
span: span, span: span,
})); });
} }
)); ));
Ok((lifetimes, types.into_vec(), bindings.into_vec())) Ok((lifetimes, types.into_vec(), bindings.into_vec()))
@ -4647,8 +4660,8 @@ impl<'a> Parser<'a> {
} }
/// Parse an impl item. /// Parse an impl item.
pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> { pub fn parse_impl_item(&mut self) -> PResult<'a, ImplItem> {
maybe_whole!(no_clone self, NtImplItem); maybe_whole!(no_clone_from_p self, NtImplItem);
let mut attrs = try!(self.parse_outer_attributes()); let mut attrs = try!(self.parse_outer_attributes());
let lo = self.span.lo; let lo = self.span.lo;
@ -4674,14 +4687,14 @@ impl<'a> Parser<'a> {
(name, node) (name, node)
}; };
Ok(P(ImplItem { Ok(ImplItem {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
span: mk_sp(lo, self.last_span.hi), span: mk_sp(lo, self.last_span.hi),
ident: name, ident: name,
vis: vis, vis: vis,
attrs: attrs, attrs: attrs,
node: node node: node
})) })
} }
fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) { fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
@ -5243,7 +5256,7 @@ impl<'a> Parser<'a> {
/// Parse a function declaration from a foreign module /// Parse a function declaration from a foreign module
fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos, fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> { attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
try!(self.expect_keyword(keywords::Fn)); try!(self.expect_keyword(keywords::Fn));
let (ident, mut generics) = try!(self.parse_fn_header()); let (ident, mut generics) = try!(self.parse_fn_header());
@ -5251,19 +5264,19 @@ impl<'a> Parser<'a> {
generics.where_clause = try!(self.parse_where_clause()); generics.where_clause = try!(self.parse_where_clause());
let hi = self.span.hi; let hi = self.span.hi;
try!(self.expect(&token::Semi)); try!(self.expect(&token::Semi));
Ok(P(ast::ForeignItem { Ok(ast::ForeignItem {
ident: ident, ident: ident,
attrs: attrs, attrs: attrs,
node: ForeignItemKind::Fn(decl, generics), node: ForeignItemKind::Fn(decl, generics),
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
span: mk_sp(lo, hi), span: mk_sp(lo, hi),
vis: vis vis: vis
})) })
} }
/// Parse a static item from a foreign module /// Parse a static item from a foreign module
fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos, fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> { attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
try!(self.expect_keyword(keywords::Static)); try!(self.expect_keyword(keywords::Static));
let mutbl = self.eat_keyword(keywords::Mut); let mutbl = self.eat_keyword(keywords::Mut);
@ -5272,14 +5285,14 @@ impl<'a> Parser<'a> {
let ty = try!(self.parse_ty_sum()); let ty = try!(self.parse_ty_sum());
let hi = self.span.hi; let hi = self.span.hi;
try!(self.expect(&token::Semi)); try!(self.expect(&token::Semi));
Ok(P(ForeignItem { Ok(ForeignItem {
ident: ident, ident: ident,
attrs: attrs, attrs: attrs,
node: ForeignItemKind::Static(ty, mutbl), node: ForeignItemKind::Static(ty, mutbl),
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
span: mk_sp(lo, hi), span: mk_sp(lo, hi),
vis: vis vis: vis
})) })
} }
/// Parse extern crate links /// Parse extern crate links
@ -5405,7 +5418,7 @@ impl<'a> Parser<'a> {
data: struct_def, data: struct_def,
disr_expr: disr_expr, disr_expr: disr_expr,
}; };
variants.push(P(spanned(vlo, self.last_span.hi, vr))); variants.push(spanned(vlo, self.last_span.hi, vr));
if !self.eat(&token::Comma) { break; } if !self.eat(&token::Comma) { break; }
} }
@ -5729,7 +5742,7 @@ impl<'a> Parser<'a> {
} }
/// Parse a foreign item. /// Parse a foreign item.
fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> { fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
let attrs = try!(self.parse_outer_attributes()); let attrs = try!(self.parse_outer_attributes());
let lo = self.span.lo; let lo = self.span.lo;
let visibility = try!(self.parse_visibility()); let visibility = try!(self.parse_visibility());

View file

@ -939,7 +939,7 @@ impl<'a> State<'a> {
attrs: &[ast::Attribute]) -> io::Result<()> { attrs: &[ast::Attribute]) -> io::Result<()> {
try!(self.print_inner_attributes(attrs)); try!(self.print_inner_attributes(attrs));
for item in &nmod.items { for item in &nmod.items {
try!(self.print_foreign_item(&**item)); try!(self.print_foreign_item(item));
} }
Ok(()) Ok(())
} }
@ -1370,7 +1370,7 @@ impl<'a> State<'a> {
} }
pub fn print_variants(&mut self, pub fn print_variants(&mut self,
variants: &[P<ast::Variant>], variants: &[ast::Variant],
span: codemap::Span) -> io::Result<()> { span: codemap::Span) -> io::Result<()> {
try!(self.bopen()); try!(self.bopen());
for v in variants { for v in variants {
@ -1378,7 +1378,7 @@ impl<'a> State<'a> {
try!(self.maybe_print_comment(v.span.lo)); try!(self.maybe_print_comment(v.span.lo));
try!(self.print_outer_attributes(&v.node.attrs)); try!(self.print_outer_attributes(&v.node.attrs));
try!(self.ibox(INDENT_UNIT)); try!(self.ibox(INDENT_UNIT));
try!(self.print_variant(&**v)); try!(self.print_variant(v));
try!(word(&mut self.s, ",")); try!(word(&mut self.s, ","));
try!(self.end()); try!(self.end());
try!(self.maybe_print_trailing_comment(v.span, None)); try!(self.maybe_print_trailing_comment(v.span, None));
@ -1686,7 +1686,7 @@ impl<'a> State<'a> {
try!(self.print_inner_attributes(attrs)); try!(self.print_inner_attributes(attrs));
for st in &blk.stmts { for st in &blk.stmts {
try!(self.print_stmt(&**st)); try!(self.print_stmt(st));
} }
match blk.expr { match blk.expr {
Some(ref expr) => { Some(ref expr) => {

View file

@ -65,6 +65,10 @@ impl<T: 'static> P<T> {
{ {
f(*self.ptr) f(*self.ptr)
} }
/// Equivalent to and_then(|x| x)
pub fn unwrap(self) -> T {
*self.ptr
}
/// Transform the inner value, consuming `self` and producing a new `P<T>`. /// Transform the inner value, consuming `self` and producing a new `P<T>`.
pub fn map<F>(mut self, f: F) -> P<T> where pub fn map<F>(mut self, f: F) -> P<T> where

View file

@ -64,7 +64,7 @@ pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> {
} }
/// Parse a string, return a stmt /// Parse a string, return a stmt
pub fn string_to_stmt(source_str : String) -> Option<P<ast::Stmt>> { pub fn string_to_stmt(source_str : String) -> Option<ast::Stmt> {
let ps = ParseSess::new(); let ps = ParseSess::new();
with_error_checking_parse(source_str, &ps, |p| { with_error_checking_parse(source_str, &ps, |p| {
p.parse_stmt() p.parse_stmt()

View file

@ -141,7 +141,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span,
fn stmt_let_undescore(cx: &mut ExtCtxt, fn stmt_let_undescore(cx: &mut ExtCtxt,
sp: Span, sp: Span,
expr: P<ast::Expr>) -> P<ast::Stmt> { expr: P<ast::Expr>) -> ast::Stmt {
let local = P(ast::Local { let local = P(ast::Local {
pat: cx.pat_wild(sp), pat: cx.pat_wild(sp),
ty: None, ty: None,
@ -151,5 +151,5 @@ fn stmt_let_undescore(cx: &mut ExtCtxt,
attrs: None, attrs: None,
}); });
let decl = respan(sp, ast::DeclKind::Local(local)); let decl = respan(sp, ast::DeclKind::Local(local));
P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))) respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))
} }

View file

@ -312,7 +312,7 @@ pub enum SubstructureFields<'a> {
/// variants for the enum itself, and the third component is a list of /// variants for the enum itself, and the third component is a list of
/// `Ident`s bound to the variant index values for each of the actual /// `Ident`s bound to the variant index values for each of the actual
/// input `Self` arguments. /// input `Self` arguments.
EnumNonMatchingCollapsed(Vec<Ident>, &'a [P<ast::Variant>], &'a [Ident]), EnumNonMatchingCollapsed(Vec<Ident>, &'a [ast::Variant], &'a [Ident]),
/// A static method where `Self` is a struct. /// A static method where `Self` is a struct.
StaticStruct(&'a ast::VariantData, StaticFields), StaticStruct(&'a ast::VariantData, StaticFields),
@ -466,12 +466,12 @@ impl<'a> TraitDef<'a> {
type_ident: Ident, type_ident: Ident,
generics: &Generics, generics: &Generics,
field_tys: Vec<P<ast::Ty>>, field_tys: Vec<P<ast::Ty>>,
methods: Vec<P<ast::ImplItem>>) -> P<ast::Item> { methods: Vec<ast::ImplItem>) -> P<ast::Item> {
let trait_path = self.path.to_path(cx, self.span, type_ident, generics); let trait_path = self.path.to_path(cx, self.span, type_ident, generics);
// Transform associated types from `deriving::ty::Ty` into `ast::ImplItem` // Transform associated types from `deriving::ty::Ty` into `ast::ImplItem`
let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| { let associated_types = self.associated_types.iter().map(|&(ident, ref type_def)| {
P(ast::ImplItem { ast::ImplItem {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
span: self.span, span: self.span,
ident: ident, ident: ident,
@ -482,7 +482,7 @@ impl<'a> TraitDef<'a> {
type_ident, type_ident,
generics generics
)), )),
}) }
}); });
let Generics { mut lifetimes, ty_params, mut where_clause } = let Generics { mut lifetimes, ty_params, mut where_clause } =
@ -857,7 +857,7 @@ impl<'a> MethodDef<'a> {
abi: Abi, abi: Abi,
explicit_self: ast::ExplicitSelf, explicit_self: ast::ExplicitSelf,
arg_types: Vec<(Ident, P<ast::Ty>)> , arg_types: Vec<(Ident, P<ast::Ty>)> ,
body: P<Expr>) -> P<ast::ImplItem> { body: P<Expr>) -> ast::ImplItem {
// create the generics that aren't for Self // create the generics that aren't for Self
let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics); let fn_generics = self.generics.to_generics(cx, trait_.span, type_ident, generics);
@ -888,7 +888,7 @@ impl<'a> MethodDef<'a> {
}; };
// Create the method. // Create the method.
P(ast::ImplItem { ast::ImplItem {
id: ast::DUMMY_NODE_ID, id: ast::DUMMY_NODE_ID,
attrs: self.attributes.clone(), attrs: self.attributes.clone(),
span: trait_.span, span: trait_.span,
@ -902,7 +902,7 @@ impl<'a> MethodDef<'a> {
constness: ast::Constness::NotConst, constness: ast::Constness::NotConst,
decl: fn_decl decl: fn_decl
}, body_block) }, body_block)
}) }
} }
/// ```ignore /// ```ignore
@ -1139,7 +1139,7 @@ impl<'a> MethodDef<'a> {
let mk_self_pat = |cx: &mut ExtCtxt, self_arg_name: &str| { let mk_self_pat = |cx: &mut ExtCtxt, self_arg_name: &str| {
let (p, idents) = trait_.create_enum_variant_pattern( let (p, idents) = trait_.create_enum_variant_pattern(
cx, type_ident, cx, type_ident,
&**variant, variant,
self_arg_name, self_arg_name,
ast::Mutability::Immutable); ast::Mutability::Immutable);
(cx.pat(sp, ast::PatRegion(p, ast::Mutability::Immutable)), idents) (cx.pat(sp, ast::PatRegion(p, ast::Mutability::Immutable)), idents)
@ -1209,7 +1209,7 @@ impl<'a> MethodDef<'a> {
// Self arg, assuming all are instances of VariantK. // Self arg, assuming all are instances of VariantK.
// Build up code associated with such a case. // Build up code associated with such a case.
let substructure = EnumMatching(index, let substructure = EnumMatching(index,
&**variant, variant,
field_tuples); field_tuples);
let arm_expr = self.call_substructure_method( let arm_expr = self.call_substructure_method(
cx, trait_, type_ident, &self_args[..], nonself_args, cx, trait_, type_ident, &self_args[..], nonself_args,
@ -1250,7 +1250,7 @@ impl<'a> MethodDef<'a> {
// let __self2_vi = unsafe { // let __self2_vi = unsafe {
// std::intrinsics::discriminant_value(&__arg2) } as i32; // std::intrinsics::discriminant_value(&__arg2) } as i32;
// ``` // ```
let mut index_let_stmts: Vec<P<ast::Stmt>> = Vec::new(); let mut index_let_stmts: Vec<ast::Stmt> = Vec::new();
//We also build an expression which checks whether all discriminants are equal //We also build an expression which checks whether all discriminants are equal
// discriminant_test = __self0_vi == __self1_vi && __self0_vi == __self2_vi && ... // discriminant_test = __self0_vi == __self1_vi && __self0_vi == __self2_vi && ...

View file

@ -461,7 +461,7 @@ impl<'a, 'b> Context<'a, 'b> {
// Wrap the declaration in a block so that it forms a single expression. // Wrap the declaration in a block so that it forms a single expression.
ecx.expr_block(ecx.block(sp, ecx.expr_block(ecx.block(sp,
vec![P(respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID)))], vec![respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID))],
Some(ecx.expr_ident(sp, name)))) Some(ecx.expr_ident(sp, name))))
} }

View file

@ -74,7 +74,7 @@ fn expand_into_foo_multi(cx: &mut ExtCtxt,
quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| { quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| {
match i.node { match i.node {
ItemKind::Impl(_, _, _, _, _, mut items) => { ItemKind::Impl(_, _, _, _, _, mut items) => {
Annotatable::ImplItem(items.pop().expect("impl method not found")) Annotatable::ImplItem(P(items.pop().expect("impl method not found")))
} }
_ => unreachable!("impl parsed to something other than impl") _ => unreachable!("impl parsed to something other than impl")
} }
@ -84,7 +84,7 @@ fn expand_into_foo_multi(cx: &mut ExtCtxt,
quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| { quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| {
match i.node { match i.node {
ItemKind::Trait(_, _, _, mut items) => { ItemKind::Trait(_, _, _, mut items) => {
Annotatable::TraitItem(items.pop().expect("trait method not found")) Annotatable::TraitItem(P(items.pop().expect("trait method not found")))
} }
_ => unreachable!("trait parsed to something other than trait") _ => unreachable!("trait parsed to something other than trait")
} }

View file

@ -59,7 +59,7 @@ fn expr<'a>(s: &str, ps: &'a ParseSess) -> PResult<'a, P<ast::Expr>> {
}) })
} }
fn stmt<'a>(s: &str, ps: &'a ParseSess) -> PResult<'a, P<ast::Stmt>> { fn stmt<'a>(s: &str, ps: &'a ParseSess) -> PResult<'a, ast::Stmt> {
with_error_checking_parse(s.to_string(), ps, |p| { with_error_checking_parse(s.to_string(), ps, |p| {
p.parse_stmt().map(|s| s.unwrap()) p.parse_stmt().map(|s| s.unwrap())
}) })

View file

@ -52,7 +52,7 @@ fn main() {
let twenty: u16 = 20; let twenty: u16 = 20;
let stmt = quote_stmt!(cx, let x = $twenty;).unwrap(); let stmt = quote_stmt!(cx, let x = $twenty;).unwrap();
check!(stmt_to_string, stmt, *quote_stmt!(cx, $stmt).unwrap(); "let x = 20u16;"); check!(stmt_to_string, stmt, quote_stmt!(cx, $stmt).unwrap(); "let x = 20u16;");
let pat = quote_pat!(cx, Some(_)); let pat = quote_pat!(cx, Some(_));
check!(pat_to_string, pat, *quote_pat!(cx, $pat); "Some(_)"); check!(pat_to_string, pat, *quote_pat!(cx, $pat); "Some(_)");

View file

@ -26,7 +26,7 @@ fn syntax_extension(cx: &ExtCtxt) {
let a: P<syntax::ast::Expr> = quote_expr!(cx, 1 + 2); let a: P<syntax::ast::Expr> = quote_expr!(cx, 1 + 2);
let _b: Option<P<syntax::ast::Item>> = quote_item!(cx, static foo : isize = $e_toks; ); let _b: Option<P<syntax::ast::Item>> = quote_item!(cx, static foo : isize = $e_toks; );
let _c: P<syntax::ast::Pat> = quote_pat!(cx, (x, 1 .. 4, *) ); let _c: P<syntax::ast::Pat> = quote_pat!(cx, (x, 1 .. 4, *) );
let _d: Option<P<syntax::ast::Stmt>> = quote_stmt!(cx, let x = $a; ); let _d: Option<syntax::ast::Stmt> = quote_stmt!(cx, let x = $a; );
let _d: syntax::ast::Arm = quote_arm!(cx, (ref x, ref y) = (x, y) ); let _d: syntax::ast::Arm = quote_arm!(cx, (ref x, ref y) = (x, y) );
let _e: P<syntax::ast::Expr> = quote_expr!(cx, match foo { $p_toks => 10 } ); let _e: P<syntax::ast::Expr> = quote_expr!(cx, match foo { $p_toks => 10 } );