diff options
Diffstat (limited to 'src/libsyntax')
45 files changed, 579 insertions, 745 deletions
diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 6766127a5f1..0a9e0aedd3d 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -100,7 +100,6 @@ impl 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) @@ -203,7 +202,7 @@ impl Encodable for Ident { impl Decodable for Ident { fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> { - Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) + Ok(str_to_ident(&try!(d.read_str())[])) } } @@ -1085,7 +1084,6 @@ pub enum IntTy { 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) @@ -1127,7 +1125,6 @@ impl UintTy { } } -//NOTE(stage0): remove after snapshot impl fmt::Show for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, f) @@ -1146,7 +1143,6 @@ 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) @@ -1734,11 +1730,8 @@ pub struct MacroDef { #[cfg(test)] mod test { - use serialize::json; use serialize; - use codemap::*; use super::*; - use std::fmt; // are ASTs encodable? #[test] diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 7496a0f9f26..3ef57279175 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -32,7 +32,7 @@ use std::slice; pub mod blocks; -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, Show)] pub enum PathElem { PathMod(Name), PathName(Name) @@ -46,13 +46,6 @@ 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()); @@ -90,7 +83,7 @@ impl<'a, T: Copy> Iterator for Values<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { - let &Values(ref mut items) = self; + let &mut Values(ref mut items) = self; items.next().map(|&x| x) } } @@ -106,7 +99,7 @@ pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String { if !s.is_empty() { s.push_str("::"); } - s.push_str(e.index(&FullRange)); + s.push_str(&e[]); s }).to_string() } @@ -483,20 +476,20 @@ impl<'ast> Map<'ast> { F: FnOnce(Option<&[Attribute]>) -> T, { let attrs = match self.get(id) { - NodeItem(i) => Some(i.attrs.index(&FullRange)), - NodeForeignItem(fi) => Some(fi.attrs.index(&FullRange)), + NodeItem(i) => Some(&i.attrs[]), + NodeForeignItem(fi) => Some(&fi.attrs[]), NodeTraitItem(ref tm) => match **tm { - 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)), + RequiredMethod(ref type_m) => Some(&type_m.attrs[]), + ProvidedMethod(ref m) => Some(&m.attrs[]), + TypeTraitItem(ref typ) => Some(&typ.attrs[]), }, NodeImplItem(ref ii) => { match **ii { - MethodImplItem(ref m) => Some(m.attrs.index(&FullRange)), - TypeImplItem(ref t) => Some(t.attrs.index(&FullRange)), + MethodImplItem(ref m) => Some(&m.attrs[]), + TypeImplItem(ref t) => Some(&t.attrs[]), } } - NodeVariant(ref v) => Some(v.node.attrs.index(&FullRange)), + NodeVariant(ref v) => Some(&v.node.attrs[]), // unit/tuple structs take the attributes straight from // the struct definition. // FIXME(eddyb) make this work again (requires access to the map). @@ -520,7 +513,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: parts.index(&(0..(parts.len() - 1))), + in_which: &parts[0..(parts.len() - 1)], idx: 0, } } @@ -597,7 +590,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { None => return false, Some((node_id, name)) => (node_id, name), }; - if part.index(&FullRange) != mod_name.as_str() { + if &part[] != mod_name.as_str() { return false; } cursor = self.map.get_parent(mod_id); @@ -635,7 +628,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.index(&FullRange) && + name.as_str() == &self.item_name[] && self.suffix_matches(parent_of_n) } } @@ -1047,7 +1040,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.index(&FullRange) } else { "" }; + let id_str = if include_id { &id_str[] } else { "" }; match map.find(id) { Some(NodeItem(item)) => { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 871f1237aee..b4e917e28cb 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -85,6 +85,13 @@ pub fn is_shift_binop(b: BinOp) -> bool { } } +pub fn is_comparison_binop(b: BinOp) -> bool { + match b { + BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true, + _ => false + } +} + /// Returns `true` if the binary operator takes its arguments by value pub fn is_by_value_binop(b: BinOp) -> bool { match b { @@ -238,11 +245,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).index(&FullRange)); + pretty.push_str(&pprust::path_to_string(&trait_ref.path)[]); } None => {} } - token::gensym_ident(pretty.index(&FullRange)) + token::gensym_ident(&pretty[]) } pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod { @@ -317,8 +324,7 @@ pub fn operator_prec(op: ast::BinOp) -> uint { BiBitAnd => 8u, BiBitXor => 7u, BiBitOr => 6u, - BiLt | BiLe | BiGe | BiGt => 4u, - BiEq | BiNe => 3u, + BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3u, BiAnd => 2u, BiOr => 1u } @@ -704,7 +710,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.index(&FullRange), b.segments.index(&FullRange))) + && (segments_name_eq(&a.segments[], &b.segments[])) } // are two arrays of segments equal when compared unhygienically? @@ -791,14 +797,14 @@ 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>>().index(&FullRange), - [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange))); + &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); assert!(!segments_name_eq( - [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .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>>().index(&FullRange))); + &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 416fc8c2278..2cea55dfc55 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -98,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.index(&FullRange)), + MetaList(_, ref l) => Some(&l[]), _ => None } } @@ -136,8 +136,8 @@ impl AttributeMethods for Attribute { let comment = self.value_str().unwrap(); let meta = mk_name_value_item_str( InternedString::new("doc"), - token::intern_and_get_ident(strip_doc_comment_decoration( - comment.get()).index(&FullRange))); + token::intern_and_get_ident(&strip_doc_comment_decoration( + comment.get())[])); if self.node.style == ast::AttrOuter { f(&mk_attr_outer(self.node.id, meta)) } else { @@ -297,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.index(&FullRange), "always") { + if contains_name(&items[], "always") { InlineAlways - } else if contains_name(items.index(&FullRange), "never") { + } else if contains_name(&items[], "never") { InlineNever } else { InlineHint @@ -403,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).index(&FullRange)); + &format!("duplicate meta item `{}`", name)[]); } } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 31fe23847d9..d1768867f0d 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -304,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.index(&(begin..)); + let slice = &self.src[begin..]; match slice.find('\n') { - Some(e) => slice.index(&(0..e)), + Some(e) => &slice[0..e], None => slice }.to_string() }) @@ -351,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.index(&(3..))) + String::from_str(&src[3..]) } else { - String::from_str(src.index(&FullRange)) + String::from_str(&src[]) }; // Append '\n' in case it's not already there. @@ -440,8 +440,7 @@ impl CodeMap { if begin.fm.start_pos != end.fm.start_pos { None } else { - Some(begin.fm.src.index(&(begin.pos.to_uint().. - end.pos.to_uint())).to_string()) + Some((&begin.fm.src[begin.pos.to_uint()..end.pos.to_uint()]).to_string()) } } @@ -590,7 +589,12 @@ impl CodeMap { Some(ref info) => { // save the parent expn_id for next loop iteration expnid = info.call_site.expn_id; - if info.callee.span.is_none() { + if info.callee.name == "format_args" { + // This is a hack because the format_args builtin calls unstable APIs. + // I spent like 6 hours trying to solve this more generally but am stupid. + is_internal = true; + false + } else if info.callee.span.is_none() { // it's a compiler built-in, we *really* don't want to mess with it // so we skip it, unless it was called by a regular macro, in which case // we will handle the caller macro next turn diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index fde2fdb3c55..7e57709f33d 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).index(&FullRange)); + self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler @@ -166,7 +166,7 @@ impl Handler { self.err_count.get()); } } - self.fatal(s.index(&FullRange)); + self.fatal(&s[]); } 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).index(&FullRange)); + self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, @@ -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.index(&(0..(msg.len()-1))))); + try!(t.write_str(&msg[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()).index(&FullRange), + &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, - format!("{}", msg).index(&FullRange), + &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); - try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).index(&FullRange), style)); + try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } @@ -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.index(&FullRange), lvl, msg, code)); + try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, lines)); } } else { - try!(print_diagnostic(dst, ss.index(&FullRange), lvl, msg, code)); + try!(print_diagnostic(dst, &ss[], 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.index(&FullRange), Help, - format!("pass `--explain {}` to see a detailed \ - explanation", code).index(&FullRange), None)); + try!(print_diagnostic(dst, &ss[], Help, + &format!("pass `--explain {}` to see a detailed \ + explanation", code)[], 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.index(&FullRange); + let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { - display_lines = display_lines.index(&(0u..MAX_LINES)); + display_lines = &display_lines[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).index(&FullRange), + &format!("{}\n", s)[], 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.index(&FullRange); + let lines = &lines.lines[]; 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.index(&FullRange), + &s[], 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.index(&FullRange), Note, - format!("in expansion of {}{}{}", pre, + try!(print_diagnostic(w, &ss[], Note, + &format!("in expansion of {}{}{}", pre, ei.callee.name, - post).index(&FullRange), None)); + post)[], None)); let ss = cm.span_to_string(ei.call_site); - try!(print_diagnostic(w, ss.index(&FullRange), Note, "expansion site", None)); + try!(print_diagnostic(w, &ss[], 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().index(&FullRange)), + None => diag.handler().bug(&msg()[]), } } diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 0f4ebd74b66..1469c50061c 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -56,9 +56,9 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, with_used_diagnostics(|diagnostics| { match diagnostics.insert(code.name, span) { Some(previous_span) => { - ecx.span_warn(span, format!( + ecx.span_warn(span, &format!( "diagnostic code {} already used", token::get_ident(code).get() - ).index(&FullRange)); + )[]); ecx.span_note(previous_span, "previous invocation"); }, None => () @@ -85,14 +85,14 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, }; with_registered_diagnostics(|diagnostics| { if diagnostics.insert(code.name, description).is_some() { - ecx.span_err(span, format!( + ecx.span_err(span, &format!( "diagnostic code {} already registered", token::get_ident(*code).get() - ).index(&FullRange)); + )[]); } }); - let sym = Ident::new(token::gensym(( + 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 04dec0e8028..fd3bac5b2fc 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -99,8 +99,8 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let output = match constraint.get().slice_shift_char() { Some(('=', _)) => None, Some(('+', operand)) => { - Some(token::intern_and_get_ident(format!( - "={}", operand).index(&FullRange))) + Some(token::intern_and_get_ident(&format!( + "={}", operand)[])) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 52e402689ba..9b9d8a9ceb3 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -341,9 +341,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { let mut syntax_expanders = SyntaxEnv::new(); syntax_expanders.insert(intern("macro_rules"), MacroRulesTT); - syntax_expanders.insert(intern("fmt"), - builtin_normal_expander( - ext::fmt::expand_syntax_ext)); syntax_expanders.insert(intern("format_args"), builtin_normal_expander( ext::format::expand_format_args)); @@ -353,9 +350,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { syntax_expanders.insert(intern("option_env"), builtin_normal_expander( ext::env::expand_option_env)); - syntax_expanders.insert(intern("bytes"), - builtin_normal_expander( - ext::bytes::expand_syntax_ext)); syntax_expanders.insert(intern("concat_idents"), builtin_normal_expander( ext::concat_idents::expand_syntax_ext)); @@ -367,8 +361,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { ext::log_syntax::expand_syntax_ext)); syntax_expanders.insert(intern("derive"), Decorator(box ext::deriving::expand_meta_derive)); - syntax_expanders.insert(intern("deriving"), - Decorator(box ext::deriving::expand_meta_deriving)); if ecfg.enable_quotes { // Quasi-quoting expanders @@ -416,9 +408,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { syntax_expanders.insert(intern("include_str"), builtin_normal_expander( ext::source_util::expand_include_str)); - syntax_expanders.insert(intern("include_bin"), - builtin_normal_expander( - ext::source_util::expand_include_bin)); syntax_expanders.insert(intern("include_bytes"), builtin_normal_expander( ext::source_util::expand_include_bytes)); @@ -539,7 +528,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.index(&FullRange))); + v.push(token::str_to_ident(&self.ecfg.crate_name[])); v.extend(self.mod_path.iter().map(|a| *a)); return v; } @@ -547,8 +536,8 @@ impl<'a> ExtCtxt<'a> { self.recursion_count += 1; 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).index(&FullRange)); + &format!("recursion limit reached while expanding the macro `{}`", + ei.callee.name)[]); } let mut call_site = ei.call_site; @@ -670,7 +659,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).index(&FullRange)); + cx.span_err(sp, &format!("{} takes no arguments", name)[]); } } @@ -683,12 +672,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).index(&FullRange)); + cx.span_err(sp, &format!("{} takes 1 argument", name)[]); 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).index(&FullRange)); + cx.span_err(sp, &format!("{} takes 1 argument", name)[]); } 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 bd4f295401c..27523ea4535 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -708,8 +708,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_fail(&self, span: Span, msg: InternedString) -> P<ast::Expr> { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, - token::intern_and_get_ident(loc.file - .name.index(&FullRange))); + token::intern_and_get_ident(&loc.file.name[])); 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/bytes.rs b/src/libsyntax/ext/bytes.rs deleted file mode 100644 index 9f225d55b44..00000000000 --- a/src/libsyntax/ext/bytes.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/* The compiler code necessary to support the bytes! extension. */ - -use ast; -use codemap::Span; -use ext::base::*; -use ext::base; -use ext::build::AstBuilder; -use std::ascii::AsciiExt; - -pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, - sp: Span, - tts: &[ast::TokenTree]) - -> Box<base::MacResult+'cx> { - cx.span_warn(sp, "`bytes!` is deprecated, use `b\"foo\"` literals instead"); - cx.parse_sess.span_diagnostic.span_help(sp, - "see http://doc.rust-lang.org/reference.html#byte-and-byte-string-literals \ - for documentation"); - cx.parse_sess.span_diagnostic.span_help(sp, - "see https://github.com/rust-lang/rust/blob/master/src/etc/2014-06-rewrite-bytes-macros.py \ - for an automated migration"); - - // Gather all argument expressions - let exprs = match get_exprs_from_tts(cx, sp, tts) { - None => return DummyResult::expr(sp), - Some(e) => e, - }; - let mut bytes = Vec::new(); - let mut err = false; - - for expr in exprs.iter() { - match expr.node { - // expression is a literal - ast::ExprLit(ref lit) => match lit.node { - // string literal, push each byte to vector expression - ast::LitStr(ref s, _) => { - for byte in s.get().bytes() { - bytes.push(cx.expr_u8(expr.span, byte)); - } - } - - // u8 literal, push to vector expression - ast::LitInt(v, ast::UnsignedIntLit(ast::TyU8)) => { - if v > 0xFF { - cx.span_err(expr.span, "too large u8 literal in bytes!"); - err = true; - } else { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } - } - - // integer literal, push to vector expression - ast::LitInt(_, ast::UnsuffixedIntLit(ast::Minus)) => { - cx.span_err(expr.span, "negative integer literal in bytes!"); - err = true; - } - ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => { - if v > 0xFF { - cx.span_err(expr.span, "too large integer literal in bytes!"); - err = true; - } else { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } - } - - // char literal, push to vector expression - ast::LitChar(v) => { - if v.is_ascii() { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } else { - cx.span_err(expr.span, "non-ascii char literal in bytes!"); - err = true; - } - } - - _ => { - cx.span_err(expr.span, "unsupported literal in bytes!"); - err = true; - } - }, - - _ => { - cx.span_err(expr.span, "non-literal in bytes!"); - err = true; - } - } - } - - // For some reason using quote_expr!() here aborts if we threw an error. - // I'm assuming that the end of the recursive parse tricks the compiler - // into thinking this is a good time to stop. But we'd rather keep going. - if err { - // Since the compiler will stop after the macro expansion phase anyway, we - // don't need type info, so we can just return a DummyResult - return DummyResult::expr(sp); - } - - let len = bytes.len(); - let e = cx.expr_vec(sp, bytes); - let ty = cx.ty(sp, ast::TyFixedLengthVec(cx.ty_ident(sp, cx.ident_of("u8")), - cx.expr_uint(sp, len))); - let item = cx.item_static(sp, cx.ident_of("BYTES"), ty, ast::MutImmutable, e); - let ret = cx.expr_ident(sp, cx.ident_of("BYTES")); - let ret = cx.expr_addr_of(sp, ret); - let e = cx.expr_block(cx.block(sp, vec![cx.stmt_item(sp, item)], - Some(ret))); - MacExpr::new(e) -} diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 1f1781dceb3..39895a3946a 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).index(&FullRange)); + accumulator.push_str(&format!("{}", i)[]); } ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => { - accumulator.push_str(format!("-{}", i).index(&FullRange)); + accumulator.push_str(&format!("-{}", i)[]); } ast::LitBool(b) => { - accumulator.push_str(format!("{}", b).index(&FullRange)); + accumulator.push_str(&format!("{}", b)[]); } 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.index(&FullRange)))) + token::intern_and_get_ident(&accumulator[]))) } diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 02f702248cb..1af3ba1d326 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.index(&FullRange)); + let res = str_to_ident(&res_str[]); let e = P(ast::Expr { id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index d9d6cebd05c..784a92b9a0e 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -79,12 +79,12 @@ fn cs_clone( }, EnumNonMatchingCollapsed (..) => { cx.span_bug(trait_span, - format!("non-matching enum variants in \ - `deriving({})`", name).index(&FullRange)) + &format!("non-matching enum variants in \ + `deriving({})`", name)[]) } StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, - format!("static method in `deriving({})`", name).index(&FullRange)) + &format!("static method in `deriving({})`", name)[]) } } @@ -100,8 +100,8 @@ fn cs_clone( Some(i) => i, None => { cx.span_bug(trait_span, - format!("unnamed field in normal struct in \ - `deriving({})`", name).index(&FullRange)) + &format!("unnamed field in normal struct in \ + `deriving({})`", name)[]) } }; 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 a9289f0175a..7c65d2b4ff4 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -197,8 +197,7 @@ fn decode_static_fields<F>(cx: &mut ExtCtxt, } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, - token::intern_and_get_ident(format!("_field{}", - i).index(&FullRange)), + token::intern_and_get_ident(&format!("_field{}", i)[]), i) }).collect(); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 7114217d51d..616390467f0 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).index(&FullRange)) + token::intern_and_get_ident(&format!("_field{}", i)[]) } }; 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 50b3559f369..47b29a4db3e 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.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) } else { method_def.expand_struct_method_body(cx, self, struct_def, type_ident, - self_args.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) }; method_def.create_method(cx, @@ -550,15 +550,15 @@ impl<'a> TraitDef<'a> { self, enum_def, type_ident, - self_args.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) } else { method_def.expand_enum_method_body(cx, self, enum_def, type_ident, self_args, - nonself_args.index(&FullRange)) + &nonself_args[]) }; method_def.create_method(cx, @@ -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).index(&FullRange)); + let ident = cx.ident_of(&format!("__arg_{}", i)[]); arg_tys.push((ident, ast_ty)); let arg_expr = cx.expr_ident(trait_.span, ident); @@ -751,8 +751,8 @@ impl<'a> MethodDef<'a> { trait_.create_struct_pattern(cx, struct_path, struct_def, - format!("__self_{}", - i).index(&FullRange), + &format!("__self_{}", + i)[], 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.index(&FullRange))) + .map(|name|cx.ident_of(&name[])) .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.index(&FullRange)); - cx.ident_of(vi_suffix.index(&FullRange)) }) + .map(|name| { let vi_suffix = format!("{}_vi", &name[]); + cx.ident_of(&vi_suffix[]) }) .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.index(&FullRange), vi_idents.index(&FullRange)); + self_arg_idents, &variants[], &vi_idents[]); // 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].index(&FullRange)); + let (p, idents) = mk_self_pat(cx, &self_arg_names[0][]); subpats.push(p); idents }; for self_arg_name in self_arg_names.tail().iter() { - let (p, idents) = mk_self_pat(cx, self_arg_name.index(&FullRange)); + let (p, idents) = mk_self_pat(cx, &self_arg_name[]); 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.index(&FullRange), nonself_args, + cx, trait_, type_ident, &self_args[], nonself_args, &substructure); cx.arm(sp, vec![single_pat], arm_expr) @@ -1059,7 +1059,7 @@ impl<'a> MethodDef<'a> { } let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, + cx, trait_, type_ident, &self_args[], 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).index(&FullRange)); + let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]); 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).index(&FullRange)); + let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]); 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.index(&FullRange)) + &field.other[]) }) } else { all_fields.iter().rev().fold(base, |old, field| { @@ -1360,12 +1360,12 @@ pub fn cs_fold<F>(use_foldl: bool, field.span, old, field.self_.clone(), - field.other.index(&FullRange)) + &field.other[]) }) } }, EnumNonMatchingCollapsed(ref all_args, _, tuple) => - enum_nonmatch_f(cx, trait_span, (all_args.index(&FullRange), tuple), + enum_nonmatch_f(cx, trait_span, (&all_args[], tuple), substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") @@ -1405,7 +1405,7 @@ pub fn cs_same_method<F>(f: F, f(cx, trait_span, called) }, EnumNonMatchingCollapsed(ref all_self_args, _, tuple) => - enum_nonmatch_f(cx, trait_span, (all_self_args.index(&FullRange), tuple), + enum_nonmatch_f(cx, trait_span, (&all_self_args[], tuple), substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 844bd80d161..db99c142443 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -30,7 +30,8 @@ pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt, let generics = LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__S", - vec!(Path::new(vec!("std", "hash", "Writer"))))), + vec!(Path::new(vec!("std", "hash", "Writer")), + Path::new(vec!("std", "hash", "Hasher"))))), }; let args = Path::new_local("__S"); let inline = cx.meta_word(span, InternedString::new("inline")); diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 43a0e0606f8..603c4478007 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -40,16 +40,6 @@ pub mod totalord; pub mod generic; -pub fn expand_meta_deriving(cx: &mut ExtCtxt, - _span: Span, - mitem: &MetaItem, - item: &Item, - push: Box<FnMut(P<Item>)>) { - cx.span_warn(mitem.span, "`deriving` is deprecated; use `derive`"); - - expand_meta_derive(cx, _span, mitem, item, push) -} - pub fn expand_meta_derive(cx: &mut ExtCtxt, _span: Span, mitem: &MetaItem, @@ -121,9 +111,9 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, ref tname => { cx.span_err(titem.span, - format!("unknown `derive` \ + &format!("unknown `derive` \ trait: `{}`", - *tname).index(&FullRange)); + *tname)[]); } }; } diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index fa9a7899a12..48034ce50ab 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -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.index(&FullRange)); + let s = token::intern_and_get_ident(&format_string[]); 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 eb3544e3c5c..9b54e259761 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.index(&FullRange)) { + let e = match os::getenv(&var[]) { 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.index(&FullRange))))) + &s[])))) } }; MacExpr::new(e) @@ -81,9 +81,9 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) }; let msg = match exprs.next() { None => { - token::intern_and_get_ident(format!("environment variable `{}` \ + token::intern_and_get_ident(&format!("environment variable `{}` \ not defined", - var).index(&FullRange)) + var)[]) } 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.index(&FullRange))) + Some(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) }; MacExpr::new(e) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 3e1bccf394a..9ef996ac317 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -286,8 +286,8 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, None => { fld.cx.span_err( pth.span, - format!("macro undefined: '{}!'", - extnamestr.get()).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr.get())[]); // 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.index(&FullRange), fm); + let marked_before = mark_tts(&tts[], 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.index(&FullRange)); + &marked_before[]); parse_thunk(expanded) }; let parsed = match opt_parsed { @@ -322,9 +322,9 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, None => { fld.cx.span_err( pth.span, - format!("non-expression macro in expression position: {}", - extnamestr.get().index(&FullRange) - ).index(&FullRange)); + &format!("non-expression macro in expression position: {}", + &extnamestr.get()[] + )[]); return None; } }; @@ -333,8 +333,8 @@ 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()).index(&FullRange)); + &format!("'{}' is not a tt-style macro", + extnamestr.get())[]); 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.index(&FullRange)); + let macro_use = contains_macro_use(fld, &new_attrs[]); let result = with_exts_frame!(fld.cx.syntax_env, macro_use, noop_fold_item(it, fld)); @@ -565,8 +565,8 @@ pub fn expand_item_mac(it: P<ast::Item>, let expanded = match fld.cx.syntax_env.find(&extname.name) { None => { fld.cx.span_err(path_span, - format!("macro undefined: '{}!'", - extnamestr).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr)[]); // let compilation continue return SmallVector::zero(); } @@ -576,10 +576,10 @@ pub fn expand_item_mac(it: P<ast::Item>, if it.ident.name != parse::token::special_idents::invalid.name { fld.cx .span_err(path_span, - format!("macro {}! expects no ident argument, \ + &format!("macro {}! expects no ident argument, \ given '{}'", extnamestr, - token::get_ident(it.ident)).index(&FullRange)); + token::get_ident(it.ident))[]); 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.index(&FullRange), fm); - expander.expand(fld.cx, it.span, marked_before.index(&FullRange)) + let marked_before = mark_tts(&tts[], fm); + expander.expand(fld.cx, it.span, &marked_before[]) } 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()).index(&FullRange)); + &format!("macro {}! expects an ident argument", + extnamestr.get())[]); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -610,14 +610,14 @@ pub fn expand_item_mac(it: P<ast::Item>, } }); // mark before expansion: - let marked_tts = mark_tts(tts.index(&FullRange), fm); + let marked_tts = mark_tts(&tts[], 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") - .index(&FullRange)); + &format!("macro_rules! expects an ident argument") + []); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -648,8 +648,8 @@ pub fn expand_item_mac(it: P<ast::Item>, } _ => { fld.cx.span_err(it.span, - format!("{}! is not legal in item position", - extnamestr.get()).index(&FullRange)); + &format!("{}! is not legal in item position", + extnamestr.get())[]); return SmallVector::zero(); } } @@ -667,8 +667,8 @@ 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()).index(&FullRange)); + &format!("non-item macro in item position: {}", + extnamestr.get())[]); return SmallVector::zero(); } }; @@ -913,8 +913,8 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { let marked_after = match fld.cx.syntax_env.find(&extname.name) { None => { fld.cx.span_err(pth.span, - format!("macro undefined: '{}!'", - extnamestr).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr)[]); // let compilation continue return DummyResult::raw_pat(span); } @@ -931,19 +931,19 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { }); let fm = fresh_mark(); - let marked_before = mark_tts(tts.index(&FullRange), fm); + let marked_before = mark_tts(&tts[], fm); let mac_span = fld.cx.original_span(); let expanded = match expander.expand(fld.cx, mac_span, - marked_before.index(&FullRange)).make_pat() { + &marked_before[]).make_pat() { Some(e) => e, None => { fld.cx.span_err( pth.span, - format!( + &format!( "non-pattern macro in pattern position: {}", extnamestr.get() - ).index(&FullRange) + )[] ); return DummyResult::raw_pat(span); } @@ -954,8 +954,8 @@ 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()).index(&FullRange)); + &format!("{}! is not legal in pattern position", + extnamestr.get())[]); return DummyResult::raw_pat(span); } } @@ -1232,7 +1232,7 @@ impl Folder for Marker { node: match node { MacInvocTT(path, tts, ctxt) => { MacInvocTT(self.fold_path(path), - self.fold_tts(tts.index(&FullRange)), + self.fold_tts(&tts[]), mtwt::apply_mark(self.mark, ctxt)) } }, @@ -1295,7 +1295,7 @@ impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> { #[cfg(test)] mod test { - use super::{pattern_bindings, expand_crate, contains_macro_use}; + use super::{pattern_bindings, expand_crate}; use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig}; use ast; use ast::{Attribute_, AttrOuter, MetaWord, Name}; @@ -1404,22 +1404,6 @@ mod test { expand_crate(&sess, test_ecfg(), vec!(), vec!(), crate_ast); } - // make a MetaWord outer attribute with the given name - fn make_dummy_attr(s: &str) -> ast::Attribute { - Spanned { - span:codemap::DUMMY_SP, - node: Attribute_ { - id: attr::mk_attr_id(), - style: AttrOuter, - value: P(Spanned { - node: MetaWord(token::intern_and_get_ident(s)), - span: codemap::DUMMY_SP, - }), - is_sugared_doc: false, - } - } - } - fn expand_crate_str(crate_str: String) -> ast::Crate { let ps = parse::new_parse_sess(); let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod(); @@ -1655,7 +1639,7 @@ mod test { let varref_idents : Vec<ast::Ident> = varref.segments.iter().map(|s| s.identifier) .collect(); - println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name); + println!("varref #{}: {:?}, resolves to {}",idx, varref_idents, varref_name); let string = token::get_ident(final_varref_ident); println!("varref's first segment's string: \"{}\"", string.get()); println!("binding #{}: {}, resolves to {}", @@ -1713,7 +1697,7 @@ foo_module!(); let string = ident.get(); "xx" == string }).collect(); - let cxbinds: &[&ast::Ident] = cxbinds.index(&FullRange); + let cxbinds: &[&ast::Ident] = &cxbinds[]; let cxbind = match cxbinds { [b] => b, _ => panic!("expected just one binding for ext_cx") diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs deleted file mode 100644 index 5352cfaf749..00000000000 --- a/src/libsyntax/ext/fmt.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Deprecated fmt! syntax extension - -use ast; -use codemap::Span; -use ext::base; -use ext::build::AstBuilder; - - -pub fn expand_syntax_ext(ecx: &mut base::ExtCtxt, - sp: Span, - _tts: &[ast::TokenTree]) - -> Box<base::MacResult+'static> { - ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead"); - ecx.parse_sess.span_diagnostic.span_note(sp, - "see http://doc.rust-lang.org/std/fmt/ \ - for documentation"); - - base::MacExpr::new(ecx.expr_uint(sp, 2)) -} diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 44a596d2657..637b6d4649d 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -112,8 +112,8 @@ 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()).index(&FullRange)); + &format!("expected ident for named argument, found `{}`", + p.this_token_to_string())[]); return None; } }; @@ -125,8 +125,8 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => {} Some(prev) => { ecx.span_err(e.span, - format!("duplicate argument named `{}`", - name).index(&FullRange)); + &format!("duplicate argument named `{}`", + name)[]); 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.index(&FullRange)); + self.ecx.span_err(self.fmtsp, &msg[]); 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.index(&FullRange)); + self.ecx.span_err(self.fmtsp, &msg[]); return; } }; @@ -277,22 +277,22 @@ impl<'a, 'b> Context<'a, 'b> { match (cur, ty) { (&Known(ref cur), &Known(ref ty)) => { self.ecx.span_err(sp, - format!("argument redeclared with type `{}` when \ + &format!("argument redeclared with type `{}` when \ it was previously `{}`", *ty, - *cur).index(&FullRange)); + *cur)[]); } (&Known(ref cur), _) => { self.ecx.span_err(sp, - format!("argument used to format with `{}` was \ + &format!("argument used to format with `{}` was \ attempted to not be used for formatting", - *cur).index(&FullRange)); + *cur)[]); } (_, &Known(ref ty)) => { self.ecx.span_err(sp, - format!("argument previously used as a format \ + &format!("argument previously used as a format \ argument attempted to be used as `{}`", - *ty).index(&FullRange)); + *ty)[]); } (_, _) => { 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.index(&FullRange)); + let s = token::intern_and_get_ident(&self.literal[]); 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).index(&FullRange)); + let name = self.ecx.ident_of(&format!("__arg{}", i)[]); 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))); @@ -525,8 +525,8 @@ impl<'a, 'b> Context<'a, 'b> { None => continue }; - let lname = self.ecx.ident_of(format!("__arg{}", - *name).index(&FullRange)); + let lname = self.ecx.ident_of(&format!("__arg{}", + *name)[]); 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,7 +606,7 @@ impl<'a, 'b> Context<'a, 'b> { -> P<ast::Expr> { let trait_ = match *ty { Known(ref tyname) => { - match tyname.index(&FullRange) { + match &tyname[] { "" => "String", "?" => "Show", "e" => "LowerExp", @@ -618,8 +618,8 @@ impl<'a, 'b> Context<'a, 'b> { "X" => "UpperHex", _ => { ecx.span_err(sp, - format!("unknown format trait `{}`", - *tyname).index(&FullRange)); + &format!("unknown format trait `{}`", + *tyname)[]); "Dummy" } } @@ -709,8 +709,8 @@ 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)).index(&FullRange)); + cx.ecx.span_err(cx.fmtsp, &format!("invalid format string: {}", + parser.errors.remove(0))[]); 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 bebd803ac4f..ae8ff118fcc 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -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 .index(&FullRange) mutable +// it's not clear to me whether it's better to use a [] 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 77aea0c370a..2dbf29c145c 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -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).index(&FullRange))).collect() + strs.iter().map(|str| str_to_ident(&(*str)[])).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.index(&FullRange)) + mk_tts(cx, &seq[]) } 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.index(&FullRange)).into_iter()); + vector.extend(mk_tts(cx, &tts[]).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 1ba91dd371c..31a1a838b13 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.index(&FullRange)); + let filename = token::intern_and_get_ident(&loc.file.name[]); 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.index(&FullRange)))) + token::intern_and_get_ident(&s[]))) } 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.index(&FullRange)))) + token::intern_and_get_ident(&string[]))) } /// 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).index(&FullRange)); + e)[]); return DummyResult::expr(sp); } Ok(bytes) => bytes, @@ -147,26 +147,20 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // Add this input file to the code map to make it available as // dependency information let filename = format!("{:?}", file.display()); - let interned = token::intern_and_get_ident(src.index(&FullRange)); + let interned = token::intern_and_get_ident(&src[]); 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()).index(&FullRange)); + &format!("{:?} wasn't a utf-8 file", + file.display())[]); return DummyResult::expr(sp); } } } -pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) - -> Box<base::MacResult+'static> { - cx.span_warn(sp, "include_bin! is deprecated; use include_bytes! instead"); - expand_include_bytes(cx, sp, tts) -} - pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") { @@ -177,7 +171,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).index(&FullRange)); + &format!("couldn't read {:?}: {}", file.display(), e)[]); 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 d33d03bbfa9..9eda4bcef99 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.index(&FullRange)) + count_names(&delim.tts[]) } &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.index(&FullRange)); + let match_idx_hi = count_names(&ms[]); let matches: Vec<_> = range(0, match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], @@ -228,8 +228,8 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) let string = token::get_ident(bind_name); p_s.span_diagnostic .span_fatal(sp, - format!("duplicated bind name: {}", - string.get()).index(&FullRange)) + &format!("duplicated bind name: {}", + string.get())[]) } } } @@ -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.index(&FullRange)) { + match parse(sess, cfg, rdr, &ms[]) { Success(m) => m, Failure(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) + sess.span_diagnostic.span_fatal(sp, &str[]) } Error(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) + sess.span_diagnostic.span_fatal(sp, &str[]) } } } @@ -447,7 +447,7 @@ pub fn parse(sess: &ParseSess, for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } - return Success(nameize(sess, ms, v.index(&FullRange))); + return Success(nameize(sess, ms, &v[])); } else if eof_eis.len() > 1u { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { @@ -532,8 +532,8 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { token::Ident(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { let token_str = pprust::token_to_string(&p.token); - p.fatal((format!("expected ident, found {}", - token_str.index(&FullRange))).index(&FullRange)) + p.fatal(&format!("expected ident, found {}", + &token_str[])[]) } }, "path" => { @@ -541,7 +541,7 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { } "meta" => token::NtMeta(p.parse_meta_item()), _ => { - p.fatal(format!("unsupported builtin nonterminal parser: {}", name).index(&FullRange)) + p.fatal(&format!("unsupported builtin nonterminal parser: {}", name)[]) } } } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 64c53e298ef..fc341e3bd85 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -52,7 +52,7 @@ impl<'a> ParserAnyMacro<'a> { following", token_str); let span = parser.span; - parser.span_err(span, msg.index(&FullRange)); + parser.span_err(span, &msg[]); } } } @@ -126,8 +126,8 @@ impl TTMacroExpander for MacroRulesMacroExpander { self.name, self.imported_from, arg, - self.lhses.index(&FullRange), - self.rhses.index(&FullRange)) + &self.lhses[], + &self.rhses[]) } } @@ -154,7 +154,7 @@ 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.index(&FullRange), + TtDelimited(_, ref delim) => &delim.tts[], _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating @@ -195,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.index(&FullRange)) + Error(sp, ref msg) => cx.span_fatal(sp, &msg[]) } } _ => cx.bug("non-matcher found in parsed lhses") } } - cx.span_fatal(best_fail_spot, best_fail_msg.index(&FullRange)); + cx.span_fatal(best_fail_spot, &best_fail_msg[]); } // Note that macro-by-example's input is also matched against a token tree: diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index bc07c7f6cae..94b8356130a 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -255,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.index(&FullRange)); + r.sp_diag.span_fatal(sp.clone(), &msg[]); } LisConstraint(len, _) => { if len == 0 { @@ -308,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)).index(&FullRange)); + &format!("variable '{:?}' is still repeating at this depth", + token::get_ident(ident))[]); } } } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index f10113254de..2cfcd38d48f 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -70,6 +70,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("associated_types", Accepted), ("visible_private_types", Active), ("slicing_syntax", Active), + ("box_syntax", Active), ("if_let", Accepted), ("while_let", Accepted), @@ -150,9 +151,9 @@ impl<'a> Context<'a> { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if !self.has_feature(feature) { self.span_handler.span_err(span, explain); - self.span_handler.span_help(span, format!("add #![feature({})] to the \ + self.span_handler.span_help(span, &format!("add #![feature({})] to the \ crate attributes to enable", - feature).index(&FullRange)); + feature)[]); } } @@ -243,7 +244,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } match i.node { ast::ItemForeignMod(ref foreign_module) => { - if attr::contains_name(i.attrs.index(&FullRange), "link_args") { + if attr::contains_name(&i.attrs[], "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ @@ -257,14 +258,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } ast::ItemFn(..) => { - if attr::contains_name(i.attrs.index(&FullRange), "plugin_registrar") { + if attr::contains_name(&i.attrs[], "plugin_registrar") { self.gate_feature("plugin_registrar", i.span, "compiler plugins are experimental and possibly buggy"); } } ast::ItemStruct(..) => { - if attr::contains_name(i.attrs.index(&FullRange), "simd") { + if attr::contains_name(&i.attrs[], "simd") { self.gate_feature("simd", i.span, "SIMD types are experimental and possibly buggy"); } @@ -290,7 +291,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { removed in the future"); } - if attr::contains_name(i.attrs.index(&FullRange), + if attr::contains_name(&i.attrs[], "old_orphan_check") { self.gate_feature( "old_orphan_check", @@ -298,7 +299,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { "the new orphan check rules will eventually be strictly enforced"); } - if attr::contains_name(i.attrs.index(&FullRange), + if attr::contains_name(&i.attrs[], "old_impl_check") { self.gate_feature("old_impl_check", i.span, @@ -313,7 +314,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { - if attr::contains_name(i.attrs.index(&FullRange), "linkage") { + if attr::contains_name(&i.attrs[], "linkage") { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") @@ -338,10 +339,11 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { fn visit_expr(&mut self, e: &ast::Expr) { match e.node { - ast::ExprRange(..) => { - self.gate_feature("slicing_syntax", + ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => { + self.gate_feature("box_syntax", e.span, - "range syntax is experimental"); + "box expression syntax is experimental in alpha release; \ + you can call `Box::new` instead."); } _ => {} } @@ -365,6 +367,11 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { but at the end of a slice (e.g. \ `[0, ..xs, 0]` are experimental") } + ast::PatBox(..) => { + self.gate_feature("box_syntax", + pattern.span, + "box pattern syntax is experimental in alpha release"); + } _ => {} } visit::walk_pat(self, pattern) diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 9e14f9dd1ea..1efd6a87f86 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -16,6 +16,7 @@ #![crate_name = "syntax"] #![experimental] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -24,6 +25,7 @@ #![allow(unknown_features)] #![feature(slicing_syntax)] +#![feature(box_syntax)] #![feature(quote, unsafe_destructor)] extern crate arena; @@ -81,7 +83,6 @@ pub mod ext { pub mod asm; pub mod base; pub mod build; - pub mod bytes; pub mod cfg; pub mod cfg_attr; pub mod concat; @@ -89,7 +90,6 @@ pub mod ext { pub mod deriving; pub mod env; pub mod expand; - pub mod fmt; pub mod format; pub mod log_syntax; pub mod mtwt; diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 4aad7f911db..54ec9c7b146 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -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).index(&FullRange)); + self.fatal(&format!("expected `#`, found `{}`", token_str)[]); } }; diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index e7fc5aac9c7..16ade904be8 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.index(&(i..j)).iter().map(|x| (*x).clone()).collect(); + return lines[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.index(&((i + 1)..line.len())).to_string() + (&line[(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.index(&(prefix.len()..)).to_string(); + return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { - let lines = comment.index(&(3u..(comment.len() - 2u))) + let lines = comment[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.index(&FullRange)) { + if is_doc_comment(&line[]) { 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.index(&FullRange), col) { + let s1 = match all_whitespace(&s[], col) { Some(col) => { if col < len { - s.index(&(col..len)).to_string() + (&s[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.index(&FullRange)) { + if is_block_doc_comment(&curr_line[]) { return } assert!(!curr_line.contains_char('\n')); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 153b18b8760..4cdafb36eec 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -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.index(&FullRange)); + self.fatal_span_(from_pos, to_pos, &m[]); } /// 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.index(&FullRange)); + self.err_span_(from_pos, to_pos, &m[]); } /// 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.index(&(from..to))); - self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); + m.push_str(&self.filemap.src[from..to]); + self.fatal_span_(from_pos, to_pos, &m[]); } /// Advance peek_tok and peek_span to refer to the next token, and @@ -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.index(&(j..i))); } + if j < i { buf.push_str(&s[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.index(&(j..))); } + if j < s.len() { buf.push_str(&s[j..]); } buf } } @@ -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.index(&FullRange))) + token::DocComment(token::intern(&string[])) } else { token::Comment }; @@ -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).index(&FullRange)) + str_to_ident(&format!("'{}", lifetime_name)[]) }); // Conjure up a "keyword checking ident" to make sure that diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index d26b3af67bd..c42a6beea2d 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -253,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).index(&FullRange)); + e)[]); unreachable!() } }; - match str::from_utf8(bytes.index(&FullRange)).ok() { + match str::from_utf8(&bytes[]).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()).index(&FullRange)) + err(&format!("{:?} is not UTF-8 encoded", path.display())[]) } } unreachable!() @@ -399,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.index(&FullRange); + let msg2 = &msg[]; fn esc(len: uint, lit: &str) -> Option<(char, int)> { - num::from_str_radix(lit.index(&(2..len)), 16) + num::from_str_radix(&lit[2..len], 16) .and_then(char::from_u32) .map(|x| (x, len as int)) } @@ -410,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.index(&(3..idx)); + let subslice = &lit[3..idx]; num::from_str_radix(subslice, 16) .and_then(char::from_u32) .map(|x| (x, subslice.chars().count() as int + 4)) @@ -472,7 +472,7 @@ pub fn str_lit(lit: &str) -> String { eat(&mut chars); } else { // otherwise, a normal escape - let (c, n) = char_lit(lit.index(&(i..))); + let (c, n) = char_lit(&lit[i..]); for _ in range(0, n - 1) { // we don't need to move past the first \ chars.next(); } @@ -535,7 +535,7 @@ 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.index(&(1..)).chars().all(|c| '0' <= c && c <= '9') + s[1..].chars().all(|c| '0' <= c && c <= '9') } fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, @@ -548,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.index(&(1..)))); + valid widths are 32 and 64", &suf[1..])); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for float literal, \ valid suffixes are `f32` and `f64`", suf)); @@ -584,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.index(&(2..4)), 16) { + match ::std::num::from_str_radix::<u64>(&lit[2..4], 16) { Some(c) => if c > 0xFF { panic!(err(2)) @@ -634,7 +634,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { } _ => { // otherwise, a normal escape - let (c, n) = byte_lit(lit.index(&(i..))); + let (c, n) = byte_lit(&lit[i..]); // we don't need to move past the first \ for _ in range(0, n - 1) { chars.next(); @@ -663,7 +663,7 @@ 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.index(&FullRange); + let mut s = &s2[]; debug!("integer_lit: {}, {:?}", s, suffix); @@ -696,7 +696,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } if base != 10 { - s = s.index(&(2..)); + s = &s[2..]; } if let Some(suf) = suffix { @@ -720,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.index(&(1..)))); + &suf[1..])); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for numeric literal", suf)); } @@ -818,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.index(&FullRange); + let tts: &[ast::TokenTree] = &tts[]; match tts { [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)), ast::TtToken(_, token::Not), @@ -826,19 +826,19 @@ mod test { ast::TtDelimited(_, ref macro_delimed)] if name_macro_rules.as_str() == "macro_rules" && name_zip.as_str() == "zip" => { - match macro_delimed.tts.index(&FullRange) { + match ¯o_delimed.tts[] { [ast::TtDelimited(_, ref first_delimed), ast::TtToken(_, token::FatArrow), ast::TtDelimited(_, ref second_delimed)] if macro_delimed.delim == token::Paren => { - match first_delimed.tts.index(&FullRange) { + match &first_delimed.tts[] { [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), } - match second_delimed.tts.index(&FullRange) { + match &second_delimed.tts[] { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if second_delimed.delim == token::Paren @@ -1116,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.index(&FullRange), use_s); + assert_eq!(&vitem_s[], use_s); let use_s = "use foo::bar as baz;"; let vitem = string_to_view_item(use_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), use_s); + assert_eq!(&vitem_s[], use_s); } #[test] fn parse_extern_crate() { let ex_s = "extern crate foo;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), ex_s); + assert_eq!(&vitem_s[], ex_s); let ex_s = "extern crate \"foo\" as bar;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), ex_s); + assert_eq!(&vitem_s[], ex_s); } fn get_spans_of_pat_idents(src: &str) -> Vec<Span> { @@ -1212,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.index(&FullRange), b); + assert_eq!(&docs[], 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 23728c74ae8..e9e207e7dbc 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).index(&FullRange)); + &format!("obsolete syntax: {}", kind_str)[]); if !self.obsolete_set.contains(&kind) { self.sess .span_diagnostic .handler() - .note(format!("{}", desc).index(&FullRange)); + .note(&format!("{}", desc)[]); self.obsolete_set.insert(kind); } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 9c16dbb2c5c..531e611594a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -16,7 +16,7 @@ use ast::{AssociatedType, BareFnTy}; use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; use ast::{ProvidedMethod, Public, Unsafety}; use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue}; -use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block}; +use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block}; use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause}; use ast::{Crate, CrateConfig, Decl, DeclItem}; use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf}; @@ -388,13 +388,13 @@ impl<'a> Parser<'a> { pub fn unexpected_last(&mut self, t: &token::Token) -> ! { let token_str = Parser::token_to_string(t); let last_span = self.last_span; - self.span_fatal(last_span, format!("unexpected token: `{}`", - token_str).index(&FullRange)); + self.span_fatal(last_span, &format!("unexpected token: `{}`", + token_str)[]); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_string(); - self.fatal(format!("unexpected token: `{}`", this_token).index(&FullRange)); + self.fatal(&format!("unexpected token: `{}`", this_token)[]); } /// Expect and consume the token t. Signal an error if @@ -406,9 +406,9 @@ impl<'a> Parser<'a> { } else { let token_str = Parser::token_to_string(t); let this_token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - this_token_str).index(&FullRange)) + this_token_str)[]) } } else { self.expect_one_of(slice::ref_slice(t), &[]); @@ -449,10 +449,10 @@ 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.index(&FullRange)); + let expect = tokens_to_string(&expected[]); let actual = self.this_token_to_string(); self.fatal( - (if expected.len() != 1 { + &(if expected.len() != 1 { (format!("expected one of {}, found `{}`", expect, actual)) @@ -460,7 +460,7 @@ impl<'a> Parser<'a> { (format!("expected {}, found `{}`", expect, actual)) - }).index(&FullRange) + }[]) ) } } @@ -493,7 +493,7 @@ impl<'a> Parser<'a> { // 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.index(&FullRange)); + self.check_for_erroneous_unit_struct_expecting(&expected[]); } 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.index(&FullRange)); + expected.push_all(&inedible[]); self.check_for_erroneous_unit_struct_expecting( - expected.index(&FullRange)); + &expected[]); } self.expect_one_of(edible, inedible) } @@ -534,8 +534,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal((format!("expected ident, found `{}`", - token_str)).index(&FullRange)) + self.fatal(&format!("expected ident, found `{}`", + token_str)[]) } } } @@ -592,8 +592,8 @@ impl<'a> Parser<'a> { if !self.eat_keyword(kw) { 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).index(&FullRange)) + self.fatal(&format!("expected `{}`, found `{}`", + id_interned_str, token_str)[]) } } @@ -603,8 +603,8 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); let span = self.span; self.span_err(span, - format!("expected identifier, found keyword `{}`", - token_str).index(&FullRange)); + &format!("expected identifier, found keyword `{}`", + token_str)[]); } } @@ -612,8 +612,8 @@ impl<'a> Parser<'a> { pub fn check_reserved_keywords(&mut self) { if self.token.is_reserved_keyword() { let token_str = self.this_token_to_string(); - self.fatal(format!("`{}` is a reserved keyword", - token_str).index(&FullRange)) + self.fatal(&format!("`{}` is a reserved keyword", + token_str)[]) } } @@ -631,9 +631,9 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); let found_token = Parser::token_to_string(&token::BinOp(token::And)); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", found_token, - token_str).index(&FullRange)) + token_str)[]) } } } @@ -652,9 +652,9 @@ impl<'a> Parser<'a> { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::BinOp(token::Or)); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - found_token).index(&FullRange)) + found_token)[]) } } } @@ -695,9 +695,9 @@ impl<'a> Parser<'a> { if !self.eat_lt() { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::Lt); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - found_token).index(&FullRange)) + found_token)[]) } } @@ -747,9 +747,9 @@ impl<'a> Parser<'a> { _ => { let gt_str = Parser::token_to_string(&token::Gt); let this_token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", gt_str, - this_token_str).index(&FullRange)) + this_token_str)[]) } } } @@ -1371,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.index(&FullRange)); + attrs.push_all(&inner_attrs[]); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, @@ -1389,8 +1389,8 @@ impl<'a> Parser<'a> { _ => { let token_str = p.this_token_to_string(); - p.fatal((format!("expected `;` or `{{`, found `{}`", - token_str)).index(&FullRange)) + p.fatal(&format!("expected `;` or `{{`, found `{}`", + token_str)[]) } } } @@ -1586,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.index(&FullRange)); + self.fatal(&msg[]); }; let sp = mk_sp(lo, self.last_span.hi); @@ -1734,8 +1734,7 @@ impl<'a> Parser<'a> { token::StrRaw(s, n) => { (true, LitStr( - token::intern_and_get_ident( - parse::raw_str_lit(s.as_str()).index(&FullRange)), + token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]), ast::RawStr(n))) } token::Binary(i) => @@ -1979,7 +1978,7 @@ impl<'a> Parser<'a> { }; } _ => { - self.fatal(format!("expected a lifetime name").index(&FullRange)); + self.fatal(&format!("expected a lifetime name")[]); } } } @@ -2017,7 +2016,7 @@ impl<'a> Parser<'a> { let msg = format!("expected `,` or `>` after lifetime \ name, found `{}`", this_token_str); - self.fatal(msg.index(&FullRange)); + self.fatal(&msg[]); } } } @@ -2501,16 +2500,16 @@ 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()).index(&FullRange)); + &format!("unexpected token: `{}`", n.as_str())[]); if fstr.chars().all(|x| "0123456789.".contains_char(x)) { let float = match fstr.parse::<f64>() { Some(f) => f, None => continue, }; self.span_help(last_span, - format!("try parenthesizing the first index; e.g., `(foo.{}){}`", + &format!("try parenthesizing the first index; e.g., `(foo.{}){}`", float.trunc() as uint, - float.fract().to_string().index(&(1..))).index(&FullRange)); + &float.fract().to_string()[1..])[]); } self.abort_if_errors(); @@ -2536,7 +2535,7 @@ impl<'a> Parser<'a> { } // expr[...] - // An index expression. + // Could be either an index expression or a slicing expression. token::OpenDelim(token::Bracket) => { let bracket_pos = self.span.lo; self.bump(); @@ -2576,22 +2575,6 @@ impl<'a> Parser<'a> { "use `&expr[]` to construct a slice of the whole of expr"); } } - - // A range expression, either `expr..expr` or `expr..`. - token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { - self.bump(); - - let opt_end = if self.token.can_begin_expr() { - let end = self.parse_expr_res(RESTRICTION_NO_DOTS); - Some(end) - } else { - None - }; - - let hi = self.span.hi; - let range = self.mk_range(Some(e), opt_end); - return self.mk_expr(lo, hi, range); - } _ => return e } } @@ -2655,8 +2638,8 @@ impl<'a> Parser<'a> { if self.quote_depth == 0u { match self.token { token::SubstNt(name, _) => - self.fatal(format!("unknown macro variable `{}`", - token::get_ident(name)).index(&FullRange)), + self.fatal(&format!("unknown macro variable `{}`", + token::get_ident(name))[]), _ => {} } } @@ -2717,8 +2700,8 @@ impl<'a> Parser<'a> { Some(&sp) => p.span_note(sp, "unclosed delimiter"), }; let token_str = p.this_token_to_string(); - p.fatal(format!("incorrect close delimiter: `{}`", - token_str).index(&FullRange)) + p.fatal(&format!("incorrect close delimiter: `{}`", + token_str)[]) }, /* we ought to allow different depths of unquotation */ token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => { @@ -2834,7 +2817,7 @@ impl<'a> Parser<'a> { token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { // A range, closed above: `..expr`. self.bump(); - let e = self.parse_prefix_expr(); + let e = self.parse_expr(); hi = e.span.hi; ex = self.mk_range(None, Some(e)); } @@ -2858,8 +2841,8 @@ impl<'a> Parser<'a> { let span = self.span; let this_token_to_string = self.this_token_to_string(); self.span_err(span, - format!("expected expression, found `{}`", - this_token_to_string).index(&FullRange)); + &format!("expected expression, found `{}`", + this_token_to_string)[]); let box_span = mk_sp(lo, self.last_span.hi); self.span_help(box_span, "perhaps you meant `box() (foo)` instead?"); @@ -2901,11 +2884,15 @@ impl<'a> Parser<'a> { self.restrictions.contains(RESTRICTION_NO_BAR_OP) { return lhs; } + self.expected_tokens.push(TokenType::Operator); let cur_opt = self.token.to_binop(); match cur_opt { Some(cur_op) => { + if ast_util::is_comparison_binop(cur_op) { + self.check_no_chained_comparison(&*lhs, cur_op) + } let cur_prec = operator_prec(cur_op); if cur_prec > min_prec { self.bump(); @@ -2934,6 +2921,25 @@ impl<'a> Parser<'a> { } } + /// Produce an error if comparison operators are chained (RFC #558). + /// We only need to check lhs, not rhs, because all comparison ops + /// have same precedence and are left-associative + fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) { + debug_assert!(ast_util::is_comparison_binop(outer_op)); + match lhs.node { + ExprBinary(op, _, _) if ast_util::is_comparison_binop(op) => { + let op_span = self.span; + self.span_err(op_span, + "Chained comparison operators require parentheses"); + if op == BiLt && outer_op == BiGt { + self.span_help(op_span, + "Use ::< instead of < if you meant to specify type arguments."); + } + } + _ => {} + } + } + /// Parse an assignment expression.... /// actually, this seems to be the main entry point for /// parsing an arbitrary expression. @@ -2970,6 +2976,23 @@ impl<'a> Parser<'a> { let assign_op = self.mk_assign_op(aop, lhs, rhs); self.mk_expr(span.lo, rhs_span.hi, assign_op) } + // A range expression, either `expr..expr` or `expr..`. + token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { + self.bump(); + + let opt_end = if self.token.can_begin_expr() { + let end = self.parse_expr_res(RESTRICTION_NO_DOTS); + Some(end) + } else { + None + }; + + let lo = lhs.span.lo; + let hi = self.span.hi; + let range = self.mk_range(Some(lhs), opt_end); + return self.mk_expr(lo, hi, range); + } + _ => { lhs } @@ -3241,8 +3264,8 @@ impl<'a> Parser<'a> { self.bump(); if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", "}", - token_str).index(&FullRange)) + self.fatal(&format!("expected `{}`, found `{}`", "}", + token_str)[]) } etc = true; break; @@ -3262,8 +3285,8 @@ impl<'a> Parser<'a> { match bind_type { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_string(); - self.fatal(format!("unexpected `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("unexpected `{}`", + token_str)[]) } _ => {} } @@ -3546,7 +3569,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).index(&FullRange)); + &format!("expected identifier, found `{}`", tok_str)[]); } let ident = self.parse_ident(); let last_span = self.last_span; @@ -3643,7 +3666,7 @@ impl<'a> Parser<'a> { let lo = self.span.lo; if self.token.is_keyword(keywords::Let) { - check_expected_item(self, item_attrs.index(&FullRange)); + check_expected_item(self, &item_attrs[]); self.expect_keyword(keywords::Let); let decl = self.parse_let(); P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) @@ -3652,7 +3675,7 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| *t == token::Not) { // it's a macro invocation: - check_expected_item(self, item_attrs.index(&FullRange)); + check_expected_item(self, &item_attrs[]); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... @@ -3678,9 +3701,9 @@ impl<'a> Parser<'a> { "" }; let tok_str = self.this_token_to_string(); - self.fatal(format!("expected {}`(` or `{{`, found `{}`", + self.fatal(&format!("expected {}`(` or `{{`, found `{}`", ident_str, - tok_str).index(&FullRange)) + tok_str)[]) }, }; @@ -3728,7 +3751,7 @@ impl<'a> Parser<'a> { } } else { let found_attrs = !item_attrs.is_empty(); - let item_err = Parser::expected_item_err(item_attrs.index(&FullRange)); + let item_err = Parser::expected_item_err(&item_attrs[]); match self.parse_item_or_view_item(item_attrs, false) { IoviItem(i) => { let hi = i.span.hi; @@ -3772,7 +3795,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).index(&FullRange), + &format!("expected `{{`, found `{}`", tok)[], "place this code inside a block"); } @@ -3826,13 +3849,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().index(&FullRange)); + attributes_box.push_all(&self.parse_outer_attributes()[]); 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.index(&FullRange))); + Parser::expected_item_err(&attributes_box[])); attributes_box = Vec::new(); } self.bump(); // empty @@ -3924,7 +3947,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.index(&FullRange))); + Parser::expected_item_err(&attributes_box[])); } let hi = self.span.hi; @@ -4367,8 +4390,8 @@ impl<'a> Parser<'a> { }, _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `self`, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected `self`, found `{}`", + token_str)[]) } } } @@ -4521,8 +4544,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `,` or `)`, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected `,` or `)`, found `{}`", + token_str)[]) } } } @@ -4698,7 +4721,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.index(&FullRange)); + new_attrs.push_all(&inner_attrs[]); (ast::MethDecl(ident, generics, abi, @@ -4915,17 +4938,17 @@ impl<'a> Parser<'a> { } if fields.len() == 0 { - self.fatal(format!("unit-like struct definition should be \ + self.fatal(&format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone())).index(&FullRange)); + token::get_ident(class_name.clone()))[]); } self.bump(); } else { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `where`, or `{}` after struct \ + self.fatal(&format!("expected `where`, or `{}` after struct \ name, found `{}`", "{", - token_str).index(&FullRange)); + token_str)[]); } fields @@ -4954,9 +4977,9 @@ impl<'a> Parser<'a> { }); if fields.len() == 0 { - self.fatal(format!("unit-like struct definition should be \ + self.fatal(&format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone())).index(&FullRange)); + token::get_ident(class_name.clone()))[]); } self.parse_where_clause(generics); @@ -4970,8 +4993,8 @@ impl<'a> Parser<'a> { // This case is where we see: `struct Foo<T>;` } else { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `where`, `{}`, `(`, or `;` after struct \ - name, found `{}`", "{", token_str).index(&FullRange)); + self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \ + name, found `{}`", "{", token_str)[]); } } @@ -4990,8 +5013,8 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal_help(span, - format!("expected `,`, or `}}`, found `{}`", - token_str).index(&FullRange), + &format!("expected `,`, or `}}`, found `{}`", + token_str)[], "struct fields should be separated by commas") } } @@ -5078,7 +5101,7 @@ impl<'a> Parser<'a> { let mut attrs = self.parse_outer_attributes(); if first { let mut tmp = attrs_remaining.clone(); - tmp.push_all(attrs.index(&FullRange)); + tmp.push_all(&attrs[]); attrs = tmp; first = false; } @@ -5094,8 +5117,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected item, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected item, found `{}`", + token_str)[]) } } } @@ -5104,7 +5127,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.index(&FullRange))); + Parser::expected_item_err(&attrs_remaining[])); } ast::Mod { @@ -5174,7 +5197,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.index(&FullRange)); + let mod_path = Path::new(".").join_many(&self.mod_path_stack[]); 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( @@ -5184,8 +5207,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.index(&FullRange)); - let secondary_path = dir_path.join(secondary_path_str.index(&FullRange)); + let default_path = dir_path.join(&default_path_str[]); + let secondary_path = dir_path.join(&secondary_path_str[]); let default_exists = default_path.exists(); let secondary_exists = secondary_path.exists(); @@ -5197,16 +5220,16 @@ impl<'a> Parser<'a> { None => self.root_module_name.as_ref().unwrap().clone(), }; self.span_note(id_sp, - format!("maybe move this module `{0}` \ + &format!("maybe move this module `{0}` \ to its own directory via \ `{0}/mod.rs`", - this_module).index(&FullRange)); + this_module)[]); if default_exists || secondary_exists { self.span_note(id_sp, - format!("... or maybe `use` the module \ + &format!("... or maybe `use` the module \ `{}` instead of possibly \ redeclaring it", - mod_name).index(&FullRange)); + mod_name)[]); } self.abort_if_errors(); } @@ -5216,22 +5239,22 @@ impl<'a> Parser<'a> { (false, true) => (secondary_path, true), (false, false) => { self.span_fatal_help(id_sp, - format!("file not found for module `{}`", - mod_name).index(&FullRange), - format!("name the file either {} or {} inside \ + &format!("file not found for module `{}`", + mod_name)[], + &format!("name the file either {} or {} inside \ the directory {:?}", default_path_str, secondary_path_str, - dir_path.display()).index(&FullRange)); + dir_path.display())[]); } (true, true) => { self.span_fatal_help( id_sp, - format!("file for module `{}` found at both {} \ + &format!("file for module `{}` found at both {} \ and {}", mod_name, default_path_str, - secondary_path_str).index(&FullRange), + secondary_path_str)[], "delete or rename one of them to remove the ambiguity"); } } @@ -5253,11 +5276,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().index(&FullRange)); + err.push_str(&p.display().as_cow()[]); err.push_str(" -> "); } - err.push_str(path.display().as_cow().index(&FullRange)); - self.span_fatal(id_sp, err.index(&FullRange)); + err.push_str(&path.display().as_cow()[]); + self.span_fatal(id_sp, &err[]); } None => () } @@ -5338,7 +5361,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.index(&FullRange))); + Parser::expected_item_err(&attrs_remaining[])); } assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { @@ -5377,9 +5400,9 @@ impl<'a> Parser<'a> { self.span_err(span, "expected `;`, found `as`"); self.span_help(span, - format!("perhaps you meant to enclose the crate name `{}` in \ + &format!("perhaps you meant to enclose the crate name `{}` in \ a string?", - the_ident.as_str()).index(&FullRange)); + the_ident.as_str())[]); None } else { None @@ -5403,9 +5426,9 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected extern crate name but \ + &format!("expected extern crate name but \ found `{}`", - token_str).index(&FullRange)); + token_str)[]); } }; @@ -5501,9 +5524,9 @@ impl<'a> Parser<'a> { let struct_def = self.parse_struct_def(); if struct_def.fields.len() == 0 { self.span_err(start_span, - format!("unit-like struct variant should be written \ + &format!("unit-like struct variant should be written \ without braces, as `{},`", - token::get_ident(ident)).index(&FullRange)); + token::get_ident(ident))[]); } kind = StructVariantKind(struct_def); } else if self.check(&token::OpenDelim(token::Paren)) { @@ -5585,10 +5608,10 @@ impl<'a> Parser<'a> { let last_span = self.last_span; self.span_err( last_span, - format!("illegal ABI: expected one of [{}], \ + &format!("illegal ABI: expected one of [{}], \ found `{}`", abi::all_names().connect(", "), - the_string).index(&FullRange)); + the_string)[]); None } } @@ -5647,10 +5670,10 @@ impl<'a> Parser<'a> { if next_is_mod { let last_span = self.last_span; self.span_err(mk_sp(lo, last_span.hi), - format!("`extern mod` is obsolete, use \ + &format!("`extern mod` is obsolete, use \ `extern crate` instead \ to refer to external \ - crates.").index(&FullRange)) + crates.")[]) } return self.parse_item_extern_crate(lo, visibility, attrs); } @@ -5677,8 +5700,8 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected `{}` or `fn`, found `{}`", "{", - token_str).index(&FullRange)); + &format!("expected `{}` or `fn`, found `{}`", "{", + token_str)[]); } if self.eat_keyword(keywords::Virtual) { @@ -5791,7 +5814,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = - self.parse_item_mod(attrs.index(&FullRange)); + self.parse_item_mod(&attrs[]); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, @@ -6131,7 +6154,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes().index(&FullRange)); + attrs.push_all(&self.parse_outer_attributes()[]); // First, parse view items. let mut view_items : Vec<ast::ViewItem> = Vec::new(); let mut items = Vec::new(); @@ -6213,7 +6236,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes().index(&FullRange)); + attrs.push_all(&self.parse_outer_attributes()[]); 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 43786738910..4b3573f84c5 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -480,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.index(&FullRange)) + interner::StrInterner::prefill(&init_vec[]) } }} @@ -629,7 +629,7 @@ impl InternedString { #[inline] pub fn get<'a>(&'a self) -> &'a str { - self.string.index(&FullRange) + &self.string[] } } @@ -659,41 +659,41 @@ impl fmt::Show for InternedString { impl fmt::String for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.string.index(&FullRange)) + write!(f, "{}", &self.string[]) } } impl<'a> PartialEq<&'a str> for InternedString { #[inline(always)] fn eq(&self, other: & &'a str) -> bool { - PartialEq::eq(self.string.index(&FullRange), *other) + PartialEq::eq(&self.string[], *other) } #[inline(always)] fn ne(&self, other: & &'a str) -> bool { - PartialEq::ne(self.string.index(&FullRange), *other) + PartialEq::ne(&self.string[], *other) } } impl<'a> PartialEq<InternedString > for &'a str { #[inline(always)] fn eq(&self, other: &InternedString) -> bool { - PartialEq::eq(*self, other.string.index(&FullRange)) + PartialEq::eq(*self, &other.string[]) } #[inline(always)] fn ne(&self, other: &InternedString) -> bool { - PartialEq::ne(*self, other.string.index(&FullRange)) + PartialEq::ne(*self, &other.string[]) } } 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()).index(&FullRange)))) + Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[]))) } } impl Encodable for InternedString { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.string.index(&FullRange)) + s.emit_str(&self.string[]) } } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 52306075c21..b69b812c958 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -138,9 +138,9 @@ pub fn buf_str(toks: Vec<Token>, if i != left { s.push_str(", "); } - s.push_str(format!("{}={}", + s.push_str(&format!("{}={}", szs[i], - tok_str(toks[i].clone())).index(&FullRange)); + tok_str(toks[i].clone()))[]); i += 1u; i %= n; } @@ -602,7 +602,7 @@ impl Printer { assert_eq!(l, len); // assert!(l <= space); self.space -= len; - self.print_str(s.index(&FullRange)) + self.print_str(&s[]) } Eof => { // Eof should never get here. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 87dcc9e70f4..9b6f8e6002d 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.index(&FullRange))); + try!(s.print_mod(&krate.module, &krate.attrs[])); 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.index(&FullRange))); + try!(word(&mut self.s, &text[])); 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.index(&FullRange), + try!(self.commasep(Inconsistent, &elts[], |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.index(&FullRange))); + try!(self.print_bounds("+", &bounds[])); } ast::TyPolyTraitRef(ref bounds) => { - try!(self.print_bounds("", bounds.index(&FullRange))); + try!(self.print_bounds("", &bounds[])); } 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.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); match item.node { ast::ForeignItemFn(ref decl, ref generics) => { try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics, @@ -769,8 +769,8 @@ impl<'a> State<'a> { self.end() // end the outer fn box } ast::ForeignItemStatic(ref t, m) => { - try!(self.head(visibility_qualified(item.vis, - "static").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "static")[])); 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.index(&FullRange))); + try!(self.print_outer_attributes(&typedef.attrs[])); 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.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); 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").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "static")[])); if m == ast::MutMutable { try!(self.word_space("mut")); } @@ -827,8 +827,8 @@ impl<'a> State<'a> { try!(self.end()); // end the outer cbox } ast::ItemConst(ref ty, ref expr) => { - try!(self.head(visibility_qualified(item.vis, - "const").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "const")[])); try!(self.print_ident(item.ident)); try!(self.word_space(":")); try!(self.print_type(&**ty)); @@ -851,29 +851,28 @@ impl<'a> State<'a> { item.vis )); try!(word(&mut self.s, " ")); - try!(self.print_block_with_attrs(&**body, item.attrs.index(&FullRange))); + try!(self.print_block_with_attrs(&**body, &item.attrs[])); } ast::ItemMod(ref _mod) => { - try!(self.head(visibility_qualified(item.vis, - "mod").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "mod")[])); try!(self.print_ident(item.ident)); try!(self.nbsp()); try!(self.bopen()); - try!(self.print_mod(_mod, item.attrs.index(&FullRange))); + try!(self.print_mod(_mod, &item.attrs[])); try!(self.bclose(item.span)); } ast::ItemForeignMod(ref nmod) => { try!(self.head("extern")); - try!(self.word_nbsp(nmod.abi.to_string().index(&FullRange))); + try!(self.word_nbsp(&nmod.abi.to_string()[])); try!(self.bopen()); - try!(self.print_foreign_mod(nmod, item.attrs.index(&FullRange))); + try!(self.print_foreign_mod(nmod, &item.attrs[])); 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").index(&FullRange))); + try!(self.word_nbsp(&visibility_qualified(item.vis, "type")[])); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); try!(self.end()); // end the inner ibox @@ -895,7 +894,7 @@ impl<'a> State<'a> { )); } ast::ItemStruct(ref struct_def, ref generics) => { - try!(self.head(visibility_qualified(item.vis,"struct").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis,"struct")[])); try!(self.print_struct(&**struct_def, generics, item.ident, item.span)); } @@ -936,7 +935,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.bopen()); - try!(self.print_inner_attributes(item.attrs.index(&FullRange))); + try!(self.print_inner_attributes(&item.attrs[])); for impl_item in impl_items.iter() { match *impl_item { ast::MethodImplItem(ref meth) => { @@ -967,7 +966,7 @@ impl<'a> State<'a> { real_bounds.push(b); } } - try!(self.print_bounds(":", real_bounds.index(&FullRange))); + try!(self.print_bounds(":", &real_bounds[])); try!(self.print_where_clause(generics)); try!(word(&mut self.s, " ")); try!(self.bopen()); @@ -985,7 +984,7 @@ impl<'a> State<'a> { try!(self.print_ident(item.ident)); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts.index(&FullRange))); + try!(self.print_tts(&tts[])); try!(self.pclose()); try!(word(&mut self.s, ";")); try!(self.end()); @@ -1019,12 +1018,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").index(&FullRange))); + try!(self.head(&visibility_qualified(visibility, "enum")[])); 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.index(&FullRange), span) + self.print_variants(&enum_definition.variants[], span) } pub fn print_variants(&mut self, @@ -1034,7 +1033,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.index(&FullRange))); + try!(self.print_outer_attributes(&v.node.attrs[])); try!(self.ibox(indent_unit)); try!(self.print_variant(&**v)); try!(word(&mut self.s, ",")); @@ -1062,7 +1061,7 @@ impl<'a> State<'a> { if !struct_def.fields.is_empty() { try!(self.popen()); try!(self.commasep( - Inconsistent, struct_def.fields.index(&FullRange), + Inconsistent, &struct_def.fields[], |s, field| { match field.node.kind { ast::NamedField(..) => panic!("unexpected named field"), @@ -1092,7 +1091,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.index(&FullRange))); + try!(self.print_outer_attributes(&field.node.attrs[])); try!(self.print_visibility(visibility)); try!(self.print_ident(ident)); try!(self.word_nbsp(":")); @@ -1116,7 +1115,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).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(tk)[])); match *tk { parse::token::DocComment(..) => { hardbreak(&mut self.s) @@ -1125,11 +1124,11 @@ impl<'a> State<'a> { } } ast::TtDelimited(_, ref delimed) => { - try!(word(&mut self.s, token_to_string(&delimed.open_token()).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(&delimed.open_token())[])); try!(space(&mut self.s)); - try!(self.print_tts(delimed.tts.index(&FullRange))); + try!(self.print_tts(&delimed.tts[])); try!(space(&mut self.s)); - word(&mut self.s, token_to_string(&delimed.close_token()).index(&FullRange)) + word(&mut self.s, &token_to_string(&delimed.close_token())[]) }, ast::TtSequence(_, ref seq) => { try!(word(&mut self.s, "$(")); @@ -1139,7 +1138,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).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(tk)[])); } None => {}, } @@ -1170,7 +1169,7 @@ impl<'a> State<'a> { if !args.is_empty() { try!(self.popen()); try!(self.commasep(Consistent, - args.index(&FullRange), + &args[], |s, arg| s.print_type(&*arg.ty))); try!(self.pclose()); } @@ -1194,7 +1193,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.index(&FullRange))); + try!(self.print_outer_attributes(&m.attrs[])); try!(self.print_ty_fn(None, None, m.unsafety, @@ -1226,7 +1225,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.index(&FullRange))); + try!(self.print_outer_attributes(&meth.attrs[])); match meth.node { ast::MethDecl(ident, ref generics, @@ -1244,7 +1243,7 @@ impl<'a> State<'a> { Some(&explicit_self.node), vis)); try!(word(&mut self.s, " ")); - self.print_block_with_attrs(&**body, meth.attrs.index(&FullRange)) + self.print_block_with_attrs(&**body, &meth.attrs[]) }, ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _), ..}) => { @@ -1253,7 +1252,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "! ")); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts.index(&FullRange))); + try!(self.print_tts(&tts[])); try!(self.pclose()); try!(word(&mut self.s, ";")); self.end() @@ -1520,7 +1519,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.index(&FullRange))); + try!(self.commasep_exprs(Inconsistent, &exprs[])); try!(word(&mut self.s, "]")); try!(self.end()); } @@ -1541,7 +1540,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "{")); try!(self.commasep_cmnt( Consistent, - fields.index(&FullRange), + &fields[], |s, field| { try!(s.ibox(indent_unit)); try!(s.print_ident(field.ident.node)); @@ -1568,7 +1567,7 @@ impl<'a> State<'a> { } ast::ExprTup(ref exprs) => { try!(self.popen()); - try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); + try!(self.commasep_exprs(Inconsistent, &exprs[])); if exprs.len() == 1 { try!(word(&mut self.s, ",")); } @@ -1576,7 +1575,7 @@ impl<'a> State<'a> { } ast::ExprCall(ref func, ref args) => { try!(self.print_expr_maybe_paren(&**func)); - try!(self.print_call_post(args.index(&FullRange))); + try!(self.print_call_post(&args[])); } ast::ExprMethodCall(ident, ref tys, ref args) => { let base_args = args.slice_from(1); @@ -1585,7 +1584,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.index(&FullRange), + try!(self.commasep(Inconsistent, &tys[], |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ">")); } @@ -1782,11 +1781,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.index(&FullRange), + try!(self.commasep(Inconsistent, &a.outputs[], |s, &(ref co, ref o, is_rw)| { match co.get().slice_shift_char() { Some(('=', operand)) if is_rw => { - try!(s.print_string(format!("+{}", operand).index(&FullRange), + try!(s.print_string(&format!("+{}", operand)[], ast::CookedStr)) } _ => try!(s.print_string(co.get(), ast::CookedStr)) @@ -1799,7 +1798,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.inputs.index(&FullRange), + try!(self.commasep(Inconsistent, &a.inputs[], |s, &(ref co, ref o)| { try!(s.print_string(co.get(), ast::CookedStr)); try!(s.popen()); @@ -1810,7 +1809,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.clobbers.index(&FullRange), + try!(self.commasep(Inconsistent, &a.clobbers[], |s, co| { try!(s.print_string(co.get(), ast::CookedStr)); Ok(()) @@ -1884,7 +1883,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.index(&FullRange))) + try!(word(&mut self.s, &encoded[])) } else { try!(word(&mut self.s, token::get_ident(ident).get())) } @@ -1892,7 +1891,7 @@ impl<'a> State<'a> { } pub fn print_uint(&mut self, i: uint) -> IoResult<()> { - word(&mut self.s, i.to_string().index(&FullRange)) + word(&mut self.s, &i.to_string()[]) } pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> { @@ -1966,7 +1965,7 @@ impl<'a> State<'a> { } try!(self.commasep( Inconsistent, - data.types.index(&FullRange), + &data.types[], |s, ty| s.print_type(&**ty))); comma = true; } @@ -1989,7 +1988,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "(")); try!(self.commasep( Inconsistent, - data.inputs.index(&FullRange), + &data.inputs[], |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ")")); @@ -2042,7 +2041,7 @@ impl<'a> State<'a> { Some(ref args) => { if !args.is_empty() { try!(self.popen()); - try!(self.commasep(Inconsistent, args.index(&FullRange), + try!(self.commasep(Inconsistent, &args[], |s, p| s.print_pat(&**p))); try!(self.pclose()); } @@ -2054,7 +2053,7 @@ impl<'a> State<'a> { try!(self.nbsp()); try!(self.word_space("{")); try!(self.commasep_cmnt( - Consistent, fields.index(&FullRange), + Consistent, &fields[], |s, f| { try!(s.cbox(indent_unit)); if !f.node.is_shorthand { @@ -2075,7 +2074,7 @@ impl<'a> State<'a> { ast::PatTup(ref elts) => { try!(self.popen()); try!(self.commasep(Inconsistent, - elts.index(&FullRange), + &elts[], |s, p| s.print_pat(&**p))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -2103,7 +2102,7 @@ impl<'a> State<'a> { ast::PatVec(ref before, ref slice, ref after) => { try!(word(&mut self.s, "[")); try!(self.commasep(Inconsistent, - before.index(&FullRange), + &before[], |s, p| s.print_pat(&**p))); for p in slice.iter() { if !before.is_empty() { try!(self.word_space(",")); } @@ -2117,7 +2116,7 @@ impl<'a> State<'a> { if !after.is_empty() { try!(self.word_space(",")); } } try!(self.commasep(Inconsistent, - after.index(&FullRange), + &after[], |s, p| s.print_pat(&**p))); try!(word(&mut self.s, "]")); } @@ -2134,7 +2133,7 @@ impl<'a> State<'a> { } try!(self.cbox(indent_unit)); try!(self.ibox(0u)); - try!(self.print_outer_attributes(arm.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&arm.attrs[])); let mut first = true; for p in arm.pats.iter() { if first { @@ -2234,7 +2233,7 @@ impl<'a> State<'a> { // HACK(eddyb) ignore the separately printed self argument. let args = if first { - decl.inputs.index(&FullRange) + &decl.inputs[] } else { decl.inputs.slice_from(1) }; @@ -2400,7 +2399,7 @@ impl<'a> State<'a> { ints.push(i); } - try!(self.commasep(Inconsistent, ints.index(&FullRange), |s, &idx| { + try!(self.commasep(Inconsistent, &ints[], |s, &idx| { if idx < generics.lifetimes.len() { let lifetime = &generics.lifetimes[idx]; s.print_lifetime_def(lifetime) @@ -2417,7 +2416,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.index(&FullRange))); + try!(self.print_bounds(":", ¶m.bounds[])); match param.default { Some(ref default) => { try!(space(&mut self.s)); @@ -2493,7 +2492,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, name.get())); try!(self.popen()); try!(self.commasep(Consistent, - items.index(&FullRange), + &items[], |s, i| s.print_meta_item(&**i))); try!(self.pclose()); } @@ -2529,7 +2528,7 @@ impl<'a> State<'a> { try!(self.print_path(path, false)); try!(word(&mut self.s, "::{")); } - try!(self.commasep(Inconsistent, idents.index(&FullRange), |s, w| { + try!(self.commasep(Inconsistent, &idents[], |s, w| { match w.node { ast::PathListIdent { name, .. } => { s.print_ident(name) @@ -2547,7 +2546,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.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); try!(self.print_visibility(item.vis)); match item.node { ast::ViewItemExternCrate(id, ref optional_path, _) => { @@ -2689,7 +2688,7 @@ impl<'a> State<'a> { try!(self.pclose()); } - try!(self.print_bounds(":", bounds.index(&FullRange))); + try!(self.print_bounds(":", &bounds[])); try!(self.print_fn_output(decl)); @@ -2748,7 +2747,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.index(&FullRange)); + return word(&mut self.s, &(*ltrl).lit[]); } _ => () } @@ -2758,7 +2757,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.index(&FullRange)) + word(&mut self.s, &res[]) } ast::LitChar(ch) => { let mut res = String::from_str("'"); @@ -2766,36 +2765,36 @@ impl<'a> State<'a> { res.push(c); } res.push('\''); - word(&mut self.s, res.index(&FullRange)) + word(&mut self.s, &res[]) } 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)).index(&FullRange)) + &ast_util::int_ty_to_string(st, Some(i as i64))[]) } ast::SignedIntLit(st, ast::Minus) => { let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); word(&mut self.s, - format!("-{}", istr).index(&FullRange)) + &format!("-{}", istr)[]) } ast::UnsignedIntLit(ut) => { 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).index(&FullRange)) + word(&mut self.s, &format!("{}", i)[]) } ast::UnsuffixedIntLit(ast::Minus) => { - word(&mut self.s, format!("-{}", i).index(&FullRange)) + word(&mut self.s, &format!("-{}", i)[]) } } } ast::LitFloat(ref f, t) => { word(&mut self.s, - format!( + &format!( "{}{}", f.get(), - ast_util::float_ty_to_string(t).index(&FullRange)).index(&FullRange)) + &ast_util::float_ty_to_string(t)[])[]) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitBool(val) => { @@ -2807,7 +2806,7 @@ impl<'a> State<'a> { ascii::escape_default(ch as u8, |ch| escaped.push(ch as char)); } - word(&mut self.s, format!("b\"{}\"", escaped).index(&FullRange)) + word(&mut self.s, &format!("b\"{}\"", escaped)[]) } } } @@ -2848,7 +2847,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].index(&FullRange))); + try!(word(&mut self.s, &cmnt.lines[0][])); zerobreak(&mut self.s) } comments::Isolated => { @@ -2857,7 +2856,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.index(&FullRange))); + try!(word(&mut self.s, &line[])); } try!(hardbreak(&mut self.s)); } @@ -2866,13 +2865,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].index(&FullRange))); + try!(word(&mut self.s, &cmnt.lines[0][])); 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.index(&FullRange))); + try!(word(&mut self.s, &line[])); } try!(hardbreak(&mut self.s)); } @@ -2905,7 +2904,7 @@ impl<'a> State<'a> { string=st)) } }; - word(&mut self.s, st.index(&FullRange)) + word(&mut self.s, &st[]) } pub fn next_comment(&mut self) -> Option<comments::Comment> { @@ -2936,7 +2935,7 @@ impl<'a> State<'a> { Some(abi::Rust) => Ok(()), Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string().index(&FullRange)) + self.word_nbsp(&abi.to_string()[]) } None => Ok(()) } @@ -2947,7 +2946,7 @@ impl<'a> State<'a> { match opt_abi { Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string().index(&FullRange)) + self.word_nbsp(&abi.to_string()[]) } None => Ok(()) } @@ -2963,7 +2962,7 @@ impl<'a> State<'a> { if abi != abi::Rust { try!(self.word_nbsp("extern")); - try!(self.word_nbsp(abi.to_string().index(&FullRange))); + try!(self.word_nbsp(&abi.to_string()[])); } word(&mut self.s, "fn") diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 8abb46011e6..13a14d069d7 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -37,9 +37,11 @@ //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. use std::fmt::{self, Show}; -use std::hash::Hash; +use std::hash::{Hash, Hasher}; +#[cfg(stage0)] use std::hash::Writer; use std::ops::Deref; use std::ptr; + use serialize::{Encodable, Decodable, Encoder, Decoder}; /// An owned smart pointer. @@ -105,7 +107,14 @@ impl<T: Show> Show for P<T> { } } -impl<S, T: Hash<S>> Hash<S> for P<T> { +#[cfg(stage0)] +impl<S: Writer, T: Hash<S>> Hash<S> for P<T> { + fn hash(&self, state: &mut S) { + (**self).hash(state); + } +} +#[cfg(not(stage0))] +impl<S: Hasher, T: Hash<S>> Hash<S> for P<T> { fn hash(&self, state: &mut S) { (**self).hash(state); } diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index daa51203287..28b9eaa54aa 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.index(&FullRange), "no_std") + !attr::contains_name(&krate.attrs[], "no_std") } fn no_prelude(attrs: &[ast::Attribute]) -> bool { @@ -48,7 +48,7 @@ fn no_prelude(attrs: &[ast::Attribute]) -> bool { } struct StandardLibraryInjector<'a> { - alt_std_name: Option<String>, + alt_std_name: Option<String> } impl<'a> fold::Folder for StandardLibraryInjector<'a> { @@ -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.index(&FullRange)), + Some(ref s) => token::intern_and_get_ident(&s[]), None => token::intern_and_get_ident("std"), }; @@ -84,14 +84,13 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { fn inject_crates_ref(krate: ast::Crate, alt_std_name: Option<String>) -> ast::Crate { let mut fold = StandardLibraryInjector { - alt_std_name: alt_std_name, + alt_std_name: alt_std_name }; fold.fold_crate(krate) } struct PreludeInjector<'a>; - impl<'a> fold::Folder for PreludeInjector<'a> { fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate { // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source. @@ -104,27 +103,17 @@ impl<'a> fold::Folder for PreludeInjector<'a> { attr::mark_used(&no_std_attr); krate.attrs.push(no_std_attr); - 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. - let globs_attr = attr::mk_attr_inner(attr::mk_attr_id(), - attr::mk_list_item( - InternedString::new("feature"), - vec!( - attr::mk_word_item(InternedString::new("globs")), - ))); - // std_inject runs after feature checking so manually mark this attr - attr::mark_used(&globs_attr); - krate.attrs.push(globs_attr); - + // only add `use std::prelude::*;` if there wasn't a + // `#![no_implicit_prelude]` at the crate level. + // fold_mod() will insert glob path. + if !no_prelude(&krate.attrs[]) { krate.module = self.fold_mod(krate.module); } krate } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { - if !no_prelude(item.attrs.index(&FullRange)) { + if !no_prelude(&item.attrs[]) { // 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 711715355e9..bacfa0bbfce 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.index(&FullRange), "test"); + let should_test = attr::contains_name(&krate.config[], "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.index(&FullRange), + attr::first_attr_value_str_by_name(&krate.attrs[], "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.index(&FullRange))); + ast_util::path_name_i(&self.cx.path[])); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { @@ -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.index(&FullRange), "test") && - !attr::contains_name(attrs.index(&FullRange), "bench") + !attr::contains_name(&attrs[], "test") && + !attr::contains_name(&attrs[], "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.index(&FullRange), "test"); + let has_test_attr = attr::contains_name(&i.attrs[], "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.index(&FullRange), "bench"); + let has_bench_attr = attr::contains_name(&i.attrs[], "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().index(&FullRange), tests) + test::test_main_static(&::os::args()[], 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.index(&FullRange)) { - Some(ref s) if "test" == s.get().index(&FullRange) => true, + match attr::find_crate_name(&krate.attrs[]) { + Some(ref s) if "test" == &s.get()[] => 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.index(&FullRange))); + debug!("encoding {}", ast_util::path_name_i(&path[])); // path to the #[test] function: "foo::bar::baz" - 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))); + let path_string = ast_util::path_name_i(&path[]); + let name_expr = ecx.expr_str(span, token::intern_and_get_ident(&path_string[])); // 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 93de342d487..5dca39f1aea 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -20,6 +20,7 @@ use std::cmp::Ordering; use std::collections::HashMap; use std::fmt; use std::hash::Hash; +use std::collections::hash_map::Hasher; use std::ops::Deref; use std::rc::Rc; @@ -28,8 +29,8 @@ pub struct Interner<T> { vect: RefCell<Vec<T> >, } -// when traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) -impl<T: Eq + Hash + Clone + 'static> Interner<T> { +// when traits can extend traits, we should extend index<Name,T> to get [] +impl<T: Eq + Hash<Hasher> + Clone + 'static> Interner<T> { pub fn new() -> Interner<T> { Interner { map: RefCell::new(HashMap::new()), @@ -78,7 +79,7 @@ impl<T: Eq + Hash + Clone + 'static> Interner<T> { } pub fn find<Q: ?Sized>(&self, val: &Q) -> Option<Name> - where Q: BorrowFrom<T> + Eq + Hash { + where Q: BorrowFrom<T> + Eq + Hash<Hasher> { let map = self.map.borrow(); match (*map).get(val) { Some(v) => Some(*v), @@ -109,27 +110,27 @@ impl Eq for RcStr {} impl Ord for RcStr { fn cmp(&self, other: &RcStr) -> Ordering { - self.index(&FullRange).cmp(other.index(&FullRange)) + self[].cmp(&other[]) } } impl fmt::Show for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Show; - self.index(&FullRange).fmt(f) + self[].fmt(f) } } impl BorrowFrom<RcStr> for str { fn borrow_from(owned: &RcStr) -> &str { - owned.string.index(&FullRange) + &owned.string[] } } impl Deref for RcStr { type Target = str; - fn deref(&self) -> &str { self.string.index(&FullRange) } + fn deref(&self) -> &str { &self.string[] } } /// A StrInterner differs from Interner<String> in that it accepts @@ -139,7 +140,7 @@ pub struct StrInterner { vect: RefCell<Vec<RcStr> >, } -/// When traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) +/// When traits can extend traits, we should extend index<Name,T> to get [] impl StrInterner { pub fn new() -> StrInterner { StrInterner { @@ -203,7 +204,7 @@ impl StrInterner { } pub fn find<Q: ?Sized>(&self, val: &Q) -> Option<Name> - where Q: BorrowFrom<RcStr> + Eq + Hash { + where Q: BorrowFrom<RcStr> + Eq + Hash<Hasher> { match (*self.map.borrow()).get(val) { Some(v) => Some(*v), None => None, |
