diff options
Diffstat (limited to 'src/libsyntax')
48 files changed, 1028 insertions, 1422 deletions
diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 09235ee209c..5f593ac7081 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -15,7 +15,7 @@ pub use self::AbiArchitecture::*; use std::fmt; -#[derive(Copy, PartialEq)] +#[derive(Copy, PartialEq, Eq, Show)] pub enum Os { OsWindows, OsMacos, @@ -26,7 +26,7 @@ pub enum Os { OsDragonfly, } -#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy)] +#[derive(PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Show)] pub enum Abi { // NB: This ordering MUST match the AbiDatas array below. // (This is ensured by the test indices_are_correct().) @@ -105,8 +105,8 @@ pub fn all_names() -> Vec<&'static str> { impl Abi { #[inline] - pub fn index(&self) -> uint { - *self as uint + pub fn index(&self) -> usize { + *self as usize } #[inline] @@ -119,25 +119,13 @@ impl Abi { } } -impl fmt::Show for Abi { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for Abi { +impl fmt::Display for Abi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } -impl fmt::Show for Os { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - -impl fmt::String for Os { +impl fmt::Display for Os { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OsLinux => "linux".fmt(f), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index fcf80410da2..7111fe3af1f 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -53,7 +53,6 @@ pub use self::UnboxedClosureKind::*; pub use self::UnOp::*; pub use self::UnsafeSource::*; pub use self::VariantKind::*; -pub use self::ViewItem_::*; pub use self::ViewPath_::*; pub use self::Visibility::*; pub use self::PathParameters::*; @@ -95,33 +94,33 @@ impl Ident { pub fn encode_with_hygiene(&self) -> String { format!("\x00name_{},ctxt_{}\x00", - self.name.uint(), + self.name.usize(), self.ctxt) } } -impl fmt::Show for Ident { +impl fmt::Debug for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}#{}", self.name, self.ctxt) } } -impl fmt::String for Ident { +impl fmt::Display for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(&self.name, f) + fmt::Display::fmt(&self.name, f) } } -impl fmt::Show for Name { +impl fmt::Debug for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Name(nm) = *self; write!(f, "{:?}({})", token::get_name(*self).get(), nm) } } -impl fmt::String for Name { +impl fmt::Display for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(token::get_name(*self).get(), f) + fmt::Display::fmt(token::get_name(*self).get(), f) } } @@ -152,7 +151,7 @@ impl PartialEq for Ident { /// A SyntaxContext represents a chain of macro-expandings /// and renamings. Each macro expansion corresponds to -/// a fresh uint +/// a fresh usize // I'm representing this syntax context as an index into // a table, in order to work around a compiler bug @@ -181,9 +180,9 @@ impl Name { } } - pub fn uint(&self) -> uint { + pub fn usize(&self) -> usize { let Name(nm) = *self; - nm as uint + nm as usize } pub fn ident(&self) -> Ident { @@ -511,7 +510,6 @@ impl PartialEq for MetaItem_ { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub struct Block { - pub view_items: Vec<ViewItem>, pub stmts: Vec<P<Stmt>>, pub expr: Option<P<Expr>>, pub id: NodeId, @@ -740,7 +738,7 @@ pub enum Expr_ { ExprAssign(P<Expr>, P<Expr>), ExprAssignOp(BinOp, P<Expr>, P<Expr>), ExprField(P<Expr>, SpannedIdent), - ExprTupField(P<Expr>, Spanned<uint>), + ExprTupField(P<Expr>, Spanned<usize>), ExprIndex(P<Expr>, P<Expr>), ExprRange(Option<P<Expr>>, Option<P<Expr>>), @@ -839,7 +837,7 @@ pub struct SequenceRepetition { /// Whether the sequence can be repeated zero (*), or one or more times (+) pub op: KleeneOp, /// The number of `MatchNt`s that appear in the sequence (and subsequences) - pub num_captures: uint, + pub num_captures: usize, } /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star) @@ -878,7 +876,7 @@ pub enum TokenTree { } impl TokenTree { - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { match *self { TtToken(_, token::DocComment(_)) => 2, TtToken(_, token::SpecialVarNt(..)) => 2, @@ -893,7 +891,7 @@ impl TokenTree { } } - pub fn get_tt(&self, index: uint) -> TokenTree { + pub fn get_tt(&self, index: usize) -> TokenTree { match (self, index) { (&TtToken(sp, token::DocComment(_)), 0) => { TtToken(sp, token::Pound) @@ -963,7 +961,7 @@ pub enum Mac_ { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)] pub enum StrStyle { CookedStr, - RawStr(uint) + RawStr(usize) } pub type Lit = Spanned<Lit_>; @@ -992,7 +990,7 @@ pub enum LitIntType { } impl LitIntType { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { UnsuffixedIntLit(_) => 0, SignedIntLit(s, _) => s.suffix_len(), @@ -1100,20 +1098,20 @@ impl PartialEq for IntTy { } } -impl fmt::Show for IntTy { +impl fmt::Debug for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for IntTy { +impl fmt::Display for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::int_ty_to_string(*self, None)) } } impl IntTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyIs(true) /* i */ => 1, TyIs(false) /* is */ | TyI8 => 2, @@ -1146,7 +1144,7 @@ impl PartialEq for UintTy { } impl UintTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyUs(true) /* u */ => 1, TyUs(false) /* us */ | TyU8 => 2, @@ -1155,13 +1153,13 @@ impl UintTy { } } -impl fmt::Show for UintTy { +impl fmt::Debug for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for UintTy { +impl fmt::Display for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::uint_ty_to_string(*self, None)) } @@ -1173,20 +1171,20 @@ pub enum FloatTy { TyF64, } -impl fmt::Show for FloatTy { +impl fmt::Debug for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Display::fmt(self, f) } } -impl fmt::String for FloatTy { +impl fmt::Display for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::float_ty_to_string(*self)) } } impl FloatTy { - pub fn suffix_len(&self) -> uint { + pub fn suffix_len(&self) -> usize { match *self { TyF32 | TyF64 => 3, // add F128 handling here } @@ -1222,24 +1220,15 @@ pub enum PrimTy { TyChar } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy, Show)] pub enum Onceness { Once, Many } -impl fmt::Show for Onceness { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { - Once => "once", - Many => "many", - }, f) - } -} - -impl fmt::String for Onceness { +impl fmt::Display for Onceness { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { Once => "once", Many => "many", }, f) @@ -1274,7 +1263,7 @@ pub enum Ty_ { TyPtr(MutTy), /// A reference (`&'a T` or `&'a mut T`) TyRptr(Option<Lifetime>, MutTy), - /// A bare function (e.g. `fn(uint) -> bool`) + /// A bare function (e.g. `fn(usize) -> bool`) TyBareFn(P<BareFnTy>), /// A tuple (`(A, B, C, D,...)`) TyTup(Vec<P<Ty>> ), @@ -1358,9 +1347,9 @@ pub enum Unsafety { Normal, } -impl fmt::String for Unsafety { +impl fmt::Display for Unsafety { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(match *self { + fmt::Display::fmt(match *self { Unsafety::Normal => "normal", Unsafety::Unsafe => "unsafe", }, f) @@ -1375,7 +1364,7 @@ pub enum ImplPolarity { Negative, } -impl fmt::Show for ImplPolarity { +impl fmt::Debug for ImplPolarity { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ImplPolarity::Positive => "positive".fmt(f), @@ -1452,14 +1441,12 @@ pub struct Mod { /// For `mod foo;`, the inner span ranges from the first token /// to the last token in the external file. pub inner: Span, - pub view_items: Vec<ViewItem>, pub items: Vec<P<Item>>, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub struct ForeignMod { pub abi: Abi, - pub view_items: Vec<ViewItem>, pub items: Vec<P<ForeignItem>>, } @@ -1518,44 +1505,13 @@ pub enum ViewPath_ { /// or just /// /// `foo::bar::baz` (with `as baz` implicitly on the right) - ViewPathSimple(Ident, Path, NodeId), + ViewPathSimple(Ident, Path), /// `foo::bar::*` - ViewPathGlob(Path, NodeId), + ViewPathGlob(Path), /// `foo::bar::{a,b,c}` - ViewPathList(Path, Vec<PathListItem> , NodeId) -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] -pub struct ViewItem { - pub node: ViewItem_, - pub attrs: Vec<Attribute>, - pub vis: Visibility, - pub span: Span, -} - -impl ViewItem { - pub fn id(&self) -> NodeId { - match self.node { - ViewItemExternCrate(_, _, id) => id, - ViewItemUse(ref vp) => match vp.node { - ViewPathSimple(_, _, id) => id, - ViewPathGlob(_, id) => id, - ViewPathList(_, _, id) => id, - } - } - } -} - -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] -pub enum ViewItem_ { - /// Ident: name used to refer to this crate in the code - /// optional (InternedString,StrStyle): if present, this is a location - /// (containing arbitrary characters) from which to fetch the crate sources - /// For example, extern crate whatever = "github.com/rust-lang/rust" - ViewItemExternCrate(Ident, Option<(InternedString,StrStyle)>, NodeId), - ViewItemUse(P<ViewPath>), + ViewPathList(Path, Vec<PathListItem>) } /// Meta-data associated with an item @@ -1571,7 +1527,7 @@ pub enum AttrStyle { } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)] -pub struct AttrId(pub uint); +pub struct AttrId(pub usize); /// Doc-comments are promoted to attributes that have is_sugared_doc = true #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] @@ -1677,6 +1633,12 @@ pub struct Item { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum Item_ { + // Optional location (containing arbitrary characters) from which + // to fetch the crate sources. + // For example, extern crate whatever = "github.com/rust-lang/rust". + ItemExternCrate(Option<(InternedString, StrStyle)>), + ItemUse(P<ViewPath>), + ItemStatic(P<Ty>, Mutability, P<Expr>), ItemConst(P<Ty>, P<Expr>), ItemFn(P<FnDecl>, Unsafety, Abi, Generics, P<Block>), @@ -1703,6 +1665,8 @@ pub enum Item_ { impl Item_ { pub fn descriptive_variant(&self) -> &str { match *self { + ItemExternCrate(..) => "extern crate", + ItemUse(..) => "use", ItemStatic(..) => "static item", ItemConst(..) => "constant item", ItemFn(..) => "function", diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index f462a730d3a..8a114e4b748 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -46,7 +46,7 @@ impl PathElem { } } -impl fmt::String for PathElem { +impl fmt::Display for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); write!(f, "{}", slot) @@ -107,7 +107,6 @@ pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String { #[derive(Copy, Show)] pub enum Node<'ast> { NodeItem(&'ast Item), - NodeViewItem(&'ast ViewItem), NodeForeignItem(&'ast ForeignItem), NodeTraitItem(&'ast TraitItem), NodeImplItem(&'ast ImplItem), @@ -134,7 +133,6 @@ enum MapEntry<'ast> { /// All the node types, with a parent ID. EntryItem(NodeId, &'ast Item), - EntryViewItem(NodeId, &'ast ViewItem), EntryForeignItem(NodeId, &'ast ForeignItem), EntryTraitItem(NodeId, &'ast TraitItem), EntryImplItem(NodeId, &'ast ImplItem), @@ -169,7 +167,6 @@ impl<'ast> MapEntry<'ast> { fn from_node(p: NodeId, node: Node<'ast>) -> MapEntry<'ast> { match node { NodeItem(n) => EntryItem(p, n), - NodeViewItem(n) => EntryViewItem(p, n), NodeForeignItem(n) => EntryForeignItem(p, n), NodeTraitItem(n) => EntryTraitItem(p, n), NodeImplItem(n) => EntryImplItem(p, n), @@ -188,7 +185,6 @@ impl<'ast> MapEntry<'ast> { fn parent(self) -> Option<NodeId> { Some(match self { EntryItem(id, _) => id, - EntryViewItem(id, _) => id, EntryForeignItem(id, _) => id, EntryTraitItem(id, _) => id, EntryImplItem(id, _) => id, @@ -208,7 +204,6 @@ impl<'ast> MapEntry<'ast> { fn to_node(self) -> Option<Node<'ast>> { Some(match self { EntryItem(_, n) => NodeItem(n), - EntryViewItem(_, n) => NodeViewItem(n), EntryForeignItem(_, n) => NodeForeignItem(n), EntryTraitItem(_, n) => NodeTraitItem(n), EntryImplItem(_, n) => NodeImplItem(n), @@ -264,12 +259,12 @@ pub struct Map<'ast> { } impl<'ast> Map<'ast> { - fn entry_count(&self) -> uint { + fn entry_count(&self) -> usize { self.map.borrow().len() } fn find_entry(&self, id: NodeId) -> Option<MapEntry<'ast>> { - self.map.borrow().get(id as uint).map(|e| *e) + self.map.borrow().get(id as usize).map(|e| *e) } pub fn krate(&self) -> &'ast Crate { @@ -341,13 +336,6 @@ impl<'ast> Map<'ast> { } } - pub fn expect_view_item(&self, id: NodeId) -> &'ast ViewItem { - match self.find(id) { - Some(NodeViewItem(view_item)) => view_item, - _ => panic!("expected view item, found {}", self.node_to_string(id)) - } - } - pub fn expect_struct(&self, id: NodeId) -> &'ast StructDef { match self.find(id) { Some(NodeItem(i)) => { @@ -525,7 +513,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: &parts[..(parts.len() - 1)], + in_which: &parts[..parts.len() - 1], idx: 0, } } @@ -533,7 +521,6 @@ impl<'ast> Map<'ast> { pub fn opt_span(&self, id: NodeId) -> Option<Span> { let sp = match self.find(id) { Some(NodeItem(item)) => item.span, - Some(NodeViewItem(item)) => item.span, Some(NodeForeignItem(foreign_item)) => foreign_item.span, Some(NodeTraitItem(trait_method)) => { match *trait_method { @@ -652,7 +639,7 @@ impl<'a, 'ast> Iterator for NodesMatchingSuffix<'a, 'ast> { fn next(&mut self) -> Option<NodeId> { loop { let idx = self.idx; - if idx as uint >= self.map.entry_count() { + if idx as usize >= self.map.entry_count() { return None; } self.idx += 1; @@ -744,10 +731,10 @@ impl<'ast> NodeCollector<'ast> { fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) { debug!("ast_map: {:?} => {:?}", id, entry); let len = self.map.len(); - if id as uint >= len { - self.map.extend(repeat(NotPresent).take(id as uint - len + 1)); + if id as usize >= len { + self.map.extend(repeat(NotPresent).take(id as usize - len + 1)); } - self.map[id as uint] = entry; + self.map[id as usize] = entry; } fn insert(&mut self, id: NodeId, node: Node<'ast>) { @@ -826,11 +813,6 @@ impl<'ast> Visitor<'ast> for NodeCollector<'ast> { self.parent = parent; } - fn visit_view_item(&mut self, item: &'ast ViewItem) { - self.insert(item.id(), NodeViewItem(item)); - visit::walk_view_item(self, item); - } - fn visit_pat(&mut self, pat: &'ast Pat) { self.insert(pat.id, match pat.node { // Note: this is at least *potentially* a pattern... @@ -904,7 +886,6 @@ pub fn map_crate<'ast, F: FoldOps>(forest: &'ast mut Forest, fold_ops: F) -> Map let krate = mem::replace(&mut forest.krate, Crate { module: Mod { inner: DUMMY_SP, - view_items: vec![], items: vec![], }, attrs: vec![], @@ -1036,7 +1017,6 @@ impl<'a> NodePrinter for pprust::State<'a> { fn print_node(&mut self, node: &Node) -> IoResult<()> { match *node { NodeItem(a) => self.print_item(&*a), - NodeViewItem(a) => self.print_view_item(&*a), NodeForeignItem(a) => self.print_foreign_item(&*a), NodeTraitItem(a) => self.print_trait_method(&*a), NodeImplItem(a) => self.print_impl_item(&*a), @@ -1065,6 +1045,8 @@ fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { Some(NodeItem(item)) => { let path_str = map.path_to_str_with_ident(id, item.ident); let item_str = match item.node { + ItemExternCrate(..) => "extern crate", + ItemUse(..) => "use", ItemStatic(..) => "static", ItemConst(..) => "const", ItemFn(..) => "fn", @@ -1079,9 +1061,6 @@ fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { }; format!("{} {}{}", item_str, path_str, id_str) } - Some(NodeViewItem(item)) => { - format!("view item {}{}", pprust::view_item_to_string(&*item), id_str) - } Some(NodeForeignItem(item)) => { let path_str = map.path_to_str_with_ident(id, item.ident); format!("foreign item {}{}", path_str, id_str) diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index bc7fbd46fd8..cf0aac5bf4a 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -156,7 +156,7 @@ pub fn int_ty_max(t: IntTy) -> u64 { } /// Get a string representation of an unsigned int type, with its value. -/// We want to avoid "42uint" in favor of "42u" +/// We want to avoid "42u" in favor of "42us". "42uint" is right out. pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String { let s = match t { TyUs(true) if val.is_some() => "u", @@ -319,25 +319,24 @@ pub fn struct_field_visibility(field: ast::StructField) -> Visibility { } /// Maps a binary operator to its precedence -pub fn operator_prec(op: ast::BinOp) -> uint { +pub fn operator_prec(op: ast::BinOp) -> usize { match op { // 'as' sits here with 12 - BiMul | BiDiv | BiRem => 11u, - BiAdd | BiSub => 10u, - BiShl | BiShr => 9u, - BiBitAnd => 8u, - BiBitXor => 7u, - BiBitOr => 6u, - BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3u, - BiAnd => 2u, - BiOr => 1u + BiMul | BiDiv | BiRem => 11us, + BiAdd | BiSub => 10us, + BiShl | BiShr => 9us, + BiBitAnd => 8us, + BiBitXor => 7us, + BiBitOr => 6us, + BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3us, + BiAnd => 2us, + BiOr => 1us } } /// Precedence of the `as` operator, which is a binary operator /// not appearing in the prior table. -#[allow(non_upper_case_globals)] -pub static as_prec: uint = 12u; +pub const AS_PREC: usize = 12us; pub fn empty_generics() -> Generics { Generics { @@ -410,37 +409,6 @@ impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> { visit::walk_mod(self, module) } - fn visit_view_item(&mut self, view_item: &ViewItem) { - if !self.pass_through_items { - if self.visited_outermost { - return; - } else { - self.visited_outermost = true; - } - } - match view_item.node { - ViewItemExternCrate(_, _, node_id) => { - self.operation.visit_id(node_id) - } - ViewItemUse(ref view_path) => { - match view_path.node { - ViewPathSimple(_, _, node_id) | - ViewPathGlob(_, node_id) => { - self.operation.visit_id(node_id) - } - ViewPathList(_, ref paths, node_id) => { - self.operation.visit_id(node_id); - for path in paths.iter() { - self.operation.visit_id(path.node.id()) - } - } - } - } - } - visit::walk_view_item(self, view_item); - self.visited_outermost = false; - } - fn visit_foreign_item(&mut self, foreign_item: &ForeignItem) { self.operation.visit_id(foreign_item.id); visit::walk_foreign_item(self, foreign_item) @@ -456,10 +424,24 @@ impl<'a, 'v, O: IdVisitingOperation> Visitor<'v> for IdVisitor<'a, O> { } self.operation.visit_id(item.id); - if let ItemEnum(ref enum_definition, _) = item.node { - for variant in enum_definition.variants.iter() { - self.operation.visit_id(variant.node.id) + match item.node { + ItemUse(ref view_path) => { + match view_path.node { + ViewPathSimple(_, _) | + ViewPathGlob(_) => {} + ViewPathList(_, ref paths) => { + for path in paths.iter() { + self.operation.visit_id(path.node.id()) + } + } + } + } + ItemEnum(ref enum_definition, _) => { + for variant in enum_definition.variants.iter() { + self.operation.visit_id(variant.node.id) + } } + _ => {} } visit::walk_item(self, item); @@ -662,37 +644,6 @@ pub fn walk_pat<F>(pat: &Pat, mut it: F) -> bool where F: FnMut(&Pat) -> bool { walk_pat_(pat, &mut it) } -pub trait EachViewItem { - fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool; -} - -struct EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool { - callback: F, -} - -impl<'v, F> Visitor<'v> for EachViewItemData<F> where F: FnMut(&ast::ViewItem) -> bool { - fn visit_view_item(&mut self, view_item: &ast::ViewItem) { - let _ = (self.callback)(view_item); - } -} - -impl EachViewItem for ast::Crate { - fn each_view_item<F>(&self, f: F) -> bool where F: FnMut(&ast::ViewItem) -> bool { - let mut visit = EachViewItemData { - callback: f, - }; - visit::walk_crate(&mut visit, self); - true - } -} - -pub fn view_path_id(p: &ViewPath) -> NodeId { - match p.node { - ViewPathSimple(_, _, id) | ViewPathGlob(_, id) - | ViewPathList(_, _, id) => id - } -} - /// Returns true if the given struct def is tuple-like; i.e. that its fields /// are unnamed. pub fn struct_def_is_tuple_like(struct_def: &ast::StructDef) -> bool { diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index d63370b41f5..061600d9420 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -175,7 +175,7 @@ pub fn mk_word_item(name: InternedString) -> P<MetaItem> { P(dummy_spanned(MetaWord(name))) } -thread_local! { static NEXT_ATTR_ID: Cell<uint> = Cell::new(0) } +thread_local! { static NEXT_ATTR_ID: Cell<usize> = Cell::new(0) } pub fn mk_attr_id() -> AttrId { let id = NEXT_ATTR_ID.with(|slot| { @@ -364,9 +364,9 @@ pub enum StabilityLevel { Stable, } -impl fmt::String for StabilityLevel { +impl fmt::Display for StabilityLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(self, f) + fmt::Debug::fmt(self, f) } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index bf26687deed..a5e10f42750 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -30,8 +30,8 @@ use libc::c_uint; use serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { - fn from_uint(n: uint) -> Self; - fn to_uint(&self) -> uint; + fn from_usize(n: usize) -> Self; + fn to_usize(&self) -> usize; } /// A byte offset. Keep this small (currently 32-bits), as AST contains @@ -43,21 +43,21 @@ pub struct BytePos(pub u32); /// is not equivalent to a character offset. The CodeMap will convert BytePos /// values to CharPos values as necessary. #[derive(Copy, PartialEq, Hash, PartialOrd, Show)] -pub struct CharPos(pub uint); +pub struct CharPos(pub usize); // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix // have been unsuccessful impl Pos for BytePos { - fn from_uint(n: uint) -> BytePos { BytePos(n as u32) } - fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint } + fn from_usize(n: usize) -> BytePos { BytePos(n as u32) } + fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize } } impl Add for BytePos { type Output = BytePos; fn add(self, rhs: BytePos) -> BytePos { - BytePos((self.to_uint() + rhs.to_uint()) as u32) + BytePos((self.to_usize() + rhs.to_usize()) as u32) } } @@ -65,20 +65,20 @@ impl Sub for BytePos { type Output = BytePos; fn sub(self, rhs: BytePos) -> BytePos { - BytePos((self.to_uint() - rhs.to_uint()) as u32) + BytePos((self.to_usize() - rhs.to_usize()) as u32) } } impl Pos for CharPos { - fn from_uint(n: uint) -> CharPos { CharPos(n) } - fn to_uint(&self) -> uint { let CharPos(n) = *self; n } + fn from_usize(n: usize) -> CharPos { CharPos(n) } + fn to_usize(&self) -> usize { let CharPos(n) = *self; n } } impl Add for CharPos { type Output = CharPos; fn add(self, rhs: CharPos) -> CharPos { - CharPos(self.to_uint() + rhs.to_uint()) + CharPos(self.to_usize() + rhs.to_usize()) } } @@ -86,7 +86,7 @@ impl Sub for CharPos { type Output = CharPos; fn sub(self, rhs: CharPos) -> CharPos { - CharPos(self.to_uint() - rhs.to_uint()) + CharPos(self.to_usize() - rhs.to_usize()) } } @@ -173,7 +173,7 @@ pub struct Loc { /// Information about the original source pub file: Rc<FileMap>, /// The (1-based) line number - pub line: uint, + pub line: usize, /// The (0-based) column offset pub col: CharPos } @@ -183,13 +183,13 @@ pub struct Loc { // perhaps they should just be removed. pub struct LocWithOpt { pub filename: FileName, - pub line: uint, + pub line: usize, pub col: CharPos, pub file: Option<Rc<FileMap>>, } // used to be structural records. Better names, anyone? -pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: uint } +pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize } pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos } /// The syntax with which a macro was invoked. @@ -258,7 +258,7 @@ pub type FileName = String; pub struct FileLines { pub file: Rc<FileMap>, - pub lines: Vec<uint> + pub lines: Vec<usize> } /// Identifies an offset of a multi-byte character in a FileMap @@ -267,7 +267,7 @@ pub struct MultiByteChar { /// The absolute offset of the character in the CodeMap pub pos: BytePos, /// The number of bytes, >=2 - pub bytes: uint, + pub bytes: usize, } /// A single source in the CodeMap @@ -306,11 +306,11 @@ impl FileMap { /// get a line from the list of pre-computed line-beginnings /// - pub fn get_line(&self, line_number: uint) -> Option<String> { + pub fn get_line(&self, line_number: usize) -> Option<String> { let lines = self.lines.borrow(); lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; - let begin = begin.to_uint(); + let begin = begin.to_usize(); let slice = &self.src[begin..]; match slice.find('\n') { Some(e) => &slice[..e], @@ -319,7 +319,7 @@ impl FileMap { }) } - pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { + pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) { assert!(bytes >=2 && bytes <= 4); let mbc = MultiByteChar { pos: pos, @@ -351,7 +351,7 @@ impl CodeMap { let mut files = self.files.borrow_mut(); let start_pos = match files.last() { None => 0, - Some(last) => last.start_pos.to_uint() + last.src.len(), + Some(last) => last.start_pos.to_usize() + last.src.len(), }; // Remove utf-8 BOM if any. @@ -374,7 +374,7 @@ impl CodeMap { let filemap = Rc::new(FileMap { name: filename, src: src.to_string(), - start_pos: Pos::from_uint(start_pos), + start_pos: Pos::from_usize(start_pos), lines: RefCell::new(Vec::new()), multibyte_chars: RefCell::new(Vec::new()), }); @@ -389,7 +389,7 @@ impl CodeMap { (format!("<{}:{}:{}>", pos.file.name, pos.line, - pos.col.to_uint() + 1)).to_string() + pos.col.to_usize() + 1)).to_string() } /// Lookup source information about a BytePos @@ -417,9 +417,9 @@ impl CodeMap { return (format!("{}:{}:{}: {}:{}", lo.filename, lo.line, - lo.col.to_uint() + 1, + lo.col.to_usize() + 1, hi.line, - hi.col.to_uint() + 1)).to_string() + hi.col.to_usize() + 1)).to_string() } pub fn span_to_filename(&self, sp: Span) -> FileName { @@ -430,7 +430,7 @@ impl CodeMap { let lo = self.lookup_char_pos(sp.lo); let hi = self.lookup_char_pos(sp.hi); let mut lines = Vec::new(); - for i in range(lo.line - 1u, hi.line as uint) { + for i in range(lo.line - 1us, hi.line as usize) { lines.push(i); }; FileLines {file: lo.file, lines: lines} @@ -447,7 +447,7 @@ impl CodeMap { if begin.fm.start_pos != end.fm.start_pos { None } else { - Some((&begin.fm.src[begin.pos.to_uint()..end.pos.to_uint()]).to_string()) + Some((&begin.fm.src[begin.pos.to_usize()..end.pos.to_usize()]).to_string()) } } @@ -484,24 +484,24 @@ impl CodeMap { total_extra_bytes += mbc.bytes - 1; // We should never see a byte position in the middle of a // character - assert!(bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes); + assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes); } else { break; } } - assert!(map.start_pos.to_uint() + total_extra_bytes <= bpos.to_uint()); - CharPos(bpos.to_uint() - map.start_pos.to_uint() - total_extra_bytes) + assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize()); + CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes) } - fn lookup_filemap_idx(&self, pos: BytePos) -> uint { + fn lookup_filemap_idx(&self, pos: BytePos) -> usize { let files = self.files.borrow(); let files = &*files; let len = files.len(); - let mut a = 0u; + let mut a = 0us; let mut b = len; - while b - a > 1u { - let m = (a + b) / 2u; + while b - a > 1us { + let m = (a + b) / 2us; if files[m].start_pos > pos { b = m; } else { @@ -520,13 +520,13 @@ impl CodeMap { } if a == 0 { panic!("position {} does not resolve to a source location", - pos.to_uint()); + pos.to_usize()); } a -= 1; } if a >= len { panic!("position {} does not resolve to a source location", - pos.to_uint()) + pos.to_usize()) } return a; @@ -537,12 +537,12 @@ impl CodeMap { let files = self.files.borrow(); let f = (*files)[idx].clone(); - let mut a = 0u; + let mut a = 0us; { let lines = f.lines.borrow(); let mut b = lines.len(); - while b - a > 1u { - let m = (a + b) / 2u; + while b - a > 1us { + let m = (a + b) / 2us; if (*lines)[m] > pos { b = m; } else { a = m; } } } @@ -551,7 +551,7 @@ impl CodeMap { fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); - let line = a + 1u; // Line numbers start at 1 + let line = a + 1us; // Line numbers start at 1 let chpos = self.bytepos_to_file_charpos(pos); let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); @@ -579,7 +579,7 @@ impl CodeMap { { match id { NO_EXPANSION => f(None), - ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint])) + ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize])) } } @@ -762,7 +762,7 @@ mod test { assert_eq!(file_lines.file.name, "blork.rs"); assert_eq!(file_lines.lines.len(), 1); - assert_eq!(file_lines.lines[0], 1u); + assert_eq!(file_lines.lines[0], 1us); } #[test] diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index 3f91831a5df..3eaac0fe333 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -63,28 +63,13 @@ pub fn strip_items<F>(krate: ast::Crate, in_cfg: F) -> ast::Crate where ctxt.fold_crate(krate) } -fn filter_view_item<F>(cx: &mut Context<F>, - view_item: ast::ViewItem) - -> Option<ast::ViewItem> where - F: FnMut(&[ast::Attribute]) -> bool -{ - if view_item_in_cfg(cx, &view_item) { - Some(view_item) - } else { - None - } -} - fn fold_mod<F>(cx: &mut Context<F>, - ast::Mod {inner, - view_items, items}: ast::Mod) -> ast::Mod where + ast::Mod {inner, items}: ast::Mod) + -> ast::Mod where F: FnMut(&[ast::Attribute]) -> bool { ast::Mod { inner: inner, - view_items: view_items.into_iter().filter_map(|a| { - filter_view_item(cx, a).map(|x| cx.fold_view_item(x)) - }).collect(), items: items.into_iter().flat_map(|a| { cx.fold_item(a).into_iter() }).collect() @@ -104,15 +89,12 @@ fn filter_foreign_item<F>(cx: &mut Context<F>, } fn fold_foreign_mod<F>(cx: &mut Context<F>, - ast::ForeignMod {abi, view_items, items}: ast::ForeignMod) + ast::ForeignMod {abi, items}: ast::ForeignMod) -> ast::ForeignMod where F: FnMut(&[ast::Attribute]) -> bool { ast::ForeignMod { abi: abi, - view_items: view_items.into_iter().filter_map(|a| { - filter_view_item(cx, a).map(|x| cx.fold_view_item(x)) - }).collect(), items: items.into_iter() .filter_map(|a| filter_foreign_item(cx, a)) .collect() @@ -216,18 +198,14 @@ fn retain_stmt<F>(cx: &mut Context<F>, stmt: &ast::Stmt) -> bool where fn fold_block<F>(cx: &mut Context<F>, b: P<ast::Block>) -> P<ast::Block> where F: FnMut(&[ast::Attribute]) -> bool { - b.map(|ast::Block {id, view_items, stmts, expr, rules, span}| { + b.map(|ast::Block {id, stmts, expr, rules, span}| { let resulting_stmts: Vec<P<ast::Stmt>> = stmts.into_iter().filter(|a| retain_stmt(cx, &**a)).collect(); let resulting_stmts = resulting_stmts.into_iter() .flat_map(|stmt| cx.fold_stmt(stmt).into_iter()) .collect(); - let filtered_view_items = view_items.into_iter().filter_map(|a| { - filter_view_item(cx, a).map(|x| cx.fold_view_item(x)) - }).collect(); ast::Block { id: id, - view_items: filtered_view_items, stmts: resulting_stmts, expr: expr.map(|x| cx.fold_expr(x)), rules: rules, @@ -267,12 +245,6 @@ fn foreign_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ForeignItem) -> bool return (cx.in_cfg)(item.attrs.as_slice()); } -fn view_item_in_cfg<F>(cx: &mut Context<F>, item: &ast::ViewItem) -> bool where - F: FnMut(&[ast::Attribute]) -> bool -{ - return (cx.in_cfg)(item.attrs.as_slice()); -} - fn trait_method_in_cfg<F>(cx: &mut Context<F>, meth: &ast::TraitItem) -> bool where F: FnMut(&[ast::Attribute]) -> bool { diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 7213b0fa955..0c7f6befc4e 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -26,7 +26,7 @@ use term::WriterWrapper; use term; /// maximum number of lines we will print for each error; arbitrary. -static MAX_LINES: uint = 6u; +static MAX_LINES: usize = 6us; #[derive(Clone, Copy)] pub enum RenderSpan { @@ -92,6 +92,10 @@ impl SpanHandler { self.handler.emit(Some((&self.cm, sp)), msg, Fatal); panic!(FatalError); } + pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! { + self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal); + panic!(FatalError); + } pub fn span_err(&self, sp: Span, msg: &str) { self.handler.emit(Some((&self.cm, sp)), msg, Error); self.handler.bump_err_count(); @@ -137,7 +141,7 @@ impl SpanHandler { /// (fatal, bug, unimpl) may cause immediate exit, /// others log errors for later reporting. pub struct Handler { - err_count: Cell<uint>, + err_count: Cell<usize>, emit: RefCell<Box<Emitter + Send>>, } @@ -151,20 +155,20 @@ impl Handler { self.bump_err_count(); } pub fn bump_err_count(&self) { - self.err_count.set(self.err_count.get() + 1u); + self.err_count.set(self.err_count.get() + 1us); } - pub fn err_count(&self) -> uint { + pub fn err_count(&self) -> usize { self.err_count.get() } pub fn has_errors(&self) -> bool { - self.err_count.get()> 0u + self.err_count.get() > 0us } pub fn abort_if_errors(&self) { let s; match self.err_count.get() { - 0u => return, - 1u => s = "aborting due to previous error".to_string(), - _ => { + 0us => return, + 1us => s = "aborting due to previous error".to_string(), + _ => { s = format!("aborting due to {} previous errors", self.err_count.get()); } @@ -235,9 +239,9 @@ pub enum Level { Help, } -impl fmt::String for Level { +impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::String; + use std::fmt::Display; match *self { Bug => "error: internal compiler error".fmt(f), @@ -280,7 +284,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { - try!(t.write_str(&msg[..(msg.len()-1)])); + try!(t.write_str(&msg[..msg.len()-1])); try!(t.reset()); try!(t.write_str("\n")); } else { @@ -448,7 +452,7 @@ fn highlight_lines(err: &mut EmitterWriter, let mut elided = false; let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { - display_lines = &display_lines[0u..MAX_LINES]; + display_lines = &display_lines[0us..MAX_LINES]; elided = true; } // Print the offending lines @@ -459,32 +463,32 @@ fn highlight_lines(err: &mut EmitterWriter, } } if elided { - let last_line = display_lines[display_lines.len() - 1u]; - let s = format!("{}:{} ", fm.name, last_line + 1u); + let last_line = display_lines[display_lines.len() - 1us]; + let s = format!("{}:{} ", fm.name, last_line + 1us); try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len())); } // FIXME (#3260) // If there's one line at fault we can easily point to the problem - if lines.lines.len() == 1u { + if lines.lines.len() == 1us { let lo = cm.lookup_char_pos(sp.lo); - let mut digits = 0u; - let mut num = (lines.lines[0] + 1u) / 10u; + let mut digits = 0us; + let mut num = (lines.lines[0] + 1us) / 10us; // how many digits must be indent past? - while num > 0u { num /= 10u; digits += 1u; } + while num > 0us { num /= 10us; digits += 1us; } // indent past |name:## | and the 0-offset column location - let left = fm.name.len() + digits + lo.col.to_uint() + 3u; + let left = fm.name.len() + digits + lo.col.to_usize() + 3us; let mut s = String::new(); // Skip is the number of characters we need to skip because they are // part of the 'filename:line ' part of the previous line. - let skip = fm.name.len() + digits + 3u; + let skip = fm.name.len() + digits + 3us; for _ in range(0, skip) { s.push(' '); } if let Some(orig) = fm.get_line(lines.lines[0]) { - for pos in range(0u, left - skip) { + for pos in range(0us, left - skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on // the error-point-squiggly-line as well (instead of a space). @@ -502,7 +506,7 @@ fn highlight_lines(err: &mut EmitterWriter, let hi = cm.lookup_char_pos(sp.hi); if hi.col != lo.col { // the ^ already takes up one space - let num_squigglies = hi.col.to_uint() - lo.col.to_uint() - 1u; + let num_squigglies = hi.col.to_usize() - lo.col.to_usize() - 1us; for _ in range(0, num_squigglies) { s.push('~'); } @@ -551,7 +555,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1); let hi = cm.lookup_char_pos(sp.hi); // Span seems to use half-opened interval, so subtract 1 - let skip = last_line_start.len() + hi.col.to_uint() - 1; + let skip = last_line_start.len() + hi.col.to_usize() - 1; let mut s = String::new(); for _ in range(0, skip) { s.push(' '); diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs index 34a193dffd3..9321d3ca3df 100644 --- a/src/libsyntax/diagnostics/macros.rs +++ b/src/libsyntax/diagnostics/macros.rs @@ -15,6 +15,14 @@ macro_rules! register_diagnostic { } #[macro_export] +macro_rules! span_fatal { + ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ + __diagnostic_used!($code); + $session.span_fatal_with_code($span, format!($($message)*).as_slice(), stringify!($code)) + }) +} + +#[macro_export] macro_rules! span_err { ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ __diagnostic_used!($code); @@ -51,3 +59,9 @@ macro_rules! register_diagnostics { ) } +#[macro_export] +macro_rules! register_long_diagnostics { + ($($code:tt: $description:tt),*) => ( + $(register_diagnostic! { $code, $description })* + ) +} diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 1469c50061c..bd5247bbad6 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::BTreeMap; use ast; use ast::{Ident, Name, TokenTree}; use codemap::Span; @@ -19,18 +19,18 @@ use parse::token; use ptr::P; thread_local! { - static REGISTERED_DIAGNOSTICS: RefCell<HashMap<Name, Option<Name>>> = { - RefCell::new(HashMap::new()) + static REGISTERED_DIAGNOSTICS: RefCell<BTreeMap<Name, Option<Name>>> = { + RefCell::new(BTreeMap::new()) } } thread_local! { - static USED_DIAGNOSTICS: RefCell<HashMap<Name, Span>> = { - RefCell::new(HashMap::new()) + static USED_DIAGNOSTICS: RefCell<BTreeMap<Name, Span>> = { + RefCell::new(BTreeMap::new()) } } fn with_registered_diagnostics<T, F>(f: F) -> T where - F: FnOnce(&mut HashMap<Name, Option<Name>>) -> T, + F: FnOnce(&mut BTreeMap<Name, Option<Name>>) -> T, { REGISTERED_DIAGNOSTICS.with(move |slot| { f(&mut *slot.borrow_mut()) @@ -38,7 +38,7 @@ fn with_registered_diagnostics<T, F>(f: F) -> T where } fn with_used_diagnostics<T, F>(f: F) -> T where - F: FnOnce(&mut HashMap<Name, Span>) -> T, + F: FnOnce(&mut BTreeMap<Name, Span>) -> T, { USED_DIAGNOSTICS.with(move |slot| { f(&mut *slot.borrow_mut()) @@ -65,6 +65,13 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, } () }); + with_registered_diagnostics(|diagnostics| { + if !diagnostics.contains_key(&code.name) { + ecx.span_err(span, &format!( + "used diagnostic code {} not registered", token::get_ident(code).get() + )[]); + } + }); MacExpr::new(quote_expr!(ecx, ())) } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index bca7131fdb7..9cfdc942c21 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -548,7 +548,7 @@ pub struct ExtCtxt<'a> { pub exported_macros: Vec<ast::MacroDef>, pub syntax_env: SyntaxEnv, - pub recursion_count: uint, + pub recursion_count: usize, } impl<'a> ExtCtxt<'a> { diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index c34142aec39..92619cf42e4 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -97,7 +97,6 @@ pub trait AstBuilder { expr: Option<P<ast::Expr>>) -> P<ast::Block>; fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block>; fn block_all(&self, span: Span, - view_items: Vec<ast::ViewItem>, stmts: Vec<P<ast::Stmt>>, expr: Option<P<ast::Expr>>) -> P<ast::Block>; @@ -116,7 +115,7 @@ pub trait AstBuilder { fn expr_mut_addr_of(&self, sp: Span, e: P<ast::Expr>) -> P<ast::Expr>; fn expr_field_access(&self, span: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr>; fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, - idx: uint) -> P<ast::Expr>; + idx: usize) -> P<ast::Expr>; fn expr_call(&self, span: Span, expr: P<ast::Expr>, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_call_ident(&self, span: Span, id: ast::Ident, args: Vec<P<ast::Expr>>) -> P<ast::Expr>; fn expr_call_global(&self, sp: Span, fn_path: Vec<ast::Ident>, @@ -134,8 +133,8 @@ pub trait AstBuilder { fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P<ast::Expr>; - fn expr_uint(&self, span: Span, i: uint) -> P<ast::Expr>; - fn expr_int(&self, sp: Span, i: int) -> P<ast::Expr>; + fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr>; + fn expr_int(&self, sp: Span, i: isize) -> P<ast::Expr>; fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr>; fn expr_bool(&self, sp: Span, value: bool) -> P<ast::Expr>; @@ -242,7 +241,7 @@ pub trait AstBuilder { fn item_mod(&self, span: Span, inner_span: Span, name: Ident, attrs: Vec<ast::Attribute>, - vi: Vec<ast::ViewItem> , items: Vec<P<ast::Item>> ) -> P<ast::Item>; + items: Vec<P<ast::Item>>) -> P<ast::Item>; fn item_static(&self, span: Span, @@ -280,15 +279,15 @@ pub trait AstBuilder { value: ast::Lit_) -> P<ast::MetaItem>; - fn view_use(&self, sp: Span, - vis: ast::Visibility, vp: P<ast::ViewPath>) -> ast::ViewItem; - fn view_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> ast::ViewItem; - fn view_use_simple_(&self, sp: Span, vis: ast::Visibility, - ident: ast::Ident, path: ast::Path) -> ast::ViewItem; - fn view_use_list(&self, sp: Span, vis: ast::Visibility, - path: Vec<ast::Ident> , imports: &[ast::Ident]) -> ast::ViewItem; - fn view_use_glob(&self, sp: Span, - vis: ast::Visibility, path: Vec<ast::Ident> ) -> ast::ViewItem; + fn item_use(&self, sp: Span, + vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item>; + fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item>; + fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, + ident: ast::Ident, path: ast::Path) -> P<ast::Item>; + fn item_use_list(&self, sp: Span, vis: ast::Visibility, + path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item>; + fn item_use_glob(&self, sp: Span, + vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item>; } impl<'a> AstBuilder for ExtCtxt<'a> { @@ -519,7 +518,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn block(&self, span: Span, stmts: Vec<P<ast::Stmt>>, expr: Option<P<Expr>>) -> P<ast::Block> { - self.block_all(span, Vec::new(), stmts, expr) + self.block_all(span, stmts, expr) } fn stmt_item(&self, sp: Span, item: P<ast::Item>) -> P<ast::Stmt> { @@ -528,15 +527,13 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn block_expr(&self, expr: P<ast::Expr>) -> P<ast::Block> { - self.block_all(expr.span, Vec::new(), Vec::new(), Some(expr)) + self.block_all(expr.span, Vec::new(), Some(expr)) } fn block_all(&self, span: Span, - view_items: Vec<ast::ViewItem>, stmts: Vec<P<ast::Stmt>>, expr: Option<P<ast::Expr>>) -> P<ast::Block> { P(ast::Block { - view_items: view_items, stmts: stmts, expr: expr, id: ast::DUMMY_NODE_ID, @@ -579,7 +576,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_field_access(&self, sp: Span, expr: P<ast::Expr>, ident: ast::Ident) -> P<ast::Expr> { let field_name = token::get_ident(ident); let field_span = Span { - lo: sp.lo - Pos::from_uint(field_name.get().len()), + lo: sp.lo - Pos::from_usize(field_name.get().len()), hi: sp.hi, expn_id: sp.expn_id, }; @@ -587,9 +584,9 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let id = Spanned { node: ident, span: field_span }; self.expr(sp, ast::ExprField(expr, id)) } - fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: uint) -> P<ast::Expr> { + fn expr_tup_field_access(&self, sp: Span, expr: P<ast::Expr>, idx: usize) -> P<ast::Expr> { let field_span = Span { - lo: sp.lo - Pos::from_uint(idx.to_string().len()), + lo: sp.lo - Pos::from_usize(idx.to_string().len()), hi: sp.hi, expn_id: sp.expn_id, }; @@ -641,10 +638,10 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_lit(&self, sp: Span, lit: ast::Lit_) -> P<ast::Expr> { self.expr(sp, ast::ExprLit(P(respan(sp, lit)))) } - fn expr_uint(&self, span: Span, i: uint) -> P<ast::Expr> { + fn expr_usize(&self, span: Span, i: usize) -> P<ast::Expr> { self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs(false)))) } - fn expr_int(&self, sp: Span, i: int) -> P<ast::Expr> { + fn expr_int(&self, sp: Span, i: isize) -> P<ast::Expr> { self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyIs(false), ast::Sign::new(i)))) } @@ -710,7 +707,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, token::intern_and_get_ident(&loc.file.name[])); - let expr_line = self.expr_uint(span, loc.line); + let expr_line = self.expr_usize(span, loc.line); let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); self.expr_call_global( @@ -1031,16 +1028,14 @@ impl<'a> AstBuilder for ExtCtxt<'a> { } fn item_mod(&self, span: Span, inner_span: Span, name: Ident, - attrs: Vec<ast::Attribute> , - vi: Vec<ast::ViewItem> , - items: Vec<P<ast::Item>> ) -> P<ast::Item> { + attrs: Vec<ast::Attribute>, + items: Vec<P<ast::Item>>) -> P<ast::Item> { self.item( span, name, attrs, ast::ItemMod(ast::Mod { inner: inner_span, - view_items: vi, items: items, }) ) @@ -1101,47 +1096,47 @@ impl<'a> AstBuilder for ExtCtxt<'a> { P(respan(sp, ast::MetaNameValue(name, respan(sp, value)))) } - fn view_use(&self, sp: Span, - vis: ast::Visibility, vp: P<ast::ViewPath>) -> ast::ViewItem { - ast::ViewItem { - node: ast::ViewItemUse(vp), - attrs: Vec::new(), + fn item_use(&self, sp: Span, + vis: ast::Visibility, vp: P<ast::ViewPath>) -> P<ast::Item> { + P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: special_idents::invalid, + attrs: vec![], + node: ast::ItemUse(vp), vis: vis, span: sp - } + }) } - fn view_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> ast::ViewItem { + fn item_use_simple(&self, sp: Span, vis: ast::Visibility, path: ast::Path) -> P<ast::Item> { let last = path.segments.last().unwrap().identifier; - self.view_use_simple_(sp, vis, last, path) + self.item_use_simple_(sp, vis, last, path) } - fn view_use_simple_(&self, sp: Span, vis: ast::Visibility, - ident: ast::Ident, path: ast::Path) -> ast::ViewItem { - self.view_use(sp, vis, + fn item_use_simple_(&self, sp: Span, vis: ast::Visibility, + ident: ast::Ident, path: ast::Path) -> P<ast::Item> { + self.item_use(sp, vis, P(respan(sp, ast::ViewPathSimple(ident, - path, - ast::DUMMY_NODE_ID)))) + path)))) } - fn view_use_list(&self, sp: Span, vis: ast::Visibility, - path: Vec<ast::Ident> , imports: &[ast::Ident]) -> ast::ViewItem { + fn item_use_list(&self, sp: Span, vis: ast::Visibility, + path: Vec<ast::Ident>, imports: &[ast::Ident]) -> P<ast::Item> { let imports = imports.iter().map(|id| { respan(sp, ast::PathListIdent { name: *id, id: ast::DUMMY_NODE_ID }) }).collect(); - self.view_use(sp, vis, + self.item_use(sp, vis, P(respan(sp, ast::ViewPathList(self.path(sp, path), - imports, - ast::DUMMY_NODE_ID)))) + imports)))) } - fn view_use_glob(&self, sp: Span, - vis: ast::Visibility, path: Vec<ast::Ident> ) -> ast::ViewItem { - self.view_use(sp, vis, + fn item_use_glob(&self, sp: Span, + vis: ast::Visibility, path: Vec<ast::Ident>) -> P<ast::Item> { + self.item_use(sp, vis, P(respan(sp, - ast::ViewPathGlob(self.path(sp, path), ast::DUMMY_NODE_ID)))) + ast::ViewPathGlob(self.path(sp, path))))) } } diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 8edbf018f22..e458bd58e8b 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -114,7 +114,7 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), read_struct_field, vec!(cx.expr_str(span, name), - cx.expr_uint(span, field), + cx.expr_usize(span, field), exprdecode.clone()))) }); let result = cx.expr_ok(trait_span, result); @@ -123,7 +123,7 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.ident_of("read_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), - cx.expr_uint(trait_span, nfields), + cx.expr_usize(trait_span, nfields), cx.lambda_expr_1(trait_span, result, blkarg) )) } @@ -143,14 +143,14 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, path, parts, |cx, span, _, field| { - let idx = cx.expr_uint(span, field); + let idx = cx.expr_usize(span, field); cx.expr_try(span, cx.expr_method_call(span, blkdecoder.clone(), rvariant_arg, vec!(idx, exprdecode.clone()))) }); arms.push(cx.arm(v_span, - vec!(cx.pat_lit(v_span, cx.expr_uint(v_span, i))), + vec!(cx.pat_lit(v_span, cx.expr_usize(v_span, i))), decoded)); } @@ -179,14 +179,14 @@ fn decodable_substructure(cx: &mut ExtCtxt, trait_span: Span, /// Create a decoder for a single enum variant/struct: /// - `outer_pat_path` is the path to this enum variant/struct -/// - `getarg` should retrieve the `uint`-th field with name `@str`. +/// - `getarg` should retrieve the `usize`-th field with name `@str`. fn decode_static_fields<F>(cx: &mut ExtCtxt, trait_span: Span, outer_pat_path: ast::Path, fields: &StaticFields, mut getarg: F) -> P<Expr> where - F: FnMut(&mut ExtCtxt, Span, InternedString, uint) -> P<Expr>, + F: FnMut(&mut ExtCtxt, Span, InternedString, usize) -> P<Expr>, { match *fields { Unnamed(ref fields) => { diff --git a/src/libsyntax/ext/deriving/default.rs b/src/libsyntax/ext/deriving/default.rs index 36c3f2c0ccb..f8fdd8575bd 100644 --- a/src/libsyntax/ext/deriving/default.rs +++ b/src/libsyntax/ext/deriving/default.rs @@ -79,7 +79,7 @@ fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructur StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue - cx.expr_uint(trait_span, 0) + cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 801ae213a7b..4c78a7b6a0c 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -16,7 +16,7 @@ //! //! ```ignore //! #[derive(Encodable, Decodable)] -//! struct Node { id: uint } +//! struct Node { id: usize } //! ``` //! //! would generate two implementations like: @@ -27,7 +27,7 @@ //! s.emit_struct("Node", 1, |this| { //! this.emit_struct_field("id", 0, |this| { //! Encodable::encode(&self.id, this) -//! /* this.emit_uint(self.id) can also be used */ +//! /* this.emit_usize(self.id) can also be used */ //! }) //! }) //! } @@ -192,7 +192,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let call = cx.expr_method_call(span, blkencoder.clone(), emit_struct_field, vec!(cx.expr_str(span, name), - cx.expr_uint(span, i), + cx.expr_usize(span, i), lambda)); // last call doesn't need a try! @@ -218,7 +218,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, cx.ident_of("emit_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), - cx.expr_uint(trait_span, fields.len()), + cx.expr_usize(trait_span, fields.len()), blk )) } @@ -239,7 +239,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let lambda = cx.lambda_expr_1(span, enc, blkarg); let call = cx.expr_method_call(span, blkencoder.clone(), emit_variant_arg, - vec!(cx.expr_uint(span, i), + vec!(cx.expr_usize(span, i), lambda)); let call = if i != last { cx.expr_try(span, call) @@ -262,8 +262,8 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let call = cx.expr_method_call(trait_span, blkencoder, cx.ident_of("emit_enum_variant"), vec!(name, - cx.expr_uint(trait_span, idx), - cx.expr_uint(trait_span, fields.len()), + cx.expr_usize(trait_span, idx), + cx.expr_usize(trait_span, fields.len()), blk)); let blk = cx.lambda_expr_1(trait_span, call, blkarg); let ret = cx.expr_method_call(trait_span, diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 293e4befd3b..272b0464010 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -28,7 +28,7 @@ //! arguments: //! //! - `Struct`, when `Self` is a struct (including tuple structs, e.g -//! `struct T(int, char)`). +//! `struct T(i32, char)`). //! - `EnumMatching`, when `Self` is an enum and all the arguments are the //! same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`) //! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments @@ -54,17 +54,17 @@ //! following snippet //! //! ```rust -//! struct A { x : int } +//! struct A { x : i32 } //! -//! struct B(int); +//! struct B(i32); //! //! enum C { -//! C0(int), -//! C1 { x: int } +//! C0(i32), +//! C1 { x: i32 } //! } //! ``` //! -//! The `int`s in `B` and `C0` don't have an identifier, so the +//! The `i32`s in `B` and `C0` don't have an identifier, so the //! `Option<ident>`s would be `None` for them. //! //! In the static cases, the structure is summarised, either into the just @@ -90,8 +90,8 @@ //! trait PartialEq { //! fn eq(&self, other: &Self); //! } -//! impl PartialEq for int { -//! fn eq(&self, other: &int) -> bool { +//! impl PartialEq for i32 { +//! fn eq(&self, other: &i32) -> bool { //! *self == *other //! } //! } @@ -117,7 +117,7 @@ //! //! ```{.text} //! Struct(vec![FieldInfo { -//! span: <span of `int`>, +//! span: <span of `i32`>, //! name: None, //! self_: <expr for &a> //! other: vec![<expr for &b>] @@ -132,7 +132,7 @@ //! ```{.text} //! EnumMatching(0, <ast::Variant for C0>, //! vec![FieldInfo { -//! span: <span of int> +//! span: <span of i32> //! name: None, //! self_: <expr for &a>, //! other: vec![<expr for &b>] @@ -179,7 +179,7 @@ //! StaticStruct(<ast::StructDef of B>, Unnamed(vec![<span of x>])) //! //! StaticEnum(<ast::EnumDef of C>, -//! vec![(<ident of C0>, <span of C0>, Unnamed(vec![<span of int>])), +//! vec![(<ident of C0>, <span of C0>, Unnamed(vec![<span of i32>])), //! (<ident of C1>, <span of C1>, Named(vec![(<ident of x>, <span of x>)]))]) //! ``` @@ -294,7 +294,7 @@ pub enum SubstructureFields<'a> { /// Matching variants of the enum: variant index, ast::Variant, /// fields: the field name is only non-`None` in the case of a struct /// variant. - EnumMatching(uint, &'a ast::Variant, Vec<FieldInfo>), + EnumMatching(usize, &'a ast::Variant, Vec<FieldInfo>), /// Non-matching variants of the enum, but with all state hidden from /// the consequent code. The first component holds `Ident`s for all of @@ -719,7 +719,7 @@ impl<'a> MethodDef<'a> { /// ``` /// #[derive(PartialEq)] - /// struct A { x: int, y: int } + /// struct A { x: i32, y: i32 } /// /// // equivalent to: /// impl PartialEq for A { @@ -748,7 +748,7 @@ impl<'a> MethodDef<'a> { let mut raw_fields = Vec::new(); // ~[[fields of self], // [fields of next Self arg], [etc]] let mut patterns = Vec::new(); - for i in range(0u, self_args.len()) { + for i in range(0us, self_args.len()) { let struct_path= cx.path(DUMMY_SP, vec!( type_ident )); let (pat, ident_expr) = trait_.create_struct_pattern(cx, @@ -825,7 +825,7 @@ impl<'a> MethodDef<'a> { /// #[derive(PartialEq)] /// enum A { /// A1, - /// A2(int) + /// A2(i32) /// } /// /// // is equivalent to @@ -837,8 +837,8 @@ impl<'a> MethodDef<'a> { /// (&A2(ref __self_0), /// &A2(ref __arg_1_0)) => (*__self_0).eq(&(*__arg_1_0)), /// _ => { - /// let __self_vi = match *self { A1(..) => 0u, A2(..) => 1u }; - /// let __arg_1_vi = match *__arg_1 { A1(..) => 0u, A2(..) => 1u }; + /// let __self_vi = match *self { A1(..) => 0us, A2(..) => 1us }; + /// let __arg_1_vi = match *__arg_1 { A1(..) => 0us, A2(..) => 1us }; /// false /// } /// } @@ -882,8 +882,8 @@ impl<'a> MethodDef<'a> { /// (Variant2, Variant2, Variant2) => ... // delegate Matching on Variant2 /// ... /// _ => { - /// let __this_vi = match this { Variant1 => 0u, Variant2 => 1u, ... }; - /// let __that_vi = match that { Variant1 => 0u, Variant2 => 1u, ... }; + /// let __this_vi = match this { Variant1 => 0us, Variant2 => 1us, ... }; + /// let __that_vi = match that { Variant1 => 0us, Variant2 => 1us, ... }; /// ... // catch-all remainder can inspect above variant index values. /// } /// } @@ -915,7 +915,7 @@ impl<'a> MethodDef<'a> { .collect::<Vec<ast::Ident>>(); // The `vi_idents` will be bound, solely in the catch-all, to - // a series of let statements mapping each self_arg to a uint + // a series of let statements mapping each self_arg to a usize // corresponding to its variant index. let vi_idents: Vec<ast::Ident> = self_arg_names.iter() .map(|name| { let vi_suffix = format!("{}_vi", &name[]); @@ -1039,19 +1039,19 @@ impl<'a> MethodDef<'a> { }).collect(); // Build a series of let statements mapping each self_arg - // to a uint corresponding to its variant index. + // to a usize corresponding to its variant index. // i.e. for `enum E<T> { A, B(1), C(T, T) }`, and a deriving // with three Self args, builds three statements: // // ``` // let __self0_vi = match self { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // let __self1_vi = match __arg1 { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // let __self2_vi = match __arg2 { - // A => 0u, B(..) => 1u, C(..) => 2u + // A => 0us, B(..) => 1us, C(..) => 2us // }; // ``` let mut index_let_stmts: Vec<P<ast::Stmt>> = Vec::new(); @@ -1073,7 +1073,7 @@ impl<'a> MethodDef<'a> { // <delegated expression referring to __self0_vi, et al.> // } let arm_expr = cx.expr_block( - cx.block_all(sp, Vec::new(), index_let_stmts, Some(arm_expr))); + cx.block_all(sp, index_let_stmts, Some(arm_expr))); // Builds arm: // _ => { let __self0_vi = ...; diff --git a/src/libsyntax/ext/deriving/generic/ty.rs b/src/libsyntax/ext/deriving/generic/ty.rs index 5e6a9c91ce0..85682d41b5f 100644 --- a/src/libsyntax/ext/deriving/generic/ty.rs +++ b/src/libsyntax/ext/deriving/generic/ty.rs @@ -32,7 +32,7 @@ pub enum PtrTy<'a> { Raw(ast::Mutability), } -/// A path, e.g. `::std::option::Option::<int>` (global). Has support +/// A path, e.g. `::std::option::Option::<i32>` (global). Has support /// for type parameters and a lifetime. #[derive(Clone)] pub struct Path<'a> { @@ -91,7 +91,7 @@ pub enum Ty<'a> { /// &/Box/ Ty Ptr(Box<Ty<'a>>, PtrTy<'a>), /// mod::mod::Type<[lifetime], [Params...]>, including a plain type - /// parameter, and things like `int` + /// parameter, and things like `i32` Literal(Path<'a>), /// includes unit Tuple(Vec<Ty<'a>> ) diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 08336be87d1..8dac864c2ae 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -89,7 +89,7 @@ fn hash_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) // iteration function. let discriminant = match variant.node.disr_expr { Some(ref d) => d.clone(), - None => cx.expr_uint(trait_span, index) + None => cx.expr_usize(trait_span, index) }; stmts.push(call_hash(trait_span, discriminant)); diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 603c4478007..e52a2b513ce 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -99,7 +99,9 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, "Rand" => expand!(rand::expand_deriving_rand), + // NOTE(stage0): remove "Show" "Show" => expand!(show::expand_deriving_show), + "Debug" => expand!(show::expand_deriving_show), "Default" => expand!(default::expand_deriving_default), diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index b5435896791..bb902d7059c 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -80,10 +80,10 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) if variants.is_empty() { cx.span_err(trait_span, "`Rand` cannot be derived for enums with no variants"); // let compilation continue - return cx.expr_uint(trait_span, 0); + return cx.expr_usize(trait_span, 0); } - let variant_count = cx.expr_uint(trait_span, variants.len()); + let variant_count = cx.expr_usize(trait_span, variants.len()); let rand_name = cx.path_all(trait_span, true, @@ -115,7 +115,7 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) variant_count); let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| { - let i_expr = cx.expr_uint(v_span, i); + let i_expr = cx.expr_usize(v_span, i); let pat = cx.pat_lit(v_span, i_expr); let path = cx.path(v_span, vec![substr.type_ident, ident]); diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index 48034ce50ab..f5b5d4dda19 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -35,7 +35,7 @@ pub fn expand_deriving_show<F>(cx: &mut ExtCtxt, let trait_def = TraitDef { span: span, attributes: Vec::new(), - path: Path::new(vec!("std", "fmt", "Show")), + path: Path::new(vec!("std", "fmt", "Debug")), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( @@ -67,7 +67,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, Struct(_) => substr.type_ident, EnumMatching(_, v, _) => v.node.name, EnumNonMatchingCollapsed(..) | StaticStruct(..) | StaticEnum(..) => { - cx.span_bug(span, "nonsensical .fields in `#[derive(Show)]`") + cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`") } }; diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9b54e259761..9f6bf352b04 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -104,7 +104,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let e = match os::getenv(var.get()) { None => { cx.span_err(sp, msg.get()); - cx.expr_uint(sp, 0) + cx.expr_usize(sp, 0) } Some(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) }; diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index c95bdeefd45..629991799e7 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -206,7 +206,6 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> { // wrap the if-let expr in a block let span = els.span; let blk = P(ast::Block { - view_items: vec![], stmts: vec![], expr: Some(P(els)), id: ast::DUMMY_NODE_ID, @@ -273,7 +272,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, // in this file. // Token-tree macros: MacInvocTT(pth, tts, _) => { - if pth.segments.len() > 1u { + if pth.segments.len() > 1us { fld.cx.span_err(pth.span, "expected macro name without module \ separators"); @@ -799,8 +798,7 @@ pub fn expand_block(blk: P<Block>, fld: &mut MacroExpander) -> P<Block> { // expand the elements of a block. pub fn expand_block_elts(b: P<Block>, fld: &mut MacroExpander) -> P<Block> { - b.map(|Block {id, view_items, stmts, expr, rules, span}| { - let new_view_items = view_items.into_iter().map(|x| fld.fold_view_item(x)).collect(); + b.map(|Block {id, stmts, expr, rules, span}| { let new_stmts = stmts.into_iter().flat_map(|x| { // perform all pending renames let renamed_stmt = { @@ -821,7 +819,6 @@ pub fn expand_block_elts(b: P<Block>, fld: &mut MacroExpander) -> P<Block> { }); Block { id: fld.new_id(id), - view_items: new_view_items, stmts: new_stmts, expr: new_expr, rules: rules, @@ -844,7 +841,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { }, _ => unreachable!() }; - if pth.segments.len() > 1u { + if pth.segments.len() > 1us { fld.cx.span_err(pth.span, "expected macro name without module separators"); return DummyResult::raw_pat(span); } @@ -1311,7 +1308,7 @@ fn new_span(cx: &ExtCtxt, sp: Span) -> Span { pub struct ExpansionConfig { pub crate_name: String, pub enable_quotes: bool, - pub recursion_limit: uint, + pub recursion_limit: usize, } impl ExpansionConfig { @@ -1507,7 +1504,7 @@ mod test { #[should_fail] #[test] fn macros_cant_escape_fns_test () { let src = "fn bogus() {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "<test>".to_string(), @@ -1521,7 +1518,7 @@ mod test { #[should_fail] #[test] fn macros_cant_escape_mods_test () { let src = "mod foo {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "<test>".to_string(), @@ -1533,7 +1530,7 @@ mod test { // macro_use modules should allow macros to escape #[test] fn macros_can_escape_flattened_mods_test () { let src = "#[macro_use] mod foo {macro_rules! z (() => (3+4));}\ - fn inty() -> int { z!() }".to_string(); + fn inty() -> i32 { z!() }".to_string(); let sess = parse::new_parse_sess(); let crate_ast = parse::parse_crate_from_source_str( "<test>".to_string(), @@ -1564,8 +1561,8 @@ mod test { // should be able to use a bound identifier as a literal in a macro definition: #[test] fn self_macro_parsing(){ expand_crate_str( - "macro_rules! foo ((zz) => (287u;)); - fn f(zz : int) {foo!(zz);}".to_string() + "macro_rules! foo ((zz) => (287;)); + fn f(zz: i32) {foo!(zz);}".to_string() ); } @@ -1595,29 +1592,29 @@ mod test { // in principle, you might want to control this boolean on a per-varref basis, // but that would make things even harder to understand, and might not be // necessary for thorough testing. - type RenamingTest = (&'static str, Vec<Vec<uint>>, bool); + type RenamingTest = (&'static str, Vec<Vec<usize>>, bool); #[test] fn automatic_renaming () { let tests: Vec<RenamingTest> = vec!(// b & c should get new names throughout, in the expr too: - ("fn a() -> int { let b = 13; let c = b; b+c }", + ("fn a() -> i32 { let b = 13; let c = b; b+c }", vec!(vec!(0,1),vec!(2)), false), // both x's should be renamed (how is this causing a bug?) - ("fn main () {let x: int = 13;x;}", + ("fn main () {let x: i32 = 13;x;}", vec!(vec!(0)), false), // the use of b after the + should be renamed, the other one not: - ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> int { let b = 13; f!(b)}", + ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> i32 { let b = 13; f!(b)}", vec!(vec!(1)), false), // the b before the plus should not be renamed (requires marks) - ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> int { f!(b)}", + ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> i32 { f!(b)}", vec!(vec!(1)), false), // the marks going in and out of letty should cancel, allowing that $x to // capture the one following the semicolon. // this was an awesome test case, and caught a *lot* of bugs. ("macro_rules! letty(($x:ident) => (let $x = 15;)); macro_rules! user(($x:ident) => ({letty!($x); $x})); - fn main() -> int {user!(z)}", + fn main() -> i32 {user!(z)}", vec!(vec!(0)), false) ); for (idx,s) in tests.iter().enumerate() { @@ -1680,13 +1677,13 @@ mod test { // can't write this test case until we have macro-generating macros. // method arg hygiene - // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1} + // method expands to fn get_x(&self_0, x_1: i32) {self_0 + self_2 + x_3 + x_1} #[test] fn method_arg_hygiene(){ run_renaming_test( &("macro_rules! inject_x (()=>(x)); macro_rules! inject_self (()=>(self)); struct A; - impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }", + impl A{fn get_x(&self, x: i32) {self + inject_self!() + inject_x!() + x;} }", vec!(vec!(0),vec!(3)), true), 0) @@ -1706,21 +1703,21 @@ mod test { } // item fn hygiene - // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};} + // expands to fn q(x_1: i32){fn g(x_2: i32){x_2 + x_1};} #[test] fn issue_9383(){ run_renaming_test( - &("macro_rules! bad_macro (($ex:expr) => (fn g(x:int){ x + $ex })); - fn q(x:int) { bad_macro!(x); }", + &("macro_rules! bad_macro (($ex:expr) => (fn g(x: i32){ x + $ex })); + fn q(x: i32) { bad_macro!(x); }", vec!(vec!(1),vec!(0)),true), 0) } // closure arg hygiene (ExprClosure) - // expands to fn f(){(|x_1 : int| {(x_2 + x_1)})(3);} + // expands to fn f(){(|x_1 : i32| {(x_2 + x_1)})(3);} #[test] fn closure_arg_hygiene(){ run_renaming_test( &("macro_rules! inject_x (()=>(x)); - fn f(){(|x : int| {(inject_x!() + x)})(3);}", + fn f(){(|x : i32| {(inject_x!() + x)})(3);}", vec!(vec!(1)), true), 0) @@ -1729,7 +1726,7 @@ mod test { // macro_rules in method position. Sadly, unimplemented. #[test] fn macro_in_method_posn(){ expand_crate_str( - "macro_rules! my_method (() => (fn thirteen(&self) -> int {13})); + "macro_rules! my_method (() => (fn thirteen(&self) -> i32 {13})); struct A; impl A{ my_method!(); } fn f(){A.thirteen;}".to_string()); @@ -1749,7 +1746,7 @@ mod test { } // run one of the renaming tests - fn run_renaming_test(t: &RenamingTest, test_idx: uint) { + fn run_renaming_test(t: &RenamingTest, test_idx: usize) { let invalid_name = token::special_idents::invalid.name; let (teststr, bound_connections, bound_ident_check) = match *t { (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic) @@ -1876,7 +1873,7 @@ foo_module!(); // it's the name of a 0-ary variant, and that 'i' appears twice in succession. #[test] fn crate_bindings_test(){ - let the_crate = string_to_crate("fn main (a : int) -> int {|b| { + let the_crate = string_to_crate("fn main (a: i32) -> i32 {|b| { match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string()); let idents = crate_bindings(&the_crate); assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y"))); @@ -1885,10 +1882,10 @@ foo_module!(); // test the IdentRenamer directly #[test] fn ident_renamer_test () { - let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string()); + let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string()); let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); - let int_ident = token::str_to_ident("int"); + let int_ident = token::str_to_ident("i32"); let renames = vec!((x_ident,Name(16))); let mut renamer = IdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); @@ -1900,10 +1897,10 @@ foo_module!(); // test the PatIdentRenamer; only PatIdents get renamed #[test] fn pat_ident_renamer_test () { - let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string()); + let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string()); let f_ident = token::str_to_ident("f"); let x_ident = token::str_to_ident("x"); - let int_ident = token::str_to_ident("int"); + let int_ident = token::str_to_ident("i32"); let renames = vec!((x_ident,Name(16))); let mut renamer = PatIdentRenamer{renames: &renames}; let renamed_crate = renamer.fold_crate(the_crate); diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index f512b33f024..8ea9d6168ef 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -31,7 +31,7 @@ enum ArgumentType { } enum Position { - Exact(uint), + Exact(usize), Named(String), } @@ -61,11 +61,11 @@ struct Context<'a, 'b:'a> { /// Stays `true` if all formatting parameters are default (as in "{}{}"). all_pieces_simple: bool, - name_positions: HashMap<String, uint>, + name_positions: HashMap<String, usize>, /// Updated as arguments are consumed or methods are entered - nest_level: uint, - next_arg: uint, + nest_level: usize, + next_arg: usize, } /// Parses the arguments from the given list of tokens, returning None @@ -326,11 +326,11 @@ impl<'a, 'b> Context<'a, 'b> { match c { parse::CountIs(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } parse::CountIsParam(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } parse::CountImplied => { let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, @@ -349,7 +349,7 @@ impl<'a, 'b> Context<'a, 'b> { }; let i = i + self.args.len(); self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "CountIsParam"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } } } @@ -382,7 +382,7 @@ impl<'a, 'b> Context<'a, 'b> { } parse::ArgumentIs(i) => { self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } // Named arguments are converted to positional arguments at // the end of the list of arguments @@ -393,7 +393,7 @@ impl<'a, 'b> Context<'a, 'b> { }; let i = i + self.args.len(); self.ecx.expr_call_global(sp, Context::rtpath(self.ecx, "ArgumentIs"), - vec!(self.ecx.expr_uint(sp, i))) + vec!(self.ecx.expr_usize(sp, i))) } }; @@ -432,7 +432,7 @@ impl<'a, 'b> Context<'a, 'b> { } }; let align = self.ecx.expr_path(align); - let flags = self.ecx.expr_uint(sp, arg.format.flags); + let flags = self.ecx.expr_usize(sp, arg.format.flags); let prec = self.trans_count(arg.format.precision); let width = self.trans_count(arg.format.width); let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec")); @@ -603,8 +603,8 @@ impl<'a, 'b> Context<'a, 'b> { let trait_ = match *ty { Known(ref tyname) => { match &tyname[] { - "" => "String", - "?" => "Show", + "" => "Display", + "?" => "Debug", "e" => "LowerExp", "E" => "UpperExp", "o" => "Octal", diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index ae8ff118fcc..7adc443759f 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -187,7 +187,7 @@ fn resolve_internal(id: Ident, } let resolved = { - let result = (*table.table.borrow())[id.ctxt as uint]; + let result = (*table.table.borrow())[id.ctxt as usize]; match result { EmptyCtxt => id.name, // ignore marks here: @@ -231,7 +231,7 @@ fn marksof_internal(ctxt: SyntaxContext, let mut result = Vec::new(); let mut loopvar = ctxt; loop { - let table_entry = (*table.table.borrow())[loopvar as uint]; + let table_entry = (*table.table.borrow())[loopvar as usize]; match table_entry { EmptyCtxt => { return result; @@ -258,7 +258,7 @@ fn marksof_internal(ctxt: SyntaxContext, /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { - match (*sctable.table.borrow())[ctxt as uint] { + match (*sctable.table.borrow())[ctxt as usize] { Mark(mrk, _) => mrk, _ => panic!("can't retrieve outer mark when outside is not a mark") } @@ -330,7 +330,7 @@ mod tests { let mut result = Vec::new(); loop { let table = table.table.borrow(); - match (*table)[sc as uint] { + match (*table)[sc as usize] { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); @@ -398,7 +398,7 @@ mod tests { assert_eq! (marksof_internal (ans, stopname,&t), vec!(16));} // rename where stop doesn't match: { let chain = vec!(M(9), - R(id(name1.uint() as u32, + R(id(name1.usize() as u32, apply_mark_internal (4, EMPTY_CTXT,&mut t)), Name(100101102)), M(14)); @@ -407,7 +407,7 @@ mod tests { // rename where stop does match { let name1sc = apply_mark_internal(4, EMPTY_CTXT, &mut t); let chain = vec!(M(9), - R(id(name1.uint() as u32, name1sc), + R(id(name1.usize() as u32, name1sc), stopname), M(14)); let ans = unfold_test_sc(chain,EMPTY_CTXT,&mut t); diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index c42b188302c..7e345a2d078 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -352,18 +352,11 @@ pub mod rt { impl<'a> ExtParseUtils for ExtCtxt<'a> { fn parse_item(&self, s: String) -> P<ast::Item> { - let res = parse::parse_item_from_source_str( + parse::parse_item_from_source_str( "<quote expansion>".to_string(), s, self.cfg(), - self.parse_sess()); - match res { - Some(ast) => ast, - None => { - error!("parse error"); - panic!() - } - } + self.parse_sess()).expect("parse error") } fn parse_stmt(&self, s: String) -> P<ast::Stmt> { @@ -588,7 +581,7 @@ fn mk_token(cx: &ExtCtxt, sp: Span, tok: &token::Token) -> P<ast::Expr> { } token::Literal(token::StrRaw(ident, n), suf) => { - return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_uint(sp, n)) + return mk_lit!("StrRaw", suf, mk_name(cx, sp, ident.ident()), cx.expr_usize(sp, n)) } token::Ident(ident, style) => { @@ -716,7 +709,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // try removing it when enough of them are gone. let mut p = cx.new_parser_from_tts(tts); - p.quote_depth += 1u; + p.quote_depth += 1us; let cx_expr = p.parse_expr(); if !p.eat(&token::Comma) { @@ -767,7 +760,6 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) vector.extend(mk_tts(cx, &tts[]).into_iter()); let block = cx.expr_block( cx.block_all(sp, - Vec::new(), vector, Some(cx.expr_ident(sp, id_ext("tt"))))); @@ -778,18 +770,18 @@ fn expand_wrapper(cx: &ExtCtxt, sp: Span, cx_expr: P<ast::Expr>, expr: P<ast::Expr>) -> P<ast::Expr> { - let uses = [ - &["syntax", "ext", "quote", "rt"], - ].iter().map(|path| { - let path = path.iter().map(|s| s.to_string()).collect(); - cx.view_use_glob(sp, ast::Inherited, ids_ext(path)) - }).collect(); - // Explicitly borrow to avoid moving from the invoker (#16992) let cx_expr_borrow = cx.expr_addr_of(sp, cx.expr_deref(sp, cx_expr)); let stmt_let_ext_cx = cx.stmt_let(sp, false, id_ext("ext_cx"), cx_expr_borrow); - cx.expr_block(cx.block_all(sp, uses, vec!(stmt_let_ext_cx), Some(expr))) + let stmts = [ + &["syntax", "ext", "quote", "rt"], + ].iter().map(|path| { + let path = path.iter().map(|s| s.to_string()).collect(); + cx.stmt_item(sp, cx.item_use_glob(sp, ast::Inherited, ids_ext(path))) + }).chain(Some(stmt_let_ext_cx).into_iter()).collect(); + + cx.expr_block(cx.block_all(sp, stmts, Some(expr))) } fn expand_parse_call(cx: &ExtCtxt, diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 31a1a838b13..a74adbf4085 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -35,7 +35,7 @@ pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - base::MacExpr::new(cx.expr_uint(topmost, loc.line)) + base::MacExpr::new(cx.expr_usize(topmost, loc.line)) } /* column!(): expands to the current column number */ @@ -45,7 +45,7 @@ pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - base::MacExpr::new(cx.expr_uint(topmost, loc.col.to_uint())) + base::MacExpr::new(cx.expr_usize(topmost, loc.col.to_usize())) } /// file!(): expands to the current filename */ diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 9eda4bcef99..d115f2ed620 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -110,14 +110,14 @@ enum TokenTreeOrTokenTreeVec { } impl TokenTreeOrTokenTreeVec { - fn len(&self) -> uint { + fn len(&self) -> usize { match self { &TtSeq(ref v) => v.len(), &Tt(ref tt) => tt.len(), } } - fn get_tt(&self, index: uint) -> TokenTree { + fn get_tt(&self, index: usize) -> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), @@ -129,7 +129,7 @@ impl TokenTreeOrTokenTreeVec { #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, - idx: uint, + idx: usize, } #[derive(Clone)] @@ -137,16 +137,16 @@ pub struct MatcherPos { stack: Vec<MatcherTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, - idx: uint, + idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, - match_lo: uint, - match_cur: uint, - match_hi: uint, + match_lo: usize, + match_cur: usize, + match_hi: usize, sp_lo: BytePos, } -pub fn count_names(ms: &[TokenTree]) -> uint { +pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match elt { &TtSequence(_, ref seq) => { @@ -171,11 +171,11 @@ pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: ByteP stack: vec![], top_elts: TtSeq(ms), sep: sep, - idx: 0u, + idx: 0us, up: None, matches: matches, - match_lo: 0u, - match_cur: 0u, + match_lo: 0us, + match_cur: 0us, match_hi: match_idx_hi, sp_lo: lo } @@ -206,7 +206,7 @@ pub enum NamedMatch { pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) -> HashMap<Ident, Rc<NamedMatch>> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>], - ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut uint) { + ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { for next_m in seq.tts.iter() { @@ -238,7 +238,7 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) } } let mut ret_val = HashMap::new(); - let mut idx = 0u; + let mut idx = 0us; for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } @@ -383,7 +383,7 @@ pub fn parse(sess: &ParseSess, if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; - new_ei.idx += 1u; + new_ei.idx += 1us; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); @@ -398,7 +398,7 @@ pub fn parse(sess: &ParseSess, cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), - idx: 0u, + idx: 0us, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, @@ -442,20 +442,20 @@ pub fn parse(sess: &ParseSess, /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { - if eof_eis.len() == 1u { + if eof_eis.len() == 1us { let mut v = Vec::new(); for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[])); - } else if eof_eis.len() > 1u { + } else if eof_eis.len() > 1us { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { - if (bb_eis.len() > 0u && next_eis.len() > 0u) - || bb_eis.len() > 1u { + if (bb_eis.len() > 0us && next_eis.len() > 0us) + || bb_eis.len() > 1us { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { @@ -469,12 +469,12 @@ pub fn parse(sess: &ParseSess, "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); - } else if bb_eis.len() == 0u && next_eis.len() == 0u { + } else if bb_eis.len() == 0us && next_eis.len() == 0us { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); - } else if next_eis.len() > 0u { + } else if next_eis.len() > 0us { /* Now process the next token */ - while next_eis.len() > 0u { + while next_eis.len() > 0us { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); @@ -488,7 +488,7 @@ pub fn parse(sess: &ParseSess, let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, name_string.get())))); - ei.idx += 1u; + ei.idx += 1us; ei.match_cur += 1; } _ => panic!() @@ -501,16 +501,16 @@ pub fn parse(sess: &ParseSess, } } - assert!(cur_eis.len() > 0u); + assert!(cur_eis.len() > 0us); } } pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { match name { "tt" => { - p.quote_depth += 1u; //but in theory, non-quoted tts might be useful + p.quote_depth += 1us; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); - p.quote_depth -= 1u; + p.quote_depth -= 1us; return res; } _ => {} diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 270df72eb0e..8350e0222ef 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -8,8 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use ast::{TokenTree, TtDelimited, TtSequence, TtToken}; -use ast; +use ast::{self, TokenTree, TtDelimited, TtSequence, TtToken}; use codemap::{Span, DUMMY_SP}; use ext::base::{ExtCtxt, MacResult, SyntaxExtension}; use ext::base::{NormalTT, TTMacroExpander}; @@ -19,9 +18,8 @@ use ext::tt::macro_parser::{parse, parse_or_else}; use parse::lexer::{new_tt_reader, new_tt_reader_with_doc_flag}; use parse::parser::Parser; use parse::attr::ParserAttr; -use parse::token::{special_idents, gensym_ident, NtTT, Token}; +use parse::token::{self, special_idents, gensym_ident, NtTT, Token}; use parse::token::Token::*; -use parse::token; use print; use ptr::P; @@ -336,16 +334,20 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. - match &next_token { - &Eof => return Some((sp, tok.clone())), - _ if is_in_follow(cx, &next_token, frag_spec.as_str()) => continue, - next => { + match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { + (&Eof, _) => return Some((sp, tok.clone())), + (_, Ok(true)) => continue, + (next, Ok(false)) => { cx.span_err(sp, format!("`${0}:{1}` is followed by `{2}`, which \ is not allowed for `{1}` fragments", name.as_str(), frag_spec.as_str(), token_to_string(next)).as_slice()); continue }, + (_, Err(msg)) => { + cx.span_err(sp, msg.as_slice()); + continue + } } }, TtSequence(sp, ref seq) => { @@ -412,51 +414,50 @@ fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) last } -fn is_in_follow(cx: &ExtCtxt, tok: &Token, frag: &str) -> bool { +fn is_in_follow(_: &ExtCtxt, tok: &Token, frag: &str) -> Result<bool, String> { if let &CloseDelim(_) = tok { - return true; - } - - match frag { - "item" => { - // since items *must* be followed by either a `;` or a `}`, we can - // accept anything after them - true - }, - "block" => { - // anything can follow block, the braces provide a easy boundary to - // maintain - true - }, - "stmt" | "expr" => { - match *tok { - FatArrow | Comma | Semi => true, - _ => false - } - }, - "pat" => { - match *tok { - FatArrow | Comma | Eq => true, - _ => false - } - }, - "path" | "ty" => { - match *tok { - Comma | FatArrow | Colon | Eq | Gt => true, - Ident(i, _) if i.as_str() == "as" => true, - _ => false - } - }, - "ident" => { - // being a single token, idents are harmless - true - }, - "meta" | "tt" => { - // being either a single token or a delimited sequence, tt is - // harmless - true - }, - _ => cx.bug(format!("unrecognized builtin nonterminal {}", - frag).as_slice()), + Ok(true) + } else { + match frag { + "item" => { + // since items *must* be followed by either a `;` or a `}`, we can + // accept anything after them + Ok(true) + }, + "block" => { + // anything can follow block, the braces provide a easy boundary to + // maintain + Ok(true) + }, + "stmt" | "expr" => { + match *tok { + FatArrow | Comma | Semi => Ok(true), + _ => Ok(false) + } + }, + "pat" => { + match *tok { + FatArrow | Comma | Eq => Ok(true), + _ => Ok(false) + } + }, + "path" | "ty" => { + match *tok { + Comma | FatArrow | Colon | Eq | Gt => Ok(true), + Ident(i, _) if i.as_str() == "as" => Ok(true), + _ => Ok(false) + } + }, + "ident" => { + // being a single token, idents are harmless + Ok(true) + }, + "meta" | "tt" => { + // being either a single token or a delimited sequence, tt is + // harmless + Ok(true) + }, + _ => Err(format!("unrecognized builtin nonterminal `{}`", frag)) + } } } diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 94b8356130a..0bf20b8f3e1 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -27,7 +27,7 @@ use std::collections::HashMap; #[derive(Clone)] struct TtFrame { forest: TokenTree, - idx: uint, + idx: usize, dotdotdoted: bool, sep: Option<Token>, } @@ -43,8 +43,8 @@ pub struct TtReader<'a> { // Some => return imported_from as the next token crate_name_next: Option<Span>, - repeat_idx: Vec<uint>, - repeat_len: Vec<uint>, + repeat_idx: Vec<usize>, + repeat_len: Vec<usize>, /* cached: */ pub cur_tok: Token, pub cur_span: Span, @@ -124,7 +124,7 @@ fn lookup_cur_matched(r: &TtReader, name: Ident) -> Option<Rc<NamedMatch>> { #[derive(Clone)] enum LockstepIterSize { LisUnconstrained, - LisConstraint(uint, Ident), + LisConstraint(usize, Ident), LisContradiction(String), } @@ -223,7 +223,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { r.repeat_len.pop(); } } else { /* repeat */ - *r.repeat_idx.last_mut().unwrap() += 1u; + *r.repeat_idx.last_mut().unwrap() += 1us; r.stack.last_mut().unwrap().idx = 0; match r.stack.last().unwrap().sep.clone() { Some(tk) => { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 989126cd8d6..e6046fb50dd 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -73,7 +73,7 @@ static KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[ ("rustc_diagnostic_macros", "1.0.0", Active), ("unboxed_closures", "1.0.0", Active), - ("import_shadowing", "1.0.0", Active), + ("import_shadowing", "1.0.0", Removed), ("advanced_slice_patterns", "1.0.0", Active), ("tuple_indexing", "1.0.0", Accepted), ("associated_types", "1.0.0", Accepted), @@ -138,7 +138,6 @@ enum Status { pub struct Features { pub unboxed_closures: bool, pub rustc_diagnostic_macros: bool, - pub import_shadowing: bool, pub visible_private_types: bool, pub quote: bool, pub old_orphan_check: bool, @@ -151,7 +150,6 @@ impl Features { Features { unboxed_closures: false, rustc_diagnostic_macros: false, - import_shadowing: false, visible_private_types: false, quote: false, old_orphan_check: false, @@ -249,22 +247,6 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } } - fn visit_view_item(&mut self, i: &ast::ViewItem) { - match i.node { - ast::ViewItemUse(..) => {} - ast::ViewItemExternCrate(..) => { - for attr in i.attrs.iter() { - if attr.check_name("plugin") { - self.gate_feature("plugin", attr.span, - "compiler plugins are experimental \ - and possibly buggy"); - } - } - } - } - visit::walk_view_item(self, i) - } - fn visit_item(&mut self, i: &ast::Item) { for attr in i.attrs.iter() { if attr.name() == "thread_local" { @@ -283,6 +265,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } } match i.node { + ast::ItemExternCrate(_) => { + if attr::contains_name(&i.attrs[], "plugin") { + self.gate_feature("plugin", i.span, + "compiler plugins are experimental \ + and possibly buggy"); + } + } + ast::ItemForeignMod(ref foreign_module) => { if attr::contains_name(&i.attrs[], "link_args") { self.gate_feature("link_args", i.span, @@ -563,7 +553,6 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C Features { unboxed_closures: cx.has_feature("unboxed_closures"), rustc_diagnostic_macros: cx.has_feature("rustc_diagnostic_macros"), - import_shadowing: cx.has_feature("import_shadowing"), visible_private_types: cx.has_feature("visible_private_types"), quote: cx.has_feature("quote"), old_orphan_check: cx.has_feature("old_orphan_check"), diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index f484650ad5b..9f8427cc8ae 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -78,10 +78,6 @@ pub trait Folder : Sized { noop_fold_view_path(view_path, self) } - fn fold_view_item(&mut self, vi: ViewItem) -> ViewItem { - noop_fold_view_item(vi, self) - } - fn fold_foreign_item(&mut self, ni: P<ForeignItem>) -> P<ForeignItem> { noop_fold_foreign_item(ni, self) } @@ -174,8 +170,8 @@ pub trait Folder : Sized { noop_fold_ident(i, self) } - fn fold_uint(&mut self, i: uint) -> uint { - noop_fold_uint(i, self) + fn fold_usize(&mut self, i: usize) -> usize { + noop_fold_usize(i, self) } fn fold_path(&mut self, p: Path) -> Path { @@ -349,16 +345,13 @@ pub fn noop_fold_meta_items<T: Folder>(meta_items: Vec<P<MetaItem>>, fld: &mut T pub fn noop_fold_view_path<T: Folder>(view_path: P<ViewPath>, fld: &mut T) -> P<ViewPath> { view_path.map(|Spanned {node, span}| Spanned { node: match node { - ViewPathSimple(ident, path, node_id) => { - let id = fld.new_id(node_id); - ViewPathSimple(ident, fld.fold_path(path), id) + ViewPathSimple(ident, path) => { + ViewPathSimple(ident, fld.fold_path(path)) } - ViewPathGlob(path, node_id) => { - let id = fld.new_id(node_id); - ViewPathGlob(fld.fold_path(path), id) + ViewPathGlob(path) => { + ViewPathGlob(fld.fold_path(path)) } - ViewPathList(path, path_list_idents, node_id) => { - let id = fld.new_id(node_id); + ViewPathList(path, path_list_idents) => { ViewPathList(fld.fold_path(path), path_list_idents.move_map(|path_list_ident| { Spanned { @@ -373,8 +366,7 @@ pub fn noop_fold_view_path<T: Folder>(view_path: P<ViewPath>, fld: &mut T) -> P< }, span: fld.new_span(path_list_ident.span) } - }), - id) + })) } }, span: fld.new_span(span) @@ -470,11 +462,10 @@ pub fn noop_fold_qpath<T: Folder>(qpath: P<QPath>, fld: &mut T) -> P<QPath> { }) } -pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, view_items, items}: ForeignMod, +pub fn noop_fold_foreign_mod<T: Folder>(ForeignMod {abi, items}: ForeignMod, fld: &mut T) -> ForeignMod { ForeignMod { abi: abi, - view_items: view_items.move_map(|x| fld.fold_view_item(x)), items: items.move_map(|x| fld.fold_foreign_item(x)), } } @@ -505,7 +496,7 @@ pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident { i } -pub fn noop_fold_uint<T: Folder>(i: uint, _: &mut T) -> uint { +pub fn noop_fold_usize<T: Folder>(i: usize, _: &mut T) -> usize { i } @@ -953,28 +944,9 @@ fn noop_fold_variant_arg<T: Folder>(VariantArg {id, ty}: VariantArg, folder: &mu } } -pub fn noop_fold_view_item<T: Folder>(ViewItem {node, attrs, vis, span}: ViewItem, - folder: &mut T) -> ViewItem { - ViewItem { - node: match node { - ViewItemExternCrate(ident, string, node_id) => { - ViewItemExternCrate(ident, string, - folder.new_id(node_id)) - } - ViewItemUse(view_path) => { - ViewItemUse(folder.fold_view_path(view_path)) - } - }, - attrs: attrs.move_map(|a| folder.fold_attribute(a)), - vis: vis, - span: folder.new_span(span) - } -} - pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> { - b.map(|Block {id, view_items, stmts, expr, rules, span}| Block { + b.map(|Block {id, stmts, expr, rules, span}| Block { id: folder.new_id(id), - view_items: view_items.move_map(|x| folder.fold_view_item(x)), stmts: stmts.into_iter().flat_map(|s| folder.fold_stmt(s).into_iter()).collect(), expr: expr.map(|x| folder.fold_expr(x)), rules: rules, @@ -984,6 +956,10 @@ pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> { pub fn noop_fold_item_underscore<T: Folder>(i: Item_, folder: &mut T) -> Item_ { match i { + ItemExternCrate(string) => ItemExternCrate(string), + ItemUse(view_path) => { + ItemUse(folder.fold_view_path(view_path)) + } ItemStatic(t, m, e) => { ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e)) } @@ -1103,10 +1079,9 @@ pub fn noop_fold_type_method<T: Folder>(m: TypeMethod, fld: &mut T) -> TypeMetho } } -pub fn noop_fold_mod<T: Folder>(Mod {inner, view_items, items}: Mod, folder: &mut T) -> Mod { +pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod { Mod { inner: folder.new_span(inner), - view_items: view_items.move_map(|x| folder.fold_view_item(x)), items: items.into_iter().flat_map(|x| folder.fold_item(x).into_iter()).collect(), } } @@ -1137,9 +1112,8 @@ pub fn noop_fold_crate<T: Folder>(Crate {module, attrs, config, mut exported_mac } None => (ast::Mod { inner: span, - view_items: Vec::new(), - items: Vec::new(), - }, Vec::new(), span) + items: vec![], + }, vec![], span) }; for def in exported_macros.iter_mut() { @@ -1371,7 +1345,7 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span}: Expr, folder: &mut T) -> } ExprTupField(el, ident) => { ExprTupField(folder.fold_expr(el), - respan(ident.span, folder.fold_uint(ident.node))) + respan(ident.span, folder.fold_usize(ident.node))) } ExprIndex(el, er) => { ExprIndex(folder.fold_expr(el), folder.fold_expr(er)) diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 707e540a17b..872354024e9 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -22,7 +22,7 @@ pub struct OwnedSlice<T> { data: Box<[T]> } -impl<T:fmt::Show> fmt::Show for OwnedSlice<T> { +impl<T:fmt::Debug> fmt::Debug for OwnedSlice<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.data.fmt(fmt) } diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 16ade904be8..c58136b30aa 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -22,7 +22,7 @@ use print::pprust; use std::io; use std::str; use std::string::String; -use std::uint; +use std::usize; #[derive(Clone, Copy, PartialEq)] pub enum CommentStyle { @@ -62,7 +62,7 @@ pub fn doc_comment_style(comment: &str) -> ast::AttrStyle { pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove whitespace-only lines from the start/end of lines fn vertical_trim(lines: Vec<String> ) -> Vec<String> { - let mut i = 0u; + let mut i = 0us; let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && @@ -87,7 +87,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { /// remove a "[ \t]*\*" block from each line, if possible fn horizontal_trim(lines: Vec<String> ) -> Vec<String> { - let mut i = uint::MAX; + let mut i = usize::MAX; let mut can_trim = true; let mut first = true; for line in lines.iter() { @@ -116,7 +116,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { if can_trim { lines.iter().map(|line| { - (&line[(i + 1)..line.len()]).to_string() + (&line[i + 1..line.len()]).to_string() }).collect() } else { lines @@ -132,7 +132,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { } if comment.starts_with("/*") { - let lines = comment[3u..(comment.len() - 2u)] + let lines = comment[3..comment.len() - 2] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); @@ -158,7 +158,7 @@ fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) { fn consume_whitespace_counting_blank_lines(rdr: &mut StringReader, comments: &mut Vec<Comment>) { while is_whitespace(rdr.curr) && !rdr.is_eof() { - if rdr.col == CharPos(0u) && rdr.curr_is('\n') { + if rdr.col == CharPos(0us) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); @@ -206,10 +206,10 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, /// Returns None if the first col chars of s contain a non-whitespace char. /// Otherwise returns Some(k) where k is first char offset after that leading /// whitespace. Note k may be outside bounds of s. -fn all_whitespace(s: &str, col: CharPos) -> Option<uint> { +fn all_whitespace(s: &str, col: CharPos) -> Option<usize> { let len = s.len(); - let mut col = col.to_uint(); - let mut cursor: uint = 0; + let mut col = col.to_usize(); + let mut cursor: usize = 0; while col > 0 && cursor < len { let r: str::CharRange = s.char_range_at(cursor); if !r.ch.is_whitespace() { @@ -267,7 +267,7 @@ fn read_block_comment(rdr: &mut StringReader, assert!(!curr_line.contains_char('\n')); lines.push(curr_line); } else { - let mut level: int = 1; + let mut level: isize = 1; while level > 0 { debug!("=== block comment level {}", level); if rdr.is_eof() { @@ -305,7 +305,7 @@ fn read_block_comment(rdr: &mut StringReader, let mut style = if code_to_the_left { Trailing } else { Isolated }; rdr.consume_non_eol_whitespace(); - if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1u { + if !rdr.is_eof() && !rdr.curr_is('\n') && lines.len() == 1us { style = Mixed; } debug!("<<< block comment"); @@ -399,9 +399,9 @@ mod test { } #[test] fn test_block_doc_comment_3() { - let comment = "/**\n let a: *int;\n *a = 5;\n*/"; + let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); - assert_eq!(stripped, " let a: *int;\n *a = 5;"); + assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 4cdafb36eec..3b9dcf53009 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -212,8 +212,8 @@ impl<'a> StringReader<'a> { /// offending string to the error message fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! { m.push_str(": "); - let from = self.byte_offset(from_pos).to_uint(); - let to = self.byte_offset(to_pos).to_uint(); + let from = self.byte_offset(from_pos).to_usize(); + let to = self.byte_offset(to_pos).to_usize(); m.push_str(&self.filemap.src[from..to]); self.fatal_span_(from_pos, to_pos, &m[]); } @@ -271,15 +271,15 @@ impl<'a> StringReader<'a> { fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where F: FnOnce(&str) -> T, { - f(self.filemap.src.slice( - self.byte_offset(start).to_uint(), - self.byte_offset(end).to_uint())) + f(&self.filemap.src[ + self.byte_offset(start).to_usize().. + self.byte_offset(end).to_usize()]) } /// Converts CRLF to LF in the given string, raising an error on bare CR. fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> CowString<'b> { - let mut i = 0u; + let mut i = 0us; while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { @@ -295,7 +295,7 @@ impl<'a> StringReader<'a> { return s.into_cow(); fn translate_crlf_(rdr: &StringReader, start: BytePos, - s: &str, errmsg: &str, mut i: uint) -> String { + s: &str, errmsg: &str, mut i: usize) -> String { let mut buf = String::with_capacity(s.len()); let mut j = 0; while i < s.len() { @@ -321,7 +321,7 @@ impl<'a> StringReader<'a> { /// discovered, add it to the FileMap's list of line start offsets. pub fn bump(&mut self) { self.last_pos = self.pos; - let current_byte_offset = self.byte_offset(self.pos).to_uint(); + let current_byte_offset = self.byte_offset(self.pos).to_usize(); if current_byte_offset < self.filemap.src.len() { assert!(self.curr.is_some()); let last_char = self.curr.unwrap(); @@ -329,12 +329,12 @@ impl<'a> StringReader<'a> { .src .char_range_at(current_byte_offset); let byte_offset_diff = next.next - current_byte_offset; - self.pos = self.pos + Pos::from_uint(byte_offset_diff); + self.pos = self.pos + Pos::from_usize(byte_offset_diff); self.curr = Some(next.ch); - self.col = self.col + CharPos(1u); + self.col = self.col + CharPos(1us); if last_char == '\n' { self.filemap.next_line(self.last_pos); - self.col = CharPos(0u); + self.col = CharPos(0us); } if byte_offset_diff > 1 { @@ -346,7 +346,7 @@ impl<'a> StringReader<'a> { } pub fn nextch(&self) -> Option<char> { - let offset = self.byte_offset(self.pos).to_uint(); + let offset = self.byte_offset(self.pos).to_usize(); if offset < self.filemap.src.len() { Some(self.filemap.src.char_at(offset)) } else { @@ -359,7 +359,7 @@ impl<'a> StringReader<'a> { } pub fn nextnextch(&self) -> Option<char> { - let offset = self.byte_offset(self.pos).to_uint(); + let offset = self.byte_offset(self.pos).to_usize(); let s = self.filemap.src.as_slice(); if offset >= s.len() { return None } let str::CharRange { next, .. } = s.char_range_at(offset); @@ -472,7 +472,7 @@ impl<'a> StringReader<'a> { cmap.files.borrow_mut().push(self.filemap.clone()); let loc = cmap.lookup_char_pos_adj(self.last_pos); debug!("Skipping a shebang"); - if loc.line == 1u && loc.col == CharPos(0u) { + if loc.line == 1us && loc.col == CharPos(0us) { // FIXME: Add shebang "token", return it let start = self.last_pos; while !self.curr_is('\n') && !self.is_eof() { self.bump(); } @@ -519,7 +519,7 @@ impl<'a> StringReader<'a> { let is_doc_comment = self.curr_is('*') || self.curr_is('!'); let start_bpos = self.last_pos - BytePos(2); - let mut level: int = 1; + let mut level: isize = 1; let mut has_cr = false; while level > 0 { if self.is_eof() { @@ -586,10 +586,10 @@ impl<'a> StringReader<'a> { /// `\x00` marker. #[inline(never)] fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident { - fn bump_expecting_char<'a,D:fmt::Show>(r: &mut StringReader<'a>, - c: char, - described_c: D, - whence: &str) { + fn bump_expecting_char<'a,D:fmt::Debug>(r: &mut StringReader<'a>, + c: char, + described_c: D, + whence: &str) { match r.curr { Some(r_c) if r_c == c => r.bump(), Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence), @@ -645,8 +645,8 @@ impl<'a> StringReader<'a> { /// Scan through any digits (base `radix`) or underscores, and return how /// many digits there were. - fn scan_digits(&mut self, radix: uint) -> uint { - let mut len = 0u; + fn scan_digits(&mut self, radix: usize) -> usize { + let mut len = 0us; loop { let c = self.curr; if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } @@ -724,7 +724,7 @@ impl<'a> StringReader<'a> { /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an /// error if too many or too few digits are encountered. fn scan_hex_digits(&mut self, - n_digits: uint, + n_digits: usize, delim: char, below_0x7f_only: bool) -> bool { @@ -799,14 +799,14 @@ impl<'a> StringReader<'a> { if self.curr == Some('{') { self.scan_unicode_escape(delim) } else { - let res = self.scan_hex_digits(4u, delim, false); + let res = self.scan_hex_digits(4us, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res } } 'U' if !ascii_only => { - let res = self.scan_hex_digits(8u, delim, false); + let res = self.scan_hex_digits(8us, delim, false); let sp = codemap::mk_sp(escaped_pos, self.last_pos); self.old_escape_warning(sp); res @@ -877,7 +877,7 @@ impl<'a> StringReader<'a> { fn scan_unicode_escape(&mut self, delim: char) -> bool { self.bump(); // past the { let start_bpos = self.last_pos; - let mut count: uint = 0; + let mut count = 0us; let mut accum_int = 0; while !self.curr_is('}') && count <= 6 { @@ -935,13 +935,13 @@ impl<'a> StringReader<'a> { /// Check that a base is valid for a floating literal, emitting a nice /// error if it isn't. - fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: uint) { + fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { match base { - 16u => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ - supported"), - 8u => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), - 2u => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), - _ => () + 16us => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \ + supported"), + 8us => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"), + 2us => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"), + _ => () } } @@ -1189,7 +1189,7 @@ impl<'a> StringReader<'a> { 'r' => { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0u; + let mut hash_count = 0us; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1374,7 +1374,7 @@ impl<'a> StringReader<'a> { fn scan_raw_byte_string(&mut self) -> token::Lit { let start_bpos = self.last_pos; self.bump(); - let mut hash_count = 0u; + let mut hash_count = 0us; while self.curr_is('#') { self.bump(); hash_count += 1; @@ -1616,9 +1616,9 @@ mod test { test!("1.0", Float, "1.0"); test!("1.0e10", Float, "1.0e10"); - assert_eq!(setup(&mk_sh(), "2u".to_string()).next_token().tok, + assert_eq!(setup(&mk_sh(), "2us".to_string()).next_token().tok, token::Literal(token::Integer(token::intern("2")), - Some(token::intern("u")))); + Some(token::intern("us")))); assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok, token::Literal(token::StrRaw(token::intern("raw"), 3), Some(token::intern("suffix")))); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index dd376fe9e10..8cb7ee5b337 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -181,7 +181,7 @@ pub fn parse_tts_from_source_str(name: String, name, source ); - p.quote_depth += 1u; + p.quote_depth += 1us; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -324,7 +324,7 @@ pub mod with_hygiene { name, source ); - p.quote_depth += 1u; + p.quote_depth += 1us; // right now this is re-creating the token trees from ... token trees. maybe_aborted(p.parse_all_token_trees(),p) } @@ -364,7 +364,7 @@ pub mod with_hygiene { } /// Abort if necessary -pub fn maybe_aborted<T>(result: T, mut p: Parser) -> T { +pub fn maybe_aborted<T>(result: T, p: Parser) -> T { p.abort_if_errors(); result } @@ -373,7 +373,7 @@ pub fn maybe_aborted<T>(result: T, mut p: Parser) -> T { /// Rather than just accepting/rejecting a given literal, unescapes it as /// well. Can take any slice prefixed by a character escape. Returns the /// character and the number of characters consumed. -pub fn char_lit(lit: &str) -> (char, int) { +pub fn char_lit(lit: &str) -> (char, isize) { use std::{num, char}; let mut chars = lit.chars(); @@ -400,19 +400,19 @@ pub fn char_lit(lit: &str) -> (char, int) { let msg = format!("lexer should have rejected a bad character escape {}", lit); let msg2 = &msg[]; - fn esc(len: uint, lit: &str) -> Option<(char, int)> { + fn esc(len: usize, lit: &str) -> Option<(char, isize)> { num::from_str_radix(&lit[2..len], 16) .and_then(char::from_u32) - .map(|x| (x, len as int)) + .map(|x| (x, len as isize)) } - let unicode_escape = |&: | -> Option<(char, int)> + let unicode_escape = |&: | -> Option<(char, isize)> if lit.as_bytes()[2] == b'{' { let idx = lit.find('}').expect(msg2); let subslice = &lit[3..idx]; num::from_str_radix(subslice, 16) .and_then(char::from_u32) - .map(|x| (x, subslice.chars().count() as int + 4)) + .map(|x| (x, subslice.chars().count() as isize + 4)) } else { esc(6, lit) }; @@ -436,7 +436,7 @@ pub fn str_lit(lit: &str) -> String { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a>(it: &mut iter::Peekable<(uint, char), str::CharIndices<'a>>) { + fn eat<'a>(it: &mut iter::Peekable<(usize, char), str::CharIndices<'a>>) { loop { match it.peek().map(|x| x.1) { Some(' ') | Some('\n') | Some('\r') | Some('\t') => { @@ -567,13 +567,13 @@ pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> a } /// Parse a string representing a byte literal into its final form. Similar to `char_lit` -pub fn byte_lit(lit: &str) -> (u8, uint) { +pub fn byte_lit(lit: &str) -> (u8, usize) { let err = |&: i| format!("lexer accepted invalid byte literal {} step {}", lit, i); if lit.len() == 1 { (lit.as_bytes()[0], 1) } else { - assert!(lit.as_bytes()[0] == b'\\', err(0i)); + assert!(lit.as_bytes()[0] == b'\\', err(0is)); let b = match lit.as_bytes()[1] { b'"' => b'"', b'n' => b'\n', @@ -605,7 +605,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { let error = |&: i| format!("lexer should have rejected {} at {}", lit, i); /// Eat everything up to a non-whitespace - fn eat<'a, I: Iterator<Item=(uint, u8)>>(it: &mut iter::Peekable<(uint, u8), I>) { + fn eat<'a, I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<(usize, u8), I>) { loop { match it.peek().map(|x| x.1) { Some(b' ') | Some(b'\n') | Some(b'\r') | Some(b'\t') => { @@ -683,9 +683,9 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> match suffix { Some(suf) if looks_like_width_suffix(&['f'], suf) => { match base { - 16u => sd.span_err(sp, "hexadecimal float literal is not supported"), - 8u => sd.span_err(sp, "octal float literal is not supported"), - 2u => sd.span_err(sp, "binary float literal is not supported"), + 16us => sd.span_err(sp, "hexadecimal float literal is not supported"), + 8us => sd.span_err(sp, "octal float literal is not supported"), + 2us => sd.span_err(sp, "binary float literal is not supported"), _ => () } let ident = token::intern_and_get_ident(&*s); @@ -757,11 +757,10 @@ mod test { use attr::{first_attr_value_str_by_name, AttrMetaMethods}; use parse::parser::Parser; use parse::token::{str_to_ident}; - use print::pprust::view_item_to_string; + use print::pprust::item_to_string; use ptr::P; use util::parser_testing::{string_to_tts, string_to_parser}; - use util::parser_testing::{string_to_expr, string_to_item}; - use util::parser_testing::{string_to_stmt, string_to_view_item}; + use util::parser_testing::{string_to_expr, string_to_item, string_to_stmt}; // produce a codemap::span fn sp(a: u32, b: u32) -> Span { @@ -854,7 +853,7 @@ mod test { #[test] fn string_to_tts_1 () { - let tts = string_to_tts("fn a (b : int) { b; }".to_string()); + let tts = string_to_tts("fn a (b : i32) { b; }".to_string()); assert_eq!(json::encode(&tts), "[\ {\ @@ -918,7 +917,7 @@ mod test { {\ \"variant\":\"Ident\",\ \"fields\":[\ - \"int\",\ + \"i32\",\ \"Plain\"\ ]\ }\ @@ -1030,8 +1029,8 @@ mod test { // check the contents of the tt manually: #[test] fn parse_fundecl () { - // this test depends on the intern order of "fn" and "int" - assert!(string_to_item("fn a (b : int) { b; }".to_string()) == + // this test depends on the intern order of "fn" and "i32" + assert_eq!(string_to_item("fn a (b : i32) { b; }".to_string()), Some( P(ast::Item{ident:str_to_ident("a"), attrs:Vec::new(), @@ -1045,7 +1044,7 @@ mod test { segments: vec!( ast::PathSegment { identifier: - str_to_ident("int"), + str_to_ident("i32"), parameters: ast::PathParameters::none(), } ), @@ -1079,7 +1078,6 @@ mod test { } }, P(ast::Block { - view_items: Vec::new(), stmts: vec!(P(Spanned{ node: ast::StmtSemi(P(ast::Expr{ id: ast::DUMMY_NODE_ID, @@ -1111,25 +1109,25 @@ mod test { #[test] fn parse_use() { let use_s = "use foo::bar::baz;"; - let vitem = string_to_view_item(use_s.to_string()); - let vitem_s = view_item_to_string(&vitem); + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&*vitem); assert_eq!(&vitem_s[], use_s); let use_s = "use foo::bar as baz;"; - let vitem = string_to_view_item(use_s.to_string()); - let vitem_s = view_item_to_string(&vitem); + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&*vitem); assert_eq!(&vitem_s[], use_s); } #[test] fn parse_extern_crate() { let ex_s = "extern crate foo;"; - let vitem = string_to_view_item(ex_s.to_string()); - let vitem_s = view_item_to_string(&vitem); + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&*vitem); assert_eq!(&vitem_s[], ex_s); let ex_s = "extern crate \"foo\" as bar;"; - let vitem = string_to_view_item(ex_s.to_string()); - let vitem_s = view_item_to_string(&vitem); + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&*vitem); assert_eq!(&vitem_s[], ex_s); } @@ -1158,19 +1156,19 @@ mod test { #[test] fn span_of_self_arg_pat_idents_are_correct() { - let srcs = ["impl z { fn a (&self, &myarg: int) {} }", - "impl z { fn a (&mut self, &myarg: int) {} }", - "impl z { fn a (&'a self, &myarg: int) {} }", - "impl z { fn a (self, &myarg: int) {} }", - "impl z { fn a (self: Foo, &myarg: int) {} }", + let srcs = ["impl z { fn a (&self, &myarg: i32) {} }", + "impl z { fn a (&mut self, &myarg: i32) {} }", + "impl z { fn a (&'a self, &myarg: i32) {} }", + "impl z { fn a (self, &myarg: i32) {} }", + "impl z { fn a (self: Foo, &myarg: i32) {} }", ]; for &src in srcs.iter() { let spans = get_spans_of_pat_idents(src); let Span{ lo, hi, .. } = spans[0]; - assert!("self" == &src[lo.to_uint()..hi.to_uint()], + assert!("self" == &src[lo.to_usize()..hi.to_usize()], "\"{}\" != \"self\". src=\"{}\"", - &src[lo.to_uint()..hi.to_uint()], src) + &src[lo.to_usize()..hi.to_usize()], src) } } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 9d03ec73af8..a3600506057 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -62,7 +62,7 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { "use a `move ||` expression instead", ), ObsoleteSyntax::ClosureType => ( - "`|uint| -> bool` closure type syntax", + "`|usize| -> bool` closure type syntax", "use unboxed closures instead, no type annotation needed" ), ObsoleteSyntax::Sized => ( diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 83a7504bc49..e59dbe52b76 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -9,7 +9,6 @@ // except according to those terms. pub use self::PathParsingMode::*; -use self::ItemOrViewItem::*; use abi; use ast::{AssociatedType, BareFnTy}; @@ -35,6 +34,7 @@ use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRet use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic}; use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst}; use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy}; +use ast::{ItemExternCrate, ItemUse}; use ast::{LifetimeDef, Lit, Lit_}; use ast::{LitBool, LitChar, LitByte, LitBinary}; use ast::{LitStr, LitInt, Local, LocalLet}; @@ -59,11 +59,10 @@ use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq}; use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind}; use ast::{UnnamedField, UnsafeBlock}; -use ast::{ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse}; use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; use ast::{Visibility, WhereClause}; use ast; -use ast_util::{self, as_prec, ident_to_path, operator_prec}; +use ast_util::{self, AS_PREC, ident_to_path, operator_prec}; use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp}; use diagnostic; use ext::tt::macro_parser; @@ -94,7 +93,6 @@ bitflags! { const RESTRICTION_STMT_EXPR = 0b0001, const RESTRICTION_NO_BAR_OP = 0b0010, const RESTRICTION_NO_STRUCT_LITERAL = 0b0100, - const RESTRICTION_NO_DOTS = 0b1000, } } @@ -122,14 +120,9 @@ pub enum BoundParsingMode { Modified, } -enum ItemOrViewItem { - /// Indicates a failure to parse any kind of item. The attributes are - /// returned. - IoviNone(Vec<Attribute>), - IoviItem(P<Item>), - IoviForeignItem(P<ForeignItem>), - IoviViewItem(ViewItem) -} +/// The `Err` case indicates a failure to parse any kind of item. +/// The attributes are returned. +type MaybeItem = Result<P<Item>, Vec<Attribute>>; /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression @@ -231,19 +224,6 @@ macro_rules! maybe_whole { } } ); - (iovi $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 IoviItem(x.clone()); - } - } - ); (pair_empty $p:expr, $constructor:ident) => ( { let found = match ($p).token { @@ -269,14 +249,6 @@ fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>) lhs } - -struct ParsedItemsAndViewItems { - attrs_remaining: Vec<Attribute>, - view_items: Vec<ViewItem>, - items: Vec<P<Item>> , - foreign_items: Vec<P<ForeignItem>> -} - /* ident is handled by common.rs */ pub struct Parser<'a> { @@ -291,11 +263,11 @@ pub struct Parser<'a> { /// the previous token or None (only stashed sometimes). pub last_token: Option<Box<token::Token>>, pub buffer: [TokenAndSpan; 4], - pub buffer_start: int, - pub buffer_end: int, - pub tokens_consumed: uint, + pub buffer_start: isize, + pub buffer_end: isize, + pub tokens_consumed: usize, pub restrictions: Restrictions, - pub quote_depth: uint, // not (yet) related to the quasiquoter + pub quote_depth: usize, // not (yet) related to the quasiquoter pub reader: Box<Reader+'a>, pub interner: Rc<token::IdentInterner>, /// The set of seen errors about obsolete syntax. Used to suppress @@ -382,18 +354,18 @@ impl<'a> Parser<'a> { } /// Convert the current token to a string using self's reader - pub fn this_token_to_string(&mut self) -> String { + pub fn this_token_to_string(&self) -> String { Parser::token_to_string(&self.token) } - pub fn unexpected_last(&mut self, t: &token::Token) -> ! { + pub fn unexpected_last(&self, t: &token::Token) -> ! { let token_str = Parser::token_to_string(t); let last_span = self.last_span; self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)[]); } - pub fn unexpected(&mut self) -> ! { + pub fn unexpected(&self) -> ! { let this_token = self.this_token_to_string(); self.fatal(&format!("unexpected token: `{}`", this_token)[]); } @@ -660,7 +632,7 @@ impl<'a> Parser<'a> { } } - pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) { + pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) { match suffix { None => {/* everything ok */} Some(suf) => { @@ -768,7 +740,7 @@ impl<'a> Parser<'a> { // would encounter a `>` and stop. This lets the parser handle trailing // commas in generic parameters, because it can stop either after // parsing a type or after parsing a comma. - for i in iter::count(0u, 1) { + for i in iter::count(0us, 1) { if self.check(&token::Gt) || self.token == token::BinOp(token::Shr) || self.token == token::Ge @@ -933,9 +905,9 @@ impl<'a> Parser<'a> { self.reader.real_token() } else { // Avoid token copies with `replace`. - let buffer_start = self.buffer_start as uint; - let next_index = (buffer_start + 1) & 3 as uint; - self.buffer_start = next_index as int; + let buffer_start = self.buffer_start as usize; + let next_index = (buffer_start + 1) & 3 as usize; + self.buffer_start = next_index as isize; let placeholder = TokenAndSpan { tok: token::Underscore, @@ -945,7 +917,7 @@ impl<'a> Parser<'a> { }; self.span = next.sp; self.token = next.tok; - self.tokens_consumed += 1u; + self.tokens_consumed += 1us; self.expected_tokens.clear(); // check after each token self.check_unknown_macro_variable(); @@ -967,55 +939,55 @@ impl<'a> Parser<'a> { self.token = next; self.span = mk_sp(lo, hi); } - pub fn buffer_length(&mut self) -> int { + pub fn buffer_length(&mut self) -> isize { if self.buffer_start <= self.buffer_end { return self.buffer_end - self.buffer_start; } return (4 - self.buffer_start) + self.buffer_end; } - pub fn look_ahead<R, F>(&mut self, distance: uint, f: F) -> R where + pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where F: FnOnce(&token::Token) -> R, { - let dist = distance as int; + let dist = distance as isize; while self.buffer_length() < dist { - self.buffer[self.buffer_end as uint] = self.reader.real_token(); + self.buffer[self.buffer_end as usize] = self.reader.real_token(); self.buffer_end = (self.buffer_end + 1) & 3; } - f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok) + f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok) } - pub fn fatal(&mut self, m: &str) -> ! { + pub fn fatal(&self, m: &str) -> ! { self.sess.span_diagnostic.span_fatal(self.span, m) } - pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! { + pub fn span_fatal(&self, sp: Span, m: &str) -> ! { self.sess.span_diagnostic.span_fatal(sp, m) } - pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! { + pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> ! { self.span_err(sp, m); self.span_help(sp, help); panic!(diagnostic::FatalError); } - pub fn span_note(&mut self, sp: Span, m: &str) { + pub fn span_note(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_note(sp, m) } - pub fn span_help(&mut self, sp: Span, m: &str) { + pub fn span_help(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_help(sp, m) } - pub fn bug(&mut self, m: &str) -> ! { + pub fn bug(&self, m: &str) -> ! { self.sess.span_diagnostic.span_bug(self.span, m) } - pub fn warn(&mut self, m: &str) { + pub fn warn(&self, m: &str) { self.sess.span_diagnostic.span_warn(self.span, m) } - pub fn span_warn(&mut self, sp: Span, m: &str) { + pub fn span_warn(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_warn(sp, m) } - pub fn span_err(&mut self, sp: Span, m: &str) { + pub fn span_err(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_err(sp, m) } - pub fn span_bug(&mut self, sp: Span, m: &str) -> ! { + pub fn span_bug(&self, sp: Span, m: &str) -> ! { self.sess.span_diagnostic.span_bug(sp, m) } - pub fn abort_if_errors(&mut self) { + pub fn abort_if_errors(&self) { self.sess.span_diagnostic.handler().abort_if_errors(); } @@ -1496,7 +1468,7 @@ impl<'a> Parser<'a> { self.expect(&token::OpenDelim(token::Bracket)); let t = self.parse_ty_sum(); - // Parse the `; e` in `[ int; e ]` + // Parse the `; e` in `[ i32; e ]` // where `e` is a const expression let t = match self.maybe_parse_fixed_length_of_vec() { None => TyVec(t), @@ -1670,7 +1642,7 @@ impl<'a> Parser<'a> { } /// Matches token_lit = LIT_INTEGER | ... - pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ { + pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ { match *tok { token::Interpolated(token::NtExpr(ref v)) => { match v.node { @@ -2084,7 +2056,7 @@ impl<'a> Parser<'a> { ExprField(expr, ident) } - pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ { + pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ { ExprTupField(expr, idx) } @@ -2483,7 +2455,7 @@ impl<'a> Parser<'a> { hi = self.span.hi; self.bump(); - let index = n.as_str().parse::<uint>(); + let index = n.as_str().parse::<usize>(); match index { Some(n) => { let id = spanned(dot, hi, n); @@ -2509,7 +2481,7 @@ impl<'a> Parser<'a> { }; self.span_help(last_span, &format!("try parenthesizing the first index; e.g., `(foo.{}){}`", - float.trunc() as uint, + float.trunc() as usize, &float.fract().to_string()[1..])[]); } self.abort_if_errors(); @@ -2636,7 +2608,7 @@ impl<'a> Parser<'a> { } pub fn check_unknown_macro_variable(&mut self) { - if self.quote_depth == 0u { + if self.quote_depth == 0us { match self.token { token::SubstNt(name, _) => self.fatal(&format!("unknown macro variable `{}`", @@ -2705,7 +2677,7 @@ impl<'a> Parser<'a> { token_str)[]) }, /* we ought to allow different depths of unquotation */ - token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => { + token::Dollar | token::SubstNt(..) if p.quote_depth > 0us => { p.parse_unquoted() } _ => { @@ -2802,13 +2774,6 @@ impl<'a> Parser<'a> { hi = e.span.hi; ex = ExprAddrOf(m, e); } - token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { - // A range, closed above: `..expr`. - self.bump(); - let e = self.parse_expr(); - hi = e.span.hi; - ex = self.mk_range(None, Some(e)); - } token::Ident(_, _) => { if !self.token.is_keyword(keywords::Box) { return self.parse_dot_or_call_expr(); @@ -2863,7 +2828,7 @@ impl<'a> Parser<'a> { } /// Parse an expression of binops of at least min_prec precedence - pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> { + pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> { if self.expr_is_complete(&*lhs) { return lhs; } // Prevent dynamic borrow errors later on by limiting the @@ -2882,10 +2847,10 @@ impl<'a> Parser<'a> { self.check_no_chained_comparison(&*lhs, cur_op) } let cur_prec = operator_prec(cur_op); - if cur_prec > min_prec { + if cur_prec >= min_prec { self.bump(); let expr = self.parse_prefix_expr(); - let rhs = self.parse_more_binops(expr, cur_prec); + let rhs = self.parse_more_binops(expr, cur_prec + 1); let lhs_span = lhs.span; let rhs_span = rhs.span; let binary = self.mk_binary(cur_op, lhs, rhs); @@ -2896,7 +2861,7 @@ impl<'a> Parser<'a> { } } None => { - if as_prec > min_prec && self.eat_keyword(keywords::As) { + if AS_PREC >= min_prec && self.eat_keyword(keywords::As) { let rhs = self.parse_ty(); let _as = self.mk_expr(lhs.span.lo, rhs.span.hi, @@ -2921,7 +2886,7 @@ impl<'a> Parser<'a> { "Chained comparison operators require parentheses"); if op == BiLt && outer_op == BiGt { self.span_help(op_span, - "Use ::< instead of < if you meant to specify type arguments."); + "use ::< instead of < if you meant to specify type arguments"); } } _ => {} @@ -2932,8 +2897,24 @@ impl<'a> Parser<'a> { /// actually, this seems to be the main entry point for /// parsing an arbitrary expression. pub fn parse_assign_expr(&mut self) -> P<Expr> { - let lhs = self.parse_binops(); - self.parse_assign_expr_with(lhs) + match self.token { + token::DotDot => { + // prefix-form of range notation '..expr' + // This has the same precedence as assignment expressions + // (much lower than other prefix expressions) to be consistent + // with the postfix-form 'expr..' + let lo = self.span.lo; + self.bump(); + let rhs = self.parse_binops(); + let hi = rhs.span.hi; + let ex = self.mk_range(None, Some(rhs)); + self.mk_expr(lo, hi, ex) + } + _ => { + let lhs = self.parse_binops(); + self.parse_assign_expr_with(lhs) + } + } } pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> { @@ -2965,11 +2946,11 @@ impl<'a> Parser<'a> { self.mk_expr(span.lo, rhs_span.hi, assign_op) } // A range expression, either `expr..expr` or `expr..`. - token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { + token::DotDot => { self.bump(); - let opt_end = if self.token.can_begin_expr() { - let end = self.parse_expr_res(RESTRICTION_NO_DOTS); + let opt_end = if self.is_at_start_of_range_notation_rhs() { + let end = self.parse_binops(); Some(end) } else { None @@ -2987,6 +2968,18 @@ impl<'a> Parser<'a> { } } + fn is_at_start_of_range_notation_rhs(&self) -> bool { + if self.token.can_begin_expr() { + // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. + if self.token == token::OpenDelim(token::Brace) { + return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL); + } + true + } else { + false + } + } + /// Parse an 'if' or 'if let' expression ('if' token already eaten) pub fn parse_if_expr(&mut self) -> P<Expr> { if self.token.is_keyword(keywords::Let) { @@ -3032,8 +3025,7 @@ impl<'a> Parser<'a> { let body = self.parse_expr(); let fakeblock = P(ast::Block { id: ast::DUMMY_NODE_ID, - view_items: Vec::new(), - stmts: Vec::new(), + stmts: vec![], span: body.span, expr: Some(body), rules: DefaultBlock, @@ -3731,20 +3723,13 @@ impl<'a> Parser<'a> { } else { let found_attrs = !item_attrs.is_empty(); let item_err = Parser::expected_item_err(&item_attrs[]); - match self.parse_item_or_view_item(item_attrs, false) { - IoviItem(i) => { + match self.parse_item_(item_attrs, false) { + Ok(i) => { let hi = i.span.hi; let decl = P(spanned(lo, hi, DeclItem(i))); P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) } - IoviViewItem(vi) => { - self.span_fatal(vi.span, - "view items must be declared at the top of the block"); - } - IoviForeignItem(_) => { - self.fatal("foreign items are not allowed here"); - } - IoviNone(_) => { + Err(_) => { if found_attrs { let last_span = self.last_span; self.span_err(last_span, item_err); @@ -3794,36 +3779,17 @@ impl<'a> Parser<'a> { (inner, self.parse_block_tail_(lo, DefaultBlock, next)) } - /// Precondition: already parsed the '{' or '#{' - /// I guess that also means "already parsed the 'impure'" if - /// necessary, and this should take a qualifier. - /// Some blocks start with "#{"... + /// Precondition: already parsed the '{'. fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> { self.parse_block_tail_(lo, s, Vec::new()) } /// Parse the rest of a block expression or function body fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode, - first_item_attrs: Vec<Attribute> ) -> P<Block> { - let mut stmts = Vec::new(); + first_item_attrs: Vec<Attribute>) -> P<Block> { + let mut stmts = vec![]; let mut expr = None; - - // wouldn't it be more uniform to parse view items only, here? - let ParsedItemsAndViewItems { - attrs_remaining, - view_items, - items, - .. - } = self.parse_items_and_view_items(first_item_attrs, - false, false); - - for item in items.into_iter() { - let span = item.span; - let decl = P(spanned(span.lo, span.hi, DeclItem(item))); - stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))); - } - - let mut attributes_box = attrs_remaining; + let mut attributes_box = first_item_attrs; while self.token != token::CloseDelim(token::Brace) { // parsing items even when they're not allowed lets us give @@ -3932,7 +3898,6 @@ impl<'a> Parser<'a> { let hi = self.span.hi; self.bump(); P(ast::Block { - view_items: view_items, stmts: stmts, expr: expr, id: ast::DUMMY_NODE_ID, @@ -4795,7 +4760,7 @@ impl<'a> Parser<'a> { Some(attrs)) } - /// Parse a::B<String,int> + /// Parse a::B<String,i32> fn parse_trait_ref(&mut self) -> TraitRef { ast::TraitRef { path: self.parse_path(LifetimeAndTypesWithoutColons), @@ -4814,7 +4779,7 @@ impl<'a> Parser<'a> { } } - /// Parse for<'l> a::B<String,int> + /// Parse for<'l> a::B<String,i32> fn parse_poly_trait_ref(&mut self) -> PolyTraitRef { let lifetime_defs = self.parse_late_bound_lifetime_defs(); @@ -5031,39 +4996,34 @@ impl<'a> Parser<'a> { first_item_attrs: Vec<Attribute>, inner_lo: BytePos) -> Mod { - // parse all of the items up to closing or an attribute. - // view items are legal here. - let ParsedItemsAndViewItems { - attrs_remaining, - view_items, - items: starting_items, - .. - } = self.parse_items_and_view_items(first_item_attrs, true, true); - let mut items: Vec<P<Item>> = starting_items; - let attrs_remaining_len = attrs_remaining.len(); + // Parse all of the items up to closing or an attribute. + + let mut attrs = first_item_attrs; + attrs.push_all(&self.parse_outer_attributes()[]); + let mut items = vec![]; + + loop { + match self.parse_item_(attrs, true) { + Err(returned_attrs) => { + attrs = returned_attrs; + break + } + Ok(item) => { + attrs = self.parse_outer_attributes(); + items.push(item) + } + } + } // don't think this other loop is even necessary.... - let mut first = true; while self.token != term { - let mut attrs = self.parse_outer_attributes(); - if first { - let mut tmp = attrs_remaining.clone(); - tmp.push_all(&attrs[]); - attrs = tmp; - first = false; - } - debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})", - attrs); - match self.parse_item_or_view_item(attrs, - true /* macros allowed */) { - IoviItem(item) => items.push(item), - IoviViewItem(view_item) => { - self.span_fatal(view_item.span, - "view items must be declared at the top of \ - the module"); - } - _ => { + let mut attrs = mem::replace(&mut attrs, vec![]); + attrs.push_all(&self.parse_outer_attributes()[]); + debug!("parse_mod_items: parse_item_(attrs={:?})", attrs); + match self.parse_item_(attrs, true /* macros allowed */) { + Ok(item) => items.push(item), + Err(_) => { let token_str = self.this_token_to_string(); self.fatal(&format!("expected item, found `{}`", token_str)[]) @@ -5071,16 +5031,15 @@ impl<'a> Parser<'a> { } } - if first && attrs_remaining_len > 0u { + if !attrs.is_empty() { // We parsed attributes for the first item but didn't find it let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(&attrs_remaining[])); + Parser::expected_item_err(&attrs[])); } ast::Mod { inner: mk_sp(inner_lo, self.span.lo), - view_items: view_items, items: items } } @@ -5223,7 +5182,7 @@ impl<'a> Parser<'a> { Some(i) => { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); - for p in included_mod_stack.slice(i, len).iter() { + for p in included_mod_stack[i.. len].iter() { err.push_str(&p.display().as_cow()[]); err.push_str(" -> "); } @@ -5298,23 +5257,12 @@ impl<'a> Parser<'a> { /// parse_foreign_items. fn parse_foreign_mod_items(&mut self, abi: abi::Abi, - first_item_attrs: Vec<Attribute> ) + first_item_attrs: Vec<Attribute>) -> ForeignMod { - let ParsedItemsAndViewItems { - attrs_remaining, - view_items, - items: _, - foreign_items, - } = self.parse_foreign_items(first_item_attrs, true); - if !attrs_remaining.is_empty() { - let last_span = self.last_span; - self.span_err(last_span, - Parser::expected_item_err(&attrs_remaining[])); - } + let foreign_items = self.parse_foreign_items(first_item_attrs); assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { abi: abi, - view_items: view_items, items: foreign_items } } @@ -5329,8 +5277,8 @@ impl<'a> Parser<'a> { fn parse_item_extern_crate(&mut self, lo: BytePos, visibility: Visibility, - attrs: Vec<Attribute> ) - -> ItemOrViewItem { + attrs: Vec<Attribute>) + -> P<Item> { let span = self.span; let (maybe_path, ident) = match self.token { @@ -5374,12 +5322,13 @@ impl<'a> Parser<'a> { } }; - IoviViewItem(ast::ViewItem { - node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID), - attrs: attrs, - vis: visibility, - span: mk_sp(lo, self.last_span.hi) - }) + let last_span = self.last_span; + self.mk_item(lo, + last_span.hi, + ident, + ItemExternCrate(maybe_path), + visibility, + attrs) } /// Parse `extern` for foreign ABIs @@ -5396,8 +5345,8 @@ impl<'a> Parser<'a> { lo: BytePos, opt_abi: Option<abi::Abi>, visibility: Visibility, - attrs: Vec<Attribute> ) - -> ItemOrViewItem { + attrs: Vec<Attribute>) + -> P<Item> { self.expect(&token::OpenDelim(token::Brace)); @@ -5408,13 +5357,12 @@ impl<'a> Parser<'a> { self.expect(&token::CloseDelim(token::Brace)); let last_span = self.last_span; - let item = self.mk_item(lo, - last_span.hi, - special_idents::invalid, - ItemForeignMod(m), - visibility, - maybe_append(attrs, Some(inner))); - return IoviItem(item); + self.mk_item(lo, + last_span.hi, + special_idents::invalid, + ItemForeignMod(m), + visibility, + maybe_append(attrs, Some(inner))) } /// Parse type Foo = Bar; @@ -5556,14 +5504,12 @@ impl<'a> Parser<'a> { } } - /// Parse one of the items or view items allowed by the - /// flags; on failure, return IoviNone. + /// Parse one of the items allowed by the flags; on failure, + /// return `Err(remaining_attrs)`. /// NB: this function no longer parses the items inside an /// extern crate. - fn parse_item_or_view_item(&mut self, - attrs: Vec<Attribute> , - macros_allowed: bool) - -> ItemOrViewItem { + fn parse_item_(&mut self, attrs: Vec<Attribute>, + macros_allowed: bool) -> MaybeItem { let nt_item = match self.token { token::Interpolated(token::NtItem(ref item)) => { Some((**item).clone()) @@ -5576,7 +5522,7 @@ impl<'a> Parser<'a> { let mut attrs = attrs; mem::swap(&mut item.attrs, &mut attrs); item.attrs.extend(attrs.into_iter()); - return IoviItem(P(item)); + return Ok(P(item)); } None => {} } @@ -5585,22 +5531,24 @@ impl<'a> Parser<'a> { let visibility = self.parse_visibility(); - // must be a view item: if self.eat_keyword(keywords::Use) { - // USE ITEM (IoviViewItem) - let view_item = self.parse_use(); + // USE ITEM + let item_ = ItemUse(self.parse_view_path()); self.expect(&token::Semi); - return IoviViewItem(ast::ViewItem { - node: view_item, - attrs: attrs, - vis: visibility, - span: mk_sp(lo, self.last_span.hi) - }); + + let last_span = self.last_span; + let item = self.mk_item(lo, + last_span.hi, + token::special_idents::invalid, + item_, + visibility, + attrs); + return Ok(item); } - // either a view item or an item: + if self.eat_keyword(keywords::Extern) { if self.eat_keyword(keywords::Crate) { - return self.parse_item_extern_crate(lo, visibility, attrs); + return Ok(self.parse_item_extern_crate(lo, visibility, attrs)); } let opt_abi = self.parse_opt_abi(); @@ -5617,9 +5565,9 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } else if self.check(&token::OpenDelim(token::Brace)) { - return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs); + return Ok(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)); } let span = self.span; @@ -5634,7 +5582,6 @@ impl<'a> Parser<'a> { self.span_err(span, "`virtual` structs have been removed from the language"); } - // the rest are all guaranteed to be items: if self.token.is_keyword(keywords::Static) { // STATIC ITEM self.bump(); @@ -5647,7 +5594,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.token.is_keyword(keywords::Const) { // CONST ITEM @@ -5665,10 +5612,10 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1u, |t| t.is_keyword(keywords::Trait)) + self.look_ahead(1us, |t| t.is_keyword(keywords::Trait)) { // UNSAFE TRAIT ITEM self.expect_keyword(keywords::Unsafe); @@ -5682,10 +5629,10 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.token.is_keyword(keywords::Unsafe) && - self.look_ahead(1u, |t| t.is_keyword(keywords::Impl)) + self.look_ahead(1us, |t| t.is_keyword(keywords::Impl)) { // IMPL ITEM self.expect_keyword(keywords::Unsafe); @@ -5698,7 +5645,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.token.is_keyword(keywords::Fn) { // FUNCTION ITEM @@ -5712,10 +5659,10 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.token.is_keyword(keywords::Unsafe) - && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) { + && self.look_ahead(1us, |t| *t != token::OpenDelim(token::Brace)) { // UNSAFE FUNCTION ITEM self.bump(); let abi = if self.eat_keyword(keywords::Extern) { @@ -5733,7 +5680,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Mod) { // MODULE ITEM @@ -5746,7 +5693,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Type) { // TYPE ITEM @@ -5758,7 +5705,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Enum) { // ENUM ITEM @@ -5770,7 +5717,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Trait) { // TRAIT ITEM @@ -5783,7 +5730,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Impl) { // IMPL ITEM @@ -5795,7 +5742,7 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } if self.eat_keyword(keywords::Struct) { // STRUCT ITEM @@ -5807,32 +5754,30 @@ impl<'a> Parser<'a> { item_, visibility, maybe_append(attrs, extra_attrs)); - return IoviItem(item); + return Ok(item); } self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } - /// Parse a foreign item; on failure, return IoviNone. - fn parse_foreign_item(&mut self, - attrs: Vec<Attribute> , - macros_allowed: bool) - -> ItemOrViewItem { - maybe_whole!(iovi self, NtItem); + /// Parse a foreign item; on failure, return `Err(remaining_attrs)`. + fn parse_foreign_item(&mut self, attrs: Vec<Attribute>) + -> Result<P<ForeignItem>, Vec<Attribute>> { let lo = self.span.lo; let visibility = self.parse_visibility(); if self.token.is_keyword(keywords::Static) { // FOREIGN STATIC ITEM - let item = self.parse_item_foreign_static(visibility, attrs); - return IoviForeignItem(item); + return Ok(self.parse_item_foreign_static(visibility, attrs)); } if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) { // FOREIGN FUNCTION ITEM - let item = self.parse_item_foreign_fn(visibility, attrs); - return IoviForeignItem(item); + return Ok(self.parse_item_foreign_fn(visibility, attrs)); } - self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) + + // FIXME #5668: this will occur for a macro invocation: + let item = try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility)); + self.span_fatal(item.span, "macros cannot expand to foreign items"); } /// This is the fall-through for parsing items. @@ -5842,7 +5787,7 @@ impl<'a> Parser<'a> { macros_allowed: bool, lo: BytePos, visibility: Visibility - ) -> ItemOrViewItem { + ) -> MaybeItem { if macros_allowed && !self.token.is_any_keyword() && self.look_ahead(1, |t| *t == token::Not) && (self.look_ahead(2, |t| t.is_plain_ident()) @@ -5891,7 +5836,7 @@ impl<'a> Parser<'a> { item_, visibility, attrs); - return IoviItem(item); + return Ok(item); } // FAILURE TO PARSE ITEM @@ -5902,7 +5847,7 @@ impl<'a> Parser<'a> { self.span_fatal(last_span, "unmatched visibility `pub`"); } } - return IoviNone(attrs); + Err(attrs) } pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> { @@ -5911,30 +5856,9 @@ impl<'a> Parser<'a> { } pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> { - match self.parse_item_or_view_item(attrs, true) { - IoviNone(_) => None, - IoviViewItem(_) => - self.fatal("view items are not allowed here"), - IoviForeignItem(_) => - self.fatal("foreign items are not allowed here"), - IoviItem(item) => Some(item) - } + self.parse_item_(attrs, true).ok() } - /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo` - pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem { - match self.parse_item_or_view_item(attrs, false) { - IoviViewItem(vi) => vi, - _ => self.fatal("expected `use` or `extern crate`"), - } - } - - /// Parse, e.g., "use a::b::{z,y}" - fn parse_use(&mut self) -> ViewItem_ { - return ViewItemUse(self.parse_view_path()); - } - - /// Matches view_path : MOD? non_global_path as IDENT /// | MOD? non_global_path MOD_SEP LBRACE RBRACE /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE @@ -5959,8 +5883,7 @@ impl<'a> Parser<'a> { global: false, segments: Vec::new() }; - return P(spanned(lo, self.span.hi, - ViewPathList(path, idents, ast::DUMMY_NODE_ID))); + return P(spanned(lo, self.span.hi, ViewPathList(path, idents))); } let first_ident = self.parse_ident(); @@ -5994,8 +5917,7 @@ impl<'a> Parser<'a> { } }).collect() }; - return P(spanned(lo, self.span.hi, - ViewPathList(path, idents, ast::DUMMY_NODE_ID))); + return P(spanned(lo, self.span.hi, ViewPathList(path, idents))); } // foo::bar::* @@ -6011,15 +5933,14 @@ impl<'a> Parser<'a> { } }).collect() }; - return P(spanned(lo, self.span.hi, - ViewPathGlob(path, ast::DUMMY_NODE_ID))); + return P(spanned(lo, self.span.hi, ViewPathGlob(path))); } _ => break } } } - let mut rename_to = path[path.len() - 1u]; + let mut rename_to = path[path.len() - 1us]; let path = ast::Path { span: mk_sp(lo, self.last_span.hi), global: false, @@ -6033,136 +5954,39 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::As) { rename_to = self.parse_ident() } - P(spanned(lo, - self.last_span.hi, - ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID))) - } - - /// Parses a sequence of items. Stops when it finds program - /// text that can't be parsed as an item - /// - mod_items uses extern_mod_allowed = true - /// - block_tail_ uses extern_mod_allowed = false - fn parse_items_and_view_items(&mut self, - first_item_attrs: Vec<Attribute> , - mut extern_mod_allowed: bool, - macros_allowed: bool) - -> ParsedItemsAndViewItems { - let mut attrs = first_item_attrs; - attrs.push_all(&self.parse_outer_attributes()[]); - // First, parse view items. - let mut view_items : Vec<ast::ViewItem> = Vec::new(); - let mut items = Vec::new(); - - // I think this code would probably read better as a single - // loop with a mutable three-state-variable (for extern crates, - // view items, and regular items) ... except that because - // of macros, I'd like to delay that entire check until later. - loop { - match self.parse_item_or_view_item(attrs, macros_allowed) { - IoviNone(attrs) => { - return ParsedItemsAndViewItems { - attrs_remaining: attrs, - view_items: view_items, - items: items, - foreign_items: Vec::new() - } - } - IoviViewItem(view_item) => { - match view_item.node { - ViewItemUse(..) => { - // `extern crate` must precede `use`. - extern_mod_allowed = false; - } - ViewItemExternCrate(..) if !extern_mod_allowed => { - self.span_err(view_item.span, - "\"extern crate\" declarations are \ - not allowed here"); - } - ViewItemExternCrate(..) => {} - } - view_items.push(view_item); - } - IoviItem(item) => { - items.push(item); - attrs = self.parse_outer_attributes(); - break; - } - IoviForeignItem(_) => { - panic!(); - } - } - attrs = self.parse_outer_attributes(); - } - - // Next, parse items. - loop { - match self.parse_item_or_view_item(attrs, macros_allowed) { - IoviNone(returned_attrs) => { - attrs = returned_attrs; - break - } - IoviViewItem(view_item) => { - attrs = self.parse_outer_attributes(); - self.span_err(view_item.span, - "`use` and `extern crate` declarations must precede items"); - } - IoviItem(item) => { - attrs = self.parse_outer_attributes(); - items.push(item) - } - IoviForeignItem(_) => { - panic!(); - } - } - } - - ParsedItemsAndViewItems { - attrs_remaining: attrs, - view_items: view_items, - items: items, - foreign_items: Vec::new() - } + P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))) } /// Parses a sequence of foreign items. Stops when it finds program /// text that can't be parsed as an item - fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> , - macros_allowed: bool) - -> ParsedItemsAndViewItems { + fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute>) + -> Vec<P<ForeignItem>> { let mut attrs = first_item_attrs; attrs.push_all(&self.parse_outer_attributes()[]); let mut foreign_items = Vec::new(); loop { - match self.parse_foreign_item(attrs, macros_allowed) { - IoviNone(returned_attrs) => { + match self.parse_foreign_item(attrs) { + Ok(foreign_item) => { + foreign_items.push(foreign_item); + } + Err(returned_attrs) => { if self.check(&token::CloseDelim(token::Brace)) { attrs = returned_attrs; break } self.unexpected(); - }, - IoviViewItem(view_item) => { - // I think this can't occur: - self.span_err(view_item.span, - "`use` and `extern crate` declarations must precede items"); - } - IoviItem(item) => { - // FIXME #5668: this will occur for a macro invocation: - self.span_fatal(item.span, "macros cannot expand to foreign items"); - } - IoviForeignItem(foreign_item) => { - foreign_items.push(foreign_item); } } attrs = self.parse_outer_attributes(); } - ParsedItemsAndViewItems { - attrs_remaining: attrs, - view_items: Vec::new(), - items: Vec::new(), - foreign_items: foreign_items + if !attrs.is_empty() { + let last_span = self.last_span; + self.span_err(last_span, + Parser::expected_item_err(&attrs[])); } + + foreign_items } /// Parses a source module as a crate. This is the main diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index e5aef12e827..a129fd19d94 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -83,9 +83,9 @@ pub enum Lit { Integer(ast::Name), Float(ast::Name), Str_(ast::Name), - StrRaw(ast::Name, uint), /* raw str delimited by n hash symbols */ + StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */ Binary(ast::Name), - BinaryRaw(ast::Name, uint), /* raw binary str delimited by n hash symbols */ + BinaryRaw(ast::Name, usize), /* raw binary str delimited by n hash symbols */ } impl Lit { @@ -375,7 +375,7 @@ pub enum Nonterminal { NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity } -impl fmt::Show for Nonterminal { +impl fmt::Debug for Nonterminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NtItem(..) => f.pad("NtItem(..)"), @@ -651,15 +651,15 @@ impl BytesContainer for InternedString { } } -impl fmt::Show for InternedString { +impl fmt::Debug for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + fmt::Debug::fmt(&self.string[], f) } } -impl fmt::String for InternedString { +impl fmt::Display for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", &self.string[]) + fmt::Display::fmt(&self.string[], f) } } @@ -724,7 +724,7 @@ pub fn intern(s: &str) -> ast::Name { get_ident_interner().intern(s) } -/// gensym's a new uint, using the current interner. +/// gensym's a new usize, using the current interner. #[inline] pub fn gensym(s: &str) -> ast::Name { get_ident_interner().gensym(s) @@ -757,7 +757,7 @@ pub fn fresh_name(src: &ast::Ident) -> ast::Name { // create a fresh mark. pub fn fresh_mark() -> ast::Mrk { - gensym("mark").uint() as u32 + gensym("mark").usize() as u32 } #[cfg(test)] diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 06d510d37bd..0b1bd282941 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -31,7 +31,7 @@ //! //! In particular you'll see a certain amount of churn related to INTEGER vs. //! CARDINAL in the Mesa implementation. Mesa apparently interconverts the two -//! somewhat readily? In any case, I've used uint for indices-in-buffers and +//! somewhat readily? In any case, I've used usize for indices-in-buffers and //! ints for character-sizes-and-indentation-offsets. This respects the need //! for ints to "go negative" while carrying a pending-calculation balance, and //! helps differentiate all the numbers flying around internally (slightly). @@ -71,19 +71,19 @@ pub enum Breaks { #[derive(Clone, Copy)] pub struct BreakToken { - offset: int, - blank_space: int + offset: isize, + blank_space: isize } #[derive(Clone, Copy)] pub struct BeginToken { - offset: int, + offset: isize, breaks: Breaks } #[derive(Clone)] pub enum Token { - String(String, int), + String(String, isize), Break(BreakToken), Begin(BeginToken), End, @@ -122,25 +122,25 @@ pub fn tok_str(token: &Token) -> String { } pub fn buf_str(toks: &[Token], - szs: &[int], - left: uint, - right: uint, - lim: uint) + szs: &[isize], + left: usize, + right: usize, + lim: usize) -> String { let n = toks.len(); assert_eq!(n, szs.len()); let mut i = left; let mut l = lim; let mut s = string::String::from_str("["); - while i != right && l != 0u { - l -= 1u; + while i != right && l != 0us { + l -= 1us; if i != left { s.push_str(", "); } s.push_str(&format!("{}={}", szs[i], tok_str(&toks[i]))[]); - i += 1u; + i += 1us; i %= n; } s.push(']'); @@ -155,25 +155,25 @@ pub enum PrintStackBreak { #[derive(Copy)] pub struct PrintStackElem { - offset: int, + offset: isize, pbreak: PrintStackBreak } -static SIZE_INFINITY: int = 0xffff; +static SIZE_INFINITY: isize = 0xffff; -pub fn mk_printer(out: Box<io::Writer+'static>, linewidth: uint) -> Printer { +pub fn mk_printer(out: Box<io::Writer+'static>, linewidth: usize) -> Printer { // Yes 3, it makes the ring buffers big enough to never // fall behind. - let n: uint = 3 * linewidth; + let n: usize = 3 * linewidth; debug!("mk_printer {}", linewidth); let token: Vec<Token> = repeat(Token::Eof).take(n).collect(); - let size: Vec<int> = repeat(0i).take(n).collect(); - let scan_stack: Vec<uint> = repeat(0u).take(n).collect(); + let size: Vec<isize> = repeat(0is).take(n).collect(); + let scan_stack: Vec<usize> = repeat(0us).take(n).collect(); Printer { out: out, buf_len: n, - margin: linewidth as int, - space: linewidth as int, + margin: linewidth as isize, + space: linewidth as isize, left: 0, right: 0, token: token, @@ -267,40 +267,40 @@ pub fn mk_printer(out: Box<io::Writer+'static>, linewidth: uint) -> Printer { /// called 'print'. pub struct Printer { pub out: Box<io::Writer+'static>, - buf_len: uint, + buf_len: usize, /// Width of lines we're constrained to - margin: int, + margin: isize, /// Number of spaces left on line - space: int, + space: isize, /// Index of left side of input stream - left: uint, + left: usize, /// Index of right side of input stream - right: uint, + right: usize, /// Ring-buffer stream goes through token: Vec<Token> , /// Ring-buffer of calculated sizes - size: Vec<int> , + size: Vec<isize> , /// Running size of stream "...left" - left_total: int, + left_total: isize, /// Running size of stream "...right" - right_total: int, + right_total: isize, /// Pseudo-stack, really a ring too. Holds the /// primary-ring-buffers index of the Begin that started the /// current block, possibly with the most recent Break after that /// Begin (if there is any) on top of it. Stuff is flushed off the /// bottom as it becomes irrelevant due to the primary ring-buffer /// advancing. - scan_stack: Vec<uint> , + scan_stack: Vec<usize> , /// Top==bottom disambiguator scan_stack_empty: bool, /// Index of top of scan_stack - top: uint, + top: usize, /// Index of bottom of scan_stack - bottom: uint, + bottom: usize, /// Stack of blocks-in-progress being flushed by print print_stack: Vec<PrintStackElem> , /// Buffered indentation to avoid writing trailing whitespace - pending_indentation: int, + pending_indentation: isize, } impl Printer { @@ -326,8 +326,8 @@ impl Printer { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0u; - self.right = 0u; + self.left = 0us; + self.right = 0us; } else { self.advance_right(); } debug!("pp Begin({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -355,8 +355,8 @@ impl Printer { if self.scan_stack_empty { self.left_total = 1; self.right_total = 1; - self.left = 0u; - self.right = 0u; + self.left = 0us; + self.right = 0us; } else { self.advance_right(); } debug!("pp Break({})/buffer ~[{},{}]", b.offset, self.left, self.right); @@ -405,43 +405,43 @@ impl Printer { } Ok(()) } - pub fn scan_push(&mut self, x: uint) { + pub fn scan_push(&mut self, x: usize) { debug!("scan_push {}", x); if self.scan_stack_empty { self.scan_stack_empty = false; } else { - self.top += 1u; + self.top += 1us; self.top %= self.buf_len; assert!((self.top != self.bottom)); } self.scan_stack[self.top] = x; } - pub fn scan_pop(&mut self) -> uint { + pub fn scan_pop(&mut self) -> usize { assert!((!self.scan_stack_empty)); let x = self.scan_stack[self.top]; if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.top += self.buf_len - 1u; self.top %= self.buf_len; + self.top += self.buf_len - 1us; self.top %= self.buf_len; } return x; } - pub fn scan_top(&mut self) -> uint { + pub fn scan_top(&mut self) -> usize { assert!((!self.scan_stack_empty)); return self.scan_stack[self.top]; } - pub fn scan_pop_bottom(&mut self) -> uint { + pub fn scan_pop_bottom(&mut self) -> usize { assert!((!self.scan_stack_empty)); let x = self.scan_stack[self.bottom]; if self.top == self.bottom { self.scan_stack_empty = true; } else { - self.bottom += 1u; self.bottom %= self.buf_len; + self.bottom += 1us; self.bottom %= self.buf_len; } return x; } pub fn advance_right(&mut self) { - self.right += 1u; + self.right += 1us; self.right %= self.buf_len; assert!((self.right != self.left)); } @@ -471,7 +471,7 @@ impl Printer { break; } - self.left += 1u; + self.left += 1us; self.left %= self.buf_len; left_size = self.size[self.left]; @@ -479,7 +479,7 @@ impl Printer { Ok(()) } - pub fn check_stack(&mut self, k: int) { + pub fn check_stack(&mut self, k: isize) { if !self.scan_stack_empty { let x = self.scan_top(); match self.token[x] { @@ -506,21 +506,21 @@ impl Printer { } } } - pub fn print_newline(&mut self, amount: int) -> io::IoResult<()> { + pub fn print_newline(&mut self, amount: isize) -> io::IoResult<()> { debug!("NEWLINE {}", amount); let ret = write!(self.out, "\n"); self.pending_indentation = 0; self.indent(amount); return ret; } - pub fn indent(&mut self, amount: int) { + pub fn indent(&mut self, amount: isize) { debug!("INDENT {}", amount); self.pending_indentation += amount; } pub fn get_top(&mut self) -> PrintStackElem { let print_stack = &mut self.print_stack; let n = print_stack.len(); - if n != 0u { + if n != 0us { (*print_stack)[n - 1] } else { PrintStackElem { @@ -536,7 +536,7 @@ impl Printer { } write!(self.out, "{}", s) } - pub fn print(&mut self, token: Token, l: int) -> io::IoResult<()> { + pub fn print(&mut self, token: Token, l: isize) -> io::IoResult<()> { debug!("print {} {} (remaining line space={})", tok_str(&token), l, self.space); debug!("{}", buf_str(&self.token[], @@ -565,7 +565,7 @@ impl Printer { Token::End => { debug!("print End -> pop End"); let print_stack = &mut self.print_stack; - assert!((print_stack.len() != 0u)); + assert!((print_stack.len() != 0us)); print_stack.pop().unwrap(); Ok(()) } @@ -620,25 +620,25 @@ impl Printer { // Convenience functions to talk to the printer. // // "raw box" -pub fn rbox(p: &mut Printer, indent: uint, b: Breaks) -> io::IoResult<()> { +pub fn rbox(p: &mut Printer, indent: usize, b: Breaks) -> io::IoResult<()> { p.pretty_print(Token::Begin(BeginToken { - offset: indent as int, + offset: indent as isize, breaks: b })) } -pub fn ibox(p: &mut Printer, indent: uint) -> io::IoResult<()> { +pub fn ibox(p: &mut Printer, indent: usize) -> io::IoResult<()> { rbox(p, indent, Breaks::Inconsistent) } -pub fn cbox(p: &mut Printer, indent: uint) -> io::IoResult<()> { +pub fn cbox(p: &mut Printer, indent: usize) -> io::IoResult<()> { rbox(p, indent, Breaks::Consistent) } -pub fn break_offset(p: &mut Printer, n: uint, off: int) -> io::IoResult<()> { +pub fn break_offset(p: &mut Printer, n: usize, off: isize) -> io::IoResult<()> { p.pretty_print(Token::Break(BreakToken { offset: off, - blank_space: n as int + blank_space: n as isize })) } @@ -651,7 +651,7 @@ pub fn eof(p: &mut Printer) -> io::IoResult<()> { } pub fn word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { - p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as int)) + p.pretty_print(Token::String(/* bad */ wrd.to_string(), wrd.len() as isize)) } pub fn huge_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { @@ -662,23 +662,23 @@ pub fn zero_word(p: &mut Printer, wrd: &str) -> io::IoResult<()> { p.pretty_print(Token::String(/* bad */ wrd.to_string(), 0)) } -pub fn spaces(p: &mut Printer, n: uint) -> io::IoResult<()> { +pub fn spaces(p: &mut Printer, n: usize) -> io::IoResult<()> { break_offset(p, n, 0) } pub fn zerobreak(p: &mut Printer) -> io::IoResult<()> { - spaces(p, 0u) + spaces(p, 0us) } pub fn space(p: &mut Printer) -> io::IoResult<()> { - spaces(p, 1u) + spaces(p, 1us) } pub fn hardbreak(p: &mut Printer) -> io::IoResult<()> { - spaces(p, SIZE_INFINITY as uint) + spaces(p, SIZE_INFINITY as usize) } -pub fn hardbreak_tok_offset(off: int) -> Token { +pub fn hardbreak_tok_offset(off: isize) -> Token { Token::Break(BreakToken {offset: off, blank_space: SIZE_INFINITY}) } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b59e770c6ba..d1cd7631c82 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -54,8 +54,8 @@ impl PpAnn for NoAnn {} #[derive(Copy)] pub struct CurrentCommentAndLiteral { - cur_cmnt: uint, - cur_lit: uint, + cur_cmnt: usize, + cur_lit: usize, } pub struct State<'a> { @@ -92,10 +92,10 @@ pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>, } #[allow(non_upper_case_globals)] -pub const indent_unit: uint = 4u; +pub const indent_unit: usize = 4us; #[allow(non_upper_case_globals)] -pub const default_columns: uint = 78u; +pub const default_columns: usize = 78us; /// Requires you to pass an input filename and reader so that /// it can scan the input text for comments and literals to @@ -337,10 +337,6 @@ pub fn item_to_string(i: &ast::Item) -> String { $to_string(|s| s.print_item(i)) } -pub fn view_item_to_string(i: &ast::ViewItem) -> String { - $to_string(|s| s.print_view_item(i)) -} - pub fn generics_to_string(generics: &ast::Generics) -> String { $to_string(|s| s.print_generics(generics)) } @@ -381,7 +377,7 @@ pub fn block_to_string(blk: &ast::Block) -> String { // containing cbox, will be closed by print-block at } try!(s.cbox(indent_unit)); // head-ibox, will be closed by print-block after { - try!(s.ibox(0u)); + try!(s.ibox(0us)); s.print_block(blk) }) } @@ -459,7 +455,7 @@ fn needs_parentheses(expr: &ast::Expr) -> bool { } impl<'a> State<'a> { - pub fn ibox(&mut self, u: uint) -> IoResult<()> { + pub fn ibox(&mut self, u: usize) -> IoResult<()> { self.boxes.push(pp::Breaks::Inconsistent); pp::ibox(&mut self.s, u) } @@ -469,13 +465,13 @@ impl<'a> State<'a> { pp::end(&mut self.s) } - pub fn cbox(&mut self, u: uint) -> IoResult<()> { + pub fn cbox(&mut self, u: usize) -> IoResult<()> { self.boxes.push(pp::Breaks::Consistent); pp::cbox(&mut self.s, u) } // "raw box" - pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> { + pub fn rbox(&mut self, u: usize, b: pp::Breaks) -> IoResult<()> { self.boxes.push(b); pp::rbox(&mut self.s, u, b) } @@ -514,13 +510,13 @@ impl<'a> State<'a> { } pub fn bclose_(&mut self, span: codemap::Span, - indented: uint) -> IoResult<()> { + indented: usize) -> IoResult<()> { self.bclose_maybe_open(span, indented, true) } pub fn bclose_maybe_open (&mut self, span: codemap::Span, - indented: uint, close_box: bool) -> IoResult<()> { + indented: usize, close_box: bool) -> IoResult<()> { try!(self.maybe_print_comment(span.hi)); - try!(self.break_offset_if_not_bol(1u, -(indented as int))); + try!(self.break_offset_if_not_bol(1us, -(indented as isize))); try!(word(&mut self.s, "}")); if close_box { try!(self.end()); // close the outer-box @@ -567,8 +563,8 @@ impl<'a> State<'a> { if !self.is_bol() { try!(space(&mut self.s)); } Ok(()) } - pub fn break_offset_if_not_bol(&mut self, n: uint, - off: int) -> IoResult<()> { + pub fn break_offset_if_not_bol(&mut self, n: usize, + off: isize) -> IoResult<()> { if !self.is_bol() { break_offset(&mut self.s, n, off) } else { @@ -595,7 +591,7 @@ impl<'a> State<'a> { pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where F: FnMut(&mut State, &T) -> IoResult<()>, { - try!(self.rbox(0u, b)); + try!(self.rbox(0us, b)); let mut first = true; for elt in elts.iter() { if first { first = false; } else { try!(self.word_space(",")); } @@ -613,13 +609,13 @@ impl<'a> State<'a> { F: FnMut(&mut State, &T) -> IoResult<()>, G: FnMut(&T) -> codemap::Span, { - try!(self.rbox(0u, b)); + try!(self.rbox(0us, b)); let len = elts.len(); - let mut i = 0u; + let mut i = 0us; for elt in elts.iter() { try!(self.maybe_print_comment(get_span(elt).hi)); try!(op(self, elt)); - i += 1u; + i += 1us; if i < len { try!(word(&mut self.s, ",")); try!(self.maybe_print_trailing_comment(get_span(elt), @@ -638,9 +634,6 @@ impl<'a> State<'a> { pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) -> IoResult<()> { try!(self.print_inner_attributes(attrs)); - for vitem in _mod.view_items.iter() { - try!(self.print_view_item(vitem)); - } for item in _mod.items.iter() { try!(self.print_item(&**item)); } @@ -650,9 +643,6 @@ impl<'a> State<'a> { pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) -> IoResult<()> { try!(self.print_inner_attributes(attrs)); - for vitem in nmod.view_items.iter() { - try!(self.print_view_item(vitem)); - } for item in nmod.items.iter() { try!(self.print_foreign_item(&**item)); } @@ -670,7 +660,7 @@ impl<'a> State<'a> { pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> { try!(self.maybe_print_comment(ty.span.lo)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); match ty.node { ast::TyVec(ref ty) => { try!(word(&mut self.s, "[")); @@ -809,6 +799,28 @@ impl<'a> State<'a> { try!(self.print_outer_attributes(&item.attrs[])); try!(self.ann.pre(self, NodeItem(item))); match item.node { + ast::ItemExternCrate(ref optional_path) => { + try!(self.head(&visibility_qualified(item.vis, + "extern crate")[])); + for &(ref p, style) in optional_path.iter() { + try!(self.print_string(p.get(), style)); + try!(space(&mut self.s)); + try!(word(&mut self.s, "as")); + try!(space(&mut self.s)); + } + try!(self.print_ident(item.ident)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end inner head-block + try!(self.end()); // end outer head-block + } + ast::ItemUse(ref vp) => { + try!(self.head(&visibility_qualified(item.vis, + "use")[])); + try!(self.print_view_path(&**vp)); + try!(word(&mut self.s, ";")); + try!(self.end()); // end inner head-block + try!(self.end()); // end outer head-block + } ast::ItemStatic(ref ty, m, ref expr) => { try!(self.head(&visibility_qualified(item.vis, "static")[])); @@ -871,7 +883,7 @@ impl<'a> State<'a> { } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.word_nbsp(&visibility_qualified(item.vis, "type")[])); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); @@ -1152,11 +1164,20 @@ impl<'a> State<'a> { pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> { try!(self.ibox(0)); + let mut suppress_space = false; for (i, tt) in tts.iter().enumerate() { - if i != 0 { + if i != 0 && !suppress_space { try!(space(&mut self.s)); } try!(self.print_tt(tt)); + // There should be no space between the module name and the following `::` in paths, + // otherwise imported macros get re-parsed from crate metadata incorrectly (#20701) + suppress_space = match tt { + &ast::TtToken(_, token::Ident(_, token::ModName)) | + &ast::TtToken(_, token::MatchNt(_, _, _, token::ModName)) | + &ast::TtToken(_, token::SubstNt(_, token::ModName)) => true, + _ => false + } } self.end() } @@ -1262,7 +1283,7 @@ impl<'a> State<'a> { pub fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0u; + let mut count = 0us; for attr in attrs.iter() { match attr.node.style { ast::AttrOuter => { @@ -1280,7 +1301,7 @@ impl<'a> State<'a> { pub fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> IoResult<()> { - let mut count = 0u; + let mut count = 0us; for attr in attrs.iter() { match attr.node.style { ast::AttrInner => { @@ -1355,7 +1376,7 @@ impl<'a> State<'a> { } pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block, - indented: uint) -> IoResult<()> { + indented: usize) -> IoResult<()> { self.print_block_maybe_unclosed(blk, indented, &[], false) } @@ -1367,7 +1388,7 @@ impl<'a> State<'a> { pub fn print_block_maybe_unclosed(&mut self, blk: &ast::Block, - indented: uint, + indented: usize, attrs: &[ast::Attribute], close_box: bool) -> IoResult<()> { match blk.rules { @@ -1380,9 +1401,6 @@ impl<'a> State<'a> { try!(self.print_inner_attributes(attrs)); - for vi in blk.view_items.iter() { - try!(self.print_view_item(vi)); - } for st in blk.stmts.iter() { try!(self.print_stmt(&**st)); } @@ -1404,8 +1422,8 @@ impl<'a> State<'a> { match _else.node { // "another else-if" ast::ExprIf(ref i, ref then, ref e) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else if ")); try!(self.print_expr(&**i)); try!(space(&mut self.s)); @@ -1414,8 +1432,8 @@ impl<'a> State<'a> { } // "another else-if-let" ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else if let ")); try!(self.print_pat(&**pat)); try!(space(&mut self.s)); @@ -1427,8 +1445,8 @@ impl<'a> State<'a> { } // "final else" ast::ExprBlock(ref b) => { - try!(self.cbox(indent_unit - 1u)); - try!(self.ibox(0u)); + try!(self.cbox(indent_unit - 1us)); + try!(self.ibox(0us)); try!(word(&mut self.s, " else ")); self.print_block(&**b) } @@ -1590,11 +1608,11 @@ impl<'a> State<'a> { ident: ast::SpannedIdent, tys: &[P<ast::Ty>], args: &[P<ast::Expr>]) -> IoResult<()> { - let base_args = args.slice_from(1); + let base_args = &args[1..]; try!(self.print_expr(&*args[0])); try!(word(&mut self.s, ".")); try!(self.print_ident(ident.node)); - if tys.len() > 0u { + if tys.len() > 0us { try!(word(&mut self.s, "::<")); try!(self.commasep(Inconsistent, tys, |s, ty| s.print_type(&**ty))); @@ -1765,7 +1783,7 @@ impl<'a> State<'a> { // containing cbox, will be closed by print-block at } try!(self.cbox(indent_unit)); // head-box, will be closed by print-block after { - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.print_block(&**blk)); } ast::ExprAssign(ref lhs, ref rhs) => { @@ -1789,7 +1807,7 @@ impl<'a> State<'a> { ast::ExprTupField(ref expr, id) => { try!(self.print_expr(&**expr)); try!(word(&mut self.s, ".")); - try!(self.print_uint(id.node)); + try!(self.print_usize(id.node)); } ast::ExprIndex(ref expr, ref index) => { try!(self.print_expr(&**expr)); @@ -1951,7 +1969,7 @@ impl<'a> State<'a> { self.ann.post(self, NodeIdent(&ident)) } - pub fn print_uint(&mut self, i: uint) -> IoResult<()> { + pub fn print_usize(&mut self, i: usize) -> IoResult<()> { word(&mut self.s, &i.to_string()[]) } @@ -2142,7 +2160,7 @@ impl<'a> State<'a> { }, |f| f.node.pat.span)); if etc { - if fields.len() != 0u { try!(self.word_space(",")); } + if fields.len() != 0us { try!(self.word_space(",")); } try!(word(&mut self.s, "..")); } try!(space(&mut self.s)); @@ -2209,7 +2227,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); } try!(self.cbox(indent_unit)); - try!(self.ibox(0u)); + try!(self.ibox(0us)); try!(self.print_outer_attributes(&arm.attrs[])); let mut first = true; for p in arm.pats.iter() { @@ -2295,7 +2313,7 @@ impl<'a> State<'a> { -> IoResult<()> { // It is unfortunate to duplicate the commasep logic, but we want the // self type and the args all in the same box. - try!(self.rbox(0u, Inconsistent)); + try!(self.rbox(0us, Inconsistent)); let mut first = true; for &explicit_self in opt_explicit_self.iter() { let m = match explicit_self { @@ -2312,7 +2330,7 @@ impl<'a> State<'a> { let args = if first { &decl.inputs[] } else { - decl.inputs.slice_from(1) + &decl.inputs[1..] }; for arg in args.iter() { @@ -2470,7 +2488,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "<")); let mut ints = Vec::new(); - for i in range(0u, total) { + for i in range(0us, total) { ints.push(i); } @@ -2577,7 +2595,7 @@ impl<'a> State<'a> { pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> { match vp.node { - ast::ViewPathSimple(ident, ref path, _) => { + ast::ViewPathSimple(ident, ref path) => { try!(self.print_path(path, false)); // FIXME(#6993) can't compare identifiers directly here @@ -2591,12 +2609,12 @@ impl<'a> State<'a> { Ok(()) } - ast::ViewPathGlob(ref path, _) => { + ast::ViewPathGlob(ref path) => { try!(self.print_path(path, false)); word(&mut self.s, "::*") } - ast::ViewPathList(ref path, ref idents, _) => { + ast::ViewPathList(ref path, ref idents) => { if path.segments.is_empty() { try!(word(&mut self.s, "{")); } else { @@ -2618,33 +2636,6 @@ impl<'a> State<'a> { } } - pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> { - try!(self.hardbreak_if_not_bol()); - try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(&item.attrs[])); - try!(self.print_visibility(item.vis)); - match item.node { - ast::ViewItemExternCrate(id, ref optional_path, _) => { - try!(self.head("extern crate")); - for &(ref p, style) in optional_path.iter() { - try!(self.print_string(p.get(), style)); - try!(space(&mut self.s)); - try!(word(&mut self.s, "as")); - try!(space(&mut self.s)); - } - try!(self.print_ident(id)); - } - - ast::ViewItemUse(ref vp) => { - try!(self.head("use")); - try!(self.print_view_path(&**vp)); - } - } - try!(word(&mut self.s, ";")); - try!(self.end()); // end inner head-block - self.end() // end outer head-block - } - pub fn print_mutability(&mut self, mutbl: ast::Mutability) -> IoResult<()> { match mutbl { @@ -2788,7 +2779,7 @@ impl<'a> State<'a> { if span.hi < (*cmnt).pos && (*cmnt).pos < next && span_line.line == comment_line.line { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } } _ => () @@ -2806,7 +2797,7 @@ impl<'a> State<'a> { match self.next_comment() { Some(ref cmnt) => { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } _ => break } @@ -2888,7 +2879,7 @@ impl<'a> State<'a> { while self.cur_cmnt_and_lit.cur_lit < lits.len() { let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone(); if ltrl.pos > pos { return None; } - self.cur_cmnt_and_lit.cur_lit += 1u; + self.cur_cmnt_and_lit.cur_lit += 1us; if ltrl.pos == pos { return Some(ltrl); } } None @@ -2903,7 +2894,7 @@ impl<'a> State<'a> { Some(ref cmnt) => { if (*cmnt).pos < pos { try!(self.print_comment(cmnt)); - self.cur_cmnt_and_lit.cur_cmnt += 1u; + self.cur_cmnt_and_lit.cur_cmnt += 1us; } else { break; } } _ => break @@ -2916,7 +2907,7 @@ impl<'a> State<'a> { cmnt: &comments::Comment) -> IoResult<()> { match cmnt.style { comments::Mixed => { - assert_eq!(cmnt.lines.len(), 1u); + assert_eq!(cmnt.lines.len(), 1us); try!(zerobreak(&mut self.s)); try!(word(&mut self.s, &cmnt.lines[0][])); zerobreak(&mut self.s) @@ -2935,11 +2926,11 @@ impl<'a> State<'a> { } comments::Trailing => { try!(word(&mut self.s, " ")); - if cmnt.lines.len() == 1u { + if cmnt.lines.len() == 1us { try!(word(&mut self.s, &cmnt.lines[0][])); hardbreak(&mut self.s) } else { - try!(self.ibox(0u)); + try!(self.ibox(0us)); for line in cmnt.lines.iter() { if !line.is_empty() { try!(word(&mut self.s, &line[])); @@ -3047,7 +3038,7 @@ impl<'a> State<'a> { } } -fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() } +fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() } #[cfg(test)] mod test { diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 37fa8703706..01f3839b039 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -36,7 +36,7 @@ //! implementation changes (using a special thread-local heap, for example). //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. -use std::fmt::{self, Show}; +use std::fmt::{self, Display, Debug}; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::ptr; @@ -100,9 +100,14 @@ impl<T: PartialEq> PartialEq for P<T> { impl<T: Eq> Eq for P<T> {} -impl<T: Show> Show for P<T> { +impl<T: Debug> Debug for P<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + Debug::fmt(&**self, f) + } +} +impl<T: Display> Display for P<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) } } diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 28b9eaa54aa..d75fbcf199d 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -20,8 +20,6 @@ use parse::token; use ptr::P; use util::small_vector::SmallVector; -use std::mem; - pub fn maybe_inject_crates_ref(krate: ast::Crate, alt_std_name: Option<String>) -> ast::Crate { if use_std(&krate) { @@ -60,20 +58,16 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { None => token::intern_and_get_ident("std"), }; - let mut vis = vec!(ast::ViewItem { - node: ast::ViewItemExternCrate(token::str_to_ident("std"), - Some((actual_crate_name, ast::CookedStr)), - ast::DUMMY_NODE_ID), + krate.module.items.insert(0, P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: token::str_to_ident("std"), attrs: vec!( attr::mk_attr_outer(attr::mk_attr_id(), attr::mk_word_item( InternedString::new("macro_use")))), + node: ast::ItemExternCrate(Some((actual_crate_name, ast::CookedStr))), vis: ast::Inherited, span: DUMMY_SP - }); - - // `extern crate` must be precede `use` items - mem::swap(&mut vis, &mut krate.module.view_items); - krate.module.view_items.extend(vis.into_iter()); + })); // don't add #![no_std] here, that will block the prelude injection later. // Add it during the prelude injection instead. @@ -123,7 +117,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { } } - fn fold_mod(&mut self, ast::Mod {inner, view_items, items}: ast::Mod) -> ast::Mod { + fn fold_mod(&mut self, mut mod_: ast::Mod) -> ast::Mod { let prelude_path = ast::Path { span: DUMMY_SP, global: false, @@ -143,18 +137,11 @@ impl<'a> fold::Folder for PreludeInjector<'a> { ], }; - let (crates, uses): (Vec<_>, _) = view_items.iter().cloned().partition(|x| { - match x.node { - ast::ViewItemExternCrate(..) => true, - _ => false, - } - }); - - // add prelude after any `extern crate` but before any `use` - let mut view_items = crates; - let vp = P(codemap::dummy_spanned(ast::ViewPathGlob(prelude_path, ast::DUMMY_NODE_ID))); - view_items.push(ast::ViewItem { - node: ast::ViewItemUse(vp), + let vp = P(codemap::dummy_spanned(ast::ViewPathGlob(prelude_path))); + mod_.items.insert(0, P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: special_idents::invalid, + node: ast::ItemUse(vp), attrs: vec![ast::Attribute { span: DUMMY_SP, node: ast::Attribute_ { @@ -170,14 +157,9 @@ impl<'a> fold::Folder for PreludeInjector<'a> { }], vis: ast::Inherited, span: DUMMY_SP, - }); - view_items.extend(uses.into_iter()); - - fold::noop_fold_mod(ast::Mod { - inner: inner, - view_items: view_items, - items: items - }, self) + })); + + fold::noop_fold_mod(mod_, self) } } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index c7d7b57e66e..4b6657d67a4 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -105,11 +105,11 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { // Add a special __test module to the crate that will contain code // generated for the test harness let (mod_, reexport) = mk_test_module(&mut self.cx); - folded.module.items.push(mod_); match reexport { - Some(re) => folded.module.view_items.push(re), + Some(re) => folded.module.items.push(re), None => {} } + folded.module.items.push(mod_); folded } @@ -205,22 +205,19 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { fn mk_reexport_mod(cx: &mut TestCtxt, tests: Vec<ast::Ident>, tested_submods: Vec<(ast::Ident, ast::Ident)>) -> (P<ast::Item>, ast::Ident) { - let mut view_items = Vec::new(); let super_ = token::str_to_ident("super"); - view_items.extend(tests.into_iter().map(|r| { - cx.ext_cx.view_use_simple(DUMMY_SP, ast::Public, + let items = tests.into_iter().map(|r| { + cx.ext_cx.item_use_simple(DUMMY_SP, ast::Public, cx.ext_cx.path(DUMMY_SP, vec![super_, r])) - })); - view_items.extend(tested_submods.into_iter().map(|(r, sym)| { + }).chain(tested_submods.into_iter().map(|(r, sym)| { let path = cx.ext_cx.path(DUMMY_SP, vec![super_, r, sym]); - cx.ext_cx.view_use_simple_(DUMMY_SP, ast::Public, r, path) + cx.ext_cx.item_use_simple_(DUMMY_SP, ast::Public, r, path) })); let reexport_mod = ast::Mod { inner: DUMMY_SP, - view_items: view_items, - items: Vec::new(), + items: items.collect(), }; let sym = token::gensym_ident("__test_reexports"); @@ -357,8 +354,8 @@ fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { let tparm_cnt = generics.ty_params.len(); // NB: inadequate check, but we're running // well before resolve, can't get too deep. - input_cnt == 1u - && no_output && tparm_cnt == 0u + input_cnt == 1us + && no_output && tparm_cnt == 0us } _ => false } @@ -406,24 +403,24 @@ mod __test { */ -fn mk_std(cx: &TestCtxt) -> ast::ViewItem { +fn mk_std(cx: &TestCtxt) -> P<ast::Item> { let id_test = token::str_to_ident("test"); - let (vi, vis) = if cx.is_test_crate { - (ast::ViewItemUse( + let (vi, vis, ident) = if cx.is_test_crate { + (ast::ItemUse( P(nospan(ast::ViewPathSimple(id_test, - path_node(vec!(id_test)), - ast::DUMMY_NODE_ID)))), - ast::Public) + path_node(vec!(id_test)))))), + ast::Public, token::special_idents::invalid) } else { - (ast::ViewItemExternCrate(id_test, None, ast::DUMMY_NODE_ID), - ast::Inherited) + (ast::ItemExternCrate(None), ast::Inherited, id_test) }; - ast::ViewItem { + P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: ident, node: vi, - attrs: Vec::new(), + attrs: vec![], vis: vis, span: DUMMY_SP - } + }) } fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> { @@ -450,8 +447,9 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> { token::str_to_ident("args")]); // use std::slice::AsSlice let as_slice_path = P(nospan(ast::ViewPathSimple(token::str_to_ident("AsSlice"), - as_slice_path, ast::DUMMY_NODE_ID))); - let use_as_slice = ecx.view_use(sp, ast::Inherited, as_slice_path); + as_slice_path))); + let use_as_slice = ecx.item_use(sp, ast::Inherited, as_slice_path); + let use_as_slice = ecx.stmt_item(sp, use_as_slice); // ::std::os::args() let os_args_path_expr = ecx.expr_path(os_args_path); let call_os_args = ecx.expr_call(sp, os_args_path_expr, vec![]); @@ -469,7 +467,7 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> { let main_attr = ecx.attribute(sp, main_meta); // pub fn main() { ... } let main_ret_ty = ecx.ty(sp, ast::TyTup(vec![])); - let main_body = ecx.block_all(sp, vec![use_as_slice], vec![call_test_main], None); + let main_body = ecx.block_all(sp, vec![use_as_slice, call_test_main], None); let main = ast::ItemFn(ecx.fn_decl(vec![], main_ret_ty), ast::Unsafety::Normal, ::abi::Rust, empty_generics(), main_body); let main = P(ast::Item { @@ -484,9 +482,9 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> { return main; } -fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<ast::ViewItem>) { +fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<P<ast::Item>>) { // Link to test crate - let view_items = vec!(mk_std(cx)); + let import = mk_std(cx); // A constant vector of test descriptors. let tests = mk_tests(cx); @@ -497,40 +495,40 @@ fn mk_test_module(cx: &mut TestCtxt) -> (P<ast::Item>, Option<ast::ViewItem>) { let testmod = ast::Mod { inner: DUMMY_SP, - view_items: view_items, - items: vec!(mainfn, tests), + items: vec![import, mainfn, tests], }; let item_ = ast::ItemMod(testmod); let mod_ident = token::gensym_ident("__test"); - let item = ast::Item { - ident: mod_ident, + let item = P(ast::Item { id: ast::DUMMY_NODE_ID, + ident: mod_ident, + attrs: vec![], node: item_, vis: ast::Public, span: DUMMY_SP, - attrs: vec![], - }; + }); let reexport = cx.reexport_test_harness_main.as_ref().map(|s| { // building `use <ident> = __test::main` let reexport_ident = token::str_to_ident(s.get()); let use_path = nospan(ast::ViewPathSimple(reexport_ident, - path_node(vec![mod_ident, token::str_to_ident("main")]), - ast::DUMMY_NODE_ID)); + path_node(vec![mod_ident, token::str_to_ident("main")]))); - ast::ViewItem { - node: ast::ViewItemUse(P(use_path)), + P(ast::Item { + id: ast::DUMMY_NODE_ID, + ident: token::special_idents::invalid, attrs: vec![], + node: ast::ItemUse(P(use_path)), vis: ast::Inherited, span: DUMMY_SP - } + }) }); - debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&item)); + debug!("Synthetic test module:\n{}\n", pprust::item_to_string(&*item)); - (P(item), reexport) + (item, reexport) } fn nospan<T>(t: T) -> codemap::Spanned<T> { diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 5dca39f1aea..1b35b1b04a3 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! An "interner" is a data structure that associates values with uint tags and +//! An "interner" is a data structure that associates values with usize tags and //! allows bidirectional lookup; i.e. given a value, one can easily find the //! type, and vice versa. @@ -70,10 +70,10 @@ impl<T: Eq + Hash<Hasher> + Clone + 'static> Interner<T> { pub fn get(&self, idx: Name) -> T { let vect = self.vect.borrow(); - (*vect)[idx.uint()].clone() + (*vect)[idx.usize()].clone() } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { let vect = self.vect.borrow(); (*vect).len() } @@ -114,9 +114,16 @@ impl Ord for RcStr { } } -impl fmt::Show for RcStr { +impl fmt::Debug for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Show; + use std::fmt::Debug; + self[].fmt(f) + } +} + +impl fmt::Display for RcStr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::fmt::Display; self[].fmt(f) } } @@ -190,16 +197,16 @@ impl StrInterner { let new_idx = Name(self.len() as u32); // leave out of map to avoid colliding let mut vect = self.vect.borrow_mut(); - let existing = (*vect)[idx.uint()].clone(); + let existing = (*vect)[idx.usize()].clone(); vect.push(existing); new_idx } pub fn get(&self, idx: Name) -> RcStr { - (*self.vect.borrow())[idx.uint()].clone() + (*self.vect.borrow())[idx.usize()].clone() } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { self.vect.borrow().len() } diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 83bbff8473d..89854f5d979 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -69,13 +69,6 @@ pub fn string_to_stmt(source_str : String) -> P<ast::Stmt> { }) } -/// Parse a string, return a view item -pub fn string_to_view_item (source_str : String) -> ast::ViewItem { - with_error_checking_parse(source_str, |p| { - p.parse_view_item(Vec::new()) - }) -} - /// Parse a string, return a pat. Uses "irrefutable"... which doesn't /// (currently) affect parsing. pub fn string_to_pat(source_str: String) -> P<ast::Pat> { @@ -130,10 +123,10 @@ pub fn matches_codepattern(a : &str, b : &str) -> bool { } } -/// Given a string and an index, return the first uint >= idx +/// Given a string and an index, return the first usize >= idx /// that is a non-ws-char or is outside of the legal range of /// the string. -fn scan_for_non_ws_or_end(a : &str, idx: uint) -> uint { +fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize { let mut i = idx; let len = a.len(); while (i < len) && (is_whitespace(a.char_at(i))) { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index 22f2fb36fc8..21a7d680847 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -89,7 +89,7 @@ impl<T> SmallVector<T> { } } - pub fn get<'a>(&'a self, idx: uint) -> &'a T { + pub fn get<'a>(&'a self, idx: usize) -> &'a T { match self.repr { One(ref v) if idx == 0 => v, Many(ref vs) => &vs[idx], @@ -127,7 +127,7 @@ impl<T> SmallVector<T> { IntoIter { repr: repr } } - pub fn len(&self) -> uint { + pub fn len(&self) -> usize { match self.repr { Zero => 0, One(..) => 1, @@ -166,7 +166,7 @@ impl<T> Iterator for IntoIter<T> { } } - fn size_hint(&self) -> (uint, Option<uint>) { + fn size_hint(&self) -> (usize, Option<usize>) { match self.repr { ZeroIterator => (0, Some(0)), OneIterator(..) => (1, Some(1)), @@ -192,17 +192,17 @@ mod test { #[test] fn test_len() { - let v: SmallVector<int> = SmallVector::zero(); + let v: SmallVector<isize> = SmallVector::zero(); assert_eq!(0, v.len()); - assert_eq!(1, SmallVector::one(1i).len()); - assert_eq!(5, SmallVector::many(vec!(1i, 2, 3, 4, 5)).len()); + assert_eq!(1, SmallVector::one(1is).len()); + assert_eq!(5, SmallVector::many(vec!(1is, 2, 3, 4, 5)).len()); } #[test] fn test_push_get() { let mut v = SmallVector::zero(); - v.push(1i); + v.push(1is); assert_eq!(1, v.len()); assert_eq!(&1, v.get(0)); v.push(2); @@ -215,7 +215,7 @@ mod test { #[test] fn test_from_iter() { - let v: SmallVector<int> = (vec!(1i, 2, 3)).into_iter().collect(); + let v: SmallVector<isize> = (vec![1is, 2, 3]).into_iter().collect(); assert_eq!(3, v.len()); assert_eq!(&1, v.get(0)); assert_eq!(&2, v.get(1)); @@ -225,31 +225,31 @@ mod test { #[test] fn test_move_iter() { let v = SmallVector::zero(); - let v: Vec<int> = v.into_iter().collect(); + let v: Vec<isize> = v.into_iter().collect(); assert_eq!(Vec::new(), v); - let v = SmallVector::one(1i); - assert_eq!(vec!(1i), v.into_iter().collect::<Vec<_>>()); + let v = SmallVector::one(1is); + assert_eq!(vec!(1is), v.into_iter().collect::<Vec<_>>()); - let v = SmallVector::many(vec!(1i, 2i, 3i)); - assert_eq!(vec!(1i, 2i, 3i), v.into_iter().collect::<Vec<_>>()); + let v = SmallVector::many(vec!(1is, 2is, 3is)); + assert_eq!(vec!(1is, 2is, 3is), v.into_iter().collect::<Vec<_>>()); } #[test] #[should_fail] fn test_expect_one_zero() { - let _: int = SmallVector::zero().expect_one(""); + let _: isize = SmallVector::zero().expect_one(""); } #[test] #[should_fail] fn test_expect_one_many() { - SmallVector::many(vec!(1i, 2)).expect_one(""); + SmallVector::many(vec!(1is, 2)).expect_one(""); } #[test] fn test_expect_one_one() { - assert_eq!(1i, SmallVector::one(1i).expect_one("")); - assert_eq!(1i, SmallVector::many(vec!(1i)).expect_one("")); + assert_eq!(1is, SmallVector::one(1is).expect_one("")); + assert_eq!(1is, SmallVector::many(vec!(1is)).expect_one("")); } } diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 7778b4fa34a..eb906788aa7 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -62,7 +62,6 @@ pub trait Visitor<'v> : Sized { self.visit_name(span, ident.name); } fn visit_mod(&mut self, m: &'v Mod, _s: Span, _n: NodeId) { walk_mod(self, m) } - fn visit_view_item(&mut self, i: &'v ViewItem) { walk_view_item(self, i) } fn visit_foreign_item(&mut self, i: &'v ForeignItem) { walk_foreign_item(self, i) } fn visit_item(&mut self, i: &'v Item) { walk_item(self, i) } fn visit_local(&mut self, l: &'v Local) { walk_local(self, l) } @@ -166,51 +165,11 @@ pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) { } pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod) { - for view_item in module.view_items.iter() { - visitor.visit_view_item(view_item) - } - for item in module.items.iter() { visitor.visit_item(&**item) } } -pub fn walk_view_item<'v, V: Visitor<'v>>(visitor: &mut V, vi: &'v ViewItem) { - match vi.node { - ViewItemExternCrate(name, _, _) => { - visitor.visit_ident(vi.span, name) - } - ViewItemUse(ref vp) => { - match vp.node { - ViewPathSimple(ident, ref path, id) => { - visitor.visit_ident(vp.span, ident); - visitor.visit_path(path, id); - } - ViewPathGlob(ref path, id) => { - visitor.visit_path(path, id); - } - ViewPathList(ref prefix, ref list, _) => { - for id in list.iter() { - match id.node { - PathListIdent { name, .. } => { - visitor.visit_ident(id.span, name); - } - PathListMod { .. } => () - } - } - - // Note that the `prefix` here is not a complete - // path, so we don't use `visit_path`. - walk_path(visitor, prefix); - } - } - } - } - for attr in vi.attrs.iter() { - visitor.visit_attribute(attr); - } -} - pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) { visitor.visit_pat(&*local.pat); walk_ty_opt(visitor, &local.ty); @@ -269,6 +228,32 @@ pub fn walk_trait_ref<'v,V>(visitor: &mut V, pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_ident(item.span, item.ident); match item.node { + ItemExternCrate(..) => {} + ItemUse(ref vp) => { + match vp.node { + ViewPathSimple(ident, ref path) => { + visitor.visit_ident(vp.span, ident); + visitor.visit_path(path, item.id); + } + ViewPathGlob(ref path) => { + visitor.visit_path(path, item.id); + } + ViewPathList(ref prefix, ref list) => { + for id in list.iter() { + match id.node { + PathListIdent { name, .. } => { + visitor.visit_ident(id.span, name); + } + PathListMod { .. } => () + } + } + + // Note that the `prefix` here is not a complete + // path, so we don't use `visit_path`. + walk_path(visitor, prefix); + } + } + } ItemStatic(ref typ, _, ref expr) | ItemConst(ref typ, ref expr) => { visitor.visit_ty(&**typ); @@ -285,9 +270,6 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { visitor.visit_mod(module, item.span, item.id) } ItemForeignMod(ref foreign_module) => { - for view_item in foreign_module.view_items.iter() { - visitor.visit_view_item(view_item) - } for foreign_item in foreign_module.items.iter() { visitor.visit_foreign_item(&**foreign_item) } @@ -732,9 +714,6 @@ pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, } pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) { - for view_item in block.view_items.iter() { - visitor.visit_view_item(view_item) - } for statement in block.stmts.iter() { visitor.visit_stmt(&**statement) } |
