From f7ff37e4c52a1d6562635fcd5bab6309cf75ea08 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Fri, 2 Jan 2015 13:56:28 +1300 Subject: Replace full slice notation with index calls --- src/libsyntax/ast.rs | 2 +- src/libsyntax/ast_map/mod.rs | 26 ++--- src/libsyntax/ast_util.rs | 14 +-- src/libsyntax/attr.rs | 12 +-- src/libsyntax/codemap.rs | 12 +-- src/libsyntax/diagnostic.rs | 40 ++++---- src/libsyntax/diagnostics/plugin.rs | 6 +- src/libsyntax/ext/asm.rs | 2 +- src/libsyntax/ext/base.rs | 10 +- src/libsyntax/ext/build.rs | 2 +- src/libsyntax/ext/concat.rs | 8 +- src/libsyntax/ext/concat_idents.rs | 2 +- src/libsyntax/ext/deriving/bounds.rs | 4 +- src/libsyntax/ext/deriving/clone.rs | 6 +- src/libsyntax/ext/deriving/decodable.rs | 2 +- src/libsyntax/ext/deriving/encodable.rs | 2 +- src/libsyntax/ext/deriving/generic/mod.rs | 46 ++++----- src/libsyntax/ext/deriving/mod.rs | 2 +- src/libsyntax/ext/deriving/show.rs | 2 +- src/libsyntax/ext/env.rs | 8 +- src/libsyntax/ext/expand.rs | 47 ++++----- src/libsyntax/ext/format.rs | 26 ++--- src/libsyntax/ext/mtwt.rs | 2 +- src/libsyntax/ext/quote.rs | 6 +- src/libsyntax/ext/source_util.rs | 14 +-- src/libsyntax/ext/tt/macro_parser.rs | 26 ++--- src/libsyntax/ext/tt/macro_rules.rs | 12 +-- src/libsyntax/ext/tt/transcribe.rs | 4 +- src/libsyntax/feature_gate.rs | 10 +- src/libsyntax/parse/attr.rs | 2 +- src/libsyntax/parse/lexer/comments.rs | 16 +-- src/libsyntax/parse/lexer/mod.rs | 16 +-- src/libsyntax/parse/mod.rs | 46 ++++----- src/libsyntax/parse/obsolete.rs | 4 +- src/libsyntax/parse/parser.rs | 158 ++++++++++++++--------------- src/libsyntax/parse/token.rs | 18 ++-- src/libsyntax/print/pp.rs | 4 +- src/libsyntax/print/pprust.rs | 160 +++++++++++++++--------------- src/libsyntax/std_inject.rs | 8 +- src/libsyntax/test.rs | 26 ++--- src/libsyntax/util/interner.rs | 12 +-- 41 files changed, 413 insertions(+), 412 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 7aa7c4fcfb3..54e6a338178 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -199,7 +199,7 @@ impl Encodable for Ident { #[cfg(stage0)] impl, E> Decodable for Ident { fn decode(d: &mut D) -> Result { - Ok(str_to_ident(try!(d.read_str())[])) + Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) } } diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index cf09e2777f7..efd35f73d45 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -99,7 +99,7 @@ pub fn path_to_string>(path: PI) -> String { if !s.is_empty() { s.push_str("::"); } - s.push_str(e[]); + s.push_str(e.index(&FullRange)); s }).to_string() } @@ -476,20 +476,20 @@ impl<'ast> Map<'ast> { F: FnOnce(Option<&[Attribute]>) -> T, { let attrs = match self.get(id) { - NodeItem(i) => Some(i.attrs[]), - NodeForeignItem(fi) => Some(fi.attrs[]), + NodeItem(i) => Some(i.attrs.index(&FullRange)), + NodeForeignItem(fi) => Some(fi.attrs.index(&FullRange)), NodeTraitItem(ref tm) => match **tm { - RequiredMethod(ref type_m) => Some(type_m.attrs[]), - ProvidedMethod(ref m) => Some(m.attrs[]), - TypeTraitItem(ref typ) => Some(typ.attrs[]), + RequiredMethod(ref type_m) => Some(type_m.attrs.index(&FullRange)), + ProvidedMethod(ref m) => Some(m.attrs.index(&FullRange)), + TypeTraitItem(ref typ) => Some(typ.attrs.index(&FullRange)), }, NodeImplItem(ref ii) => { match **ii { - MethodImplItem(ref m) => Some(m.attrs[]), - TypeImplItem(ref t) => Some(t.attrs[]), + MethodImplItem(ref m) => Some(m.attrs.index(&FullRange)), + TypeImplItem(ref t) => Some(t.attrs.index(&FullRange)), } } - NodeVariant(ref v) => Some(v.node.attrs[]), + NodeVariant(ref v) => Some(v.node.attrs.index(&FullRange)), // unit/tuple structs take the attributes straight from // the struct definition. // FIXME(eddyb) make this work again (requires access to the map). @@ -513,7 +513,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: parts[..parts.len() - 1], + in_which: parts.index(&(0..(parts.len() - 1))), idx: 0, } } @@ -590,7 +590,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { None => return false, Some((node_id, name)) => (node_id, name), }; - if part[] != mod_name.as_str() { + if part.index(&FullRange) != mod_name.as_str() { return false; } cursor = self.map.get_parent(mod_id); @@ -628,7 +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[] && + name.as_str() == self.item_name.index(&FullRange) && self.suffix_matches(parent_of_n) } } @@ -1040,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[] } else { "" }; + let id_str = if include_id { id_str.index(&FullRange) } else { "" }; match map.find(id) { Some(NodeItem(item)) => { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 5e03afec16c..aad6f115206 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -238,11 +238,11 @@ pub fn impl_pretty_name(trait_ref: &Option, ty: &Ty) -> Ident { match *trait_ref { Some(ref trait_ref) => { pretty.push('.'); - pretty.push_str(pprust::path_to_string(&trait_ref.path)[]); + pretty.push_str(pprust::path_to_string(&trait_ref.path).index(&FullRange)); } None => {} } - token::gensym_ident(pretty[]) + token::gensym_ident(pretty.index(&FullRange)) } pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod { @@ -704,7 +704,7 @@ pub fn pat_is_ident(pat: P) -> bool { pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool { (a.span == b.span) && (a.global == b.global) - && (segments_name_eq(a.segments[], b.segments[])) + && (segments_name_eq(a.segments.index(&FullRange), b.segments.index(&FullRange))) } // are two arrays of segments equal when compared unhygienically? @@ -792,13 +792,13 @@ mod test { #[test] fn idents_name_eq_test() { assert!(segments_name_eq( [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::>()[], + .iter().map(ident_to_segment).collect::>().index(&FullRange), [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] - .iter().map(ident_to_segment).collect::>()[])); + .iter().map(ident_to_segment).collect::>().index(&FullRange))); assert!(!segments_name_eq( [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::>()[], + .iter().map(ident_to_segment).collect::>().index(&FullRange), [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] - .iter().map(ident_to_segment).collect::>()[])); + .iter().map(ident_to_segment).collect::>().index(&FullRange))); } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 43e23f26e93..97f70d416db 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -97,7 +97,7 @@ impl AttrMetaMethods for MetaItem { fn meta_item_list<'a>(&'a self) -> Option<&'a [P]> { match self.node { - MetaList(_, ref l) => Some(l[]), + MetaList(_, ref l) => Some(l.index(&FullRange)), _ => None } } @@ -136,7 +136,7 @@ impl AttributeMethods for Attribute { let meta = mk_name_value_item_str( InternedString::new("doc"), token::intern_and_get_ident(strip_doc_comment_decoration( - comment.get())[])); + comment.get()).index(&FullRange))); if self.node.style == ast::AttrOuter { f(&mk_attr_outer(self.node.id, meta)) } else { @@ -296,9 +296,9 @@ pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr { } MetaList(ref n, ref items) if *n == "inline" => { mark_used(attr); - if contains_name(items[], "always") { + if contains_name(items.index(&FullRange), "always") { InlineAlways - } else if contains_name(items[], "never") { + } else if contains_name(items.index(&FullRange), "never") { InlineNever } else { InlineHint @@ -332,7 +332,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P], cfg: &ast::Me !cfg_matches(diagnostic, cfgs, &*mis[0]) } ast::MetaList(ref pred, _) => { - diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred)[]); + diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).index(&FullRange)); false }, ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg), @@ -396,7 +396,7 @@ pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P]) { if !set.insert(name.clone()) { diagnostic.span_fatal(meta.span, - format!("duplicate meta item `{}`", name)[]); + format!("duplicate meta item `{}`", name).index(&FullRange)); } } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index a49f2614cd7..6d329fe614c 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -321,9 +321,9 @@ impl FileMap { lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; let begin = begin.to_uint(); - let slice = self.src[begin..]; + let slice = self.src.index(&(begin..)); match slice.find('\n') { - Some(e) => slice[0..e], + Some(e) => slice.index(&(0..e)), None => slice }.to_string() }) @@ -368,9 +368,9 @@ impl CodeMap { // FIXME #12884: no efficient/safe way to remove from the start of a string // and reuse the allocation. let mut src = if src.starts_with("\u{feff}") { - String::from_str(src[3..]) + String::from_str(src.index(&(3..))) } else { - String::from_str(src[]) + String::from_str(src.index(&FullRange)) }; // Append '\n' in case it's not already there. @@ -457,8 +457,8 @@ impl CodeMap { if begin.fm.start_pos != end.fm.start_pos { None } else { - Some(begin.fm.src[begin.pos.to_uint().. - end.pos.to_uint()].to_string()) + Some(begin.fm.src.index(&(begin.pos.to_uint().. + end.pos.to_uint())).to_string()) } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index c19c06c3155..f43a236341e 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -123,7 +123,7 @@ impl SpanHandler { panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { - self.span_bug(sp, format!("unimplemented {}", msg)[]); + self.span_bug(sp, format!("unimplemented {}", msg).index(&FullRange)); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler @@ -166,7 +166,7 @@ impl Handler { self.err_count.get()); } } - self.fatal(s[]); + self.fatal(s.index(&FullRange)); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); @@ -182,7 +182,7 @@ impl Handler { panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) -> ! { - self.bug(format!("unimplemented {}", msg)[]); + self.bug(format!("unimplemented {}", msg).index(&FullRange)); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, @@ -277,7 +277,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { - try!(t.write_str(msg[0..msg.len()-1])); + try!(t.write_str(msg.index(&(0..(msg.len()-1))))); try!(t.reset()); try!(t.write_str("\n")); } else { @@ -299,16 +299,16 @@ fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, } try!(print_maybe_styled(dst, - format!("{}: ", lvl.to_string())[], + format!("{}: ", lvl.to_string()).index(&FullRange), term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, - format!("{}", msg)[], + format!("{}", msg).index(&FullRange), term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); - try!(print_maybe_styled(dst, format!(" [{}]", code.clone())[], style)); + try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).index(&FullRange), style)); } None => () } @@ -398,12 +398,12 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); - try!(print_diagnostic(dst, ses[], lvl, msg, code)); + try!(print_diagnostic(dst, ses.index(&FullRange), lvl, msg, code)); if rsp.is_full_span() { try!(custom_highlight_lines(dst, cm, sp, lvl, lines)); } } else { - try!(print_diagnostic(dst, ss[], lvl, msg, code)); + try!(print_diagnostic(dst, ss.index(&FullRange), lvl, msg, code)); if rsp.is_full_span() { try!(highlight_lines(dst, cm, sp, lvl, lines)); } @@ -413,9 +413,9 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { - try!(print_diagnostic(dst, ss[], Help, + try!(print_diagnostic(dst, ss.index(&FullRange), Help, format!("pass `--explain {}` to see a detailed \ - explanation", code)[], None)); + explanation", code).index(&FullRange), None)); } None => () }, @@ -432,9 +432,9 @@ fn highlight_lines(err: &mut EmitterWriter, let fm = &*lines.file; let mut elided = false; - let mut display_lines = lines.lines[]; + let mut display_lines = lines.lines.index(&FullRange); if display_lines.len() > MAX_LINES { - display_lines = display_lines[0u..MAX_LINES]; + display_lines = display_lines.index(&(0u..MAX_LINES)); elided = true; } // Print the offending lines @@ -494,7 +494,7 @@ fn highlight_lines(err: &mut EmitterWriter, } } try!(print_maybe_styled(err, - format!("{}\n", s)[], + format!("{}\n", s).index(&FullRange), term::attr::ForegroundColor(lvl.color()))); } Ok(()) @@ -514,7 +514,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, -> io::IoResult<()> { let fm = &*lines.file; - let lines = lines.lines[]; + let lines = lines.lines.index(&FullRange); if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, @@ -545,7 +545,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, s.push('^'); s.push('\n'); print_maybe_styled(w, - s[], + s.index(&FullRange), term::attr::ForegroundColor(lvl.color())) } @@ -560,12 +560,12 @@ fn print_macro_backtrace(w: &mut EmitterWriter, codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; - try!(print_diagnostic(w, ss[], Note, + try!(print_diagnostic(w, ss.index(&FullRange), Note, format!("in expansion of {}{}{}", pre, ei.callee.name, - post)[], None)); + post).index(&FullRange), None)); let ss = cm.span_to_string(ei.call_site); - try!(print_diagnostic(w, ss[], Note, "expansion site", None)); + try!(print_diagnostic(w, ss.index(&FullRange), Note, "expansion site", None)); Ok(Some(ei.call_site)) } None => Ok(None) @@ -578,6 +578,6 @@ pub fn expect(diag: &SpanHandler, opt: Option, msg: M) -> T where { match opt { Some(t) => t, - None => diag.handler().bug(msg()[]), + None => diag.handler().bug(msg().index(&FullRange)), } } diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 720a907fe77..0f4ebd74b66 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -58,7 +58,7 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, Some(previous_span) => { ecx.span_warn(span, format!( "diagnostic code {} already used", token::get_ident(code).get() - )[]); + ).index(&FullRange)); ecx.span_note(previous_span, "previous invocation"); }, None => () @@ -87,12 +87,12 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, if diagnostics.insert(code.name, description).is_some() { ecx.span_err(span, format!( "diagnostic code {} already registered", token::get_ident(*code).get() - )[]); + ).index(&FullRange)); } }); let sym = Ident::new(token::gensym(( "__register_diagnostic_".to_string() + token::get_ident(*code).get() - )[])); + ).index(&FullRange))); MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter()) } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index b77b822a6b2..04dec0e8028 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -100,7 +100,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(('=', _)) => None, Some(('+', operand)) => { Some(token::intern_and_get_ident(format!( - "={}", operand)[])) + "={}", operand).index(&FullRange))) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 91ae7396ea4..52e402689ba 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -539,7 +539,7 @@ impl<'a> ExtCtxt<'a> { pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); } pub fn mod_path(&self) -> Vec { let mut v = Vec::new(); - v.push(token::str_to_ident(self.ecfg.crate_name[])); + v.push(token::str_to_ident(self.ecfg.crate_name.index(&FullRange))); v.extend(self.mod_path.iter().map(|a| *a)); return v; } @@ -548,7 +548,7 @@ impl<'a> ExtCtxt<'a> { if self.recursion_count > self.ecfg.recursion_limit { self.span_fatal(ei.call_site, format!("recursion limit reached while expanding the macro `{}`", - ei.callee.name)[]); + ei.callee.name).index(&FullRange)); } let mut call_site = ei.call_site; @@ -670,7 +670,7 @@ pub fn check_zero_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], name: &str) { if tts.len() != 0 { - cx.span_err(sp, format!("{} takes no arguments", name)[]); + cx.span_err(sp, format!("{} takes no arguments", name).index(&FullRange)); } } @@ -683,12 +683,12 @@ pub fn get_single_str_from_tts(cx: &mut ExtCtxt, -> Option { let mut p = cx.new_parser_from_tts(tts); if p.token == token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name)[]); + cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); return None } let ret = cx.expander().fold_expr(p.parse_expr()); if p.token != token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name)[]); + cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); } expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| { s.get().to_string() diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index ea345f3a458..e3561e86070 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -709,7 +709,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, token::intern_and_get_ident(loc.file - .name[])); + .name.index(&FullRange))); let expr_line = self.expr_uint(span, loc.line); let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 03dd08fdf7f..1f1781dceb3 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -40,14 +40,14 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, ast::LitInt(i, ast::UnsignedIntLit(_)) | ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => { - accumulator.push_str(format!("{}", i)[]); + accumulator.push_str(format!("{}", i).index(&FullRange)); } ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => { - accumulator.push_str(format!("-{}", i)[]); + accumulator.push_str(format!("-{}", i).index(&FullRange)); } ast::LitBool(b) => { - accumulator.push_str(format!("{}", b)[]); + accumulator.push_str(format!("{}", b).index(&FullRange)); } ast::LitByte(..) | ast::LitBinary(..) => { @@ -62,5 +62,5 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, } base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(accumulator[]))) + token::intern_and_get_ident(accumulator.index(&FullRange)))) } diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 2cf60d30a1b..02f702248cb 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -40,7 +40,7 @@ pub fn expand_syntax_ext<'cx>(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree] } } } - let res = str_to_ident(res_str[]); + let res = str_to_ident(res_str.index(&FullRange)); let e = P(ast::Expr { id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/ext/deriving/bounds.rs b/src/libsyntax/ext/deriving/bounds.rs index cf29bb048d6..2189f7d83d8 100644 --- a/src/libsyntax/ext/deriving/bounds.rs +++ b/src/libsyntax/ext/deriving/bounds.rs @@ -29,12 +29,12 @@ pub fn expand_deriving_bound(cx: &mut ExtCtxt, "Send" | "Sync" => { return cx.span_err(span, format!("{} is an unsafe trait and it \ - should be implemented explicitly", *tname)[]) + should be implemented explicitly", *tname).index(&FullRange)) } ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ - found {}", *tname)[]) + found {}", *tname).index(&FullRange)) } } }, diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 3c74a9f4431..d9d6cebd05c 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -80,11 +80,11 @@ fn cs_clone( EnumNonMatchingCollapsed (..) => { cx.span_bug(trait_span, format!("non-matching enum variants in \ - `deriving({})`", name)[]) + `deriving({})`", name).index(&FullRange)) } StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, - format!("static method in `deriving({})`", name)[]) + format!("static method in `deriving({})`", name).index(&FullRange)) } } @@ -101,7 +101,7 @@ fn cs_clone( None => { cx.span_bug(trait_span, format!("unnamed field in normal struct in \ - `deriving({})`", name)[]) + `deriving({})`", name).index(&FullRange)) } }; cx.field_imm(field.span, ident, subcall(field)) diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 8094f0d3de8..a9289f0175a 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -198,7 +198,7 @@ fn decode_static_fields(cx: &mut ExtCtxt, let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, token::intern_and_get_ident(format!("_field{}", - i)[]), + i).index(&FullRange)), i) }).collect(); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 0fceb0fbfda..7114217d51d 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -183,7 +183,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let name = match name { Some(id) => token::get_ident(id), None => { - token::intern_and_get_ident(format!("_field{}", i)[]) + token::intern_and_get_ident(format!("_field{}", i).index(&FullRange)) } }; let enc = cx.expr_method_call(span, self_.clone(), diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 1aa430c4a08..8ef9a7dc012 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -510,15 +510,15 @@ impl<'a> TraitDef<'a> { self, struct_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) } else { method_def.expand_struct_method_body(cx, self, struct_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) }; method_def.create_method(cx, @@ -550,15 +550,15 @@ impl<'a> TraitDef<'a> { self, enum_def, type_ident, - self_args[], - nonself_args[]) + self_args.index(&FullRange), + nonself_args.index(&FullRange)) } else { method_def.expand_enum_method_body(cx, self, enum_def, type_ident, self_args, - nonself_args[]) + nonself_args.index(&FullRange)) }; method_def.create_method(cx, @@ -645,7 +645,7 @@ impl<'a> MethodDef<'a> { for (i, ty) in self.args.iter().enumerate() { let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics); - let ident = cx.ident_of(format!("__arg_{}", i)[]); + let ident = cx.ident_of(format!("__arg_{}", i).index(&FullRange)); arg_tys.push((ident, ast_ty)); let arg_expr = cx.expr_ident(trait_.span, ident); @@ -752,7 +752,7 @@ impl<'a> MethodDef<'a> { struct_path, struct_def, format!("__self_{}", - i)[], + i).index(&FullRange), ast::MutImmutable); patterns.push(pat); raw_fields.push(ident_expr); @@ -908,22 +908,22 @@ impl<'a> MethodDef<'a> { .collect::>(); let self_arg_idents = self_arg_names.iter() - .map(|name|cx.ident_of(name[])) + .map(|name|cx.ident_of(name.index(&FullRange))) .collect::>(); // 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 = self_arg_names.iter() - .map(|name| { let vi_suffix = format!("{}_vi", name[]); - cx.ident_of(vi_suffix[]) }) + .map(|name| { let vi_suffix = format!("{}_vi", name.index(&FullRange)); + cx.ident_of(vi_suffix.index(&FullRange)) }) .collect::>(); // Builds, via callback to call_substructure_method, the // delegated expression that handles the catch-all case, // using `__variants_tuple` to drive logic if necessary. let catch_all_substructure = EnumNonMatchingCollapsed( - self_arg_idents, variants[], vi_idents[]); + self_arg_idents, variants.index(&FullRange), vi_idents.index(&FullRange)); // These arms are of the form: // (Variant1, Variant1, ...) => Body1 @@ -945,12 +945,12 @@ impl<'a> MethodDef<'a> { let mut subpats = Vec::with_capacity(self_arg_names.len()); let mut self_pats_idents = Vec::with_capacity(self_arg_names.len() - 1); let first_self_pat_idents = { - let (p, idents) = mk_self_pat(cx, self_arg_names[0][]); + let (p, idents) = mk_self_pat(cx, self_arg_names[0].index(&FullRange)); subpats.push(p); idents }; for self_arg_name in self_arg_names.tail().iter() { - let (p, idents) = mk_self_pat(cx, self_arg_name[]); + let (p, idents) = mk_self_pat(cx, self_arg_name.index(&FullRange)); subpats.push(p); self_pats_idents.push(idents); } @@ -1006,7 +1006,7 @@ impl<'a> MethodDef<'a> { &**variant, field_tuples); let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args[], nonself_args, + cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, &substructure); cx.arm(sp, vec![single_pat], arm_expr) @@ -1059,7 +1059,7 @@ impl<'a> MethodDef<'a> { } let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args[], nonself_args, + cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, &catch_all_substructure); // Builds the expression: @@ -1263,7 +1263,7 @@ impl<'a> TraitDef<'a> { cx.span_bug(sp, "a struct with named and unnamed fields in `derive`"); } }; - let ident = cx.ident_of(format!("{}_{}", prefix, i)[]); + let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); paths.push(codemap::Spanned{span: sp, node: ident}); let val = cx.expr( sp, ast::ExprParen(cx.expr_deref(sp, cx.expr_path(cx.path_ident(sp,ident))))); @@ -1309,7 +1309,7 @@ impl<'a> TraitDef<'a> { let mut ident_expr = Vec::new(); for (i, va) in variant_args.iter().enumerate() { let sp = self.set_expn_info(cx, va.ty.span); - let ident = cx.ident_of(format!("{}_{}", prefix, i)[]); + let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); let path1 = codemap::Spanned{span: sp, node: ident}; paths.push(path1); let expr_path = cx.expr_path(cx.path_ident(sp, ident)); @@ -1352,7 +1352,7 @@ pub fn cs_fold(use_foldl: bool, field.span, old, field.self_.clone(), - field.other[]) + field.other.index(&FullRange)) }) } else { all_fields.iter().rev().fold(base, |old, field| { @@ -1360,12 +1360,12 @@ pub fn cs_fold(use_foldl: bool, field.span, old, field.self_.clone(), - field.other[]) + field.other.index(&FullRange)) }) } }, EnumNonMatchingCollapsed(ref all_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_args[], tuple), + enum_nonmatch_f.call_mut((cx, trait_span, (all_args.index(&FullRange), 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(cx, trait_span, called) }, EnumNonMatchingCollapsed(ref all_self_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_self_args[], tuple), + enum_nonmatch_f.call_mut((cx, trait_span, (all_self_args.index(&FullRange), tuple), substructure.nonself_args)), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index e72c83b67c8..b44aa9dbd9f 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -123,7 +123,7 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, cx.span_err(titem.span, format!("unknown `derive` \ trait: `{}`", - *tname)[]); + *tname).index(&FullRange)); } }; } diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index eceac4e9a83..70d6da0f88b 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[]); + let s = token::intern_and_get_ident(format_string.index(&FullRange)); let format_string = cx.expr_str(span, s); // phew, not our responsibility any more! diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 9fedc4a158e..eb3544e3c5c 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -30,7 +30,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT Some(v) => v }; - let e = match os::getenv(var[]) { + let e = match os::getenv(var.index(&FullRange)) { None => { cx.expr_path(cx.path_all(sp, true, @@ -56,7 +56,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT cx.ident_of("Some")), vec!(cx.expr_str(sp, token::intern_and_get_ident( - s[])))) + s.index(&FullRange))))) } }; MacExpr::new(e) @@ -83,7 +83,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => { token::intern_and_get_ident(format!("environment variable `{}` \ not defined", - var)[]) + var).index(&FullRange)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { @@ -106,7 +106,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) cx.span_err(sp, msg.get()); cx.expr_uint(sp, 0) } - Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s[])) + Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s.index(&FullRange))) }; MacExpr::new(e) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 212ec3b0903..75aea623de6 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -287,7 +287,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("macro undefined: '{}!'", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); // let compilation continue None @@ -303,7 +303,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, }, }); let fm = fresh_mark(); - let marked_before = mark_tts(tts[], fm); + let marked_before = mark_tts(tts.index(&FullRange), fm); // The span that we pass to the expanders we want to // be the root of the call stack. That's the most @@ -314,7 +314,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, let opt_parsed = { let expanded = expandfun.expand(fld.cx, mac_span, - marked_before[]); + marked_before.index(&FullRange)); parse_thunk(expanded) }; let parsed = match opt_parsed { @@ -323,8 +323,8 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("non-expression macro in expression position: {}", - extnamestr.get()[] - )[]); + extnamestr.get().index(&FullRange) + ).index(&FullRange)); return None; } }; @@ -334,7 +334,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, fld.cx.span_err( pth.span, format!("'{}' is not a tt-style macro", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); None } } @@ -439,7 +439,7 @@ pub fn expand_item(it: P, fld: &mut MacroExpander) if valid_ident { fld.cx.mod_push(it.ident); } - let macro_use = contains_macro_use(fld, new_attrs[]); + let macro_use = contains_macro_use(fld, new_attrs.index(&FullRange)); let result = with_exts_frame!(fld.cx.syntax_env, macro_use, noop_fold_item(it, fld)); @@ -566,7 +566,7 @@ pub fn expand_item_mac(it: P, None => { fld.cx.span_err(path_span, format!("macro undefined: '{}!'", - extnamestr)[]); + extnamestr).index(&FullRange)); // let compilation continue return SmallVector::zero(); } @@ -579,7 +579,7 @@ pub fn expand_item_mac(it: P, format!("macro {}! expects no ident argument, \ given '{}'", extnamestr, - token::get_ident(it.ident))[]); + token::get_ident(it.ident)).index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -591,14 +591,14 @@ pub fn expand_item_mac(it: P, } }); // mark before expansion: - let marked_before = mark_tts(tts[], fm); - expander.expand(fld.cx, it.span, marked_before[]) + let marked_before = mark_tts(tts.index(&FullRange), fm); + expander.expand(fld.cx, it.span, marked_before.index(&FullRange)) } IdentTT(ref expander, span) => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, format!("macro {}! expects an ident argument", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -610,13 +610,14 @@ pub fn expand_item_mac(it: P, } }); // mark before expansion: - let marked_tts = mark_tts(tts[], fm); + let marked_tts = mark_tts(tts.index(&FullRange), fm); expander.expand(fld.cx, it.span, it.ident, marked_tts) } MacroRulesTT => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, - format!("macro_rules! expects an ident argument")[]); + format!("macro_rules! expects an ident argument") + .index(&FullRange)); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -648,7 +649,7 @@ pub fn expand_item_mac(it: P, _ => { fld.cx.span_err(it.span, format!("{}! is not legal in item position", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } } @@ -667,7 +668,7 @@ pub fn expand_item_mac(it: P, None => { fld.cx.span_err(path_span, format!("non-item macro in item position: {}", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return SmallVector::zero(); } }; @@ -913,7 +914,7 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { None => { fld.cx.span_err(pth.span, format!("macro undefined: '{}!'", - extnamestr)[]); + extnamestr).index(&FullRange)); // let compilation continue return DummyResult::raw_pat(span); } @@ -930,11 +931,11 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { }); let fm = fresh_mark(); - let marked_before = mark_tts(tts[], fm); + let marked_before = mark_tts(tts.index(&FullRange), fm); let mac_span = fld.cx.original_span(); let expanded = match expander.expand(fld.cx, mac_span, - marked_before[]).make_pat() { + marked_before.index(&FullRange)).make_pat() { Some(e) => e, None => { fld.cx.span_err( @@ -942,7 +943,7 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { format!( "non-pattern macro in pattern position: {}", extnamestr.get() - )[] + ).index(&FullRange) ); return DummyResult::raw_pat(span); } @@ -954,7 +955,7 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { _ => { fld.cx.span_err(span, format!("{}! is not legal in pattern position", - extnamestr.get())[]); + extnamestr.get()).index(&FullRange)); return DummyResult::raw_pat(span); } } @@ -1231,7 +1232,7 @@ impl Folder for Marker { node: match node { MacInvocTT(path, tts, ctxt) => { MacInvocTT(self.fold_path(path), - self.fold_tts(tts[]), + self.fold_tts(tts.index(&FullRange)), mtwt::apply_mark(self.mark, ctxt)) } }, @@ -1712,7 +1713,7 @@ foo_module!(); let string = ident.get(); "xx" == string }).collect(); - let cxbinds: &[&ast::Ident] = cxbinds[]; + let cxbinds: &[&ast::Ident] = cxbinds.index(&FullRange); let cxbind = match cxbinds { [b] => b, _ => panic!("expected just one binding for ext_cx") diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 1f39555f496..85a3a5ebcae 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -113,7 +113,7 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) _ => { ecx.span_err(p.span, format!("expected ident for named argument, found `{}`", - p.this_token_to_string())[]); + p.this_token_to_string()).index(&FullRange)); return None; } }; @@ -126,7 +126,7 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Some(prev) => { ecx.span_err(e.span, format!("duplicate argument named `{}`", - name)[]); + name).index(&FullRange)); ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here"); continue } @@ -217,7 +217,7 @@ impl<'a, 'b> Context<'a, 'b> { let msg = format!("invalid reference to argument `{}` ({})", arg, self.describe_num_args()); - self.ecx.span_err(self.fmtsp, msg[]); + self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); return; } { @@ -237,7 +237,7 @@ impl<'a, 'b> Context<'a, 'b> { Some(e) => e.span, None => { let msg = format!("there is no argument named `{}`", name); - self.ecx.span_err(self.fmtsp, msg[]); + self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); return; } }; @@ -280,19 +280,19 @@ impl<'a, 'b> Context<'a, 'b> { format!("argument redeclared with type `{}` when \ it was previously `{}`", *ty, - *cur)[]); + *cur).index(&FullRange)); } (&Known(ref cur), _) => { self.ecx.span_err(sp, format!("argument used to format with `{}` was \ attempted to not be used for formatting", - *cur)[]); + *cur).index(&FullRange)); } (_, &Known(ref ty)) => { self.ecx.span_err(sp, format!("argument previously used as a format \ argument attempted to be used as `{}`", - *ty)[]); + *ty).index(&FullRange)); } (_, _) => { self.ecx.span_err(sp, "argument declared with multiple formats"); @@ -357,7 +357,7 @@ impl<'a, 'b> Context<'a, 'b> { /// Translate the accumulated string literals to a literal expression fn trans_literal_string(&mut self) -> P { let sp = self.fmtsp; - let s = token::intern_and_get_ident(self.literal[]); + let s = token::intern_and_get_ident(self.literal.index(&FullRange)); self.literal.clear(); self.ecx.expr_str(sp, s) } @@ -509,7 +509,7 @@ impl<'a, 'b> Context<'a, 'b> { None => continue // error already generated }; - let name = self.ecx.ident_of(format!("__arg{}", i)[]); + let name = self.ecx.ident_of(format!("__arg{}", i).index(&FullRange)); pats.push(self.ecx.pat_ident(e.span, name)); locals.push(Context::format_arg(self.ecx, e.span, arg_ty, self.ecx.expr_ident(e.span, name))); @@ -526,7 +526,7 @@ impl<'a, 'b> Context<'a, 'b> { }; let lname = self.ecx.ident_of(format!("__arg{}", - *name)[]); + *name).index(&FullRange)); pats.push(self.ecx.pat_ident(e.span, lname)); names[self.name_positions[*name]] = Some(Context::format_arg(self.ecx, e.span, arg_ty, @@ -606,7 +606,7 @@ impl<'a, 'b> Context<'a, 'b> { -> P { let trait_ = match *ty { Known(ref tyname) => { - match tyname[] { + match tyname.index(&FullRange) { "" => "Show", "?" => "Show", "e" => "LowerExp", @@ -619,7 +619,7 @@ impl<'a, 'b> Context<'a, 'b> { _ => { ecx.span_err(sp, format!("unknown format trait `{}`", - *tyname)[]); + *tyname).index(&FullRange)); "Dummy" } } @@ -710,7 +710,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, } if !parser.errors.is_empty() { cx.ecx.span_err(cx.fmtsp, format!("invalid format string: {}", - parser.errors.remove(0))[]); + parser.errors.remove(0)).index(&FullRange)); return DummyResult::raw_expr(sp); } if !cx.literal.is_empty() { diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 4075b208f78..49d6b255c81 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 { } // the internal function for computing marks -// it's not clear to me whether it's better to use a [] mutable +// it's not clear to me whether it's better to use a .index(&FullRange) mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index f1b52fa33c3..66c7381e433 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 ) -> Vec { - strs.iter().map(|str| str_to_ident((*str)[])).collect() + strs.iter().map(|str| str_to_ident((*str).index(&FullRange))).collect() } fn id_ext(str: &str) -> ast::Ident { @@ -675,7 +675,7 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec> { for i in range(0, tt.len()) { seq.push(tt.get_tt(i)); } - mk_tts(cx, seq[]) + mk_tts(cx, seq.index(&FullRange)) } ast::TtToken(sp, ref tok) => { let e_sp = cx.expr_ident(sp, id_ext("_sp")); @@ -764,7 +764,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); let mut vector = vec!(stmt_let_sp, stmt_let_tt); - vector.extend(mk_tts(cx, tts[]).into_iter()); + vector.extend(mk_tts(cx, tts.index(&FullRange)).into_iter()); let block = cx.expr_block( cx.block_all(sp, Vec::new(), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index a49df457cb3..5c966ed9823 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -57,7 +57,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - let filename = token::intern_and_get_ident(loc.file.name[]); + let filename = token::intern_and_get_ident(loc.file.name.index(&FullRange)); base::MacExpr::new(cx.expr_str(topmost, filename)) } @@ -65,7 +65,7 @@ pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box { let s = pprust::tts_to_string(tts); base::MacExpr::new(cx.expr_str(sp, - token::intern_and_get_ident(s[]))) + token::intern_and_get_ident(s.index(&FullRange)))) } pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) @@ -78,7 +78,7 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) .connect("::"); base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(string[]))) + token::intern_and_get_ident(string.index(&FullRange)))) } /// include! : parse the given file as an expr @@ -137,7 +137,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) cx.span_err(sp, format!("couldn't read {}: {}", file.display(), - e)[]); + e).index(&FullRange)); return DummyResult::expr(sp); } Ok(bytes) => bytes, @@ -147,7 +147,7 @@ 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 = file.display().to_string(); - let interned = token::intern_and_get_ident(src[]); + let interned = token::intern_and_get_ident(src.index(&FullRange)); cx.codemap().new_filemap(filename, src); base::MacExpr::new(cx.expr_str(sp, interned)) @@ -155,7 +155,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Err(_) => { cx.span_err(sp, format!("{} wasn't a utf-8 file", - file.display())[]); + file.display()).index(&FullRange)); return DummyResult::expr(sp); } } @@ -177,7 +177,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {}: {}", file.display(), e)[]); + format!("couldn't read {}: {}", file.display(), e).index(&FullRange)); return DummyResult::expr(sp); } Ok(bytes) => { diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 1438d152554..328e302bef3 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -153,7 +153,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { seq.num_captures } &TtDelimited(_, ref delim) => { - count_names(delim.tts[]) + count_names(delim.tts.index(&FullRange)) } &TtToken(_, MatchNt(..)) => { 1 @@ -165,7 +165,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { pub fn initial_matcher_pos(ms: Rc>, sep: Option, lo: BytePos) -> Box { - let match_idx_hi = count_names(ms[]); + let match_idx_hi = count_names(ms.index(&FullRange)); let matches: Vec<_> = range(0, match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], @@ -229,7 +229,7 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc]) p_s.span_diagnostic .span_fatal(sp, format!("duplicated bind name: {}", - string.get())[]) + string.get()).index(&FullRange)) } } } @@ -254,13 +254,13 @@ pub fn parse_or_else(sess: &ParseSess, rdr: TtReader, ms: Vec ) -> HashMap> { - match parse(sess, cfg, rdr, ms[]) { + match parse(sess, cfg, rdr, ms.index(&FullRange)) { Success(m) => m, Failure(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str[]) + sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) } Error(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str[]) + sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) } } } @@ -341,7 +341,7 @@ pub fn parse(sess: &ParseSess, // Only touch the binders we have actually bound for idx in range(ei.match_lo, ei.match_hi) { let sub = (ei.matches[idx]).clone(); - new_pos.matches[idx] + (&mut new_pos.matches[idx]) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, sp.hi)))); } @@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess, new_ei.idx += 1u; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { - new_ei.matches[idx].push(Rc::new(MatchedSeq(Vec::new(), sp))); + (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(Vec::new(), sp))); } cur_eis.push(new_ei); @@ -444,10 +444,10 @@ pub fn parse(sess: &ParseSess, if token_name_eq(&tok, &token::Eof) { if eof_eis.len() == 1u { let mut v = Vec::new(); - for dv in eof_eis[0].matches.iter_mut() { + for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } - return Success(nameize(sess, ms, v[])); + return Success(nameize(sess, ms, v.index(&FullRange))); } else if eof_eis.len() > 1u { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { @@ -486,7 +486,7 @@ pub fn parse(sess: &ParseSess, TtToken(_, MatchNt(_, name, _, _)) => { let name_string = token::get_ident(name); let match_cur = ei.match_cur; - ei.matches[match_cur].push(Rc::new(MatchedNonterminal( + (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, name_string.get())))); ei.idx += 1u; ei.match_cur += 1; @@ -522,7 +522,7 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { _ => { let token_str = pprust::token_to_string(&p.token); p.fatal((format!("expected ident, found {}", - token_str[]))[]) + token_str.index(&FullRange))).index(&FullRange)) } }, "path" => { @@ -536,7 +536,7 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { res } _ => { - p.fatal(format!("unsupported builtin nonterminal parser: {}", name)[]) + p.fatal(format!("unsupported builtin nonterminal parser: {}", name).index(&FullRange)) } } } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 9837c8088fa..805af484e28 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[]); + parser.span_err(span, msg.index(&FullRange)); } } } @@ -126,8 +126,8 @@ impl TTMacroExpander for MacroRulesMacroExpander { self.name, self.imported_from, arg, - self.lhses[], - self.rhses[]) + self.lhses.index(&FullRange), + self.rhses.index(&FullRange)) } } @@ -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[], + TtDelimited(_, ref delim) => delim.tts.index(&FullRange), _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating @@ -194,13 +194,13 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, - Error(sp, ref msg) => cx.span_fatal(sp, msg[]) + Error(sp, ref msg) => cx.span_fatal(sp, msg.index(&FullRange)) } } _ => cx.bug("non-matcher found in parsed lhses") } } - cx.span_fatal(best_fail_spot, best_fail_msg[]); + cx.span_fatal(best_fail_spot, best_fail_msg.index(&FullRange)); } // Note that macro-by-example's input is also matched against a token tree: diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index e4e6f5ac6b0..7ca920a6196 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -240,7 +240,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { } LisContradiction(ref msg) => { // FIXME #2887 blame macro invoker instead - r.sp_diag.span_fatal(sp.clone(), msg[]); + r.sp_diag.span_fatal(sp.clone(), msg.index(&FullRange)); } LisConstraint(len, _) => { if len == 0 { @@ -297,7 +297,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { r.sp_diag.span_fatal( r.cur_span, /* blame the macro writer */ format!("variable '{}' is still repeating at this depth", - token::get_ident(ident))[]); + token::get_ident(ident)).index(&FullRange)); } } } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 0810d4ee93a..afe149e9d69 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -149,7 +149,7 @@ impl<'a> Context<'a> { self.span_handler.span_err(span, explain); self.span_handler.span_help(span, format!("add #![feature({})] to the \ crate attributes to enable", - feature)[]); + feature).index(&FullRange)); } } @@ -240,7 +240,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } match i.node { ast::ItemForeignMod(ref foreign_module) => { - if attr::contains_name(i.attrs[], "link_args") { + if attr::contains_name(i.attrs.index(&FullRange), "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ @@ -254,14 +254,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } ast::ItemFn(..) => { - if attr::contains_name(i.attrs[], "plugin_registrar") { + if attr::contains_name(i.attrs.index(&FullRange), "plugin_registrar") { self.gate_feature("plugin_registrar", i.span, "compiler plugins are experimental and possibly buggy"); } } ast::ItemStruct(..) => { - if attr::contains_name(i.attrs[], "simd") { + if attr::contains_name(i.attrs.index(&FullRange), "simd") { self.gate_feature("simd", i.span, "SIMD types are experimental and possibly buggy"); } @@ -303,7 +303,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { - if attr::contains_name(i.attrs[], "linkage") { + if attr::contains_name(i.attrs.index(&FullRange), "linkage") { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 41693d9d47a..f4810cee5f8 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)[]); + self.fatal(format!("expected `#`, found `{}`", token_str).index(&FullRange)); } }; diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index 0d5592b57b1..e7fc5aac9c7 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -82,7 +82,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { while j > i && lines[j - 1].trim().is_empty() { j -= 1; } - return lines[i..j].iter().map(|x| (*x).clone()).collect(); + return lines.index(&(i..j)).iter().map(|x| (*x).clone()).collect(); } /// remove a "[ \t]*\*" block from each line, if possible @@ -116,7 +116,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { if can_trim { lines.iter().map(|line| { - line[i + 1..line.len()].to_string() + line.index(&((i + 1)..line.len())).to_string() }).collect() } else { lines @@ -127,12 +127,12 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONLINERS.iter() { if comment.starts_with(*prefix) { - return comment[prefix.len()..].to_string(); + return comment.index(&(prefix.len()..)).to_string(); } } if comment.starts_with("/*") { - let lines = comment[3u..comment.len() - 2u] + let lines = comment.index(&(3u..(comment.len() - 2u))) .lines_any() .map(|s| s.to_string()) .collect:: >(); @@ -187,7 +187,7 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. - if is_doc_comment(line[]) { + if is_doc_comment(line.index(&FullRange)) { break; } lines.push(line); @@ -224,10 +224,10 @@ fn all_whitespace(s: &str, col: CharPos) -> Option { fn trim_whitespace_prefix_and_push_line(lines: &mut Vec , s: String, col: CharPos) { let len = s.len(); - let s1 = match all_whitespace(s[], col) { + let s1 = match all_whitespace(s.index(&FullRange), col) { Some(col) => { if col < len { - s[col..len].to_string() + s.index(&(col..len)).to_string() } else { "".to_string() } @@ -261,7 +261,7 @@ fn read_block_comment(rdr: &mut StringReader, rdr.bump(); rdr.bump(); } - if is_block_doc_comment(curr_line[]) { + if is_block_doc_comment(curr_line.index(&FullRange)) { return } assert!(!curr_line.contains_char('\n')); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index a50b97142c2..850d527fe39 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[]); + self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an @@ -205,7 +205,7 @@ impl<'a> StringReader<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } - self.err_span_(from_pos, to_pos, m[]); + self.err_span_(from_pos, to_pos, m.index(&FullRange)); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the @@ -214,8 +214,8 @@ impl<'a> StringReader<'a> { m.push_str(": "); let from = self.byte_offset(from_pos).to_uint(); let to = self.byte_offset(to_pos).to_uint(); - m.push_str(self.filemap.src[from..to]); - self.fatal_span_(from_pos, to_pos, m[]); + m.push_str(self.filemap.src.index(&(from..to))); + self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); } /// Advance peek_tok and peek_span to refer to the next token, and @@ -301,7 +301,7 @@ impl<'a> StringReader<'a> { while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { - if j < i { buf.push_str(s[j..i]); } + if j < i { buf.push_str(s.index(&(j..i))); } j = next; if next >= s.len() || s.char_at(next) != '\n' { let pos = start + BytePos(i as u32); @@ -311,7 +311,7 @@ impl<'a> StringReader<'a> { } i = next; } - if j < s.len() { buf.push_str(s[j..]); } + if j < s.len() { buf.push_str(s.index(&(j..))); } buf } } @@ -556,7 +556,7 @@ impl<'a> StringReader<'a> { self.translate_crlf(start_bpos, string, "bare CR not allowed in block doc-comment") } else { string.into_cow() }; - token::DocComment(token::intern(string[])) + token::DocComment(token::intern(string.index(&FullRange))) } else { token::Comment }; @@ -1110,7 +1110,7 @@ impl<'a> StringReader<'a> { // expansion purposes. See #12512 for the gory details of why // this is necessary. let ident = self.with_str_from(start, |lifetime_name| { - str_to_ident(format!("'{}", lifetime_name)[]) + str_to_ident(format!("'{}", lifetime_name).index(&FullRange)) }); // Conjure up a "keyword checking ident" to make sure that diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index b0969a573e6..24a909cc5fb 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -256,17 +256,17 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) Err(e) => { err(format!("couldn't read {}: {}", path.display(), - e)[]); + e).index(&FullRange)); unreachable!() } }; - match str::from_utf8(bytes[]).ok() { + match str::from_utf8(bytes.index(&FullRange)).ok() { Some(s) => { return string_to_filemap(sess, s.to_string(), path.as_str().unwrap().to_string()) } None => { - err(format!("{} is not UTF-8 encoded", path.display())[]) + err(format!("{} is not UTF-8 encoded", path.display()).index(&FullRange)) } } unreachable!() @@ -398,10 +398,10 @@ pub fn char_lit(lit: &str) -> (char, int) { } let msg = format!("lexer should have rejected a bad character escape {}", lit); - let msg2 = msg[]; + let msg2 = msg.index(&FullRange); fn esc(len: uint, lit: &str) -> Option<(char, int)> { - num::from_str_radix(lit[2..len], 16) + num::from_str_radix(lit.index(&(2..len)), 16) .and_then(char::from_u32) .map(|x| (x, len as int)) } @@ -409,7 +409,7 @@ pub fn char_lit(lit: &str) -> (char, int) { let unicode_escape = |&: | -> Option<(char, int)> if lit.as_bytes()[2] == b'{' { let idx = lit.find('}').expect(msg2); - let subslice = lit[3..idx]; + let subslice = lit.index(&(3..idx)); num::from_str_radix(subslice, 16) .and_then(char::from_u32) .map(|x| (x, subslice.chars().count() as int + 4)) @@ -471,7 +471,7 @@ pub fn str_lit(lit: &str) -> String { eat(&mut chars); } else { // otherwise, a normal escape - let (c, n) = char_lit(lit[i..]); + let (c, n) = char_lit(lit.index(&(i..))); for _ in range(0, n - 1) { // we don't need to move past the first \ chars.next(); } @@ -534,7 +534,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[1..].chars().all(|c| '0' <= c && c <= '9') + s.index(&(1..)).chars().all(|c| '0' <= c && c <= '9') } fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, @@ -547,7 +547,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) { // if it looks like a width, lets try to be helpful. sd.span_err(sp, &*format!("illegal width `{}` for float literal, \ - valid widths are 32 and 64", suf[1..])); + valid widths are 32 and 64", suf.index(&(1..)))); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for float literal, \ valid suffixes are `f32` and `f64`", suf)); @@ -583,7 +583,7 @@ pub fn byte_lit(lit: &str) -> (u8, uint) { b'\'' => b'\'', b'0' => b'\0', _ => { - match ::std::num::from_str_radix::(lit[2..4], 16) { + match ::std::num::from_str_radix::(lit.index(&(2..4)), 16) { Some(c) => if c > 0xFF { panic!(err(2)) @@ -633,7 +633,7 @@ pub fn binary_lit(lit: &str) -> Rc> { } _ => { // otherwise, a normal escape - let (c, n) = byte_lit(lit[i..]); + let (c, n) = byte_lit(lit.index(&(i..))); // we don't need to move past the first \ for _ in range(0, n - 1) { chars.next(); @@ -662,7 +662,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::(); - let mut s = s2[]; + let mut s = s2.index(&FullRange); debug!("integer_lit: {}, {}", s, suffix); @@ -695,7 +695,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } if base != 10 { - s = s[2..]; + s = s.index(&(2..)); } if let Some(suf) = suffix { @@ -717,7 +717,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> if looks_like_width_suffix(&['i', 'u'], suf) { sd.span_err(sp, &*format!("illegal width `{}` for integer literal; \ valid widths are 8, 16, 32 and 64", - suf[1..])); + suf.index(&(1..)))); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for numeric literal", suf)); } @@ -815,7 +815,7 @@ mod test { #[test] fn string_to_tts_macro () { let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string()); - let tts: &[ast::TokenTree] = tts[]; + let tts: &[ast::TokenTree] = tts.index(&FullRange); match tts { [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)), ast::TtToken(_, token::Not), @@ -823,19 +823,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[] { + match macro_delimed.tts.index(&FullRange) { [ast::TtDelimited(_, ref first_delimed), ast::TtToken(_, token::FatArrow), ast::TtDelimited(_, ref second_delimed)] if macro_delimed.delim == token::Paren => { - match first_delimed.tts[] { + match first_delimed.tts.index(&FullRange) { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if first_delimed.delim == token::Paren && name.as_str() == "a" => {}, _ => panic!("value 3: {}", **first_delimed), } - match second_delimed.tts[] { + match second_delimed.tts.index(&FullRange) { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if second_delimed.delim == token::Paren @@ -1113,24 +1113,24 @@ mod test { let use_s = "use foo::bar::baz;"; let vitem = string_to_view_item(use_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s[], use_s); + assert_eq!(vitem_s.index(&FullRange), use_s); let use_s = "use foo::bar as baz;"; let vitem = string_to_view_item(use_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s[], use_s); + assert_eq!(vitem_s.index(&FullRange), use_s); } #[test] fn parse_extern_crate() { let ex_s = "extern crate foo;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s[], ex_s); + assert_eq!(vitem_s.index(&FullRange), ex_s); let ex_s = "extern crate \"foo\" as bar;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s[], ex_s); + assert_eq!(vitem_s.index(&FullRange), ex_s); } fn get_spans_of_pat_idents(src: &str) -> Vec { @@ -1209,7 +1209,7 @@ mod test { let docs = item.attrs.iter().filter(|a| a.name().get() == "doc") .map(|a| a.value_str().unwrap().get().to_string()).collect::>(); let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; - assert_eq!(docs[], b); + assert_eq!(docs.index(&FullRange), b); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap(); diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index a49680d7e1c..23728c74ae8 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -127,13 +127,13 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { kind_str: &str, desc: &str) { self.span_err(sp, - format!("obsolete syntax: {}", kind_str)[]); + format!("obsolete syntax: {}", kind_str).index(&FullRange)); if !self.obsolete_set.contains(&kind) { self.sess .span_diagnostic .handler() - .note(format!("{}", desc)[]); + .note(format!("{}", desc).index(&FullRange)); self.obsolete_set.insert(kind); } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 32f8f5ee3d6..f35f42d5aca 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -389,12 +389,12 @@ impl<'a> Parser<'a> { let token_str = Parser::token_to_string(t); let last_span = self.last_span; self.span_fatal(last_span, format!("unexpected token: `{}`", - token_str)[]); + token_str).index(&FullRange)); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_string(); - self.fatal(format!("unexpected token: `{}`", this_token)[]); + self.fatal(format!("unexpected token: `{}`", this_token).index(&FullRange)); } /// Expect and consume the token t. Signal an error if @@ -408,7 +408,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", token_str, - this_token_str)[]) + this_token_str).index(&FullRange)) } } else { self.expect_one_of(slice::ref_slice(t), &[]); @@ -449,7 +449,7 @@ impl<'a> Parser<'a> { expected.push_all(&*self.expected_tokens); expected.sort_by(|a, b| a.to_string().cmp(&b.to_string())); expected.dedup(); - let expect = tokens_to_string(expected[]); + let expect = tokens_to_string(expected.index(&FullRange)); let actual = self.this_token_to_string(); self.fatal( (if expected.len() != 1 { @@ -460,7 +460,7 @@ impl<'a> Parser<'a> { (format!("expected {}, found `{}`", expect, actual)) - })[] + }).index(&FullRange) ) } } @@ -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::>(); expected.push_all(inedible); - self.check_for_erroneous_unit_struct_expecting(expected[]); + self.check_for_erroneous_unit_struct_expecting(expected.index(&FullRange)); } self.expect_one_of(edible, inedible) } @@ -510,9 +510,9 @@ impl<'a> Parser<'a> { .as_ref() .map_or(false, |t| t.is_ident() || t.is_path()) { let mut expected = edible.iter().map(|x| x.clone()).collect::>(); - expected.push_all(inedible[]); + expected.push_all(inedible.index(&FullRange)); self.check_for_erroneous_unit_struct_expecting( - expected[]); + expected.index(&FullRange)); } self.expect_one_of(edible, inedible) } @@ -535,7 +535,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal((format!("expected ident, found `{}`", - token_str))[]) + token_str)).index(&FullRange)) } } } @@ -593,7 +593,7 @@ impl<'a> Parser<'a> { let id_interned_str = token::get_name(kw.to_name()); let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", - id_interned_str, token_str)[]) + id_interned_str, token_str).index(&FullRange)) } } @@ -604,7 +604,7 @@ impl<'a> Parser<'a> { let span = self.span; self.span_err(span, format!("expected identifier, found keyword `{}`", - token_str)[]); + token_str).index(&FullRange)); } } @@ -613,7 +613,7 @@ impl<'a> Parser<'a> { if self.token.is_reserved_keyword() { let token_str = self.this_token_to_string(); self.fatal(format!("`{}` is a reserved keyword", - token_str)[]) + token_str).index(&FullRange)) } } @@ -633,7 +633,7 @@ impl<'a> Parser<'a> { Parser::token_to_string(&token::BinOp(token::And)); self.fatal(format!("expected `{}`, found `{}`", found_token, - token_str)[]) + token_str).index(&FullRange)) } } } @@ -654,7 +654,7 @@ impl<'a> Parser<'a> { Parser::token_to_string(&token::BinOp(token::Or)); self.fatal(format!("expected `{}`, found `{}`", token_str, - found_token)[]) + found_token).index(&FullRange)) } } } @@ -697,7 +697,7 @@ impl<'a> Parser<'a> { let token_str = Parser::token_to_string(&token::Lt); self.fatal(format!("expected `{}`, found `{}`", token_str, - found_token)[]) + found_token).index(&FullRange)) } } @@ -749,7 +749,7 @@ impl<'a> Parser<'a> { let this_token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", gt_str, - this_token_str)[]) + this_token_str).index(&FullRange)) } } } @@ -1369,7 +1369,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = p.parse_inner_attrs_and_block(); let mut attrs = attrs; - attrs.push_all(inner_attrs[]); + attrs.push_all(inner_attrs.index(&FullRange)); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, @@ -1388,7 +1388,7 @@ impl<'a> Parser<'a> { _ => { let token_str = p.this_token_to_string(); p.fatal((format!("expected `;` or `{{`, found `{}`", - token_str))[]) + token_str)).index(&FullRange)) } } } @@ -1584,7 +1584,7 @@ impl<'a> Parser<'a> { } else { let this_token_str = self.this_token_to_string(); let msg = format!("expected type, found `{}`", this_token_str); - self.fatal(msg[]); + self.fatal(msg.index(&FullRange)); }; let sp = mk_sp(lo, self.last_span.hi); @@ -1726,14 +1726,14 @@ impl<'a> Parser<'a> { token::Str_(s) => { (true, - LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str())[]), + LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).index(&FullRange)), ast::CookedStr)) } token::StrRaw(s, n) => { (true, LitStr( token::intern_and_get_ident( - parse::raw_str_lit(s.as_str())[]), + parse::raw_str_lit(s.as_str()).index(&FullRange)), ast::RawStr(n))) } token::Binary(i) => @@ -1977,7 +1977,7 @@ impl<'a> Parser<'a> { }; } _ => { - self.fatal(format!("expected a lifetime name")[]); + self.fatal(format!("expected a lifetime name").index(&FullRange)); } } } @@ -2015,7 +2015,7 @@ impl<'a> Parser<'a> { let msg = format!("expected `,` or `>` after lifetime \ name, found `{}`", this_token_str); - self.fatal(msg[]); + self.fatal(msg.index(&FullRange)); } } } @@ -2515,7 +2515,7 @@ impl<'a> Parser<'a> { let last_span = self.last_span; let fstr = n.as_str(); self.span_err(last_span, - format!("unexpected token: `{}`", n.as_str())[]); + format!("unexpected token: `{}`", n.as_str()).index(&FullRange)); if fstr.chars().all(|x| "0123456789.".contains_char(x)) { let float = match fstr.parse::() { Some(f) => f, @@ -2524,7 +2524,7 @@ impl<'a> Parser<'a> { self.span_help(last_span, format!("try parenthesizing the first index; e.g., `(foo.{}){}`", float.trunc() as uint, - float.fract().to_string()[1..])[]); + float.fract().to_string().index(&(1..))).index(&FullRange)); } self.abort_if_errors(); @@ -2561,18 +2561,18 @@ impl<'a> Parser<'a> { MutImmutable }; match self.token { - // e[] + // e.index(&FullRange) token::CloseDelim(token::Bracket) => { self.bump(); hi = self.span.hi; let slice = self.mk_slice(e, None, None, mutbl); e = self.mk_expr(lo, hi, slice) } - // e[..e] + // e.index(&(0..e)) token::DotDot => { self.bump(); match self.token { - // e[..] + // e.index(&(..)) token::CloseDelim(token::Bracket) => { self.bump(); hi = self.span.hi; @@ -2581,9 +2581,9 @@ impl<'a> Parser<'a> { self.span_err(e.span, "incorrect slicing expression: `[..]`"); self.span_note(e.span, - "use `expr[]` to construct a slice of the whole of expr"); + "use `expr.index(&FullRange)` to construct a slice of the whole of expr"); } - // e[..e] + // e.index(&(0..e)) _ => { hi = self.span.hi; let e2 = self.parse_expr(); @@ -2593,20 +2593,20 @@ impl<'a> Parser<'a> { } } } - // e[e] | e[e..] | e[e..e] + // e[e] | e.index(&(e..)) | e.index(&(e..e)) _ => { let ix = self.parse_expr_res(RESTRICTION_NO_DOTS); match self.token { - // e[e..] | e[e..e] + // e.index(&(e..)) | e.index(&(e..e)) token::DotDot => { self.bump(); let e2 = match self.token { - // e[e..] + // e.index(&(e..)) token::CloseDelim(token::Bracket) => { self.bump(); None } - // e[e..e] + // e.index(&(e..e)) _ => { let e2 = self.parse_expr_res(RESTRICTION_NO_DOTS); self.commit_expr_expecting(&*e2, @@ -2711,7 +2711,7 @@ impl<'a> Parser<'a> { }; let token_str = p.this_token_to_string(); p.fatal(format!("incorrect close delimiter: `{}`", - token_str)[]) + token_str).index(&FullRange)) }, /* we ought to allow different depths of unquotation */ token::Dollar if p.quote_depth > 0u => { @@ -2729,7 +2729,7 @@ impl<'a> Parser<'a> { let seq = match seq { Spanned { node, .. } => node, }; - let name_num = macro_parser::count_names(seq[]); + let name_num = macro_parser::count_names(seq.index(&FullRange)); TtSequence(mk_sp(sp.lo, p.span.hi), Rc::new(SequenceRepetition { tts: seq, @@ -2890,7 +2890,7 @@ impl<'a> Parser<'a> { let this_token_to_string = self.this_token_to_string(); self.span_err(span, format!("expected expression, found `{}`", - this_token_to_string)[]); + this_token_to_string).index(&FullRange)); let box_span = mk_sp(lo, self.last_span.hi); self.span_help(box_span, "perhaps you meant `box() (foo)` instead?"); @@ -3273,7 +3273,7 @@ impl<'a> Parser<'a> { if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string(); self.fatal(format!("expected `{}`, found `{}`", "}", - token_str)[]) + token_str).index(&FullRange)) } etc = true; break; @@ -3294,7 +3294,7 @@ impl<'a> Parser<'a> { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_string(); self.fatal(format!("unexpected `{}`", - token_str)[]) + token_str).index(&FullRange)) } _ => {} } @@ -3577,7 +3577,7 @@ impl<'a> Parser<'a> { let span = self.span; let tok_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected identifier, found `{}`", tok_str)[]); + format!("expected identifier, found `{}`", tok_str).index(&FullRange)); } let ident = self.parse_ident(); let last_span = self.last_span; @@ -3674,7 +3674,7 @@ impl<'a> Parser<'a> { let lo = self.span.lo; if self.token.is_keyword(keywords::Let) { - check_expected_item(self, item_attrs[]); + check_expected_item(self, item_attrs.index(&FullRange)); self.expect_keyword(keywords::Let); let decl = self.parse_let(); P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) @@ -3683,7 +3683,7 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| *t == token::Not) { // it's a macro invocation: - check_expected_item(self, item_attrs[]); + check_expected_item(self, item_attrs.index(&FullRange)); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... @@ -3711,7 +3711,7 @@ impl<'a> Parser<'a> { let tok_str = self.this_token_to_string(); self.fatal(format!("expected {}`(` or `{{`, found `{}`", ident_str, - tok_str)[]) + tok_str).index(&FullRange)) }, }; @@ -3759,7 +3759,7 @@ impl<'a> Parser<'a> { } } else { let found_attrs = !item_attrs.is_empty(); - let item_err = Parser::expected_item_err(item_attrs[]); + let item_err = Parser::expected_item_err(item_attrs.index(&FullRange)); match self.parse_item_or_view_item(item_attrs, false) { IoviItem(i) => { let hi = i.span.hi; @@ -3803,7 +3803,7 @@ impl<'a> Parser<'a> { let sp = self.span; let tok = self.this_token_to_string(); self.span_fatal_help(sp, - format!("expected `{{`, found `{}`", tok)[], + format!("expected `{{`, found `{}`", tok).index(&FullRange), "place this code inside a block"); } @@ -3857,13 +3857,13 @@ impl<'a> Parser<'a> { while self.token != token::CloseDelim(token::Brace) { // parsing items even when they're not allowed lets us give // better error messages and recover more gracefully. - attributes_box.push_all(self.parse_outer_attributes()[]); + attributes_box.push_all(self.parse_outer_attributes().index(&FullRange)); match self.token { token::Semi => { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box[])); + Parser::expected_item_err(attributes_box.index(&FullRange))); attributes_box = Vec::new(); } self.bump(); // empty @@ -3955,7 +3955,7 @@ impl<'a> Parser<'a> { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box[])); + Parser::expected_item_err(attributes_box.index(&FullRange))); } let hi = self.span.hi; @@ -4399,7 +4399,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `self`, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -4553,7 +4553,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected `,` or `)`, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -4729,7 +4729,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = self.parse_inner_attrs_and_block(); let body_span = body.span; let mut new_attrs = attrs; - new_attrs.push_all(inner_attrs[]); + new_attrs.push_all(inner_attrs.index(&FullRange)); (ast::MethDecl(ident, generics, abi, @@ -4948,7 +4948,7 @@ impl<'a> Parser<'a> { if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone()))[]); + token::get_ident(class_name.clone())).index(&FullRange)); } self.bump(); @@ -4987,7 +4987,7 @@ impl<'a> Parser<'a> { if fields.len() == 0 { self.fatal(format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone()))[]); + token::get_ident(class_name.clone())).index(&FullRange)); } self.parse_where_clause(generics); @@ -5002,7 +5002,7 @@ impl<'a> Parser<'a> { } else { let token_str = self.this_token_to_string(); self.fatal(format!("expected `where`, `{}`, `(`, or `;` after struct \ - name, found `{}`", "{", token_str)[]); + name, found `{}`", "{", token_str).index(&FullRange)); } } @@ -5022,7 +5022,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.span_fatal_help(span, format!("expected `,`, or `}}`, found `{}`", - token_str)[], + token_str).index(&FullRange), "struct fields should be separated by commas") } } @@ -5109,7 +5109,7 @@ impl<'a> Parser<'a> { let mut attrs = self.parse_outer_attributes(); if first { let mut tmp = attrs_remaining.clone(); - tmp.push_all(attrs[]); + tmp.push_all(attrs.index(&FullRange)); attrs = tmp; first = false; } @@ -5126,7 +5126,7 @@ impl<'a> Parser<'a> { _ => { let token_str = self.this_token_to_string(); self.fatal(format!("expected item, found `{}`", - token_str)[]) + token_str).index(&FullRange)) } } } @@ -5135,7 +5135,7 @@ impl<'a> Parser<'a> { // We parsed attributes for the first item but didn't find it let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attrs_remaining[])); + Parser::expected_item_err(attrs_remaining.index(&FullRange))); } ast::Mod { @@ -5205,7 +5205,7 @@ impl<'a> Parser<'a> { -> (ast::Item_, Vec ) { let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span)); prefix.pop(); - let mod_path = Path::new(".").join_many(self.mod_path_stack[]); + let mod_path = Path::new(".").join_many(self.mod_path_stack.index(&FullRange)); let dir_path = prefix.join(&mod_path); let mod_string = token::get_ident(id); let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name( @@ -5215,8 +5215,8 @@ impl<'a> Parser<'a> { let mod_name = mod_string.get().to_string(); let default_path_str = format!("{}.rs", mod_name); let secondary_path_str = format!("{}/mod.rs", mod_name); - let default_path = dir_path.join(default_path_str[]); - let secondary_path = dir_path.join(secondary_path_str[]); + let default_path = dir_path.join(default_path_str.index(&FullRange)); + let secondary_path = dir_path.join(secondary_path_str.index(&FullRange)); let default_exists = default_path.exists(); let secondary_exists = secondary_path.exists(); @@ -5231,13 +5231,13 @@ impl<'a> Parser<'a> { format!("maybe move this module `{0}` \ to its own directory via \ `{0}/mod.rs`", - this_module)[]); + this_module).index(&FullRange)); if default_exists || secondary_exists { self.span_note(id_sp, format!("... or maybe `use` the module \ `{}` instead of possibly \ redeclaring it", - mod_name)[]); + mod_name).index(&FullRange)); } self.abort_if_errors(); } @@ -5248,12 +5248,12 @@ impl<'a> Parser<'a> { (false, false) => { self.span_fatal_help(id_sp, format!("file not found for module `{}`", - mod_name)[], + mod_name).index(&FullRange), format!("name the file either {} or {} inside \ the directory {}", default_path_str, secondary_path_str, - dir_path.display())[]); + dir_path.display()).index(&FullRange)); } (true, true) => { self.span_fatal_help( @@ -5262,7 +5262,7 @@ impl<'a> Parser<'a> { and {}", mod_name, default_path_str, - secondary_path_str)[], + secondary_path_str).index(&FullRange), "delete or rename one of them to remove the ambiguity"); } } @@ -5284,11 +5284,11 @@ impl<'a> Parser<'a> { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); for p in included_mod_stack.slice(i, len).iter() { - err.push_str(p.display().as_cow()[]); + err.push_str(p.display().as_cow().index(&FullRange)); err.push_str(" -> "); } - err.push_str(path.display().as_cow()[]); - self.span_fatal(id_sp, err[]); + err.push_str(path.display().as_cow().index(&FullRange)); + self.span_fatal(id_sp, err.index(&FullRange)); } None => () } @@ -5369,7 +5369,7 @@ impl<'a> Parser<'a> { if !attrs_remaining.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attrs_remaining[])); + Parser::expected_item_err(attrs_remaining.index(&FullRange))); } assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { @@ -5410,7 +5410,7 @@ impl<'a> Parser<'a> { self.span_help(span, format!("perhaps you meant to enclose the crate name `{}` in \ a string?", - the_ident.as_str())[]); + the_ident.as_str()).index(&FullRange)); None } else { None @@ -5436,7 +5436,7 @@ impl<'a> Parser<'a> { self.span_fatal(span, format!("expected extern crate name but \ found `{}`", - token_str)[]); + token_str).index(&FullRange)); } }; @@ -5534,7 +5534,7 @@ impl<'a> Parser<'a> { self.span_err(start_span, format!("unit-like struct variant should be written \ without braces, as `{},`", - token::get_ident(ident))[]); + token::get_ident(ident)).index(&FullRange)); } kind = StructVariantKind(struct_def); } else if self.check(&token::OpenDelim(token::Paren)) { @@ -5619,7 +5619,7 @@ impl<'a> Parser<'a> { format!("illegal ABI: expected one of [{}], \ found `{}`", abi::all_names().connect(", "), - the_string)[]); + the_string).index(&FullRange)); None } } @@ -5681,7 +5681,7 @@ impl<'a> Parser<'a> { format!("`extern mod` is obsolete, use \ `extern crate` instead \ to refer to external \ - crates.")[]) + crates.").index(&FullRange)) } return self.parse_item_extern_crate(lo, visibility, attrs); } @@ -5709,7 +5709,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.span_fatal(span, format!("expected `{}` or `fn`, found `{}`", "{", - token_str)[]); + token_str).index(&FullRange)); } if self.eat_keyword(keywords::Virtual) { @@ -5822,7 +5822,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = - self.parse_item_mod(attrs[]); + self.parse_item_mod(attrs.index(&FullRange)); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, @@ -6162,7 +6162,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes()[]); + attrs.push_all(self.parse_outer_attributes().index(&FullRange)); // First, parse view items. let mut view_items : Vec = Vec::new(); let mut items = Vec::new(); @@ -6244,7 +6244,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes()[]); + attrs.push_all(self.parse_outer_attributes().index(&FullRange)); let mut foreign_items = Vec::new(); loop { match self.parse_foreign_item(attrs, macros_allowed) { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 094aacf3207..ca683a56472 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -479,7 +479,7 @@ macro_rules! declare_special_idents_and_keywords {( $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* - interner::StrInterner::prefill(init_vec[]) + interner::StrInterner::prefill(init_vec.index(&FullRange)) } }} @@ -628,7 +628,7 @@ impl InternedString { #[inline] pub fn get<'a>(&'a self) -> &'a str { - self.string[] + self.string.index(&FullRange) } } @@ -652,29 +652,29 @@ impl BytesContainer for InternedString { impl fmt::Show for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.string[]) + write!(f, "{}", self.string.index(&FullRange)) } } impl<'a> PartialEq<&'a str> for InternedString { #[inline(always)] fn eq(&self, other: & &'a str) -> bool { - PartialEq::eq(self.string[], *other) + PartialEq::eq(self.string.index(&FullRange), *other) } #[inline(always)] fn ne(&self, other: & &'a str) -> bool { - PartialEq::ne(self.string[], *other) + PartialEq::ne(self.string.index(&FullRange), *other) } } impl<'a> PartialEq for &'a str { #[inline(always)] fn eq(&self, other: &InternedString) -> bool { - PartialEq::eq(*self, other.string[]) + PartialEq::eq(*self, other.string.index(&FullRange)) } #[inline(always)] fn ne(&self, other: &InternedString) -> bool { - PartialEq::ne(*self, other.string[]) + PartialEq::ne(*self, other.string.index(&FullRange)) } } @@ -682,7 +682,7 @@ impl<'a> PartialEq for &'a str { impl, E> Decodable for InternedString { fn decode(d: &mut D) -> Result { Ok(get_name(get_ident_interner().intern( - try!(d.read_str())[]))) + try!(d.read_str()).index(&FullRange)))) } } @@ -697,7 +697,7 @@ impl Decodable for InternedString { #[cfg(stage0)] impl, E> Encodable for InternedString { fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self.string[]) + s.emit_str(self.string.index(&FullRange)) } } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 11cefc8719b..52306075c21 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -140,7 +140,7 @@ pub fn buf_str(toks: Vec, } s.push_str(format!("{}={}", szs[i], - tok_str(toks[i].clone()))[]); + tok_str(toks[i].clone())).index(&FullRange)); i += 1u; i %= n; } @@ -602,7 +602,7 @@ impl Printer { assert_eq!(l, len); // assert!(l <= space); self.space -= len; - self.print_str(s[]) + self.print_str(s.index(&FullRange)) } Eof => { // Eof should never get here. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 402583b60fa..9a38f6c8ac3 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -114,7 +114,7 @@ pub fn print_crate<'a>(cm: &'a CodeMap, out, ann, is_expanded); - try!(s.print_mod(&krate.module, krate.attrs[])); + try!(s.print_mod(&krate.module, krate.attrs.index(&FullRange))); try!(s.print_remaining_comments()); eof(&mut s.s) } @@ -580,7 +580,7 @@ impl<'a> State<'a> { pub fn synth_comment(&mut self, text: String) -> IoResult<()> { try!(word(&mut self.s, "/*")); try!(space(&mut self.s)); - try!(word(&mut self.s, text[])); + try!(word(&mut self.s, text.index(&FullRange))); try!(space(&mut self.s)); word(&mut self.s, "*/") } @@ -685,7 +685,7 @@ impl<'a> State<'a> { } ast::TyTup(ref elts) => { try!(self.popen()); - try!(self.commasep(Inconsistent, elts[], + try!(self.commasep(Inconsistent, elts.index(&FullRange), |s, ty| s.print_type(&**ty))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -721,10 +721,10 @@ impl<'a> State<'a> { } ast::TyObjectSum(ref ty, ref bounds) => { try!(self.print_type(&**ty)); - try!(self.print_bounds("+", bounds[])); + try!(self.print_bounds("+", bounds.index(&FullRange))); } ast::TyPolyTraitRef(ref bounds) => { - try!(self.print_bounds("", bounds[])); + try!(self.print_bounds("", bounds.index(&FullRange))); } ast::TyQPath(ref qpath) => { try!(word(&mut self.s, "<")); @@ -759,7 +759,7 @@ impl<'a> State<'a> { item: &ast::ForeignItem) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs[])); + try!(self.print_outer_attributes(item.attrs.index(&FullRange))); match item.node { ast::ForeignItemFn(ref decl, ref generics) => { try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics, @@ -770,7 +770,7 @@ impl<'a> State<'a> { } ast::ForeignItemStatic(ref t, m) => { try!(self.head(visibility_qualified(item.vis, - "static")[])); + "static").index(&FullRange))); if m { try!(self.word_space("mut")); } @@ -787,7 +787,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, typedef: &ast::AssociatedType) -> IoResult<()> { - try!(self.print_outer_attributes(typedef.attrs[])); + try!(self.print_outer_attributes(typedef.attrs.index(&FullRange))); try!(self.word_space("type")); try!(self.print_ty_param(&typedef.ty_param)); word(&mut self.s, ";") @@ -806,12 +806,12 @@ impl<'a> State<'a> { pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs[])); + try!(self.print_outer_attributes(item.attrs.index(&FullRange))); try!(self.ann.pre(self, NodeItem(item))); match item.node { ast::ItemStatic(ref ty, m, ref expr) => { try!(self.head(visibility_qualified(item.vis, - "static")[])); + "static").index(&FullRange))); if m == ast::MutMutable { try!(self.word_space("mut")); } @@ -828,7 +828,7 @@ impl<'a> State<'a> { } ast::ItemConst(ref ty, ref expr) => { try!(self.head(visibility_qualified(item.vis, - "const")[])); + "const").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.word_space(":")); try!(self.print_type(&**ty)); @@ -851,29 +851,29 @@ impl<'a> State<'a> { item.vis )); try!(word(&mut self.s, " ")); - try!(self.print_block_with_attrs(&**body, item.attrs[])); + try!(self.print_block_with_attrs(&**body, item.attrs.index(&FullRange))); } ast::ItemMod(ref _mod) => { try!(self.head(visibility_qualified(item.vis, - "mod")[])); + "mod").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.nbsp()); try!(self.bopen()); - try!(self.print_mod(_mod, item.attrs[])); + try!(self.print_mod(_mod, item.attrs.index(&FullRange))); try!(self.bclose(item.span)); } ast::ItemForeignMod(ref nmod) => { try!(self.head("extern")); - try!(self.word_nbsp(nmod.abi.to_string()[])); + try!(self.word_nbsp(nmod.abi.to_string().index(&FullRange))); try!(self.bopen()); - try!(self.print_foreign_mod(nmod, item.attrs[])); + try!(self.print_foreign_mod(nmod, item.attrs.index(&FullRange))); try!(self.bclose(item.span)); } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); try!(self.ibox(0u)); try!(self.word_nbsp(visibility_qualified(item.vis, - "type")[])); + "type").index(&FullRange))); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); try!(self.end()); // end the inner ibox @@ -895,7 +895,7 @@ impl<'a> State<'a> { )); } ast::ItemStruct(ref struct_def, ref generics) => { - try!(self.head(visibility_qualified(item.vis,"struct")[])); + try!(self.head(visibility_qualified(item.vis,"struct").index(&FullRange))); try!(self.print_struct(&**struct_def, generics, item.ident, item.span)); } @@ -936,7 +936,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.bopen()); - try!(self.print_inner_attributes(item.attrs[])); + try!(self.print_inner_attributes(item.attrs.index(&FullRange))); for impl_item in impl_items.iter() { match *impl_item { ast::MethodImplItem(ref meth) => { @@ -967,7 +967,7 @@ impl<'a> State<'a> { real_bounds.push(b); } } - try!(self.print_bounds(":", real_bounds[])); + try!(self.print_bounds(":", real_bounds.index(&FullRange))); try!(self.print_where_clause(generics)); try!(word(&mut self.s, " ")); try!(self.bopen()); @@ -985,7 +985,7 @@ impl<'a> State<'a> { try!(self.print_ident(item.ident)); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts[])); + try!(self.print_tts(tts.index(&FullRange))); try!(self.pclose()); try!(word(&mut self.s, ";")); try!(self.end()); @@ -1019,12 +1019,12 @@ impl<'a> State<'a> { generics: &ast::Generics, ident: ast::Ident, span: codemap::Span, visibility: ast::Visibility) -> IoResult<()> { - try!(self.head(visibility_qualified(visibility, "enum")[])); + try!(self.head(visibility_qualified(visibility, "enum").index(&FullRange))); try!(self.print_ident(ident)); try!(self.print_generics(generics)); try!(self.print_where_clause(generics)); try!(space(&mut self.s)); - self.print_variants(enum_definition.variants[], span) + self.print_variants(enum_definition.variants.index(&FullRange), span) } pub fn print_variants(&mut self, @@ -1034,7 +1034,7 @@ impl<'a> State<'a> { for v in variants.iter() { try!(self.space_if_not_bol()); try!(self.maybe_print_comment(v.span.lo)); - try!(self.print_outer_attributes(v.node.attrs[])); + try!(self.print_outer_attributes(v.node.attrs.index(&FullRange))); try!(self.ibox(indent_unit)); try!(self.print_variant(&**v)); try!(word(&mut self.s, ",")); @@ -1062,7 +1062,7 @@ impl<'a> State<'a> { if !struct_def.fields.is_empty() { try!(self.popen()); try!(self.commasep( - Inconsistent, struct_def.fields[], + Inconsistent, struct_def.fields.index(&FullRange), |s, field| { match field.node.kind { ast::NamedField(..) => panic!("unexpected named field"), @@ -1092,7 +1092,7 @@ impl<'a> State<'a> { ast::NamedField(ident, visibility) => { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(field.span.lo)); - try!(self.print_outer_attributes(field.node.attrs[])); + try!(self.print_outer_attributes(field.node.attrs.index(&FullRange))); try!(self.print_visibility(visibility)); try!(self.print_ident(ident)); try!(self.word_nbsp(":")); @@ -1116,7 +1116,7 @@ impl<'a> State<'a> { pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> { match *tt { ast::TtToken(_, ref tk) => { - try!(word(&mut self.s, token_to_string(tk)[])); + try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); match *tk { parse::token::DocComment(..) => { hardbreak(&mut self.s) @@ -1125,11 +1125,11 @@ impl<'a> State<'a> { } } ast::TtDelimited(_, ref delimed) => { - try!(word(&mut self.s, token_to_string(&delimed.open_token())[])); + try!(word(&mut self.s, token_to_string(&delimed.open_token()).index(&FullRange))); try!(space(&mut self.s)); - try!(self.print_tts(delimed.tts[])); + try!(self.print_tts(delimed.tts.index(&FullRange))); try!(space(&mut self.s)); - word(&mut self.s, token_to_string(&delimed.close_token())[]) + word(&mut self.s, token_to_string(&delimed.close_token()).index(&FullRange)) }, ast::TtSequence(_, ref seq) => { try!(word(&mut self.s, "$(")); @@ -1139,7 +1139,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, ")")); match seq.separator { Some(ref tk) => { - try!(word(&mut self.s, token_to_string(tk)[])); + try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); } None => {}, } @@ -1170,7 +1170,7 @@ impl<'a> State<'a> { if !args.is_empty() { try!(self.popen()); try!(self.commasep(Consistent, - args[], + args.index(&FullRange), |s, arg| s.print_type(&*arg.ty))); try!(self.pclose()); } @@ -1194,7 +1194,7 @@ impl<'a> State<'a> { pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(m.span.lo)); - try!(self.print_outer_attributes(m.attrs[])); + try!(self.print_outer_attributes(m.attrs.index(&FullRange))); try!(self.print_ty_fn(None, None, m.unsafety, @@ -1226,7 +1226,7 @@ impl<'a> State<'a> { pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(meth.span.lo)); - try!(self.print_outer_attributes(meth.attrs[])); + try!(self.print_outer_attributes(meth.attrs.index(&FullRange))); match meth.node { ast::MethDecl(ident, ref generics, @@ -1244,7 +1244,7 @@ impl<'a> State<'a> { Some(&explicit_self.node), vis)); try!(word(&mut self.s, " ")); - self.print_block_with_attrs(&**body, meth.attrs[]) + self.print_block_with_attrs(&**body, meth.attrs.index(&FullRange)) }, ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _), ..}) => { @@ -1253,7 +1253,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "! ")); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts[])); + try!(self.print_tts(tts.index(&FullRange))); try!(self.pclose()); try!(word(&mut self.s, ";")); self.end() @@ -1520,7 +1520,7 @@ impl<'a> State<'a> { ast::ExprVec(ref exprs) => { try!(self.ibox(indent_unit)); try!(word(&mut self.s, "[")); - try!(self.commasep_exprs(Inconsistent, exprs[])); + try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); try!(word(&mut self.s, "]")); try!(self.end()); } @@ -1540,7 +1540,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "{")); try!(self.commasep_cmnt( Consistent, - fields[], + fields.index(&FullRange), |s, field| { try!(s.ibox(indent_unit)); try!(s.print_ident(field.ident.node)); @@ -1566,7 +1566,7 @@ impl<'a> State<'a> { } ast::ExprTup(ref exprs) => { try!(self.popen()); - try!(self.commasep_exprs(Inconsistent, exprs[])); + try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); if exprs.len() == 1 { try!(word(&mut self.s, ",")); } @@ -1574,7 +1574,7 @@ impl<'a> State<'a> { } ast::ExprCall(ref func, ref args) => { try!(self.print_expr_maybe_paren(&**func)); - try!(self.print_call_post(args[])); + try!(self.print_call_post(args.index(&FullRange))); } ast::ExprMethodCall(ident, ref tys, ref args) => { let base_args = args.slice_from(1); @@ -1583,7 +1583,7 @@ impl<'a> State<'a> { try!(self.print_ident(ident.node)); if tys.len() > 0u { try!(word(&mut self.s, "::<")); - try!(self.commasep(Inconsistent, tys[], + try!(self.commasep(Inconsistent, tys.index(&FullRange), |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ">")); } @@ -1780,11 +1780,11 @@ impl<'a> State<'a> { try!(self.print_string(a.asm.get(), a.asm_str_style)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.outputs[], + try!(self.commasep(Inconsistent, a.outputs.index(&FullRange), |s, &(ref co, ref o, is_rw)| { match co.get().slice_shift_char() { Some(('=', operand)) if is_rw => { - try!(s.print_string(format!("+{}", operand)[], + try!(s.print_string(format!("+{}", operand).index(&FullRange), ast::CookedStr)) } _ => try!(s.print_string(co.get(), ast::CookedStr)) @@ -1797,7 +1797,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.inputs[], + try!(self.commasep(Inconsistent, a.inputs.index(&FullRange), |s, &(ref co, ref o)| { try!(s.print_string(co.get(), ast::CookedStr)); try!(s.popen()); @@ -1808,7 +1808,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.clobbers[], + try!(self.commasep(Inconsistent, a.clobbers.index(&FullRange), |s, co| { try!(s.print_string(co.get(), ast::CookedStr)); Ok(()) @@ -1882,7 +1882,7 @@ impl<'a> State<'a> { pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> { if self.encode_idents_with_hygiene { let encoded = ident.encode_with_hygiene(); - try!(word(&mut self.s, encoded[])) + try!(word(&mut self.s, encoded.index(&FullRange))) } else { try!(word(&mut self.s, token::get_ident(ident).get())) } @@ -1890,7 +1890,7 @@ impl<'a> State<'a> { } pub fn print_uint(&mut self, i: uint) -> IoResult<()> { - word(&mut self.s, i.to_string()[]) + word(&mut self.s, i.to_string().index(&FullRange)) } pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> { @@ -1964,7 +1964,7 @@ impl<'a> State<'a> { } try!(self.commasep( Inconsistent, - data.types[], + data.types.index(&FullRange), |s, ty| s.print_type(&**ty))); comma = true; } @@ -1987,7 +1987,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "(")); try!(self.commasep( Inconsistent, - data.inputs[], + data.inputs.index(&FullRange), |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ")")); @@ -2040,7 +2040,7 @@ impl<'a> State<'a> { Some(ref args) => { if !args.is_empty() { try!(self.popen()); - try!(self.commasep(Inconsistent, args[], + try!(self.commasep(Inconsistent, args.index(&FullRange), |s, p| s.print_pat(&**p))); try!(self.pclose()); } @@ -2052,7 +2052,7 @@ impl<'a> State<'a> { try!(self.nbsp()); try!(self.word_space("{")); try!(self.commasep_cmnt( - Consistent, fields[], + Consistent, fields.index(&FullRange), |s, f| { try!(s.cbox(indent_unit)); if !f.node.is_shorthand { @@ -2073,7 +2073,7 @@ impl<'a> State<'a> { ast::PatTup(ref elts) => { try!(self.popen()); try!(self.commasep(Inconsistent, - elts[], + elts.index(&FullRange), |s, p| s.print_pat(&**p))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -2101,7 +2101,7 @@ impl<'a> State<'a> { ast::PatVec(ref before, ref slice, ref after) => { try!(word(&mut self.s, "[")); try!(self.commasep(Inconsistent, - before[], + before.index(&FullRange), |s, p| s.print_pat(&**p))); for p in slice.iter() { if !before.is_empty() { try!(self.word_space(",")); } @@ -2115,7 +2115,7 @@ impl<'a> State<'a> { if !after.is_empty() { try!(self.word_space(",")); } } try!(self.commasep(Inconsistent, - after[], + after.index(&FullRange), |s, p| s.print_pat(&**p))); try!(word(&mut self.s, "]")); } @@ -2132,7 +2132,7 @@ impl<'a> State<'a> { } try!(self.cbox(indent_unit)); try!(self.ibox(0u)); - try!(self.print_outer_attributes(arm.attrs[])); + try!(self.print_outer_attributes(arm.attrs.index(&FullRange))); let mut first = true; for p in arm.pats.iter() { if first { @@ -2232,7 +2232,7 @@ impl<'a> State<'a> { // HACK(eddyb) ignore the separately printed self argument. let args = if first { - decl.inputs[] + decl.inputs.index(&FullRange) } else { decl.inputs.slice_from(1) }; @@ -2398,7 +2398,7 @@ impl<'a> State<'a> { ints.push(i); } - try!(self.commasep(Inconsistent, ints[], |s, &idx| { + try!(self.commasep(Inconsistent, ints.index(&FullRange), |s, &idx| { if idx < generics.lifetimes.len() { let lifetime = &generics.lifetimes[idx]; s.print_lifetime_def(lifetime) @@ -2415,7 +2415,7 @@ impl<'a> State<'a> { pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> { try!(self.print_ident(param.ident)); - try!(self.print_bounds(":", param.bounds[])); + try!(self.print_bounds(":", param.bounds.index(&FullRange))); match param.default { Some(ref default) => { try!(space(&mut self.s)); @@ -2491,7 +2491,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, name.get())); try!(self.popen()); try!(self.commasep(Consistent, - items[], + items.index(&FullRange), |s, i| s.print_meta_item(&**i))); try!(self.pclose()); } @@ -2527,7 +2527,7 @@ impl<'a> State<'a> { try!(self.print_path(path, false)); try!(word(&mut self.s, "::{")); } - try!(self.commasep(Inconsistent, idents[], |s, w| { + try!(self.commasep(Inconsistent, idents.index(&FullRange), |s, w| { match w.node { ast::PathListIdent { name, .. } => { s.print_ident(name) @@ -2545,7 +2545,7 @@ impl<'a> State<'a> { pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs[])); + try!(self.print_outer_attributes(item.attrs.index(&FullRange))); try!(self.print_visibility(item.vis)); match item.node { ast::ViewItemExternCrate(id, ref optional_path, _) => { @@ -2687,7 +2687,7 @@ impl<'a> State<'a> { try!(self.pclose()); } - try!(self.print_bounds(":", bounds[])); + try!(self.print_bounds(":", bounds.index(&FullRange))); try!(self.print_fn_output(decl)); @@ -2746,7 +2746,7 @@ impl<'a> State<'a> { try!(self.maybe_print_comment(lit.span.lo)); match self.next_lit(lit.span.lo) { Some(ref ltrl) => { - return word(&mut self.s, (*ltrl).lit[]); + return word(&mut self.s, (*ltrl).lit.index(&FullRange)); } _ => () } @@ -2756,7 +2756,7 @@ impl<'a> State<'a> { let mut res = String::from_str("b'"); ascii::escape_default(byte, |c| res.push(c as char)); res.push('\''); - word(&mut self.s, res[]) + word(&mut self.s, res.index(&FullRange)) } ast::LitChar(ch) => { let mut res = String::from_str("'"); @@ -2764,27 +2764,27 @@ impl<'a> State<'a> { res.push(c); } res.push('\''); - word(&mut self.s, res[]) + word(&mut self.s, res.index(&FullRange)) } ast::LitInt(i, t) => { match t { ast::SignedIntLit(st, ast::Plus) => { word(&mut self.s, - ast_util::int_ty_to_string(st, Some(i as i64))[]) + ast_util::int_ty_to_string(st, Some(i as i64)).index(&FullRange)) } ast::SignedIntLit(st, ast::Minus) => { let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); word(&mut self.s, - format!("-{}", istr)[]) + format!("-{}", istr).index(&FullRange)) } ast::UnsignedIntLit(ut) => { - word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[]) + word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).index(&FullRange)) } ast::UnsuffixedIntLit(ast::Plus) => { - word(&mut self.s, format!("{}", i)[]) + word(&mut self.s, format!("{}", i).index(&FullRange)) } ast::UnsuffixedIntLit(ast::Minus) => { - word(&mut self.s, format!("-{}", i)[]) + word(&mut self.s, format!("-{}", i).index(&FullRange)) } } } @@ -2793,7 +2793,7 @@ impl<'a> State<'a> { format!( "{}{}", f.get(), - ast_util::float_ty_to_string(t)[])[]) + ast_util::float_ty_to_string(t).index(&FullRange)).index(&FullRange)) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitBool(val) => { @@ -2805,7 +2805,7 @@ impl<'a> State<'a> { ascii::escape_default(ch as u8, |ch| escaped.push(ch as char)); } - word(&mut self.s, format!("b\"{}\"", escaped)[]) + word(&mut self.s, format!("b\"{}\"", escaped).index(&FullRange)) } } } @@ -2846,7 +2846,7 @@ impl<'a> State<'a> { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1u); try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, cmnt.lines[0][])); + try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); zerobreak(&mut self.s) } comments::Isolated => { @@ -2855,7 +2855,7 @@ impl<'a> State<'a> { // Don't print empty lines because they will end up as trailing // whitespace if !line.is_empty() { - try!(word(&mut self.s, line[])); + try!(word(&mut self.s, line.index(&FullRange))); } try!(hardbreak(&mut self.s)); } @@ -2864,13 +2864,13 @@ impl<'a> State<'a> { comments::Trailing => { try!(word(&mut self.s, " ")); if cmnt.lines.len() == 1u { - try!(word(&mut self.s, cmnt.lines[0][])); + try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); hardbreak(&mut self.s) } else { try!(self.ibox(0u)); for line in cmnt.lines.iter() { if !line.is_empty() { - try!(word(&mut self.s, line[])); + try!(word(&mut self.s, line.index(&FullRange))); } try!(hardbreak(&mut self.s)); } @@ -2903,7 +2903,7 @@ impl<'a> State<'a> { string=st)) } }; - word(&mut self.s, st[]) + word(&mut self.s, st.index(&FullRange)) } pub fn next_comment(&mut self) -> Option { @@ -2934,7 +2934,7 @@ impl<'a> State<'a> { Some(abi::Rust) => Ok(()), Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string()[]) + self.word_nbsp(abi.to_string().index(&FullRange)) } None => Ok(()) } @@ -2945,7 +2945,7 @@ impl<'a> State<'a> { match opt_abi { Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string()[]) + self.word_nbsp(abi.to_string().index(&FullRange)) } None => Ok(()) } @@ -2961,7 +2961,7 @@ impl<'a> State<'a> { if abi != abi::Rust { try!(self.word_nbsp("extern")); - try!(self.word_nbsp(abi.to_string()[])); + try!(self.word_nbsp(abi.to_string().index(&FullRange))); } word(&mut self.s, "fn") diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 4ef7eb97a21..daa51203287 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -40,7 +40,7 @@ pub fn maybe_inject_prelude(krate: ast::Crate) -> ast::Crate { } fn use_std(krate: &ast::Crate) -> bool { - !attr::contains_name(krate.attrs[], "no_std") + !attr::contains_name(krate.attrs.index(&FullRange), "no_std") } fn no_prelude(attrs: &[ast::Attribute]) -> bool { @@ -56,7 +56,7 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { // The name to use in `extern crate "name" as std;` let actual_crate_name = match self.alt_std_name { - Some(ref s) => token::intern_and_get_ident(s[]), + Some(ref s) => token::intern_and_get_ident(s.index(&FullRange)), None => token::intern_and_get_ident("std"), }; @@ -104,7 +104,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { attr::mark_used(&no_std_attr); krate.attrs.push(no_std_attr); - if !no_prelude(krate.attrs[]) { + if !no_prelude(krate.attrs.index(&FullRange)) { // only add `use std::prelude::*;` if there wasn't a // `#![no_implicit_prelude]` at the crate level. // fold_mod() will insert glob path. @@ -124,7 +124,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { } fn fold_item(&mut self, item: P) -> SmallVector> { - if !no_prelude(item.attrs[]) { + if !no_prelude(item.attrs.index(&FullRange)) { // only recur if there wasn't `#![no_implicit_prelude]` // on this item, i.e. this means that the prelude is not // implicitly imported though the whole subtree diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index e480532a410..0b2c45ee3a7 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -73,14 +73,14 @@ pub fn modify_for_testing(sess: &ParseSess, // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. - let should_test = attr::contains_name(krate.config[], "test"); + let should_test = attr::contains_name(krate.config.index(&FullRange), "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = - attr::first_attr_value_str_by_name(krate.attrs[], + attr::first_attr_value_str_by_name(krate.attrs.index(&FullRange), "reexport_test_harness_main"); if should_test { @@ -119,7 +119,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { self.cx.path.push(ident); } debug!("current path: {}", - ast_util::path_name_i(self.cx.path[])); + ast_util::path_name_i(self.cx.path.index(&FullRange))); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { @@ -277,8 +277,8 @@ fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { - !attr::contains_name(attrs[], "test") && - !attr::contains_name(attrs[], "bench") + !attr::contains_name(attrs.index(&FullRange), "test") && + !attr::contains_name(attrs.index(&FullRange), "bench") }) } @@ -291,7 +291,7 @@ enum HasTestSignature { fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_test_attr = attr::contains_name(i.attrs[], "test"); + let has_test_attr = attr::contains_name(i.attrs.index(&FullRange), "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { @@ -329,7 +329,7 @@ fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_bench_attr = attr::contains_name(i.attrs[], "bench"); + let has_bench_attr = attr::contains_name(i.attrs.index(&FullRange), "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { @@ -384,7 +384,7 @@ We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { - test::test_main_static(::os::args()[], tests) + test::test_main_static(::os::args().index(&FullRange), tests) } static tests : &'static [test::TestDescAndFn] = &[ @@ -510,8 +510,8 @@ fn mk_tests(cx: &TestCtxt) -> P { } fn is_test_crate(krate: &ast::Crate) -> bool { - match attr::find_crate_name(krate.attrs[]) { - Some(ref s) if "test" == s.get()[] => true, + match attr::find_crate_name(krate.attrs.index(&FullRange)) { + Some(ref s) if "test" == s.get().index(&FullRange) => true, _ => false } } @@ -551,11 +551,11 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P { // creates $name: $expr let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr); - debug!("encoding {}", ast_util::path_name_i(path[])); + debug!("encoding {}", ast_util::path_name_i(path.index(&FullRange))); // path to the #[test] function: "foo::bar::baz" - let path_string = ast_util::path_name_i(path[]); - let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string[])); + let path_string = ast_util::path_name_i(path.index(&FullRange)); + let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string.index(&FullRange))); // self::test::StaticTestName($name_expr) let name_expr = ecx.expr_call(span, diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 85eea2d9daf..93de342d487 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -28,7 +28,7 @@ pub struct Interner { vect: RefCell >, } -// when traits can extend traits, we should extend index to get [] +// when traits can extend traits, we should extend index to get .index(&FullRange) impl Interner { pub fn new() -> Interner { Interner { @@ -109,27 +109,27 @@ impl Eq for RcStr {} impl Ord for RcStr { fn cmp(&self, other: &RcStr) -> Ordering { - self[].cmp(other[]) + self.index(&FullRange).cmp(other.index(&FullRange)) } } impl fmt::Show for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Show; - self[].fmt(f) + self.index(&FullRange).fmt(f) } } impl BorrowFrom for str { fn borrow_from(owned: &RcStr) -> &str { - owned.string[] + owned.string.index(&FullRange) } } impl Deref for RcStr { type Target = str; - fn deref(&self) -> &str { self.string[] } + fn deref(&self) -> &str { self.string.index(&FullRange) } } /// A StrInterner differs from Interner in that it accepts @@ -139,7 +139,7 @@ pub struct StrInterner { vect: RefCell >, } -/// When traits can extend traits, we should extend index to get [] +/// When traits can extend traits, we should extend index to get .index(&FullRange) impl StrInterner { pub fn new() -> StrInterner { StrInterner { -- cgit 1.4.1-3-g733a5 From e970db37a9bba47bd46ff2755b042f830641e5f1 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Sat, 3 Jan 2015 13:33:54 +1300 Subject: Remove old slicing hacks and make new slicing work --- src/librustc/middle/expr_use_visitor.rs | 28 +--- src/librustc/middle/lang_items.rs | 2 - src/librustc/middle/mem_categorization.rs | 34 ++--- src/librustc/middle/ty.rs | 5 +- src/librustc_trans/trans/cleanup.rs | 8 +- src/librustc_trans/trans/expr.rs | 35 +---- src/librustc_typeck/check/mod.rs | 215 ++++++------------------------ src/libsyntax/parse/parser.rs | 115 +++------------- src/libsyntax/parse/token.rs | 98 +++++++------- 9 files changed, 137 insertions(+), 403 deletions(-) (limited to 'src/libsyntax') diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index ca20cbc736d..f71d020a1b8 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -441,28 +441,12 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { } ast::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs] - match rhs.node { - ast::ExprRange(ref start, ref end) => { - // Hacked slicing syntax (KILLME). - let args = match (start, end) { - (&Some(ref e1), &Some(ref e2)) => vec![&**e1, &**e2], - (&Some(ref e), &None) => vec![&**e], - (&None, &Some(ref e)) => vec![&**e], - (&None, &None) => Vec::new() - }; - let overloaded = - self.walk_overloaded_operator(expr, &**lhs, args, PassArgs::ByRef); - assert!(overloaded); - } - _ => { - if !self.walk_overloaded_operator(expr, - &**lhs, - vec![&**rhs], - PassArgs::ByRef) { - self.select_from_expr(&**lhs); - self.consume_expr(&**rhs); - } - } + if !self.walk_overloaded_operator(expr, + &**lhs, + vec![&**rhs], + PassArgs::ByRef) { + self.select_from_expr(&**lhs); + self.consume_expr(&**rhs); } } diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index bbb11b9f93b..2f81d8c0f70 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -266,8 +266,6 @@ lets_do_this! { ShrTraitLangItem, "shr", shr_trait; IndexTraitLangItem, "index", index_trait; IndexMutTraitLangItem, "index_mut", index_mut_trait; - SliceTraitLangItem, "slice", slice_trait; - SliceMutTraitLangItem, "slice_mut", slice_mut_trait; RangeStructLangItem, "range", range_struct; RangeFromStructLangItem, "range_from", range_from_struct; RangeToStructLangItem, "range_to", range_to_struct; diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index af80edb739e..99c2fad0e50 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -482,28 +482,20 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { Ok(self.cat_tup_field(expr, base_cmt, idx.node, expr_ty)) } - ast::ExprIndex(ref base, ref idx) => { - match idx.node { - ast::ExprRange(..) => { - // Slicing syntax special case (KILLME). - Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty)) + ast::ExprIndex(ref base, _) => { + let method_call = ty::MethodCall::expr(expr.id()); + match self.typer.node_method_ty(method_call) { + Some(method_ty) => { + // If this is an index implemented by a method call, then it will + // include an implicit deref of the result. + let ret_ty = ty::ty_fn_ret(method_ty).unwrap(); + self.cat_deref(expr, + self.cat_rvalue_node(expr.id(), + expr.span(), + ret_ty), 1, true) } - _ => { - let method_call = ty::MethodCall::expr(expr.id()); - match self.typer.node_method_ty(method_call) { - Some(method_ty) => { - // If this is an index implemented by a method call, then it will - // include an implicit deref of the result. - let ret_ty = ty::ty_fn_ret(method_ty).unwrap(); - self.cat_deref(expr, - self.cat_rvalue_node(expr.id(), - expr.span(), - ret_ty), 1, true) - } - None => { - self.cat_index(expr, try!(self.cat_expr(&**base))) - } - } + None => { + self.cat_index(expr, self.cat_expr(&**base)) } } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index af35b9e0e82..d954495055d 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -1047,7 +1047,7 @@ pub struct ClosureTy<'tcx> { pub abi: abi::Abi, } -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Show)] pub enum FnOutput<'tcx> { FnConverging(Ty<'tcx>), FnDiverging @@ -1699,8 +1699,7 @@ impl fmt::Show for RegionVid { impl<'tcx> fmt::Show for FnSig<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // grr, without tcx not much we can do. - write!(f, "(...)") + write!(f, "({}; variadic: {})->{}", self.inputs, self.variadic, self.output) } } diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index ac64e10ecc8..561391400a1 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -24,8 +24,7 @@ use trans::common; use trans::common::{Block, FunctionContext, ExprId, NodeInfo}; use trans::debuginfo; use trans::glue; -// Temporary due to slicing syntax hacks (KILLME) -//use middle::region; +use middle::region; use trans::type_::Type; use middle::ty::{self, Ty}; use std::fmt; @@ -129,8 +128,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { // excluding id's that correspond to closure bodies only). For // now we just say that if there is already an AST scope on the stack, // this new AST scope had better be its immediate child. - // Temporarily removed due to slicing syntax hacks (KILLME). - /*let top_scope = self.top_ast_scope(); + let top_scope = self.top_ast_scope(); if top_scope.is_some() { assert_eq!(self.ccx .tcx() @@ -138,7 +136,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { .opt_encl_scope(region::CodeExtent::from_node_id(debug_loc.id)) .map(|s|s.node_id()), top_scope); - }*/ + } self.push_scope(CleanupScope::new(AstScopeKind(debug_loc.id), Some(debug_loc))); diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index fe5333061c7..24feb579a06 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -573,40 +573,7 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, trans_rec_tup_field(bcx, &**base, idx.node) } ast::ExprIndex(ref base, ref idx) => { - match idx.node { - ast::ExprRange(ref start, ref end) => { - // Special case for slicing syntax (KILLME). - let _icx = push_ctxt("trans_slice"); - let ccx = bcx.ccx(); - - let method_call = MethodCall::expr(expr.id); - let method_ty = ccx.tcx() - .method_map - .borrow() - .get(&method_call) - .map(|method| method.ty); - let base_datum = unpack_datum!(bcx, trans(bcx, &**base)); - - let mut args = vec![]; - start.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id))); - end.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id))); - - let result_ty = ty::ty_fn_ret(monomorphize_type(bcx, - method_ty.unwrap())).unwrap(); - let scratch = rvalue_scratch_datum(bcx, result_ty, "trans_slice"); - - unpack_result!(bcx, - trans_overloaded_op(bcx, - expr, - method_call, - base_datum, - args, - Some(SaveIn(scratch.val)), - true)); - DatumBlock::new(bcx, scratch.to_expr_datum()) - } - _ => trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id)) - } + trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id)) } ast::ExprBox(_, ref contents) => { // Special case for `Box` diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 25e53c74f25..24d2907e953 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -2377,90 +2377,6 @@ fn autoderef_for_index<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>, } } -/// Checks for a `Slice` (or `SliceMut`) impl at the relevant level of autoderef. If it finds one, -/// installs method info and returns type of method (else None). -fn try_overloaded_slice_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, - method_call: MethodCall, - expr: &ast::Expr, - base_expr: &ast::Expr, - base_ty: Ty<'tcx>, // autoderef'd type - autoderefref: ty::AutoDerefRef<'tcx>, - lvalue_pref: LvaluePreference, - start_expr: &Option>, - end_expr: &Option>) - -> Option<(Ty<'tcx>, /* index type */ - Ty<'tcx>)> /* return type */ -{ - let input_ty = fcx.infcx().next_ty_var(); - let return_ty = fcx.infcx().next_ty_var(); - - let method = match lvalue_pref { - PreferMutLvalue => { - // Try `SliceMut` first, if preferred. - match fcx.tcx().lang_items.slice_mut_trait() { - Some(trait_did) => { - let method_name = match (start_expr, end_expr) { - (&Some(_), &Some(_)) => "slice_or_fail_mut", - (&Some(_), &None) => "slice_from_or_fail_mut", - (&None, &Some(_)) => "slice_to_or_fail_mut", - (&None, &None) => "as_mut_slice_", - }; - - method::lookup_in_trait_adjusted(fcx, - expr.span, - Some(&*base_expr), - token::intern(method_name), - trait_did, - autoderefref, - base_ty, - Some(vec![input_ty, return_ty])) - } - _ => None, - } - } - NoPreference => { - // Otherwise, fall back to `Slice`. - match fcx.tcx().lang_items.slice_trait() { - Some(trait_did) => { - let method_name = match (start_expr, end_expr) { - (&Some(_), &Some(_)) => "slice_or_fail", - (&Some(_), &None) => "slice_from_or_fail", - (&None, &Some(_)) => "slice_to_or_fail", - (&None, &None) => "as_slice_", - }; - - method::lookup_in_trait_adjusted(fcx, - expr.span, - Some(&*base_expr), - token::intern(method_name), - trait_did, - autoderefref, - base_ty, - Some(vec![input_ty, return_ty])) - } - _ => None, - } - } - }; - - // If some lookup succeeded, install method in table - method.map(|method| { - let method_ty = method.ty; - make_overloaded_lvalue_return_type(fcx, Some(method_call), Some(method)); - - let result_ty = ty::ty_fn_ret(method_ty); - let result_ty = match result_ty { - ty::FnConverging(result_ty) => result_ty, - ty::FnDiverging => { - fcx.tcx().sess.span_bug(expr.span, - "slice trait does not define a `!` return") - } - }; - - (input_ty, result_ty) - }) -} - /// To type-check `base_expr[index_expr]`, we progressively autoderef (and otherwise adjust) /// `base_expr`, looking for a type which either supports builtin indexing or overloaded indexing. /// This loop implements one step in that search; the autoderef loop is implemented by @@ -2474,26 +2390,17 @@ fn try_index_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, lvalue_pref: LvaluePreference) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { + let tcx = fcx.tcx(); debug!("try_index_step(expr={}, base_expr.id={}, adjusted_ty={}, adjustment={})", - expr.repr(fcx.tcx()), - base_expr.repr(fcx.tcx()), - adjusted_ty.repr(fcx.tcx()), + expr.repr(tcx), + base_expr.repr(tcx), + adjusted_ty.repr(tcx), adjustment); - // Try built-in indexing first. - match ty::index(adjusted_ty) { - Some(ty) => { - fcx.write_adjustment(base_expr.id, base_expr.span, ty::AdjustDerefRef(adjustment)); - return Some((fcx.tcx().types.uint, ty)); - } - - None => { } - } - let input_ty = fcx.infcx().next_ty_var(); // Try `IndexMut` first, if preferred. - let method = match (lvalue_pref, fcx.tcx().lang_items.index_mut_trait()) { + let method = match (lvalue_pref, tcx.lang_items.index_mut_trait()) { (PreferMutLvalue, Some(trait_did)) => { method::lookup_in_trait_adjusted(fcx, expr.span, @@ -2508,24 +2415,37 @@ fn try_index_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, }; // Otherwise, fall back to `Index`. - let method = match (method, fcx.tcx().lang_items.index_trait()) { + let method = match (method, tcx.lang_items.index_trait()) { (None, Some(trait_did)) => { method::lookup_in_trait_adjusted(fcx, expr.span, Some(&*base_expr), token::intern("index"), trait_did, - adjustment, + adjustment.clone(), adjusted_ty, Some(vec![input_ty])) } (method, _) => method, }; + if method.is_none() { + // If there are no overridden index impls, use built-in indexing. + match ty::index(adjusted_ty) { + Some(ty) => { + debug!("try_index_step: success, using built-in indexing"); + fcx.write_adjustment(base_expr.id, base_expr.span, ty::AdjustDerefRef(adjustment)); + return Some((tcx.types.uint, ty)); + } + None => {} + } + } + // If some lookup succeeds, write callee into table and extract index/element // type from the method signature. // If some lookup succeeded, install method in table method.and_then(|method| { + debug!("try_index_step: success, using overloaded indexing"); make_overloaded_lvalue_return_type(fcx, Some(method_call), Some(method)). map(|ret| (input_ty, ret.ty)) }) @@ -4270,91 +4190,42 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, if ty::type_is_error(base_t) { fcx.write_ty(id, base_t); } else { - match idx.node { - ast::ExprRange(ref start, ref end) => { - // A slice, rather than an index. Special cased for now (KILLME). + check_expr(fcx, &**idx); + let idx_t = fcx.expr_ty(&**idx); + if ty::type_is_error(idx_t) { + fcx.write_ty(id, idx_t); + } else { let base_t = structurally_resolved_type(fcx, expr.span, base_t); let result = autoderef_for_index(fcx, &**base, base_t, lvalue_pref, |adj_ty, adj| { - try_overloaded_slice_step(fcx, - MethodCall::expr(expr.id), - expr, - &**base, - adj_ty, - adj, - lvalue_pref, - start, - end) + try_index_step(fcx, + MethodCall::expr(expr.id), + expr, + &**base, + adj_ty, + adj, + lvalue_pref) }); - let mut args = vec![]; - start.as_ref().map(|x| args.push(x)); - end.as_ref().map(|x| args.push(x)); - match result { Some((index_ty, element_ty)) => { - for a in args.iter() { - check_expr_has_type(fcx, &***a, index_ty); - } - fcx.write_ty(idx.id, element_ty); - fcx.write_ty(id, element_ty) + check_expr_has_type(fcx, &**idx, index_ty); + fcx.write_ty(id, element_ty); } _ => { - for a in args.iter() { - check_expr(fcx, &***a); - } - fcx.type_error_message(expr.span, - |actual| { - format!("cannot take a slice of a value with type `{}`", + check_expr_has_type(fcx, &**idx, fcx.tcx().types.err); + fcx.type_error_message( + expr.span, + |actual| { + format!("cannot index a value of type `{}`", actual) - }, - base_t, - None); - fcx.write_ty(idx.id, fcx.tcx().types.err); + }, + base_t, + None); fcx.write_ty(id, fcx.tcx().types.err); } } - } - _ => { - check_expr(fcx, &**idx); - let idx_t = fcx.expr_ty(&**idx); - if ty::type_is_error(idx_t) { - fcx.write_ty(id, idx_t); - } else { - let base_t = structurally_resolved_type(fcx, expr.span, base_t); - - let result = - autoderef_for_index(fcx, &**base, base_t, lvalue_pref, |adj_ty, adj| { - try_index_step(fcx, - MethodCall::expr(expr.id), - expr, - &**base, - adj_ty, - adj, - lvalue_pref) - }); - - match result { - Some((index_ty, element_ty)) => { - check_expr_has_type(fcx, &**idx, index_ty); - fcx.write_ty(id, element_ty); - } - _ => { - check_expr_has_type(fcx, &**idx, fcx.tcx().types.err); - fcx.type_error_message( - expr.span, - |actual| { - format!("cannot index a value of type `{}`", - actual) - }, - base_t, - None); - fcx.write_ty(id, fcx.tcx().types.err); - } - } - } - } } } } @@ -4387,7 +4258,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, }; // Note that we don't check the type of start/end satisfy any - // bounds because right the range structs do not have any. If we add + // bounds because right now the range structs do not have any. If we add // some bounds, then we'll need to check `t_start` against them here. let range_type = match idx_type { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index f35f42d5aca..7824dacd3a1 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -63,7 +63,7 @@ use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; use ast::{Visibility, WhereClause}; use ast; use ast_util::{self, as_prec, ident_to_path, operator_prec}; -use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP}; +use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp}; use diagnostic; use ext::tt::macro_parser; use parse; @@ -2103,22 +2103,6 @@ impl<'a> Parser<'a> { ExprIndex(expr, idx) } - pub fn mk_slice(&mut self, - expr: P, - start: Option>, - end: Option>, - _mutbl: Mutability) - -> ast::Expr_ { - // FIXME: we could give more accurate span info here. - let (lo, hi) = match (&start, &end) { - (&Some(ref s), &Some(ref e)) => (s.span.lo, e.span.hi), - (&Some(ref s), &None) => (s.span.lo, s.span.hi), - (&None, &Some(ref e)) => (e.span.lo, e.span.hi), - (&None, &None) => (DUMMY_SP.lo, DUMMY_SP.hi), - }; - ExprIndex(expr, self.mk_expr(lo, hi, ExprRange(start, end))) - } - pub fn mk_range(&mut self, start: Option>, end: Option>) @@ -2550,87 +2534,28 @@ impl<'a> Parser<'a> { } // expr[...] - // Could be either an index expression or a slicing expression. - // Any slicing non-terminal can have a mutable version with `mut` - // after the opening square bracket. + // An index expression. token::OpenDelim(token::Bracket) => { + let bracket_pos = self.span.lo; self.bump(); - let mutbl = if self.eat_keyword(keywords::Mut) { - MutMutable + if self.eat(&token::CloseDelim(token::Bracket)) { + // No expression, expand to a FullRange + let ix = { + hi = self.last_span.hi; + let range = ExprStruct(ident_to_path(mk_sp(lo, hi), + token::special_idents::FullRange), + vec![], + None); + self.mk_expr(bracket_pos, hi, range) + }; + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index) } else { - MutImmutable - }; - match self.token { - // e.index(&FullRange) - token::CloseDelim(token::Bracket) => { - self.bump(); - hi = self.span.hi; - let slice = self.mk_slice(e, None, None, mutbl); - e = self.mk_expr(lo, hi, slice) - } - // e.index(&(0..e)) - token::DotDot => { - self.bump(); - match self.token { - // e.index(&(..)) - token::CloseDelim(token::Bracket) => { - self.bump(); - hi = self.span.hi; - let slice = self.mk_slice(e, None, None, mutbl); - e = self.mk_expr(lo, hi, slice); - - self.span_err(e.span, "incorrect slicing expression: `[..]`"); - self.span_note(e.span, - "use `expr.index(&FullRange)` to construct a slice of the whole of expr"); - } - // e.index(&(0..e)) - _ => { - hi = self.span.hi; - let e2 = self.parse_expr(); - self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket)); - let slice = self.mk_slice(e, None, Some(e2), mutbl); - e = self.mk_expr(lo, hi, slice) - } - } - } - // e[e] | e.index(&(e..)) | e.index(&(e..e)) - _ => { - let ix = self.parse_expr_res(RESTRICTION_NO_DOTS); - match self.token { - // e.index(&(e..)) | e.index(&(e..e)) - token::DotDot => { - self.bump(); - let e2 = match self.token { - // e.index(&(e..)) - token::CloseDelim(token::Bracket) => { - self.bump(); - None - } - // e.index(&(e..e)) - _ => { - let e2 = self.parse_expr_res(RESTRICTION_NO_DOTS); - self.commit_expr_expecting(&*e2, - token::CloseDelim(token::Bracket)); - Some(e2) - } - }; - hi = self.span.hi; - let slice = self.mk_slice(e, Some(ix), e2, mutbl); - e = self.mk_expr(lo, hi, slice) - } - // e[e] - _ => { - if mutbl == ast::MutMutable { - self.span_err(e.span, - "`mut` keyword is invalid in index expressions"); - } - hi = self.span.hi; - self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)); - let index = self.mk_index(e, ix); - e = self.mk_expr(lo, hi, index) - } - } - } + let ix = self.parse_expr(); + hi = self.span.hi; + self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)); + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index) } } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index ca683a56472..ada463a40cb 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -515,66 +515,66 @@ declare_special_idents_and_keywords! { (9, unnamed_field, ""); (10, type_self, "Self"); (11, prelude_import, "prelude_import"); + (12, FullRange, "FullRange"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: - (12, As, "as"); - (13, Break, "break"); - (14, Crate, "crate"); - (15, Else, "else"); - (16, Enum, "enum"); - (17, Extern, "extern"); - (18, False, "false"); - (19, Fn, "fn"); - (20, For, "for"); - (21, If, "if"); - (22, Impl, "impl"); - (23, In, "in"); - (24, Let, "let"); - (25, Loop, "loop"); - (26, Match, "match"); - (27, Mod, "mod"); - (28, Move, "move"); - (29, Mut, "mut"); - (30, Pub, "pub"); - (31, Ref, "ref"); - (32, Return, "return"); + (13, As, "as"); + (14, Break, "break"); + (15, Crate, "crate"); + (16, Else, "else"); + (17, Enum, "enum"); + (18, Extern, "extern"); + (19, False, "false"); + (20, Fn, "fn"); + (21, For, "for"); + (22, If, "if"); + (23, Impl, "impl"); + (24, In, "in"); + (25, Let, "let"); + (26, Loop, "loop"); + (27, Match, "match"); + (28, Mod, "mod"); + (29, Move, "move"); + (30, Mut, "mut"); + (31, Pub, "pub"); + (32, Ref, "ref"); + (33, Return, "return"); // Static and Self are also special idents (prefill de-dupes) (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); (super::SELF_KEYWORD_NAME_NUM, Self, "self"); - (33, Struct, "struct"); + (34, Struct, "struct"); (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); - (34, True, "true"); - (35, Trait, "trait"); - (36, Type, "type"); - (37, Unsafe, "unsafe"); - (38, Use, "use"); - (39, Virtual, "virtual"); - (40, While, "while"); - (41, Continue, "continue"); - (42, Proc, "proc"); - (43, Box, "box"); - (44, Const, "const"); - (45, Where, "where"); - + (35, True, "true"); + (36, Trait, "trait"); + (37, Type, "type"); + (38, Unsafe, "unsafe"); + (39, Use, "use"); + (40, Virtual, "virtual"); + (41, While, "while"); + (42, Continue, "continue"); + (43, Proc, "proc"); + (44, Box, "box"); + (45, Const, "const"); + (46, Where, "where"); 'reserved: - (46, Alignof, "alignof"); - (47, Be, "be"); - (48, Offsetof, "offsetof"); - (49, Priv, "priv"); - (50, Pure, "pure"); - (51, Sizeof, "sizeof"); - (52, Typeof, "typeof"); - (53, Unsized, "unsized"); - (54, Yield, "yield"); - (55, Do, "do"); - (56, Abstract, "abstract"); - (57, Final, "final"); - (58, Override, "override"); - (59, Macro, "macro"); + (47, Alignof, "alignof"); + (48, Be, "be"); + (49, Offsetof, "offsetof"); + (50, Priv, "priv"); + (51, Pure, "pure"); + (52, Sizeof, "sizeof"); + (53, Typeof, "typeof"); + (54, Unsized, "unsized"); + (55, Yield, "yield"); + (56, Do, "do"); + (57, Abstract, "abstract"); + (58, Final, "final"); + (59, Override, "override"); + (60, Macro, "macro"); } } -- cgit 1.4.1-3-g733a5 From 791f5456859845a4a1814eca45aa900fc62d4e44 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 5 Jan 2015 12:02:47 +1300 Subject: Pretty print empty structs properly --- src/libsyntax/print/pprust.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 9a38f6c8ac3..721769be7a4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1537,6 +1537,9 @@ impl<'a> State<'a> { ast::ExprStruct(ref path, ref fields, ref wth) => { try!(self.print_path(path, true)); + if fields.is_empty() && wth.is_none() { + return; + } try!(word(&mut self.s, "{")); try!(self.commasep_cmnt( Consistent, @@ -1560,7 +1563,7 @@ impl<'a> State<'a> { try!(self.print_expr(&**expr)); try!(self.end()); } - _ => try!(word(&mut self.s, ",")) + _ => try!(word(&mut self.s, ",")), } try!(word(&mut self.s, "}")); } -- cgit 1.4.1-3-g733a5 From 0c7f7a5fb8919c6a382f9acd1e921c51f807f625 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Sun, 4 Jan 2015 17:43:24 +1300 Subject: fallout --- src/compiletest/runtest.rs | 15 ++- src/libcollections/ring_buf.rs | 2 +- src/libcollections/slice.rs | 15 ++- src/libcollections/str.rs | 14 +-- src/libcollections/string.rs | 26 +++--- src/libcollections/vec.rs | 49 +++++----- src/libcore/array.rs | 16 +++- src/libcore/fmt/mod.rs | 2 +- src/libcore/slice.rs | 104 ++++++++++----------- src/libcore/str/mod.rs | 15 +-- src/libcoretest/iter.rs | 35 ++++--- src/libcoretest/slice.rs | 16 ++-- src/libgetopts/lib.rs | 4 +- src/librand/distributions/mod.rs | 6 +- src/librand/distributions/range.rs | 2 +- src/librand/lib.rs | 8 +- src/libregex/test/matches.rs | 2 +- src/libregex/test/tests.rs | 2 +- src/librustc/lint/context.rs | 4 +- src/librustc/metadata/creader.rs | 8 +- src/librustc/metadata/encoder.rs | 4 +- src/librustc/metadata/loader.rs | 3 +- src/librustc/middle/cfg/graphviz.rs | 4 +- src/librustc/middle/check_const.rs | 1 + src/librustc/middle/expr_use_visitor.rs | 2 +- src/librustc/middle/mem_categorization.rs | 4 +- src/librustc/middle/traits/mod.rs | 2 +- src/librustc/middle/traits/object_safety.rs | 2 +- src/librustc/middle/traits/project.rs | 2 +- src/librustc/middle/ty.rs | 6 +- src/librustc/session/config.rs | 4 +- src/librustc_back/target/mod.rs | 4 +- src/librustc_borrowck/borrowck/doc.rs | 8 +- src/librustc_borrowck/borrowck/mod.rs | 2 +- src/librustc_resolve/lib.rs | 4 +- src/librustc_trans/back/link.rs | 6 +- src/librustc_trans/back/lto.rs | 2 +- src/librustc_trans/back/write.rs | 4 +- src/librustc_trans/save/mod.rs | 11 ++- src/librustc_trans/save/recorder.rs | 2 +- src/librustc_trans/trans/_match.rs | 4 +- src/librustc_trans/trans/base.rs | 8 +- src/librustc_trans/trans/debuginfo.rs | 2 +- src/librustc_trans/trans/expr.rs | 11 ++- src/librustc_trans/trans/foreign.rs | 4 +- src/librustc_typeck/astconv.rs | 11 ++- src/librustc_typeck/check/callee.rs | 2 +- src/librustc_typeck/check/method/confirm.rs | 4 +- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/collect.rs | 2 +- src/librustdoc/html/format.rs | 6 +- src/librustdoc/html/render.rs | 14 +-- src/libserialize/json.rs | 57 +++++++---- src/libserialize/json_stage0.rs | 28 +++--- src/libserialize/serialize_stage0.rs | 3 +- src/libstd/io/buffered.rs | 36 ++++--- src/libstd/io/mem.rs | 8 +- src/libstd/io/process.rs | 8 +- src/libstd/path/mod.rs | 2 +- src/libstd/path/windows.rs | 10 +- src/libstd/prelude/v1.rs | 3 +- src/libstd/sys/windows/backtrace.rs | 3 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/attr.rs | 2 +- src/libsyntax/ext/deriving/bounds.rs | 5 +- src/libsyntax/ext/tt/macro_parser.rs | 2 +- src/libsyntax/feature_gate.rs | 7 +- src/libsyntax/parse/mod.rs | 6 +- src/libsyntax/parse/parser.rs | 38 +++++--- src/libsyntax/parse/token.rs | 5 +- src/libsyntax/print/pprust.rs | 53 ++++++----- src/test/bench/shootout-fannkuch-redux.rs | 2 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 4 +- src/test/compile-fail/borrowck-loan-vec-content.rs | 4 +- src/test/compile-fail/indexing-requires-a-uint.rs | 3 +- src/test/compile-fail/integral-indexing.rs | 32 ++++--- src/test/compile-fail/issue-16709.rs | 25 ----- src/test/compile-fail/slice-2.rs | 8 +- src/test/compile-fail/slice-mut-2.rs | 2 +- src/test/compile-fail/slice-mut.rs | 2 +- src/test/compile-fail/str-idx.rs | 3 +- src/test/run-pass/issue-17503.rs | 6 +- src/test/run-pass/issue-3888-2.rs | 2 +- src/test/run-pass/issue-4464.rs | 2 +- src/test/run-pass/issue-8898.rs | 2 +- src/test/run-pass/slice-panic-1.rs | 4 +- src/test/run-pass/slice-panic-2.rs | 4 +- src/test/run-pass/slice.rs | 44 ++++++--- 89 files changed, 498 insertions(+), 423 deletions(-) delete mode 100644 src/test/compile-fail/issue-16709.rs (limited to 'src/libsyntax') diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 684315de004..afcdcf6439c 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -539,18 +539,17 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { script_str.push_str("set print pretty off\n"); // Add the pretty printer directory to GDB's source-file search path - script_str.push_str(format!("directory {}\n", rust_pp_module_abs_path)[]); + script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[]); // Load the target executable - script_str.push_str(format!("file {}\n", - exe_file.as_str().unwrap().replace("\\", "\\\\")) - .as_slice()); + script_str.push_str(&format!("file {}\n", + exe_file.as_str().unwrap().replace("\\", "\\\\"))[]); // Add line breakpoints for line in breakpoint_lines.iter() { - script_str.push_str(format!("break '{}':{}\n", - testfile.filename_display(), - *line)[]); + script_str.push_str(&format!("break '{}':{}\n", + testfile.filename_display(), + *line)[]); } script_str.push_str(cmds.as_slice()); @@ -676,7 +675,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) .unwrap() .to_string(); - script_str.push_str(format!("command script import {}\n", rust_pp_module_abs_path.index(&FullRange))[]); + script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[])[]); script_str.push_str("type summary add --no-value "); script_str.push_str("--python-function lldb_rust_formatters.print_val "); script_str.push_str("-x \".*\" --category Rust\n"); diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index eff25b6d385..98e9d6c16b8 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -525,7 +525,7 @@ impl RingBuf { /// *num = *num - 2; /// } /// let b: &[_] = &[&mut 3, &mut 1, &mut 2]; - /// assert_eq!(buf.iter_mut().collect::>()[], b); + /// assert_eq!(&buf.iter_mut().collect::>()[], b); /// ``` #[stable] pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index ca1fed0f78f..e57574fdbce 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -1393,15 +1393,20 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order #[cfg(test)] mod tests { - use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal}; - use prelude::{SliceExt, Iterator, IteratorExt}; - use prelude::AsSlice; - use prelude::{RandomAccessIterator, Ord, SliceConcatExt}; + use core::cmp::Ordering::{Greater, Less, Equal}; + use core::prelude::{Some, None, range, Clone}; + use core::prelude::{Iterator, IteratorExt}; + use core::prelude::{AsSlice}; + use core::prelude::{Ord, FullRange}; use core::default::Default; use core::mem; + use core::ops::Index; + use std::iter::RandomAccessIterator; use std::rand::{Rng, thread_rng}; use std::rc::Rc; - use super::ElementSwaps; + use string::ToString; + use vec::Vec; + use super::{ElementSwaps, SliceConcatExt, SliceExt}; fn square(n: uint) -> uint { n * n } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index cb4264ec34f..aacb6d90d6f 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -60,7 +60,7 @@ use core::char::CharExt; use core::clone::Clone; use core::iter::AdditiveIterator; use core::iter::{range, Iterator, IteratorExt}; -use core::ops::{self, llRange, Index}; +use core::ops::{FullRange, Index}; use core::option::Option::{self, Some, None}; use core::slice::AsSlice; use core::str as core_str; @@ -408,7 +408,7 @@ Section: Trait implementations /// Any string that can be represented as a slice. #[stable] -pub trait StrExt: Index { +pub trait StrExt: Index { /// Escapes each char in `s` with `char::escape_default`. #[unstable = "return type may change to be an iterator"] fn escape_default(&self) -> String { @@ -1339,12 +1339,6 @@ pub trait StrExt: Index { fn trim_left(&self) -> &str { UnicodeStr::trim_left(self.index(&FullRange)) } - - /// Returns a string with trailing whitespace removed. - #[stable] - fn trim_right(&self) -> &str { - UnicodeStr::trim_right(self.index(&FullRange)) - } } #[stable] @@ -2133,7 +2127,7 @@ mod tests { let mut bytes = [0u8; 4]; for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { let len = c.encode_utf8(&mut bytes).unwrap_or(0); - let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap(); + let s = ::core::str::from_utf8(&bytes[..len]).unwrap(); if Some(c) != s.chars().next() { panic!("character {:x}={} does not decode correctly", c as u32, c); } @@ -2145,7 +2139,7 @@ mod tests { let mut bytes = [0u8; 4]; for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { let len = c.encode_utf8(&mut bytes).unwrap_or(0); - let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap(); + let s = ::core::str::from_utf8(&bytes[..len]).unwrap(); if Some(c) != s.chars().rev().next() { panic!("character {:x}={} does not decode correctly", c as u32, c); } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 69ff513a85b..20bc08416dc 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -22,7 +22,7 @@ use core::fmt; use core::hash; use core::iter::FromIterator; use core::mem; -use core::ops::{self, Deref, Add}; +use core::ops::{self, Deref, Add, Index}; use core::ptr; use core::raw::Slice as RawSlice; use unicode::str as unicode_str; @@ -818,28 +818,29 @@ impl<'a> Add<&'a str> for String { } } -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::Range) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::RangeTo) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index for String { +impl ops::Index for String { + type Output = str; #[inline] fn index(&self, _index: &ops::FullRange) -> &str { unsafe { mem::transmute(self.vec.as_slice()) } @@ -949,6 +950,7 @@ mod tests { use str::Utf8Error; use core::iter::repeat; use super::{as_string, CowString}; + use core::ops::FullRange; #[test] fn test_as_string() { @@ -1230,10 +1232,10 @@ mod tests { #[test] fn test_slicing() { let s = "foobar".to_string(); - assert_eq!("foobar", s.index(&FullRange)); - assert_eq!("foo", s.index(&(0..3))); - assert_eq!("bar", s.index(&(3..))); - assert_eq!("oob", s.index(&(1..4))); + assert_eq!("foobar", &s[]); + assert_eq!("foo", &s[..3]); + assert_eq!("bar", &s[3..]); + assert_eq!("oob", &s[1..4]); } #[test] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 3f667698bae..1cfbbdf6cb8 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1209,62 +1209,66 @@ impl IndexMut for Vec { } } -impl ops::Index, [T]> for Vec { + +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index, [T]> for Vec { +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index, [T]> for Vec { +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index for Vec { +impl ops::Index for Vec { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { self.as_slice() } } -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut for Vec { +impl ops::IndexMut for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { self.as_mut_slice() } } + #[stable] impl ops::Deref for Vec { type Target = [T]; @@ -1795,6 +1799,7 @@ mod tests { use prelude::*; use core::mem::size_of; use core::iter::repeat; + use core::ops::FullRange; use test::Bencher; use super::as_vec; @@ -1932,7 +1937,7 @@ mod tests { let (left, right) = values.split_at_mut(2); { let left: &[_] = left; - assert!(left[0..left.len()] == [1, 2][]); + assert!(&left[..left.len()] == &[1, 2][]); } for p in left.iter_mut() { *p += 1; @@ -1940,7 +1945,7 @@ mod tests { { let right: &[_] = right; - assert!(right[0..right.len()] == [3, 4, 5][]); + assert!(&right[..right.len()] == &[3, 4, 5][]); } for p in right.iter_mut() { *p += 2; @@ -2111,35 +2116,35 @@ mod tests { #[should_fail] fn test_slice_out_of_bounds_1() { let x: Vec = vec![1, 2, 3, 4, 5]; - x[-1..]; + &x[(-1)..]; } #[test] #[should_fail] fn test_slice_out_of_bounds_2() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(0..6)); + &x[..6]; } #[test] #[should_fail] fn test_slice_out_of_bounds_3() { let x: Vec = vec![1, 2, 3, 4, 5]; - x[-1..4]; + &x[(-1)..4]; } #[test] #[should_fail] fn test_slice_out_of_bounds_4() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(1..6)); + &x[1..6]; } #[test] #[should_fail] fn test_slice_out_of_bounds_5() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(3..2)); + &x[3..2]; } #[test] @@ -2385,7 +2390,7 @@ mod tests { b.bytes = src_len as u64; b.iter(|| { - let dst = src.clone().as_slice().to_vec(); + let dst = src.clone()[].to_vec(); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 37a2177b38d..a4b32f2b6a2 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -57,9 +57,13 @@ macro_rules! array_impls { Rhs: Deref, { #[inline(always)] - fn eq(&self, other: &Rhs) -> bool { PartialEq::eq(self.index(&FullRange), &**other) } + fn eq(&self, other: &Rhs) -> bool { + PartialEq::eq(self.index(&FullRange), &**other) + } #[inline(always)] - fn ne(&self, other: &Rhs) -> bool { PartialEq::ne(self.index(&FullRange), &**other) } + fn ne(&self, other: &Rhs) -> bool { + PartialEq::ne(self.index(&FullRange), &**other) + } } #[stable] @@ -68,9 +72,13 @@ macro_rules! array_impls { Lhs: Deref { #[inline(always)] - fn eq(&self, other: &[B; $N]) -> bool { PartialEq::eq(&**self, other.index(&FullRange)) } + fn eq(&self, other: &[B; $N]) -> bool { + PartialEq::eq(&**self, other.index(&FullRange)) + } #[inline(always)] - fn ne(&self, other: &[B; $N]) -> bool { PartialEq::ne(&**self, other.index(&FullRange)) } + fn ne(&self, other: &[B; $N]) -> bool { + PartialEq::ne(&**self, other.index(&FullRange)) + } } #[stable] diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 19c6b29417f..76c2671cfd0 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -521,7 +521,7 @@ impl<'a> Formatter<'a> { let mut fill = [0u8; 4]; let len = self.fill.encode_utf8(&mut fill).unwrap_or(0); - let fill = unsafe { str::from_utf8_unchecked(fill[..len]) }; + let fill = unsafe { str::from_utf8_unchecked(fill.index(&(..len))) }; for _ in range(0, pre_pad) { try!(self.buf.write_str(fill)); diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index a0bb0205c42..8ab927f701a 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -551,9 +551,10 @@ impl ops::IndexMut for [T] { } } -impl ops::Index, [T]> for [T] { +impl ops::Index> for [T] { + type Output = [T]; #[inline] - fn index(&self, &index: &ops::Range) -> &[T] { + fn index(&self, index: &ops::Range) -> &[T] { assert!(index.start <= index.end); assert!(index.end <= self.len()); unsafe { @@ -564,31 +565,32 @@ impl ops::Index, [T]> for [T] { } } } - -impl ops::Index, [T]> for [T] { +impl ops::Index> for [T] { + type Output = [T]; #[inline] - fn index(&self, &index: &ops::RangeTo) -> &[T] { + fn index(&self, index: &ops::RangeTo) -> &[T] { self.index(&ops::Range{ start: 0, end: index.end }) } } - -impl ops::Index, [T]> for [T] { +impl ops::Index> for [T] { + type Output = [T]; #[inline] - fn index(&self, &index: &ops::RangeFrom) -> &[T] { + fn index(&self, index: &ops::RangeFrom) -> &[T] { self.index(&ops::Range{ start: index.start, end: self.len() }) } } - -impl ops::Index for [T] { +impl ops::Index for [T] { + type Output = [T]; #[inline] - fn index(&self, &index: &ops::FullRange) -> &[T] { + fn index(&self, _index: &ops::FullRange) -> &[T] { self } } -impl ops::IndexMut, [T]> for [T] { +impl ops::IndexMut> for [T] { + type Output = [T]; #[inline] - fn index_mut(&mut self, &index: &ops::Range) -> &mut [T] { + fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { assert!(index.start <= index.end); assert!(index.end <= self.len()); unsafe { @@ -599,43 +601,29 @@ impl ops::IndexMut, [T]> for [T] { } } } - -impl ops::IndexMut, [T]> for [T] { +impl ops::IndexMut> for [T] { + type Output = [T]; #[inline] - fn index_mut(&mut self, &index: &ops::RangeTo) -> &mut [T] { + fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.index_mut(&ops::Range{ start: 0, end: index.end }) } } - -impl ops::IndexMut, [T]> for [T] { +impl ops::IndexMut> for [T] { + type Output = [T]; #[inline] - fn index_mut(&mut self, &index: &ops::RangeFrom) -> &mut [T] { + fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { let len = self.len(); self.index_mut(&ops::Range{ start: index.start, end: len }) } } - -impl ops::IndexMut for [T] { +impl ops::IndexMut for [T] { + type Output = [T]; #[inline] - fn index_mut(&mut self, &index: &ops::FullRange) -> &mut [T] { + fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { self } } -impl ops::Index, [T]> for [T] { - #[inline] - fn index(&self, index: &ops::Range) -> &[T] { - assert!(index.start <= index.end); - assert!(index.end <= self.len()); - unsafe { - transmute(RawSlice { - data: self.as_ptr().offset(index.start as int), - len: index.end - index.start - }) - } - } -} - //////////////////////////////////////////////////////////////////////////////// // Common traits @@ -767,7 +755,8 @@ pub struct Iter<'a, T: 'a> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.as_slice().index(index) @@ -775,7 +764,8 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.as_slice().index(index) @@ -783,7 +773,8 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.as_slice().index(index) @@ -791,14 +782,14 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index for Iter<'a, T> { +impl<'a, T> ops::Index for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { self.as_slice() } } - impl<'a, T> Iter<'a, T> { /// View the underlying data as a subslice of the original data. /// @@ -855,32 +846,34 @@ pub struct IterMut<'a, T: 'a> { marker: marker::ContravariantLifetime<'a>, } + #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index for IterMut<'a, T> { +impl<'a, T> ops::Index for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { make_slice!(T -> &[T]: self.ptr, self.end) @@ -888,31 +881,32 @@ impl<'a, T> ops::Index for IterMut<'a, T> { } #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut for IterMut<'a, T> { +impl<'a, T> ops::IndexMut for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { make_slice!(T -> &mut [T]: self.ptr, self.end) diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index c4e97fe3b7f..bc995a2af72 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1119,28 +1119,29 @@ mod traits { } } - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::Range) -> &str { self.slice(index.start, index.end) } } - - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::RangeTo) -> &str { self.slice_to(index.end) } } - - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { self.slice_from(index.start) } } - - impl ops::Index for str { + impl ops::Index for str { + type Output = str; #[inline] fn index(&self, _index: &ops::FullRange) -> &str { self diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs index 19bfbf3df44..61266a92649 100644 --- a/src/libcoretest/iter.rs +++ b/src/libcoretest/iter.rs @@ -14,7 +14,6 @@ use core::iter::MinMaxResult::*; use core::num::SignedInt; use core::uint; use core::cmp; -use core::ops::Slice; use test::Bencher; @@ -230,7 +229,7 @@ fn test_inspect() { .collect::>(); assert_eq!(n, xs.len()); - assert_eq!(xs.index(&FullRange), ys.index(&FullRange)); + assert_eq!(&xs[], &ys[]); } #[test] @@ -281,47 +280,47 @@ fn test_iterator_nth() { fn test_iterator_last() { let v: &[_] = &[0i, 1, 2, 3, 4]; assert_eq!(v.iter().last().unwrap(), &4); - assert_eq!(v.index(&(0..1)).iter().last().unwrap(), &0); + assert_eq!(v[..1].iter().last().unwrap(), &0); } #[test] fn test_iterator_len() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().count(), 4); - assert_eq!(v.index(&(0..10)).iter().count(), 10); - assert_eq!(v.index(&(0..0)).iter().count(), 0); + assert_eq!(v[..4].iter().count(), 4); + assert_eq!(v[..10].iter().count(), 10); + assert_eq!(v[0..0].iter().count(), 0); } #[test] fn test_iterator_sum() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).sum(), 6); + assert_eq!(v[..4].iter().map(|&x| x).sum(), 6); assert_eq!(v.iter().map(|&x| x).sum(), 55); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).sum(), 0); + assert_eq!(v[0..0].iter().map(|&x| x).sum(), 0); } #[test] fn test_iterator_product() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).product(), 0); - assert_eq!(v.index(&(1..5)).iter().map(|&x| x).product(), 24); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).product(), 1); + assert_eq!(v[0..4].iter().map(|&x| x).product(), 0); + assert_eq!(v[1..5].iter().map(|&x| x).product(), 24); + assert_eq!(v[0..0].iter().map(|&x| x).product(), 1); } #[test] fn test_iterator_max() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).max(), Some(3)); + assert_eq!(v[0..4].iter().map(|&x| x).max(), Some(3)); assert_eq!(v.iter().map(|&x| x).max(), Some(10)); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).max(), None); + assert_eq!(v[0..0].iter().map(|&x| x).max(), None); } #[test] fn test_iterator_min() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).min(), Some(0)); + assert_eq!(v[0..4].iter().map(|&x| x).min(), Some(0)); assert_eq!(v.iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).min(), None); + assert_eq!(v[0..0].iter().map(|&x| x).min(), None); } #[test] @@ -374,7 +373,7 @@ fn test_all() { assert!(v.iter().all(|&x| x < 10)); assert!(!v.iter().all(|&x| x % 2 == 0)); assert!(!v.iter().all(|&x| x > 100)); - assert!(v.slice_or_fail(&0, &0).iter().all(|_| panic!())); + assert!(v[0..0].iter().all(|_| panic!())); } #[test] @@ -383,7 +382,7 @@ fn test_any() { assert!(v.iter().any(|&x| x < 10)); assert!(v.iter().any(|&x| x % 2 == 0)); assert!(!v.iter().any(|&x| x > 100)); - assert!(!v.slice_or_fail(&0, &0).iter().any(|_| panic!())); + assert!(!v[0..0].iter().any(|_| panic!())); } #[test] @@ -586,7 +585,7 @@ fn check_randacc_iter(a: T, len: uint) where fn test_double_ended_flat_map() { let u = [0u,1]; let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v[*x..v.len()].iter()); + let mut it = u.iter().flat_map(|x| v[(*x)..v.len()].iter()); assert_eq!(it.next_back().unwrap(), &8); assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); diff --git a/src/libcoretest/slice.rs b/src/libcoretest/slice.rs index d20def89abb..b714b6a4e41 100644 --- a/src/libcoretest/slice.rs +++ b/src/libcoretest/slice.rs @@ -43,35 +43,35 @@ fn iterator_to_slice() { { let mut iter = data.iter(); - assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); + assert_eq!(&iter[], &other_data[]); iter.next(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); + assert_eq!(&iter[], &other_data[1..]); iter.next_back(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); + assert_eq!(&iter[], &other_data[1..2]); let s = iter.as_slice(); iter.next(); - assert_eq!(s, other_data.index(&(1..2))); + assert_eq!(s, &other_data[1..2]); } { let mut iter = data.iter_mut(); assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); // mutability: - assert!(iter[mut] == other_data); + assert!(&mut iter[] == other_data); iter.next(); assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); - assert!(iter[mut] == other_data[mut 1..]); + assert!(&mut iter[] == &mut other_data[1..]); iter.next_back(); assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); - assert!(iter[mut] == other_data[mut 1..2]); + assert!(&mut iter[] == &mut other_data[1..2]); let s = iter.into_slice(); - assert!(s == other_data[mut 1..2]); + assert!(s == &mut other_data[1..2]); } }} } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index a9e4e8d2514..dd9e5e5a038 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -1413,7 +1413,7 @@ mod tests { assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_single.opts_present(&["encrypt".to_string()])); assert!(!matches_single.opts_present(&["thing".to_string()])); - assert!(!matches_single.opts_present(&.index(&FullRange))); + assert!(!matches_single.opts_present(&[])); assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), @@ -1434,7 +1434,7 @@ mod tests { assert!(matches_both.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_both.opts_present(&["f".to_string()])); assert!(!matches_both.opts_present(&["thing".to_string()])); - assert!(!matches_both.opts_present(&.index(&FullRange))); + assert!(!matches_both.opts_present(&[])); assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 6fe995d1c58..2fdba8a6c4f 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -24,7 +24,7 @@ use core::num::{Float, Int}; use {Rng, Rand}; -pub use self::range::Range as RandRange; +pub use self::range::Range; pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT}; pub use self::normal::{Normal, LogNormal}; pub use self::exponential::Exp; @@ -104,7 +104,7 @@ pub struct Weighted { /// ``` pub struct WeightedChoice<'a, T:'a> { items: &'a mut [Weighted], - weight_range: RandRange + weight_range: Range } impl<'a, T: Clone> WeightedChoice<'a, T> { @@ -138,7 +138,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> { items: items, // we're likely to be generating numbers in this range // relatively often, so might as well cache it - weight_range: RandRange::new(0, running_total) + weight_range: Range::new(0, running_total) } } } diff --git a/src/librand/distributions/range.rs b/src/librand/distributions/range.rs index 2369c094b9f..1002d9693ba 100644 --- a/src/librand/distributions/range.rs +++ b/src/librand/distributions/range.rs @@ -166,7 +166,7 @@ mod tests { use std::num::Int; use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; - use super::Range; + use super::Range as Range; #[should_fail] #[test] diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 51ae3114cad..aeecd69e205 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -58,7 +58,7 @@ use core::prelude::*; pub use isaac::{IsaacRng, Isaac64Rng}; pub use chacha::ChaChaRng; -use distributions::{RandRange, IndependentSample}; +use distributions::{Range, IndependentSample}; use distributions::range::SampleRange; #[cfg(test)] @@ -247,7 +247,7 @@ pub trait Rng : Sized { /// ``` fn gen_range(&mut self, low: T, high: T) -> T { assert!(low < high, "Rng.gen_range called with low >= high"); - RandRange::new(low, high).ind_sample(self) + Range::new(low, high).ind_sample(self) } /// Return a bool with a 1 in n chance of true @@ -290,8 +290,8 @@ pub trait Rng : Sized { /// let choices = [1i, 2, 4, 8, 16, 32]; /// let mut rng = thread_rng(); /// println!("{}", rng.choose(&choices)); - /// # // replace with slicing syntax when it's stable! - /// assert_eq!(rng.choose(choices.index(&(0..0))), None); + /// # // uncomment when slicing syntax is stable + /// //assert_eq!(rng.choose(choices.index(&(0..0))), None); /// ``` fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { if values.is_empty() { diff --git a/src/libregex/test/matches.rs b/src/libregex/test/matches.rs index b422ac668ca..7508f4c50a2 100644 --- a/src/libregex/test/matches.rs +++ b/src/libregex/test/matches.rs @@ -121,7 +121,7 @@ mat!{match_basic_110, r"a[b-d]", r"aac", Some((1, 3))} mat!{match_basic_111, r"a[-b]", r"a-", Some((0, 2))} mat!{match_basic_112, r"a[b-]", r"a-", Some((0, 2))} mat!{match_basic_113, r"a]", r"a]", Some((0, 2))} -mat!{match_basic_114, r"a.index(&FullRange)]b", r"a]b", Some((0, 3))} +mat!{match_basic_114, r"a[]]b", r"a]b", Some((0, 3))} mat!{match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))} mat!{match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))} mat!{match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))} diff --git a/src/libregex/test/tests.rs b/src/libregex/test/tests.rs index d087814b7f4..4f38370d7a1 100644 --- a/src/libregex/test/tests.rs +++ b/src/libregex/test/tests.rs @@ -159,7 +159,7 @@ macro_rules! mat { // actual capture groups to match test set. let mut sgot = got.as_slice(); if sgot.len() > expected.len() { - sgot = sgot[0..expected.len()] + sgot = &sgot[..expected.len()] } if expected != sgot { panic!("For RE '{}' against '{}', expected '{}' but got '{}'", diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index fa451e03ab9..51998bdbcf2 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -499,7 +499,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { None => { self.span_lint(builtin::UNKNOWN_LINTS, span, format!("unknown `{}` attribute: `{}`", - level.as_str(), lint_name).index(&FullRange)); + level.as_str(), lint_name).as_slice()); continue; } } @@ -791,7 +791,7 @@ pub fn check_crate(tcx: &ty::ctxt, for &(lint, span, ref msg) in v.iter() { tcx.sess.span_bug(span, format!("unprocessed lint {} at {}: {}", - lint.as_str(), tcx.map.node_to_string(*id), *msg).index(&FullRange)) + lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice()) } } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 08d19dcb607..8961c3e728c 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -209,7 +209,7 @@ impl<'a> CrateReader<'a> { let name = match *path_opt { Some((ref path_str, _)) => { let name = path_str.get().to_string(); - validate_crate_name(Some(self.sess), name[], + validate_crate_name(Some(self.sess), name.index(&FullRange), Some(i.span)); name } @@ -276,7 +276,7 @@ impl<'a> CrateReader<'a> { } else { self.sess.span_err(m.span, format!("unknown kind: `{}`", - k)[]); + k).index(&FullRange)); cstore::NativeUnknown } } @@ -330,7 +330,7 @@ impl<'a> CrateReader<'a> { match self.sess.opts.externs.get(name) { Some(locs) => { let found = locs.iter().any(|l| { - let l = fs::realpath(&Path::new(l[])).ok(); + let l = fs::realpath(&Path::new(l.index(&FullRange))).ok(); l == source.dylib || l == source.rlib }); if found { @@ -409,7 +409,7 @@ impl<'a> CrateReader<'a> { crate_name: name, hash: hash.map(|a| &*a), filesearch: self.sess.target_filesearch(kind), - triple: self.sess.opts.target_triple[], + triple: self.sess.opts.target_triple.index(&FullRange), root: root, rejected_via_hash: vec!(), rejected_via_triple: vec!(), diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 592fbe4d64e..b19501229aa 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1826,10 +1826,10 @@ fn encode_macro_defs(rbml_w: &mut Encoder, rbml_w.start_tag(tag_macro_def); encode_name(rbml_w, def.ident.name); - encode_attributes(rbml_w, def.attrs[]); + encode_attributes(rbml_w, def.attrs.index(&FullRange)); rbml_w.start_tag(tag_macro_def_body); - rbml_w.wr_str(pprust::tts_to_string(def.body[])[]); + rbml_w.wr_str(pprust::tts_to_string(def.body.index(&FullRange)).index(&FullRange)); rbml_w.end_tag(); rbml_w.end_tag(); diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 6f75770bcb8..4106d216bf9 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -624,7 +624,8 @@ impl<'a> Context<'a> { return true } else { let (ref prefix, ref suffix) = dylibname; - if file.starts_with(prefix.index(&FullRange)) && file.ends_with(suffix.index(&FullRange)) { + if file.starts_with(prefix.index(&FullRange)) && + file.ends_with(suffix.index(&FullRange)) { return true } } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 34dae07642d..8b9a0d89b38 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -85,7 +85,9 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); - label.push_str(format!("exiting scope_{} {}", i, s.index(&FullRange)).index(&FullRange)); + label.push_str(format!("exiting scope_{} {}", + i, + s.index(&FullRange)).index(&FullRange)); } dot::LabelText::EscStr(label.into_cow()) } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index d8d7c5afb10..ac53bdbefcf 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -165,6 +165,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) { ast::ExprParen(..) | ast::ExprField(..) | ast::ExprTupField(..) | + ast::ExprIndex(..) | ast::ExprTup(..) | ast::ExprRepeat(..) | ast::ExprStruct(..) => {} diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index f71d020a1b8..1f89121488e 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -1158,7 +1158,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { let msg = format!("Pattern has unexpected type: {} and type {}", def, cmt_pat.ty.repr(tcx)); - tcx.sess.span_bug(pat.span, msg[]) + tcx.sess.span_bug(pat.span, msg.as_slice()) } } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 99c2fad0e50..81d4d66a88e 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -495,7 +495,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { ret_ty), 1, true) } None => { - self.cat_index(expr, self.cat_expr(&**base)) + self.cat_index(expr, try!(self.cat_expr(&**base))) } } } @@ -1497,7 +1497,7 @@ impl<'tcx> Repr<'tcx> for InteriorKind { token::get_name(fld).get().to_string() } InteriorField(PositionalField(i)) => format!("#{}", i), - InteriorElement(_) => ".index(&FullRange)".to_string(), + InteriorElement(_) => "[]".to_string(), } } } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index ce926fd8d10..3638d98ae88 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -378,7 +378,7 @@ pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, span, format!("overflow evaluating whether `{}` is `{}`", ty.user_string(infcx.tcx), - bound.user_string(infcx.tcx))[]); + bound.user_string(infcx.tcx)).as_slice()); suggest_new_overflow_limit(infcx.tcx, span); false } diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index 8880cb7ce73..17792ef78ab 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -178,7 +178,7 @@ fn object_safety_violations_for_method<'tcx>(tcx: &ty::ctxt<'tcx>, // The `Self` type is erased, so it should not appear in list of // arguments or return type apart from the receiver. let ref sig = method.fty.sig; - for &input_ty in sig.0.inputs[1..].iter() { + for &input_ty in sig.0.inputs.index(&(1..)).iter() { if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) { return Some(MethodViolationCode::ReferencesSelf); } diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index 65f7ad296db..67a8508e60d 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -490,7 +490,7 @@ fn assemble_candidates_from_object_type<'cx,'tcx>( selcx.tcx().sess.span_bug( obligation.cause.span, format!("assemble_candidates_from_object_type called with non-object: {}", - object_ty.repr(selcx.tcx()))[]); + object_ty.repr(selcx.tcx())).as_slice()); } }; let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty); diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index d954495055d..e24fe46b34d 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -3654,7 +3654,8 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // inference by-products or unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[]) + cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + ty).as_slice()) } ty_tup(ref ts) => { @@ -3747,7 +3748,8 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[]) + cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + ty).as_slice()) } _ => Representable, } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 88a71e53b60..d3f8c8284e0 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -639,7 +639,7 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config { let target = match Target::search(opts.target_triple.index(&FullRange)) { Ok(t) => t, Err(e) => { - sp.handler().fatal((format!("Error loading target specification: {}", e)).index(&FullRange)); + sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice()); } }; @@ -1027,7 +1027,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { s => { early_error(format!("unknown library kind `{}`, expected \ one of dylib, framework, or static", - s)[]); + s).as_slice()); } }; return (name.to_string(), kind) diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 5f5ad7efdf1..02bb6aa4b0d 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -247,7 +247,9 @@ impl Target { } ); ($key_name:ident, bool) => ( { let name = (stringify!($key_name)).replace("_", "-"); - obj.find(name.index(&FullRange)).map(|o| o.as_boolean().map(|s| base.options.$key_name = s)); + obj.find(name.index(&FullRange)) + .map(|o| o.as_boolean() + .map(|s| base.options.$key_name = s)); } ); ($key_name:ident, list) => ( { let name = (stringify!($key_name)).replace("_", "-"); diff --git a/src/librustc_borrowck/borrowck/doc.rs b/src/librustc_borrowck/borrowck/doc.rs index e309ba0a634..2100d5a9bc3 100644 --- a/src/librustc_borrowck/borrowck/doc.rs +++ b/src/librustc_borrowck/borrowck/doc.rs @@ -138,7 +138,7 @@ //! - `FREEZE` means that the `LV` cannot be borrowed immutably; //! //! Finally, it is never possible to move from an lvalue that appears in a -//! restriction. This implies that the "empty restriction" `(LV, .index(&FullRange))`, +//! restriction. This implies that the "empty restriction" `(LV, [])`, //! which contains an empty set of actions, still has a purpose---it //! prevents moves from `LV`. I chose not to make `MOVE` a fourth kind of //! action because that would imply that sometimes moves are permitted @@ -476,7 +476,7 @@ //! ```text //! &mut LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM|FREEZE) //! &LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM) -//! &const LV => RESTRICTIONS(LV, LT, .index(&FullRange)) +//! &const LV => RESTRICTIONS(LV, LT, []) //! ``` //! //! The reasoning here is that a mutable borrow must be the only writer, @@ -542,7 +542,7 @@ //! restricting `MUTATE` and `CLAIM` actions: //! //! ```text -//! RESTRICTIONS(*LV, LT, ACTIONS) = .index(&FullRange) // R-Deref-Imm-Borrowed +//! RESTRICTIONS(*LV, LT, ACTIONS) = [] // R-Deref-Imm-Borrowed //! TYPE(LV) = <' Ty //! LT <= LT' // (1) //! ACTIONS subset of [MUTATE, CLAIM] @@ -660,7 +660,7 @@ //! necessary to add any restrictions at all to the final result. //! //! ```text -//! RESTRICTIONS(*LV, LT, .index(&FullRange)) = .index(&FullRange) // R-Deref-Freeze-Borrowed +//! RESTRICTIONS(*LV, LT, []) = [] // R-Deref-Freeze-Borrowed //! TYPE(LV) = &const Ty //! ``` //! diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 36e1a486112..75dee496234 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -804,7 +804,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { mc::AliasableClosure(id) => { self.tcx.sess.span_err(span, format!("{} in a captured outer \ - variable in an `Fn` closure", prefix).index(&FullRange)); + variable in an `Fn` closure", prefix).as_slice()); span_help!(self.tcx.sess, self.tcx.map.span(id), "consider changing this closure to take self by mutable reference"); } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index d8c7a62e194..debbf2767ac 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -3763,13 +3763,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.resolve_error(path.span, format!("`{}` is not an enum variant, struct or const", token::get_ident( - path.segments.last().unwrap().identifier)).index(&FullRange)); + path.segments.last().unwrap().identifier)).as_slice()); } None => { self.resolve_error(path.span, format!("unresolved enum variant, struct or const `{}`", token::get_ident( - path.segments.last().unwrap().identifier)).index(&FullRange)); + path.segments.last().unwrap().identifier)).as_slice()); } } diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 388bc4a4d30..aff5f00e64e 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -608,7 +608,7 @@ fn link_rlib<'a>(sess: &'a Session, // extension to it. This is to work around a bug in LLDB that // would cause it to crash if the name of a file in an archive // was exactly 16 bytes. - let bc_filename = obj_filename.with_extension(format!("{}.bc", i).index(&FullRange)); + let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice()); let bc_deflated_filename = obj_filename.with_extension( format!("{}.bytecode.deflate", i).index(&FullRange)); @@ -1083,8 +1083,8 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { // -force_load is the OSX equivalent of --whole-archive, but it // involves passing the full path to the library to link. let lib = archive::find_library(l.index(&FullRange), - sess.target.target.options.staticlib_prefix.index(&FullRange), - sess.target.target.options.staticlib_suffix.index(&FullRange), + sess.target.target.options.staticlib_prefix.as_slice(), + sess.target.target.options.staticlib_suffix.as_slice(), search_path.index(&FullRange), &sess.diagnostic().handler); let mut v = b"-Wl,-force_load,".to_vec(); diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index 450b4176b7a..ecf2e9ed724 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -64,7 +64,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, debug!("reading {}", file); for i in iter::count(0u, 1) { let bc_encoded = time(sess.time_passes(), - format!("check for {}.{}.bytecode.deflate", name, i).index(&FullRange), + format!("check for {}.{}.bytecode.deflate", name, i).as_slice(), (), |_| { archive.read(format!("{}.{}.bytecode.deflate", diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index f27f7dc5719..56d7fb09662 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -381,8 +381,8 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo cgcx.handler.note(format!("optimization {} for {} at {}: {}", opt.kind.describe(), pass_name, - if loc.is_empty() { "[unknown]" } else { loc.index(&FullRange) }, - llvm::twine_to_string(opt.message)).index(&FullRange)); + if loc.is_empty() { "[unknown]" } else { loc.as_slice() }, + llvm::twine_to_string(opt.message)).as_slice()); } } diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index b27421ea426..4ac9f1c7c93 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -292,7 +292,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { Some(def_id) => { result.push_str(" as "); result.push_str( - ty::item_path_str(&self.analysis.ty_cx, def_id).index(&FullRange)); + ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice()); }, None => {} } @@ -636,7 +636,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { item.id); for field in struct_def.fields.iter() { - self.process_struct_field_def(field, qualname.index(&FullRange), variant.node.id); + self.process_struct_field_def(field, qualname.as_slice(), variant.node.id); self.visit_ty(&*field.node.ty); } } @@ -774,7 +774,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(span, - format!("def_map has no key for {} in visit_expr", id).index(&FullRange)); + format!("def_map has no key for {} in visit_expr", id).as_slice()); } let def = &(*def_map)[id]; let sub_span = self.span.span_for_last_ident(span); @@ -1065,7 +1065,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { value.index(&FullRange)); self.visit_ty(&**ty); - self.process_generic_params(ty_params, item.span, qualname.index(&FullRange), item.id); + self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id); }, ast::ItemMac(_) => (), _ => visit::walk_item(self, item), @@ -1418,7 +1418,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(p.span, - format!("def_map has no key for {} in visit_arm", id).index(&FullRange)); + format!("def_map has no key for {} in visit_arm", + id).index(&FullRange)); } let def = &(*def_map)[id]; match *def { diff --git a/src/librustc_trans/save/recorder.rs b/src/librustc_trans/save/recorder.rs index 5352fcc2fed..bb0fb387002 100644 --- a/src/librustc_trans/save/recorder.rs +++ b/src/librustc_trans/save/recorder.rs @@ -237,7 +237,7 @@ impl<'a> FmtStrs<'a> { if !needs_span { self.span.sess.span_bug(span, format!("Called record_with_span for '{}' \ - which does not require a span", label).index(&FullRange)); + which does not require a span", label).as_slice()); } let values_str = match self.make_values_str(label, fields, values, span) { diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index f55076e7484..438cfe0b6c7 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -1037,8 +1037,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, field_vals.len()) ); let mut vals = field_vals; - vals.push_all(vals_left.index(&FullRange)); - compile_submatch(bcx, pats.index(&FullRange), vals.index(&FullRange), chk, has_genuine_default); + vals.push_all(vals_left.as_slice()); + compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default); return; } _ => () diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index e69bfb57670..458c1fa923e 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -2239,7 +2239,7 @@ pub fn update_linkage(ccx: &CrateContext, if let Some(id) = id { let item = ccx.tcx().map.get(id); if let ast_map::NodeItem(i) = item { - if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.index(&FullRange), "linkage") { + if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.as_slice(), "linkage") { if let Some(linkage) = llvm_linkage_by_name(name.get()) { llvm::SetLinkage(llval, linkage); } else { @@ -2597,7 +2597,11 @@ pub fn register_fn_llvmty(ccx: &CrateContext, llfty: Type) -> ValueRef { debug!("register_fn_llvmty id={} sym={}", node_id, sym); - let llfn = decl_fn(ccx, sym.index(&FullRange), cc, llfty, ty::FnConverging(ty::mk_nil(ccx.tcx()))); + let llfn = decl_fn(ccx, + sym.index(&FullRange), + cc, + llfty, + ty::FnConverging(ty::mk_nil(ccx.tcx()))); finish_register_fn(ccx, sp, sym, node_id, llfn); llfn } diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 5777ee78800..44890407d08 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -414,7 +414,7 @@ impl<'tcx> TypeMap<'tcx> { unique_type_id.push_str(format!("[{}]", len).index(&FullRange)); } None => { - unique_type_id.push_str(".index(&FullRange)"); + unique_type_id.push_str("[]"); } }; diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 24feb579a06..da19fc52c8c 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -1369,13 +1369,13 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let tcx = bcx.tcx(); with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| { - let mut need_base: Vec<_> = repeat(true).take(field_tys.len()).collect(); + let mut need_base: Vec = repeat(true).take(field_tys.len()).collect(); let numbered_fields = fields.iter().map(|field| { let opt_pos = field_tys.iter().position(|field_ty| field_ty.name == field.ident.node.name); - match opt_pos { + let result = match opt_pos { Some(i) => { need_base[i] = false; (i, &*field.expr) @@ -1384,14 +1384,15 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, tcx.sess.span_bug(field.span, "Couldn't find field in struct type") } - } + }; + result }).collect::>(); let optbase = match base { Some(base_expr) => { let mut leftovers = Vec::new(); for (i, b) in need_base.iter().enumerate() { if *b { - leftovers.push((i, field_tys[i].mt.ty)) + leftovers.push((i, field_tys[i].mt.ty)); } } Some(StructBaseInfo {expr: base_expr, @@ -1408,7 +1409,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, trans_adt(bcx, ty, discr, - numbered_fields.index(&FullRange), + numbered_fields.as_slice(), optbase, dest, Some(NodeInfo { id: expr_id, span: expr_span })) diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index a90f0dbbf15..c8112e03707 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -748,7 +748,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, debug!("calling llrustfn = {}, t = {}", ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx())); let attributes = base::get_fn_llvm_attributes(ccx, t); - let llrust_ret_val = builder.call(llrustfn, llrust_args.index(&FullRange), Some(attributes)); + let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), Some(attributes)); // Get the return value where the foreign fn expects it. let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast { @@ -869,7 +869,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty.repr(ccx.tcx()), ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)), ccx.tn().type_to_string(llsig.llret_ty), - ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::>().index(&FullRange)), + ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::>().as_slice()), ccx.tn().type_to_string(fn_ty.ret_ty.ty), llsig.ret_def); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 7d36d01cc50..a2b1c32f0a5 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -556,7 +556,8 @@ pub fn instantiate_trait_ref<'tcx>( _ => { this.tcx().sess.span_fatal( ast_trait_ref.path.span, - format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx())).index(&FullRange)); + format!("`{}` is not a trait", + ast_trait_ref.path.user_string(this.tcx())).index(&FullRange)); } } } @@ -1069,8 +1070,12 @@ pub fn ast_ty_to_ty<'tcx>( ast::TyObjectSum(ref ty, ref bounds) => { match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) { Ok((trait_ref, projection_bounds)) => { - trait_ref_to_object_type(this, rscope, ast_ty.span, - trait_ref, projection_bounds, bounds.index(&FullRange)) + trait_ref_to_object_type(this, + rscope, + ast_ty.span, + trait_ref, + projection_bounds, + bounds.index(&FullRange)) } Err(ErrorReported) => { this.tcx().types.err diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index b1dc033b567..dff216ac293 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -195,7 +195,7 @@ fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>]. check_argument_types(fcx, call_expr.span, - fn_sig.inputs[], + fn_sig.inputs.as_slice(), arg_exprs.as_slice(), AutorefArgs::No, fn_sig.variadic, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index d43850989fe..652540bde70 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -563,7 +563,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { &**base_expr, Some(&ty::AdjustDerefRef(base_adjustment.clone()))); let index_expr_ty = self.fcx.expr_ty(&**index_expr); - + let result = check::try_index_step( self.fcx, MethodCall::expr(expr.id), @@ -640,7 +640,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { self.span, format!("cannot upcast `{}` to `{}`", source_trait_ref.repr(self.tcx()), - target_trait_def_id.repr(self.tcx()))[]); + target_trait_def_id.repr(self.tcx())).as_slice()); } } } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 50f73312c77..eb85654e68e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -3976,7 +3976,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, callee::check_call(fcx, expr, &**callee, args.as_slice()); } ast::ExprMethodCall(ident, ref tps, ref args) => { - check_method_call(fcx, expr, ident, args.index(&FullRange), tps.index(&FullRange), lvalue_pref); + check_method_call(fcx, expr, ident, args.as_slice(), tps.as_slice(), lvalue_pref); let arg_tys = args.iter().map(|a| fcx.expr_ty(&**a)); let args_err = arg_tys.fold(false, |rest_err, a| { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index cc36065656c..7d52418a9db 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1318,7 +1318,7 @@ fn get_or_create_type_parameter_def<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, let param_ty = ty::ParamTy::new(space, index, param.ident.name); let bounds = compute_bounds(ccx, param_ty.to_ty(ccx.tcx), - param.bounds.index(&FullRange, + param.bounds.index(&FullRange), SizedByDefault::Yes, param.span); let default = match param.default { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 6c0f6610802..abc669729fe 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -97,7 +97,7 @@ impl fmt::Show for clean::Generics { if i > 0 { try!(f.write_str(", ")) } - try!(f.write_str(tp.name[])); + try!(f.write_str(tp.name.as_slice())); if tp.bounds.len() > 0 { try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice()))); @@ -337,7 +337,7 @@ fn path(w: &mut fmt::Formatter, // This is a documented path, link to it! Some((ref fqp, shortty)) if abs_root.is_some() => { let mut url = String::from_str(abs_root.unwrap().as_slice()); - let to_link = fqp[..fqp.len() - 1]; + let to_link = &fqp[..(fqp.len() - 1)]; for component in to_link.iter() { url.push_str(component.as_slice()); url.push_str("/"); @@ -433,7 +433,7 @@ impl fmt::Show for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::TyParamBinder(id) => { - f.write_str(cache().typarams[ast_util::local_def(id)][]) + f.write_str(cache().typarams[ast_util::local_def(id)].as_slice()) } clean::Generic(ref name) => { f.write_str(name.as_slice()) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ddb14d6944b..a01fcd39952 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult search_index.push(IndexItem { ty: shortty(item), name: item.name.clone().unwrap(), - path: fqp[..fqp.len() - 1].connect("::"), + path: fqp[..(fqp.len() - 1)].connect("::"), desc: shorter(item.doc_value()).to_string(), parent: Some(did), }); @@ -559,7 +559,7 @@ fn write_shared(cx: &Context, }; let mut mydst = dst.clone(); - for part in remote_path[..remote_path.len() - 1].iter() { + for part in remote_path[..(remote_path.len() - 1)].iter() { mydst.push(part.as_slice()); try!(mkdir(&mydst)); } @@ -842,7 +842,7 @@ impl DocFolder for Cache { clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), - Some(self.stack[..self.stack.len() - 1])), + Some(&self.stack[..(self.stack.len() - 1)])), false) } clean::MethodItem(..) => { @@ -853,13 +853,13 @@ impl DocFolder for Cache { let did = *last; let path = match self.paths.get(&did) { Some(&(_, ItemType::Trait)) => - Some(self.stack[..self.stack.len() - 1]), + Some(&self.stack[..(self.stack.len() - 1)]), // The current stack not necessarily has correlation for // where the type was defined. On the other hand, // `paths` always has the right information if present. Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Enum)) => - Some(fqp[..fqp.len() - 1]), + Some(&fqp[..(fqp.len() - 1)]), Some(..) => Some(self.stack.as_slice()), None => None }; @@ -1185,7 +1185,7 @@ impl Context { .collect::(); match cache().paths.get(&it.def_id) { Some(&(ref names, _)) => { - for name in names[..names.len() - 1].iter() { + for name in (&names[..(names.len() - 1)]).iter() { url.push_str(name.as_slice()); url.push_str("/"); } @@ -2267,7 +2267,7 @@ fn item_macro(w: &mut fmt::Formatter, it: &clean::Item, t: &clean::Macro) -> fmt::Result { try!(w.write_str(highlight::highlight(t.source.as_slice(), Some("macro"), - None)[])); + None).as_slice())); document(w, it) } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 18c79fb9c59..c520b6f4723 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1124,7 +1124,7 @@ impl Json { } } -impl<'a> ops::Index<&'a str> for Json { +impl<'a> Index<&'a str> for Json { type Output = Json; fn index(&self, idx: & &str) -> &Json { @@ -1132,7 +1132,7 @@ impl<'a> ops::Index<&'a str> for Json { } } -impl ops::Index for Json { +impl Index for Json { type Output = Json; fn index<'a>(&'a self, idx: &uint) -> &'a Json { @@ -1186,7 +1186,8 @@ pub struct Stack { } /// StackElements compose a Stack. -/// For example, StackElement::Key("foo"), StackElement::Key("bar"), StackElement::Index(3) and StackElement::Key("x") are the +/// For example, StackElement::Key("foo"), StackElement::Key("bar"), +/// StackElement::Index(3) and StackElement::Key("x") are the /// StackElements compositing the stack that represents foo.bar[3].x #[derive(PartialEq, Clone, Show)] pub enum StackElement<'l> { @@ -2505,12 +2506,12 @@ mod tests { use super::ParserError::*; use super::DecoderError::*; use super::JsonEvent::*; - use super::StackElement::*; use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement, Stack, Decoder}; - use std::{i64, u64, f32, f64}; + use std::{i64, u64, f32, f64, io}; use std::collections::BTreeMap; use std::num::Float; + use std::ops::Index; use std::string; #[derive(RustcDecodable, Eq, PartialEq, Show)] @@ -3487,9 +3488,12 @@ mod tests { (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]), (ArrayEnd, vec![StackElement::Key("array")]), (ArrayStart, vec![StackElement::Key("idents")]), - (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]), - (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]), - (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]), + (NullValue, vec![StackElement::Key("idents"), + StackElement::Index(0)]), + (BooleanValue(true), vec![StackElement::Key("idents"), + StackElement::Index(1)]), + (BooleanValue(false), vec![StackElement::Key("idents"), + StackElement::Index(2)]), (ArrayEnd, vec![StackElement::Key("idents")]), (ObjectEnd, vec![]), ] @@ -3567,13 +3571,24 @@ mod tests { (ObjectStart, vec![]), (F64Value(1.0), vec![StackElement::Key("a")]), (ArrayStart, vec![StackElement::Key("b")]), - (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]), - (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), StackElement::Index(1)]), - (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]), - (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), - (NullValue, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c"), StackElement::Key("d")]), - (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), - (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]), + (BooleanValue(true), vec![StackElement::Key("b"), + StackElement::Index(0)]), + (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), + StackElement::Index(1)]), + (ObjectStart, vec![StackElement::Key("b"), + StackElement::Index(2)]), + (ObjectStart, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c")]), + (NullValue, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c"), + StackElement::Key("d")]), + (ObjectEnd, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c")]), + (ObjectEnd, vec![StackElement::Key("b"), + StackElement::Index(2)]), (ArrayEnd, vec![StackElement::Key("b")]), (ObjectEnd, vec![]), ] @@ -3716,13 +3731,19 @@ mod tests { stack.push_key("bar".to_string()); assert!(stack.len() == 3); - assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.is_equal_to(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(stack.starts_with(&[StackElement::Index(1)])); assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")])); - assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.starts_with(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(stack.ends_with(&[StackElement::Key("bar")])); assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")])); - assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.ends_with(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(!stack.last_is_index()); assert!(stack.get(0) == StackElement::Index(1)); assert!(stack.get(1) == StackElement::Key("foo")); diff --git a/src/libserialize/json_stage0.rs b/src/libserialize/json_stage0.rs index a157d917274..1c2855f6745 100644 --- a/src/libserialize/json_stage0.rs +++ b/src/libserialize/json_stage0.rs @@ -211,6 +211,7 @@ use std::string; use std::ops; use unicode::str as unicode_str; use unicode::str::Utf16Item; +use std::ops::Index as IndexOp; use Encodable; @@ -386,7 +387,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { }; if start < i { - try!(wr.write_str(v[start..i])); + try!(wr.write_str(v.index(&(start..i)))); } try!(wr.write_str(escaped)); @@ -395,7 +396,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { } if start != v.len() { - try!(wr.write_str(v[start..])); + try!(wr.write_str(v.index(&(start..)))); } wr.write_str("\"") @@ -404,7 +405,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result { let mut buf = [0; 4]; let n = v.encode_utf8(&mut buf).unwrap(); - let buf = unsafe { str::from_utf8_unchecked(buf[0..n]) }; + let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) }; escape_str(writer, buf) } @@ -417,7 +418,7 @@ fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result { } if n > 0 { - wr.write_str(BUF[..n]) + wr.write_str(BUF.index(&(..n))) } else { Ok(()) } @@ -624,7 +625,7 @@ impl<'a> ::Encoder for Encoder<'a> { let mut check_encoder = Encoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf[]).unwrap(); + let out = str::from_utf8(buf.index(&FullRange)).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -893,7 +894,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> { let mut check_encoder = PrettyEncoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf[]).unwrap(); + let out = str::from_utf8(buf.index(&FullRange)).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -1026,7 +1027,7 @@ impl Json { /// Returns None otherwise. pub fn as_string<'a>(&'a self) -> Option<&'a str> { match *self { - Json::String(ref s) => Some(s[]), + Json::String(ref s) => Some(s.index(&FullRange)), _ => None } } @@ -1220,7 +1221,8 @@ impl Stack { InternalIndex(i) => Index(i), InternalKey(start, size) => { Key(str::from_utf8( - self.str_buffer[start as uint .. start as uint + size as uint]).unwrap()) + self.str_buffer.index( + &((start as uint) .. (start as uint + size as uint)))).unwrap()) } } } @@ -1262,7 +1264,7 @@ impl Stack { Some(&InternalIndex(i)) => Some(Index(i)), Some(&InternalKey(start, size)) => { Some(Key(str::from_utf8( - self.str_buffer[start as uint .. (start+size) as uint] + self.str_buffer.index(&(start as uint) .. ((start+size) as uint)) ).unwrap())) } } @@ -2139,7 +2141,7 @@ impl ::Decoder for Decoder { return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) } }; - let idx = match names.iter().position(|n| *n == name[]) { + let idx = match names.iter().position(|n| *n == name.index(&FullRange)) { Some(idx) => idx, None => return Err(UnknownVariantError(name)) }; @@ -3352,7 +3354,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf[]).unwrap(); + let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {}", json_str), _ => {} // it parsed and we are good to go @@ -3368,7 +3370,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf[]).unwrap(); + let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {}", json_str), _ => {} // it parsed and we are good to go @@ -3408,7 +3410,7 @@ mod tests { write!(&mut writer, "{}", super::as_pretty_json(&json).indent(i)).unwrap(); - let printed = from_utf8(writer[]).unwrap(); + let printed = from_utf8(&writer.index(&FullRange)).unwrap(); // Check for indents at each line let lines: Vec<&str> = printed.lines().collect(); diff --git a/src/libserialize/serialize_stage0.rs b/src/libserialize/serialize_stage0.rs index fd37bb63230..87ff5922c1a 100644 --- a/src/libserialize/serialize_stage0.rs +++ b/src/libserialize/serialize_stage0.rs @@ -14,6 +14,7 @@ Core encoding and decoding interfaces. */ +use std::ops::FullRange; use std::path; use std::rc::Rc; use std::cell::{Cell, RefCell}; @@ -308,7 +309,7 @@ impl> Encodable for str { impl> Encodable for String { fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self[]) + s.emit_str(self.index(&FullRange)) } } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 11d48dff32a..c54a5ffa665 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -472,41 +472,37 @@ mod test { writer.write(&[0, 1]).unwrap(); let b: &[_] = &[]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[2]).unwrap(); let b: &[_] = &[0, 1]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[3]).unwrap(); - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let a: &[_] = &[0, 1, 2, 3]; - assert_eq!(a, writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[4]).unwrap(); writer.write(&[5]).unwrap(); - assert_eq!(a, writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[6]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[7, 8]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[9, 10, 11]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.flush().unwrap(); - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); } #[test] @@ -514,7 +510,7 @@ mod test { let mut w = BufferedWriter::with_capacity(3, Vec::new()); w.write(&[0, 1]).unwrap(); let a: &[_] = &[]; - assert_eq!(a, w.get_ref()[]); + assert_eq!(a, &w.get_ref()[]); let w = w.into_inner(); let a: &[_] = &[0, 1]; assert_eq!(a, w.index(&FullRange)); @@ -559,21 +555,21 @@ mod test { let mut writer = LineBufferedWriter::new(Vec::new()); writer.write(&[0]).unwrap(); let b: &[_] = &[]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[1]).unwrap(); - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n']; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[3, b'\n']).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); } #[test] diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 2c2824cbb3b..9e6af86925b 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -13,7 +13,7 @@ //! Readers and Writers for in-memory buffers use cmp::min; -use prelude::Index; +use prelude::v1::Index; use option::Option::None; use result::Result::{Err, Ok}; use io; @@ -391,9 +391,9 @@ impl<'a> Buffer for BufReader<'a> { #[cfg(test)] mod test { extern crate "test" as test_crate; - use prelude::v1::*; - - use io::{SeekSet, SeekCur, SeekEnd}; + use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; + use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt}; + use prelude::v1::{IteratorExt, Index}; use io; use iter::repeat; use self::test_crate::Bencher; diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index ea232ad0c3f..5f77ab38d74 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -752,12 +752,12 @@ impl Drop for Process { #[cfg(test)] mod tests { - use prelude::v1::*; - + use io::{Truncate, Write, TimedOut, timer, process, FileNotFound}; + use prelude::v1::{Ok, Err, range, drop, Some, None, Vec}; + use prelude::v1::{Path, String, Reader, Writer, Clone}; + use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath}; use io::fs::PathExtensions; - use io::process; use io::timer::*; - use io::{Truncate, Write, TimedOut, timer, FileNotFound}; use rt::running_on_valgrind; use str; use super::{CreatePipe}; diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 021aae5a601..87188c0d4a2 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -68,7 +68,7 @@ use fmt; use iter::IteratorExt; use option::Option; use option::Option::{None, Some}; -use prelude::{FullRange, Index}; +use prelude::v1::{FullRange, Index}; use str; use str::StrExt; use string::{String, CowString}; diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index d469bb4d767..97545bc2022 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -24,7 +24,7 @@ use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map, repeat}; use mem; use option::Option::{self, Some, None}; -use prelude::{FullRange, Index}; +use prelude::v1::{FullRange, Index}; use slice::{SliceExt, SliceConcatExt}; use str::{SplitTerminator, FromStr, StrExt}; use string::{String, ToString}; @@ -337,8 +337,12 @@ impl GenericPath for Path { Some(match self.sepidx_or_prefix_len() { None if ".." == self.repr => self.repr.index(&FullRange), None => ".", - Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => self.repr.index(&FullRange), - Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => self.repr.index(&FullRange), + Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => { + self.repr.index(&FullRange) + } + Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => { + self.repr.index(&FullRange) + } Some((0,idxa,_)) => self.repr.index(&(0..idxa)), Some((idxb,idxa,_)) => { match self.prefix { diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index 9e9a483e1a5..d0dcf77002f 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -14,7 +14,8 @@ // Reexported core operators #[stable] #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync}; -#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; +#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce, FullRange}; +#[unstable] #[doc(no_inline)] pub use ops::{Index, IndexMut}; // Reexported functions #[stable] #[doc(no_inline)] pub use mem::drop; diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index 4ccecfd1f5f..eb76f13afe7 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -23,6 +23,7 @@ use dynamic_lib::DynamicLibrary; use ffi; +use core::ops::Index; use intrinsics; use io::{IoResult, Writer}; use libc; @@ -361,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(bytes[..bytes.len()-1])), + Err(..) => try!(w.write(bytes.index(&(..(bytes.len()-1))))), } } try!(w.write(&['\n' as u8])); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 54e6a338178..da3744d83f5 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -206,7 +206,7 @@ impl, E> Decodable for Ident { #[cfg(not(stage0))] impl Decodable for Ident { fn decode(d: &mut D) -> Result { - Ok(str_to_ident(try!(d.read_str())[])) + Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 97f70d416db..68bbde35ae6 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -332,7 +332,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P], cfg: &ast::Me !cfg_matches(diagnostic, cfgs, &*mis[0]) } ast::MetaList(ref pred, _) => { - diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).index(&FullRange)); + diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice()); false }, ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg), diff --git a/src/libsyntax/ext/deriving/bounds.rs b/src/libsyntax/ext/deriving/bounds.rs index 2189f7d83d8..440bdff1471 100644 --- a/src/libsyntax/ext/deriving/bounds.rs +++ b/src/libsyntax/ext/deriving/bounds.rs @@ -29,12 +29,13 @@ pub fn expand_deriving_bound(cx: &mut ExtCtxt, "Send" | "Sync" => { return cx.span_err(span, format!("{} is an unsafe trait and it \ - should be implemented explicitly", *tname).index(&FullRange)) + should be implemented explicitly", + *tname).as_slice()) } ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ - found {}", *tname).index(&FullRange)) + found {}", *tname).as_slice()) } } }, diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 328e302bef3..581c60bdeb9 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess, new_ei.idx += 1u; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { - (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(Vec::new(), sp))); + (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index afe149e9d69..2c36a02d44f 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -278,7 +278,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { _ => {} } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.as_slice(), "unsafe_destructor") { self.gate_feature("unsafe_destructor", i.span, @@ -287,7 +287,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { removed in the future"); } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.index(&FullRange), "old_orphan_check") { self.gate_feature( "old_orphan_check", @@ -309,7 +309,8 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { and not portable across platforms") } - let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") { + let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(), + "link_name") { Some(val) => val.get().starts_with("llvm."), _ => false }; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 24a909cc5fb..d4650a4bb03 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -1167,10 +1167,10 @@ mod test { for &src in srcs.iter() { let spans = get_spans_of_pat_idents(src); - let Span{lo:lo,hi:hi,..} = spans[0]; - assert!("self" == src[lo.to_uint()..hi.to_uint()], + let Span{ lo, hi, .. } = spans[0]; + assert!("self" == &src[lo.to_uint()..hi.to_uint()], "\"{}\" != \"self\". src=\"{}\"", - src[lo.to_uint()..hi.to_uint()], src) + &src[lo.to_uint()..hi.to_uint()], src) } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 7824dacd3a1..0ecd098951f 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1726,7 +1726,7 @@ impl<'a> Parser<'a> { token::Str_(s) => { (true, - LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).index(&FullRange)), + LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()), ast::CookedStr)) } token::StrRaw(s, n) => { @@ -2538,16 +2538,26 @@ impl<'a> Parser<'a> { token::OpenDelim(token::Bracket) => { let bracket_pos = self.span.lo; self.bump(); - if self.eat(&token::CloseDelim(token::Bracket)) { + + let mut found_dotdot = false; + if self.token == token::DotDot && + self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) { + // Using expr[..], which is a mistake, should be expr[] + self.bump(); + self.bump(); + found_dotdot = true; + } + + if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) { // No expression, expand to a FullRange - let ix = { - hi = self.last_span.hi; - let range = ExprStruct(ident_to_path(mk_sp(lo, hi), - token::special_idents::FullRange), - vec![], - None); - self.mk_expr(bracket_pos, hi, range) - }; + // FIXME(#20516) It would be better to use a lang item or + // something for FullRange. + hi = self.last_span.hi; + let range = ExprStruct(ident_to_path(mk_sp(lo, hi), + token::special_idents::FullRange), + vec![], + None); + let ix = self.mk_expr(bracket_pos, hi, range); let index = self.mk_index(e, ix); e = self.mk_expr(lo, hi, index) } else { @@ -2557,6 +2567,12 @@ impl<'a> Parser<'a> { let index = self.mk_index(e, ix); e = self.mk_expr(lo, hi, index) } + + if found_dotdot { + self.span_err(e.span, "incorrect slicing expression: `[..]`"); + self.span_note(e.span, + "use `&expr[]` to construct a slice of the whole of expr"); + } } // A range expression, either `expr..expr` or `expr..`. @@ -4881,7 +4897,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.fatal(format!("expected `where`, or `{}` after struct \ name, found `{}`", "{", - token_str)[]); + token_str).index(&FullRange)); } fields diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index ada463a40cb..f70ce54bb1c 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -689,8 +689,7 @@ impl, E> Decodable for InternedString { #[cfg(not(stage0))] impl Decodable for InternedString { fn decode(d: &mut D) -> Result { - Ok(get_name(get_ident_interner().intern( - try!(d.read_str())[]))) + Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange)))) } } @@ -704,7 +703,7 @@ impl, E> Encodable for InternedString { #[cfg(not(stage0))] impl Encodable for InternedString { fn encode(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.string[]) + s.emit_str(self.string.index(&FullRange)) } } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 721769be7a4..87dcc9e70f4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1537,35 +1537,34 @@ impl<'a> State<'a> { ast::ExprStruct(ref path, ref fields, ref wth) => { try!(self.print_path(path, true)); - if fields.is_empty() && wth.is_none() { - return; - } - try!(word(&mut self.s, "{")); - try!(self.commasep_cmnt( - Consistent, - fields.index(&FullRange), - |s, field| { - try!(s.ibox(indent_unit)); - try!(s.print_ident(field.ident.node)); - try!(s.word_space(":")); - try!(s.print_expr(&*field.expr)); - s.end() - }, - |f| f.span)); - match *wth { - Some(ref expr) => { - try!(self.ibox(indent_unit)); - if !fields.is_empty() { - try!(word(&mut self.s, ",")); - try!(space(&mut self.s)); + if !(fields.is_empty() && wth.is_none()) { + try!(word(&mut self.s, "{")); + try!(self.commasep_cmnt( + Consistent, + fields.index(&FullRange), + |s, field| { + try!(s.ibox(indent_unit)); + try!(s.print_ident(field.ident.node)); + try!(s.word_space(":")); + try!(s.print_expr(&*field.expr)); + s.end() + }, + |f| f.span)); + match *wth { + Some(ref expr) => { + try!(self.ibox(indent_unit)); + if !fields.is_empty() { + try!(word(&mut self.s, ",")); + try!(space(&mut self.s)); + } + try!(word(&mut self.s, "..")); + try!(self.print_expr(&**expr)); + try!(self.end()); } - try!(word(&mut self.s, "..")); - try!(self.print_expr(&**expr)); - try!(self.end()); + _ => try!(word(&mut self.s, ",")), } - _ => try!(word(&mut self.s, ",")), + try!(word(&mut self.s, "}")); } - try!(word(&mut self.s, "}")); } ast::ExprTup(ref exprs) => { try!(self.popen()); @@ -2781,7 +2780,7 @@ impl<'a> State<'a> { format!("-{}", istr).index(&FullRange)) } ast::UnsignedIntLit(ut) => { - word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).index(&FullRange)) + 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)) diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 7dca2b24fc1..8ce365f765d 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -105,7 +105,7 @@ impl Perm { let d = idx / self.fact[i] as i32; self.cnt[i] = d; idx %= self.fact[i] as i32; - for (place, val) in pp.iter_mut().zip(self.perm.p[..i+1].iter()) { + for (place, val) in pp.iter_mut().zip(self.perm.p[..(i+1)].iter()) { *place = (*val) as u8 } diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 9128930651f..29994f45d3a 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -99,7 +99,7 @@ fn make_fasta>( } n -= nb; line[nb] = '\n' as u8; - try!(wr.write(line[..nb+1])); + try!(wr.write(&line[..(nb+1)])); } Ok(()) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index e6ef6a8c8c9..39c839ba114 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -101,11 +101,11 @@ fn windows_with_carry(bb: &[u8], nn: uint, mut it: F) -> Vec where let len = bb.len(); while ii < len - (nn - 1u) { - it(bb[ii..ii+nn]); + it(&bb[ii..(ii+nn)]); ii += 1u; } - return bb[len - (nn - 1u)..len].to_vec(); + return bb[(len - (nn - 1u))..len].to_vec(); } fn make_sequence_processor(sz: uint, diff --git a/src/test/compile-fail/borrowck-loan-vec-content.rs b/src/test/compile-fail/borrowck-loan-vec-content.rs index 7849475ec67..efb7a5253ed 100644 --- a/src/test/compile-fail/borrowck-loan-vec-content.rs +++ b/src/test/compile-fail/borrowck-loan-vec-content.rs @@ -17,12 +17,12 @@ fn takes_imm_elt(_v: &int, f: F) where F: FnOnce() { } fn has_mut_vec_and_does_not_try_to_change_it() { - let mut v = vec!(1, 2, 3); + let mut v: Vec = vec!(1, 2, 3); takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { - let mut v = vec!(1, 2, 3); + let mut v: Vec = vec!(1, 2, 3); takes_imm_elt( &v[0], || { //~ ERROR cannot borrow `v` as mutable diff --git a/src/test/compile-fail/indexing-requires-a-uint.rs b/src/test/compile-fail/indexing-requires-a-uint.rs index 9ac4bd2566e..e5edb2358f8 100644 --- a/src/test/compile-fail/indexing-requires-a-uint.rs +++ b/src/test/compile-fail/indexing-requires-a-uint.rs @@ -13,7 +13,8 @@ fn main() { fn bar(_: T) {} - [0][0u8]; //~ ERROR: mismatched types + [0][0u8]; //~ ERROR: the trait `core::ops::Index` is not implemented + //~^ ERROR: the trait `core::ops::Index` is not implemented [0][0]; // should infer to be a uint diff --git a/src/test/compile-fail/integral-indexing.rs b/src/test/compile-fail/integral-indexing.rs index 8b1f9eb1986..bbceb00abd3 100644 --- a/src/test/compile-fail/integral-indexing.rs +++ b/src/test/compile-fail/integral-indexing.rs @@ -11,16 +11,24 @@ pub fn main() { let v: Vec = vec!(0, 1, 2, 3, 4, 5); let s: String = "abcdef".to_string(); - assert_eq!(v.as_slice()[3u], 3); - assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3u32], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3i32], 3); //~ ERROR: mismatched types - println!("{}", v.as_slice()[3u8]); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3u], 'd' as u8); - assert_eq!(s.as_bytes()[3u8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3i8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3u32], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3i32], 'd' as u8); //~ ERROR: mismatched types - println!("{}", s.as_bytes()[3u8]); //~ ERROR: mismatched types + v.as_slice()[3u]; + v.as_slice()[3]; + v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3i8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3u]; + s.as_bytes()[3]; + s.as_bytes()[3u8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3i8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3u32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3i32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented } diff --git a/src/test/compile-fail/issue-16709.rs b/src/test/compile-fail/issue-16709.rs deleted file mode 100644 index 327f50ee059..00000000000 --- a/src/test/compile-fail/issue-16709.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::ptr; -use std::raw; - -trait Slice {} - -fn main() { - unsafe { - let nil: *const u8 = ptr::null(); - let slice: raw::Slice = - Slice { //~ ERROR use of trait `Slice` as a struct constructor [E0159] - data: nil, - len: 0, - }; - } -} diff --git a/src/test/compile-fail/slice-2.rs b/src/test/compile-fail/slice-2.rs index 9ee70022545..a03693b5fad 100644 --- a/src/test/compile-fail/slice-2.rs +++ b/src/test/compile-fail/slice-2.rs @@ -16,8 +16,8 @@ struct Foo; fn main() { let x = Foo; - &x[]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[0..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` + &x[]; //~ ERROR cannot index a value of type `Foo` + &x[Foo..]; //~ ERROR cannot index a value of type `Foo` + &x[..Foo]; //~ ERROR cannot index a value of type `Foo` + &x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo` } diff --git a/src/test/compile-fail/slice-mut-2.rs b/src/test/compile-fail/slice-mut-2.rs index b34c9a49268..1dedb0cf888 100644 --- a/src/test/compile-fail/slice-mut-2.rs +++ b/src/test/compile-fail/slice-mut-2.rs @@ -16,5 +16,5 @@ fn main() { let x: &[int] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice let slice: &mut [int] = &mut [0, 1]; - &mut x[2..4] = slice; //~ ERROR cannot borrow + let _ = &mut x[2..4]; //~ERROR cannot borrow immutable dereference of `&`-pointer `*x` as mutabl } diff --git a/src/test/compile-fail/slice-mut.rs b/src/test/compile-fail/slice-mut.rs index e7353dfbcd0..f0f525a5535 100644 --- a/src/test/compile-fail/slice-mut.rs +++ b/src/test/compile-fail/slice-mut.rs @@ -15,5 +15,5 @@ fn main() { let x: &[int] = &[1, 2, 3, 4, 5]; // Immutable slices are not mutable. - let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutabl + let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutab } diff --git a/src/test/compile-fail/str-idx.rs b/src/test/compile-fail/str-idx.rs index 424ffed989b..ddd2a4eeedf 100644 --- a/src/test/compile-fail/str-idx.rs +++ b/src/test/compile-fail/str-idx.rs @@ -10,5 +10,6 @@ pub fn main() { let s: &str = "hello"; - let c: u8 = s[4]; //~ ERROR cannot index a value of type `&str` + let c: u8 = s[4]; //~ ERROR the trait `core::ops::Index<_>` is not implemented + //~^ ERROR the trait `core::ops::Index<_>` is not implemented } diff --git a/src/test/run-pass/issue-17503.rs b/src/test/run-pass/issue-17503.rs index 9d1a51ad79c..8acda175006 100644 --- a/src/test/run-pass/issue-17503.rs +++ b/src/test/run-pass/issue-17503.rs @@ -15,7 +15,7 @@ fn main() { let ss: &&[int] = &s; let sss: &&&[int] = &ss; - println!("{}", s.index(&(0..3))); - println!("{}", ss.index(&(3..))); - println!("{}", sss.index(&(2..4))); + println!("{}", &s[0..3]); + println!("{}", &ss[3..]); + println!("{}", &sss[2..4]); } diff --git a/src/test/run-pass/issue-3888-2.rs b/src/test/run-pass/issue-3888-2.rs index 115a96d5289..5ed9729c142 100644 --- a/src/test/run-pass/issue-3888-2.rs +++ b/src/test/run-pass/issue-3888-2.rs @@ -11,7 +11,7 @@ #![feature(slicing_syntax)] fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] { - v.index(&(1..5)) + &v[1..5] } pub fn main() {} diff --git a/src/test/run-pass/issue-4464.rs b/src/test/run-pass/issue-4464.rs index fa75b5d2583..2581069d29b 100644 --- a/src/test/run-pass/issue-4464.rs +++ b/src/test/run-pass/issue-4464.rs @@ -10,6 +10,6 @@ #![feature(slicing_syntax)] -fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { v.index(&(i..j)) } +fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] } pub fn main() {} diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index 5b90878aa28..0c19286921a 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -18,7 +18,7 @@ pub fn main() { let abc = [1i, 2, 3]; let tf = [true, false]; let x = [(), ()]; - let slice = x.index(&(0..1)); + let slice = &x[0..1]; assert_repr_eq(&abc[], "[1, 2, 3]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); diff --git a/src/test/run-pass/slice-panic-1.rs b/src/test/run-pass/slice-panic-1.rs index 87de4246f3e..ebe6e974c26 100644 --- a/src/test/run-pass/slice-panic-1.rs +++ b/src/test/run-pass/slice-panic-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen. +// Test that if a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] @@ -24,7 +24,7 @@ impl Drop for Foo { fn foo() { let x: &[_] = &[Foo, Foo]; - x.index(&(3..4)); + &x[3..4]; } fn main() { diff --git a/src/test/run-pass/slice-panic-2.rs b/src/test/run-pass/slice-panic-2.rs index afffaba64de..6bbd1ac7b2d 100644 --- a/src/test/run-pass/slice-panic-2.rs +++ b/src/test/run-pass/slice-panic-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen. +// Test that if a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] @@ -28,7 +28,7 @@ fn bar() -> uint { fn foo() { let x: &[_] = &[Foo, Foo]; - x[3..bar()]; + &x[3..bar()]; } fn main() { diff --git a/src/test/run-pass/slice.rs b/src/test/run-pass/slice.rs index e039886022c..fca7daeb07d 100644 --- a/src/test/run-pass/slice.rs +++ b/src/test/run-pass/slice.rs @@ -11,6 +11,7 @@ // Test slicing sugar. #![feature(slicing_syntax)] +#![feature(associated_types)] extern crate core; use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange}; @@ -19,49 +20,70 @@ static mut COUNT: uint = 0; struct Foo; -impl Slice for Foo { - fn as_slice_<'a>(&'a self) -> &'a Foo { +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &Range) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo { +} +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &RangeTo) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo { +} +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &RangeFrom) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo { +} +impl Index for Foo { + type Output = Foo; + fn index(&self, _index: &FullRange) -> &Foo { unsafe { COUNT += 1; } self } } -impl SliceMut for Foo { - fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo { +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &Range) -> &mut Foo { unsafe { COUNT += 1; } self } - fn slice_from_or_fail_mut<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo { +} +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &RangeTo) -> &mut Foo { unsafe { COUNT += 1; } self } - fn slice_to_or_fail_mut<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo { +} +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &RangeFrom) -> &mut Foo { unsafe { COUNT += 1; } self } - fn slice_or_fail_mut<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo { +} +impl IndexMut for Foo { + type Output = Foo; + fn index_mut(&mut self, _index: &FullRange) -> &mut Foo { unsafe { COUNT += 1; } self } } + fn main() { let mut x = Foo; &x[]; &x[Foo..]; - &x[0..Foo]; + &x[..Foo]; &x[Foo..Foo]; &mut x[]; &mut x[Foo..]; -- cgit 1.4.1-3-g733a5