diff options
| author | bors <bors@rust-lang.org> | 2015-01-07 05:31:23 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2015-01-07 05:31:23 +0000 |
| commit | 9e4e524e0eb17c8f463e731f23b544003e8709c6 (patch) | |
| tree | 916024d35e08f0826c20654f629ec596b5cb1f14 /src/libsyntax | |
| parent | ea6f65c5f1a3f84e010d2cef02a0160804e9567a (diff) | |
| parent | a64000820f0fc32be4d7535a9a92418a434fa4ba (diff) | |
| download | rust-9e4e524e0eb17c8f463e731f23b544003e8709c6.tar.gz rust-9e4e524e0eb17c8f463e731f23b544003e8709c6.zip | |
auto merge of #20677 : alexcrichton/rust/rollup, r=alexcrichton
Diffstat (limited to 'src/libsyntax')
45 files changed, 1031 insertions, 868 deletions
diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index c366ced58b2..09235ee209c 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -47,7 +47,7 @@ pub enum Abi { } #[allow(non_camel_case_types)] -#[derive(Copy, PartialEq)] +#[derive(Copy, PartialEq, Show)] pub enum Architecture { X86, X86_64, @@ -121,12 +121,24 @@ 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 { + 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 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OsLinux => "linux".fmt(f), OsWindows => "windows".fmt(f), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 7aa7c4fcfb3..6766127a5f1 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -100,16 +100,29 @@ impl Ident { } } -impl Show for Ident { +//NOTE(stage0): remove after snapshot +impl fmt::Show for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}#{}", self.name, self.ctxt) } } -impl Show for Name { +impl fmt::String for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&self.name, f) + } +} + +impl fmt::Show for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Name(nm) = *self; - write!(f, "\"{}\"({})", token::get_name(*self).get(), nm) + write!(f, "{:?}({})", token::get_name(*self).get(), nm) + } +} + +impl fmt::String for Name { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(token::get_name(*self).get(), f) } } @@ -182,31 +195,15 @@ impl Name { /// A mark represents a unique id associated with a macro expansion pub type Mrk = u32; -#[cfg(stage0)] -impl<S: Encoder<E>, E> Encodable<S, E> for Ident { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(token::get_ident(*self).get()) - } -} - -#[cfg(not(stage0))] impl Encodable for Ident { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(token::get_ident(*self).get()) } } -#[cfg(stage0)] -impl<D: Decoder<E>, E> Decodable<D, E> for Ident { - fn decode(d: &mut D) -> Result<Ident, E> { - Ok(str_to_ident(try!(d.read_str())[])) - } -} - -#[cfg(not(stage0))] impl Decodable for Ident { fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> { - Ok(str_to_ident(try!(d.read_str())[])) + Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) } } @@ -883,7 +880,6 @@ impl TokenTree { pub fn len(&self) -> uint { match *self { TtToken(_, token::DocComment(_)) => 2, - TtToken(_, token::SubstNt(..)) => 2, TtToken(_, token::SpecialVarNt(..)) => 2, TtToken(_, token::MatchNt(..)) => 3, TtDelimited(_, ref delimed) => { @@ -921,11 +917,6 @@ impl TokenTree { } delimed.tts[index - 1].clone() } - (&TtToken(sp, token::SubstNt(name, name_st)), _) => { - let v = [TtToken(sp, token::Dollar), - TtToken(sp, token::Ident(name, name_st))]; - v[index] - } (&TtToken(sp, token::SpecialVarNt(var)), _) => { let v = [TtToken(sp, token::Dollar), TtToken(sp, token::Ident(token::str_to_ident(var.as_str()), @@ -982,8 +973,8 @@ pub enum Sign { Plus } -impl<T> Sign where T: Int { - pub fn new(n: T) -> Sign { +impl Sign { + pub fn new<T:Int>(n: T) -> Sign { if n < Int::zero() { Minus } else { @@ -1087,15 +1078,22 @@ pub struct Typedef { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] pub enum IntTy { - TyI, + TyIs, TyI8, TyI16, TyI32, TyI64, } +//NOTE(stage0): remove after snapshot impl fmt::Show for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::int_ty_to_string(*self, None)) } } @@ -1103,7 +1101,7 @@ impl fmt::Show for IntTy { impl IntTy { pub fn suffix_len(&self) -> uint { match *self { - TyI => 1, + TyIs => 1, TyI8 => 2, TyI16 | TyI32 | TyI64 => 3, } @@ -1112,7 +1110,7 @@ impl IntTy { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] pub enum UintTy { - TyU, + TyUs, TyU8, TyU16, TyU32, @@ -1122,15 +1120,22 @@ pub enum UintTy { impl UintTy { pub fn suffix_len(&self) -> uint { match *self { - TyU => 1, + TyUs => 1, TyU8 => 2, TyU16 | TyU32 | TyU64 => 3, } } } +//NOTE(stage0): remove after snapshot impl fmt::Show for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::uint_ty_to_string(*self, None)) } } @@ -1141,8 +1146,15 @@ pub enum FloatTy { TyF64, } +//NOTE(stage0): remove after snapshot impl fmt::Show for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::float_ty_to_string(*self)) } } @@ -1192,10 +1204,19 @@ pub enum Onceness { impl fmt::Show for Onceness { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Once => "once".fmt(f), - Many => "many".fmt(f), - } + fmt::String::fmt(match *self { + Once => "once", + Many => "many", + }, f) + } +} + +impl fmt::String for Onceness { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(match *self { + Once => "once", + Many => "many", + }, f) } } @@ -1305,18 +1326,18 @@ pub struct FnDecl { pub variadic: bool } -#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum Unsafety { Unsafe, Normal, } -impl fmt::Show for Unsafety { +impl fmt::String for Unsafety { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Unsafety::Normal => "normal".fmt(f), - Unsafety::Unsafe => "unsafe".fmt(f), - } + fmt::String::fmt(match *self { + Unsafety::Normal => "normal", + Unsafety::Unsafe => "unsafe", + }, f) } } diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index cf09e2777f7..7496a0f9f26 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -46,8 +46,15 @@ impl PathElem { } } +//NOTE(stage0): replace with deriving(Show) after snapshot impl fmt::Show for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for PathElem { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); write!(f, "{}", slot) } @@ -99,7 +106,7 @@ pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String { if !s.is_empty() { s.push_str("::"); } - s.push_str(e[]); + s.push_str(e.index(&FullRange)); s }).to_string() } @@ -396,7 +403,7 @@ impl<'ast> Map<'ast> { PathName(ident.name) } MethMac(_) => { - panic!("no path elem for {}", node) + panic!("no path elem for {:?}", node) } } } @@ -410,7 +417,7 @@ impl<'ast> Map<'ast> { MethDecl(ident, _, _, _, _, _, _, _) => { PathName(ident.name) } - MethMac(_) => panic!("no path elem for {}", node), + MethMac(_) => panic!("no path elem for {:?}", node), } } TypeTraitItem(ref m) => { @@ -418,7 +425,7 @@ impl<'ast> Map<'ast> { } }, NodeVariant(v) => PathName(v.node.name.name), - _ => panic!("no path elem for {}", node) + _ => panic!("no path elem for {:?}", node) } } @@ -476,20 +483,20 @@ impl<'ast> Map<'ast> { F: FnOnce(Option<&[Attribute]>) -> T, { let attrs = match self.get(id) { - NodeItem(i) => Some(i.attrs[]), - NodeForeignItem(fi) => Some(fi.attrs[]), + NodeItem(i) => Some(i.attrs.index(&FullRange)), + NodeForeignItem(fi) => Some(fi.attrs.index(&FullRange)), NodeTraitItem(ref tm) => match **tm { - RequiredMethod(ref type_m) => Some(type_m.attrs[]), - ProvidedMethod(ref m) => Some(m.attrs[]), - TypeTraitItem(ref typ) => Some(typ.attrs[]), + RequiredMethod(ref type_m) => Some(type_m.attrs.index(&FullRange)), + ProvidedMethod(ref m) => Some(m.attrs.index(&FullRange)), + TypeTraitItem(ref typ) => Some(typ.attrs.index(&FullRange)), }, NodeImplItem(ref ii) => { match **ii { - MethodImplItem(ref m) => Some(m.attrs[]), - TypeImplItem(ref t) => Some(t.attrs[]), + MethodImplItem(ref m) => Some(m.attrs.index(&FullRange)), + TypeImplItem(ref t) => Some(t.attrs.index(&FullRange)), } } - NodeVariant(ref v) => Some(v.node.attrs[]), + NodeVariant(ref v) => Some(v.node.attrs.index(&FullRange)), // unit/tuple structs take the attributes straight from // the struct definition. // FIXME(eddyb) make this work again (requires access to the map). @@ -513,7 +520,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: parts[..parts.len() - 1], + in_which: parts.index(&(0..(parts.len() - 1))), idx: 0, } } @@ -549,7 +556,7 @@ impl<'ast> Map<'ast> { pub fn span(&self, id: NodeId) -> Span { self.opt_span(id) - .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {}", id)) + .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id)) } pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span { @@ -590,7 +597,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { None => return false, Some((node_id, name)) => (node_id, name), }; - if part[] != mod_name.as_str() { + if part.index(&FullRange) != mod_name.as_str() { return false; } cursor = self.map.get_parent(mod_id); @@ -628,7 +635,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { // We are looking at some node `n` with a given name and parent // id; do their names match what I am seeking? fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool { - name.as_str() == self.item_name[] && + name.as_str() == self.item_name.index(&FullRange) && self.suffix_matches(parent_of_n) } } @@ -729,7 +736,7 @@ struct NodeCollector<'ast> { impl<'ast> NodeCollector<'ast> { fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) { - debug!("ast_map: {} => {}", id, entry); + 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)); @@ -1040,7 +1047,7 @@ impl<'a> NodePrinter for pprust::State<'a> { fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { let id_str = format!(" (id={})", id); - let id_str = if include_id { id_str[] } else { "" }; + let id_str = if include_id { id_str.index(&FullRange) } else { "" }; match map.find(id) { Some(NodeItem(item)) => { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 5e03afec16c..871f1237aee 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -120,8 +120,8 @@ pub fn is_path(e: P<Expr>) -> bool { /// We want to avoid "45int" and "-3int" in favor of "45" and "-3" pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { - TyI if val.is_some() => "i", - TyI => "int", + TyIs if val.is_some() => "is", + TyIs => "isize", TyI8 => "i8", TyI16 => "i16", TyI32 => "i32", @@ -141,7 +141,7 @@ pub fn int_ty_max(t: IntTy) -> u64 { match t { TyI8 => 0x80u64, TyI16 => 0x8000u64, - TyI | TyI32 => 0x80000000u64, // actually ni about TyI + TyIs | TyI32 => 0x80000000u64, // actually ni about TyIs TyI64 => 0x8000000000000000u64 } } @@ -150,8 +150,8 @@ pub fn int_ty_max(t: IntTy) -> u64 { /// We want to avoid "42uint" in favor of "42u" pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String { let s = match t { - TyU if val.is_some() => "u", - TyU => "uint", + TyUs if val.is_some() => "us", + TyUs => "usize", TyU8 => "u8", TyU16 => "u16", TyU32 => "u32", @@ -168,7 +168,7 @@ pub fn uint_ty_max(t: UintTy) -> u64 { match t { TyU8 => 0xffu64, TyU16 => 0xffffu64, - TyU | TyU32 => 0xffffffffu64, // actually ni about TyU + TyUs | TyU32 => 0xffffffffu64, // actually ni about TyUs TyU64 => 0xffffffffffffffffu64 } } @@ -238,11 +238,11 @@ pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident { match *trait_ref { Some(ref trait_ref) => { pretty.push('.'); - pretty.push_str(pprust::path_to_string(&trait_ref.path)[]); + pretty.push_str(pprust::path_to_string(&trait_ref.path).index(&FullRange)); } None => {} } - token::gensym_ident(pretty[]) + token::gensym_ident(pretty.index(&FullRange)) } pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod { @@ -704,7 +704,7 @@ pub fn pat_is_ident(pat: P<ast::Pat>) -> bool { pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool { (a.span == b.span) && (a.global == b.global) - && (segments_name_eq(a.segments[], b.segments[])) + && (segments_name_eq(a.segments.index(&FullRange), b.segments.index(&FullRange))) } // are two arrays of segments equal when compared unhygienically? @@ -792,13 +792,13 @@ mod test { #[test] fn idents_name_eq_test() { assert!(segments_name_eq( [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange), [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange))); assert!(!segments_name_eq( [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange), [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange))); } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 43e23f26e93..416fc8c2278 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -28,6 +28,7 @@ use ptr::P; use std::cell::{RefCell, Cell}; use std::collections::BitvSet; use std::collections::HashSet; +use std::fmt; thread_local! { static USED_ATTRS: RefCell<BitvSet> = RefCell::new(BitvSet::new()) } @@ -97,7 +98,7 @@ impl AttrMetaMethods for MetaItem { fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> { match self.node { - MetaList(_, ref l) => Some(l[]), + MetaList(_, ref l) => Some(l.index(&FullRange)), _ => None } } @@ -136,7 +137,7 @@ impl AttributeMethods for Attribute { let meta = mk_name_value_item_str( InternedString::new("doc"), token::intern_and_get_ident(strip_doc_comment_decoration( - comment.get())[])); + comment.get()).index(&FullRange))); if self.node.style == ast::AttrOuter { f(&mk_attr_outer(self.node.id, meta)) } else { @@ -296,9 +297,9 @@ pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr { } MetaList(ref n, ref items) if *n == "inline" => { mark_used(attr); - if contains_name(items[], "always") { + if contains_name(items.index(&FullRange), "always") { InlineAlways - } else if contains_name(items[], "never") { + } else if contains_name(items.index(&FullRange), "never") { InlineNever } else { InlineHint @@ -332,7 +333,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::Me !cfg_matches(diagnostic, cfgs, &*mis[0]) } ast::MetaList(ref pred, _) => { - diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred)[]); + diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice()); false }, ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg), @@ -357,6 +358,12 @@ pub enum StabilityLevel { Locked } +impl fmt::String for StabilityLevel { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Show::fmt(self, f) + } +} + pub fn find_stability_generic<'a, AM: AttrMetaMethods, I: Iterator<Item=&'a AM>> @@ -396,7 +403,7 @@ pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) { if !set.insert(name.clone()) { diagnostic.span_fatal(meta.span, - format!("duplicate meta item `{}`", name)[]); + format!("duplicate meta item `{}`", name).index(&FullRange)); } } } @@ -457,8 +464,10 @@ fn int_type_of_word(s: &str) -> Option<IntType> { "u32" => Some(UnsignedInt(ast::TyU32)), "i64" => Some(SignedInt(ast::TyI64)), "u64" => Some(UnsignedInt(ast::TyU64)), - "int" => Some(SignedInt(ast::TyI)), - "uint" => Some(UnsignedInt(ast::TyU)), + "int" => Some(SignedInt(ast::TyIs)), + "uint" => Some(UnsignedInt(ast::TyUs)), + "isize" => Some(SignedInt(ast::TyIs)), + "usize" => Some(UnsignedInt(ast::TyUs)), _ => None } } @@ -502,7 +511,7 @@ impl IntType { SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) | SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) | SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true, - SignedInt(ast::TyI) | UnsignedInt(ast::TyU) => false + SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false } } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index a49f2614cd7..31fe23847d9 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -120,15 +120,6 @@ impl PartialEq for Span { impl Eq for Span {} -#[cfg(stage0)] -impl<S:Encoder<E>, E> Encodable<S, E> for Span { - /* Note #1972 -- spans are encoded but not decoded */ - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_nil() - } -} - -#[cfg(not(stage0))] impl Encodable for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { @@ -136,14 +127,6 @@ impl Encodable for Span { } } -#[cfg(stage0)] -impl<D:Decoder<E>, E> Decodable<D, E> for Span { - fn decode(_d: &mut D) -> Result<Span, E> { - Ok(DUMMY_SP) - } -} - -#[cfg(not(stage0))] impl Decodable for Span { fn decode<D: Decoder>(_d: &mut D) -> Result<Span, D::Error> { Ok(DUMMY_SP) @@ -321,9 +304,9 @@ impl FileMap { lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; let begin = begin.to_uint(); - let slice = self.src[begin..]; + let slice = self.src.index(&(begin..)); match slice.find('\n') { - Some(e) => slice[0..e], + Some(e) => slice.index(&(0..e)), None => slice }.to_string() }) @@ -368,9 +351,9 @@ impl CodeMap { // FIXME #12884: no efficient/safe way to remove from the start of a string // and reuse the allocation. let mut src = if src.starts_with("\u{feff}") { - String::from_str(src[3..]) + String::from_str(src.index(&(3..))) } else { - String::from_str(src[]) + String::from_str(src.index(&FullRange)) }; // Append '\n' in case it's not already there. @@ -457,8 +440,8 @@ 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.index(&(begin.pos.to_uint().. + end.pos.to_uint())).to_string()) } } @@ -488,7 +471,7 @@ impl CodeMap { let mut total_extra_bytes = 0; for mbc in map.multibyte_chars.borrow().iter() { - debug!("{}-byte char at {}", mbc.bytes, mbc.pos); + debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { // every character is at least one byte, so we only // count the actual extra bytes. @@ -566,9 +549,9 @@ impl CodeMap { let chpos = self.bytepos_to_file_charpos(pos); let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); - debug!("byte pos {} is on the line at byte pos {}", + debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); - debug!("char pos {} is on the line at char pos {}", + debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("byte is on line: {}", line); assert!(chpos >= linechpos); diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index c19c06c3155..fde2fdb3c55 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -123,7 +123,7 @@ impl SpanHandler { panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { - self.span_bug(sp, format!("unimplemented {}", msg)[]); + self.span_bug(sp, format!("unimplemented {}", msg).index(&FullRange)); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler @@ -166,7 +166,7 @@ impl Handler { self.err_count.get()); } } - self.fatal(s[]); + self.fatal(s.index(&FullRange)); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); @@ -182,7 +182,7 @@ impl Handler { panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) -> ! { - self.bug(format!("unimplemented {}", msg)[]); + self.bug(format!("unimplemented {}", msg).index(&FullRange)); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, @@ -222,7 +222,7 @@ pub fn mk_handler(e: Box<Emitter + Send>) -> Handler { } } -#[derive(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, @@ -232,9 +232,9 @@ pub enum Level { Help, } -impl fmt::Show for Level { +impl fmt::String for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Show; + use std::fmt::String; match *self { Bug => "error: internal compiler error".fmt(f), @@ -277,7 +277,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[0..msg.len()-1])); + try!(t.write_str(msg.index(&(0..(msg.len()-1))))); try!(t.reset()); try!(t.write_str("\n")); } else { @@ -299,16 +299,16 @@ fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, } try!(print_maybe_styled(dst, - format!("{}: ", lvl.to_string())[], + format!("{}: ", lvl.to_string()).index(&FullRange), term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, - format!("{}", msg)[], + format!("{}", msg).index(&FullRange), term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); - try!(print_maybe_styled(dst, format!(" [{}]", code.clone())[], style)); + try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).index(&FullRange), style)); } None => () } @@ -374,7 +374,7 @@ impl Emitter for EmitterWriter { match error { Ok(()) => {} - Err(e) => panic!("failed to print diagnostics: {}", e), + Err(e) => panic!("failed to print diagnostics: {:?}", e), } } @@ -382,7 +382,7 @@ impl Emitter for EmitterWriter { sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} - Err(e) => panic!("failed to print diagnostics: {}", e), + Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } @@ -398,12 +398,12 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); - try!(print_diagnostic(dst, ses[], lvl, msg, code)); + try!(print_diagnostic(dst, ses.index(&FullRange), lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, lines)); } } else { - try!(print_diagnostic(dst, ss[], lvl, msg, code)); + try!(print_diagnostic(dst, ss.index(&FullRange), lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, lines)); } @@ -413,9 +413,9 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { - try!(print_diagnostic(dst, ss[], Help, + try!(print_diagnostic(dst, ss.index(&FullRange), Help, format!("pass `--explain {}` to see a detailed \ - explanation", code)[], None)); + explanation", code).index(&FullRange), None)); } None => () }, @@ -432,9 +432,9 @@ fn highlight_lines(err: &mut EmitterWriter, let fm = &*lines.file; let mut elided = false; - let mut display_lines = lines.lines[]; + let mut display_lines = lines.lines.index(&FullRange); if display_lines.len() > MAX_LINES { - display_lines = display_lines[0u..MAX_LINES]; + display_lines = display_lines.index(&(0u..MAX_LINES)); elided = true; } // Print the offending lines @@ -494,7 +494,7 @@ fn highlight_lines(err: &mut EmitterWriter, } } try!(print_maybe_styled(err, - format!("{}\n", s)[], + format!("{}\n", s).index(&FullRange), term::attr::ForegroundColor(lvl.color()))); } Ok(()) @@ -514,7 +514,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, -> io::IoResult<()> { let fm = &*lines.file; - let lines = lines.lines[]; + let lines = lines.lines.index(&FullRange); if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, @@ -545,7 +545,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, s.push('^'); s.push('\n'); print_maybe_styled(w, - s[], + s.index(&FullRange), term::attr::ForegroundColor(lvl.color())) } @@ -560,12 +560,12 @@ fn print_macro_backtrace(w: &mut EmitterWriter, codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; - try!(print_diagnostic(w, ss[], Note, + try!(print_diagnostic(w, ss.index(&FullRange), Note, format!("in expansion of {}{}{}", pre, ei.callee.name, - post)[], None)); + post).index(&FullRange), None)); let ss = cm.span_to_string(ei.call_site); - try!(print_diagnostic(w, ss[], Note, "expansion site", None)); + try!(print_diagnostic(w, ss.index(&FullRange), Note, "expansion site", None)); Ok(Some(ei.call_site)) } None => Ok(None) @@ -578,6 +578,6 @@ pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where { match opt { Some(t) => t, - None => diag.handler().bug(msg()[]), + None => diag.handler().bug(msg().index(&FullRange)), } } diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 720a907fe77..0f4ebd74b66 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -58,7 +58,7 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, Some(previous_span) => { ecx.span_warn(span, format!( "diagnostic code {} already used", token::get_ident(code).get() - )[]); + ).index(&FullRange)); ecx.span_note(previous_span, "previous invocation"); }, None => () @@ -87,12 +87,12 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, if diagnostics.insert(code.name, description).is_some() { ecx.span_err(span, format!( "diagnostic code {} already registered", token::get_ident(*code).get() - )[]); + ).index(&FullRange)); } }); let sym = Ident::new(token::gensym(( "__register_diagnostic_".to_string() + token::get_ident(*code).get() - )[])); + ).index(&FullRange))); MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter()) } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index b77b822a6b2..04dec0e8028 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -100,7 +100,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(('=', _)) => None, Some(('+', operand)) => { Some(token::intern_and_get_ident(format!( - "={}", operand)[])) + "={}", operand).index(&FullRange))) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 91ae7396ea4..52e402689ba 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -539,7 +539,7 @@ impl<'a> ExtCtxt<'a> { pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); } pub fn mod_path(&self) -> Vec<ast::Ident> { let mut v = Vec::new(); - v.push(token::str_to_ident(self.ecfg.crate_name[])); + v.push(token::str_to_ident(self.ecfg.crate_name.index(&FullRange))); v.extend(self.mod_path.iter().map(|a| *a)); return v; } @@ -548,7 +548,7 @@ impl<'a> ExtCtxt<'a> { if self.recursion_count > self.ecfg.recursion_limit { self.span_fatal(ei.call_site, format!("recursion limit reached while expanding the macro `{}`", - ei.callee.name)[]); + ei.callee.name).index(&FullRange)); } let mut call_site = ei.call_site; @@ -670,7 +670,7 @@ pub fn check_zero_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], name: &str) { if tts.len() != 0 { - cx.span_err(sp, format!("{} takes no arguments", name)[]); + cx.span_err(sp, format!("{} takes no arguments", name).index(&FullRange)); } } @@ -683,12 +683,12 @@ pub fn get_single_str_from_tts(cx: &mut ExtCtxt, -> Option<String> { let mut p = cx.new_parser_from_tts(tts); if p.token == token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name)[]); + cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); return None } let ret = cx.expander().fold_expr(p.parse_expr()); if p.token != token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name)[]); + cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); } expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| { s.get().to_string() diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index ea345f3a458..bd4f295401c 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -642,10 +642,10 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.expr(sp, ast::ExprLit(P(respan(sp, lit)))) } fn expr_uint(&self, span: Span, i: uint) -> P<ast::Expr> { - self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyU))) + self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs))) } fn expr_int(&self, sp: Span, i: int) -> P<ast::Expr> { - self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyI, ast::Sign::new(i)))) + self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyIs, ast::Sign::new(i)))) } fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr> { self.expr_lit(sp, ast::LitInt(u as u64, ast::UnsignedIntLit(ast::TyU8))) @@ -709,7 +709,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[])); + .name.index(&FullRange))); let expr_line = self.expr_uint(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); diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 03dd08fdf7f..1f1781dceb3 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -40,14 +40,14 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, ast::LitInt(i, ast::UnsignedIntLit(_)) | ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => { - accumulator.push_str(format!("{}", i)[]); + accumulator.push_str(format!("{}", i).index(&FullRange)); } ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => { - accumulator.push_str(format!("-{}", i)[]); + accumulator.push_str(format!("-{}", i).index(&FullRange)); } ast::LitBool(b) => { - accumulator.push_str(format!("{}", b)[]); + accumulator.push_str(format!("{}", b).index(&FullRange)); } ast::LitByte(..) | ast::LitBinary(..) => { @@ -62,5 +62,5 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, } base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(accumulator[]))) + token::intern_and_get_ident(accumulator.index(&FullRange)))) } diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 2cf60d30a1b..02f702248cb 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -40,7 +40,7 @@ pub fn expand_syntax_ext<'cx>(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree] } } } - let res = str_to_ident(res_str[]); + let res = str_to_ident(res_str.index(&FullRange)); let e = P(ast::Expr { id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/ext/deriving/bounds.rs b/src/libsyntax/ext/deriving/bounds.rs index cf29bb048d6..8ac7e57bb81 100644 --- a/src/libsyntax/ext/deriving/bounds.rs +++ b/src/libsyntax/ext/deriving/bounds.rs @@ -29,12 +29,13 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt, "Send" | "Sync" => { return cx.span_err(span, format!("{} is an unsafe trait and it \ - should be implemented explicitly", *tname)[]) + should be implemented explicitly", + *tname).as_slice()) } ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ - found {}", *tname)[]) + found {}", *tname).as_slice()) } } }, @@ -47,7 +48,7 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt, let trait_def = TraitDef { span: span, attributes: Vec::new(), - path: Path::new(vec!("std", "kinds", name)), + path: Path::new(vec!("std", "marker", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 3c74a9f4431..d9d6cebd05c 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -80,11 +80,11 @@ fn cs_clone( EnumNonMatchingCollapsed (..) => { cx.span_bug(trait_span, format!("non-matching enum variants in \ - `deriving({})`", name)[]) + `deriving({})`", name).index(&FullRange)) } StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, - format!("static method in `deriving({})`", name)[]) + format!("static method in `deriving({})`", name).index(&FullRange)) } } @@ -101,7 +101,7 @@ fn cs_clone( None => { cx.span_bug(trait_span, format!("unnamed field in normal struct in \ - `deriving({})`", name)[]) + `deriving({})`", name).index(&FullRange)) } }; cx.field_imm(field.span, ident, subcall(field)) diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 8094f0d3de8..a9289f0175a 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -198,7 +198,7 @@ fn decode_static_fields<F>(cx: &mut ExtCtxt, let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(format!("_field{}", - i)[]), + i).index(&FullRange)), i) }).collect(); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 0fceb0fbfda..7114217d51d 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -183,7 +183,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let name = match name { Some(id) => token::get_ident(id), None => { - token::intern_and_get_ident(format!("_field{}", i)[]) + token::intern_and_get_ident(format!("_field{}", i).index(&FullRange)) } }; let enc = cx.expr_method_call(span, self_.clone(), diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 1aa430c4a08..50b3559f369 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -510,15 +510,15 @@ impl<'a> TraitDef<'a> { self, struct_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) } else { method_def.expand_struct_method_body(cx, self, struct_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) }; method_def.create_method(cx, @@ -550,15 +550,15 @@ impl<'a> TraitDef<'a> { self, enum_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) } else { method_def.expand_enum_method_body(cx, self, enum_def, type_ident, self_args, - nonself_args[]) + nonself_args.index(&FullRange)) }; method_def.create_method(cx, @@ -602,7 +602,7 @@ impl<'a> MethodDef<'a> { }; let mut f = self.combine_substructure.borrow_mut(); let f: &mut CombineSubstructureFunc = &mut *f; - f.call_mut((cx, trait_.span, &substructure)) + f(cx, trait_.span, &substructure) } fn get_ret_ty(&self, @@ -645,7 +645,7 @@ impl<'a> MethodDef<'a> { for (i, ty) in self.args.iter().enumerate() { let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics); - let ident = cx.ident_of(format!("__arg_{}", i)[]); + let ident = cx.ident_of(format!("__arg_{}", i).index(&FullRange)); arg_tys.push((ident, ast_ty)); let arg_expr = cx.expr_ident(trait_.span, ident); @@ -752,7 +752,7 @@ impl<'a> MethodDef<'a> { struct_path, struct_def, format!("__self_{}", - i)[], + i).index(&FullRange), ast::MutImmutable); patterns.push(pat); raw_fields.push(ident_expr); @@ -908,22 +908,22 @@ impl<'a> MethodDef<'a> { .collect::<Vec<String>>(); let self_arg_idents = self_arg_names.iter() - .map(|name|cx.ident_of(name[])) + .map(|name|cx.ident_of(name.index(&FullRange))) .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 // corresponding to its variant index. let vi_idents: Vec<ast::Ident> = self_arg_names.iter() - .map(|name| { let vi_suffix = format!("{}_vi", name[]); - cx.ident_of(vi_suffix[]) }) + .map(|name| { let vi_suffix = format!("{}_vi", name.index(&FullRange)); + cx.ident_of(vi_suffix.index(&FullRange)) }) .collect::<Vec<ast::Ident>>(); // Builds, via callback to call_substructure_method, the // delegated expression that handles the catch-all case, // using `__variants_tuple` to drive logic if necessary. let catch_all_substructure = EnumNonMatchingCollapsed( - self_arg_idents, variants[], vi_idents[]); + self_arg_idents, variants.index(&FullRange), vi_idents.index(&FullRange)); // These arms are of the form: // (Variant1, Variant1, ...) => Body1 @@ -945,12 +945,12 @@ impl<'a> MethodDef<'a> { let mut subpats = Vec::with_capacity(self_arg_names.len()); let mut self_pats_idents = Vec::with_capacity(self_arg_names.len() - 1); let first_self_pat_idents = { - let (p, idents) = mk_self_pat(cx, self_arg_names[0][]); + let (p, idents) = mk_self_pat(cx, self_arg_names[0].index(&FullRange)); subpats.push(p); idents }; for self_arg_name in self_arg_names.tail().iter() { - let (p, idents) = mk_self_pat(cx, self_arg_name[]); + let (p, idents) = mk_self_pat(cx, self_arg_name.index(&FullRange)); subpats.push(p); self_pats_idents.push(idents); } @@ -1006,7 +1006,7 @@ impl<'a> MethodDef<'a> { &**variant, field_tuples); let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args[], nonself_args, + cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, &substructure); cx.arm(sp, vec![single_pat], arm_expr) @@ -1031,7 +1031,7 @@ impl<'a> MethodDef<'a> { let arms: Vec<ast::Arm> = variants.iter().enumerate() .map(|(index, variant)| { let pat = variant_to_pat(cx, sp, type_ident, &**variant); - let lit = ast::LitInt(index as u64, ast::UnsignedIntLit(ast::TyU)); + let lit = ast::LitInt(index as u64, ast::UnsignedIntLit(ast::TyUs)); cx.arm(sp, vec![pat], cx.expr_lit(sp, lit)) }).collect(); @@ -1059,7 +1059,7 @@ impl<'a> MethodDef<'a> { } let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args[], nonself_args, + cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, &catch_all_substructure); // Builds the expression: @@ -1263,7 +1263,7 @@ impl<'a> TraitDef<'a> { cx.span_bug(sp, "a struct with named and unnamed fields in `derive`"); } }; - let ident = cx.ident_of(format!("{}_{}", prefix, i)[]); + let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); paths.push(codemap::Spanned{span: sp, node: ident}); let val = cx.expr( sp, ast::ExprParen(cx.expr_deref(sp, cx.expr_path(cx.path_ident(sp,ident))))); @@ -1309,7 +1309,7 @@ impl<'a> TraitDef<'a> { let mut ident_expr = Vec::new(); for (i, va) in variant_args.iter().enumerate() { let sp = self.set_expn_info(cx, va.ty.span); - let ident = cx.ident_of(format!("{}_{}", prefix, i)[]); + let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); let path1 = codemap::Spanned{span: sp, node: ident}; paths.push(path1); let expr_path = cx.expr_path(cx.path_ident(sp, ident)); @@ -1352,7 +1352,7 @@ pub fn cs_fold<F>(use_foldl: bool, field.span, old, field.self_.clone(), - field.other[]) + field.other.index(&FullRange)) }) } else { all_fields.iter().rev().fold(base, |old, field| { @@ -1360,13 +1360,13 @@ pub fn cs_fold<F>(use_foldl: bool, field.span, old, field.self_.clone(), - field.other[]) + field.other.index(&FullRange)) }) } }, EnumNonMatchingCollapsed(ref all_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_args[], tuple), - substructure.nonself_args)), + enum_nonmatch_f(cx, trait_span, (all_args.index(&FullRange), tuple), + substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") } @@ -1405,8 +1405,8 @@ pub fn cs_same_method<F>(f: F, f(cx, trait_span, called) }, EnumNonMatchingCollapsed(ref all_self_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_self_args[], tuple), - substructure.nonself_args)), + enum_nonmatch_f(cx, trait_span, (all_self_args.index(&FullRange), tuple), + substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") } diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index e72c83b67c8..43a0e0606f8 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -73,7 +73,7 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, MetaWord(ref tname) => { macro_rules! expand { ($func:path) => ($func(cx, titem.span, &**titem, item, - |i| push.call_mut((i,)))) + |i| push(i))) } match tname.get() { @@ -123,7 +123,7 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, cx.span_err(titem.span, format!("unknown `derive` \ trait: `{}`", - *tname)[]); + *tname).index(&FullRange)); } }; } diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index eceac4e9a83..fa9a7899a12 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -90,7 +90,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, for (i, field) in fields.iter().enumerate() { if i != 0 { format_string.push_str(", "); } - format_string.push_str("{}"); + format_string.push_str("{:?}"); exprs.push(field.self_.clone()); } @@ -107,7 +107,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, let name = token::get_ident(field.name.unwrap()); format_string.push_str(" "); format_string.push_str(name.get()); - format_string.push_str(": {}"); + format_string.push_str(": {:?}"); exprs.push(field.self_.clone()); } @@ -127,7 +127,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, let formatter = substr.nonself_args[0].clone(); let meth = cx.ident_of("write_fmt"); - let s = token::intern_and_get_ident(format_string[]); + let s = token::intern_and_get_ident(format_string.index(&FullRange)); let format_string = cx.expr_str(span, s); // phew, not our responsibility any more! diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9fedc4a158e..eb3544e3c5c 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -30,7 +30,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT Some(v) => v }; - let e = match os::getenv(var[]) { + let e = match os::getenv(var.index(&FullRange)) { None => { cx.expr_path(cx.path_all(sp, true, @@ -56,7 +56,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT cx.ident_of("Some")), vec!(cx.expr_str(sp, token::intern_and_get_ident( - s[])))) + s.index(&FullRange))))) } }; MacExpr::new(e) @@ -83,7 +83,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => { token::intern_and_get_ident(format!("environment variable `{}` \ not defined", - var)[]) + var).index(&FullRange)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { @@ -106,7 +106,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) cx.span_err(sp, msg.get()); cx.expr_uint(sp, 0) } - Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s[])) + Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s.index(&FullRange))) }; MacExpr::new(e) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 212ec3b0903..3e1bccf394a 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -36,7 +36,7 @@ pub fn expand_type(t: P<ast::Ty>, fld: &mut MacroExpander, impl_ty: Option<P<ast::Ty>>) -> P<ast::Ty> { - debug!("expanding type {} with impl_ty {}", t, impl_ty); + debug!("expanding type {:?} with impl_ty {:?}", t, impl_ty); let t = match (t.node.clone(), impl_ty) { // Expand uses of `Self` in impls to the concrete type. (ast::Ty_::TyPath(ref path, _), Some(ref impl_ty)) => { @@ -287,7 +287,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("macro undefined: '{}!'", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); // let compilation continue None @@ -303,7 +303,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, }, }); let fm = fresh_mark(); - let marked_before = mark_tts(tts[], fm); + let marked_before = mark_tts(tts.index(&FullRange), fm); // The span that we pass to the expanders we want to // be the root of the call stack. That's the most @@ -314,7 +314,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, let opt_parsed = { let expanded = expandfun.expand(fld.cx, mac_span, - marked_before[]); + marked_before.index(&FullRange)); parse_thunk(expanded) }; let parsed = match opt_parsed { @@ -323,8 +323,8 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("non-expression macro in expression position: {}", - extnamestr.get()[] - )[]); + extnamestr.get().index(&FullRange) + ).index(&FullRange)); return None; } }; @@ -334,7 +334,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("'{}' is not a tt-style macro", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); None } } @@ -439,7 +439,7 @@ pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander) if valid_ident { fld.cx.mod_push(it.ident); } - let macro_use = contains_macro_use(fld, new_attrs[]); + let macro_use = contains_macro_use(fld, new_attrs.index(&FullRange)); let result = with_exts_frame!(fld.cx.syntax_env, macro_use, noop_fold_item(it, fld)); @@ -566,7 +566,7 @@ pub fn expand_item_mac(it: P<ast::Item>, None => { fld.cx.span_err(path_span, format!("macro undefined: '{}!'", - extnamestr)[]); + extnamestr).index(&FullRange)); // let compilation continue return SmallVector::zero(); } @@ -579,7 +579,7 @@ pub fn expand_item_mac(it: P<ast::Item>, format!("macro {}! expects no ident argument, \ given '{}'", extnamestr, - token::get_ident(it.ident))[]); + token::get_ident(it.ident)).index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -591,14 +591,14 @@ pub fn expand_item_mac(it: P<ast::Item>, } }); // mark before expansion: - let marked_before = mark_tts(tts[], fm); - expander.expand(fld.cx, it.span, marked_before[]) + let marked_before = mark_tts(tts.index(&FullRange), fm); + expander.expand(fld.cx, it.span, marked_before.index(&FullRange)) } IdentTT(ref expander, span) => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, format!("macro {}! expects an ident argument", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -610,13 +610,14 @@ pub fn expand_item_mac(it: P<ast::Item>, } }); // mark before expansion: - let marked_tts = mark_tts(tts[], fm); + let marked_tts = mark_tts(tts.index(&FullRange), fm); expander.expand(fld.cx, it.span, it.ident, marked_tts) } MacroRulesTT => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, - format!("macro_rules! expects an ident argument")[]); + format!("macro_rules! expects an ident argument") + .index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -648,7 +649,7 @@ pub fn expand_item_mac(it: P<ast::Item>, _ => { fld.cx.span_err(it.span, format!("{}! is not legal in item position", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } } @@ -667,7 +668,7 @@ pub fn expand_item_mac(it: P<ast::Item>, None => { fld.cx.span_err(path_span, format!("non-item macro in item position: {}", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } }; @@ -913,7 +914,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { None => { fld.cx.span_err(pth.span, format!("macro undefined: '{}!'", - extnamestr)[]); + extnamestr).index(&FullRange)); // let compilation continue return DummyResult::raw_pat(span); } @@ -930,11 +931,11 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { }); let fm = fresh_mark(); - let marked_before = mark_tts(tts[], fm); + let marked_before = mark_tts(tts.index(&FullRange), fm); let mac_span = fld.cx.original_span(); let expanded = match expander.expand(fld.cx, mac_span, - marked_before[]).make_pat() { + marked_before.index(&FullRange)).make_pat() { Some(e) => e, None => { fld.cx.span_err( @@ -942,7 +943,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { format!( "non-pattern macro in pattern position: {}", extnamestr.get() - )[] + ).index(&FullRange) ); return DummyResult::raw_pat(span); } @@ -954,7 +955,7 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { _ => { fld.cx.span_err(span, format!("{}! is not legal in pattern position", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return DummyResult::raw_pat(span); } } @@ -1231,7 +1232,7 @@ impl Folder for Marker { node: match node { MacInvocTT(path, tts, ctxt) => { MacInvocTT(self.fold_path(path), - self.fold_tts(tts[]), + self.fold_tts(tts.index(&FullRange)), mtwt::apply_mark(self.mark, ctxt)) } }, @@ -1712,7 +1713,7 @@ foo_module!(); let string = ident.get(); "xx" == string }).collect(); - let cxbinds: &[&ast::Ident] = cxbinds[]; + let cxbinds: &[&ast::Ident] = cxbinds.index(&FullRange); let cxbind = match cxbinds { [b] => b, _ => panic!("expected just one binding for ext_cx") diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 1f39555f496..44a596d2657 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -113,7 +113,7 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) _ => { ecx.span_err(p.span, format!("expected ident for named argument, found `{}`", - p.this_token_to_string())[]); + p.this_token_to_string()).index(&FullRange)); return None; } }; @@ -126,7 +126,7 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(prev) => { ecx.span_err(e.span, format!("duplicate argument named `{}`", - name)[]); + name).index(&FullRange)); ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here"); continue } @@ -217,7 +217,7 @@ impl<'a, 'b> Context<'a, 'b> { let msg = format!("invalid reference to argument `{}` ({})", arg, self.describe_num_args()); - self.ecx.span_err(self.fmtsp, msg[]); + self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); return; } { @@ -237,7 +237,7 @@ impl<'a, 'b> Context<'a, 'b> { Some(e) => e.span, None => { let msg = format!("there is no argument named `{}`", name); - self.ecx.span_err(self.fmtsp, msg[]); + self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); return; } }; @@ -280,19 +280,19 @@ impl<'a, 'b> Context<'a, 'b> { format!("argument redeclared with type `{}` when \ it was previously `{}`", *ty, - *cur)[]); + *cur).index(&FullRange)); } (&Known(ref cur), _) => { self.ecx.span_err(sp, format!("argument used to format with `{}` was \ attempted to not be used for formatting", - *cur)[]); + *cur).index(&FullRange)); } (_, &Known(ref ty)) => { self.ecx.span_err(sp, format!("argument previously used as a format \ argument attempted to be used as `{}`", - *ty)[]); + *ty).index(&FullRange)); } (_, _) => { self.ecx.span_err(sp, "argument declared with multiple formats"); @@ -357,7 +357,7 @@ impl<'a, 'b> Context<'a, 'b> { /// Translate the accumulated string literals to a literal expression fn trans_literal_string(&mut self) -> P<ast::Expr> { let sp = self.fmtsp; - let s = token::intern_and_get_ident(self.literal[]); + let s = token::intern_and_get_ident(self.literal.index(&FullRange)); self.literal.clear(); self.ecx.expr_str(sp, s) } @@ -509,7 +509,7 @@ impl<'a, 'b> Context<'a, 'b> { None => continue // error already generated }; - let name = self.ecx.ident_of(format!("__arg{}", i)[]); + let name = self.ecx.ident_of(format!("__arg{}", i).index(&FullRange)); pats.push(self.ecx.pat_ident(e.span, name)); locals.push(Context::format_arg(self.ecx, e.span, arg_ty, self.ecx.expr_ident(e.span, name))); @@ -526,7 +526,7 @@ impl<'a, 'b> Context<'a, 'b> { }; let lname = self.ecx.ident_of(format!("__arg{}", - *name)[]); + *name).index(&FullRange)); pats.push(self.ecx.pat_ident(e.span, lname)); names[self.name_positions[*name]] = Some(Context::format_arg(self.ecx, e.span, arg_ty, @@ -606,8 +606,8 @@ impl<'a, 'b> Context<'a, 'b> { -> P<ast::Expr> { let trait_ = match *ty { Known(ref tyname) => { - match tyname[] { - "" => "Show", + match tyname.index(&FullRange) { + "" => "String", "?" => "Show", "e" => "LowerExp", "E" => "UpperExp", @@ -619,7 +619,7 @@ impl<'a, 'b> Context<'a, 'b> { _ => { ecx.span_err(sp, format!("unknown format trait `{}`", - *tyname)[]); + *tyname).index(&FullRange)); "Dummy" } } @@ -710,7 +710,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, } if !parser.errors.is_empty() { cx.ecx.span_err(cx.fmtsp, format!("invalid format string: {}", - parser.errors.remove(0))[]); + parser.errors.remove(0)).index(&FullRange)); return DummyResult::raw_expr(sp); } if !cx.literal.is_empty() { diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 4075b208f78..bebd803ac4f 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -66,7 +66,7 @@ pub fn apply_mark(m: Mrk, ctxt: SyntaxContext) -> SyntaxContext { /// Extend a syntax context with a given mark and sctable (explicit memoization) fn apply_mark_internal(m: Mrk, ctxt: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (ctxt, m); - * table.mark_memo.borrow_mut().entry(&key).get().unwrap_or_else( + * table.mark_memo.borrow_mut().entry(key).get().unwrap_or_else( |vacant_entry| vacant_entry.insert(idx_push(&mut *table.table.borrow_mut(), Mark(m, ctxt)))) } @@ -84,7 +84,7 @@ fn apply_rename_internal(id: Ident, table: &SCTable) -> SyntaxContext { let key = (ctxt, id, to); - * table.rename_memo.borrow_mut().entry(&key).get().unwrap_or_else( + * table.rename_memo.borrow_mut().entry(key).get().unwrap_or_else( |vacant_entry| vacant_entry.insert(idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt)))) } @@ -121,7 +121,7 @@ fn new_sctable_internal() -> SCTable { pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { - error!("{:4} : {}",idx,val); + error!("{:4} : {:?}",idx,val); } } @@ -223,7 +223,7 @@ pub fn marksof(ctxt: SyntaxContext, stopname: Name) -> Vec<Mrk> { } // the internal function for computing marks -// it's not clear to me whether it's better to use a [] mutable +// it's not clear to me whether it's better to use a .index(&FullRange) mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index f1b52fa33c3..77aea0c370a 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -273,13 +273,13 @@ pub mod rt { ); } - impl_to_source_int! { signed, int, TyI } + impl_to_source_int! { signed, int, TyIs } impl_to_source_int! { signed, i8, TyI8 } impl_to_source_int! { signed, i16, TyI16 } impl_to_source_int! { signed, i32, TyI32 } impl_to_source_int! { signed, i64, TyI64 } - impl_to_source_int! { unsigned, uint, TyU } + impl_to_source_int! { unsigned, uint, TyUs } impl_to_source_int! { unsigned, u8, TyU8 } impl_to_source_int! { unsigned, u16, TyU16 } impl_to_source_int! { unsigned, u32, TyU32 } @@ -473,7 +473,7 @@ pub fn expand_quote_stmt(cx: &mut ExtCtxt, } fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> { - strs.iter().map(|str| str_to_ident((*str)[])).collect() + strs.iter().map(|str| str_to_ident((*str).index(&FullRange))).collect() } fn id_ext(str: &str) -> ast::Ident { @@ -675,7 +675,7 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> { for i in range(0, tt.len()) { seq.push(tt.get_tt(i)); } - mk_tts(cx, seq[]) + mk_tts(cx, seq.index(&FullRange)) } ast::TtToken(sp, ref tok) => { let e_sp = cx.expr_ident(sp, id_ext("_sp")); @@ -764,7 +764,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); let mut vector = vec!(stmt_let_sp, stmt_let_tt); - vector.extend(mk_tts(cx, tts[]).into_iter()); + vector.extend(mk_tts(cx, tts.index(&FullRange)).into_iter()); let block = cx.expr_block( cx.block_all(sp, Vec::new(), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index a49df457cb3..1ba91dd371c 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -57,7 +57,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - let filename = token::intern_and_get_ident(loc.file.name[]); + let filename = token::intern_and_get_ident(loc.file.name.index(&FullRange)); base::MacExpr::new(cx.expr_str(topmost, filename)) } @@ -65,7 +65,7 @@ pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let s = pprust::tts_to_string(tts); base::MacExpr::new(cx.expr_str(sp, - token::intern_and_get_ident(s[]))) + token::intern_and_get_ident(s.index(&FullRange)))) } pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) @@ -78,7 +78,7 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) .connect("::"); base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(string[]))) + token::intern_and_get_ident(string.index(&FullRange)))) } /// include! : parse the given file as an expr @@ -135,9 +135,9 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let bytes = match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {}: {}", + format!("couldn't read {:?}: {}", file.display(), - e)[]); + e).index(&FullRange)); return DummyResult::expr(sp); } Ok(bytes) => bytes, @@ -146,16 +146,16 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Ok(src) => { // Add this input file to the code map to make it available as // dependency information - let filename = file.display().to_string(); - let interned = token::intern_and_get_ident(src[]); + let filename = format!("{:?}", file.display()); + let interned = token::intern_and_get_ident(src.index(&FullRange)); cx.codemap().new_filemap(filename, src); base::MacExpr::new(cx.expr_str(sp, interned)) } Err(_) => { cx.span_err(sp, - format!("{} wasn't a utf-8 file", - file.display())[]); + format!("{:?} wasn't a utf-8 file", + file.display()).index(&FullRange)); return DummyResult::expr(sp); } } @@ -177,7 +177,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {}: {}", file.display(), e)[]); + format!("couldn't read {:?}: {}", file.display(), e).index(&FullRange)); return DummyResult::expr(sp); } Ok(bytes) => { diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 1438d152554..d33d03bbfa9 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -153,7 +153,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { seq.num_captures } &TtDelimited(_, ref delim) => { - count_names(delim.tts[]) + count_names(delim.tts.index(&FullRange)) } &TtToken(_, MatchNt(..)) => { 1 @@ -165,7 +165,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { - let match_idx_hi = count_names(ms[]); + let match_idx_hi = count_names(ms.index(&FullRange)); let matches: Vec<_> = range(0, match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], @@ -219,7 +219,7 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) } } &TtToken(sp, MatchNt(bind_name, _, _, _)) => { - match ret_val.entry(&bind_name) { + match ret_val.entry(bind_name) { Vacant(spot) => { spot.insert(res[*idx].clone()); *idx += 1; @@ -229,7 +229,7 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) p_s.span_diagnostic .span_fatal(sp, format!("duplicated bind name: {}", - string.get())[]) + string.get()).index(&FullRange)) } } } @@ -254,13 +254,13 @@ pub fn parse_or_else(sess: &ParseSess, rdr: TtReader, ms: Vec<TokenTree> ) -> HashMap<Ident, Rc<NamedMatch>> { - match parse(sess, cfg, rdr, ms[]) { + match parse(sess, cfg, rdr, ms.index(&FullRange)) { Success(m) => m, Failure(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str[]) + sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) } Error(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str[]) + sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) } } } @@ -341,7 +341,7 @@ pub fn parse(sess: &ParseSess, // Only touch the binders we have actually bound for idx in range(ei.match_lo, ei.match_hi) { let sub = (ei.matches[idx]).clone(); - new_pos.matches[idx] + (&mut new_pos.matches[idx]) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, sp.hi)))); } @@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess, new_ei.idx += 1u; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { - new_ei.matches[idx].push(Rc::new(MatchedSeq(Vec::new(), sp))); + (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); @@ -444,10 +444,10 @@ pub fn parse(sess: &ParseSess, if token_name_eq(&tok, &token::Eof) { if eof_eis.len() == 1u { let mut v = Vec::new(); - for dv in eof_eis[0].matches.iter_mut() { + for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } - return Success(nameize(sess, ms, v[])); + return Success(nameize(sess, ms, v.index(&FullRange))); } else if eof_eis.len() > 1u { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { @@ -486,7 +486,7 @@ pub fn parse(sess: &ParseSess, TtToken(_, MatchNt(_, name, _, _)) => { let name_string = token::get_ident(name); let match_cur = ei.match_cur; - ei.matches[match_cur].push(Rc::new(MatchedNonterminal( + (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, name_string.get())))); ei.idx += 1u; ei.match_cur += 1; @@ -507,6 +507,17 @@ pub fn parse(sess: &ParseSess, 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 + let res = token::NtTT(P(p.parse_token_tree())); + p.quote_depth -= 1u; + return res; + } + _ => {} + } + // check at the beginning and the parser checks after each bump + p.check_unknown_macro_variable(); + match name { "item" => match p.parse_item(Vec::new()) { Some(i) => token::NtItem(i), None => p.fatal("expected an item keyword") @@ -522,21 +533,15 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { _ => { let token_str = pprust::token_to_string(&p.token); p.fatal((format!("expected ident, found {}", - token_str[]))[]) + token_str.index(&FullRange))).index(&FullRange)) } }, "path" => { token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons)) } "meta" => token::NtMeta(p.parse_meta_item()), - "tt" => { - p.quote_depth += 1u; //but in theory, non-quoted tts might be useful - let res = token::NtTT(P(p.parse_token_tree())); - p.quote_depth -= 1u; - res - } _ => { - p.fatal(format!("unsupported builtin nonterminal parser: {}", name)[]) + p.fatal(format!("unsupported builtin nonterminal parser: {}", name).index(&FullRange)) } } } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 9837c8088fa..64c53e298ef 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use ast::{Ident, TtDelimited, TtSequence, TtToken}; +use ast::{TokenTree, TtDelimited, TtSequence, TtToken}; use ast; use codemap::{Span, DUMMY_SP}; use ext::base::{ExtCtxt, MacResult, SyntaxExtension}; @@ -16,11 +16,11 @@ use ext::base::{NormalTT, TTMacroExpander}; use ext::tt::macro_parser::{Success, Error, Failure}; use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal}; use ext::tt::macro_parser::{parse, parse_or_else}; -use parse::lexer::new_tt_reader; +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}; -use parse::token::{MatchNt, NtTT}; +use parse::token::{special_idents, gensym_ident, NtTT, Token}; +use parse::token::Token::*; use parse::token; use print; use ptr::P; @@ -52,7 +52,7 @@ impl<'a> ParserAnyMacro<'a> { following", token_str); let span = parser.span; - parser.span_err(span, msg[]); + parser.span_err(span, msg.index(&FullRange)); } } } @@ -109,8 +109,8 @@ impl<'a> MacResult for ParserAnyMacro<'a> { } struct MacroRulesMacroExpander { - name: Ident, - imported_from: Option<Ident>, + name: ast::Ident, + imported_from: Option<ast::Ident>, lhses: Vec<Rc<NamedMatch>>, rhses: Vec<Rc<NamedMatch>>, } @@ -126,16 +126,16 @@ impl TTMacroExpander for MacroRulesMacroExpander { self.name, self.imported_from, arg, - self.lhses[], - self.rhses[]) + self.lhses.index(&FullRange), + self.rhses.index(&FullRange)) } } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx ExtCtxt, sp: Span, - name: Ident, - imported_from: Option<Ident>, + name: ast::Ident, + imported_from: Option<ast::Ident>, arg: &[ast::TokenTree], lhses: &[Rc<NamedMatch>], rhses: &[Rc<NamedMatch>]) @@ -154,17 +154,17 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { - TtDelimited(_, ref delim) => delim.tts[], + TtDelimited(_, ref delim) => delim.tts.index(&FullRange), _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating - let mut arg_rdr = new_tt_reader(&cx.parse_sess().span_diagnostic, - None, - None, - arg.iter() - .map(|x| (*x).clone()) - .collect()); - arg_rdr.desugar_doc_comments = true; + let arg_rdr = new_tt_reader_with_doc_flag(&cx.parse_sess().span_diagnostic, + None, + None, + arg.iter() + .map(|x| (*x).clone()) + .collect(), + true); match parse(cx.parse_sess(), cx.cfg(), arg_rdr, lhs_tt) { Success(named_matches) => { let rhs = match *rhses[i] { @@ -183,7 +183,8 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, Some(named_matches), imported_from, rhs); - let p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); + let mut p = Parser::new(cx.parse_sess(), cx.cfg(), box trncbr); + p.check_unknown_macro_variable(); // Let the context choose how to interpret the result. // Weird, but useful for X-macros. return box ParserAnyMacro { @@ -194,13 +195,13 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, - Error(sp, ref msg) => cx.span_fatal(sp, msg[]) + Error(sp, ref msg) => cx.span_fatal(sp, msg.index(&FullRange)) } } _ => cx.bug("non-matcher found in parsed lhses") } } - cx.span_fatal(best_fail_spot, best_fail_msg[]); + cx.span_fatal(best_fail_spot, best_fail_msg.index(&FullRange)); } // Note that macro-by-example's input is also matched against a token tree: @@ -260,6 +261,10 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, _ => cx.span_bug(def.span, "wrong-structured lhs") }; + for lhs in lhses.iter() { + check_lhs_nt_follows(cx, &**lhs, def.span); + } + let rhses = match *argument_map[rhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") @@ -274,3 +279,181 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, NormalTT(exp, Some(def.span)) } + +fn check_lhs_nt_follows(cx: &mut ExtCtxt, lhs: &NamedMatch, sp: Span) { + // lhs is going to be like MatchedNonterminal(NtTT(TtDelimited(...))), where + // the entire lhs is those tts. + // if ever we get box/deref patterns, this could turn into an `if let + // &MatchedNonterminal(NtTT(box TtDelimited(...))) = lhs` + let matcher = match lhs { + &MatchedNonterminal(NtTT(ref inner)) => match &**inner { + &TtDelimited(_, ref tts) => tts.tts.as_slice(), + _ => cx.span_bug(sp, "wrong-structured lhs for follow check") + }, + _ => cx.span_bug(sp, "wrong-structured lhs for follow check") + }; + + check_matcher(cx, matcher.iter(), &Eof); + // we don't abort on errors on rejection, the driver will do that for us + // after parsing/expansion. we can report every error in every macro this way. +} + +// returns the last token that was checked, for TtSequence. this gets used later on. +fn check_matcher<'a, I>(cx: &mut ExtCtxt, matcher: I, follow: &Token) +-> Option<(Span, Token)> where I: Iterator<Item=&'a TokenTree> { + use print::pprust::token_to_string; + + let mut last = None; + + // 2. For each token T in M: + let mut tokens = matcher.peekable(); + while let Some(token) = tokens.next() { + last = match *token { + TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { + // ii. If T is a simple NT, look ahead to the next token T' in + // M. + let next_token = match tokens.peek() { + // If T' closes a complex NT, replace T' with F + Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), + Some(&&TtToken(_, ref tok)) => tok.clone(), + Some(&&TtSequence(sp, _)) => { + cx.span_err(sp, + format!("`${0}:{1}` is followed by a \ + sequence repetition, which is not \ + allowed for `{1}` fragments", + name.as_str(), frag_spec.as_str()) + .as_slice()); + Eof + }, + // die next iteration + Some(&&TtDelimited(_, ref delim)) => delim.close_token(), + // else, we're at the end of the macro or sequence + None => follow.clone() + }; + + 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 => { + 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 + }, + } + }, + TtSequence(sp, ref seq) => { + // iii. Else, T is a complex NT. + match seq.separator { + // If T has the form $(...)U+ or $(...)U* for some token U, + // run the algorithm on the contents with F set to U. If it + // accepts, continue, else, reject. + Some(ref u) => { + let last = check_matcher(cx, seq.tts.iter(), u); + match last { + // Since the delimiter isn't required after the last + // repetition, make sure that the *next* token is + // sane. This doesn't actually compute the FIRST of + // the rest of the matcher yet, it only considers + // single tokens and simple NTs. This is imprecise, + // but conservatively correct. + Some((span, tok)) => { + let fol = match tokens.peek() { + Some(&&TtToken(_, ref tok)) => tok.clone(), + Some(&&TtDelimited(_, ref delim)) => delim.close_token(), + Some(_) => { + cx.span_err(sp, "sequence repetition followed by \ + another sequence repetition, which is not allowed"); + Eof + }, + None => Eof + }; + check_matcher(cx, Some(&TtToken(span, tok.clone())).into_iter(), + &fol) + }, + None => last, + } + }, + // If T has the form $(...)+ or $(...)*, run the algorithm + // on the contents with F set to the token following the + // sequence. If it accepts, continue, else, reject. + None => { + let fol = match tokens.peek() { + Some(&&TtToken(_, ref tok)) => tok.clone(), + Some(&&TtDelimited(_, ref delim)) => delim.close_token(), + Some(_) => { + cx.span_err(sp, "sequence repetition followed by another \ + sequence repetition, which is not allowed"); + Eof + }, + None => Eof + }; + check_matcher(cx, seq.tts.iter(), &fol) + } + } + }, + TtToken(..) => { + // i. If T is not an NT, continue. + continue + }, + TtDelimited(_, ref tts) => { + // if we don't pass in that close delimiter, we'll incorrectly consider the matcher + // `{ $foo:ty }` as having a follow that isn't `RBrace` + check_matcher(cx, tts.tts.iter(), &tts.close_token()) + } + } + } + last +} + +fn is_in_follow(cx: &ExtCtxt, tok: &Token, frag: &str) -> bool { + 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()), + } +} diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index e4e6f5ac6b0..bc07c7f6cae 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -53,13 +53,28 @@ pub struct TtReader<'a> { } /// This can do Macro-By-Example transcription. On the other hand, if -/// `src` contains no `TtSequence`s and `TtNonterminal`s, `interp` can (and -/// should) be none. +/// `src` contains no `TtSequence`s, `MatchNt`s or `SubstNt`s, `interp` can +/// (and should) be None. pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler, interp: Option<HashMap<Ident, Rc<NamedMatch>>>, imported_from: Option<Ident>, - src: Vec<ast::TokenTree> ) + src: Vec<ast::TokenTree>) -> TtReader<'a> { + new_tt_reader_with_doc_flag(sp_diag, interp, imported_from, src, false) +} + +/// The extra `desugar_doc_comments` flag enables reading doc comments +/// like any other attribute which consists of `meta` and surrounding #[ ] tokens. +/// +/// This can do Macro-By-Example transcription. On the other hand, if +/// `src` contains no `TtSequence`s, `MatchNt`s or `SubstNt`s, `interp` can +/// (and should) be None. +pub fn new_tt_reader_with_doc_flag<'a>(sp_diag: &'a SpanHandler, + interp: Option<HashMap<Ident, Rc<NamedMatch>>>, + imported_from: Option<Ident>, + src: Vec<ast::TokenTree>, + desugar_doc_comments: bool) + -> TtReader<'a> { let mut r = TtReader { sp_diag: sp_diag, stack: vec!(TtFrame { @@ -80,7 +95,7 @@ pub fn new_tt_reader<'a>(sp_diag: &'a SpanHandler, crate_name_next: None, repeat_idx: Vec::new(), repeat_len: Vec::new(), - desugar_doc_comments: false, + desugar_doc_comments: desugar_doc_comments, /* dummy values, never read: */ cur_tok: token::Eof, cur_span: DUMMY_SP, @@ -128,7 +143,7 @@ impl Add for LockstepIterSize { let l_n = token::get_ident(l_id.clone()); let r_n = token::get_ident(r_id); LisContradiction(format!("inconsistent lockstep iteration: \ - '{}' has {} items, but '{}' has {}", + '{:?}' has {} items, but '{:?}' has {}", l_n, l_len, r_n, r_len).to_string()) } }, @@ -240,7 +255,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { } LisContradiction(ref msg) => { // FIXME #2887 blame macro invoker instead - r.sp_diag.span_fatal(sp.clone(), msg[]); + r.sp_diag.span_fatal(sp.clone(), msg.index(&FullRange)); } LisConstraint(len, _) => { if len == 0 { @@ -266,18 +281,15 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { } // FIXME #2887: think about span stuff here TtToken(sp, SubstNt(ident, namep)) => { + r.stack.last_mut().unwrap().idx += 1; match lookup_cur_matched(r, ident) { None => { - r.stack.push(TtFrame { - forest: TtToken(sp, SubstNt(ident, namep)), - idx: 0, - dotdotdoted: false, - sep: None - }); + r.cur_span = sp; + r.cur_tok = SubstNt(ident, namep); + return ret_val; // this can't be 0 length, just like TtDelimited } Some(cur_matched) => { - r.stack.last_mut().unwrap().idx += 1; match *cur_matched { // sidestep the interpolation tricks for ident because // (a) idents can be in lots of places, so it'd be a pain @@ -296,8 +308,8 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { MatchedSeq(..) => { r.sp_diag.span_fatal( r.cur_span, /* blame the macro writer */ - format!("variable '{}' is still repeating at this depth", - token::get_ident(ident))[]); + format!("variable '{:?}' is still repeating at this depth", + token::get_ident(ident)).index(&FullRange)); } } } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 0810d4ee93a..f10113254de 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -44,7 +44,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), - ("phase", Active), // NOTE(stage0): switch to Removed after next snapshot + ("phase", Removed), ("plugin_registrar", Active), ("log_syntax", Active), ("trace_macros", Active), @@ -86,6 +86,9 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ // A way to temporarily opt out of the new orphan rules. This will *never* be accepted. ("old_orphan_check", Deprecated), + // A way to temporarily opt out of the new impl rules. This will *never* be accepted. + ("old_impl_check", Deprecated), + // OIBIT specific features ("optin_builtin_traits", Active), @@ -149,7 +152,7 @@ impl<'a> Context<'a> { self.span_handler.span_err(span, explain); self.span_handler.span_help(span, format!("add #![feature({})] to the \ crate attributes to enable", - feature)[]); + feature).index(&FullRange)); } } @@ -240,7 +243,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } match i.node { ast::ItemForeignMod(ref foreign_module) => { - if attr::contains_name(i.attrs[], "link_args") { + if attr::contains_name(i.attrs.index(&FullRange), "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ @@ -254,14 +257,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } ast::ItemFn(..) => { - if attr::contains_name(i.attrs[], "plugin_registrar") { + if attr::contains_name(i.attrs.index(&FullRange), "plugin_registrar") { self.gate_feature("plugin_registrar", i.span, "compiler plugins are experimental and possibly buggy"); } } ast::ItemStruct(..) => { - if attr::contains_name(i.attrs[], "simd") { + if attr::contains_name(i.attrs.index(&FullRange), "simd") { self.gate_feature("simd", i.span, "SIMD types are experimental and possibly buggy"); } @@ -278,7 +281,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { _ => {} } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.as_slice(), "unsafe_destructor") { self.gate_feature("unsafe_destructor", i.span, @@ -287,13 +290,20 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { removed in the future"); } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.index(&FullRange), "old_orphan_check") { self.gate_feature( "old_orphan_check", i.span, "the new orphan check rules will eventually be strictly enforced"); } + + if attr::contains_name(i.attrs.index(&FullRange), + "old_impl_check") { + self.gate_feature("old_impl_check", + i.span, + "`#[old_impl_check]` will be removed in the future"); + } } _ => {} @@ -303,13 +313,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { - if attr::contains_name(i.attrs[], "linkage") { + if attr::contains_name(i.attrs.index(&FullRange), "linkage") { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") } - let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") { + let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(), + "link_name") { Some(val) => val.get().starts_with("llvm."), _ => false }; diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index b7bfd346d50..9e14f9dd1ea 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -23,25 +23,15 @@ html_root_url = "http://doc.rust-lang.org/nightly/")] #![allow(unknown_features)] -#![feature(macro_rules, globs, default_type_params, phase, slicing_syntax)] +#![feature(slicing_syntax)] #![feature(quote, unsafe_destructor)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] extern crate arena; extern crate fmt_macros; extern crate serialize; extern crate term; extern crate libc; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[macro_use] extern crate log; extern crate "serialize" as rustc_serialize; // used by deriving diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 2a27431a086..707e540a17b 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -82,31 +82,12 @@ impl<T> FromIterator<T> for OwnedSlice<T> { } } -#[cfg(stage0)] -impl<S: Encoder<E>, T: Encodable<S, E>, E> Encodable<S, E> for OwnedSlice<T> { - fn encode(&self, s: &mut S) -> Result<(), E> { - self.as_slice().encode(s) - } -} - -#[cfg(not(stage0))] impl<T: Encodable> Encodable for OwnedSlice<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { self.as_slice().encode(s) } } -#[cfg(stage0)] -impl<D: Decoder<E>, T: Decodable<D, E>, E> Decodable<D, E> for OwnedSlice<T> { - fn decode(d: &mut D) -> Result<OwnedSlice<T>, E> { - Ok(OwnedSlice::from_vec(match Decodable::decode(d) { - Ok(t) => t, - Err(e) => return Err(e) - })) - } -} - -#[cfg(not(stage0))] impl<T: Decodable> Decodable for OwnedSlice<T> { fn decode<D: Decoder>(d: &mut D) -> Result<OwnedSlice<T>, D::Error> { Ok(OwnedSlice::from_vec(match Decodable::decode(d) { diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 41693d9d47a..4aad7f911db 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -32,7 +32,7 @@ impl<'a> ParserAttr for Parser<'a> { fn parse_outer_attributes(&mut self) -> Vec<ast::Attribute> { let mut attrs: Vec<ast::Attribute> = Vec::new(); loop { - debug!("parse_outer_attributes: self.token={}", + debug!("parse_outer_attributes: self.token={:?}", self.token); match self.token { token::Pound => { @@ -62,7 +62,7 @@ impl<'a> ParserAttr for Parser<'a> { /// If permit_inner is true, then a leading `!` indicates an inner /// attribute fn parse_attribute(&mut self, permit_inner: bool) -> ast::Attribute { - debug!("parse_attributes: permit_inner={} self.token={}", + debug!("parse_attributes: permit_inner={:?} self.token={:?}", permit_inner, self.token); let (span, value, mut style) = match self.token { token::Pound => { @@ -92,7 +92,7 @@ impl<'a> ParserAttr for Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `#`, found `{}`", token_str)[]); + self.fatal(format!("expected `#`, found `{}`", token_str).index(&FullRange)); } }; diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 0d5592b57b1..e7fc5aac9c7 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -82,7 +82,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { while j > i && lines[j - 1].trim().is_empty() { j -= 1; } - return lines[i..j].iter().map(|x| (*x).clone()).collect(); + return lines.index(&(i..j)).iter().map(|x| (*x).clone()).collect(); } /// remove a "[ \t]*\*" block from each line, if possible @@ -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.index(&((i + 1)..line.len())).to_string() }).collect() } else { lines @@ -127,12 +127,12 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONLINERS.iter() { if comment.starts_with(*prefix) { - return comment[prefix.len()..].to_string(); + return comment.index(&(prefix.len()..)).to_string(); } } if comment.starts_with("/*") { - let lines = comment[3u..comment.len() - 2u] + let lines = comment.index(&(3u..(comment.len() - 2u))) .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); @@ -187,7 +187,7 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. - if is_doc_comment(line[]) { + if is_doc_comment(line.index(&FullRange)) { break; } lines.push(line); @@ -224,10 +224,10 @@ fn all_whitespace(s: &str, col: CharPos) -> Option<uint> { fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String> , s: String, col: CharPos) { let len = s.len(); - let s1 = match all_whitespace(s[], col) { + let s1 = match all_whitespace(s.index(&FullRange), col) { Some(col) => { if col < len { - s[col..len].to_string() + s.index(&(col..len)).to_string() } else { "".to_string() } @@ -261,7 +261,7 @@ fn read_block_comment(rdr: &mut StringReader, rdr.bump(); rdr.bump(); } - if is_block_doc_comment(curr_line[]) { + if is_block_doc_comment(curr_line.index(&FullRange)) { return } assert!(!curr_line.contains_char('\n')); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index a50b97142c2..153b18b8760 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -25,7 +25,7 @@ use std::rc::Rc; use std::str; use std::string::CowString; -pub use ext::tt::transcribe::{TtReader, new_tt_reader}; +pub use ext::tt::transcribe::{TtReader, new_tt_reader, new_tt_reader_with_doc_flag}; pub mod comments; @@ -111,7 +111,7 @@ impl<'a> Reader for TtReader<'a> { } fn next_token(&mut self) -> TokenAndSpan { let r = tt_next_token(self); - debug!("TtReader: r={}", r); + debug!("TtReader: r={:?}", r); r } fn fatal(&self, m: &str) -> ! { @@ -196,7 +196,7 @@ impl<'a> StringReader<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } - self.fatal_span_(from_pos, to_pos, m[]); + self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an @@ -205,7 +205,7 @@ impl<'a> StringReader<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } - self.err_span_(from_pos, to_pos, m[]); + self.err_span_(from_pos, to_pos, m.index(&FullRange)); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the @@ -214,8 +214,8 @@ impl<'a> StringReader<'a> { m.push_str(": "); let from = self.byte_offset(from_pos).to_uint(); let to = self.byte_offset(to_pos).to_uint(); - m.push_str(self.filemap.src[from..to]); - self.fatal_span_(from_pos, to_pos, m[]); + m.push_str(self.filemap.src.index(&(from..to))); + self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); } /// Advance peek_tok and peek_span to refer to the next token, and @@ -256,13 +256,13 @@ impl<'a> StringReader<'a> { /// adjusted 1 towards each other (assumes that on either side there is a /// single-byte delimiter). pub fn name_from(&self, start: BytePos) -> ast::Name { - debug!("taking an ident from {} to {}", start, self.last_pos); + debug!("taking an ident from {:?} to {:?}", start, self.last_pos); self.with_str_from(start, token::intern) } /// As name_from, with an explicit endpoint. pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name { - debug!("taking an ident from {} to {}", start, end); + debug!("taking an ident from {:?} to {:?}", start, end); self.with_str_from_to(start, end, token::intern) } @@ -301,7 +301,7 @@ impl<'a> StringReader<'a> { while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { - if j < i { buf.push_str(s[j..i]); } + if j < i { buf.push_str(s.index(&(j..i))); } j = next; if next >= s.len() || s.char_at(next) != '\n' { let pos = start + BytePos(i as u32); @@ -311,7 +311,7 @@ impl<'a> StringReader<'a> { } i = next; } - if j < s.len() { buf.push_str(s[j..]); } + if j < s.len() { buf.push_str(s.index(&(j..))); } buf } } @@ -496,7 +496,7 @@ impl<'a> StringReader<'a> { // for skipping over all "junk" '/' | '#' => { let c = self.scan_comment(); - debug!("scanning a comment {}", c); + debug!("scanning a comment {:?}", c); c }, c if is_whitespace(Some(c)) => { @@ -506,7 +506,7 @@ impl<'a> StringReader<'a> { tok: token::Whitespace, sp: codemap::mk_sp(start_bpos, self.last_pos) }); - debug!("scanning whitespace: {}", c); + debug!("scanning whitespace: {:?}", c); c }, _ => None @@ -556,7 +556,7 @@ impl<'a> StringReader<'a> { self.translate_crlf(start_bpos, string, "bare CR not allowed in block doc-comment") } else { string.into_cow() }; - token::DocComment(token::intern(string[])) + token::DocComment(token::intern(string.index(&FullRange))) } else { token::Comment }; @@ -592,8 +592,8 @@ impl<'a> StringReader<'a> { 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), - None => panic!("expected {}, hit EOF, {}", described_c, whence), + Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence), + None => panic!("expected {:?}, hit EOF, {}", described_c, whence), } } @@ -614,7 +614,7 @@ impl<'a> StringReader<'a> { self.scan_digits(base); let encoded_name : u32 = self.with_str_from(start_bpos, |s| { num::from_str_radix(s, 10).unwrap_or_else(|| { - panic!("expected digits representing a name, got `{}`, {}, range [{},{}]", + panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]", s, whence, start_bpos, self.last_pos); }) }); @@ -632,7 +632,7 @@ impl<'a> StringReader<'a> { self.scan_digits(base); let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| { num::from_str_radix(s, 10).unwrap_or_else(|| { - panic!("expected digits representing a ctxt, got `{}`, {}", s, whence); + panic!("expected digits representing a ctxt, got {:?}, {}", s, whence); }) }); @@ -652,7 +652,7 @@ impl<'a> StringReader<'a> { if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } match c.and_then(|cc| cc.to_digit(radix)) { Some(_) => { - debug!("{} in scan_digits", c); + debug!("{:?} in scan_digits", c); len += 1; self.bump(); } @@ -728,7 +728,7 @@ impl<'a> StringReader<'a> { delim: char, below_0x7f_only: bool) -> bool { - debug!("scanning {} digits until {}", n_digits, delim); + debug!("scanning {} digits until {:?}", n_digits, delim); let start_bpos = self.last_pos; let mut accum_int = 0; @@ -990,7 +990,7 @@ impl<'a> StringReader<'a> { if is_dec_digit(c) { let num = self.scan_number(c.unwrap()); let suffix = self.scan_optional_raw_name(); - debug!("next_token_inner: scanned number {}, {}", num, suffix); + debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix); return token::Literal(num, suffix) } @@ -1110,7 +1110,7 @@ impl<'a> StringReader<'a> { // expansion purposes. See #12512 for the gory details of why // this is necessary. let ident = self.with_str_from(start, |lifetime_name| { - str_to_ident(format!("'{}", lifetime_name)[]) + str_to_ident(format!("'{}", lifetime_name).index(&FullRange)) }); // Conjure up a "keyword checking ident" to make sure that @@ -1444,14 +1444,14 @@ fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); } pub fn is_doc_comment(s: &str) -> bool { let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || s.starts_with("//!"); - debug!("is `{}` a doc comment? {}", s, res); + debug!("is {:?} a doc comment? {}", s, res); res } pub fn is_block_doc_comment(s: &str) -> bool { let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || s.starts_with("/*!"); - debug!("is `{}` a doc comment? {}", s, res); + debug!("is {:?} a doc comment? {}", s, res); res } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index b0969a573e6..d26b3af67bd 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -24,8 +24,7 @@ use std::num::Int; use std::str; use std::iter; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod parser; pub mod lexer; @@ -254,19 +253,19 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>) let bytes = match File::open(path).read_to_end() { Ok(bytes) => bytes, Err(e) => { - err(format!("couldn't read {}: {}", + err(format!("couldn't read {:?}: {:?}", path.display(), - e)[]); + e).index(&FullRange)); unreachable!() } }; - match str::from_utf8(bytes[]).ok() { + match str::from_utf8(bytes.index(&FullRange)).ok() { Some(s) => { return string_to_filemap(sess, s.to_string(), path.as_str().unwrap().to_string()) } None => { - err(format!("{} is not UTF-8 encoded", path.display())[]) + err(format!("{:?} is not UTF-8 encoded", path.display()).index(&FullRange)) } } unreachable!() @@ -297,7 +296,9 @@ pub fn tts_to_parser<'a>(sess: &'a ParseSess, tts: Vec<ast::TokenTree>, cfg: ast::CrateConfig) -> Parser<'a> { let trdr = lexer::new_tt_reader(&sess.span_diagnostic, None, None, tts); - Parser::new(sess, cfg, box trdr) + let mut p = Parser::new(sess, cfg, box trdr); + p.check_unknown_macro_variable(); + p } // FIXME (Issue #16472): The `with_hygiene` mod should go away after @@ -398,10 +399,10 @@ pub fn char_lit(lit: &str) -> (char, int) { } let msg = format!("lexer should have rejected a bad character escape {}", lit); - let msg2 = msg[]; + let msg2 = msg.index(&FullRange); fn esc(len: uint, lit: &str) -> Option<(char, int)> { - num::from_str_radix(lit[2..len], 16) + num::from_str_radix(lit.index(&(2..len)), 16) .and_then(char::from_u32) .map(|x| (x, len as int)) } @@ -409,7 +410,7 @@ pub fn char_lit(lit: &str) -> (char, int) { let unicode_escape = |&: | -> Option<(char, int)> if lit.as_bytes()[2] == b'{' { let idx = lit.find('}').expect(msg2); - let subslice = lit[3..idx]; + let subslice = lit.index(&(3..idx)); num::from_str_radix(subslice, 16) .and_then(char::from_u32) .map(|x| (x, subslice.chars().count() as int + 4)) @@ -471,7 +472,7 @@ pub fn str_lit(lit: &str) -> String { eat(&mut chars); } else { // otherwise, a normal escape - let (c, n) = char_lit(lit[i..]); + let (c, n) = char_lit(lit.index(&(i..))); for _ in range(0, n - 1) { // we don't need to move past the first \ chars.next(); } @@ -534,12 +535,12 @@ pub fn raw_str_lit(lit: &str) -> String { fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { s.len() > 1 && first_chars.contains(&s.char_at(0)) && - s[1..].chars().all(|c| '0' <= c && c <= '9') + s.index(&(1..)).chars().all(|c| '0' <= c && c <= '9') } fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ { - debug!("filtered_float_lit: {}, {}", data, suffix); + debug!("filtered_float_lit: {}, {:?}", data, suffix); match suffix { Some("f32") => ast::LitFloat(data, ast::TyF32), Some("f64") => ast::LitFloat(data, ast::TyF64), @@ -547,7 +548,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) { // if it looks like a width, lets try to be helpful. sd.span_err(sp, &*format!("illegal width `{}` for float literal, \ - valid widths are 32 and 64", suf[1..])); + valid widths are 32 and 64", suf.index(&(1..)))); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for float literal, \ valid suffixes are `f32` and `f64`", suf)); @@ -559,7 +560,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, } } pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ { - debug!("float_lit: {}, {}", s, suffix); + debug!("float_lit: {:?}, {:?}", s, suffix); // FIXME #2252: bounds checking float literals is defered until trans let s = s.chars().filter(|&c| c != '_').collect::<String>(); let data = token::intern_and_get_ident(&*s); @@ -583,7 +584,7 @@ pub fn byte_lit(lit: &str) -> (u8, uint) { b'\'' => b'\'', b'0' => b'\0', _ => { - match ::std::num::from_str_radix::<u64>(lit[2..4], 16) { + match ::std::num::from_str_radix::<u64>(lit.index(&(2..4)), 16) { Some(c) => if c > 0xFF { panic!(err(2)) @@ -633,7 +634,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { } _ => { // otherwise, a normal escape - let (c, n) = byte_lit(lit[i..]); + let (c, n) = byte_lit(lit.index(&(i..))); // we don't need to move past the first \ for _ in range(0, n - 1) { chars.next(); @@ -662,9 +663,9 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> // s can only be ascii, byte indexing is fine let s2 = s.chars().filter(|&c| c != '_').collect::<String>(); - let mut s = s2[]; + let mut s = s2.index(&FullRange); - debug!("integer_lit: {}, {}", s, suffix); + debug!("integer_lit: {}, {:?}", s, suffix); let mut base = 10; let orig = s; @@ -695,18 +696,20 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } if base != 10 { - s = s[2..]; + s = s.index(&(2..)); } if let Some(suf) = suffix { if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")} ty = match suf { - "i" => ast::SignedIntLit(ast::TyI, ast::Plus), + "i" => ast::SignedIntLit(ast::TyIs, ast::Plus), + "is" => ast::SignedIntLit(ast::TyIs, ast::Plus), "i8" => ast::SignedIntLit(ast::TyI8, ast::Plus), "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus), "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus), "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus), - "u" => ast::UnsignedIntLit(ast::TyU), + "u" => ast::UnsignedIntLit(ast::TyUs), + "us" => ast::UnsignedIntLit(ast::TyUs), "u8" => ast::UnsignedIntLit(ast::TyU8), "u16" => ast::UnsignedIntLit(ast::TyU16), "u32" => ast::UnsignedIntLit(ast::TyU32), @@ -717,7 +720,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> if looks_like_width_suffix(&['i', 'u'], suf) { sd.span_err(sp, &*format!("illegal width `{}` for integer literal; \ valid widths are 8, 16, 32 and 64", - suf[1..])); + suf.index(&(1..)))); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for numeric literal", suf)); } @@ -727,8 +730,8 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } } - debug!("integer_lit: the type is {}, base {}, the new string is {}, the original \ - string was {}, the original suffix was {}", ty, base, s, orig, suffix); + debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \ + string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix); let res: u64 = match ::std::num::from_str_radix(s, base) { Some(r) => r, @@ -815,7 +818,7 @@ mod test { #[test] fn string_to_tts_macro () { let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string()); - let tts: &[ast::TokenTree] = tts[]; + let tts: &[ast::TokenTree] = tts.index(&FullRange); match tts { [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)), ast::TtToken(_, token::Not), @@ -823,30 +826,30 @@ mod test { ast::TtDelimited(_, ref macro_delimed)] if name_macro_rules.as_str() == "macro_rules" && name_zip.as_str() == "zip" => { - match macro_delimed.tts[] { + match macro_delimed.tts.index(&FullRange) { [ast::TtDelimited(_, ref first_delimed), ast::TtToken(_, token::FatArrow), ast::TtDelimited(_, ref second_delimed)] if macro_delimed.delim == token::Paren => { - match first_delimed.tts[] { + match first_delimed.tts.index(&FullRange) { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if first_delimed.delim == token::Paren && name.as_str() == "a" => {}, - _ => panic!("value 3: {}", **first_delimed), + _ => panic!("value 3: {:?}", **first_delimed), } - match second_delimed.tts[] { + match second_delimed.tts.index(&FullRange) { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if second_delimed.delim == token::Paren && name.as_str() == "a" => {}, - _ => panic!("value 4: {}", **second_delimed), + _ => panic!("value 4: {:?}", **second_delimed), } }, - _ => panic!("value 2: {}", **macro_delimed), + _ => panic!("value 2: {:?}", **macro_delimed), } }, - _ => panic!("value: {}",tts), + _ => panic!("value: {:?}",tts), } } @@ -1113,24 +1116,24 @@ mod test { 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); - assert_eq!(vitem_s[], use_s); + assert_eq!(vitem_s.index(&FullRange), 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); - assert_eq!(vitem_s[], use_s); + assert_eq!(vitem_s.index(&FullRange), 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); - assert_eq!(vitem_s[], ex_s); + assert_eq!(vitem_s.index(&FullRange), 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); - assert_eq!(vitem_s[], ex_s); + assert_eq!(vitem_s.index(&FullRange), ex_s); } fn get_spans_of_pat_idents(src: &str) -> Vec<Span> { @@ -1167,10 +1170,10 @@ mod test { for &src in srcs.iter() { let spans = get_spans_of_pat_idents(src); - let Span{lo:lo,hi:hi,..} = spans[0]; - assert!("self" == src[lo.to_uint()..hi.to_uint()], + let Span{ lo, hi, .. } = spans[0]; + assert!("self" == &src[lo.to_uint()..hi.to_uint()], "\"{}\" != \"self\". src=\"{}\"", - src[lo.to_uint()..hi.to_uint()], src) + &src[lo.to_uint()..hi.to_uint()], src) } } @@ -1209,7 +1212,7 @@ mod test { let docs = item.attrs.iter().filter(|a| a.name().get() == "doc") .map(|a| a.value_str().unwrap().get().to_string()).collect::<Vec<_>>(); let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; - assert_eq!(docs[], b); + assert_eq!(docs.index(&FullRange), b); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap(); diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index a49680d7e1c..23728c74ae8 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -127,13 +127,13 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { kind_str: &str, desc: &str) { self.span_err(sp, - format!("obsolete syntax: {}", kind_str)[]); + format!("obsolete syntax: {}", kind_str).index(&FullRange)); if !self.obsolete_set.contains(&kind) { self.sess .span_diagnostic .handler() - .note(format!("{}", desc)[]); + .note(format!("{}", desc).index(&FullRange)); self.obsolete_set.insert(kind); } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 32f8f5ee3d6..92e0395eca4 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -63,7 +63,7 @@ use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; use ast::{Visibility, WhereClause}; use ast; use ast_util::{self, as_prec, ident_to_path, operator_prec}; -use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP}; +use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp}; use diagnostic; use ext::tt::macro_parser; use parse; @@ -389,12 +389,12 @@ impl<'a> Parser<'a> { let token_str = Parser::token_to_string(t); let last_span = self.last_span; self.span_fatal(last_span, format!("unexpected token: `{}`", - token_str)[]); + token_str).index(&FullRange)); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_string(); - self.fatal(format!("unexpected token: `{}`", this_token)[]); + self.fatal(format!("unexpected token: `{}`", this_token).index(&FullRange)); } /// Expect and consume the token t. Signal an error if @@ -408,7 +408,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", token_str, - this_token_str)[]) + this_token_str).index(&FullRange)) } } else { self.expect_one_of(slice::ref_slice(t), &[]); @@ -449,7 +449,7 @@ impl<'a> Parser<'a> { expected.push_all(&*self.expected_tokens); expected.sort_by(|a, b| a.to_string().cmp(&b.to_string())); expected.dedup(); - let expect = tokens_to_string(expected[]); + let expect = tokens_to_string(expected.index(&FullRange)); let actual = self.this_token_to_string(); self.fatal( (if expected.len() != 1 { @@ -460,7 +460,7 @@ impl<'a> Parser<'a> { (format!("expected {}, found `{}`", expect, actual)) - })[] + }).index(&FullRange) ) } } @@ -488,12 +488,12 @@ impl<'a> Parser<'a> { /// followed by some token from the set edible + inedible. Recover /// from anticipated input errors, discarding erroneous characters. pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) { - debug!("commit_expr {}", e); + debug!("commit_expr {:?}", e); if let ExprPath(..) = e.node { // might be unit-struct construction; check for recoverableinput error. let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); expected.push_all(inedible); - self.check_for_erroneous_unit_struct_expecting(expected[]); + self.check_for_erroneous_unit_struct_expecting(expected.index(&FullRange)); } self.expect_one_of(edible, inedible) } @@ -510,9 +510,9 @@ impl<'a> Parser<'a> { .as_ref() .map_or(false, |t| t.is_ident() || t.is_path()) { let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); - expected.push_all(inedible[]); + expected.push_all(inedible.index(&FullRange)); self.check_for_erroneous_unit_struct_expecting( - expected[]); + expected.index(&FullRange)); } self.expect_one_of(edible, inedible) } @@ -535,7 +535,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal((format!("expected ident, found `{}`", - token_str))[]) + token_str)).index(&FullRange)) } } } @@ -593,7 +593,7 @@ impl<'a> Parser<'a> { let id_interned_str = token::get_name(kw.to_name()); let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", - id_interned_str, token_str)[]) + id_interned_str, token_str).index(&FullRange)) } } @@ -604,7 +604,7 @@ impl<'a> Parser<'a> { let span = self.span; self.span_err(span, format!("expected identifier, found keyword `{}`", - token_str)[]); + token_str).index(&FullRange)); } } @@ -613,7 +613,7 @@ impl<'a> Parser<'a> { if self.token.is_reserved_keyword() { let token_str = self.this_token_to_string(); self.fatal(format!("`{}` is a reserved keyword", - token_str)[]) + token_str).index(&FullRange)) } } @@ -633,7 +633,7 @@ impl<'a> Parser<'a> { Parser::token_to_string(&token::BinOp(token::And)); self.fatal(format!("expected `{}`, found `{}`", found_token, - token_str)[]) + token_str).index(&FullRange)) } } } @@ -654,7 +654,7 @@ impl<'a> Parser<'a> { Parser::token_to_string(&token::BinOp(token::Or)); self.fatal(format!("expected `{}`, found `{}`", token_str, - found_token)[]) + found_token).index(&FullRange)) } } } @@ -697,7 +697,7 @@ impl<'a> Parser<'a> { let token_str = Parser::token_to_string(&token::Lt); self.fatal(format!("expected `{}`, found `{}`", token_str, - found_token)[]) + found_token).index(&FullRange)) } } @@ -749,7 +749,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", gt_str, - this_token_str)[]) + this_token_str).index(&FullRange)) } } } @@ -946,6 +946,8 @@ impl<'a> Parser<'a> { self.token = next.tok; self.tokens_consumed += 1u; self.expected_tokens.clear(); + // check after each token + self.check_unknown_macro_variable(); } /// Advance the parser by one token and return the bumped token. @@ -1369,7 +1371,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = p.parse_inner_attrs_and_block(); let mut attrs = attrs; - attrs.push_all(inner_attrs[]); + attrs.push_all(inner_attrs.index(&FullRange)); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, @@ -1388,7 +1390,7 @@ impl<'a> Parser<'a> { _ => { let token_str = p.this_token_to_string(); p.fatal((format!("expected `;` or `{{`, found `{}`", - token_str))[]) + token_str)).index(&FullRange)) } } } @@ -1584,7 +1586,7 @@ impl<'a> Parser<'a> { } else { let this_token_str = self.this_token_to_string(); let msg = format!("expected type, found `{}`", this_token_str); - self.fatal(msg[]); + self.fatal(msg.index(&FullRange)); }; let sp = mk_sp(lo, self.last_span.hi); @@ -1726,14 +1728,14 @@ impl<'a> Parser<'a> { token::Str_(s) => { (true, - LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str())[]), + LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()), ast::CookedStr)) } token::StrRaw(s, n) => { (true, LitStr( token::intern_and_get_ident( - parse::raw_str_lit(s.as_str())[]), + parse::raw_str_lit(s.as_str()).index(&FullRange)), ast::RawStr(n))) } token::Binary(i) => @@ -1977,7 +1979,7 @@ impl<'a> Parser<'a> { }; } _ => { - self.fatal(format!("expected a lifetime name")[]); + self.fatal(format!("expected a lifetime name").index(&FullRange)); } } } @@ -2015,7 +2017,7 @@ impl<'a> Parser<'a> { let msg = format!("expected `,` or `>` after lifetime \ name, found `{}`", this_token_str); - self.fatal(msg[]); + self.fatal(msg.index(&FullRange)); } } } @@ -2103,22 +2105,6 @@ impl<'a> Parser<'a> { ExprIndex(expr, idx) } - pub fn mk_slice(&mut self, - expr: P<Expr>, - start: Option<P<Expr>>, - end: Option<P<Expr>>, - _mutbl: Mutability) - -> ast::Expr_ { - // FIXME: we could give more accurate span info here. - let (lo, hi) = match (&start, &end) { - (&Some(ref s), &Some(ref e)) => (s.span.lo, e.span.hi), - (&Some(ref s), &None) => (s.span.lo, s.span.hi), - (&None, &Some(ref e)) => (e.span.lo, e.span.hi), - (&None, &None) => (DUMMY_SP.lo, DUMMY_SP.hi), - }; - ExprIndex(expr, self.mk_expr(lo, hi, ExprRange(start, end))) - } - pub fn mk_range(&mut self, start: Option<P<Expr>>, end: Option<P<Expr>>) @@ -2515,7 +2501,7 @@ impl<'a> Parser<'a> { let last_span = self.last_span; let fstr = n.as_str(); self.span_err(last_span, - format!("unexpected token: `{}`", n.as_str())[]); + format!("unexpected token: `{}`", n.as_str()).index(&FullRange)); if fstr.chars().all(|x| "0123456789.".contains_char(x)) { let float = match fstr.parse::<f64>() { Some(f) => f, @@ -2524,7 +2510,7 @@ impl<'a> Parser<'a> { self.span_help(last_span, format!("try parenthesizing the first index; e.g., `(foo.{}){}`", float.trunc() as uint, - float.fract().to_string()[1..])[]); + float.fract().to_string().index(&(1..))).index(&FullRange)); } self.abort_if_errors(); @@ -2550,87 +2536,44 @@ impl<'a> Parser<'a> { } // expr[...] - // Could be either an index expression or a slicing expression. - // Any slicing non-terminal can have a mutable version with `mut` - // after the opening square bracket. + // An index expression. token::OpenDelim(token::Bracket) => { + let bracket_pos = self.span.lo; self.bump(); - let mutbl = if self.eat_keyword(keywords::Mut) { - MutMutable + + let mut found_dotdot = false; + if self.token == token::DotDot && + self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) { + // Using expr[..], which is a mistake, should be expr[] + self.bump(); + self.bump(); + found_dotdot = true; + } + + if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) { + // No expression, expand to a FullRange + // FIXME(#20516) It would be better to use a lang item or + // something for FullRange. + hi = self.last_span.hi; + let range = ExprStruct(ident_to_path(mk_sp(lo, hi), + token::special_idents::FullRange), + vec![], + None); + let ix = self.mk_expr(bracket_pos, hi, range); + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index) } else { - MutImmutable - }; - match self.token { - // e[] - token::CloseDelim(token::Bracket) => { - self.bump(); - hi = self.span.hi; - let slice = self.mk_slice(e, None, None, mutbl); - e = self.mk_expr(lo, hi, slice) - } - // e[..e] - token::DotDot => { - self.bump(); - match self.token { - // e[..] - token::CloseDelim(token::Bracket) => { - self.bump(); - hi = self.span.hi; - let slice = self.mk_slice(e, None, None, mutbl); - e = self.mk_expr(lo, hi, slice); + let ix = self.parse_expr(); + hi = self.span.hi; + self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)); + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index) + } - self.span_err(e.span, "incorrect slicing expression: `[..]`"); - self.span_note(e.span, - "use `expr[]` to construct a slice of the whole of expr"); - } - // e[..e] - _ => { - hi = self.span.hi; - let e2 = self.parse_expr(); - self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket)); - let slice = self.mk_slice(e, None, Some(e2), mutbl); - e = self.mk_expr(lo, hi, slice) - } - } - } - // e[e] | e[e..] | e[e..e] - _ => { - let ix = self.parse_expr_res(RESTRICTION_NO_DOTS); - match self.token { - // e[e..] | e[e..e] - token::DotDot => { - self.bump(); - let e2 = match self.token { - // e[e..] - token::CloseDelim(token::Bracket) => { - self.bump(); - None - } - // e[e..e] - _ => { - let e2 = self.parse_expr_res(RESTRICTION_NO_DOTS); - self.commit_expr_expecting(&*e2, - token::CloseDelim(token::Bracket)); - Some(e2) - } - }; - hi = self.span.hi; - let slice = self.mk_slice(e, Some(ix), e2, mutbl); - e = self.mk_expr(lo, hi, slice) - } - // e[e] - _ => { - if mutbl == ast::MutMutable { - self.span_err(e.span, - "`mut` keyword is invalid in index expressions"); - } - hi = self.span.hi; - self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)); - let index = self.mk_index(e, ix); - e = self.mk_expr(lo, hi, index) - } - } - } + if found_dotdot { + self.span_err(e.span, "incorrect slicing expression: `[..]`"); + self.span_note(e.span, + "use `&expr[]` to construct a slice of the whole of expr"); } } @@ -2655,6 +2598,70 @@ impl<'a> Parser<'a> { return e; } + // Parse unquoted tokens after a `$` in a token tree + fn parse_unquoted(&mut self) -> TokenTree { + let mut sp = self.span; + let (name, namep) = match self.token { + token::Dollar => { + self.bump(); + + if self.token == token::OpenDelim(token::Paren) { + let Spanned { node: seq, span: seq_span } = self.parse_seq( + &token::OpenDelim(token::Paren), + &token::CloseDelim(token::Paren), + seq_sep_none(), + |p| p.parse_token_tree() + ); + let (sep, repeat) = self.parse_sep_and_kleene_op(); + let name_num = macro_parser::count_names(seq.as_slice()); + return TtSequence(mk_sp(sp.lo, seq_span.hi), + Rc::new(SequenceRepetition { + tts: seq, + separator: sep, + op: repeat, + num_captures: name_num + })); + } else if self.token.is_keyword_allow_following_colon(keywords::Crate) { + self.bump(); + return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)); + } else { + sp = mk_sp(sp.lo, self.span.hi); + let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain }; + let name = self.parse_ident(); + (name, namep) + } + } + token::SubstNt(name, namep) => { + self.bump(); + (name, namep) + } + _ => unreachable!() + }; + // continue by trying to parse the `:ident` after `$name` + if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() && + !t.is_strict_keyword() && + !t.is_reserved_keyword()) { + self.bump(); + sp = mk_sp(sp.lo, self.span.hi); + let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain }; + let nt_kind = self.parse_ident(); + TtToken(sp, MatchNt(name, nt_kind, namep, kindp)) + } else { + TtToken(sp, SubstNt(name, namep)) + } + } + + pub fn check_unknown_macro_variable(&mut self) { + if self.quote_depth == 0u { + match self.token { + token::SubstNt(name, _) => + self.fatal(format!("unknown macro variable `{}`", + token::get_ident(name)).index(&FullRange)), + _ => {} + } + } + } + /// Parse an optional separator followed by a Kleene-style /// repetition token (+ or *). pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) { @@ -2701,63 +2708,25 @@ impl<'a> Parser<'a> { fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree { maybe_whole!(deref p, NtTT); match p.token { - token::CloseDelim(_) => { - // This is a conservative error: only report the last unclosed delimiter. The - // previous unclosed delimiters could actually be closed! The parser just hasn't - // gotten to them yet. - match p.open_braces.last() { - None => {} - Some(&sp) => p.span_note(sp, "unclosed delimiter"), - }; - let token_str = p.this_token_to_string(); - p.fatal(format!("incorrect close delimiter: `{}`", - token_str)[]) - }, - /* we ought to allow different depths of unquotation */ - token::Dollar if p.quote_depth > 0u => { - p.bump(); - let sp = p.span; - - if p.token == token::OpenDelim(token::Paren) { - let seq = p.parse_seq( - &token::OpenDelim(token::Paren), - &token::CloseDelim(token::Paren), - seq_sep_none(), - |p| p.parse_token_tree() - ); - let (sep, repeat) = p.parse_sep_and_kleene_op(); - let seq = match seq { - Spanned { node, .. } => node, + token::CloseDelim(_) => { + // This is a conservative error: only report the last unclosed delimiter. The + // previous unclosed delimiters could actually be closed! The parser just hasn't + // gotten to them yet. + match p.open_braces.last() { + None => {} + Some(&sp) => p.span_note(sp, "unclosed delimiter"), }; - let name_num = macro_parser::count_names(seq[]); - TtSequence(mk_sp(sp.lo, p.span.hi), - Rc::new(SequenceRepetition { - tts: seq, - separator: sep, - op: repeat, - num_captures: name_num - })) - } else if p.token.is_keyword_allow_following_colon(keywords::Crate) { - p.bump(); - TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)) - } else { - // A nonterminal that matches or not - let namep = match p.token { token::Ident(_, p) => p, _ => token::Plain }; - let name = p.parse_ident(); - if p.token == token::Colon && p.look_ahead(1, |t| t.is_ident()) { - p.bump(); - let kindp = match p.token { token::Ident(_, p) => p, _ => token::Plain }; - let nt_kind = p.parse_ident(); - let m = TtToken(sp, MatchNt(name, nt_kind, namep, kindp)); - m - } else { - TtToken(sp, SubstNt(name, namep)) - } + let token_str = p.this_token_to_string(); + p.fatal(format!("incorrect close delimiter: `{}`", + token_str).index(&FullRange)) + }, + /* we ought to allow different depths of unquotation */ + token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => { + p.parse_unquoted() + } + _ => { + TtToken(p.span, p.bump_and_get()) } - } - _ => { - TtToken(p.span, p.bump_and_get()) - } } } @@ -2890,7 +2859,7 @@ impl<'a> Parser<'a> { let this_token_to_string = self.this_token_to_string(); self.span_err(span, format!("expected expression, found `{}`", - this_token_to_string)[]); + this_token_to_string).index(&FullRange)); let box_span = mk_sp(lo, self.last_span.hi); self.span_help(box_span, "perhaps you meant `box() (foo)` instead?"); @@ -3273,7 +3242,7 @@ impl<'a> Parser<'a> { if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", "}", - token_str)[]) + token_str).index(&FullRange)) } etc = true; break; @@ -3294,7 +3263,7 @@ impl<'a> Parser<'a> { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_string(); self.fatal(format!("unexpected `{}`", - token_str)[]) + token_str).index(&FullRange)) } _ => {} } @@ -3577,7 +3546,7 @@ impl<'a> Parser<'a> { let span = self.span; let tok_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected identifier, found `{}`", tok_str)[]); + format!("expected identifier, found `{}`", tok_str).index(&FullRange)); } let ident = self.parse_ident(); let last_span = self.last_span; @@ -3674,7 +3643,7 @@ impl<'a> Parser<'a> { let lo = self.span.lo; if self.token.is_keyword(keywords::Let) { - check_expected_item(self, item_attrs[]); + check_expected_item(self, item_attrs.index(&FullRange)); self.expect_keyword(keywords::Let); let decl = self.parse_let(); P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) @@ -3683,7 +3652,7 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| *t == token::Not) { // it's a macro invocation: - check_expected_item(self, item_attrs[]); + check_expected_item(self, item_attrs.index(&FullRange)); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... @@ -3711,7 +3680,7 @@ impl<'a> Parser<'a> { let tok_str = self.this_token_to_string(); self.fatal(format!("expected {}`(` or `{{`, found `{}`", ident_str, - tok_str)[]) + tok_str).index(&FullRange)) }, }; @@ -3759,7 +3728,7 @@ impl<'a> Parser<'a> { } } else { let found_attrs = !item_attrs.is_empty(); - let item_err = Parser::expected_item_err(item_attrs[]); + let item_err = Parser::expected_item_err(item_attrs.index(&FullRange)); match self.parse_item_or_view_item(item_attrs, false) { IoviItem(i) => { let hi = i.span.hi; @@ -3803,7 +3772,7 @@ impl<'a> Parser<'a> { let sp = self.span; let tok = self.this_token_to_string(); self.span_fatal_help(sp, - format!("expected `{{`, found `{}`", tok)[], + format!("expected `{{`, found `{}`", tok).index(&FullRange), "place this code inside a block"); } @@ -3857,13 +3826,13 @@ impl<'a> Parser<'a> { while self.token != token::CloseDelim(token::Brace) { // parsing items even when they're not allowed lets us give // better error messages and recover more gracefully. - attributes_box.push_all(self.parse_outer_attributes()[]); + attributes_box.push_all(self.parse_outer_attributes().index(&FullRange)); match self.token { token::Semi => { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box[])); + Parser::expected_item_err(attributes_box.index(&FullRange))); attributes_box = Vec::new(); } self.bump(); // empty @@ -3955,7 +3924,7 @@ impl<'a> Parser<'a> { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box[])); + Parser::expected_item_err(attributes_box.index(&FullRange))); } let hi = self.span.hi; @@ -4399,7 +4368,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `self`, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -4553,7 +4522,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `,` or `)`, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -4729,7 +4698,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = self.parse_inner_attrs_and_block(); let body_span = body.span; let mut new_attrs = attrs; - new_attrs.push_all(inner_attrs[]); + new_attrs.push_all(inner_attrs.index(&FullRange)); (ast::MethDecl(ident, generics, abi, @@ -4948,7 +4917,7 @@ impl<'a> Parser<'a> { if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone()))[]); + token::get_ident(class_name.clone())).index(&FullRange)); } self.bump(); @@ -4956,7 +4925,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.fatal(format!("expected `where`, or `{}` after struct \ name, found `{}`", "{", - token_str)[]); + token_str).index(&FullRange)); } fields @@ -4987,7 +4956,7 @@ impl<'a> Parser<'a> { if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone()))[]); + token::get_ident(class_name.clone())).index(&FullRange)); } self.parse_where_clause(generics); @@ -5002,7 +4971,7 @@ impl<'a> Parser<'a> { } else { let token_str = self.this_token_to_string(); self.fatal(format!("expected `where`, `{}`, `(`, or `;` after struct \ - name, found `{}`", "{", token_str)[]); + name, found `{}`", "{", token_str).index(&FullRange)); } } @@ -5022,7 +4991,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.span_fatal_help(span, format!("expected `,`, or `}}`, found `{}`", - token_str)[], + token_str).index(&FullRange), "struct fields should be separated by commas") } } @@ -5109,11 +5078,11 @@ impl<'a> Parser<'a> { let mut attrs = self.parse_outer_attributes(); if first { let mut tmp = attrs_remaining.clone(); - tmp.push_all(attrs[]); + tmp.push_all(attrs.index(&FullRange)); attrs = tmp; first = false; } - debug!("parse_mod_items: parse_item_or_view_item(attrs={})", + debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})", attrs); match self.parse_item_or_view_item(attrs, true /* macros allowed */) { @@ -5126,7 +5095,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected item, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -5135,7 +5104,7 @@ impl<'a> Parser<'a> { // 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_remaining.index(&FullRange))); } ast::Mod { @@ -5205,7 +5174,7 @@ impl<'a> Parser<'a> { -> (ast::Item_, Vec<ast::Attribute> ) { let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span)); prefix.pop(); - let mod_path = Path::new(".").join_many(self.mod_path_stack[]); + let mod_path = Path::new(".").join_many(self.mod_path_stack.index(&FullRange)); let dir_path = prefix.join(&mod_path); let mod_string = token::get_ident(id); let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name( @@ -5215,8 +5184,8 @@ impl<'a> Parser<'a> { let mod_name = mod_string.get().to_string(); let default_path_str = format!("{}.rs", mod_name); let secondary_path_str = format!("{}/mod.rs", mod_name); - let default_path = dir_path.join(default_path_str[]); - let secondary_path = dir_path.join(secondary_path_str[]); + let default_path = dir_path.join(default_path_str.index(&FullRange)); + let secondary_path = dir_path.join(secondary_path_str.index(&FullRange)); let default_exists = default_path.exists(); let secondary_exists = secondary_path.exists(); @@ -5231,13 +5200,13 @@ impl<'a> Parser<'a> { format!("maybe move this module `{0}` \ to its own directory via \ `{0}/mod.rs`", - this_module)[]); + this_module).index(&FullRange)); if default_exists || secondary_exists { self.span_note(id_sp, format!("... or maybe `use` the module \ `{}` instead of possibly \ redeclaring it", - mod_name)[]); + mod_name).index(&FullRange)); } self.abort_if_errors(); } @@ -5248,12 +5217,12 @@ impl<'a> Parser<'a> { (false, false) => { self.span_fatal_help(id_sp, format!("file not found for module `{}`", - mod_name)[], + mod_name).index(&FullRange), format!("name the file either {} or {} inside \ - the directory {}", + the directory {:?}", default_path_str, secondary_path_str, - dir_path.display())[]); + dir_path.display()).index(&FullRange)); } (true, true) => { self.span_fatal_help( @@ -5262,7 +5231,7 @@ impl<'a> Parser<'a> { and {}", mod_name, default_path_str, - secondary_path_str)[], + secondary_path_str).index(&FullRange), "delete or rename one of them to remove the ambiguity"); } } @@ -5284,11 +5253,11 @@ impl<'a> Parser<'a> { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); for p in included_mod_stack.slice(i, len).iter() { - err.push_str(p.display().as_cow()[]); + err.push_str(p.display().as_cow().index(&FullRange)); err.push_str(" -> "); } - err.push_str(path.display().as_cow()[]); - self.span_fatal(id_sp, err[]); + err.push_str(path.display().as_cow().index(&FullRange)); + self.span_fatal(id_sp, err.index(&FullRange)); } None => () } @@ -5369,7 +5338,7 @@ impl<'a> Parser<'a> { if !attrs_remaining.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attrs_remaining[])); + Parser::expected_item_err(attrs_remaining.index(&FullRange))); } assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { @@ -5410,7 +5379,7 @@ impl<'a> Parser<'a> { self.span_help(span, format!("perhaps you meant to enclose the crate name `{}` in \ a string?", - the_ident.as_str())[]); + the_ident.as_str()).index(&FullRange)); None } else { None @@ -5436,7 +5405,7 @@ impl<'a> Parser<'a> { self.span_fatal(span, format!("expected extern crate name but \ found `{}`", - token_str)[]); + token_str).index(&FullRange)); } }; @@ -5534,7 +5503,7 @@ impl<'a> Parser<'a> { self.span_err(start_span, format!("unit-like struct variant should be written \ without braces, as `{},`", - token::get_ident(ident))[]); + token::get_ident(ident)).index(&FullRange)); } kind = StructVariantKind(struct_def); } else if self.check(&token::OpenDelim(token::Paren)) { @@ -5619,7 +5588,7 @@ impl<'a> Parser<'a> { format!("illegal ABI: expected one of [{}], \ found `{}`", abi::all_names().connect(", "), - the_string)[]); + the_string).index(&FullRange)); None } } @@ -5681,7 +5650,7 @@ impl<'a> Parser<'a> { format!("`extern mod` is obsolete, use \ `extern crate` instead \ to refer to external \ - crates.")[]) + crates.").index(&FullRange)) } return self.parse_item_extern_crate(lo, visibility, attrs); } @@ -5709,7 +5678,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected `{}` or `fn`, found `{}`", "{", - token_str)[]); + token_str).index(&FullRange)); } if self.eat_keyword(keywords::Virtual) { @@ -5822,7 +5791,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = - self.parse_item_mod(attrs[]); + self.parse_item_mod(attrs.index(&FullRange)); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, @@ -6162,7 +6131,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes()[]); + attrs.push_all(self.parse_outer_attributes().index(&FullRange)); // First, parse view items. let mut view_items : Vec<ast::ViewItem> = Vec::new(); let mut items = Vec::new(); @@ -6244,7 +6213,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes()[]); + attrs.push_all(self.parse_outer_attributes().index(&FullRange)); let mut foreign_items = Vec::new(); loop { match self.parse_foreign_item(attrs, macros_allowed) { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 094aacf3207..013bce1755b 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -392,6 +392,7 @@ impl fmt::Show for Nonterminal { } } + // Get the first "argument" macro_rules! first { ( $first:expr, $( $remainder:expr, )* ) => ( $first ) @@ -479,7 +480,7 @@ macro_rules! declare_special_idents_and_keywords {( $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* - interner::StrInterner::prefill(init_vec[]) + interner::StrInterner::prefill(init_vec.index(&FullRange)) } }} @@ -515,66 +516,66 @@ declare_special_idents_and_keywords! { (9, unnamed_field, "<unnamed_field>"); (10, type_self, "Self"); (11, prelude_import, "prelude_import"); + (12, FullRange, "FullRange"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: - (12, As, "as"); - (13, Break, "break"); - (14, Crate, "crate"); - (15, Else, "else"); - (16, Enum, "enum"); - (17, Extern, "extern"); - (18, False, "false"); - (19, Fn, "fn"); - (20, For, "for"); - (21, If, "if"); - (22, Impl, "impl"); - (23, In, "in"); - (24, Let, "let"); - (25, Loop, "loop"); - (26, Match, "match"); - (27, Mod, "mod"); - (28, Move, "move"); - (29, Mut, "mut"); - (30, Pub, "pub"); - (31, Ref, "ref"); - (32, Return, "return"); + (13, As, "as"); + (14, Break, "break"); + (15, Crate, "crate"); + (16, Else, "else"); + (17, Enum, "enum"); + (18, Extern, "extern"); + (19, False, "false"); + (20, Fn, "fn"); + (21, For, "for"); + (22, If, "if"); + (23, Impl, "impl"); + (24, In, "in"); + (25, Let, "let"); + (26, Loop, "loop"); + (27, Match, "match"); + (28, Mod, "mod"); + (29, Move, "move"); + (30, Mut, "mut"); + (31, Pub, "pub"); + (32, Ref, "ref"); + (33, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, Self, "self"); - (33, Struct, "struct"); + (34, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); - (34, True, "true"); - (35, Trait, "trait"); - (36, Type, "type"); - (37, Unsafe, "unsafe"); - (38, Use, "use"); - (39, Virtual, "virtual"); - (40, While, "while"); - (41, Continue, "continue"); - (42, Proc, "proc"); - (43, Box, "box"); - (44, Const, "const"); - (45, Where, "where"); - + (35, True, "true"); + (36, Trait, "trait"); + (37, Type, "type"); + (38, Unsafe, "unsafe"); + (39, Use, "use"); + (40, Virtual, "virtual"); + (41, While, "while"); + (42, Continue, "continue"); + (43, Proc, "proc"); + (44, Box, "box"); + (45, Const, "const"); + (46, Where, "where"); 'reserved: - (46, Alignof, "alignof"); - (47, Be, "be"); - (48, Offsetof, "offsetof"); - (49, Priv, "priv"); - (50, Pure, "pure"); - (51, Sizeof, "sizeof"); - (52, Typeof, "typeof"); - (53, Unsized, "unsized"); - (54, Yield, "yield"); - (55, Do, "do"); - (56, Abstract, "abstract"); - (57, Final, "final"); - (58, Override, "override"); - (59, Macro, "macro"); + (47, Alignof, "alignof"); + (48, Be, "be"); + (49, Offsetof, "offsetof"); + (50, Priv, "priv"); + (51, Pure, "pure"); + (52, Sizeof, "sizeof"); + (53, Typeof, "typeof"); + (54, Unsized, "unsized"); + (55, Yield, "yield"); + (56, Do, "do"); + (57, Abstract, "abstract"); + (58, Final, "final"); + (59, Override, "override"); + (60, Macro, "macro"); } } @@ -628,7 +629,7 @@ impl InternedString { #[inline] pub fn get<'a>(&'a self) -> &'a str { - self.string[] + self.string.index(&FullRange) } } @@ -652,59 +653,47 @@ impl BytesContainer for InternedString { impl fmt::Show for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.string[]) + fmt::String::fmt(self, f) + } +} + +impl fmt::String for InternedString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.string.index(&FullRange)) } } impl<'a> PartialEq<&'a str> for InternedString { #[inline(always)] fn eq(&self, other: & &'a str) -> bool { - PartialEq::eq(self.string[], *other) + PartialEq::eq(self.string.index(&FullRange), *other) } #[inline(always)] fn ne(&self, other: & &'a str) -> bool { - PartialEq::ne(self.string[], *other) + PartialEq::ne(self.string.index(&FullRange), *other) } } impl<'a> PartialEq<InternedString > for &'a str { #[inline(always)] fn eq(&self, other: &InternedString) -> bool { - PartialEq::eq(*self, other.string[]) + PartialEq::eq(*self, other.string.index(&FullRange)) } #[inline(always)] fn ne(&self, other: &InternedString) -> bool { - PartialEq::ne(*self, other.string[]) + PartialEq::ne(*self, other.string.index(&FullRange)) } } -#[cfg(stage0)] -impl<D:Decoder<E>, E> Decodable<D, E> for InternedString { - fn decode(d: &mut D) -> Result<InternedString, E> { - Ok(get_name(get_ident_interner().intern( - try!(d.read_str())[]))) - } -} - -#[cfg(not(stage0))] impl Decodable for InternedString { fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> { - Ok(get_name(get_ident_interner().intern( - try!(d.read_str())[]))) - } -} - -#[cfg(stage0)] -impl<S:Encoder<E>, E> Encodable<S, E> for InternedString { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self.string[]) + Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange)))) } } -#[cfg(not(stage0))] impl Encodable for InternedString { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.string[]) + s.emit_str(self.string.index(&FullRange)) } } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 11cefc8719b..52306075c21 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -140,7 +140,7 @@ pub fn buf_str(toks: Vec<Token>, } s.push_str(format!("{}={}", szs[i], - tok_str(toks[i].clone()))[]); + tok_str(toks[i].clone())).index(&FullRange)); i += 1u; i %= n; } @@ -602,7 +602,7 @@ impl Printer { assert_eq!(l, len); // assert!(l <= space); self.space -= len; - self.print_str(s[]) + self.print_str(s.index(&FullRange)) } Eof => { // Eof should never get here. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 402583b60fa..87dcc9e70f4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -114,7 +114,7 @@ pub fn print_crate<'a>(cm: &'a CodeMap, out, ann, is_expanded); - try!(s.print_mod(&krate.module, krate.attrs[])); + try!(s.print_mod(&krate.module, krate.attrs.index(&FullRange))); try!(s.print_remaining_comments()); eof(&mut s.s) } @@ -580,7 +580,7 @@ impl<'a> State<'a> { pub fn synth_comment(&mut self, text: String) -> IoResult<()> { try!(word(&mut self.s, "/*")); try!(space(&mut self.s)); - try!(word(&mut self.s, text[])); + try!(word(&mut self.s, text.index(&FullRange))); try!(space(&mut self.s)); word(&mut self.s, "*/") } @@ -685,7 +685,7 @@ impl<'a> State<'a> { } ast::TyTup(ref elts) => { try!(self.popen()); - try!(self.commasep(Inconsistent, elts[], + try!(self.commasep(Inconsistent, elts.index(&FullRange), |s, ty| s.print_type(&**ty))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -721,10 +721,10 @@ impl<'a> State<'a> { } ast::TyObjectSum(ref ty, ref bounds) => { try!(self.print_type(&**ty)); - try!(self.print_bounds("+", bounds[])); + try!(self.print_bounds("+", bounds.index(&FullRange))); } ast::TyPolyTraitRef(ref bounds) => { - try!(self.print_bounds("", bounds[])); + try!(self.print_bounds("", bounds.index(&FullRange))); } ast::TyQPath(ref qpath) => { try!(word(&mut self.s, "<")); @@ -759,7 +759,7 @@ impl<'a> State<'a> { item: &ast::ForeignItem) -> 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_outer_attributes(item.attrs.index(&FullRange))); match item.node { ast::ForeignItemFn(ref decl, ref generics) => { try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics, @@ -770,7 +770,7 @@ impl<'a> State<'a> { } ast::ForeignItemStatic(ref t, m) => { try!(self.head(visibility_qualified(item.vis, - "static")[])); + "static").index(&FullRange))); if m { try!(self.word_space("mut")); } @@ -787,7 +787,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, typedef: &ast::AssociatedType) -> IoResult<()> { - try!(self.print_outer_attributes(typedef.attrs[])); + try!(self.print_outer_attributes(typedef.attrs.index(&FullRange))); try!(self.word_space("type")); try!(self.print_ty_param(&typedef.ty_param)); word(&mut self.s, ";") @@ -806,12 +806,12 @@ impl<'a> State<'a> { pub fn print_item(&mut self, item: &ast::Item) -> 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_outer_attributes(item.attrs.index(&FullRange))); try!(self.ann.pre(self, NodeItem(item))); match item.node { ast::ItemStatic(ref ty, m, ref expr) => { try!(self.head(visibility_qualified(item.vis, - "static")[])); + "static").index(&FullRange))); if m == ast::MutMutable { try!(self.word_space("mut")); } @@ -828,7 +828,7 @@ impl<'a> State<'a> { } ast::ItemConst(ref ty, ref expr) => { try!(self.head(visibility_qualified(item.vis, - "const")[])); + "const").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.word_space(":")); try!(self.print_type(&**ty)); @@ -851,29 +851,29 @@ impl<'a> State<'a> { item.vis )); try!(word(&mut self.s, " ")); - try!(self.print_block_with_attrs(&**body, item.attrs[])); + try!(self.print_block_with_attrs(&**body, item.attrs.index(&FullRange))); } ast::ItemMod(ref _mod) => { try!(self.head(visibility_qualified(item.vis, - "mod")[])); + "mod").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.nbsp()); try!(self.bopen()); - try!(self.print_mod(_mod, item.attrs[])); + try!(self.print_mod(_mod, item.attrs.index(&FullRange))); try!(self.bclose(item.span)); } ast::ItemForeignMod(ref nmod) => { try!(self.head("extern")); - try!(self.word_nbsp(nmod.abi.to_string()[])); + try!(self.word_nbsp(nmod.abi.to_string().index(&FullRange))); try!(self.bopen()); - try!(self.print_foreign_mod(nmod, item.attrs[])); + try!(self.print_foreign_mod(nmod, item.attrs.index(&FullRange))); try!(self.bclose(item.span)); } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); try!(self.ibox(0u)); try!(self.word_nbsp(visibility_qualified(item.vis, - "type")[])); + "type").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); try!(self.end()); // end the inner ibox @@ -895,7 +895,7 @@ impl<'a> State<'a> { )); } ast::ItemStruct(ref struct_def, ref generics) => { - try!(self.head(visibility_qualified(item.vis,"struct")[])); + try!(self.head(visibility_qualified(item.vis,"struct").index(&FullRange))); try!(self.print_struct(&**struct_def, generics, item.ident, item.span)); } @@ -936,7 +936,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.bopen()); - try!(self.print_inner_attributes(item.attrs[])); + try!(self.print_inner_attributes(item.attrs.index(&FullRange))); for impl_item in impl_items.iter() { match *impl_item { ast::MethodImplItem(ref meth) => { @@ -967,7 +967,7 @@ impl<'a> State<'a> { real_bounds.push(b); } } - try!(self.print_bounds(":", real_bounds[])); + try!(self.print_bounds(":", real_bounds.index(&FullRange))); try!(self.print_where_clause(generics)); try!(word(&mut self.s, " ")); try!(self.bopen()); @@ -985,7 +985,7 @@ impl<'a> State<'a> { try!(self.print_ident(item.ident)); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts[])); + try!(self.print_tts(tts.index(&FullRange))); try!(self.pclose()); try!(word(&mut self.s, ";")); try!(self.end()); @@ -1019,12 +1019,12 @@ impl<'a> State<'a> { generics: &ast::Generics, ident: ast::Ident, span: codemap::Span, visibility: ast::Visibility) -> IoResult<()> { - try!(self.head(visibility_qualified(visibility, "enum")[])); + try!(self.head(visibility_qualified(visibility, "enum").index(&FullRange))); try!(self.print_ident(ident)); try!(self.print_generics(generics)); try!(self.print_where_clause(generics)); try!(space(&mut self.s)); - self.print_variants(enum_definition.variants[], span) + self.print_variants(enum_definition.variants.index(&FullRange), span) } pub fn print_variants(&mut self, @@ -1034,7 +1034,7 @@ impl<'a> State<'a> { for v in variants.iter() { try!(self.space_if_not_bol()); try!(self.maybe_print_comment(v.span.lo)); - try!(self.print_outer_attributes(v.node.attrs[])); + try!(self.print_outer_attributes(v.node.attrs.index(&FullRange))); try!(self.ibox(indent_unit)); try!(self.print_variant(&**v)); try!(word(&mut self.s, ",")); @@ -1062,7 +1062,7 @@ impl<'a> State<'a> { if !struct_def.fields.is_empty() { try!(self.popen()); try!(self.commasep( - Inconsistent, struct_def.fields[], + Inconsistent, struct_def.fields.index(&FullRange), |s, field| { match field.node.kind { ast::NamedField(..) => panic!("unexpected named field"), @@ -1092,7 +1092,7 @@ impl<'a> State<'a> { ast::NamedField(ident, visibility) => { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(field.span.lo)); - try!(self.print_outer_attributes(field.node.attrs[])); + try!(self.print_outer_attributes(field.node.attrs.index(&FullRange))); try!(self.print_visibility(visibility)); try!(self.print_ident(ident)); try!(self.word_nbsp(":")); @@ -1116,7 +1116,7 @@ impl<'a> State<'a> { pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> { match *tt { ast::TtToken(_, ref tk) => { - try!(word(&mut self.s, token_to_string(tk)[])); + try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); match *tk { parse::token::DocComment(..) => { hardbreak(&mut self.s) @@ -1125,11 +1125,11 @@ impl<'a> State<'a> { } } ast::TtDelimited(_, ref delimed) => { - try!(word(&mut self.s, token_to_string(&delimed.open_token())[])); + try!(word(&mut self.s, token_to_string(&delimed.open_token()).index(&FullRange))); try!(space(&mut self.s)); - try!(self.print_tts(delimed.tts[])); + try!(self.print_tts(delimed.tts.index(&FullRange))); try!(space(&mut self.s)); - word(&mut self.s, token_to_string(&delimed.close_token())[]) + word(&mut self.s, token_to_string(&delimed.close_token()).index(&FullRange)) }, ast::TtSequence(_, ref seq) => { try!(word(&mut self.s, "$(")); @@ -1139,7 +1139,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, ")")); match seq.separator { Some(ref tk) => { - try!(word(&mut self.s, token_to_string(tk)[])); + try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); } None => {}, } @@ -1170,7 +1170,7 @@ impl<'a> State<'a> { if !args.is_empty() { try!(self.popen()); try!(self.commasep(Consistent, - args[], + args.index(&FullRange), |s, arg| s.print_type(&*arg.ty))); try!(self.pclose()); } @@ -1194,7 +1194,7 @@ impl<'a> State<'a> { pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(m.span.lo)); - try!(self.print_outer_attributes(m.attrs[])); + try!(self.print_outer_attributes(m.attrs.index(&FullRange))); try!(self.print_ty_fn(None, None, m.unsafety, @@ -1226,7 +1226,7 @@ impl<'a> State<'a> { pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(meth.span.lo)); - try!(self.print_outer_attributes(meth.attrs[])); + try!(self.print_outer_attributes(meth.attrs.index(&FullRange))); match meth.node { ast::MethDecl(ident, ref generics, @@ -1244,7 +1244,7 @@ impl<'a> State<'a> { Some(&explicit_self.node), vis)); try!(word(&mut self.s, " ")); - self.print_block_with_attrs(&**body, meth.attrs[]) + self.print_block_with_attrs(&**body, meth.attrs.index(&FullRange)) }, ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _), ..}) => { @@ -1253,7 +1253,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "! ")); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts[])); + try!(self.print_tts(tts.index(&FullRange))); try!(self.pclose()); try!(word(&mut self.s, ";")); self.end() @@ -1520,7 +1520,7 @@ impl<'a> State<'a> { ast::ExprVec(ref exprs) => { try!(self.ibox(indent_unit)); try!(word(&mut self.s, "[")); - try!(self.commasep_exprs(Inconsistent, exprs[])); + try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); try!(word(&mut self.s, "]")); try!(self.end()); } @@ -1537,36 +1537,38 @@ impl<'a> State<'a> { ast::ExprStruct(ref path, ref fields, ref wth) => { try!(self.print_path(path, true)); - try!(word(&mut self.s, "{")); - try!(self.commasep_cmnt( - Consistent, - fields[], - |s, field| { - try!(s.ibox(indent_unit)); - try!(s.print_ident(field.ident.node)); - try!(s.word_space(":")); - try!(s.print_expr(&*field.expr)); - s.end() - }, - |f| f.span)); - match *wth { - Some(ref expr) => { - try!(self.ibox(indent_unit)); - if !fields.is_empty() { - try!(word(&mut self.s, ",")); - try!(space(&mut self.s)); + if !(fields.is_empty() && wth.is_none()) { + try!(word(&mut self.s, "{")); + try!(self.commasep_cmnt( + Consistent, + fields.index(&FullRange), + |s, field| { + try!(s.ibox(indent_unit)); + try!(s.print_ident(field.ident.node)); + try!(s.word_space(":")); + try!(s.print_expr(&*field.expr)); + s.end() + }, + |f| f.span)); + match *wth { + Some(ref expr) => { + try!(self.ibox(indent_unit)); + if !fields.is_empty() { + try!(word(&mut self.s, ",")); + try!(space(&mut self.s)); + } + try!(word(&mut self.s, "..")); + try!(self.print_expr(&**expr)); + try!(self.end()); } - try!(word(&mut self.s, "..")); - try!(self.print_expr(&**expr)); - try!(self.end()); + _ => try!(word(&mut self.s, ",")), } - _ => try!(word(&mut self.s, ",")) + try!(word(&mut self.s, "}")); } - try!(word(&mut self.s, "}")); } ast::ExprTup(ref exprs) => { try!(self.popen()); - try!(self.commasep_exprs(Inconsistent, exprs[])); + try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); if exprs.len() == 1 { try!(word(&mut self.s, ",")); } @@ -1574,7 +1576,7 @@ impl<'a> State<'a> { } ast::ExprCall(ref func, ref args) => { try!(self.print_expr_maybe_paren(&**func)); - try!(self.print_call_post(args[])); + try!(self.print_call_post(args.index(&FullRange))); } ast::ExprMethodCall(ident, ref tys, ref args) => { let base_args = args.slice_from(1); @@ -1583,7 +1585,7 @@ impl<'a> State<'a> { try!(self.print_ident(ident.node)); if tys.len() > 0u { try!(word(&mut self.s, "::<")); - try!(self.commasep(Inconsistent, tys[], + try!(self.commasep(Inconsistent, tys.index(&FullRange), |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ">")); } @@ -1780,11 +1782,11 @@ impl<'a> State<'a> { try!(self.print_string(a.asm.get(), a.asm_str_style)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.outputs[], + try!(self.commasep(Inconsistent, a.outputs.index(&FullRange), |s, &(ref co, ref o, is_rw)| { match co.get().slice_shift_char() { Some(('=', operand)) if is_rw => { - try!(s.print_string(format!("+{}", operand)[], + try!(s.print_string(format!("+{}", operand).index(&FullRange), ast::CookedStr)) } _ => try!(s.print_string(co.get(), ast::CookedStr)) @@ -1797,7 +1799,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.inputs[], + try!(self.commasep(Inconsistent, a.inputs.index(&FullRange), |s, &(ref co, ref o)| { try!(s.print_string(co.get(), ast::CookedStr)); try!(s.popen()); @@ -1808,7 +1810,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.clobbers[], + try!(self.commasep(Inconsistent, a.clobbers.index(&FullRange), |s, co| { try!(s.print_string(co.get(), ast::CookedStr)); Ok(()) @@ -1882,7 +1884,7 @@ impl<'a> State<'a> { pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> { if self.encode_idents_with_hygiene { let encoded = ident.encode_with_hygiene(); - try!(word(&mut self.s, encoded[])) + try!(word(&mut self.s, encoded.index(&FullRange))) } else { try!(word(&mut self.s, token::get_ident(ident).get())) } @@ -1890,7 +1892,7 @@ impl<'a> State<'a> { } pub fn print_uint(&mut self, i: uint) -> IoResult<()> { - word(&mut self.s, i.to_string()[]) + word(&mut self.s, i.to_string().index(&FullRange)) } pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> { @@ -1964,7 +1966,7 @@ impl<'a> State<'a> { } try!(self.commasep( Inconsistent, - data.types[], + data.types.index(&FullRange), |s, ty| s.print_type(&**ty))); comma = true; } @@ -1987,7 +1989,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "(")); try!(self.commasep( Inconsistent, - data.inputs[], + data.inputs.index(&FullRange), |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ")")); @@ -2040,7 +2042,7 @@ impl<'a> State<'a> { Some(ref args) => { if !args.is_empty() { try!(self.popen()); - try!(self.commasep(Inconsistent, args[], + try!(self.commasep(Inconsistent, args.index(&FullRange), |s, p| s.print_pat(&**p))); try!(self.pclose()); } @@ -2052,7 +2054,7 @@ impl<'a> State<'a> { try!(self.nbsp()); try!(self.word_space("{")); try!(self.commasep_cmnt( - Consistent, fields[], + Consistent, fields.index(&FullRange), |s, f| { try!(s.cbox(indent_unit)); if !f.node.is_shorthand { @@ -2073,7 +2075,7 @@ impl<'a> State<'a> { ast::PatTup(ref elts) => { try!(self.popen()); try!(self.commasep(Inconsistent, - elts[], + elts.index(&FullRange), |s, p| s.print_pat(&**p))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -2101,7 +2103,7 @@ impl<'a> State<'a> { ast::PatVec(ref before, ref slice, ref after) => { try!(word(&mut self.s, "[")); try!(self.commasep(Inconsistent, - before[], + before.index(&FullRange), |s, p| s.print_pat(&**p))); for p in slice.iter() { if !before.is_empty() { try!(self.word_space(",")); } @@ -2115,7 +2117,7 @@ impl<'a> State<'a> { if !after.is_empty() { try!(self.word_space(",")); } } try!(self.commasep(Inconsistent, - after[], + after.index(&FullRange), |s, p| s.print_pat(&**p))); try!(word(&mut self.s, "]")); } @@ -2132,7 +2134,7 @@ impl<'a> State<'a> { } try!(self.cbox(indent_unit)); try!(self.ibox(0u)); - try!(self.print_outer_attributes(arm.attrs[])); + try!(self.print_outer_attributes(arm.attrs.index(&FullRange))); let mut first = true; for p in arm.pats.iter() { if first { @@ -2232,7 +2234,7 @@ impl<'a> State<'a> { // HACK(eddyb) ignore the separately printed self argument. let args = if first { - decl.inputs[] + decl.inputs.index(&FullRange) } else { decl.inputs.slice_from(1) }; @@ -2398,7 +2400,7 @@ impl<'a> State<'a> { ints.push(i); } - try!(self.commasep(Inconsistent, ints[], |s, &idx| { + try!(self.commasep(Inconsistent, ints.index(&FullRange), |s, &idx| { if idx < generics.lifetimes.len() { let lifetime = &generics.lifetimes[idx]; s.print_lifetime_def(lifetime) @@ -2415,7 +2417,7 @@ impl<'a> State<'a> { pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> { try!(self.print_ident(param.ident)); - try!(self.print_bounds(":", param.bounds[])); + try!(self.print_bounds(":", param.bounds.index(&FullRange))); match param.default { Some(ref default) => { try!(space(&mut self.s)); @@ -2491,7 +2493,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, name.get())); try!(self.popen()); try!(self.commasep(Consistent, - items[], + items.index(&FullRange), |s, i| s.print_meta_item(&**i))); try!(self.pclose()); } @@ -2527,7 +2529,7 @@ impl<'a> State<'a> { try!(self.print_path(path, false)); try!(word(&mut self.s, "::{")); } - try!(self.commasep(Inconsistent, idents[], |s, w| { + try!(self.commasep(Inconsistent, idents.index(&FullRange), |s, w| { match w.node { ast::PathListIdent { name, .. } => { s.print_ident(name) @@ -2545,7 +2547,7 @@ 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_outer_attributes(item.attrs.index(&FullRange))); try!(self.print_visibility(item.vis)); match item.node { ast::ViewItemExternCrate(id, ref optional_path, _) => { @@ -2687,7 +2689,7 @@ impl<'a> State<'a> { try!(self.pclose()); } - try!(self.print_bounds(":", bounds[])); + try!(self.print_bounds(":", bounds.index(&FullRange))); try!(self.print_fn_output(decl)); @@ -2746,7 +2748,7 @@ impl<'a> State<'a> { try!(self.maybe_print_comment(lit.span.lo)); match self.next_lit(lit.span.lo) { Some(ref ltrl) => { - return word(&mut self.s, (*ltrl).lit[]); + return word(&mut self.s, (*ltrl).lit.index(&FullRange)); } _ => () } @@ -2756,7 +2758,7 @@ impl<'a> State<'a> { let mut res = String::from_str("b'"); ascii::escape_default(byte, |c| res.push(c as char)); res.push('\''); - word(&mut self.s, res[]) + word(&mut self.s, res.index(&FullRange)) } ast::LitChar(ch) => { let mut res = String::from_str("'"); @@ -2764,27 +2766,27 @@ impl<'a> State<'a> { res.push(c); } res.push('\''); - word(&mut self.s, res[]) + word(&mut self.s, res.index(&FullRange)) } ast::LitInt(i, t) => { match t { ast::SignedIntLit(st, ast::Plus) => { word(&mut self.s, - ast_util::int_ty_to_string(st, Some(i as i64))[]) + ast_util::int_ty_to_string(st, Some(i as i64)).index(&FullRange)) } ast::SignedIntLit(st, ast::Minus) => { let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); word(&mut self.s, - format!("-{}", istr)[]) + format!("-{}", istr).index(&FullRange)) } ast::UnsignedIntLit(ut) => { - word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[]) + word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice()) } ast::UnsuffixedIntLit(ast::Plus) => { - word(&mut self.s, format!("{}", i)[]) + word(&mut self.s, format!("{}", i).index(&FullRange)) } ast::UnsuffixedIntLit(ast::Minus) => { - word(&mut self.s, format!("-{}", i)[]) + word(&mut self.s, format!("-{}", i).index(&FullRange)) } } } @@ -2793,7 +2795,7 @@ impl<'a> State<'a> { format!( "{}{}", f.get(), - ast_util::float_ty_to_string(t)[])[]) + ast_util::float_ty_to_string(t).index(&FullRange)).index(&FullRange)) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitBool(val) => { @@ -2805,7 +2807,7 @@ impl<'a> State<'a> { ascii::escape_default(ch as u8, |ch| escaped.push(ch as char)); } - word(&mut self.s, format!("b\"{}\"", escaped)[]) + word(&mut self.s, format!("b\"{}\"", escaped).index(&FullRange)) } } } @@ -2846,7 +2848,7 @@ impl<'a> State<'a> { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1u); try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, cmnt.lines[0][])); + try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); zerobreak(&mut self.s) } comments::Isolated => { @@ -2855,7 +2857,7 @@ impl<'a> State<'a> { // Don't print empty lines because they will end up as trailing // whitespace if !line.is_empty() { - try!(word(&mut self.s, line[])); + try!(word(&mut self.s, line.index(&FullRange))); } try!(hardbreak(&mut self.s)); } @@ -2864,13 +2866,13 @@ impl<'a> State<'a> { comments::Trailing => { try!(word(&mut self.s, " ")); if cmnt.lines.len() == 1u { - try!(word(&mut self.s, cmnt.lines[0][])); + try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); hardbreak(&mut self.s) } else { try!(self.ibox(0u)); for line in cmnt.lines.iter() { if !line.is_empty() { - try!(word(&mut self.s, line[])); + try!(word(&mut self.s, line.index(&FullRange))); } try!(hardbreak(&mut self.s)); } @@ -2903,7 +2905,7 @@ impl<'a> State<'a> { string=st)) } }; - word(&mut self.s, st[]) + word(&mut self.s, st.index(&FullRange)) } pub fn next_comment(&mut self) -> Option<comments::Comment> { @@ -2934,7 +2936,7 @@ impl<'a> State<'a> { Some(abi::Rust) => Ok(()), Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string()[]) + self.word_nbsp(abi.to_string().index(&FullRange)) } None => Ok(()) } @@ -2945,7 +2947,7 @@ impl<'a> State<'a> { match opt_abi { Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string()[]) + self.word_nbsp(abi.to_string().index(&FullRange)) } None => Ok(()) } @@ -2961,7 +2963,7 @@ impl<'a> State<'a> { if abi != abi::Rust { try!(self.word_nbsp("extern")); - try!(self.word_nbsp(abi.to_string()[])); + try!(self.word_nbsp(abi.to_string().index(&FullRange))); } word(&mut self.s, "fn") diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 13eda7bb88f..8abb46011e6 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -111,28 +111,12 @@ impl<S, T: Hash<S>> Hash<S> for P<T> { } } -#[cfg(stage0)] -impl<E, D: Decoder<E>, T: 'static + Decodable<D, E>> Decodable<D, E> for P<T> { - fn decode(d: &mut D) -> Result<P<T>, E> { - Decodable::decode(d).map(P) - } -} - -#[cfg(not(stage0))] impl<T: 'static + Decodable> Decodable for P<T> { fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> { Decodable::decode(d).map(P) } } -#[cfg(stage0)] -impl<E, S: Encoder<E>, T: Encodable<S, E>> Encodable<S, E> for P<T> { - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -#[cfg(not(stage0))] impl<T: Encodable> Encodable for P<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 4ef7eb97a21..daa51203287 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -40,7 +40,7 @@ pub fn maybe_inject_prelude(krate: ast::Crate) -> ast::Crate { } fn use_std(krate: &ast::Crate) -> bool { - !attr::contains_name(krate.attrs[], "no_std") + !attr::contains_name(krate.attrs.index(&FullRange), "no_std") } fn no_prelude(attrs: &[ast::Attribute]) -> bool { @@ -56,7 +56,7 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { // The name to use in `extern crate "name" as std;` let actual_crate_name = match self.alt_std_name { - Some(ref s) => token::intern_and_get_ident(s[]), + Some(ref s) => token::intern_and_get_ident(s.index(&FullRange)), None => token::intern_and_get_ident("std"), }; @@ -104,7 +104,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { attr::mark_used(&no_std_attr); krate.attrs.push(no_std_attr); - if !no_prelude(krate.attrs[]) { + if !no_prelude(krate.attrs.index(&FullRange)) { // only add `use std::prelude::*;` if there wasn't a // `#![no_implicit_prelude]` at the crate level. // fold_mod() will insert glob path. @@ -124,7 +124,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { - if !no_prelude(item.attrs[]) { + if !no_prelude(item.attrs.index(&FullRange)) { // only recur if there wasn't `#![no_implicit_prelude]` // on this item, i.e. this means that the prelude is not // implicitly imported though the whole subtree diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index e480532a410..711715355e9 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -73,14 +73,14 @@ pub fn modify_for_testing(sess: &ParseSess, // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. - let should_test = attr::contains_name(krate.config[], "test"); + let should_test = attr::contains_name(krate.config.index(&FullRange), "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = - attr::first_attr_value_str_by_name(krate.attrs[], + attr::first_attr_value_str_by_name(krate.attrs.index(&FullRange), "reexport_test_harness_main"); if should_test { @@ -119,7 +119,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { self.cx.path.push(ident); } debug!("current path: {}", - ast_util::path_name_i(self.cx.path[])); + ast_util::path_name_i(self.cx.path.index(&FullRange))); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { @@ -194,7 +194,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { if !self.cx.path.is_empty() { self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); } else { - debug!("pushing nothing, sym: {}", sym); + debug!("pushing nothing, sym: {:?}", sym); self.cx.toplevel_reexport = Some(sym); } } @@ -277,8 +277,8 @@ fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { - !attr::contains_name(attrs[], "test") && - !attr::contains_name(attrs[], "bench") + !attr::contains_name(attrs.index(&FullRange), "test") && + !attr::contains_name(attrs.index(&FullRange), "bench") }) } @@ -291,7 +291,7 @@ enum HasTestSignature { fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_test_attr = attr::contains_name(i.attrs[], "test"); + let has_test_attr = attr::contains_name(i.attrs.index(&FullRange), "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { @@ -329,7 +329,7 @@ fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_bench_attr = attr::contains_name(i.attrs[], "bench"); + let has_bench_attr = attr::contains_name(i.attrs.index(&FullRange), "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { @@ -384,7 +384,7 @@ We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { - test::test_main_static(::os::args()[], tests) + test::test_main_static(::os::args().index(&FullRange), tests) } static tests : &'static [test::TestDescAndFn] = &[ @@ -510,8 +510,8 @@ fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { } fn is_test_crate(krate: &ast::Crate) -> bool { - match attr::find_crate_name(krate.attrs[]) { - Some(ref s) if "test" == s.get()[] => true, + match attr::find_crate_name(krate.attrs.index(&FullRange)) { + Some(ref s) if "test" == s.get().index(&FullRange) => true, _ => false } } @@ -551,11 +551,11 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> { // creates $name: $expr let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr); - debug!("encoding {}", ast_util::path_name_i(path[])); + debug!("encoding {}", ast_util::path_name_i(path.index(&FullRange))); // path to the #[test] function: "foo::bar::baz" - let path_string = ast_util::path_name_i(path[]); - let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string[])); + let path_string = ast_util::path_name_i(path.index(&FullRange)); + let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string.index(&FullRange))); // self::test::StaticTestName($name_expr) let name_expr = ecx.expr_call(span, diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 85eea2d9daf..93de342d487 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -28,7 +28,7 @@ pub struct Interner<T> { vect: RefCell<Vec<T> >, } -// when traits can extend traits, we should extend index<Name,T> to get [] +// when traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) impl<T: Eq + Hash + Clone + 'static> Interner<T> { pub fn new() -> Interner<T> { Interner { @@ -109,27 +109,27 @@ impl Eq for RcStr {} impl Ord for RcStr { fn cmp(&self, other: &RcStr) -> Ordering { - self[].cmp(other[]) + self.index(&FullRange).cmp(other.index(&FullRange)) } } impl fmt::Show for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Show; - self[].fmt(f) + self.index(&FullRange).fmt(f) } } impl BorrowFrom<RcStr> for str { fn borrow_from(owned: &RcStr) -> &str { - owned.string[] + owned.string.index(&FullRange) } } impl Deref for RcStr { type Target = str; - fn deref(&self) -> &str { self.string[] } + fn deref(&self) -> &str { self.string.index(&FullRange) } } /// A StrInterner differs from Interner<String> in that it accepts @@ -139,7 +139,7 @@ pub struct StrInterner { vect: RefCell<Vec<RcStr> >, } -/// When traits can extend traits, we should extend index<Name,T> to get [] +/// When traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) impl StrInterner { pub fn new() -> StrInterner { StrInterner { |
