From 07f4fda598f3fa3e7980f7d97621879fbbf00750 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Wed, 17 Sep 2014 19:01:33 +0300 Subject: syntax: use an index in CodeMap instead of Gc for ExpnInfo. --- src/libsyntax/codemap.rs | 39 ++++++++++++---- src/libsyntax/diagnostic.rs | 38 ++++++++-------- src/libsyntax/ext/base.rs | 75 ++++++++++++++++++++++--------- src/libsyntax/ext/build.rs | 4 +- src/libsyntax/ext/deriving/generic/mod.rs | 3 +- src/libsyntax/ext/expand.rs | 27 +++-------- src/libsyntax/ext/source_util.rs | 46 ++++--------------- src/libsyntax/lib.rs | 2 +- src/libsyntax/parse/parser.rs | 2 +- 9 files changed, 123 insertions(+), 113 deletions(-) (limited to 'src/libsyntax') diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 2f30108c27b..7fe044b0fc8 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -25,7 +25,6 @@ source code snippets, etc. use serialize::{Encodable, Decodable, Encoder, Decoder}; use std::cell::RefCell; -use std::gc::Gc; use std::rc::Rc; pub trait Pos { @@ -93,10 +92,10 @@ pub struct Span { pub hi: BytePos, /// Information about where the macro came from, if this piece of /// code was created by a macro expansion. - pub expn_info: Option> + pub expn_id: ExpnId } -pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; +pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION }; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub struct Spanned { @@ -140,17 +139,19 @@ pub fn dummy_spanned(t: T) -> Spanned { /* assuming that we're not in macro expansion */ pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span { - Span {lo: lo, hi: hi, expn_info: None} + Span {lo: lo, hi: hi, expn_id: NO_EXPANSION} } /// Return the span itself if it doesn't come from a macro expansion, /// otherwise return the call site span up to the `enclosing_sp` by /// following the `expn_info` chain. -pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span { - match (sp.expn_info, enclosing_sp.expn_info) { +pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span { + let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site)); + let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site)); + match (call_site1, call_site2) { (None, _) => sp, - (Some(expn1), Some(expn2)) if expn1.call_site == expn2.call_site => sp, - (Some(expn1), _) => original_sp(expn1.call_site, enclosing_sp), + (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp, + (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp), } } @@ -222,6 +223,11 @@ pub struct ExpnInfo { pub callee: NameAndSpan } +#[deriving(PartialEq, Eq, Clone, Show, Hash)] +pub struct ExpnId(u32); + +pub static NO_EXPANSION: ExpnId = ExpnId(-1); + pub type FileName = String; pub struct FileLines { @@ -299,13 +305,15 @@ impl FileMap { } pub struct CodeMap { - pub files: RefCell>> + pub files: RefCell>>, + expansions: RefCell> } impl CodeMap { pub fn new() -> CodeMap { CodeMap { files: RefCell::new(Vec::new()), + expansions: RefCell::new(Vec::new()), } } @@ -527,6 +535,19 @@ impl CodeMap { col: chpos - linechpos } } + + pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId { + let mut expansions = self.expansions.borrow_mut(); + expansions.push(expn_info); + ExpnId(expansions.len().to_u32().expect("too many ExpnInfo's!") - 1) + } + + pub fn with_expn_info(&self, id: ExpnId, f: |Option<&ExpnInfo>| -> T) -> T { + match id { + NO_EXPANSION => f(None), + ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint])) + } + } } #[cfg(test)] diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index faa3946b74d..f33c768d647 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -389,7 +389,7 @@ fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) - let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info}; + 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.as_slice(), lvl, msg, code)); if rsp.is_full_span() { @@ -523,24 +523,24 @@ fn print_macro_backtrace(w: &mut EmitterWriter, cm: &codemap::CodeMap, sp: Span) -> io::IoResult<()> { - for ei in sp.expn_info.iter() { - let ss = ei.callee - .span - .as_ref() - .map_or("".to_string(), |span| cm.span_to_string(*span)); - let (pre, post) = match ei.callee.format { - codemap::MacroAttribute => ("#[", "]"), - codemap::MacroBang => ("", "!") - }; - try!(print_diagnostic(w, ss.as_slice(), Note, - format!("in expansion of {}{}{}", pre, - ei.callee.name, - post).as_slice(), None)); - let ss = cm.span_to_string(ei.call_site); - try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site", None)); - try!(print_macro_backtrace(w, cm, ei.call_site)); - } - Ok(()) + let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| match expn_info { + Some(ei) => { + let ss = ei.callee.span.map_or(String::new(), |span| cm.span_to_string(span)); + let (pre, post) = match ei.callee.format { + codemap::MacroAttribute => ("#[", "]"), + codemap::MacroBang => ("", "!") + }; + try!(print_diagnostic(w, ss.as_slice(), Note, + format!("in expansion of {}{}{}", pre, + ei.callee.name, + post).as_slice(), None)); + let ss = cm.span_to_string(ei.call_site); + try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site", None)); + Ok(Some(ei.call_site)) + } + None => Ok(None) + })); + cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site)) } pub fn expect(diag: &SpanHandler, opt: Option, msg: || -> String) -> T { diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 773daa4a4c5..be0ab63e50d 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -11,7 +11,7 @@ use ast; use ast::Name; use codemap; -use codemap::{CodeMap, Span, ExpnInfo}; +use codemap::{CodeMap, Span, ExpnId, ExpnInfo, NO_EXPANSION}; use ext; use ext::expand; use parse; @@ -24,7 +24,6 @@ use ext::mtwt; use fold::Folder; use std::collections::HashMap; -use std::gc::{Gc, GC}; use std::rc::Rc; // new-style macro! tt code: @@ -457,7 +456,7 @@ fn initial_syntax_expander_table() -> SyntaxEnv { pub struct ExtCtxt<'a> { pub parse_sess: &'a parse::ParseSess, pub cfg: ast::CrateConfig, - pub backtrace: Option>, + pub backtrace: ExpnId, pub ecfg: expand::ExpansionConfig, pub mod_path: Vec , @@ -473,7 +472,7 @@ impl<'a> ExtCtxt<'a> { ExtCtxt { parse_sess: parse_sess, cfg: cfg, - backtrace: None, + backtrace: NO_EXPANSION, mod_path: Vec::new(), ecfg: ecfg, trace_mac: false, @@ -501,13 +500,49 @@ impl<'a> ExtCtxt<'a> { pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess } pub fn cfg(&self) -> ast::CrateConfig { self.cfg.clone() } pub fn call_site(&self) -> Span { - match self.backtrace { + self.codemap().with_expn_info(self.backtrace, |ei| match ei { Some(expn_info) => expn_info.call_site, None => self.bug("missing top span") - } + }) } pub fn print_backtrace(&self) { } - pub fn backtrace(&self) -> Option> { self.backtrace } + pub fn backtrace(&self) -> ExpnId { self.backtrace } + pub fn original_span(&self) -> Span { + let mut expn_id = self.backtrace; + let mut call_site = None; + loop { + match self.codemap().with_expn_info(expn_id, |ei| ei.map(|ei| ei.call_site)) { + None => break, + Some(cs) => { + call_site = Some(cs); + expn_id = cs.expn_id; + } + } + } + call_site.expect("missing expansion backtrace") + } + pub fn original_span_in_file(&self) -> Span { + let mut expn_id = self.backtrace; + let mut call_site = None; + loop { + let expn_info = self.codemap().with_expn_info(expn_id, |ei| { + ei.map(|ei| (ei.call_site, ei.callee.name.as_slice() == "include")) + }); + match expn_info { + None => break, + Some((cs, is_include)) => { + if is_include { + // Don't recurse into file using "include!". + break; + } + call_site = Some(cs); + expn_id = cs.expn_id; + } + } + } + call_site.expect("missing expansion backtrace") + } + pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); } pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); } pub fn mod_path(&self) -> Vec { @@ -516,22 +551,22 @@ impl<'a> ExtCtxt<'a> { v.extend(self.mod_path.iter().map(|a| *a)); return v; } - pub fn bt_push(&mut self, ei: codemap::ExpnInfo) { - match ei { - ExpnInfo {call_site: cs, callee: ref callee} => { - self.backtrace = - Some(box(GC) ExpnInfo { - call_site: Span {lo: cs.lo, hi: cs.hi, - expn_info: self.backtrace.clone()}, - callee: (*callee).clone() - }); - } - } + pub fn bt_push(&mut self, ei: ExpnInfo) { + let mut call_site = ei.call_site; + call_site.expn_id = self.backtrace; + self.backtrace = self.codemap().record_expansion(ExpnInfo { + call_site: call_site, + callee: ei.callee + }); } pub fn bt_pop(&mut self) { match self.backtrace { - Some(expn_info) => self.backtrace = expn_info.call_site.expn_info, - _ => self.bug("tried to pop without a push") + NO_EXPANSION => self.bug("tried to pop without a push"), + expn_id => { + self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| { + expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id) + }); + } } } /// Emit `msg` attached to `sp`, and stop compilation immediately. diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 7b2613d4e8b..16ecd83180e 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -573,7 +573,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let field_span = Span { lo: sp.lo - Pos::from_uint(field_name.get().len()), hi: sp.hi, - expn_info: sp.expn_info, + expn_id: sp.expn_id, }; let id = Spanned { node: ident, span: field_span }; @@ -583,7 +583,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let field_span = Span { lo: sp.lo - Pos::from_uint(idx.to_string().len()), hi: sp.hi, - expn_info: sp.expn_info, + expn_id: sp.expn_id, }; let id = Spanned { node: idx, span: field_span }; diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index ff249495bd7..142adc9b721 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -181,7 +181,6 @@ //! ~~~ use std::cell::RefCell; -use std::gc::GC; use std::vec; use abi::Abi; @@ -1169,7 +1168,7 @@ impl<'a> TraitDef<'a> { None => cx.span_bug(self.span, "trait with empty path in generic `deriving`"), Some(name) => *name }; - to_set.expn_info = Some(box(GC) codemap::ExpnInfo { + to_set.expn_id = cx.codemap().record_expansion(codemap::ExpnInfo { call_site: to_set, callee: codemap::NameAndSpan { name: format!("deriving({})", trait_name), diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 4ff9912645a..f81fc909a74 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -30,8 +30,6 @@ use util::small_vector::SmallVector; use visit; use visit::Visitor; -use std::gc::Gc; - enum Either { Left(L), Right(R) @@ -161,11 +159,11 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, // be the root of the call stack. That's the most // relevant span and it's the actual invocation of // the macro. - let mac_span = original_span(fld.cx); + let mac_span = fld.cx.original_span(); let opt_parsed = { let expanded = expandfun.expand(fld.cx, - mac_span.call_site, + mac_span, marked_before.as_slice()); parse_thunk(expanded) }; @@ -759,9 +757,9 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { let fm = fresh_mark(); let marked_before = mark_tts(tts.as_slice(), fm); - let mac_span = original_span(fld.cx); + let mac_span = fld.cx.original_span(); let expanded = match expander.expand(fld.cx, - mac_span.call_site, + mac_span, marked_before.as_slice()).make_pat() { Some(e) => e, None => { @@ -969,7 +967,7 @@ fn new_span(cx: &ExtCtxt, sp: Span) -> Span { Span { lo: sp.lo, hi: sp.hi, - expn_info: cx.backtrace(), + expn_id: cx.backtrace(), } } @@ -1083,21 +1081,6 @@ fn mark_method(expr: P, m: Mrk) -> P { .expect_one("marking an item didn't return exactly one method") } -fn original_span(cx: &ExtCtxt) -> Gc { - let mut relevant_info = cx.backtrace(); - let mut einfo = relevant_info.unwrap(); - loop { - match relevant_info { - None => { break } - Some(e) => { - einfo = e; - relevant_info = einfo.call_site.expn_info; - } - } - } - return einfo; -} - /// Check that there are no macro invocations left in the AST: pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) { visit::walk_crate(&mut MacroExterminator{sess:sess}, krate); diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 5cc0ec4a122..41967b0680c 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -11,7 +11,6 @@ use ast; use codemap; use codemap::{Pos, Span}; -use codemap::{ExpnInfo, NameAndSpan}; use ext::base::*; use ext::base; use ext::build::AstBuilder; @@ -19,7 +18,6 @@ use parse; use parse::token; use print::pprust; -use std::gc::Gc; use std::io::File; use std::rc::Rc; @@ -32,10 +30,10 @@ pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box { base::check_zero_tts(cx, sp, tts, "line!"); - let topmost = topmost_expn_info(cx.backtrace().unwrap()); - let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); + let topmost = cx.original_span_in_file(); + let loc = cx.codemap().lookup_char_pos(topmost.lo); - base::MacExpr::new(cx.expr_uint(topmost.call_site, loc.line)) + base::MacExpr::new(cx.expr_uint(topmost, loc.line)) } /* col!(): expands to the current column number */ @@ -43,9 +41,9 @@ pub fn expand_col(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box { base::check_zero_tts(cx, sp, tts, "col!"); - let topmost = topmost_expn_info(cx.backtrace().unwrap()); - let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MacExpr::new(cx.expr_uint(topmost.call_site, loc.col.to_uint())) + let topmost = cx.original_span_in_file(); + let loc = cx.codemap().lookup_char_pos(topmost.lo); + base::MacExpr::new(cx.expr_uint(topmost, loc.col.to_uint())) } /// file!(): expands to the current filename */ @@ -55,10 +53,10 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box { base::check_zero_tts(cx, sp, tts, "file!"); - let topmost = topmost_expn_info(cx.backtrace().unwrap()); - let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); + 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.as_slice()); - base::MacExpr::new(cx.expr_str(topmost.call_site, filename)) + base::MacExpr::new(cx.expr_str(topmost, filename)) } pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) @@ -162,32 +160,6 @@ pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } } -// recur along an ExpnInfo chain to find the original expression -fn topmost_expn_info(expn_info: Gc) -> Gc { - match *expn_info { - ExpnInfo { call_site: ref call_site, .. } => { - match call_site.expn_info { - Some(next_expn_info) => { - match *next_expn_info { - ExpnInfo { - callee: NameAndSpan { name: ref name, .. }, - .. - } => { - // Don't recurse into file using "include!" - if "include" == name.as_slice() { - expn_info - } else { - topmost_expn_info(next_expn_info) - } - } - } - }, - None => expn_info - } - } - } -} - // resolve a file-system path to an absolute file-system path (if it // isn't already) fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> Path { diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 457d77efb70..153b3cc90d6 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -23,7 +23,7 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/master/")] -#![feature(macro_rules, globs, managed_boxes, default_type_params, phase)] +#![feature(macro_rules, globs, default_type_params, phase)] #![feature(quote, struct_variant, unsafe_destructor, import_shadowing)] #![allow(deprecated)] diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ff4fd41fbd7..7c0564c28d1 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3590,7 +3590,7 @@ impl<'a> Parser<'a> { let span_with_semi = Span { lo: span.lo, hi: self.last_span.hi, - expn_info: span.expn_info, + expn_id: span.expn_id, }; stmts.push(P(Spanned { node: StmtSemi(e, stmt_id), -- cgit 1.4.1-3-g733a5 From f1a8f53cf10c2a68342aac70c5a706a865300bb4 Mon Sep 17 00:00:00 2001 From: Eduard Burtescu Date: Thu, 18 Sep 2014 14:36:01 +0300 Subject: Fix fallout in tests from removing the use of Gc in ExpnInfo. --- src/grammar/verify.rs | 2 +- src/librustc/middle/astencode.rs | 2 +- src/libsyntax/ast.rs | 4 ++-- src/libsyntax/codemap.rs | 6 +++--- src/libsyntax/parse/lexer/mod.rs | 6 +++--- src/libsyntax/parse/mod.rs | 4 ++-- src/test/compile-fail/qquote-1.rs | 2 +- src/test/compile-fail/qquote-2.rs | 2 +- src/test/run-pass-fulldeps/qquote.rs | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) (limited to 'src/libsyntax') diff --git a/src/grammar/verify.rs b/src/grammar/verify.rs index f2ae5a1ea4e..a95eeb3c97d 100644 --- a/src/grammar/verify.rs +++ b/src/grammar/verify.rs @@ -211,7 +211,7 @@ fn parse_antlr_token(s: &str, tokens: &HashMap) -> TokenAndSpan { let sp = syntax::codemap::Span { lo: syntax::codemap::BytePos(from_str::(start).unwrap() - offset), hi: syntax::codemap::BytePos(from_str::(end).unwrap() + 1), - expn_info: None + expn_id: syntax::codemap::NO_EXPANSION }; TokenAndSpan { diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 399313ddd8e..7a1064fdc00 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -2035,7 +2035,7 @@ impl fake_ext_ctxt for parse::ParseSess { codemap::Span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), - expn_info: None + expn_id: codemap::NO_EXPANSION } } fn ident_of(&self, st: &str) -> ast::Ident { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index eac158e664c..de9979d40b0 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -1363,7 +1363,7 @@ mod test { inner: Span { lo: BytePos(11), hi: BytePos(19), - expn_info: None, + expn_id: NO_EXPANSION, }, view_items: Vec::new(), items: Vec::new(), @@ -1373,7 +1373,7 @@ mod test { span: Span { lo: BytePos(10), hi: BytePos(20), - expn_info: None, + expn_id: NO_EXPANSION, }, exported_macros: Vec::new(), }; diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 7fe044b0fc8..9072889463c 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -686,7 +686,7 @@ mod test { fn t7() { // Test span_to_lines for a span ending at the end of filemap let cm = init_code_map(); - let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None}; + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; let file_lines = cm.span_to_lines(span); assert_eq!(file_lines.file.name, "blork.rs".to_string()); @@ -698,7 +698,7 @@ mod test { fn t8() { // Test span_to_snippet for a span ending at the end of filemap let cm = init_code_map(); - let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None}; + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; let snippet = cm.span_to_snippet(span); assert_eq!(snippet, Some("second line".to_string())); @@ -708,7 +708,7 @@ mod test { fn t9() { // Test span_to_str for a span ending at the end of filemap let cm = init_code_map(); - let span = Span {lo: BytePos(12), hi: BytePos(23), expn_info: None}; + let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION}; let sstr = cm.span_to_string(span); assert_eq!(sstr, "blork.rs:2:1: 2:12".to_string()); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index da43f08a4e5..68ddd17dd01 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -1406,7 +1406,7 @@ fn ident_continue(c: Option) -> bool { mod test { use super::*; - use codemap::{BytePos, CodeMap, Span}; + use codemap::{BytePos, CodeMap, Span, NO_EXPANSION}; use diagnostic; use parse::token; use parse::token::{str_to_ident}; @@ -1436,7 +1436,7 @@ mod test { let tok1 = string_reader.next_token(); let tok2 = TokenAndSpan{ tok:token::IDENT(id, false), - sp:Span {lo:BytePos(21),hi:BytePos(23),expn_info: None}}; + sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}}; assert_eq!(tok1,tok2); assert_eq!(string_reader.next_token().tok, token::WS); // the 'main' id is already read: @@ -1445,7 +1445,7 @@ mod test { let tok3 = string_reader.next_token(); let tok4 = TokenAndSpan{ tok:token::IDENT(str_to_ident("main"), false), - sp:Span {lo:BytePos(24),hi:BytePos(28),expn_info: None}}; + sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}}; assert_eq!(tok3,tok4); // the lparen is already read: assert_eq!(string_reader.last_pos.clone(), BytePos(29)) diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index d73cb211694..66ecdbfca02 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -721,7 +721,7 @@ pub fn integer_lit(s: &str, sd: &SpanHandler, sp: Span) -> ast::Lit_ { mod test { use super::*; use serialize::json; - use codemap::{Span, BytePos, Spanned}; + use codemap::{Span, BytePos, Spanned, NO_EXPANSION}; use owned_slice::OwnedSlice; use ast; use abi; @@ -736,7 +736,7 @@ mod test { // produce a codemap::span fn sp(a: u32, b: u32) -> Span { - Span{lo:BytePos(a),hi:BytePos(b),expn_info:None} + Span {lo: BytePos(a), hi: BytePos(b), expn_id: NO_EXPANSION} } #[test] fn path_exprs_1() { diff --git a/src/test/compile-fail/qquote-1.rs b/src/test/compile-fail/qquote-1.rs index 365a2fbe287..06d473baea8 100644 --- a/src/test/compile-fail/qquote-1.rs +++ b/src/test/compile-fail/qquote-1.rs @@ -39,7 +39,7 @@ impl fake_ext_ctxt for fake_session { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), - expn_info: None + expn_id: NO_EXPANSION } } fn ident_of(st: &str) -> ast::ident { diff --git a/src/test/compile-fail/qquote-2.rs b/src/test/compile-fail/qquote-2.rs index f202f1bb73c..f63dd91eb2b 100644 --- a/src/test/compile-fail/qquote-2.rs +++ b/src/test/compile-fail/qquote-2.rs @@ -36,7 +36,7 @@ impl fake_ext_ctxt for fake_session { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), - expn_info: None + expn_id: codemap::NO_EXPANSION } } fn ident_of(st: &str) -> ast::ident { diff --git a/src/test/run-pass-fulldeps/qquote.rs b/src/test/run-pass-fulldeps/qquote.rs index a5cf8e46b7e..252d297d12d 100644 --- a/src/test/run-pass-fulldeps/qquote.rs +++ b/src/test/run-pass-fulldeps/qquote.rs @@ -41,7 +41,7 @@ impl fake_ext_ctxt for fake_session { codemap::span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), - expn_info: None + expn_id: codemap::NO_EXPANSION } } fn ident_of(st: &str) -> ast::ident { -- cgit 1.4.1-3-g733a5 From 31a7e38759cc50b5135e73232dc9fa98e5154710 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 15 Sep 2014 20:48:58 +1200 Subject: Implement slicing syntax. `expr[]`, `expr[expr..]`, `expr[..expr]`,`expr[expr..expr]` Uses the Slice and SliceMut traits. Allows ... as well as .. in range patterns. --- src/libcollections/vec.rs | 80 +++++++++ src/libcore/ops.rs | 105 +++++++++++- src/libcore/slice.rs | 58 +++++++ src/librustc/middle/cfg/construct.rs | 7 + src/librustc/middle/expr_use_visitor.rs | 21 ++- src/librustc/middle/lang_items.rs | 2 + src/librustc/middle/liveness.rs | 10 +- src/librustc/middle/mem_categorization.rs | 2 +- src/librustc/middle/trans/callee.rs | 24 ++- src/librustc/middle/trans/debuginfo.rs | 6 + src/librustc/middle/trans/expr.rs | 40 ++++- src/librustc/middle/ty.rs | 6 +- src/librustc/middle/typeck/check/mod.rs | 267 +++++++++++++++++++++++------- src/librustc_back/svh.rs | 2 + src/libsyntax/ast.rs | 1 + src/libsyntax/fold.rs | 6 + src/libsyntax/parse/parser.rs | 105 +++++++++++- src/libsyntax/print/pprust.rs | 24 ++- src/libsyntax/visit.rs | 5 + src/test/compile-fail/slice-1.rs | 19 +++ src/test/compile-fail/slice-2.rs | 25 +++ src/test/compile-fail/slice-borrow.rs | 19 +++ src/test/compile-fail/slice-mut-2.rs | 17 ++ src/test/compile-fail/slice-mut.rs | 22 +++ src/test/run-pass/match-range-static.rs | 2 +- src/test/run-pass/slice-2.rs | 69 ++++++++ src/test/run-pass/slice.rs | 70 ++++++++ 27 files changed, 909 insertions(+), 105 deletions(-) create mode 100644 src/test/compile-fail/slice-1.rs create mode 100644 src/test/compile-fail/slice-2.rs create mode 100644 src/test/compile-fail/slice-borrow.rs create mode 100644 src/test/compile-fail/slice-mut-2.rs create mode 100644 src/test/compile-fail/slice-mut.rs create mode 100644 src/test/run-pass/slice-2.rs create mode 100644 src/test/run-pass/slice.rs (limited to 'src/libsyntax') diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index f570573262a..4051f682134 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -20,6 +20,7 @@ use core::default::Default; use core::fmt; use core::mem; use core::num; +use core::ops; use core::ptr; use core::raw::Slice as RawSlice; use core::uint; @@ -464,6 +465,47 @@ impl Index for Vec { } }*/ +impl ops::Slice for Vec { + #[inline] + fn as_slice_<'a>(&'a self) -> &'a [T] { + self.as_slice() + } + + #[inline] + fn slice_from_<'a>(&'a self, start: &uint) -> &'a [T] { + self.as_slice().slice_from_(start) + } + + #[inline] + fn slice_to_<'a>(&'a self, end: &uint) -> &'a [T] { + self.as_slice().slice_to_(end) + } + #[inline] + fn slice_<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] { + self.as_slice().slice_(start, end) + } +} + +impl ops::SliceMut for Vec { + #[inline] + fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] { + self.as_mut_slice() + } + + #[inline] + fn slice_from_mut_<'a>(&'a mut self, start: &uint) -> &'a mut [T] { + self.as_mut_slice().slice_from_mut_(start) + } + + #[inline] + fn slice_to_mut_<'a>(&'a mut self, end: &uint) -> &'a mut [T] { + self.as_mut_slice().slice_to_mut_(end) + } + #[inline] + fn slice_mut_<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] { + self.as_mut_slice().slice_mut_(start, end) + } +} impl FromIterator for Vec { #[inline] fn from_iter>(mut iterator: I) -> Vec { @@ -2327,6 +2369,44 @@ mod tests { let _ = vec[3]; } + // NOTE uncomment after snapshot + /* + #[test] + #[should_fail] + fn test_slice_out_of_bounds_1() { + let x: Vec = vec![1, 2, 3, 4, 5]; + x[-1..]; + } + + #[test] + #[should_fail] + fn test_slice_out_of_bounds_2() { + let x: Vec = vec![1, 2, 3, 4, 5]; + x[..6]; + } + + #[test] + #[should_fail] + fn test_slice_out_of_bounds_3() { + let x: Vec = vec![1, 2, 3, 4, 5]; + x[-1..4]; + } + + #[test] + #[should_fail] + fn test_slice_out_of_bounds_4() { + let x: Vec = vec![1, 2, 3, 4, 5]; + x[1..6]; + } + + #[test] + #[should_fail] + fn test_slice_out_of_bounds_5() { + let x: Vec = vec![1, 2, 3, 4, 5]; + x[3..2]; + } + */ + #[test] fn test_swap_remove_empty() { let mut vec: Vec = vec!(); diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 94febf03635..718d3119995 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -638,7 +638,7 @@ shr_impl!(uint u8 u16 u32 u64 int i8 i16 i32 i64) * ``` */ #[lang="index"] -pub trait Index { +pub trait Index { /// The method for the indexing (`Foo[Bar]`) operation fn index<'a>(&'a self, index: &Index) -> &'a Result; } @@ -651,7 +651,7 @@ pub trait Index { * # Example * * A trivial implementation of `IndexMut`. When `Foo[Foo]` happens, it ends up - * calling `index`, and therefore, `main` prints `Indexing!`. + * calling `index_mut`, and therefore, `main` prints `Indexing!`. * * ``` * struct Foo; @@ -669,11 +669,110 @@ pub trait Index { * ``` */ #[lang="index_mut"] -pub trait IndexMut { +pub trait IndexMut { /// The method for the indexing (`Foo[Bar]`) operation fn index_mut<'a>(&'a mut self, index: &Index) -> &'a mut Result; } +/** + * + * The `Slice` trait is used to specify the functionality of slicing operations + * like `arr[from..to]` when used in an immutable context. + * + * # Example + * + * A trivial implementation of `Slice`. When `Foo[..Foo]` happens, it ends up + * calling `slice_to`, and therefore, `main` prints `Slicing!`. + * + * ``` + * struct Foo; + * + * impl ::core::ops::Slice for Foo { + * fn as_slice_<'a>(&'a self) -> &'a Foo { + * println!("Slicing!"); + * self + * } + * fn slice_from_<'a>(&'a self, from: &Foo) -> &'a Foo { + * println!("Slicing!"); + * self + * } + * fn slice_to_<'a>(&'a self, to: &Foo) -> &'a Foo { + * println!("Slicing!"); + * self + * } + * fn slice_<'a>(&'a self, from: &Foo, to: &Foo) -> &'a Foo { + * println!("Slicing!"); + * self + * } + * } + * + * fn main() { + * Foo[..Foo]; + * } + * ``` + */ +// FIXME(#17273) remove the postscript _s +#[lang="slice"] +pub trait Slice for Sized? { + /// The method for the slicing operation foo[] + fn as_slice_<'a>(&'a self) -> &'a Result; + /// The method for the slicing operation foo[from..] + fn slice_from_<'a>(&'a self, from: &Idx) -> &'a Result; + /// The method for the slicing operation foo[..to] + fn slice_to_<'a>(&'a self, to: &Idx) -> &'a Result; + /// The method for the slicing operation foo[from..to] + fn slice_<'a>(&'a self, from: &Idx, to: &Idx) -> &'a Result; +} + +/** + * + * The `SliceMut` trait is used to specify the functionality of slicing + * operations like `arr[from..to]`, when used in a mutable context. + * + * # Example + * + * A trivial implementation of `SliceMut`. When `Foo[Foo..]` happens, it ends up + * calling `slice_from_mut`, and therefore, `main` prints `Slicing!`. + * + * ``` + * struct Foo; + * + * impl ::core::ops::SliceMut for Foo { + * fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo { + * println!("Slicing!"); + * self + * } + * fn slice_from_mut_<'a>(&'a mut self, from: &Foo) -> &'a mut Foo { + * println!("Slicing!"); + * self + * } + * fn slice_to_mut_<'a>(&'a mut self, to: &Foo) -> &'a mut Foo { + * println!("Slicing!"); + * self + * } + * fn slice_mut_<'a>(&'a mut self, from: &Foo, to: &Foo) -> &'a mut Foo { + * println!("Slicing!"); + * self + * } + * } + * + * fn main() { + * Foo[mut Foo..]; + * } + * ``` + */ +// FIXME(#17273) remove the postscript _s +#[lang="slice_mut"] +pub trait SliceMut for Sized? { + /// The method for the slicing operation foo[] + fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Result; + /// The method for the slicing operation foo[from..] + fn slice_from_mut_<'a>(&'a mut self, from: &Idx) -> &'a mut Result; + /// The method for the slicing operation foo[..to] + fn slice_to_mut_<'a>(&'a mut self, to: &Idx) -> &'a mut Result; + /// The method for the slicing operation foo[from..to] + fn slice_mut_<'a>(&'a mut self, from: &Idx, to: &Idx) -> &'a mut Result; +} /** * * The `Deref` trait is used to specify the functionality of dereferencing diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 65ad7bb1753..5368cb44502 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -42,6 +42,7 @@ use cmp; use default::Default; use iter::*; use num::{CheckedAdd, Saturating, div_rem}; +use ops; use option::{None, Option, Some}; use ptr; use ptr::RawPtr; @@ -475,6 +476,63 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] { } } +impl ops::Slice for [T] { + #[inline] + fn as_slice_<'a>(&'a self) -> &'a [T] { + self + } + + #[inline] + fn slice_from_<'a>(&'a self, start: &uint) -> &'a [T] { + self.slice_(start, &self.len()) + } + + #[inline] + fn slice_to_<'a>(&'a self, end: &uint) -> &'a [T] { + self.slice_(&0, end) + } + #[inline] + fn slice_<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] { + assert!(*start <= *end); + assert!(*end <= self.len()); + unsafe { + transmute(RawSlice { + data: self.as_ptr().offset(*start as int), + len: (*end - *start) + }) + } + } +} + +impl ops::SliceMut for [T] { + #[inline] + fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] { + self + } + + #[inline] + fn slice_from_mut_<'a>(&'a mut self, start: &uint) -> &'a mut [T] { + let len = &self.len(); + self.slice_mut_(start, len) + } + + #[inline] + fn slice_to_mut_<'a>(&'a mut self, end: &uint) -> &'a mut [T] { + self.slice_mut_(&0, end) + } + #[inline] + fn slice_mut_<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] { + assert!(*start <= *end); + assert!(*end <= self.len()); + unsafe { + transmute(RawSlice { + data: self.as_ptr().offset(*start as int), + len: (*end - *start) + }) + } + } +} + /// Extension methods for vectors such that their elements are /// mutable. #[experimental = "may merge with other traits; may lose region param; needs review"] diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index f1c288ae7a9..b268c2a7a51 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -424,6 +424,13 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { self.call(expr, pred, &**l, Some(&**r).into_iter()) } + ast::ExprSlice(ref base, ref start, ref end, _) => { + self.call(expr, + pred, + &**base, + start.iter().chain(end.iter()).map(|x| &**x)) + } + ast::ExprUnary(_, ref e) if self.is_method_call(expr) => { self.call(expr, pred, &**e, None::.iter()) } diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index c8c5284022d..7ae01c30e5c 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -316,7 +316,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { ast::ExprPath(..) => { } ast::ExprUnary(ast::UnDeref, ref base) => { // *base - if !self.walk_overloaded_operator(expr, &**base, None) { + if !self.walk_overloaded_operator(expr, &**base, Vec::new()) { self.select_from_expr(&**base); } } @@ -330,12 +330,23 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { } ast::ExprIndex(ref lhs, ref rhs) => { // lhs[rhs] - if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) { + if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs]) { self.select_from_expr(&**lhs); self.consume_expr(&**rhs); } } + ast::ExprSlice(ref base, ref start, ref end, _) => { // base[start..end] + 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, &**base, args); + assert!(overloaded); + } + ast::ExprCall(ref callee, ref args) => { // callee(args) self.walk_callee(expr, &**callee); self.consume_exprs(args); @@ -430,13 +441,13 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { } ast::ExprUnary(_, ref lhs) => { - if !self.walk_overloaded_operator(expr, &**lhs, None) { + if !self.walk_overloaded_operator(expr, &**lhs, Vec::new()) { self.consume_expr(&**lhs); } } ast::ExprBinary(_, ref lhs, ref rhs) => { - if !self.walk_overloaded_operator(expr, &**lhs, Some(&**rhs)) { + if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs]) { self.consume_expr(&**lhs); self.consume_expr(&**rhs); } @@ -774,7 +785,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { fn walk_overloaded_operator(&mut self, expr: &ast::Expr, receiver: &ast::Expr, - rhs: Option<&ast::Expr>) + rhs: Vec<&ast::Expr>) -> bool { if !self.typer.is_method_call(expr.id) { diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 1875c53f074..daba3b701c0 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -247,6 +247,8 @@ 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; UnsafeTypeLangItem, "unsafe", unsafe_type; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index fee6c77a799..69d37edf5ab 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -511,7 +511,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { // otherwise, live nodes are not required: ExprIndex(..) | ExprField(..) | ExprTupField(..) | ExprVec(..) | - ExprCall(..) | ExprMethodCall(..) | ExprTup(..) | + ExprCall(..) | ExprMethodCall(..) | ExprTup(..) | ExprSlice(..) | ExprBinary(..) | ExprAddrOf(..) | ExprCast(..) | ExprUnary(..) | ExprBreak(_) | ExprAgain(_) | ExprLit(_) | ExprRet(..) | ExprBlock(..) | @@ -1184,6 +1184,12 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.propagate_through_expr(&**l, r_succ) } + ExprSlice(ref e1, ref e2, ref e3, _) => { + let succ = e3.as_ref().map_or(succ, |e| self.propagate_through_expr(&**e, succ)); + let succ = e2.as_ref().map_or(succ, |e| self.propagate_through_expr(&**e, succ)); + self.propagate_through_expr(&**e1, succ) + } + ExprAddrOf(_, ref e) | ExprCast(ref e, _) | ExprUnary(_, ref e) | @@ -1468,7 +1474,7 @@ fn check_expr(this: &mut Liveness, expr: &Expr) { ExprWhile(..) | ExprLoop(..) | ExprIndex(..) | ExprField(..) | ExprTupField(..) | ExprVec(..) | ExprTup(..) | ExprBinary(..) | ExprCast(..) | ExprUnary(..) | ExprRet(..) | ExprBreak(..) | - ExprAgain(..) | ExprLit(_) | ExprBlock(..) | + ExprAgain(..) | ExprLit(_) | ExprBlock(..) | ExprSlice(..) | ExprMac(..) | ExprAddrOf(..) | ExprStruct(..) | ExprRepeat(..) | ExprParen(..) | ExprFnBlock(..) | ExprProc(..) | ExprUnboxedFn(..) | ExprPath(..) | ExprBox(..) => { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 17d941b5958..04883d94872 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -504,7 +504,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { ast::ExprAssign(..) | ast::ExprAssignOp(..) | ast::ExprFnBlock(..) | ast::ExprProc(..) | ast::ExprUnboxedFn(..) | ast::ExprRet(..) | - ast::ExprUnary(..) | + ast::ExprUnary(..) | ast::ExprSlice(..) | ast::ExprMethodCall(..) | ast::ExprCast(..) | ast::ExprVec(..) | ast::ExprTup(..) | ast::ExprIf(..) | ast::ExprBinary(..) | ast::ExprWhile(..) | diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index c54a446c455..9d30cd77717 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -860,10 +860,10 @@ pub enum CallArgs<'a> { // value. ArgVals(&'a [ValueRef]), - // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs` + // For overloaded operators: `(lhs, Vec(rhs, rhs_id))`. `lhs` // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of - // the right-hand-side (if any). - ArgOverloadedOp(Datum, Option<(Datum, ast::NodeId)>), + // the right-hand-side arguments (if any). + ArgOverloadedOp(Datum, Vec<(Datum, ast::NodeId)>), // Supply value of arguments as a list of expressions that must be // translated, for overloaded call operators. @@ -1047,17 +1047,13 @@ pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>, DontAutorefArg) })); - match rhs { - Some((rhs, rhs_id)) => { - assert_eq!(arg_tys.len(), 2); - - llargs.push(unpack_result!(bcx, { - trans_arg_datum(bcx, *arg_tys.get(1), rhs, - arg_cleanup_scope, - DoAutorefArg(rhs_id)) - })); - } - None => assert_eq!(arg_tys.len(), 1) + assert_eq!(arg_tys.len(), 1 + rhs.len()); + for (rhs, rhs_id) in rhs.move_iter() { + llargs.push(unpack_result!(bcx, { + trans_arg_datum(bcx, *arg_tys.get(1), rhs, + arg_cleanup_scope, + DoAutorefArg(rhs_id)) + })); } } ArgVals(vs) => { diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 62571ef9f9b..ac4b7d2e6f1 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -3479,6 +3479,12 @@ fn populate_scope_map(cx: &CrateContext, walk_expr(cx, &**rhs, scope_stack, scope_map); } + ast::ExprSlice(ref base, ref start, ref end, _) => { + walk_expr(cx, &**base, scope_stack, scope_map); + start.as_ref().map(|x| walk_expr(cx, &**x, scope_stack, scope_map)); + end.as_ref().map(|x| walk_expr(cx, &**x, scope_stack, scope_map)); + } + ast::ExprVec(ref init_expressions) | ast::ExprTup(ref init_expressions) => { for ie in init_expressions.iter() { diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 77712570185..6876403c8c2 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -590,6 +590,34 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ast::ExprIndex(ref base, ref idx) => { trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id)) } + ast::ExprSlice(ref base, ref start, ref end, _) => { + 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() + .find(&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())); + 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)))); + DatumBlock::new(bcx, scratch.to_expr_datum()) + } ast::ExprBox(_, ref contents) => { // Special case for `Box` and `Gc` let box_ty = expr_ty(bcx, expr); @@ -725,7 +753,7 @@ fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, index_expr, method_call, base_datum, - Some((ix_datum, idx.id)), + vec![(ix_datum, idx.id)], None)); let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty)); let elt_ty = match ty::deref(ref_ty, true) { @@ -1044,20 +1072,20 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let lhs = unpack_datum!(bcx, trans(bcx, &**lhs)); let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs)); trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs, - Some((rhs_datum, rhs.id)), Some(dest)).bcx + vec![(rhs_datum, rhs.id)], Some(dest)).bcx } ast::ExprUnary(_, ref subexpr) => { // if not overloaded, would be RvalueDatumExpr let arg = unpack_datum!(bcx, trans(bcx, &**subexpr)); trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), - arg, None, Some(dest)).bcx + arg, Vec::new(), Some(dest)).bcx } ast::ExprIndex(ref base, ref idx) => { // if not overloaded, would be RvalueDatumExpr let base = unpack_datum!(bcx, trans(bcx, &**base)); let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx)); trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base, - Some((idx_datum, idx.id)), Some(dest)).bcx + vec![(idx_datum, idx.id)], Some(dest)).bcx } ast::ExprCast(ref val, _) => { // DPS output mode means this is a trait cast: @@ -1751,7 +1779,7 @@ fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr, method_call: MethodCall, lhs: Datum, - rhs: Option<(Datum, ast::NodeId)>, + rhs: Vec<(Datum, ast::NodeId)>, dest: Option) -> Result<'blk, 'tcx> { let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty; @@ -2074,7 +2102,7 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref"); unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call, - datum, None, Some(SaveIn(scratch.val)))); + datum, Vec::new(), Some(SaveIn(scratch.val)))); scratch.to_expr_datum() } None => { diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 897bc4517f4..d6a36cd7e38 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -3648,6 +3648,9 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind { // the index method invoked for `a[i]` always yields an `&T` ast::ExprIndex(..) => LvalueExpr, + // the slice method invoked for `a[..]` always yields an `&T` + ast::ExprSlice(..) => LvalueExpr, + // `for` loops are statements ast::ExprForLoop(..) => RvalueStmtExpr, @@ -3702,7 +3705,8 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind { ast::ExprUnary(ast::UnDeref, _) | ast::ExprField(..) | ast::ExprTupField(..) | - ast::ExprIndex(..) => { + ast::ExprIndex(..) | + ast::ExprSlice(..) => { LvalueExpr } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index c8728d375f6..3257ddd11cd 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -110,7 +110,7 @@ use middle::typeck::rscope::RegionScope; use middle::typeck::{lookup_def_ccx}; use middle::typeck::no_params; use middle::typeck::{require_same_types}; -use middle::typeck::{MethodCall, MethodMap, ObjectCastMap}; +use middle::typeck::{MethodCall, MethodCallee, MethodMap, ObjectCastMap}; use middle::typeck::{TypeAndSubsts}; use middle::typeck; use middle::lang_items::TypeIdLangItem; @@ -124,7 +124,6 @@ use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::mem::replace; use std::rc::Rc; -use std::slice; use syntax::abi; use syntax::ast::{ProvidedMethod, RequiredMethod, TypeTraitItem}; use syntax::ast; @@ -2188,12 +2187,12 @@ pub fn autoderef(fcx: &FnCtxt, sp: Span, base_ty: ty::t, } /// Attempts to resolve a call expression as an overloaded call. -fn try_overloaded_call(fcx: &FnCtxt, - call_expression: &ast::Expr, - callee: &ast::Expr, - callee_type: ty::t, - args: &[P]) - -> bool { +fn try_overloaded_call<'a>(fcx: &FnCtxt, + call_expression: &ast::Expr, + callee: &ast::Expr, + callee_type: ty::t, + args: &[&'a P]) + -> bool { // Bail out if the callee is a bare function or a closure. We check those // manually. match *structure_of(fcx, callee.span, callee_type) { @@ -2276,18 +2275,125 @@ fn try_overloaded_deref(fcx: &FnCtxt, (method, _) => method }; + make_return_type(fcx, method_call, method) +} + +fn get_method_ty(method: &Option) -> ty::t { + match method { + &Some(ref method) => method.ty, + &None => ty::mk_err() + } +} + +fn make_return_type(fcx: &FnCtxt, + method_call: Option, + method: Option) + -> Option { match method { Some(method) => { let ref_ty = ty::ty_fn_ret(method.ty); match method_call { Some(method_call) => { - fcx.inh.method_map.borrow_mut().insert(method_call, method); + fcx.inh.method_map.borrow_mut().insert(method_call, + method); } None => {} } ty::deref(ref_ty, true) } - None => None + None => None, + } +} + +fn try_overloaded_slice(fcx: &FnCtxt, + method_call: Option, + expr: &ast::Expr, + base_expr: &ast::Expr, + base_ty: ty::t, + start_expr: &Option>, + end_expr: &Option>, + mutbl: &ast::Mutability) + -> Option { + let method = if mutbl == &ast::MutMutable { + // 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_mut_", + (&Some(_), &None) => "slice_from_mut_", + (&None, &Some(_)) => "slice_to_mut_", + (&None, &None) => "as_mut_slice_", + }; + + method::lookup_in_trait(fcx, + expr.span, + Some(&*base_expr), + token::intern(method_name), + trait_did, + base_ty, + [], + DontAutoderefReceiver, + IgnoreStaticMethods) + } + _ => None, + } + } else { + // Otherwise, fall back to `Slice`. + // FIXME(#17293) this will not coerce base_expr, so we miss the Slice + // trait for `&mut [T]`. + match fcx.tcx().lang_items.slice_trait() { + Some(trait_did) => { + let method_name = match (start_expr, end_expr) { + (&Some(_), &Some(_)) => "slice_", + (&Some(_), &None) => "slice_from_", + (&None, &Some(_)) => "slice_to_", + (&None, &None) => "as_slice_", + }; + + method::lookup_in_trait(fcx, + expr.span, + Some(&*base_expr), + token::intern(method_name), + trait_did, + base_ty, + [], + DontAutoderefReceiver, + IgnoreStaticMethods) + } + _ => None, + } + }; + + + // Regardless of whether the lookup succeeds, check the method arguments + // so that we have *some* type for each argument. + let method_type = get_method_ty(&method); + + let mut args = vec![]; + start_expr.as_ref().map(|x| args.push(x)); + end_expr.as_ref().map(|x| args.push(x)); + + check_method_argument_types(fcx, + expr.span, + method_type, + expr, + args.as_slice(), + DoDerefArgs, + DontTupleArguments); + + match method { + Some(method) => { + let result_ty = ty::ty_fn_ret(method.ty); + match method_call { + Some(method_call) => { + fcx.inh.method_map.borrow_mut().insert(method_call, + method); + } + None => {} + } + Some(ty::mt { ty: result_ty, mutbl: ast::MutImmutable }) + } + None => None, } } @@ -2333,32 +2439,16 @@ fn try_overloaded_index(fcx: &FnCtxt, // Regardless of whether the lookup succeeds, check the method arguments // so that we have *some* type for each argument. - let method_type = match method { - Some(ref method) => method.ty, - None => ty::mk_err() - }; + let method_type = get_method_ty(&method); check_method_argument_types(fcx, expr.span, method_type, expr, - slice::ref_slice(index_expr), + &[index_expr], DoDerefArgs, DontTupleArguments); - match method { - Some(method) => { - let ref_ty = ty::ty_fn_ret(method.ty); - match method_call { - Some(method_call) => { - fcx.inh.method_map.borrow_mut().insert(method_call, - method); - } - None => {} - } - ty::deref(ref_ty, true) - } - None => None, - } + make_return_type(fcx, method_call, method) } /// Given the head of a `for` expression, looks up the `next` method in the @@ -2442,14 +2532,14 @@ fn lookup_method_for_for_loop(fcx: &FnCtxt, } } -fn check_method_argument_types(fcx: &FnCtxt, - sp: Span, - method_fn_ty: ty::t, - callee_expr: &ast::Expr, - args_no_rcvr: &[P], - deref_args: DerefArgs, - tuple_arguments: TupleArgumentsFlag) - -> ty::t { +fn check_method_argument_types<'a>(fcx: &FnCtxt, + sp: Span, + method_fn_ty: ty::t, + callee_expr: &ast::Expr, + args_no_rcvr: &[&'a P], + deref_args: DerefArgs, + tuple_arguments: TupleArgumentsFlag) + -> ty::t { if ty::type_is_error(method_fn_ty) { let err_inputs = err_args(args_no_rcvr.len()); check_argument_types(fcx, @@ -2483,14 +2573,14 @@ fn check_method_argument_types(fcx: &FnCtxt, } } -fn check_argument_types(fcx: &FnCtxt, - sp: Span, - fn_inputs: &[ty::t], - _callee_expr: &ast::Expr, - args: &[P], - deref_args: DerefArgs, - variadic: bool, - tuple_arguments: TupleArgumentsFlag) { +fn check_argument_types<'a>(fcx: &FnCtxt, + sp: Span, + fn_inputs: &[ty::t], + _callee_expr: &ast::Expr, + args: &[&'a P], + deref_args: DerefArgs, + variadic: bool, + tuple_arguments: TupleArgumentsFlag) { /*! * * Generic function that factors out common logic from @@ -2627,7 +2717,7 @@ fn check_argument_types(fcx: &FnCtxt, DontDerefArgs => {} } - check_expr_coercable_to_type(fcx, &**arg, formal_ty); + check_expr_coercable_to_type(fcx, &***arg, formal_ty); } } } @@ -2636,12 +2726,12 @@ fn check_argument_types(fcx: &FnCtxt, // arguments which we skipped above. if variadic { for arg in args.iter().skip(expected_arg_count) { - check_expr(fcx, &**arg); + check_expr(fcx, &***arg); // There are a few types which get autopromoted when passed via varargs // in C but we just error out instead and require explicit casts. let arg_ty = structurally_resolved_type(fcx, arg.span, - fcx.expr_ty(&**arg)); + fcx.expr_ty(&***arg)); match ty::get(arg_ty).sty { ty::ty_float(ast::TyF32) => { fcx.type_error_message(arg.span, @@ -2877,10 +2967,10 @@ fn check_expr_with_unifier(fcx: &FnCtxt, expr.repr(fcx.tcx()), expected.repr(fcx.tcx())); // A generic function for doing all of the checking for call expressions - fn check_call(fcx: &FnCtxt, - call_expr: &ast::Expr, - f: &ast::Expr, - args: &[P]) { + fn check_call<'a>(fcx: &FnCtxt, + call_expr: &ast::Expr, + f: &ast::Expr, + args: &[&'a P]) { // Store the type of `f` as the type of the callee let fn_ty = fcx.expr_ty(f); @@ -2990,11 +3080,12 @@ fn check_expr_with_unifier(fcx: &FnCtxt, }; // Call the generic checker. + let args: Vec<_> = args.slice_from(1).iter().map(|x| x).collect(); let ret_ty = check_method_argument_types(fcx, method_name.span, fn_ty, expr, - args.slice_from(1), + args.as_slice(), DontDerefArgs, DontTupleArguments); @@ -3085,12 +3176,8 @@ fn check_expr_with_unifier(fcx: &FnCtxt, None => None }; let args = match rhs { - Some(rhs) => slice::ref_slice(rhs), - None => { - // Work around the lack of coercion. - let empty: &[_] = &[]; - empty - } + Some(rhs) => vec![rhs], + None => vec![] }; match method { Some(method) => { @@ -3102,7 +3189,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, op_ex.span, method_ty, op_ex, - args, + args.as_slice(), DoDerefArgs, DontTupleArguments) } @@ -3115,7 +3202,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, op_ex.span, expected_ty, op_ex, - args, + args.as_slice(), DoDerefArgs, DontTupleArguments); ty::mk_err() @@ -4136,12 +4223,13 @@ fn check_expr_with_unifier(fcx: &FnCtxt, check_expr(fcx, &**f); let f_ty = fcx.expr_ty(&**f); + let args: Vec<_> = args.iter().map(|x| x).collect(); if !try_overloaded_call(fcx, expr, &**f, f_ty, args.as_slice()) { check_call(fcx, expr, &**f, args.as_slice()); let (args_bot, args_err) = args.iter().fold((false, false), |(rest_bot, rest_err), a| { // is this not working? - let a_ty = fcx.expr_ty(&**a); + let a_ty = fcx.expr_ty(&***a); (rest_bot || ty::type_is_bot(a_ty), rest_err || ty::type_is_error(a_ty))}); if ty::type_is_error(f_ty) || args_err { @@ -4427,6 +4515,61 @@ fn check_expr_with_unifier(fcx: &FnCtxt, } } } + ast::ExprSlice(ref base, ref start, ref end, ref mutbl) => { + check_expr_with_lvalue_pref(fcx, &**base, lvalue_pref); + let raw_base_t = fcx.expr_ty(&**base); + + let mut some_err = false; + if ty::type_is_error(raw_base_t) || ty::type_is_bot(raw_base_t) { + fcx.write_ty(id, raw_base_t); + some_err = true; + } + + { + let check_slice_idx = |e: &ast::Expr| { + check_expr(fcx, e); + let e_t = fcx.expr_ty(e); + if ty::type_is_error(e_t) || ty::type_is_bot(e_t) { + fcx.write_ty(id, e_t); + some_err = true; + } + }; + start.as_ref().map(|e| check_slice_idx(&**e)); + end.as_ref().map(|e| check_slice_idx(&**e)); + } + + if !some_err { + let base_t = structurally_resolved_type(fcx, + expr.span, + raw_base_t); + let method_call = MethodCall::expr(expr.id); + match try_overloaded_slice(fcx, + Some(method_call), + expr, + &**base, + base_t, + start, + end, + mutbl) { + Some(mt) => fcx.write_ty(id, mt.ty), + None => { + fcx.type_error_message(expr.span, + |actual| { + format!("cannot take a {}slice of a value with type `{}`", + if mutbl == &ast::MutMutable { + "mutable " + } else { + "" + }, + actual) + }, + base_t, + None); + fcx.write_ty(id, ty::mk_err()) + } + } + } + } } debug!("type of expr({}) {} is...", expr.id, diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index 415141c0b94..f98a2dac084 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -245,6 +245,7 @@ mod svh_visitor { SawExprAssign, SawExprAssignOp(ast::BinOp), SawExprIndex, + SawExprSlice, SawExprPath, SawExprAddrOf(ast::Mutability), SawExprRet, @@ -279,6 +280,7 @@ mod svh_visitor { ExprField(_, id, _) => SawExprField(content(id.node)), ExprTupField(_, id, _) => SawExprTupField(id.node), ExprIndex(..) => SawExprIndex, + ExprSlice(..) => SawExprSlice, ExprPath(..) => SawExprPath, ExprAddrOf(m, _) => SawExprAddrOf(m), ExprBreak(id) => SawExprBreak(id.map(content)), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index eac158e664c..e2e40bc38f0 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -531,6 +531,7 @@ pub enum Expr_ { ExprField(P, SpannedIdent, Vec>), ExprTupField(P, Spanned, Vec>), ExprIndex(P, P), + ExprSlice(P, Option>, Option>, Mutability), /// Variable reference, possibly containing `::` and/or /// type parameters, e.g. foo::bar:: diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 3beba5bcda4..c71910779c2 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -1242,6 +1242,12 @@ pub fn noop_fold_expr(Expr {id, node, span}: Expr, folder: &mut T) -> ExprIndex(el, er) => { ExprIndex(folder.fold_expr(el), folder.fold_expr(er)) } + ExprSlice(e, e1, e2, m) => { + ExprSlice(folder.fold_expr(e), + e1.map(|x| folder.fold_expr(x)), + e2.map(|x| folder.fold_expr(x)), + m) + } ExprPath(pth) => ExprPath(folder.fold_path(pth)), ExprBreak(opt_ident) => ExprBreak(opt_ident.map(|x| folder.fold_ident(x))), ExprAgain(opt_ident) => ExprAgain(opt_ident.map(|x| folder.fold_ident(x))), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ff4fd41fbd7..1021a09177c 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -23,7 +23,7 @@ use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, Explicit use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain}; use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox}; use ast::{ExprBreak, ExprCall, ExprCast}; -use ast::{ExprField, ExprTupField, ExprFnBlock, ExprIf, ExprIndex}; +use ast::{ExprField, ExprTupField, ExprFnBlock, ExprIf, ExprIndex, ExprSlice}; use ast::{ExprLit, ExprLoop, ExprMac}; use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc}; use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary, ExprUnboxedFn}; @@ -1986,6 +1986,14 @@ impl<'a> Parser<'a> { ExprIndex(expr, idx) } + pub fn mk_slice(&mut self, expr: P, + start: Option>, + end: Option>, + mutbl: Mutability) + -> ast::Expr_ { + ExprSlice(expr, start, end, mutbl) + } + pub fn mk_field(&mut self, expr: P, ident: ast::SpannedIdent, tys: Vec>) -> ast::Expr_ { ExprField(expr, ident, tys) @@ -2400,13 +2408,87 @@ 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. token::LBRACKET => { self.bump(); - let ix = self.parse_expr(); - hi = self.span.hi; - self.commit_expr_expecting(&*ix, token::RBRACKET); - let index = self.mk_index(e, ix); - e = self.mk_expr(lo, hi, index) + let mutbl = if self.eat_keyword(keywords::Mut) { + MutMutable + } else { + MutImmutable + }; + match self.token { + // e[] + token::RBRACKET => { + self.bump(); + hi = self.span.hi; + let slice = self.mk_slice(e, None, None, mutbl); + e = self.mk_expr(lo, hi, slice) + } + // e[..e] + token::DOTDOT => { + self.bump(); + match self.token { + // e[..] + token::RBRACKET => { + 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[]` to construct a slice of the whole of expr"); + } + // e[..e] + _ => { + hi = self.span.hi; + let e2 = self.parse_expr(); + self.commit_expr_expecting(&*e2, token::RBRACKET); + let slice = self.mk_slice(e, None, Some(e2), mutbl); + e = self.mk_expr(lo, hi, slice) + } + } + } + // e[e] | e[e..] | e[e..e] + _ => { + let ix = self.parse_expr(); + match self.token { + // e[e..] | e[e..e] + token::DOTDOT => { + self.bump(); + let e2 = match self.token { + // e[e..] + token::RBRACKET => { + self.bump(); + None + } + // e[e..e] + _ => { + let e2 = self.parse_expr(); + self.commit_expr_expecting(&*e2, token::RBRACKET); + 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::RBRACKET); + let index = self.mk_index(e, ix); + e = self.mk_expr(lo, hi, index) + } + } + } + } } _ => return e @@ -3153,7 +3235,8 @@ impl<'a> Parser<'a> { // These expressions are limited to literals (possibly // preceded by unary-minus) or identifiers. let val = self.parse_literal_maybe_minus(); - if self.token == token::DOTDOT && + // FIXME(#17295) remove the DOTDOT option. + if (self.token == token::DOTDOTDOT || self.token == token::DOTDOT) && self.look_ahead(1, |t| { *t != token::COMMA && *t != token::RBRACKET }) { @@ -3198,12 +3281,16 @@ impl<'a> Parser<'a> { } }); - if self.look_ahead(1, |t| *t == token::DOTDOT) && + // FIXME(#17295) remove the DOTDOT option. + if self.look_ahead(1, |t| *t == token::DOTDOTDOT || *t == token::DOTDOT) && self.look_ahead(2, |t| { *t != token::COMMA && *t != token::RBRACKET }) { let start = self.parse_expr_res(RestrictionNoBarOp); - self.eat(&token::DOTDOT); + // FIXME(#17295) remove the DOTDOT option (self.eat(&token::DOTDOTDOT)). + if self.token == token::DOTDOTDOT || self.token == token::DOTDOT { + self.bump(); + } let end = self.parse_expr_res(RestrictionNoBarOp); pat = PatRange(start, end); } else if is_plain_ident(&self.token) && !can_be_enum_or_struct { diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 0ae5303641b..c6b9a3bceab 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1651,6 +1651,28 @@ impl<'a> State<'a> { try!(self.print_expr(&**index)); try!(word(&mut self.s, "]")); } + ast::ExprSlice(ref e, ref start, ref end, ref mutbl) => { + try!(self.print_expr(&**e)); + try!(word(&mut self.s, "[")); + if mutbl == &ast::MutMutable { + try!(word(&mut self.s, "mut")); + if start.is_some() || end.is_some() { + try!(space(&mut self.s)); + } + } + match start { + &Some(ref e) => try!(self.print_expr(&**e)), + _ => {} + } + if start.is_some() || end.is_some() { + try!(word(&mut self.s, "..")); + } + match end { + &Some(ref e) => try!(self.print_expr(&**e)), + _ => {} + } + try!(word(&mut self.s, "]")); + } ast::ExprPath(ref path) => try!(self.print_path(path, true)), ast::ExprBreak(opt_ident) => { try!(word(&mut self.s, "break")); @@ -1944,7 +1966,7 @@ impl<'a> State<'a> { ast::PatRange(ref begin, ref end) => { try!(self.print_expr(&**begin)); try!(space(&mut self.s)); - try!(word(&mut self.s, "..")); + try!(word(&mut self.s, "...")); try!(self.print_expr(&**end)); } ast::PatVec(ref before, ref slice, ref after) => { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index d425c60f4c9..32084856817 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -785,6 +785,11 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { visitor.visit_expr(&**main_expression); visitor.visit_expr(&**index_expression) } + ExprSlice(ref main_expression, ref start, ref end, _) => { + visitor.visit_expr(&**main_expression); + walk_expr_opt(visitor, start); + walk_expr_opt(visitor, end) + } ExprPath(ref path) => { visitor.visit_path(path, expression.id) } diff --git a/src/test/compile-fail/slice-1.rs b/src/test/compile-fail/slice-1.rs new file mode 100644 index 00000000000..622195a41c2 --- /dev/null +++ b/src/test/compile-fail/slice-1.rs @@ -0,0 +1,19 @@ +// 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. + +// Test slicing expr[..] is an error and gives a helpful error message. + +struct Foo; + +fn main() { + let x = Foo; + x[..]; //~ ERROR incorrect slicing expression: `[..]` + //~^ NOTE use `expr[]` to construct a slice of the whole of expr +} \ No newline at end of file diff --git a/src/test/compile-fail/slice-2.rs b/src/test/compile-fail/slice-2.rs new file mode 100644 index 00000000000..da00aa48ae0 --- /dev/null +++ b/src/test/compile-fail/slice-2.rs @@ -0,0 +1,25 @@ +// 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. + +// Test that slicing syntax gives errors if we have not implemented the trait. + +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[..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[mut]; //~ ERROR cannot take a mutable slice of a value with type `Foo` + x[mut Foo..]; //~ ERROR cannot take a mutable slice of a value with type `Foo` + x[mut ..Foo]; //~ ERROR cannot take a mutable slice of a value with type `Foo` + x[mut Foo..Foo]; //~ ERROR cannot take a mutable slice of a value with type `Foo` +} \ No newline at end of file diff --git a/src/test/compile-fail/slice-borrow.rs b/src/test/compile-fail/slice-borrow.rs new file mode 100644 index 00000000000..3d12511134f --- /dev/null +++ b/src/test/compile-fail/slice-borrow.rs @@ -0,0 +1,19 @@ +// 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. + +// Test slicing expressions doesn't defeat the borrow checker. + +fn main() { + let y; + { + let x: &[int] = &[1, 2, 3, 4, 5]; //~ ERROR borrowed value does not live long enough + y = x[1..]; + } +} diff --git a/src/test/compile-fail/slice-mut-2.rs b/src/test/compile-fail/slice-mut-2.rs new file mode 100644 index 00000000000..1176b637cec --- /dev/null +++ b/src/test/compile-fail/slice-mut-2.rs @@ -0,0 +1,17 @@ +// 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. + +// Test mutability and slicing syntax. + +fn main() { + let x: &[int] = &[1, 2, 3, 4, 5]; + // Can't mutably slice an immutable slice + let y = x[mut 2..4]; //~ ERROR cannot take a mutable slice of a value with type `&[int]` +} diff --git a/src/test/compile-fail/slice-mut.rs b/src/test/compile-fail/slice-mut.rs new file mode 100644 index 00000000000..8cd7c4ed0bb --- /dev/null +++ b/src/test/compile-fail/slice-mut.rs @@ -0,0 +1,22 @@ +// 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. + +// Test mutability and slicing syntax. + +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 x: &mut [int] = &mut [1, 2, 3, 4, 5]; + // Can't borrow mutably twice + let y = x[mut 1..2]; + let y = x[mut 4..5]; //~ERROR cannot borrow +} diff --git a/src/test/run-pass/match-range-static.rs b/src/test/run-pass/match-range-static.rs index 039b3f9a26c..08875699245 100644 --- a/src/test/run-pass/match-range-static.rs +++ b/src/test/run-pass/match-range-static.rs @@ -13,7 +13,7 @@ static e: int = 42; pub fn main() { match 7 { - s..e => (), + s...e => (), _ => (), } } diff --git a/src/test/run-pass/slice-2.rs b/src/test/run-pass/slice-2.rs new file mode 100644 index 00000000000..3c0933a055c --- /dev/null +++ b/src/test/run-pass/slice-2.rs @@ -0,0 +1,69 @@ +// 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. + +// Test slicing expressions on slices and Vecs. + +fn main() { + let x: &[int] = &[1, 2, 3, 4, 5]; + let cmp: &[int] = &[1, 2, 3, 4, 5]; + assert!(x[] == cmp) + let cmp: &[int] = &[3, 4, 5]; + assert!(x[2..] == cmp) + let cmp: &[int] = &[1, 2, 3]; + assert!(x[..3] == cmp) + let cmp: &[int] = &[2, 3, 4]; + assert!(x[1..4] == cmp) + + let x: Vec = vec![1, 2, 3, 4, 5]; + let cmp: &[int] = &[1, 2, 3, 4, 5]; + assert!(x[] == cmp) + let cmp: &[int] = &[3, 4, 5]; + assert!(x[2..] == cmp) + let cmp: &[int] = &[1, 2, 3]; + assert!(x[..3] == cmp) + let cmp: &[int] = &[2, 3, 4]; + assert!(x[1..4] == cmp) + + let x: &mut [int] = &mut [1, 2, 3, 4, 5]; + { + let cmp: &mut [int] = &mut [1, 2, 3, 4, 5]; + assert!(x[mut] == cmp) + } + { + let cmp: &mut [int] = &mut [3, 4, 5]; + assert!(x[mut 2..] == cmp) + } + { + let cmp: &mut [int] = &mut [1, 2, 3]; + assert!(x[mut ..3] == cmp) + } + { + let cmp: &mut [int] = &mut [2, 3, 4]; + assert!(x[mut 1..4] == cmp) + } + + let mut x: Vec = vec![1, 2, 3, 4, 5]; + { + let cmp: &mut [int] = &mut [1, 2, 3, 4, 5]; + assert!(x[mut] == cmp) + } + { + let cmp: &mut [int] = &mut [3, 4, 5]; + assert!(x[mut 2..] == cmp) + } + { + let cmp: &mut [int] = &mut [1, 2, 3]; + assert!(x[mut ..3] == cmp) + } + { + let cmp: &mut [int] = &mut [2, 3, 4]; + assert!(x[mut 1..4] == cmp) + } +} diff --git a/src/test/run-pass/slice.rs b/src/test/run-pass/slice.rs new file mode 100644 index 00000000000..1aa40f0d492 --- /dev/null +++ b/src/test/run-pass/slice.rs @@ -0,0 +1,70 @@ +// 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. + +// Test slicing sugar. + +extern crate core; +use core::ops::{Slice,SliceMut}; + +static mut COUNT: uint = 0; + +struct Foo; + +impl Slice for Foo { + fn as_slice_<'a>(&'a self) -> &'a Foo { + unsafe { COUNT += 1; } + self + } + fn slice_from_<'a>(&'a self, _from: &Foo) -> &'a Foo { + unsafe { COUNT += 1; } + self + } + fn slice_to_<'a>(&'a self, _to: &Foo) -> &'a Foo { + unsafe { COUNT += 1; } + self + } + fn slice_<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo { + unsafe { COUNT += 1; } + self + } +} + +impl SliceMut for Foo { + fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo { + unsafe { COUNT += 1; } + self + } + fn slice_from_mut_<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo { + unsafe { COUNT += 1; } + self + } + fn slice_to_mut_<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo { + unsafe { COUNT += 1; } + self + } + fn slice_mut_<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo { + unsafe { COUNT += 1; } + self + } +} +fn main() { + let mut x = Foo; + x[]; + x[Foo..]; + x[..Foo]; + x[Foo..Foo]; + x[mut]; + x[mut Foo..]; + x[mut ..Foo]; + x[mut Foo..Foo]; + unsafe { + assert!(COUNT == 8); + } +} \ No newline at end of file -- cgit 1.4.1-3-g733a5 From 5aa264a14fbc386c2cbb1d8f7dc0f0d7c7f1a773 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Thu, 18 Sep 2014 16:25:07 -0700 Subject: libsyntax: Disallow keywords followed by `::`. This breaks code that looked like: mymacro!(static::foo); ... where `mymacro!` expects a path or expression. Change such macros to not accept keywords followed by `::`. Closes #17298. [breaking-change] --- src/libsyntax/parse/token.rs | 83 +++++++++++++--------- .../keywords-followed-by-double-colon.rs | 15 ++++ 2 files changed, 63 insertions(+), 35 deletions(-) create mode 100644 src/test/compile-fail/keywords-followed-by-double-colon.rs (limited to 'src/libsyntax') diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 5a0aeece272..f71190da430 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -431,9 +431,11 @@ macro_rules! declare_special_idents_and_keywords {( // If the special idents get renumbered, remember to modify these two as appropriate pub static SELF_KEYWORD_NAME: Name = Name(SELF_KEYWORD_NAME_NUM); static STATIC_KEYWORD_NAME: Name = Name(STATIC_KEYWORD_NAME_NUM); +static SUPER_KEYWORD_NAME: Name = Name(SUPER_KEYWORD_NAME_NUM); pub static SELF_KEYWORD_NAME_NUM: u32 = 1; static STATIC_KEYWORD_NAME_NUM: u32 = 2; +static SUPER_KEYWORD_NAME_NUM: u32 = 3; // NB: leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max @@ -443,52 +445,53 @@ declare_special_idents_and_keywords! { pub mod special_idents { // These ones are statics (0, invalid, ""); - (super::SELF_KEYWORD_NAME_NUM, self_, "self"); - (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); - (3, static_lifetime, "'static"); + (super::SELF_KEYWORD_NAME_NUM, self_, "self"); + (super::STATIC_KEYWORD_NAME_NUM, statik, "static"); + (super::SUPER_KEYWORD_NAME_NUM, super_, "super"); + (4, static_lifetime, "'static"); // for matcher NTs - (4, tt, "tt"); - (5, matchers, "matchers"); + (5, tt, "tt"); + (6, matchers, "matchers"); // outside of libsyntax - (6, clownshoe_abi, "__rust_abi"); - (7, opaque, ""); - (8, unnamed_field, ""); - (9, type_self, "Self"); - (10, prelude_import, "prelude_import"); + (7, clownshoe_abi, "__rust_abi"); + (8, opaque, ""); + (9, unnamed_field, ""); + (10, type_self, "Self"); + (11, prelude_import, "prelude_import"); } pub mod keywords { // These ones are variants of the Keyword enum 'strict: - (11, As, "as"); - (12, Break, "break"); - (13, Crate, "crate"); - (14, Else, "else"); - (15, Enum, "enum"); - (16, Extern, "extern"); - (17, False, "false"); - (18, Fn, "fn"); - (19, For, "for"); - (20, If, "if"); - (21, Impl, "impl"); - (22, In, "in"); - (23, Let, "let"); - (24, Loop, "loop"); - (25, Match, "match"); - (26, Mod, "mod"); - (27, Mut, "mut"); - (28, Once, "once"); - (29, Pub, "pub"); - (30, Ref, "ref"); - (31, Return, "return"); + (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, Mut, "mut"); + (29, Once, "once"); + (30, Pub, "pub"); + (31, Ref, "ref"); + (32, 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"); - (32, Struct, "struct"); - (33, Super, "super"); + (super::STATIC_KEYWORD_NAME_NUM, Static, "static"); + (super::SELF_KEYWORD_NAME_NUM, Self, "self"); + (33, Struct, "struct"); + (super::SUPER_KEYWORD_NAME_NUM, Super, "super"); (34, True, "true"); (35, Trait, "trait"); (36, Type, "type"); @@ -713,6 +716,7 @@ pub fn is_any_keyword(tok: &Token) -> bool { n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME + || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= RESERVED_KEYWORD_FINAL }, @@ -727,9 +731,18 @@ pub fn is_strict_keyword(tok: &Token) -> bool { n == SELF_KEYWORD_NAME || n == STATIC_KEYWORD_NAME + || n == SUPER_KEYWORD_NAME || STRICT_KEYWORD_START <= n && n <= STRICT_KEYWORD_FINAL }, + token::IDENT(sid, true) => { + let n = sid.name; + + n != SELF_KEYWORD_NAME + && n != SUPER_KEYWORD_NAME + && STRICT_KEYWORD_START <= n + && n <= STRICT_KEYWORD_FINAL + } _ => false, } } diff --git a/src/test/compile-fail/keywords-followed-by-double-colon.rs b/src/test/compile-fail/keywords-followed-by-double-colon.rs new file mode 100644 index 00000000000..f69b041597e --- /dev/null +++ b/src/test/compile-fail/keywords-followed-by-double-colon.rs @@ -0,0 +1,15 @@ +// 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. + +fn main() { + struct::foo(); //~ ERROR expected identifier + mut::baz(); //~ ERROR expected identifier +} + -- cgit 1.4.1-3-g733a5 From 7c00d77e8bd18d2e1873e8e995885b3500a88a0d Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 5 Sep 2014 21:27:47 -0700 Subject: librustc: Implement the syntax in the RFC for unboxed closure sugar. Part of issue #16640. I am leaving this issue open to handle parsing of higher-rank lifetimes in traits. This change breaks code that used unboxed closures: * Instead of `F:|&: int| -> int`, write `F:Fn(int) -> int`. * Instead of `F:|&mut: int| -> int`, write `F:FnMut(int) -> int`. * Instead of `F:|: int| -> int`, write `F:FnOnce(int) -> int`. [breaking-change] --- src/librustc/middle/resolve.rs | 28 ++++++++ src/librustc/middle/typeck/astconv.rs | 28 ++++---- src/librustc/middle/typeck/collect.rs | 42 ++++++++++-- src/libsyntax/ast.rs | 9 ++- src/libsyntax/fold.rs | 24 +++++-- src/libsyntax/parse/parser.rs | 76 ++++++++-------------- src/libsyntax/print/pprust.rs | 49 +++++++------- src/test/compile-fail/borrowck-unboxed-closures.rs | 6 +- .../unboxed-closure-sugar-nonexistent-trait.rs | 18 +++++ .../unboxed-closure-sugar-wrong-trait.rs | 17 +++++ .../compile-fail/unboxed-closures-wrong-trait.rs | 2 +- src/test/run-pass/fn-trait-sugar.rs | 2 +- src/test/run-pass/unboxed-closures-all-traits.rs | 6 +- src/test/run-pass/unboxed-closures-drop.rs | 6 +- .../run-pass/unboxed-closures-single-word-env.rs | 6 +- .../run-pass/unboxed-closures-unique-type-id.rs | 3 +- .../run-pass/where-clauses-unboxed-closures.rs | 2 +- 17 files changed, 207 insertions(+), 117 deletions(-) create mode 100644 src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs create mode 100644 src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs (limited to 'src/libsyntax') diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 6fa33f4b5aa..15564f7bc53 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -4328,6 +4328,34 @@ impl<'a> Resolver<'a> { self.resolve_trait_reference(id, tref, reference_type) } UnboxedFnTyParamBound(ref unboxed_function) => { + match self.resolve_path(unboxed_function.ref_id, + &unboxed_function.path, + TypeNS, + true) { + None => { + let path_str = self.path_idents_to_string( + &unboxed_function.path); + self.resolve_error(unboxed_function.path.span, + format!("unresolved trait `{}`", + path_str).as_slice()) + } + Some(def) => { + match def { + (DefTrait(_), _) => { + self.record_def(unboxed_function.ref_id, def); + } + _ => { + let msg = + format!("`{}` is not a trait", + self.path_idents_to_string( + &unboxed_function.path)); + self.resolve_error(unboxed_function.path.span, + msg.as_slice()); + } + } + } + } + for argument in unboxed_function.decl.inputs.iter() { self.resolve_type(&*argument.ty); } diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 8f60be8f7fb..2503fb2541b 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -585,32 +585,29 @@ pub fn trait_ref_for_unboxed_function<'tcx, AC: AstConv<'tcx>, RS:RegionScope>( this: &AC, rscope: &RS, - unboxed_function: &ast::UnboxedFnTy, + kind: ast::UnboxedClosureKind, + decl: &ast::FnDecl, self_ty: Option) -> ty::TraitRef { - let lang_item = match unboxed_function.kind { + let lang_item = match kind { ast::FnUnboxedClosureKind => FnTraitLangItem, ast::FnMutUnboxedClosureKind => FnMutTraitLangItem, ast::FnOnceUnboxedClosureKind => FnOnceTraitLangItem, }; let trait_did = this.tcx().lang_items.require(lang_item).unwrap(); - let input_types = - unboxed_function.decl - .inputs - .iter() - .map(|input| { + let input_types = decl.inputs + .iter() + .map(|input| { ast_ty_to_ty(this, rscope, &*input.ty) - }).collect::>(); + }).collect::>(); let input_tuple = if input_types.len() == 0 { ty::mk_nil() } else { ty::mk_tup(this.tcx(), input_types) }; - let output_type = ast_ty_to_ty(this, - rscope, - &*unboxed_function.decl.output); + let output_type = ast_ty_to_ty(this, rscope, &*decl.output); let mut substs = Substs::new_type(vec!(input_tuple, output_type), - Vec::new()); + Vec::new()); match self_ty { Some(s) => substs.types.push(SelfSpace, s), @@ -648,7 +645,8 @@ fn mk_pointer<'tcx, AC: AstConv<'tcx>, RS: RegionScope>( substs } = trait_ref_for_unboxed_function(this, rscope, - &**unboxed_function, + unboxed_function.kind, + &*unboxed_function.decl, None); let r = ptr_ty.default_region(); let tr = ty::mk_trait(this.tcx(), @@ -1510,7 +1508,7 @@ fn compute_region_bound<'tcx, AC: AstConv<'tcx>, RS:RegionScope>( pub struct PartitionedBounds<'a> { pub builtin_bounds: ty::BuiltinBounds, pub trait_bounds: Vec<&'a ast::TraitRef>, - pub unboxed_fn_ty_bounds: Vec<&'a ast::UnboxedFnTy>, + pub unboxed_fn_ty_bounds: Vec<&'a ast::UnboxedFnBound>, pub region_bounds: Vec<&'a ast::Lifetime>, } @@ -1574,7 +1572,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, region_bounds.push(l); } ast::UnboxedFnTyParamBound(ref unboxed_function) => { - unboxed_fn_ty_bounds.push(unboxed_function); + unboxed_fn_ty_bounds.push(&**unboxed_function); } } } diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index b7aa7656ae9..40c52fd36b9 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -1427,7 +1427,8 @@ pub fn instantiate_unboxed_fn_ty<'tcx,AC>(this: &AC, let param_ty = param_ty.to_ty(this.tcx()); Rc::new(astconv::trait_ref_for_unboxed_function(this, &rscope, - unboxed_function, + unboxed_function.kind, + &*unboxed_function.decl, Some(param_ty))) } @@ -2165,9 +2166,42 @@ fn conv_param_bounds<'tcx,AC>(this: &AC, region_bounds, unboxed_fn_ty_bounds } = astconv::partition_bounds(this.tcx(), span, all_bounds.as_slice()); - let unboxed_fn_ty_bounds = - unboxed_fn_ty_bounds.into_iter() - .map(|b| instantiate_unboxed_fn_ty(this, b, param_ty)); + + let unboxed_fn_ty_bounds = unboxed_fn_ty_bounds.move_iter().map(|b| { + let trait_id = this.tcx().def_map.borrow().get(&b.ref_id).def_id(); + let mut kind = None; + for &(lang_item, this_kind) in [ + (this.tcx().lang_items.fn_trait(), ast::FnUnboxedClosureKind), + (this.tcx().lang_items.fn_mut_trait(), + ast::FnMutUnboxedClosureKind), + (this.tcx().lang_items.fn_once_trait(), + ast::FnOnceUnboxedClosureKind) + ].iter() { + if Some(trait_id) == lang_item { + kind = Some(this_kind); + break + } + } + + let kind = match kind { + Some(kind) => kind, + None => { + this.tcx().sess.span_err(b.path.span, + "unboxed function trait must be one \ + of `Fn`, `FnMut`, or `FnOnce`"); + ast::FnMutUnboxedClosureKind + } + }; + + let rscope = ExplicitRscope; + let param_ty = param_ty.to_ty(this.tcx()); + Rc::new(astconv::trait_ref_for_unboxed_function(this, + &rscope, + kind, + &*b.decl, + Some(param_ty))) + }); + let trait_bounds: Vec> = trait_bounds.into_iter() .map(|b| { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index eac158e664c..e74222fac09 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -213,12 +213,19 @@ pub static DUMMY_NODE_ID: NodeId = -1; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub enum TyParamBound { TraitTyParamBound(TraitRef), - UnboxedFnTyParamBound(UnboxedFnTy), + UnboxedFnTyParamBound(P), RegionTyParamBound(Lifetime) } pub type TyParamBounds = OwnedSlice; +#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] +pub struct UnboxedFnBound { + pub path: Path, + pub decl: P, + pub ref_id: NodeId, +} + #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)] pub struct TyParam { pub ident: Ident, diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 3beba5bcda4..1441f5beb6a 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -657,16 +657,26 @@ pub fn noop_fold_fn_decl(decl: P, fld: &mut T) -> P { }) } -pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) - -> TyParamBound { +pub fn noop_fold_ty_param_bound(tpb: TyParamBound, fld: &mut T) + -> TyParamBound + where T: Folder { match tpb { TraitTyParamBound(ty) => TraitTyParamBound(fld.fold_trait_ref(ty)), RegionTyParamBound(lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)), - UnboxedFnTyParamBound(UnboxedFnTy {decl, kind}) => { - UnboxedFnTyParamBound(UnboxedFnTy { - decl: fld.fold_fn_decl(decl), - kind: kind, - }) + UnboxedFnTyParamBound(bound) => { + match *bound { + UnboxedFnBound { + ref path, + ref decl, + ref_id + } => { + UnboxedFnTyParamBound(P(UnboxedFnBound { + path: fld.fold_path(path.clone()), + decl: fld.fold_fn_decl(decl.clone()), + ref_id: fld.new_id(ref_id), + })) + } + } } } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ff4fd41fbd7..8a0027e5c06 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -55,7 +55,8 @@ use ast::{TyTypeof, TyInfer, TypeMethod}; use ast::{TyNil, TyParam, TyParamBound, TyParen, TyPath, TyPtr, TyQPath}; use ast::{TyRptr, TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq}; use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind}; -use ast::{UnboxedFnTy, UnboxedFnTyParamBound, UnnamedField, UnsafeBlock}; +use ast::{UnboxedFnBound, UnboxedFnTy, UnboxedFnTyParamBound}; +use ast::{UnnamedField, UnsafeBlock}; use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse}; use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple}; use ast::{Visibility, WhereClause, WherePredicate}; @@ -3666,39 +3667,6 @@ impl<'a> Parser<'a> { }) } - fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy { - let (optional_unboxed_closure_kind, inputs) = - if self.eat(&token::OROR) { - (None, Vec::new()) - } else { - self.expect_or(); - - let optional_unboxed_closure_kind = - self.parse_optional_unboxed_closure_kind(); - - let inputs = self.parse_seq_to_before_or(&token::COMMA, - |p| { - p.parse_arg_general(false) - }); - self.expect_or(); - (optional_unboxed_closure_kind, inputs) - }; - - let (return_style, output) = self.parse_ret_ty(); - UnboxedFnTy { - decl: P(FnDecl { - inputs: inputs, - output: output, - cf: return_style, - variadic: false, - }), - kind: match optional_unboxed_closure_kind { - Some(kind) => kind, - None => FnMutUnboxedClosureKind, - }, - } - } - // Parses a sequence of bounds if a `:` is found, // otherwise returns empty list. fn parse_colon_then_ty_param_bounds(&mut self) @@ -3730,13 +3698,31 @@ impl<'a> Parser<'a> { self.bump(); } token::MOD_SEP | token::IDENT(..) => { - let tref = self.parse_trait_ref(); - result.push(TraitTyParamBound(tref)); - } - token::BINOP(token::OR) | token::OROR => { - let unboxed_function_type = - self.parse_unboxed_function_type(); - result.push(UnboxedFnTyParamBound(unboxed_function_type)); + let path = + self.parse_path(LifetimeAndTypesWithoutColons).path; + if self.token == token::LPAREN { + self.bump(); + let inputs = self.parse_seq_to_end( + &token::RPAREN, + seq_sep_trailing_allowed(token::COMMA), + |p| p.parse_arg_general(false)); + let (return_style, output) = self.parse_ret_ty(); + result.push(UnboxedFnTyParamBound(P(UnboxedFnBound { + path: path, + decl: P(FnDecl { + inputs: inputs, + output: output, + cf: return_style, + variadic: false, + }), + ref_id: ast::DUMMY_NODE_ID, + }))); + } else { + result.push(TraitTyParamBound(ast::TraitRef { + path: path, + ref_id: ast::DUMMY_NODE_ID, + })) + } } _ => break, } @@ -4423,14 +4409,6 @@ impl<'a> Parser<'a> { Some(attrs)) } - /// Parse a::B - fn parse_trait_ref(&mut self) -> TraitRef { - ast::TraitRef { - path: self.parse_path(LifetimeAndTypesWithoutColons).path, - ref_id: ast::DUMMY_NODE_ID, - } - } - /// Parse struct Foo { ... } fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo { let class_name = self.parse_ident(); diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 0ae5303641b..d7dd87a096e 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2190,16 +2190,13 @@ impl<'a> State<'a> { self.print_lifetime(lt) } UnboxedFnTyParamBound(ref unboxed_function_type) => { - self.print_ty_fn(None, - None, - ast::NormalFn, - ast::Many, - &*unboxed_function_type.decl, - None, - &OwnedSlice::empty(), - None, - None, - Some(unboxed_function_type.kind)) + try!(self.print_path(&unboxed_function_type.path, + false)); + try!(self.popen()); + try!(self.print_fn_args(&*unboxed_function_type.decl, + None)); + try!(self.pclose()); + self.print_fn_output(&*unboxed_function_type.decl) } }) } @@ -2430,6 +2427,23 @@ impl<'a> State<'a> { self.end() } + pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> { + match decl.output.node { + ast::TyNil => Ok(()), + _ => { + try!(self.space_if_not_bol()); + try!(self.ibox(indent_unit)); + try!(self.word_space("->")); + if decl.cf == ast::NoReturn { + try!(self.word_nbsp("!")); + } else { + try!(self.print_type(&*decl.output)); + } + self.end() + } + } + } + pub fn print_ty_fn(&mut self, opt_abi: Option, opt_sigil: Option, @@ -2510,20 +2524,7 @@ impl<'a> State<'a> { try!(self.maybe_print_comment(decl.output.span.lo)); - match decl.output.node { - ast::TyNil => {} - _ => { - try!(self.space_if_not_bol()); - try!(self.ibox(indent_unit)); - try!(self.word_space("->")); - if decl.cf == ast::NoReturn { - try!(self.word_nbsp("!")); - } else { - try!(self.print_type(&*decl.output)); - } - try!(self.end()); - } - } + try!(self.print_fn_output(decl)); match generics { Some(generics) => try!(self.print_where_clause(generics)), diff --git a/src/test/compile-fail/borrowck-unboxed-closures.rs b/src/test/compile-fail/borrowck-unboxed-closures.rs index d822bb22e2a..03438b1d7e1 100644 --- a/src/test/compile-fail/borrowck-unboxed-closures.rs +++ b/src/test/compile-fail/borrowck-unboxed-closures.rs @@ -10,17 +10,17 @@ #![feature(overloaded_calls)] -fn a int>(mut f: F) { +fn a int>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } -fn b int>(f: F) { +fn b int>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable argument } -fn c int>(f: F) { +fn c int>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } diff --git a/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs b/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs new file mode 100644 index 00000000000..f51160a1b23 --- /dev/null +++ b/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs @@ -0,0 +1,18 @@ +// 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. + +fn f int>(x: F) {} //~ ERROR unresolved trait + +type Typedef = int; + +fn g int>(x: F) {} //~ ERROR `Typedef` is not a trait + +fn main() {} + diff --git a/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs b/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs new file mode 100644 index 00000000000..a751ae1c518 --- /dev/null +++ b/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs @@ -0,0 +1,17 @@ +// 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. + +trait Trait {} + +fn f int>(x: F) {} +//~^ ERROR unboxed function trait must be one of `Fn`, `FnMut`, or `FnOnce` + +fn main() {} + diff --git a/src/test/compile-fail/unboxed-closures-wrong-trait.rs b/src/test/compile-fail/unboxed-closures-wrong-trait.rs index 27f1da75c3a..97ad64a77ba 100644 --- a/src/test/compile-fail/unboxed-closures-wrong-trait.rs +++ b/src/test/compile-fail/unboxed-closures-wrong-trait.rs @@ -10,7 +10,7 @@ #![feature(lang_items, overloaded_calls, unboxed_closures)] -fn c int>(f: F) -> int { +fn c int>(f: F) -> int { f(5, 6) } diff --git a/src/test/run-pass/fn-trait-sugar.rs b/src/test/run-pass/fn-trait-sugar.rs index ccb5634f7a2..b0947f46a86 100644 --- a/src/test/run-pass/fn-trait-sugar.rs +++ b/src/test/run-pass/fn-trait-sugar.rs @@ -21,7 +21,7 @@ impl FnMut<(int,),int> for S { } } -fn call_itint>(mut f: F, x: int) -> int { +fn call_itint>(mut f: F, x: int) -> int { f.call_mut((x,)) + 3 } diff --git a/src/test/run-pass/unboxed-closures-all-traits.rs b/src/test/run-pass/unboxed-closures-all-traits.rs index c362a83e60c..d9120495155 100644 --- a/src/test/run-pass/unboxed-closures-all-traits.rs +++ b/src/test/run-pass/unboxed-closures-all-traits.rs @@ -10,15 +10,15 @@ #![feature(lang_items, overloaded_calls, unboxed_closures)] -fn a int>(f: F) -> int { +fn a int>(f: F) -> int { f(1, 2) } -fn b int>(mut f: F) -> int { +fn b int>(mut f: F) -> int { f(3, 4) } -fn c int>(f: F) -> int { +fn c int>(f: F) -> int { f(5, 6) } diff --git a/src/test/run-pass/unboxed-closures-drop.rs b/src/test/run-pass/unboxed-closures-drop.rs index f20dddcae54..a455e4d2032 100644 --- a/src/test/run-pass/unboxed-closures-drop.rs +++ b/src/test/run-pass/unboxed-closures-drop.rs @@ -41,15 +41,15 @@ impl Drop for Droppable { } } -fn a int>(f: F) -> int { +fn a int>(f: F) -> int { f(1, 2) } -fn b int>(mut f: F) -> int { +fn b int>(mut f: F) -> int { f(3, 4) } -fn c int>(f: F) -> int { +fn c int>(f: F) -> int { f(5, 6) } diff --git a/src/test/run-pass/unboxed-closures-single-word-env.rs b/src/test/run-pass/unboxed-closures-single-word-env.rs index 754b1f70644..aef6956118e 100644 --- a/src/test/run-pass/unboxed-closures-single-word-env.rs +++ b/src/test/run-pass/unboxed-closures-single-word-env.rs @@ -13,15 +13,15 @@ #![feature(overloaded_calls, unboxed_closures)] -fn a int>(f: F) -> int { +fn a int>(f: F) -> int { f(1, 2) } -fn b int>(mut f: F) -> int { +fn b int>(mut f: F) -> int { f(3, 4) } -fn c int>(f: F) -> int { +fn c int>(f: F) -> int { f(5, 6) } diff --git a/src/test/run-pass/unboxed-closures-unique-type-id.rs b/src/test/run-pass/unboxed-closures-unique-type-id.rs index 55d89d4e4f6..f35daa65a43 100644 --- a/src/test/run-pass/unboxed-closures-unique-type-id.rs +++ b/src/test/run-pass/unboxed-closures-unique-type-id.rs @@ -21,8 +21,7 @@ use std::ptr; -pub fn replace_map<'a, T, F>(src: &mut T, prod: F) -where F: |: T| -> T { +pub fn replace_map<'a, T, F>(src: &mut T, prod: F) where F: FnOnce(T) -> T { unsafe { *src = prod(ptr::read(src as *mut T as *const T)); } } diff --git a/src/test/run-pass/where-clauses-unboxed-closures.rs b/src/test/run-pass/where-clauses-unboxed-closures.rs index ae005b4ae53..808e937bc72 100644 --- a/src/test/run-pass/where-clauses-unboxed-closures.rs +++ b/src/test/run-pass/where-clauses-unboxed-closures.rs @@ -13,7 +13,7 @@ struct Bencher; // ICE -fn warm_up<'a, F>(f: F) where F: |&: &'a mut Bencher| { +fn warm_up<'a, F>(f: F) where F: Fn(&'a mut Bencher) { } fn main() { -- cgit 1.4.1-3-g733a5 From ce0907e46e8e1aa23ee39f69e4f628f68bfbb0d7 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Thu, 11 Sep 2014 17:07:49 +1200 Subject: Add enum variants to the type namespace Change to resolve and update compiler and libs for uses. [breaking-change] Enum variants are now in both the value and type namespaces. This means that if you have a variant with the same name as a type in scope in a module, you will get a name clash and thus an error. The solution is to either rename the type or the variant. --- src/libcollections/string.rs | 6 +- src/libfmt_macros/lib.rs | 37 +++++---- src/libnative/io/net.rs | 8 +- src/libnum/bigint.rs | 62 +++++++------- src/libregex/compile.rs | 4 +- src/libregex/lib.rs | 2 +- src/libregex/parse.rs | 26 +++--- src/libregex/re.rs | 22 ++--- src/libregex_macros/lib.rs | 6 +- src/librustc/back/write.rs | 8 +- src/librustc/driver/config.rs | 10 +-- src/librustc/lint/builtin.rs | 6 +- src/librustc/middle/astencode.rs | 36 ++++---- src/librustc/middle/borrowck/mod.rs | 4 +- src/librustc/middle/dead.rs | 4 +- src/librustc/middle/expr_use_visitor.rs | 11 +-- src/librustc/middle/kind.rs | 1 + src/librustc/middle/liveness.rs | 11 +-- src/librustc/middle/mem_categorization.rs | 6 +- src/librustc/middle/privacy.rs | 8 +- src/librustc/middle/resolve.rs | 36 ++++---- src/librustc/middle/save/mod.rs | 4 +- src/librustc/middle/traits/fulfill.rs | 10 +-- src/librustc/middle/traits/mod.rs | 30 +++---- src/librustc/middle/traits/select.rs | 15 ++-- src/librustc/middle/traits/util.rs | 22 ++--- src/librustc/middle/trans/consts.rs | 6 +- src/librustc/middle/trans/debuginfo.rs | 12 +-- src/librustc/middle/trans/expr.rs | 6 +- src/librustc/middle/trans/meth.rs | 8 +- src/librustc/middle/ty.rs | 18 ++-- src/librustc/middle/ty_fold.rs | 12 +-- src/librustc/middle/typeck/check/method.rs | 28 +++---- src/librustc/middle/typeck/check/mod.rs | 6 +- src/librustc/middle/typeck/check/regionck.rs | 2 +- src/librustc/middle/typeck/check/vtable2.rs | 6 +- src/librustc/middle/typeck/check/writeback.rs | 8 +- src/librustc/middle/typeck/infer/coercion.rs | 18 ++-- src/librustc/middle/typeck/mod.rs | 4 +- src/librustc/plugin/registry.rs | 6 +- src/librustc/util/ppaux.rs | 4 +- src/librustc_llvm/lib.rs | 6 +- src/librustdoc/clean/mod.rs | 38 ++++----- src/librustdoc/fold.rs | 4 +- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/render.rs | 10 +-- src/librustdoc/stability_summary.rs | 4 +- src/librustrt/local_data.rs | 62 +++++++------- src/libserialize/json.rs | 105 ++++++++++++------------ src/libstd/macros.rs | 4 +- src/libsyntax/ext/base.rs | 6 +- src/libsyntax/ext/expand.rs | 6 +- src/libsyntax/ext/format.rs | 33 ++++---- src/libsyntax/print/pp.rs | 10 +-- src/libterm/terminfo/parm.rs | 22 ++--- src/test/auxiliary/macro_crate_test.rs | 2 +- src/test/auxiliary/xcrate_unit_struct.rs | 2 +- src/test/compile-fail/enum-variant-type-2.rs | 19 +++++ src/test/compile-fail/enum-variant-type.rs | 23 ++++++ src/test/compile-fail/issue-3008-1.rs | 2 +- src/test/compile-fail/issue-3008-2.rs | 2 +- src/test/compile-fail/recursion.rs | 4 +- src/test/pretty/tag-blank-lines.rs | 4 +- src/test/run-fail/issue-2444.rs | 2 +- src/test/run-pass/borrowck-univariant-enum.rs | 6 +- src/test/run-pass/coerce-to-closure-and-proc.rs | 10 +-- src/test/run-pass/issue-2804.rs | 2 +- src/test/run-pass/issue-3186.rs | 15 ---- src/test/run-pass/issue-3874.rs | 4 +- src/test/run-pass/match-arm-statics.rs | 6 +- src/test/run-pass/tag-align-shape.rs | 6 +- src/test/run-pass/tag-align-u64.rs | 4 +- src/test/run-pass/xcrate-unit-struct.rs | 4 +- 73 files changed, 500 insertions(+), 468 deletions(-) create mode 100644 src/test/compile-fail/enum-variant-type-2.rs create mode 100644 src/test/compile-fail/enum-variant-type.rs delete mode 100644 src/test/run-pass/issue-3186.rs (limited to 'src/libsyntax') diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 05d91a75041..a12d403603f 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -872,7 +872,7 @@ mod tests { use {Mutable, MutableSeq}; use str; - use str::{Str, StrSlice, Owned, Slice}; + use str::{Str, StrSlice, Owned}; use super::String; use vec::Vec; @@ -898,10 +898,10 @@ mod tests { #[test] fn test_from_utf8_lossy() { let xs = b"hello"; - assert_eq!(String::from_utf8_lossy(xs), Slice("hello")); + assert_eq!(String::from_utf8_lossy(xs), str::Slice("hello")); let xs = "ศไทย中华Việt Nam".as_bytes(); - assert_eq!(String::from_utf8_lossy(xs), Slice("ศไทย中华Việt Nam")); + assert_eq!(String::from_utf8_lossy(xs), str::Slice("ศไทย中华Việt Nam")); let xs = b"Hello\xC2 There\xFF Goodbye"; assert_eq!(String::from_utf8_lossy(xs), diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 9272369f73c..a9f34e1195c 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -23,6 +23,7 @@ use std::char; use std::str; +use std::string; /// A piece is a portion of the format string which represents the next part /// to emit. These are emitted as a stream by the `Parser` class. @@ -32,7 +33,7 @@ pub enum Piece<'a> { String(&'a str), /// This describes that formatting should process the next argument (as /// specified inside) for emission. - Argument(Argument<'a>), + NextArgument(Argument<'a>), } /// Representation of an argument specification. @@ -129,7 +130,7 @@ pub struct Parser<'a> { input: &'a str, cur: str::CharOffsets<'a>, /// Error messages accumulated during parsing - pub errors: Vec, + pub errors: Vec, } impl<'a> Iterator> for Parser<'a> { @@ -140,7 +141,7 @@ impl<'a> Iterator> for Parser<'a> { if self.consume('{') { Some(String(self.string(pos + 1))) } else { - let ret = Some(Argument(self.argument())); + let ret = Some(NextArgument(self.argument())); self.must_consume('}'); ret } @@ -469,28 +470,28 @@ mod tests { #[test] fn format_nothing() { - same("{}", [Argument(Argument { + same("{}", [NextArgument(Argument { position: ArgumentNext, format: fmtdflt(), })]); } #[test] fn format_position() { - same("{3}", [Argument(Argument { + same("{3}", [NextArgument(Argument { position: ArgumentIs(3), format: fmtdflt(), })]); } #[test] fn format_position_nothing_else() { - same("{3:}", [Argument(Argument { + same("{3:}", [NextArgument(Argument { position: ArgumentIs(3), format: fmtdflt(), })]); } #[test] fn format_type() { - same("{3:a}", [Argument(Argument { + same("{3:a}", [NextArgument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: None, @@ -504,7 +505,7 @@ mod tests { } #[test] fn format_align_fill() { - same("{3:>}", [Argument(Argument { + same("{3:>}", [NextArgument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: None, @@ -515,7 +516,7 @@ mod tests { ty: "", }, })]); - same("{3:0<}", [Argument(Argument { + same("{3:0<}", [NextArgument(Argument { position: ArgumentIs(3), format: FormatSpec { fill: Some('0'), @@ -526,7 +527,7 @@ mod tests { ty: "", }, })]); - same("{3:* u16 { } enum InAddr { - InAddr(libc::in_addr), + In4Addr(libc::in_addr), In6Addr(libc::in6_addr), } @@ -48,7 +48,7 @@ fn ip_to_inaddr(ip: rtio::IpAddr) -> InAddr { (b as u32 << 16) | (c as u32 << 8) | (d as u32 << 0); - InAddr(libc::in_addr { + In4Addr(libc::in_addr { s_addr: Int::from_be(ip) }) } @@ -74,7 +74,7 @@ fn addr_to_sockaddr(addr: rtio::SocketAddr, -> libc::socklen_t { unsafe { let len = match ip_to_inaddr(addr.ip) { - InAddr(inaddr) => { + In4Addr(inaddr) => { let storage = storage as *mut _ as *mut libc::sockaddr_in; (*storage).sin_family = libc::AF_INET as libc::sa_family_t; (*storage).sin_port = htons(addr.port); @@ -723,7 +723,7 @@ impl UdpSocket { pub fn set_membership(&mut self, addr: rtio::IpAddr, opt: libc::c_int) -> IoResult<()> { match ip_to_inaddr(addr) { - InAddr(addr) => { + In4Addr(addr) => { let mreq = libc::ip_mreq { imr_multiaddr: addr, // interface == INADDR_ANY diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 3f91ce11915..efa3402073f 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -618,7 +618,7 @@ impl ToBigUint for BigInt { fn to_biguint(&self) -> Option { if self.sign == Plus { Some(self.data.clone()) - } else if self.sign == Zero { + } else if self.sign == NoSign { Some(Zero::zero()) } else { None @@ -838,7 +838,7 @@ fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) { /// A Sign is a `BigInt`'s composing element. #[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)] -pub enum Sign { Minus, Zero, Plus } +pub enum Sign { Minus, NoSign, Plus } impl Neg for Sign { /// Negate Sign value. @@ -846,7 +846,7 @@ impl Neg for Sign { fn neg(&self) -> Sign { match *self { Minus => Plus, - Zero => Zero, + NoSign => NoSign, Plus => Minus } } @@ -882,7 +882,7 @@ impl Ord for BigInt { if scmp != Equal { return scmp; } match self.sign { - Zero => Equal, + NoSign => Equal, Plus => self.data.cmp(&other.data), Minus => other.data.cmp(&self.data), } @@ -933,11 +933,11 @@ impl Shr for BigInt { impl Zero for BigInt { #[inline] fn zero() -> BigInt { - BigInt::from_biguint(Zero, Zero::zero()) + BigInt::from_biguint(NoSign, Zero::zero()) } #[inline] - fn is_zero(&self) -> bool { self.sign == Zero } + fn is_zero(&self) -> bool { self.sign == NoSign } } impl One for BigInt { @@ -951,7 +951,7 @@ impl Signed for BigInt { #[inline] fn abs(&self) -> BigInt { match self.sign { - Plus | Zero => self.clone(), + Plus | NoSign => self.clone(), Minus => BigInt::from_biguint(Plus, self.data.clone()) } } @@ -966,7 +966,7 @@ impl Signed for BigInt { match self.sign { Plus => BigInt::from_biguint(Plus, One::one()), Minus => BigInt::from_biguint(Minus, One::one()), - Zero => Zero::zero(), + NoSign => Zero::zero(), } } @@ -981,8 +981,8 @@ impl Add for BigInt { #[inline] fn add(&self, other: &BigInt) -> BigInt { match (self.sign, other.sign) { - (Zero, _) => other.clone(), - (_, Zero) => self.clone(), + (NoSign, _) => other.clone(), + (_, NoSign) => self.clone(), (Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data), (Plus, Minus) => self - (-*other), (Minus, Plus) => other - (-*self), @@ -995,8 +995,8 @@ impl Sub for BigInt { #[inline] fn sub(&self, other: &BigInt) -> BigInt { match (self.sign, other.sign) { - (Zero, _) => -other, - (_, Zero) => self.clone(), + (NoSign, _) => -other, + (_, NoSign) => self.clone(), (Plus, Plus) => match self.data.cmp(&other.data) { Less => BigInt::from_biguint(Minus, other.data - self.data), Greater => BigInt::from_biguint(Plus, self.data - other.data), @@ -1013,7 +1013,7 @@ impl Mul for BigInt { #[inline] fn mul(&self, other: &BigInt) -> BigInt { match (self.sign, other.sign) { - (Zero, _) | (_, Zero) => Zero::zero(), + (NoSign, _) | (_, NoSign) => Zero::zero(), (Plus, Plus) | (Minus, Minus) => { BigInt::from_biguint(Plus, self.data * other.data) }, @@ -1087,9 +1087,9 @@ impl Integer for BigInt { let d = BigInt::from_biguint(Plus, d_ui); let r = BigInt::from_biguint(Plus, r_ui); match (self.sign, other.sign) { - (_, Zero) => fail!(), - (Plus, Plus) | (Zero, Plus) => ( d, r), - (Plus, Minus) | (Zero, Minus) => (-d, r), + (_, NoSign) => fail!(), + (Plus, Plus) | (NoSign, Plus) => ( d, r), + (Plus, Minus) | (NoSign, Minus) => (-d, r), (Minus, Plus) => (-d, -r), (Minus, Minus) => ( d, -r) } @@ -1113,9 +1113,9 @@ impl Integer for BigInt { let d = BigInt::from_biguint(Plus, d_ui); let m = BigInt::from_biguint(Plus, m_ui); match (self.sign, other.sign) { - (_, Zero) => fail!(), - (Plus, Plus) | (Zero, Plus) => (d, m), - (Plus, Minus) | (Zero, Minus) => if m.is_zero() { + (_, NoSign) => fail!(), + (Plus, Plus) | (NoSign, Plus) => (d, m), + (Plus, Minus) | (NoSign, Minus) => if m.is_zero() { (-d, Zero::zero()) } else { (-d - One::one(), m + *other) @@ -1166,7 +1166,7 @@ impl ToPrimitive for BigInt { fn to_i64(&self) -> Option { match self.sign { Plus => self.data.to_i64(), - Zero => Some(0), + NoSign => Some(0), Minus => { self.data.to_u64().and_then(|n| { let m: u64 = 1 << 63; @@ -1186,7 +1186,7 @@ impl ToPrimitive for BigInt { fn to_u64(&self) -> Option { match self.sign { Plus => self.data.to_u64(), - Zero => Some(0), + NoSign => Some(0), Minus => None } } @@ -1272,7 +1272,7 @@ impl ToStrRadix for BigInt { fn to_str_radix(&self, radix: uint) -> String { match self.sign { Plus => self.data.to_str_radix(radix), - Zero => "0".to_string(), + NoSign => "0".to_string(), Minus => format!("-{}", self.data.to_str_radix(radix)), } } @@ -1334,7 +1334,7 @@ impl RandBigInt for R { if self.gen() { return self.gen_bigint(bit_size); } else { - Zero + NoSign } } else if self.gen() { Plus @@ -1385,8 +1385,8 @@ impl BigInt { /// The digits are be in base 2^32. #[inline] pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt { - if sign == Zero || data.is_zero() { - return BigInt { sign: Zero, data: Zero::zero() }; + if sign == NoSign || data.is_zero() { + return BigInt { sign: NoSign, data: Zero::zero() }; } BigInt { sign: sign, data: data } } @@ -1415,7 +1415,7 @@ impl BigInt { pub fn to_biguint(&self) -> Option { match self.sign { Plus => Some(self.data.clone()), - Zero => Some(Zero::zero()), + NoSign => Some(Zero::zero()), Minus => None } } @@ -2288,7 +2288,7 @@ mod biguint_tests { mod bigint_tests { use Integer; use super::{BigDigit, BigUint, ToBigUint}; - use super::{Sign, Minus, Zero, Plus, BigInt, RandBigInt, ToBigInt}; + use super::{Sign, Minus, NoSign, Plus, BigInt, RandBigInt, ToBigInt}; use std::cmp::{Less, Equal, Greater}; use std::i64; @@ -2307,9 +2307,9 @@ mod bigint_tests { assert_eq!(inp, ans); } check(Plus, 1, Plus, 1); - check(Plus, 0, Zero, 0); + check(Plus, 0, NoSign, 0); check(Minus, 1, Minus, 1); - check(Zero, 1, Zero, 0); + check(NoSign, 1, NoSign, 0); } #[test] @@ -2357,8 +2357,8 @@ mod bigint_tests { #[test] fn test_hash() { - let a = BigInt::new(Zero, vec!()); - let b = BigInt::new(Zero, vec!(0)); + let a = BigInt::new(NoSign, vec!()); + let b = BigInt::new(NoSign, vec!(0)); let c = BigInt::new(Plus, vec!(1)); let d = BigInt::new(Plus, vec!(1,0,0,0,0,0)); let e = BigInt::new(Plus, vec!(0,0,0,0,0,1)); diff --git a/src/libregex/compile.rs b/src/libregex/compile.rs index 869dd25e3fa..c4b517c5259 100644 --- a/src/libregex/compile.rs +++ b/src/libregex/compile.rs @@ -16,7 +16,7 @@ use std::cmp; use parse; use parse::{ Flags, FLAG_EMPTY, - Nothing, Literal, Dot, Class, Begin, End, WordBoundary, Capture, Cat, Alt, + Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt, Rep, ZeroOne, ZeroMore, OneMore, }; @@ -148,7 +148,7 @@ impl<'r> Compiler<'r> { Nothing => {}, Literal(c, flags) => self.push(OneChar(c, flags)), Dot(nl) => self.push(Any(nl)), - Class(ranges, flags) => + AstClass(ranges, flags) => self.push(CharClass(ranges, flags)), Begin(flags) => self.push(EmptyBegin(flags)), End(flags) => self.push(EmptyEnd(flags)), diff --git a/src/libregex/lib.rs b/src/libregex/lib.rs index 4f849a8a67b..9ff65fe3e2a 100644 --- a/src/libregex/lib.rs +++ b/src/libregex/lib.rs @@ -425,7 +425,7 @@ pub mod native { FLAG_EMPTY, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_SWAP_GREED, FLAG_NEGATED, }; - pub use re::{Dynamic, Native}; + pub use re::{Dynamic, ExDynamic, Native, ExNative}; pub use vm::{ MatchKind, Exists, Location, Submatches, StepState, StepMatchEarlyReturn, StepMatch, StepContinue, diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 12555b7c443..ad60829c088 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -53,7 +53,7 @@ pub enum Ast { Nothing, Literal(char, Flags), Dot(Flags), - Class(Vec<(char, char)>, Flags), + AstClass(Vec<(char, char)>, Flags), Begin(Flags), End(Flags), WordBoundary(Flags), @@ -101,7 +101,7 @@ impl Greed { /// state. #[deriving(Show)] enum BuildAst { - Ast(Ast), + Expr(Ast), Paren(Flags, uint, String), // '(' Bar, // '|' } @@ -152,7 +152,7 @@ impl BuildAst { fn unwrap(self) -> Result { match self { - Ast(x) => Ok(x), + Expr(x) => Ok(x), _ => fail!("Tried to unwrap non-AST item: {}", self), } } @@ -311,7 +311,7 @@ impl<'a> Parser<'a> { } fn push(&mut self, ast: Ast) { - self.stack.push(Ast(ast)) + self.stack.push(Expr(ast)) } fn push_repeater(&mut self, c: char) -> Result<(), Error> { @@ -388,8 +388,8 @@ impl<'a> Parser<'a> { match c { '[' => match self.try_parse_ascii() { - Some(Class(asciis, flags)) => { - alts.push(Class(asciis, flags ^ negated)); + Some(AstClass(asciis, flags)) => { + alts.push(AstClass(asciis, flags ^ negated)); continue } Some(ast) => @@ -399,8 +399,8 @@ impl<'a> Parser<'a> { }, '\\' => { match try!(self.parse_escape()) { - Class(asciis, flags) => { - alts.push(Class(asciis, flags ^ negated)); + AstClass(asciis, flags) => { + alts.push(AstClass(asciis, flags ^ negated)); continue } Literal(c2, _) => c = c2, // process below @@ -417,7 +417,7 @@ impl<'a> Parser<'a> { ']' => { if ranges.len() > 0 { let flags = negated | (self.flags & FLAG_NOCASE); - let mut ast = Class(combine_ranges(ranges), flags); + let mut ast = AstClass(combine_ranges(ranges), flags); for alt in alts.into_iter() { ast = Alt(box alt, box ast) } @@ -485,7 +485,7 @@ impl<'a> Parser<'a> { Some(ranges) => { self.chari = closer; let flags = negated | (self.flags & FLAG_NOCASE); - Some(Class(combine_ranges(ranges), flags)) + Some(AstClass(combine_ranges(ranges), flags)) } } } @@ -611,7 +611,7 @@ impl<'a> Parser<'a> { let ranges = perl_unicode_class(c); let mut flags = self.flags & FLAG_NOCASE; if c.is_uppercase() { flags |= FLAG_NEGATED } - Ok(Class(ranges, flags)) + Ok(AstClass(ranges, flags)) } _ => { self.err(format!("Invalid escape sequence '\\\\{}'", @@ -655,7 +655,7 @@ impl<'a> Parser<'a> { name).as_slice()) } Some(ranges) => { - Ok(Class(ranges, negated | (self.flags & FLAG_NOCASE))) + Ok(AstClass(ranges, negated | (self.flags & FLAG_NOCASE))) } } } @@ -888,7 +888,7 @@ impl<'a> Parser<'a> { while i > from { i = i - 1; match self.stack.pop().unwrap() { - Ast(x) => combined = mk(x, combined), + Expr(x) => combined = mk(x, combined), _ => {}, } } diff --git a/src/libregex/re.rs b/src/libregex/re.rs index 8e4145b2a31..c2578d227ee 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -110,14 +110,14 @@ pub enum Regex { // See the comments for the `program` module in `lib.rs` for a more // detailed explanation for what `regex!` requires. #[doc(hidden)] - Dynamic(Dynamic), + Dynamic(ExDynamic), #[doc(hidden)] - Native(Native), + Native(ExNative), } #[deriving(Clone)] #[doc(hidden)] -pub struct Dynamic { +pub struct ExDynamic { original: String, names: Vec>, #[doc(hidden)] @@ -125,7 +125,7 @@ pub struct Dynamic { } #[doc(hidden)] -pub struct Native { +pub struct ExNative { #[doc(hidden)] pub original: &'static str, #[doc(hidden)] @@ -134,8 +134,8 @@ pub struct Native { pub prog: fn(MatchKind, &str, uint, uint) -> Vec> } -impl Clone for Native { - fn clone(&self) -> Native { *self } +impl Clone for ExNative { + fn clone(&self) -> ExNative { *self } } impl fmt::Show for Regex { @@ -156,7 +156,7 @@ impl Regex { pub fn new(re: &str) -> Result { let ast = try!(parse::parse(re)); let (prog, names) = Program::new(ast); - Ok(Dynamic(Dynamic { + Ok(Dynamic(ExDynamic { original: re.to_string(), names: names, prog: prog, @@ -510,8 +510,8 @@ impl Regex { /// Returns the original string of this regex. pub fn as_str<'a>(&'a self) -> &'a str { match *self { - Dynamic(Dynamic { ref original, .. }) => original.as_slice(), - Native(Native { ref original, .. }) => original.as_slice(), + Dynamic(ExDynamic { ref original, .. }) => original.as_slice(), + Native(ExNative { ref original, .. }) => original.as_slice(), } } @@ -915,8 +915,8 @@ fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs { fn exec_slice(re: &Regex, which: MatchKind, input: &str, s: uint, e: uint) -> CaptureLocs { match *re { - Dynamic(Dynamic { ref prog, .. }) => vm::run(which, prog, input, s, e), - Native(Native { prog, .. }) => prog(which, input, s, e), + Dynamic(ExDynamic { ref prog, .. }) => vm::run(which, prog, input, s, e), + Native(ExNative { prog, .. }) => prog(which, input, s, e), } } diff --git a/src/libregex_macros/lib.rs b/src/libregex_macros/lib.rs index 12809184003..ae6dd2a4d70 100644 --- a/src/libregex_macros/lib.rs +++ b/src/libregex_macros/lib.rs @@ -42,7 +42,7 @@ use regex::Regex; use regex::native::{ OneChar, CharClass, Any, Save, Jump, Split, Match, EmptyBegin, EmptyEnd, EmptyWordBoundary, - Program, Dynamic, Native, + Program, Dynamic, ExDynamic, Native, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED, }; @@ -91,7 +91,7 @@ fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) } }; let prog = match re { - Dynamic(Dynamic { ref prog, .. }) => prog.clone(), + Dynamic(ExDynamic { ref prog, .. }) => prog.clone(), Native(_) => unreachable!(), }; @@ -322,7 +322,7 @@ fn exec<'t>(which: ::regex::native::MatchKind, input: &'t str, } } -::regex::native::Native(::regex::native::Native { +::regex::native::Native(::regex::native::ExNative { original: $regex, names: CAP_NAMES, prog: exec, diff --git a/src/librustc/back/write.rs b/src/librustc/back/write.rs index cff5ac5375d..123131f0c21 100644 --- a/src/librustc/back/write.rs +++ b/src/librustc/back/write.rs @@ -11,7 +11,7 @@ use back::lto; use back::link::{get_cc_prog, remove}; use driver::driver::{CrateTranslation, ModuleTranslation, OutputFilenames}; -use driver::config::{NoDebugInfo, Passes, AllPasses}; +use driver::config::{NoDebugInfo, Passes, SomePasses, AllPasses}; use driver::session::Session; use driver::config; use llvm; @@ -341,7 +341,7 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo let pass_name = pass_name.as_str().expect("got a non-UTF8 pass name from LLVM"); let enabled = match cgcx.remark { AllPasses => true, - Passes(ref v) => v.iter().any(|s| s.as_slice() == pass_name), + SomePasses(ref v) => v.iter().any(|s| s.as_slice() == pass_name), }; if enabled { @@ -482,14 +482,14 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext, if config.emit_asm { let path = output_names.with_extension(format!("{}.s", name_extra).as_slice()); with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFile); + write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFileType); }); } if config.emit_obj { let path = output_names.with_extension(format!("{}.o", name_extra).as_slice()); with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFile); + write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType); }); } }); diff --git a/src/librustc/driver/config.rs b/src/librustc/driver/config.rs index 309c7a44c5d..72e2d244ad3 100644 --- a/src/librustc/driver/config.rs +++ b/src/librustc/driver/config.rs @@ -237,14 +237,14 @@ pub fn debugging_opts_map() -> Vec<(&'static str, &'static str, u64)> { #[deriving(Clone)] pub enum Passes { - Passes(Vec), + SomePasses(Vec), AllPasses, } impl Passes { pub fn is_empty(&self) -> bool { match *self { - Passes(ref v) => v.is_empty(), + SomePasses(ref v) => v.is_empty(), AllPasses => false, } } @@ -276,7 +276,7 @@ macro_rules! cgoptions( &[ $( (stringify!($opt), cgsetters::$opt, $desc) ),* ]; mod cgsetters { - use super::{CodegenOptions, Passes, AllPasses}; + use super::{CodegenOptions, Passes, SomePasses, AllPasses}; $( pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool { @@ -335,7 +335,7 @@ macro_rules! cgoptions( v => { let mut passes = vec!(); if parse_list(&mut passes, v) { - *slot = Passes(passes); + *slot = SomePasses(passes); true } else { false @@ -389,7 +389,7 @@ cgoptions!( "extra data to put in each output filename"), codegen_units: uint = (1, parse_uint, "divide crate into N units to optimize in parallel"), - remark: Passes = (Passes(Vec::new()), parse_passes, + remark: Passes = (SomePasses(Vec::new()), parse_passes, "print remarks for these optimization passes (space separated, or \"all\")"), ) diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 473c3935769..bb9e1fe7d94 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -1297,7 +1297,7 @@ impl LintPass for UnnecessaryAllocation { match cx.tcx.adjustments.borrow().find(&e.id) { Some(adjustment) => { match *adjustment { - ty::AutoDerefRef(ty::AutoDerefRef { ref autoref, .. }) => { + ty::AdjustDerefRef(ty::AutoDerefRef { ref autoref, .. }) => { match (allocation, autoref) { (VectorAllocation, &Some(ty::AutoPtr(_, _, None))) => { cx.span_lint(UNNECESSARY_ALLOCATION, e.span, @@ -1512,12 +1512,12 @@ impl LintPass for Stability { typeck::MethodStaticUnboxedClosure(def_id) => { def_id } - typeck::MethodParam(typeck::MethodParam { + typeck::MethodTypeParam(typeck::MethodParam { trait_ref: ref trait_ref, method_num: index, .. }) | - typeck::MethodObject(typeck::MethodObject { + typeck::MethodTraitObject(typeck::MethodObject { trait_ref: ref trait_ref, method_num: index, .. diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 399313ddd8e..0800c4868df 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -646,8 +646,8 @@ impl tr for MethodOrigin { typeck::MethodStaticUnboxedClosure(did) => { typeck::MethodStaticUnboxedClosure(did.tr(dcx)) } - typeck::MethodParam(ref mp) => { - typeck::MethodParam( + typeck::MethodTypeParam(ref mp) => { + typeck::MethodTypeParam( typeck::MethodParam { // def-id is already translated when we read it out trait_ref: mp.trait_ref.clone(), @@ -655,8 +655,8 @@ impl tr for MethodOrigin { } ) } - typeck::MethodObject(ref mo) => { - typeck::MethodObject( + typeck::MethodTraitObject(ref mo) => { + typeck::MethodTraitObject( typeck::MethodObject { trait_ref: mo.trait_ref.clone(), .. *mo @@ -962,8 +962,8 @@ impl<'a> rbml_writer_helpers for Encoder<'a> { }) } - typeck::MethodParam(ref p) => { - this.emit_enum_variant("MethodParam", 2, 1, |this| { + typeck::MethodTypeParam(ref p) => { + this.emit_enum_variant("MethodTypeParam", 2, 1, |this| { this.emit_struct("MethodParam", 2, |this| { try!(this.emit_struct_field("trait_ref", 0, |this| { Ok(this.emit_trait_ref(ecx, &*p.trait_ref)) @@ -976,8 +976,8 @@ impl<'a> rbml_writer_helpers for Encoder<'a> { }) } - typeck::MethodObject(ref o) => { - this.emit_enum_variant("MethodObject", 3, 1, |this| { + typeck::MethodTraitObject(ref o) => { + this.emit_enum_variant("MethodTraitObject", 3, 1, |this| { this.emit_struct("MethodObject", 2, |this| { try!(this.emit_struct_field("trait_ref", 0, |this| { Ok(this.emit_trait_ref(ecx, &*o.trait_ref)) @@ -1072,13 +1072,13 @@ impl<'a> rbml_writer_helpers for Encoder<'a> { self.emit_enum("AutoAdjustment", |this| { match *adj { - ty::AutoAddEnv(store) => { + ty::AdjustAddEnv(store) => { this.emit_enum_variant("AutoAddEnv", 0, 1, |this| { this.emit_enum_variant_arg(0, |this| store.encode(this)) }) } - ty::AutoDerefRef(ref auto_deref_ref) => { + ty::AdjustDerefRef(ref auto_deref_ref) => { this.emit_enum_variant("AutoDerefRef", 1, 1, |this| { this.emit_enum_variant_arg(0, |this| Ok(this.emit_auto_deref_ref(ecx, auto_deref_ref))) @@ -1374,7 +1374,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, }) } } - ty::AutoDerefRef(ref adj) => { + ty::AdjustDerefRef(ref adj) => { assert!(!ty::adjust_is_object(adjustment)); for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef); @@ -1505,7 +1505,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> { { self.read_enum("MethodOrigin", |this| { let variants = ["MethodStatic", "MethodStaticUnboxedClosure", - "MethodParam", "MethodObject"]; + "MethodTypeParam", "MethodTraitObject"]; this.read_enum_variant(variants, |this, i| { Ok(match i { 0 => { @@ -1519,8 +1519,8 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> { } 2 => { - this.read_struct("MethodParam", 2, |this| { - Ok(typeck::MethodParam( + this.read_struct("MethodTypeParam", 2, |this| { + Ok(typeck::MethodTypeParam( typeck::MethodParam { trait_ref: { this.read_struct_field("trait_ref", 0, |this| { @@ -1537,8 +1537,8 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> { } 3 => { - this.read_struct("MethodObject", 2, |this| { - Ok(typeck::MethodObject( + this.read_struct("MethodTraitObject", 2, |this| { + Ok(typeck::MethodTraitObject( typeck::MethodObject { trait_ref: { this.read_struct_field("trait_ref", 0, |this| { @@ -1685,14 +1685,14 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> { let store: ty::TraitStore = this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap(); - ty::AutoAddEnv(store.tr(dcx)) + ty::AdjustAddEnv(store.tr(dcx)) } 1 => { let auto_deref_ref: ty::AutoDerefRef = this.read_enum_variant_arg(0, |this| Ok(this.read_auto_deref_ref(dcx))).unwrap(); - ty::AutoDerefRef(auto_deref_ref) + ty::AdjustDerefRef(auto_deref_ref) } _ => fail!("bad enum variant for ty::AutoAdjustment") }) diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 0d584a7664f..ec36723e4ac 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -425,12 +425,12 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { adj: &ty::AutoAdjustment) -> mc::cmt { let r = match *adj { - ty::AutoDerefRef( + ty::AdjustDerefRef( ty::AutoDerefRef { autoderefs: autoderefs, ..}) => { self.mc().cat_expr_autoderefd(expr, autoderefs) } - ty::AutoAddEnv(..) => { + ty::AdjustAddEnv(..) => { // no autoderefs self.mc().cat_expr_unadjusted(expr) } diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index b75d61100ec..345b8c88372 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -101,12 +101,12 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { } } typeck::MethodStaticUnboxedClosure(_) => {} - typeck::MethodParam(typeck::MethodParam { + typeck::MethodTypeParam(typeck::MethodParam { trait_ref: ref trait_ref, method_num: index, .. }) | - typeck::MethodObject(typeck::MethodObject { + typeck::MethodTraitObject(typeck::MethodObject { trait_ref: ref trait_ref, method_num: index, .. diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index c8c5284022d..552e6902207 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -19,7 +19,8 @@ use middle::def; use middle::freevars; use middle::pat_util; use middle::ty; -use middle::typeck::{MethodCall, MethodObject, MethodOrigin, MethodParam}; +use middle::typeck::{MethodCall, MethodObject, MethodTraitObject}; +use middle::typeck::{MethodOrigin, MethodParam, MethodTypeParam}; use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure}; use middle::typeck; use util::ppaux::Repr; @@ -177,8 +178,8 @@ impl OverloadedCallType { MethodStaticUnboxedClosure(def_id) => { OverloadedCallType::from_unboxed_closure(tcx, def_id) } - MethodParam(MethodParam { trait_ref: ref trait_ref, .. }) | - MethodObject(MethodObject { trait_ref: ref trait_ref, .. }) => { + MethodTypeParam(MethodParam { trait_ref: ref trait_ref, .. }) | + MethodTraitObject(MethodObject { trait_ref: ref trait_ref, .. }) => { OverloadedCallType::from_trait_id(tcx, trait_ref.def_id) } } @@ -673,7 +674,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { None => { } Some(adjustment) => { match *adjustment { - ty::AutoAddEnv(..) => { + ty::AdjustAddEnv(..) => { // Creating a closure consumes the input and stores it // into the resulting rvalue. debug!("walk_adjustment(AutoAddEnv)"); @@ -681,7 +682,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> { return_if_err!(self.mc.cat_expr_unadjusted(expr)); self.delegate_consume(expr.id, expr.span, cmt_unadjusted); } - ty::AutoDerefRef(ty::AutoDerefRef { + ty::AdjustDerefRef(ty::AutoDerefRef { autoref: ref opt_autoref, autoderefs: n }) => { diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index aeb0c155a3f..eb6ca5ed36e 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -274,6 +274,7 @@ pub fn check_expr(cx: &mut Context, e: &Expr) { visit::walk_expr(cx, e); } + fn check_ty(cx: &mut Context, aty: &Ty) { match aty.node { TyPath(_, _, id) => { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index fee6c77a799..1a3939c9c81 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -116,6 +116,7 @@ use std::mem::transmute; use std::rc::Rc; use std::str; use std::uint; +use syntax::ast; use syntax::ast::*; use syntax::codemap::{BytePos, original_sp, Span}; use syntax::parse::token::special_idents; @@ -183,7 +184,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for IrMaps<'a, 'tcx> { b: &'v Block, s: Span, n: NodeId) { visit_fn(self, fk, fd, b, s, n); } - fn visit_local(&mut self, l: &Local) { visit_local(self, l); } + fn visit_local(&mut self, l: &ast::Local) { visit_local(self, l); } fn visit_expr(&mut self, ex: &Expr) { visit_expr(self, ex); } fn visit_arm(&mut self, a: &Arm) { visit_arm(self, a); } } @@ -346,7 +347,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Liveness<'a, 'tcx> { fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: &'v Block, s: Span, n: NodeId) { check_fn(self, fk, fd, b, s, n); } - fn visit_local(&mut self, l: &Local) { + fn visit_local(&mut self, l: &ast::Local) { check_local(self, l); } fn visit_expr(&mut self, ex: &Expr) { @@ -408,7 +409,7 @@ fn visit_fn(ir: &mut IrMaps, lsets.warn_about_unused_args(decl, entry_ln); } -fn visit_local(ir: &mut IrMaps, local: &Local) { +fn visit_local(ir: &mut IrMaps, local: &ast::Local) { pat_util::pat_bindings(&ir.tcx.def_map, &*local.pat, |_, p_id, sp, path1| { debug!("adding local variable {}", p_id); let name = path1.node; @@ -913,7 +914,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } } - fn propagate_through_local(&mut self, local: &Local, succ: LiveNode) + fn propagate_through_local(&mut self, local: &ast::Local, succ: LiveNode) -> LiveNode { // Note: we mark the variable as defined regardless of whether // there is an initializer. Initially I had thought to only mark @@ -1403,7 +1404,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // _______________________________________________________________________ // Checking for error conditions -fn check_local(this: &mut Liveness, local: &Local) { +fn check_local(this: &mut Liveness, local: &ast::Local) { match local.init { Some(_) => { this.warn_about_unused_or_dead_vars_in_pat(&*local.pat); diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 17d941b5958..2f8c08acd16 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -414,14 +414,14 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { Some(adjustment) => { match *adjustment { - ty::AutoAddEnv(..) => { + ty::AdjustAddEnv(..) => { // Convert a bare fn to a closure by adding NULL env. // Result is an rvalue. let expr_ty = if_ok!(self.expr_ty_adjusted(expr)); Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty)) } - ty::AutoDerefRef( + ty::AdjustDerefRef( ty::AutoDerefRef { autoref: Some(_), ..}) => { // Equivalent to &*expr or something similar. @@ -430,7 +430,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { Ok(self.cat_rvalue_node(expr.id(), expr.span(), expr_ty)) } - ty::AutoDerefRef( + ty::AdjustDerefRef( ty::AutoDerefRef { autoref: None, autoderefs: autoderefs}) => { // Equivalent to *expr or something similar. diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 8aac96a5410..36778e7cfc3 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -19,8 +19,8 @@ use middle::def; use lint; use middle::resolve; use middle::ty; -use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam}; -use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject}; +use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam, MethodTypeParam}; +use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject}; use util::nodemap::{NodeMap, NodeSet}; use syntax::ast; @@ -829,8 +829,8 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { MethodStaticUnboxedClosure(_) => {} // Trait methods are always all public. The only controlling factor // is whether the trait itself is accessible or not. - MethodParam(MethodParam { trait_ref: ref trait_ref, .. }) | - MethodObject(MethodObject { trait_ref: ref trait_ref, .. }) => { + MethodTypeParam(MethodParam { trait_ref: ref trait_ref, .. }) | + MethodTraitObject(MethodObject { trait_ref: ref trait_ref, .. }) => { self.report_error(self.ensure_public(span, trait_ref.def_id, None, "source trait")); } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 6fa33f4b5aa..5fadcab45af 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -28,7 +28,7 @@ use syntax::ast::{ExprPath, ExprProc, ExprStruct, ExprUnboxedFn, FnDecl}; use syntax::ast::{ForeignItem, ForeignItemFn, ForeignItemStatic, Generics}; use syntax::ast::{Ident, ImplItem, Item, ItemEnum, ItemFn, ItemForeignMod}; use syntax::ast::{ItemImpl, ItemMac, ItemMod, ItemStatic, ItemStruct}; -use syntax::ast::{ItemTrait, ItemTy, LOCAL_CRATE, Local, Method}; +use syntax::ast::{ItemTrait, ItemTy, LOCAL_CRATE, Local}; use syntax::ast::{MethodImplItem, Mod, Name, NamedField, NodeId}; use syntax::ast::{Pat, PatEnum, PatIdent, PatLit}; use syntax::ast::{PatRange, PatStruct, Path, PathListIdent, PathListMod}; @@ -1523,33 +1523,31 @@ impl<'a> Resolver<'a> { } // Constructs the reduced graph for one variant. Variants exist in the - // type and/or value namespaces. + // type and value namespaces. fn build_reduced_graph_for_variant(&mut self, variant: &Variant, item_id: DefId, parent: ReducedGraphParent, is_public: bool) { let ident = variant.node.name; - - match variant.node.kind { - TupleVariantKind(_) => { - let child = self.add_child(ident, parent, ForbidDuplicateValues, variant.span); - child.define_value(DefVariant(item_id, - local_def(variant.node.id), false), - variant.span, is_public); - } + let is_exported = match variant.node.kind { + TupleVariantKind(_) => false, StructVariantKind(_) => { - let child = self.add_child(ident, parent, - ForbidDuplicateTypesAndValues, - variant.span); - child.define_type(DefVariant(item_id, - local_def(variant.node.id), true), - variant.span, is_public); - // Not adding fields for variants as they are not accessed with a self receiver self.structs.insert(local_def(variant.node.id), Vec::new()); + true } - } + }; + + let child = self.add_child(ident, parent, + ForbidDuplicateTypesAndValues, + variant.span); + child.define_value(DefVariant(item_id, + local_def(variant.node.id), is_exported), + variant.span, is_public); + child.define_type(DefVariant(item_id, + local_def(variant.node.id), is_exported), + variant.span, is_public); } /// Constructs the reduced graph for one 'view item'. View items consist @@ -4471,7 +4469,7 @@ impl<'a> Resolver<'a> { // to be NormalRibKind? fn resolve_method(&mut self, rib_kind: RibKind, - method: &Method) { + method: &ast::Method) { let method_generics = method.pe_generics(); let type_parameters = HasTypeParameters(method_generics, FnSpace, diff --git a/src/librustc/middle/save/mod.rs b/src/librustc/middle/save/mod.rs index cab83f4cda2..31d0efc79e1 100644 --- a/src/librustc/middle/save/mod.rs +++ b/src/librustc/middle/save/mod.rs @@ -904,14 +904,14 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { }; (Some(def_id), decl_id) } - typeck::MethodParam(ref mp) => { + typeck::MethodTypeParam(ref mp) => { // method invoked on a type parameter let trait_item = ty::trait_item(&self.analysis.ty_cx, mp.trait_ref.def_id, mp.method_num); (None, Some(trait_item.def_id())) } - typeck::MethodObject(ref mo) => { + typeck::MethodTraitObject(ref mo) => { // method invoked on a trait instance let trait_item = ty::trait_item(&self.analysis.ty_cx, mo.trait_ref.def_id, diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index 22392f3f1c0..e7b1053b358 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -13,10 +13,10 @@ use middle::typeck::infer::{InferCtxt, skolemize}; use util::nodemap::DefIdMap; use util::ppaux::Repr; -use super::Ambiguity; +use super::CodeAmbiguity; use super::Obligation; use super::FulfillmentError; -use super::SelectionError; +use super::CodeSelectionError; use super::select::SelectionContext; use super::Unimplemented; @@ -78,7 +78,7 @@ impl FulfillmentContext { let errors: Vec = self.trait_obligations .iter() - .map(|o| FulfillmentError::new((*o).clone(), Ambiguity)) + .map(|o| FulfillmentError::new((*o).clone(), CodeAmbiguity)) .collect(); if errors.is_empty() { @@ -129,7 +129,7 @@ impl FulfillmentContext { errors.push(FulfillmentError::new( (*obligation).clone(), - SelectionError(selection_err))); + CodeSelectionError(selection_err))); false } } @@ -237,7 +237,7 @@ impl FulfillmentContext { errors.push( FulfillmentError::new( (*obligation).clone(), - SelectionError(Unimplemented))); + CodeSelectionError(Unimplemented))); } if errors.is_empty() { diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 62b3c982ccd..dde733a6a3e 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -97,8 +97,8 @@ pub struct FulfillmentError { #[deriving(Clone)] pub enum FulfillmentErrorCode { - SelectionError(SelectionError), - Ambiguity, + CodeSelectionError(SelectionError), + CodeAmbiguity, } /** @@ -110,7 +110,7 @@ pub enum FulfillmentErrorCode { * to inconclusive type inference. * - `Err(e)`: error `e` occurred */ -pub type SelectionResult = Result,SelectionError>; +pub type SelectionResult = Result, SelectionError>; #[deriving(PartialEq,Eq,Show)] pub enum EvaluationResult { @@ -157,12 +157,12 @@ pub enum EvaluationResult { * * ### The type parameter `N` * - * See explanation on `VtableImpl`. + * See explanation on `VtableImplData`. */ #[deriving(Show,Clone)] pub enum Vtable { /// Vtable identifying a particular impl. - VtableImpl(VtableImpl), + VtableImpl(VtableImplData), /// Vtable automatically generated for an unboxed closure. The def /// ID is the ID of the closure expression. This is a `VtableImpl` @@ -172,7 +172,7 @@ pub enum Vtable { /// Successful resolution to an obligation provided by the caller /// for some type parameter. - VtableParam(VtableParam), + VtableParam(VtableParamData), /// Successful resolution for a builtin trait. VtableBuiltin, @@ -191,7 +191,7 @@ pub enum Vtable { * impl, and nested obligations are satisfied later. */ #[deriving(Clone)] -pub struct VtableImpl { +pub struct VtableImplData { pub impl_def_id: ast::DefId, pub substs: subst::Substs, pub nested: subst::VecPerParamSpace @@ -203,7 +203,7 @@ pub struct VtableImpl { * on an instance of `T`, the vtable would be of type `VtableParam`. */ #[deriving(Clone)] -pub struct VtableParam { +pub struct VtableParamData { // In the above example, this would `Eq` pub bound: Rc, } @@ -274,7 +274,7 @@ pub fn select_inherent_impl(infcx: &InferCtxt, cause: ObligationCause, impl_def_id: ast::DefId, self_ty: ty::t) - -> SelectionResult> + -> SelectionResult> { /*! * Matches the self type of the inherent impl `impl_def_id` @@ -398,21 +398,21 @@ impl Vtable { } } -impl VtableImpl { +impl VtableImplData { pub fn map_nested(&self, op: |&N| -> M) - -> VtableImpl + -> VtableImplData { - VtableImpl { + VtableImplData { impl_def_id: self.impl_def_id, substs: self.substs.clone(), nested: self.nested.map(op) } } - pub fn map_move_nested(self, op: |N| -> M) -> VtableImpl { - let VtableImpl { impl_def_id, substs, nested } = self; - VtableImpl { + pub fn map_move_nested(self, op: |N| -> M) -> VtableImplData { + let VtableImplData { impl_def_id, substs, nested } = self; + VtableImplData { impl_def_id: impl_def_id, substs: substs, nested: nested.map_move(op) diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 681e2650f39..e475dc6063d 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -18,6 +18,7 @@ use super::{SelectionError, Unimplemented, Overflow, use super::{Selection}; use super::{SelectionResult}; use super::{VtableBuiltin, VtableImpl, VtableParam, VtableUnboxedClosure}; +use super::{VtableImplData, VtableParamData}; use super::{util}; use middle::subst::{Subst, Substs, VecPerParamSpace}; @@ -82,7 +83,7 @@ enum MatchResult { enum Candidate { MatchedBuiltinCandidate, AmbiguousBuiltinCandidate, - MatchedParamCandidate(VtableParam), + MatchedParamCandidate(VtableParamData), AmbiguousParamCandidate, Impl(ImplCandidate), MatchedUnboxedClosureCandidate(/* closure */ ast::DefId) @@ -142,7 +143,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { impl_def_id: ast::DefId, obligation_cause: ObligationCause, obligation_self_ty: ty::t) - -> SelectionResult> + -> SelectionResult> { debug!("select_inherent_impl(impl_def_id={}, obligation_self_ty={})", impl_def_id.repr(self.tcx()), @@ -597,8 +598,8 @@ v */ fn confirm_param_candidate(&self, obligation: &Obligation, - param: VtableParam) - -> Result + param: VtableParamData) + -> Result { debug!("confirm_param_candidate({},{})", obligation.repr(self.tcx()), @@ -613,7 +614,7 @@ v */ fn confirm_impl_candidate(&self, obligation: &Obligation, impl_def_id: ast::DefId) - -> Result,SelectionError> + -> Result,SelectionError> { debug!("confirm_impl_candidate({},{})", obligation.repr(self.tcx()), @@ -642,7 +643,7 @@ v */ obligation_cause: ObligationCause, obligation_self_ty: ty::t, obligation_recursion_depth: uint) - -> Result, + -> Result, SelectionError> { let substs = match self.match_impl_self_types(impl_def_id, @@ -663,7 +664,7 @@ v */ obligation_recursion_depth, impl_def_id, &substs); - let vtable_impl = VtableImpl { impl_def_id: impl_def_id, + let vtable_impl = VtableImplData { impl_def_id: impl_def_id, substs: substs, nested: impl_obligations }; diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index 1eae4ac1932..c48b125ac35 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -19,7 +19,7 @@ use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; -use super::{Obligation, ObligationCause, VtableImpl, VtableParam}; +use super::{Obligation, ObligationCause, VtableImpl, VtableParam, VtableParamData, VtableImplData}; /////////////////////////////////////////////////////////////////////////// // Supertrait iterator @@ -137,13 +137,13 @@ pub fn fresh_substs_for_impl(infcx: &InferCtxt, infcx.fresh_substs_for_generics(span, &impl_generics) } -impl fmt::Show for VtableImpl { +impl fmt::Show for VtableImplData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableImpl({})", self.impl_def_id) } } -impl fmt::Show for VtableParam { +impl fmt::Show for VtableParamData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "VtableParam(...)") } @@ -239,7 +239,7 @@ pub fn obligation_for_builtin_bound( pub fn search_trait_and_supertraits_from_bound(tcx: &ty::ctxt, caller_bound: Rc, test: |ast::DefId| -> bool) - -> Option + -> Option { /*! * Starting from a caller obligation `caller_bound` (which has @@ -252,7 +252,7 @@ pub fn search_trait_and_supertraits_from_bound(tcx: &ty::ctxt, for bound in transitive_bounds(tcx, &[caller_bound]) { if test(bound.def_id) { - let vtable_param = VtableParam { bound: bound }; + let vtable_param = VtableParamData { bound: bound }; return Some(vtable_param); } } @@ -287,7 +287,7 @@ impl Repr for super::Vtable { } } -impl Repr for super::VtableImpl { +impl Repr for super::VtableImplData { fn repr(&self, tcx: &ty::ctxt) -> String { format!("VtableImpl(impl_def_id={}, substs={}, nested={})", self.impl_def_id.repr(tcx), @@ -296,7 +296,7 @@ impl Repr for super::VtableImpl { } } -impl Repr for super::VtableParam { +impl Repr for super::VtableParamData { fn repr(&self, tcx: &ty::ctxt) -> String { format!("VtableParam(bound={})", self.bound.repr(tcx)) @@ -331,8 +331,8 @@ impl Repr for super::FulfillmentError { impl Repr for super::FulfillmentErrorCode { fn repr(&self, tcx: &ty::ctxt) -> String { match *self { - super::SelectionError(ref o) => o.repr(tcx), - super::Ambiguity => format!("Ambiguity") + super::CodeSelectionError(ref o) => o.repr(tcx), + super::CodeAmbiguity => format!("Ambiguity") } } } @@ -340,8 +340,8 @@ impl Repr for super::FulfillmentErrorCode { impl fmt::Show for super::FulfillmentErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - super::SelectionError(ref e) => write!(f, "{}", e), - super::Ambiguity => write!(f, "Ambiguity") + super::CodeSelectionError(ref e) => write!(f, "{}", e), + super::CodeAmbiguity => write!(f, "Ambiguity") } } } diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 576031500b9..d39fe4a1e70 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -207,7 +207,7 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef None => { } Some(adj) => { match adj { - ty::AutoAddEnv(ty::RegionTraitStore(ty::ReStatic, _)) => { + ty::AdjustAddEnv(ty::RegionTraitStore(ty::ReStatic, _)) => { let def = ty::resolve_expr(cx.tcx(), e); let wrapper = closure::get_wrapper_for_bare_fn(cx, ety_adjusted, @@ -216,13 +216,13 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef is_local); llconst = C_struct(cx, [wrapper, C_null(Type::i8p(cx))], false) } - ty::AutoAddEnv(store) => { + ty::AdjustAddEnv(store) => { cx.sess() .span_bug(e.span, format!("unexpected static function: {:?}", store).as_slice()) } - ty::AutoDerefRef(ref adj) => { + ty::AdjustDerefRef(ref adj) => { let mut ty = ety; // Save the last autoderef in case we can avoid it. if adj.autoderefs > 0 { diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 62571ef9f9b..f9908a933f9 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -664,7 +664,7 @@ pub struct FunctionDebugContext { } enum FunctionDebugContextRepr { - FunctionDebugContext(Box), + DebugInfo(Box), DebugInfoDisabled, FunctionWithoutDebugInfo, } @@ -675,7 +675,7 @@ impl FunctionDebugContext { span: Span) -> &'a FunctionDebugContextData { match self.repr { - FunctionDebugContext(box ref data) => data, + DebugInfo(box ref data) => data, DebugInfoDisabled => { cx.sess().span_bug(span, FunctionDebugContext::debuginfo_disabled_message()); @@ -1044,7 +1044,7 @@ pub fn set_source_location(fcx: &FunctionContext, set_debug_location(fcx.ccx, UnknownLocation); return; } - FunctionDebugContext(box ref function_debug_context) => { + DebugInfo(box ref function_debug_context) => { let cx = fcx.ccx; debug!("set_source_location: {}", cx.sess().codemap().span_to_string(span)); @@ -1082,7 +1082,7 @@ pub fn clear_source_location(fcx: &FunctionContext) { /// first real statement/expression of the function is translated. pub fn start_emitting_source_locations(fcx: &FunctionContext) { match fcx.debug_context.repr { - FunctionDebugContext(box ref data) => { + DebugInfo(box ref data) => { data.source_locations_enabled.set(true) }, _ => { /* safe to ignore */ } @@ -1291,7 +1291,7 @@ pub fn create_function_debug_context(cx: &CrateContext, fn_metadata, &mut *fn_debug_context.scope_map.borrow_mut()); - return FunctionDebugContext { repr: FunctionDebugContext(fn_debug_context) }; + return FunctionDebugContext { repr: DebugInfo(fn_debug_context) }; fn get_function_signature(cx: &CrateContext, fn_ast_id: ast::NodeId, @@ -3134,7 +3134,7 @@ fn DIB(cx: &CrateContext) -> DIBuilderRef { fn fn_should_be_ignored(fcx: &FunctionContext) -> bool { match fcx.debug_context.repr { - FunctionDebugContext(_) => false, + DebugInfo(_) => false, _ => true } } diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 77712570185..f048065101f 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -64,7 +64,7 @@ use middle::trans::inline; use middle::trans::tvec; use middle::trans::type_of; use middle::ty::{struct_fields, tup_fields}; -use middle::ty::{AutoDerefRef, AutoAddEnv, AutoUnsafe}; +use middle::ty::{AdjustDerefRef, AdjustAddEnv, AutoUnsafe}; use middle::ty::{AutoPtr}; use middle::ty; use middle::typeck; @@ -190,10 +190,10 @@ fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, debug!("unadjusted datum for expr {}: {}", expr.id, datum.to_string(bcx.ccx())); match adjustment { - AutoAddEnv(..) => { + AdjustAddEnv(..) => { datum = unpack_datum!(bcx, add_env(bcx, expr, datum)); } - AutoDerefRef(ref adj) => { + AdjustDerefRef(ref adj) => { let (autoderefs, use_autoref) = match adj.autoref { // Extracting a value from a box counts as a deref, but if we are // just converting Box<[T, ..n]> to Box<[T]> we aren't really doing diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index f1276387745..844ee0a60c6 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -131,7 +131,7 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } } - typeck::MethodParam(typeck::MethodParam { + typeck::MethodTypeParam(typeck::MethodParam { trait_ref: ref trait_ref, method_num: method_num }) => { @@ -147,7 +147,7 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_num, origin) } - typeck::MethodObject(ref mt) => { + typeck::MethodTraitObject(ref mt) => { let self_expr = match self_expr { Some(self_expr) => self_expr, None => { @@ -243,7 +243,7 @@ pub fn trans_static_method_callee(bcx: Block, // Now that we know which impl is being used, we can dispatch to // the actual function: match vtbl { - traits::VtableImpl(traits::VtableImpl { + traits::VtableImpl(traits::VtableImplData { impl_def_id: impl_did, substs: impl_substs, nested: _ }) => @@ -562,7 +562,7 @@ pub fn get_vtable(bcx: Block, trait_ref.clone()); match vtable { traits::VtableImpl( - traits::VtableImpl { + traits::VtableImplData { impl_def_id: id, substs: substs, nested: _ }) => { diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 897bc4517f4..63836f13126 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -279,8 +279,8 @@ pub enum Variance { #[deriving(Clone)] pub enum AutoAdjustment { - AutoAddEnv(ty::TraitStore), - AutoDerefRef(AutoDerefRef) + AdjustAddEnv(ty::TraitStore), + AdjustDerefRef(AutoDerefRef) } #[deriving(Clone, PartialEq)] @@ -352,7 +352,7 @@ fn autoref_object_region(autoref: &AutoRef) -> (bool, bool, Option) { // returns the region of the borrowed reference. pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option { match adj { - &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { + &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { let (b, _, r) = autoref_object_region(autoref); if b { r @@ -367,7 +367,7 @@ pub fn adjusted_object_region(adj: &AutoAdjustment) -> Option { // Returns true if there is a trait cast at the bottom of the adjustment. pub fn adjust_is_object(adj: &AutoAdjustment) -> bool { match adj { - &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { + &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { let (b, _, _) = autoref_object_region(autoref); b } @@ -409,7 +409,7 @@ pub fn type_of_adjust(cx: &ctxt, adj: &AutoAdjustment) -> Option { } match adj { - &AutoDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { + &AdjustDerefRef(AutoDerefRef{autoref: Some(ref autoref), ..}) => { type_of_autoref(cx, autoref) } _ => None @@ -3425,7 +3425,7 @@ pub fn adjust_ty(cx: &ctxt, return match adjustment { Some(adjustment) => { match *adjustment { - AutoAddEnv(store) => { + AdjustAddEnv(store) => { match ty::get(unadjusted_ty).sty { ty::ty_bare_fn(ref b) => { let bounds = ty::ExistentialBounds { @@ -3451,7 +3451,7 @@ pub fn adjust_ty(cx: &ctxt, } } - AutoDerefRef(ref adj) => { + AdjustDerefRef(ref adj) => { let mut adjusted_ty = unadjusted_ty; if !ty::type_is_error(adjusted_ty) { @@ -3584,12 +3584,12 @@ pub fn method_call_type_param_defs<'tcx, T>(typer: &T, .trait_did(typer.tcx()); lookup_trait_def(typer.tcx(), def_id).generics.types.clone() } - typeck::MethodParam(typeck::MethodParam{ + typeck::MethodTypeParam(typeck::MethodParam{ trait_ref: ref trait_ref, method_num: n_mth, .. }) | - typeck::MethodObject(typeck::MethodObject{ + typeck::MethodTraitObject(typeck::MethodObject{ trait_ref: ref trait_ref, method_num: n_mth, .. diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 3b08ccd5a7b..2e964c457bf 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -353,9 +353,9 @@ impl TypeFoldable for traits::Obligation { } } -impl TypeFoldable for traits::VtableImpl { - fn fold_with<'tcx, F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableImpl { - traits::VtableImpl { +impl TypeFoldable for traits::VtableImplData { + fn fold_with<'tcx, F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableImplData { + traits::VtableImplData { impl_def_id: self.impl_def_id, substs: self.substs.fold_with(folder), nested: self.nested.fold_with(folder), @@ -374,9 +374,9 @@ impl TypeFoldable for traits::Vtable { } } -impl TypeFoldable for traits::VtableParam { - fn fold_with<'tcx, F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableParam { - traits::VtableParam { +impl TypeFoldable for traits::VtableParamData { + fn fold_with<'tcx, F:TypeFolder<'tcx>>(&self, folder: &mut F) -> traits::VtableParamData { + traits::VtableParamData { bound: self.bound.fold_with(folder), } } diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 5d2ce7b080e..7d28a63d935 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -90,8 +90,8 @@ use middle::typeck::check::{FnCtxt, PreferMutLvalue, impl_self_ty}; use middle::typeck::check; use middle::typeck::infer; use middle::typeck::MethodCallee; -use middle::typeck::{MethodOrigin, MethodParam}; -use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject}; +use middle::typeck::{MethodOrigin, MethodParam, MethodTypeParam}; +use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject}; use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig; use middle::typeck::TypeAndSubsts; use util::common::indenter; @@ -636,7 +636,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { rcvr_match_condition: RcvrMatchesIfObject(did), rcvr_substs: new_trait_ref.substs.clone(), method_ty: Rc::new(m), - origin: MethodObject(MethodObject { + origin: MethodTraitObject(MethodObject { trait_ref: new_trait_ref, object_trait_id: did, method_num: method_num, @@ -702,7 +702,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { rcvr_match_condition: condition, rcvr_substs: trait_ref.substs.clone(), method_ty: m, - origin: MethodParam(MethodParam { + origin: MethodTypeParam(MethodParam { trait_ref: trait_ref, method_num: method_num, }) @@ -874,7 +874,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { } let (self_ty, auto_deref_ref) = self.consider_reborrow(self_ty, autoderefs); - let adjustment = Some((self.self_expr.unwrap().id, ty::AutoDerefRef(auto_deref_ref))); + let adjustment = Some((self.self_expr.unwrap().id, ty::AdjustDerefRef(auto_deref_ref))); match self.search_for_method(self_ty) { None => None, @@ -1159,7 +1159,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { self.fcx.write_adjustment( self_expr_id, self.span, - ty::AutoDerefRef(ty::AutoDerefRef { + ty::AdjustDerefRef(ty::AutoDerefRef { autoderefs: autoderefs, autoref: Some(kind(region, *mutbl)) })); @@ -1245,7 +1245,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { candidate_a.repr(self.tcx()), candidate_b.repr(self.tcx())); match (&candidate_a.origin, &candidate_b.origin) { - (&MethodParam(ref p1), &MethodParam(ref p2)) => { + (&MethodTypeParam(ref p1), &MethodTypeParam(ref p2)) => { let same_trait = p1.trait_ref.def_id == p2.trait_ref.def_id; let same_method = @@ -1330,7 +1330,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { let fn_sig = &bare_fn_ty.sig; let inputs = match candidate.origin { - MethodObject(..) => { + MethodTraitObject(..) => { // For annoying reasons, we've already handled the // substitution of self for object calls. let args = fn_sig.inputs.slice_from(1).iter().map(|t| { @@ -1403,11 +1403,11 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { match candidate.origin { MethodStatic(..) | - MethodParam(..) | + MethodTypeParam(..) | MethodStaticUnboxedClosure(..) => { return; // not a call to a trait instance } - MethodObject(..) => {} + MethodTraitObject(..) => {} } match candidate.method_ty.explicit_self { @@ -1463,8 +1463,8 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { MethodStaticUnboxedClosure(_) => bad = false, // FIXME: does this properly enforce this on everything now // that self has been merged in? -sully - MethodParam(MethodParam { trait_ref: ref trait_ref, .. }) | - MethodObject(MethodObject { trait_ref: ref trait_ref, .. }) => { + MethodTypeParam(MethodParam { trait_ref: ref trait_ref, .. }) | + MethodTraitObject(MethodObject { trait_ref: ref trait_ref, .. }) => { bad = self.tcx().destructor_for_type.borrow() .contains_key(&trait_ref.def_id); } @@ -1612,10 +1612,10 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { MethodStaticUnboxedClosure(did) => { self.report_static_candidate(idx, did) } - MethodParam(ref mp) => { + MethodTypeParam(ref mp) => { self.report_param_candidate(idx, mp.trait_ref.def_id) } - MethodObject(ref mo) => { + MethodTraitObject(ref mo) => { self.report_trait_candidate(idx, mo.trait_ref.def_id) } } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index c8728d375f6..0bd810b3845 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1704,7 +1704,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.write_adjustment( node_id, span, - ty::AutoDerefRef(ty::AutoDerefRef { + ty::AdjustDerefRef(ty::AutoDerefRef { autoderefs: derefs, autoref: None }) ); @@ -1730,8 +1730,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, adj: &ty::AutoAdjustment) { match *adj { - ty::AutoAddEnv(..) => { } - ty::AutoDerefRef(ref d_r) => { + ty::AdjustAddEnv(..) => { } + ty::AdjustDerefRef(ref d_r) => { match d_r.autoref { Some(ref a_r) => { self.register_autoref_obligations(span, a_r); diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index a8f2a8f6f1d..2ba327ae589 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -592,7 +592,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { for &adjustment in rcx.fcx.inh.adjustments.borrow().find(&expr.id).iter() { debug!("adjustment={:?}", adjustment); match *adjustment { - ty::AutoDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => { + ty::AdjustDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => { let expr_ty = rcx.resolve_node_type(expr.id); constrain_autoderefs(rcx, expr, autoderefs, expr_ty); for autoref in opt_autoref.iter() { diff --git a/src/librustc/middle/typeck/check/vtable2.rs b/src/librustc/middle/typeck/check/vtable2.rs index f75d2622fdb..0022efd845e 100644 --- a/src/librustc/middle/typeck/check/vtable2.rs +++ b/src/librustc/middle/typeck/check/vtable2.rs @@ -13,7 +13,7 @@ use middle::traits; use middle::traits::{SelectionError, Overflow, OutputTypeParameterMismatch, Unimplemented}; use middle::traits::{Obligation, obligation_for_builtin_bound}; -use middle::traits::{FulfillmentError, Ambiguity}; +use middle::traits::{FulfillmentError, CodeSelectionError, CodeAmbiguity}; use middle::traits::{ObligationCause}; use middle::ty; use middle::typeck::check::{FnCtxt, @@ -244,10 +244,10 @@ pub fn report_fulfillment_errors(fcx: &FnCtxt, pub fn report_fulfillment_error(fcx: &FnCtxt, error: &FulfillmentError) { match error.code { - SelectionError(ref e) => { + CodeSelectionError(ref e) => { report_selection_error(fcx, &error.obligation, e); } - Ambiguity => { + CodeAmbiguity => { maybe_report_ambiguity(fcx, &error.obligation); } } diff --git a/src/librustc/middle/typeck/check/writeback.rs b/src/librustc/middle/typeck/check/writeback.rs index ffe019b314a..e2a04116f90 100644 --- a/src/librustc/middle/typeck/check/writeback.rs +++ b/src/librustc/middle/typeck/check/writeback.rs @@ -282,7 +282,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { Some(adjustment) => { let adj_object = ty::adjust_is_object(&adjustment); let resolved_adjustment = match adjustment { - ty::AutoAddEnv(store) => { + ty::AdjustAddEnv(store) => { // FIXME(eddyb) #2190 Allow only statically resolved // bare functions to coerce to a closure to avoid // constructing (slower) indirect call wrappers. @@ -298,10 +298,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } } - ty::AutoAddEnv(self.resolve(&store, reason)) + ty::AdjustAddEnv(self.resolve(&store, reason)) } - ty::AutoDerefRef(adj) => { + ty::AdjustDerefRef(adj) => { for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef); self.visit_method_map_entry(reason, method_call); @@ -312,7 +312,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { self.visit_method_map_entry(reason, method_call); } - ty::AutoDerefRef(ty::AutoDerefRef { + ty::AdjustDerefRef(ty::AutoDerefRef { autoderefs: adj.autoderefs, autoref: self.resolve(&adj.autoref, reason), }) diff --git a/src/librustc/middle/typeck/infer/coercion.rs b/src/librustc/middle/typeck/infer/coercion.rs index e0a35dc72a3..7f9f569c37e 100644 --- a/src/librustc/middle/typeck/infer/coercion.rs +++ b/src/librustc/middle/typeck/infer/coercion.rs @@ -65,7 +65,7 @@ we may want to adjust precisely when coercions occur. */ use middle::subst; -use middle::ty::{AutoPtr, AutoDerefRef, AutoUnsize, AutoUnsafe}; +use middle::ty::{AutoPtr, AutoDerefRef, AdjustDerefRef, AutoUnsize, AutoUnsafe}; use middle::ty::{mt}; use middle::ty; use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; @@ -270,7 +270,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { mt {ty: inner_ty, mutbl: mutbl_b}); try!(sub.tys(a_borrowed, b)); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(AutoPtr(r_borrow, mutbl_b, None)) }))) @@ -295,7 +295,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { let unsized_ty = ty::mk_slice(self.get_ref().infcx.tcx, r_borrow, mt {ty: t_a, mutbl: mutbl_b}); try!(self.get_ref().infcx.try(|| sub.tys(unsized_ty, b))); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 0, autoref: Some(ty::AutoPtr(r_borrow, mutbl_b, @@ -343,7 +343,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { try!(self.get_ref().infcx.try(|| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ AutoPtr(AutoUnsize({:?})))", kind); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoPtr(r_borrow, mt_b.mutbl, Some(box AutoUnsize(kind)))) @@ -366,7 +366,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { try!(self.get_ref().infcx.try(|| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ AutoPtr(AutoUnsize({:?})))", kind); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl, Some(box AutoUnsize(kind)))) @@ -384,7 +384,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { try!(self.get_ref().infcx.try(|| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ AutoUnsizeUniq({:?}))", kind); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsizeUniq(kind)) }))) @@ -537,7 +537,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { let tr = ty::mk_trait(tcx, def_id, substs.clone(), bounds); try!(self.subtype(mk_ty(tr), b)); - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(mk_adjust()) }))) @@ -593,7 +593,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { _ => return self.subtype(a, b) }; - let adj = ty::AutoAddEnv(fn_ty_b.store); + let adj = ty::AdjustAddEnv(fn_ty_b.store); let a_closure = ty::mk_closure(self.get_ref().infcx.tcx, ty::ClosureTy { sig: fn_ty_a.sig.clone(), @@ -630,7 +630,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Although references and unsafe ptrs have the same // representation, we still register an AutoDerefRef so that // regionck knows that the region for `a` must be valid here. - Ok(Some(AutoDerefRef(AutoDerefRef { + Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mutbl_b, None)) }))) diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 7a913699280..e93ad056051 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -102,10 +102,10 @@ pub enum MethodOrigin { MethodStaticUnboxedClosure(ast::DefId), // method invoked on a type parameter with a bounded trait - MethodParam(MethodParam), + MethodTypeParam(MethodParam), // method invoked on a trait instance - MethodObject(MethodObject), + MethodTraitObject(MethodObject), } diff --git a/src/librustc/plugin/registry.rs b/src/librustc/plugin/registry.rs index be31e81d29b..88e6f0ad186 100644 --- a/src/librustc/plugin/registry.rs +++ b/src/librustc/plugin/registry.rs @@ -13,7 +13,7 @@ use lint::{LintPassObject, LintId, Lint}; use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT}; -use syntax::ext::base::{IdentTT, LetSyntaxTT, ItemDecorator, ItemModifier}; +use syntax::ext::base::{IdentTT, LetSyntaxTT, Decorator, Modifier}; use syntax::ext::base::{MacroExpanderFn}; use syntax::codemap::Span; use syntax::parse::token; @@ -61,8 +61,8 @@ impl Registry { self.syntax_exts.push((name, match extension { NormalTT(ext, _) => NormalTT(ext, Some(self.krate_span)), IdentTT(ext, _) => IdentTT(ext, Some(self.krate_span)), - ItemDecorator(ext) => ItemDecorator(ext), - ItemModifier(ext) => ItemModifier(ext), + Decorator(ext) => Decorator(ext), + Modifier(ext) => Modifier(ext), // there's probably a nicer way to signal this: LetSyntaxTT(_, _) => fail!("can't register a new LetSyntax!"), })); diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 2083aa52bec..5b83f024309 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -962,10 +962,10 @@ impl Repr for typeck::MethodOrigin { &typeck::MethodStaticUnboxedClosure(def_id) => { format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx)) } - &typeck::MethodParam(ref p) => { + &typeck::MethodTypeParam(ref p) => { p.repr(tcx) } - &typeck::MethodObject(ref p) => { + &typeck::MethodTraitObject(ref p) => { p.repr(tcx) } } diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 690b288043d..e26fb70529d 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -324,11 +324,11 @@ pub enum AtomicOrdering { // Consts for the LLVMCodeGenFileType type (in include/llvm/c/TargetMachine.h) #[repr(C)] pub enum FileType { - AssemblyFile = 0, - ObjectFile = 1 + AssemblyFileType = 0, + ObjectFileType = 1 } -pub enum Metadata { +pub enum MetadataType { MD_dbg = 0, MD_tbaa = 1, MD_prof = 2, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 9e05382fa55..b4d44aab239 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -99,7 +99,7 @@ pub struct Crate { pub name: String, pub module: Option, pub externs: Vec<(ast::CrateNum, ExternalCrate)>, - pub primitives: Vec, + pub primitives: Vec, } impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { @@ -147,7 +147,7 @@ impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { ModuleItem(ref mut m) => m, _ => continue, }; - let prim = match Primitive::find(child.attrs.as_slice()) { + let prim = match PrimitiveType::find(child.attrs.as_slice()) { Some(prim) => prim, None => continue, }; @@ -187,7 +187,7 @@ impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { pub struct ExternalCrate { pub name: String, pub attrs: Vec, - pub primitives: Vec, + pub primitives: Vec, } impl Clean for cstore::crate_metadata { @@ -202,7 +202,7 @@ impl Clean for cstore::crate_metadata { _ => return }; let attrs = inline::load_attrs(cx, tcx, did); - Primitive::find(attrs.as_slice()).map(|prim| primitives.push(prim)); + PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim)); }) }); ExternalCrate { @@ -316,7 +316,7 @@ pub enum ItemEnum { /// `static`s from an extern block ForeignStaticItem(Static), MacroItem(Macro), - PrimitiveItem(Primitive), + PrimitiveItem(PrimitiveType), AssociatedTypeItem, } @@ -901,7 +901,7 @@ impl Clean for ast::RetStyle { #[deriving(Clone, Encodable, Decodable)] pub struct Trait { - pub items: Vec, + pub items: Vec, pub generics: Generics, pub bounds: Vec, } @@ -931,13 +931,13 @@ impl Clean for ast::TraitRef { } #[deriving(Clone, Encodable, Decodable)] -pub enum TraitItem { +pub enum TraitMethod { RequiredMethod(Item), ProvidedMethod(Item), TypeTraitItem(Item), } -impl TraitItem { +impl TraitMethod { pub fn is_req(&self) -> bool { match self { &RequiredMethod(..) => true, @@ -959,8 +959,8 @@ impl TraitItem { } } -impl Clean for ast::TraitItem { - fn clean(&self, cx: &DocContext) -> TraitItem { +impl Clean for ast::TraitItem { + fn clean(&self, cx: &DocContext) -> TraitMethod { match self { &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)), &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)), @@ -970,13 +970,13 @@ impl Clean for ast::TraitItem { } #[deriving(Clone, Encodable, Decodable)] -pub enum ImplItem { +pub enum ImplMethod { MethodImplItem(Item), TypeImplItem(Item), } -impl Clean for ast::ImplItem { - fn clean(&self, cx: &DocContext) -> ImplItem { +impl Clean for ast::ImplItem { + fn clean(&self, cx: &DocContext) -> ImplMethod { match self { &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)), &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)), @@ -1058,7 +1058,7 @@ pub enum Type { /// For references to self Self(ast::DefId), /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char. - Primitive(Primitive), + Primitive(PrimitiveType), Closure(Box), Proc(Box), /// extern "ABI" fn @@ -1080,7 +1080,7 @@ pub enum Type { } #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)] -pub enum Primitive { +pub enum PrimitiveType { Int, I8, I16, I32, I64, Uint, U8, U16, U32, U64, F32, F64, @@ -1104,8 +1104,8 @@ pub enum TypeKind { TypeTypedef, } -impl Primitive { - fn from_str(s: &str) -> Option { +impl PrimitiveType { + fn from_str(s: &str) -> Option { match s.as_slice() { "int" => Some(Int), "i8" => Some(I8), @@ -1129,7 +1129,7 @@ impl Primitive { } } - fn find(attrs: &[Attribute]) -> Option { + fn find(attrs: &[Attribute]) -> Option { for attr in attrs.iter() { let list = match *attr { List(ref k, ref l) if k.as_slice() == "doc" => l, @@ -1141,7 +1141,7 @@ impl Primitive { if k.as_slice() == "primitive" => v.as_slice(), _ => continue, }; - match Primitive::from_str(value) { + match PrimitiveType::from_str(value) { Some(p) => return Some(p), None => {} } diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index 54e9c29e11d..b771473473c 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -40,8 +40,8 @@ pub trait DocFolder { EnumItem(i) }, TraitItem(mut i) => { - fn vtrm(this: &mut T, trm: TraitItem) - -> Option { + fn vtrm(this: &mut T, trm: TraitMethod) + -> Option { match trm { RequiredMethod(it) => { match this.fold_item(it) { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index e526286ef46..c807c180e64 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -277,7 +277,7 @@ fn path(w: &mut fmt::Formatter, path: &clean::Path, print_all: bool, } fn primitive_link(f: &mut fmt::Formatter, - prim: clean::Primitive, + prim: clean::PrimitiveType, name: &str) -> fmt::Result { let m = cache_key.get().unwrap(); let mut needs_termination = false; diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 2107854c52b..cf625d4ddfc 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -177,7 +177,7 @@ pub struct Cache { pub extern_locations: HashMap, /// Cache of where documentation for primitives can be found. - pub primitive_locations: HashMap, + pub primitive_locations: HashMap, /// Set of definitions which have been inlined from external crates. pub inlined: HashSet, @@ -1637,7 +1637,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, _ => false, } }) - .collect::>(); + .collect::>(); let provided = t.items.iter() .filter(|m| { match **m { @@ -1645,7 +1645,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, _ => false, } }) - .collect::>(); + .collect::>(); if t.items.len() == 0 { try!(write!(w, "{{ }}")); @@ -1671,7 +1671,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, // Trait documentation try!(document(w, it)); - fn trait_item(w: &mut fmt::Formatter, m: &clean::TraitItem) + fn trait_item(w: &mut fmt::Formatter, m: &clean::TraitMethod) -> fmt::Result { try!(write!(w, "

{}", shortty(m.item()), @@ -2180,7 +2180,7 @@ fn item_macro(w: &mut fmt::Formatter, it: &clean::Item, fn item_primitive(w: &mut fmt::Formatter, it: &clean::Item, - _p: &clean::Primitive) -> fmt::Result { + _p: &clean::PrimitiveType) -> fmt::Result { try!(document(w, it)); render_methods(w, it) } diff --git a/src/librustdoc/stability_summary.rs b/src/librustdoc/stability_summary.rs index 02dc4e9bdb6..f7d43037723 100644 --- a/src/librustdoc/stability_summary.rs +++ b/src/librustdoc/stability_summary.rs @@ -21,7 +21,7 @@ use syntax::attr::{Deprecated, Experimental, Unstable, Stable, Frozen, Locked}; use syntax::ast::Public; use clean::{Crate, Item, ModuleItem, Module, StructItem, Struct, EnumItem, Enum}; -use clean::{ImplItem, Impl, Trait, TraitItem, ProvidedMethod, RequiredMethod}; +use clean::{ImplItem, Impl, Trait, TraitItem, TraitMethod, ProvidedMethod, RequiredMethod}; use clean::{TypeTraitItem, ViewItemItem, PrimitiveItem}; #[deriving(Zero, Encodable, Decodable, PartialEq, Eq)] @@ -128,7 +128,7 @@ fn summarize_item(item: &Item) -> (Counts, Option) { items: ref trait_items, .. }) => { - fn extract_item<'a>(trait_item: &'a TraitItem) -> &'a Item { + fn extract_item<'a>(trait_item: &'a TraitMethod) -> &'a Item { match *trait_item { ProvidedMethod(ref item) | RequiredMethod(ref item) | diff --git a/src/librustrt/local_data.rs b/src/librustrt/local_data.rs index c71f86bb063..ba5a4dc3f21 100644 --- a/src/librustrt/local_data.rs +++ b/src/librustrt/local_data.rs @@ -67,7 +67,7 @@ use task::{Task, LocalStorage}; pub type Key = &'static KeyValue; #[allow(missing_doc)] -pub enum KeyValue { Key } +pub enum KeyValue { KeyValueKey } // The task-local-map stores all TLD information for the currently running // task. It is stored as an owned pointer into the runtime, and it's only @@ -417,7 +417,7 @@ mod tests { #[test] fn test_tls_multitask() { - static my_key: Key = &Key; + static my_key: Key = &KeyValueKey; my_key.replace(Some("parent data".to_string())); task::spawn(proc() { // TLD shouldn't carry over. @@ -435,7 +435,7 @@ mod tests { #[test] fn test_tls_overwrite() { - static my_key: Key = &Key; + static my_key: Key = &KeyValueKey; my_key.replace(Some("first data".to_string())); my_key.replace(Some("next data".to_string())); // Shouldn't leak. assert!(my_key.get().unwrap().as_slice() == "next data"); @@ -443,7 +443,7 @@ mod tests { #[test] fn test_tls_pop() { - static my_key: Key = &Key; + static my_key: Key = &KeyValueKey; my_key.replace(Some("weasel".to_string())); assert!(my_key.replace(None).unwrap() == "weasel".to_string()); // Pop must remove the data from the map. @@ -458,7 +458,7 @@ mod tests { // to get recorded as something within a rust stack segment. Then a // subsequent upcall (esp. for logging, think vsnprintf) would run on // a stack smaller than 1 MB. - static my_key: Key = &Key; + static my_key: Key = &KeyValueKey; task::spawn(proc() { my_key.replace(Some("hax".to_string())); }); @@ -466,9 +466,9 @@ mod tests { #[test] fn test_tls_multiple_types() { - static str_key: Key = &Key; - static box_key: Key> = &Key; - static int_key: Key = &Key; + static str_key: Key = &KeyValueKey; + static box_key: Key> = &KeyValueKey; + static int_key: Key = &KeyValueKey; task::spawn(proc() { str_key.replace(Some("string data".to_string())); box_key.replace(Some(box(GC) ())); @@ -478,9 +478,9 @@ mod tests { #[test] fn test_tls_overwrite_multiple_types() { - static str_key: Key = &Key; - static box_key: Key> = &Key; - static int_key: Key = &Key; + static str_key: Key = &KeyValueKey; + static box_key: Key> = &KeyValueKey; + static int_key: Key = &KeyValueKey; task::spawn(proc() { str_key.replace(Some("string data".to_string())); str_key.replace(Some("string data 2".to_string())); @@ -497,9 +497,9 @@ mod tests { #[test] #[should_fail] fn test_tls_cleanup_on_failure() { - static str_key: Key = &Key; - static box_key: Key> = &Key; - static int_key: Key = &Key; + static str_key: Key = &KeyValueKey; + static box_key: Key> = &KeyValueKey; + static int_key: Key = &KeyValueKey; str_key.replace(Some("parent data".to_string())); box_key.replace(Some(box(GC) ())); task::spawn(proc() { @@ -524,7 +524,7 @@ mod tests { self.tx.send(()); } } - static key: Key = &Key; + static key: Key = &KeyValueKey; let _ = task::try(proc() { key.replace(Some(Dropper{ tx: tx })); }); @@ -535,14 +535,14 @@ mod tests { #[test] fn test_static_pointer() { - static key: Key<&'static int> = &Key; + static key: Key<&'static int> = &KeyValueKey; static VALUE: int = 0; key.replace(Some(&VALUE)); } #[test] fn test_owned() { - static key: Key> = &Key; + static key: Key> = &KeyValueKey; key.replace(Some(box 1)); { @@ -559,11 +559,11 @@ mod tests { #[test] fn test_same_key_type() { - static key1: Key = &Key; - static key2: Key = &Key; - static key3: Key = &Key; - static key4: Key = &Key; - static key5: Key = &Key; + static key1: Key = &KeyValueKey; + static key2: Key = &KeyValueKey; + static key3: Key = &KeyValueKey; + static key4: Key = &KeyValueKey; + static key5: Key = &KeyValueKey; key1.replace(Some(1)); key2.replace(Some(2)); key3.replace(Some(3)); @@ -580,7 +580,7 @@ mod tests { #[test] #[should_fail] fn test_nested_get_set1() { - static key: Key = &Key; + static key: Key = &KeyValueKey; assert_eq!(key.replace(Some(4)), None); let _k = key.get(); @@ -602,7 +602,7 @@ mod tests { #[bench] fn bench_replace_none(b: &mut test::Bencher) { - static key: Key = &Key; + static key: Key = &KeyValueKey; let _clear = ClearKey(key); key.replace(None); b.iter(|| { @@ -612,7 +612,7 @@ mod tests { #[bench] fn bench_replace_some(b: &mut test::Bencher) { - static key: Key = &Key; + static key: Key = &KeyValueKey; let _clear = ClearKey(key); key.replace(Some(1u)); b.iter(|| { @@ -622,7 +622,7 @@ mod tests { #[bench] fn bench_replace_none_some(b: &mut test::Bencher) { - static key: Key = &Key; + static key: Key = &KeyValueKey; let _clear = ClearKey(key); key.replace(Some(0u)); b.iter(|| { @@ -634,7 +634,7 @@ mod tests { #[bench] fn bench_100_keys_replace_last(b: &mut test::Bencher) { - static keys: [KeyValue, ..100] = [Key, ..100]; + static keys: [KeyValue, ..100] = [KeyValueKey, ..100]; let _clear = keys.iter().map(ClearKey).collect::>>(); for (i, key) in keys.iter().enumerate() { key.replace(Some(i)); @@ -647,7 +647,7 @@ mod tests { #[bench] fn bench_1000_keys_replace_last(b: &mut test::Bencher) { - static keys: [KeyValue, ..1000] = [Key, ..1000]; + static keys: [KeyValue, ..1000] = [KeyValueKey, ..1000]; let _clear = keys.iter().map(ClearKey).collect::>>(); for (i, key) in keys.iter().enumerate() { key.replace(Some(i)); @@ -661,7 +661,7 @@ mod tests { #[bench] fn bench_get(b: &mut test::Bencher) { - static key: Key = &Key; + static key: Key = &KeyValueKey; let _clear = ClearKey(key); key.replace(Some(42)); b.iter(|| { @@ -671,7 +671,7 @@ mod tests { #[bench] fn bench_100_keys_get_last(b: &mut test::Bencher) { - static keys: [KeyValue, ..100] = [Key, ..100]; + static keys: [KeyValue, ..100] = [KeyValueKey, ..100]; let _clear = keys.iter().map(ClearKey).collect::>>(); for (i, key) in keys.iter().enumerate() { key.replace(Some(i)); @@ -684,7 +684,7 @@ mod tests { #[bench] fn bench_1000_keys_get_last(b: &mut test::Bencher) { - static keys: [KeyValue, ..1000] = [Key, ..1000]; + static keys: [KeyValue, ..1000] = [KeyValueKey, ..1000]; let _clear = keys.iter().map(ClearKey).collect::>>(); for (i, key) in keys.iter().enumerate() { key.replace(Some(i)); diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 833c5cd0f98..14274ef9f9b 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -28,7 +28,7 @@ Data types that can be encoded are JavaScript types (see the `Json` enum for mor * `Boolean`: equivalent to rust's `bool` * `Number`: equivalent to rust's `f64` * `String`: equivalent to rust's `String` -* `Array`: equivalent to rust's `Vec`, but also allowing objects of different types in the same +* `List`: equivalent to rust's `Vec`, but also allowing objects of different types in the same array * `Object`: equivalent to rust's `Treemap` * `Null` @@ -201,7 +201,7 @@ use std::io::MemWriter; use std::mem::{swap, transmute}; use std::num::{FPNaN, FPInfinite}; use std::str::ScalarValue; -use std::string::String; +use std::string; use std::vec::Vec; use Encodable; @@ -212,15 +212,15 @@ pub enum Json { I64(i64), U64(u64), F64(f64), - String(String), + String(string::String), Boolean(bool), - List(List), - Object(Object), + List(JsonList), + Object(JsonObject), Null, } -pub type List = Vec; -pub type Object = TreeMap; +pub type JsonList = Vec; +pub type JsonObject = TreeMap; /// The errors that can arise while parsing a JSON stream. #[deriving(Clone, PartialEq)] @@ -257,10 +257,10 @@ pub type BuilderError = ParserError; #[deriving(Clone, PartialEq, Show)] pub enum DecoderError { ParseError(ParserError), - ExpectedError(String, String), - MissingFieldError(String), - UnknownVariantError(String), - ApplicationError(String) + ExpectedError(string::String, string::String), + MissingFieldError(string::String), + UnknownVariantError(string::String), + ApplicationError(string::String) } /// Returns a readable error string for a given error code. @@ -298,9 +298,9 @@ pub fn decode>(s: &str) -> DecodeResult } /// Shortcut function to encode a `T` into a JSON `String` -pub fn encode<'a, T: Encodable, io::IoError>>(object: &T) -> String { +pub fn encode<'a, T: Encodable, io::IoError>>(object: &T) -> string::String { let buff = Encoder::buffer_encode(object); - String::from_utf8(buff).unwrap() + string::String::from_utf8(buff).unwrap() } impl fmt::Show for ErrorCode { @@ -375,9 +375,9 @@ fn spaces(wr: &mut io::Writer, mut n: uint) -> Result<(), io::IoError> { } } -fn fmt_number_or_null(v: f64) -> String { +fn fmt_number_or_null(v: f64) -> string::String { match v.classify() { - FPNaN | FPInfinite => String::from_str("null"), + FPNaN | FPInfinite => string::String::from_str("null"), _ => f64::to_str_digits(v, 6u) } } @@ -411,7 +411,7 @@ impl<'a> Encoder<'a> { /// /// Note: this function is deprecated. Consider using `json::encode` instead. #[deprecated = "Replaced by `json::encode`"] - pub fn str_encode, io::IoError>>(object: &T) -> String { + pub fn str_encode, io::IoError>>(object: &T) -> string::String { encode(object) } } @@ -877,15 +877,15 @@ impl Json { } /// Encodes a json value into a string - pub fn to_pretty_str(&self) -> String { + pub fn to_pretty_str(&self) -> string::String { let mut s = MemWriter::new(); self.to_pretty_writer(&mut s as &mut io::Writer).unwrap(); - String::from_utf8(s.unwrap()).unwrap() + string::String::from_utf8(s.unwrap()).unwrap() } /// If the Json value is an Object, returns the value associated with the provided key. /// Otherwise, returns None. - pub fn find<'a>(&'a self, key: &String) -> Option<&'a Json>{ + pub fn find<'a>(&'a self, key: &string::String) -> Option<&'a Json>{ match self { &Object(ref map) => map.find(key), _ => None @@ -895,7 +895,7 @@ impl Json { /// Attempts to get a nested Json Object for each key in `keys`. /// If any key is found not to exist, find_path will return None. /// Otherwise, it will return the Json value associated with the final key. - pub fn find_path<'a>(&'a self, keys: &[&String]) -> Option<&'a Json>{ + pub fn find_path<'a>(&'a self, keys: &[&string::String]) -> Option<&'a Json>{ let mut target = self; for key in keys.iter() { match target.find(*key) { @@ -909,7 +909,7 @@ impl Json { /// If the Json value is an Object, performs a depth-first search until /// a value associated with the provided key is found. If no value is found /// or the Json value is not an Object, returns None. - pub fn search<'a>(&'a self, key: &String) -> Option<&'a Json> { + pub fn search<'a>(&'a self, key: &string::String) -> Option<&'a Json> { match self { &Object(ref map) => { match map.find(key) { @@ -937,7 +937,7 @@ impl Json { /// If the Json value is an Object, returns the associated TreeMap. /// Returns None otherwise. - pub fn as_object<'a>(&'a self) -> Option<&'a Object> { + pub fn as_object<'a>(&'a self) -> Option<&'a JsonObject> { match self { &Object(ref map) => Some(map), _ => None @@ -951,7 +951,7 @@ impl Json { /// If the Json value is a List, returns the associated vector. /// Returns None otherwise. - pub fn as_list<'a>(&'a self) -> Option<&'a List> { + pub fn as_list<'a>(&'a self) -> Option<&'a JsonList> { match self { &List(ref list) => Some(&*list), _ => None @@ -1075,7 +1075,7 @@ pub enum JsonEvent { I64Value(i64), U64Value(u64), F64Value(f64), - StringValue(String), + StringValue(string::String), NullValue, Error(ParserError), } @@ -1083,7 +1083,7 @@ pub enum JsonEvent { #[deriving(PartialEq, Show)] enum ParserState { // Parse a value in a list, true means first element. - ParseList(bool), + ParseArray(bool), // Parse ',' or ']' after an element in a list. ParseListComma, // Parse a key:value in an object, true means first element. @@ -1191,7 +1191,7 @@ impl Stack { } // Used by Parser to insert Key elements at the top of the stack. - fn push_key(&mut self, key: String) { + fn push_key(&mut self, key: string::String) { self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16)); for c in key.as_bytes().iter() { self.str_buffer.push(*c); @@ -1502,9 +1502,9 @@ impl> Parser { Ok(n) } - fn parse_str(&mut self) -> Result { + fn parse_str(&mut self) -> Result { let mut escape = false; - let mut res = String::new(); + let mut res = string::String::new(); loop { self.bump(); @@ -1574,7 +1574,7 @@ impl> Parser { // The only paths where the loop can spin a new iteration // are in the cases ParseListComma and ParseObjectComma if ',' // is parsed. In these cases the state is set to (respectively) - // ParseList(false) and ParseObject(false), which always return, + // ParseArray(false) and ParseObject(false), which always return, // so there is no risk of getting stuck in an infinite loop. // All other paths return before the end of the loop's iteration. self.parse_whitespace(); @@ -1583,7 +1583,7 @@ impl> Parser { ParseStart => { return self.parse_start(); } - ParseList(first) => { + ParseArray(first) => { return self.parse_list(first); } ParseListComma => { @@ -1615,7 +1615,7 @@ impl> Parser { let val = self.parse_value(); self.state = match val { Error(_) => { ParseFinished } - ListStart => { ParseList(true) } + ListStart => { ParseArray(true) } ObjectStart => { ParseObject(true) } _ => { ParseBeforeFinish } }; @@ -1647,7 +1647,7 @@ impl> Parser { self.state = match val { Error(_) => { ParseFinished } - ListStart => { ParseList(true) } + ListStart => { ParseArray(true) } ObjectStart => { ParseObject(true) } _ => { ParseListComma } }; @@ -1657,7 +1657,7 @@ impl> Parser { fn parse_list_comma_or_end(&mut self) -> Option { if self.ch_is(',') { self.stack.bump_index(); - self.state = ParseList(false); + self.state = ParseArray(false); self.bump(); return None; } else if self.ch_is(']') { @@ -1728,7 +1728,7 @@ impl> Parser { self.state = match val { Error(_) => { ParseFinished } - ListStart => { ParseList(true) } + ListStart => { ParseArray(true) } ObjectStart => { ParseObject(true) } _ => { ParseObjectComma } }; @@ -1830,7 +1830,7 @@ impl> Builder { Some(F64Value(n)) => { Ok(F64(n)) } Some(BooleanValue(b)) => { Ok(Boolean(b)) } Some(StringValue(ref mut s)) => { - let mut temp = String::new(); + let mut temp = string::String::new(); swap(s, &mut temp); Ok(String(temp)) } @@ -2034,7 +2034,7 @@ impl ::Decoder for Decoder { Err(ExpectedError("single character string".to_string(), format!("{}", s))) } - fn read_str(&mut self) -> DecodeResult { + fn read_str(&mut self) -> DecodeResult { debug!("read_str"); expect!(self.pop(), String) } @@ -2284,7 +2284,7 @@ impl ToJson for bool { fn to_json(&self) -> Json { Boolean(*self) } } -impl ToJson for String { +impl ToJson for string::String { fn to_json(&self) -> Json { String((*self).clone()) } } @@ -2328,7 +2328,7 @@ impl ToJson for Vec { fn to_json(&self) -> Json { List(self.iter().map(|elt| elt.to_json()).collect()) } } -impl ToJson for TreeMap { +impl ToJson for TreeMap { fn to_json(&self) -> Json { let mut d = TreeMap::new(); for (key, value) in self.iter() { @@ -2338,7 +2338,7 @@ impl ToJson for TreeMap { } } -impl ToJson for HashMap { +impl ToJson for HashMap { fn to_json(&self) -> Json { let mut d = TreeMap::new(); for (key, value) in self.iter() { @@ -2375,7 +2375,7 @@ mod tests { extern crate test; use self::test::Bencher; use {Encodable, Decodable}; - use super::{Encoder, Decoder, Error, Boolean, I64, U64, F64, List, String, Null, + use super::{List, Encoder, Decoder, Error, Boolean, I64, U64, F64, String, Null, PrettyEncoder, Object, Json, from_str, ParseError, ExpectedError, MissingFieldError, UnknownVariantError, DecodeResult, DecoderError, JsonEvent, Parser, StackElement, @@ -2386,6 +2386,7 @@ mod tests { TrailingCharacters, TrailingComma}; use std::{i64, u64, f32, f64, io}; use std::collections::TreeMap; + use std::string; #[deriving(Decodable, Eq, PartialEq, Show)] struct OptionData { @@ -2417,14 +2418,14 @@ mod tests { #[deriving(PartialEq, Encodable, Decodable, Show)] enum Animal { Dog, - Frog(String, int) + Frog(string::String, int) } #[deriving(PartialEq, Encodable, Decodable, Show)] struct Inner { a: (), b: uint, - c: Vec, + c: Vec, } #[deriving(PartialEq, Encodable, Decodable, Show)] @@ -2432,7 +2433,7 @@ mod tests { inner: Vec, } - fn mk_object(items: &[(String, Json)]) -> Json { + fn mk_object(items: &[(string::String, Json)]) -> Json { let mut d = TreeMap::new(); for item in items.iter() { @@ -2610,7 +2611,7 @@ mod tests { from_str(a.to_pretty_str().as_slice()).unwrap()); } - fn with_str_writer(f: |&mut io::Writer|) -> String { + fn with_str_writer(f: |&mut io::Writer|) -> string::String { use std::io::MemWriter; use std::str; @@ -2678,7 +2679,7 @@ mod tests { #[test] fn test_write_none() { - let value: Option = None; + let value: Option = None; let s = with_str_writer(|writer| { let mut encoder = Encoder::new(writer); value.encode(&mut encoder).unwrap(); @@ -2825,7 +2826,7 @@ mod tests { ("\"\\uAB12\"", "\uAB12")]; for &(i, o) in s.iter() { - let v: String = super::decode(i).unwrap(); + let v: string::String = super::decode(i).unwrap(); assert_eq!(v.as_slice(), o); } } @@ -2959,10 +2960,10 @@ mod tests { #[test] fn test_decode_option() { - let value: Option = super::decode("null").unwrap(); + let value: Option = super::decode("null").unwrap(); assert_eq!(value, None); - let value: Option = super::decode("\"jodhpurs\"").unwrap(); + let value: Option = super::decode("\"jodhpurs\"").unwrap(); assert_eq!(value, Some("jodhpurs".to_string())); } @@ -2980,7 +2981,7 @@ mod tests { fn test_decode_map() { let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\ \"fields\":[\"Henry\", 349]}}"; - let mut map: TreeMap = super::decode(s).unwrap(); + let mut map: TreeMap = super::decode(s).unwrap(); assert_eq!(map.pop(&"a".to_string()), Some(Dog)); assert_eq!(map.pop(&"b".to_string()), Some(Frog("Henry".to_string(), 349))); @@ -2997,13 +2998,13 @@ mod tests { struct DecodeStruct { x: f64, y: bool, - z: String, + z: string::String, w: Vec } #[deriving(Decodable)] enum DecodeEnum { A(f64), - B(String) + B(string::String) } fn check_err>(to_parse: &'static str, expected: DecoderError) { @@ -3709,7 +3710,7 @@ mod tests { }); } - fn big_json() -> String { + fn big_json() -> string::String { let mut src = "[\n".to_string(); for _ in range(0i, 500) { src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \ diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index e1f2f43673f..86c03708e40 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -304,10 +304,10 @@ macro_rules! println( #[macro_export] macro_rules! local_data_key( ($name:ident: $ty:ty) => ( - static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key; + static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey; ); (pub $name:ident: $ty:ty) => ( - pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key; + pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::KeyValueKey; ); ) diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 773daa4a4c5..30b47b916df 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -305,11 +305,11 @@ pub enum SyntaxExtension { /// based upon it. /// /// `#[deriving(...)]` is an `ItemDecorator`. - ItemDecorator(Box), + Decorator(Box), /// A syntax extension that is attached to an item and modifies it /// in-place. - ItemModifier(Box), + Modifier(Box), /// A normal, function-like syntax extension. /// @@ -387,7 +387,7 @@ fn initial_syntax_expander_table() -> SyntaxEnv { builtin_normal_expander( ext::log_syntax::expand_syntax_ext)); syntax_expanders.insert(intern("deriving"), - ItemDecorator(box ext::deriving::expand_meta_deriving)); + Decorator(box ext::deriving::expand_meta_deriving)); // Quasi-quoting expanders syntax_expanders.insert(intern("quote_tokens"), diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 4ff9912645a..8f5fd647dbd 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -254,7 +254,7 @@ pub fn expand_item(it: P, fld: &mut MacroExpander) match fld.cx.syntax_env.find(&intern(mname.get())) { Some(rc) => match *rc { - ItemDecorator(ref dec) => { + Decorator(ref dec) => { attr::mark_used(attr); fld.cx.bt_push(ExpnInfo { @@ -311,7 +311,7 @@ fn expand_item_modifiers(mut it: P, fld: &mut MacroExpander) // partition the attributes into ItemModifiers and others let (modifiers, other_attrs) = it.attrs.partitioned(|attr| { match fld.cx.syntax_env.find(&intern(attr.name().get())) { - Some(rc) => match *rc { ItemModifier(_) => true, _ => false }, + Some(rc) => match *rc { Modifier(_) => true, _ => false }, _ => false } }); @@ -330,7 +330,7 @@ fn expand_item_modifiers(mut it: P, fld: &mut MacroExpander) match fld.cx.syntax_env.find(&intern(mname.get())) { Some(rc) => match *rc { - ItemModifier(ref mac) => { + Modifier(ref mac) => { attr::mark_used(attr); fld.cx.bt_push(ExpnInfo { call_site: attr.span, diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 26586684309..b760c893a10 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -19,17 +19,18 @@ use parse::token; use ptr::P; use std::collections::HashMap; +use std::string; #[deriving(PartialEq)] enum ArgumentType { - Known(String), + Known(string::String), Unsigned, String, } enum Position { Exact(uint), - Named(String), + Named(string::String), } struct Context<'a, 'b:'a> { @@ -44,12 +45,12 @@ struct Context<'a, 'b:'a> { /// Note that we keep a side-array of the ordering of the named arguments /// found to be sure that we can translate them in the same order that they /// were declared in. - names: HashMap>, - name_types: HashMap, - name_ordering: Vec, + names: HashMap>, + name_types: HashMap, + name_ordering: Vec, /// The latest consecutive literal strings, or empty if there weren't any. - literal: String, + literal: string::String, /// Collection of the compiled `rt::Argument` structures pieces: Vec>, @@ -58,7 +59,7 @@ struct Context<'a, 'b:'a> { /// Stays `true` if all formatting parameters are default (as in "{}{}"). all_pieces_simple: bool, - name_positions: HashMap, + name_positions: HashMap, method_statics: Vec>, /// Updated as arguments are consumed or methods are entered @@ -81,10 +82,10 @@ pub enum Invocation { /// named arguments)) fn parse_args(ecx: &mut ExtCtxt, sp: Span, allow_method: bool, tts: &[ast::TokenTree]) - -> (Invocation, Option<(P, Vec>, Vec, - HashMap>)>) { + -> (Invocation, Option<(P, Vec>, Vec, + HashMap>)>) { let mut args = Vec::new(); - let mut names = HashMap::>::new(); + let mut names = HashMap::>::new(); let mut order = Vec::new(); let mut p = ecx.new_parser_from_tts(tts); @@ -167,7 +168,7 @@ impl<'a, 'b> Context<'a, 'b> { fn verify_piece(&mut self, p: &parse::Piece) { match *p { parse::String(..) => {} - parse::Argument(ref arg) => { + parse::NextArgument(ref arg) => { // width/precision first, if they have implicit positional // parameters it makes more sense to consume them first. self.verify_count(arg.format.width); @@ -222,7 +223,7 @@ impl<'a, 'b> Context<'a, 'b> { } } - fn describe_num_args(&self) -> String { + fn describe_num_args(&self) -> string::String { match self.args.len() { 0 => "no arguments given".to_string(), 1 => "there is 1 argument".to_string(), @@ -391,7 +392,7 @@ impl<'a, 'b> Context<'a, 'b> { self.literal.push_str(s); None } - parse::Argument(ref arg) => { + parse::NextArgument(ref arg) => { // Translate the position let pos = match arg.position { // These two have a direct mapping @@ -747,8 +748,8 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, invocation: Invocation, efmt: P, args: Vec>, - name_ordering: Vec, - names: HashMap>) + name_ordering: Vec, + names: HashMap>) -> P { let arg_types = Vec::from_fn(args.len(), |_| None); let mut cx = Context { @@ -761,7 +762,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, name_ordering: name_ordering, nest_level: 0, next_arg: 0, - literal: String::new(), + literal: string::String::new(), pieces: Vec::new(), str_pieces: Vec::new(), all_pieces_simple: true, diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 70da4e11961..f1fdc71b9c6 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -60,7 +60,7 @@ //! avoid combining it with other lines and making matters even worse. use std::io; -use std::string::String; +use std::string; #[deriving(Clone, PartialEq)] pub enum Breaks { @@ -82,7 +82,7 @@ pub struct BeginToken { #[deriving(Clone)] pub enum Token { - String(String, int), + String(string::String, int), Break(BreakToken), Begin(BeginToken), End, @@ -107,7 +107,7 @@ impl Token { } } -pub fn tok_str(t: Token) -> String { +pub fn tok_str(t: Token) -> string::String { match t { String(s, len) => return format!("STR({},{})", s, len), Break(_) => return "BREAK".to_string(), @@ -122,12 +122,12 @@ pub fn buf_str(toks: Vec, left: uint, right: uint, lim: uint) - -> String { + -> string::String { let n = toks.len(); assert_eq!(n, szs.len()); let mut i = left; let mut l = lim; - let mut s = String::from_str("["); + let mut s = string::String::from_str("["); while i != right && l != 0u { l -= 1u; if i != left { diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index e6fc64cbd3b..93f773f430d 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -41,7 +41,7 @@ enum FormatState { #[allow(missing_doc)] #[deriving(Clone)] pub enum Param { - String(String), + Words(String), Number(int) } @@ -140,8 +140,8 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) '{' => state = IntConstant(0), 'l' => if stack.len() > 0 { match stack.pop().unwrap() { - String(s) => stack.push(Number(s.len() as int)), - _ => return Err("a non-str was used with %l".to_string()) + Words(s) => stack.push(Number(s.len() as int)), + _ => return Err("a non-str was used with %l".to_string()) } } else { return Err("stack is empty".to_string()) }, '+' => if stack.len() > 1 { @@ -543,7 +543,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result ,String> { } s } - String(s) => { + Words(s) => { match op { FormatString => { let mut s = Vec::from_slice(s.as_bytes()); @@ -575,7 +575,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result ,String> { #[cfg(test)] mod test { - use super::{expand,String,Variables,Number}; + use super::{expand,Words,Variables,Number}; use std::result::Ok; #[test] @@ -611,7 +611,7 @@ mod test { assert!(res.is_err(), "Op {} succeeded incorrectly with 0 stack entries", *cap); let p = if *cap == "%s" || *cap == "%l" { - String("foo".to_string()) + Words("foo".to_string()) } else { Number(97) }; @@ -689,12 +689,12 @@ mod test { let mut varstruct = Variables::new(); let vars = &mut varstruct; assert_eq!(expand(b"%p1%s%p2%2s%p3%2s%p4%.2s", - [String("foo".to_string()), - String("foo".to_string()), - String("f".to_string()), - String("foo".to_string())], vars), + [Words("foo".to_string()), + Words("foo".to_string()), + Words("f".to_string()), + Words("foo".to_string())], vars), Ok("foofoo ffo".bytes().collect())); - assert_eq!(expand(b"%p1%:-4.2s", [String("foo".to_string())], vars), + assert_eq!(expand(b"%p1%:-4.2s", [Words("foo".to_string())], vars), Ok("fo ".bytes().collect())); assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", [Number(1)], vars), diff --git a/src/test/auxiliary/macro_crate_test.rs b/src/test/auxiliary/macro_crate_test.rs index dd1f9c3404f..befd33fca4e 100644 --- a/src/test/auxiliary/macro_crate_test.rs +++ b/src/test/auxiliary/macro_crate_test.rs @@ -35,7 +35,7 @@ pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), - ItemModifier(box expand_into_foo)); + Modifier(box expand_into_foo)); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) diff --git a/src/test/auxiliary/xcrate_unit_struct.rs b/src/test/auxiliary/xcrate_unit_struct.rs index 7619513a2a6..6487c704765 100644 --- a/src/test/auxiliary/xcrate_unit_struct.rs +++ b/src/test/auxiliary/xcrate_unit_struct.rs @@ -15,7 +15,7 @@ pub struct Struct; pub enum Unit { - Unit, + UnitVariant, Argument(Struct) } diff --git a/src/test/compile-fail/enum-variant-type-2.rs b/src/test/compile-fail/enum-variant-type-2.rs new file mode 100644 index 00000000000..bf80626793d --- /dev/null +++ b/src/test/compile-fail/enum-variant-type-2.rs @@ -0,0 +1,19 @@ +// 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. + +// Test that enum variants are not actually types. + +enum Foo { + Bar +} + +fn foo(x: Bar) {} //~ERROR found value name used as a type + +fn main() {} diff --git a/src/test/compile-fail/enum-variant-type.rs b/src/test/compile-fail/enum-variant-type.rs new file mode 100644 index 00000000000..93d44f96c8a --- /dev/null +++ b/src/test/compile-fail/enum-variant-type.rs @@ -0,0 +1,23 @@ +// 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. + +// Test that enum variants are in the type namespace. + +enum Foo { + Foo //~ERROR duplicate definition of type or module `Foo` +} + +enum Bar { + Baz +} + +trait Baz {} //~ERROR duplicate definition of type or module `Baz` + +pub fn main() {} diff --git a/src/test/compile-fail/issue-3008-1.rs b/src/test/compile-fail/issue-3008-1.rs index 3613fb8ccbe..d2d7d800470 100644 --- a/src/test/compile-fail/issue-3008-1.rs +++ b/src/test/compile-fail/issue-3008-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum foo { foo(bar) } +enum foo { foo_(bar) } enum bar { bar_none, bar_some(bar) } //~^ ERROR illegal recursive enum type; wrap the inner value in a box to make it representable diff --git a/src/test/compile-fail/issue-3008-2.rs b/src/test/compile-fail/issue-3008-2.rs index db3124214bd..1e8f81a05e7 100644 --- a/src/test/compile-fail/issue-3008-2.rs +++ b/src/test/compile-fail/issue-3008-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum foo { foo(bar) } +enum foo { foo_(bar) } struct bar { x: bar } //~^ ERROR illegal recursive struct type; wrap the inner value in a box to make it representable //~^^ ERROR this type cannot be instantiated without an instance of itself diff --git a/src/test/compile-fail/recursion.rs b/src/test/compile-fail/recursion.rs index 96676257184..c99ec5187b0 100644 --- a/src/test/compile-fail/recursion.rs +++ b/src/test/compile-fail/recursion.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum Nil {Nil} +enum Nil {NilValue} struct Cons {head:int, tail:T} trait Dot {fn dot(&self, other:Self) -> int;} impl Dot for Nil { @@ -29,6 +29,6 @@ fn test (n:int, i:int, first:T, second:T) ->int { } } pub fn main() { - let n = test(1, 0, Nil, Nil); + let n = test(1, 0, NilValue, NilValue); println!("{}", n); } diff --git a/src/test/pretty/tag-blank-lines.rs b/src/test/pretty/tag-blank-lines.rs index 93373b0066d..29a3b965251 100644 --- a/src/test/pretty/tag-blank-lines.rs +++ b/src/test/pretty/tag-blank-lines.rs @@ -11,8 +11,8 @@ // pp-exact enum foo { - foo, // a foo. - bar, + bar, // a bar. + baz, } fn main() { } diff --git a/src/test/run-fail/issue-2444.rs b/src/test/run-fail/issue-2444.rs index dbe2a9e9229..9a5a8e7c38f 100644 --- a/src/test/run-fail/issue-2444.rs +++ b/src/test/run-fail/issue-2444.rs @@ -12,7 +12,7 @@ use std::sync::Arc; -enum e { e(Arc) } +enum e { ee(Arc) } fn foo() -> e {fail!();} diff --git a/src/test/run-pass/borrowck-univariant-enum.rs b/src/test/run-pass/borrowck-univariant-enum.rs index 0910f02dc29..8192566da19 100644 --- a/src/test/run-pass/borrowck-univariant-enum.rs +++ b/src/test/run-pass/borrowck-univariant-enum.rs @@ -13,7 +13,7 @@ use std::cell::Cell; use std::gc::GC; enum newtype { - newtype(int) + newvar(int) } pub fn main() { @@ -22,9 +22,9 @@ pub fn main() { // specially. let x = box(GC) Cell::new(5); - let y = box(GC) Cell::new(newtype(3)); + let y = box(GC) Cell::new(newvar(3)); let z = match y.get() { - newtype(b) => { + newvar(b) => { x.set(x.get() + 1); x.get() * b } diff --git a/src/test/run-pass/coerce-to-closure-and-proc.rs b/src/test/run-pass/coerce-to-closure-and-proc.rs index 15870b627b2..44a3517cc75 100644 --- a/src/test/run-pass/coerce-to-closure-and-proc.rs +++ b/src/test/run-pass/coerce-to-closure-and-proc.rs @@ -17,7 +17,7 @@ struct Foo(T); #[deriving(PartialEq, Show)] enum Bar { - Bar(T) + Baz(T) } pub fn main() { @@ -33,11 +33,11 @@ pub fn main() { let f: proc(int) -> Foo = Foo; assert_eq!(f(5), Foo(5)); - let f: |int| -> Bar = Bar; - assert_eq!(f(5), Bar(5)); + let f: |int| -> Bar = Baz; + assert_eq!(f(5), Baz(5)); - let f: proc(int) -> Bar = Bar; - assert_eq!(f(5), Bar(5)); + let f: proc(int) -> Bar = Baz; + assert_eq!(f(5), Baz(5)); let f: |int| -> Option = Some; assert_eq!(f(5), Some(5)); diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index d4b77ea4976..b160fa34c91 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -22,7 +22,7 @@ enum object { int_value(i64), } -fn lookup(table: json::Object, key: String, default: String) -> String +fn lookup(table: json::JsonObject, key: String, default: String) -> String { match table.find(&key.to_string()) { option::Some(&json::String(ref s)) => { diff --git a/src/test/run-pass/issue-3186.rs b/src/test/run-pass/issue-3186.rs deleted file mode 100644 index 6b35cd7e0c9..00000000000 --- a/src/test/run-pass/issue-3186.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2012 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. - -enum y { x } - -enum x {} - -pub fn main() {} diff --git a/src/test/run-pass/issue-3874.rs b/src/test/run-pass/issue-3874.rs index 40725311f31..75f6a2faa80 100644 --- a/src/test/run-pass/issue-3874.rs +++ b/src/test/run-pass/issue-3874.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum PureCounter { PureCounter(uint) } +enum PureCounter { PureCounterVariant(uint) } fn each(thing: PureCounter, blk: |v: &uint|) { - let PureCounter(ref x) = thing; + let PureCounterVariant(ref x) = thing; blk(x); } diff --git a/src/test/run-pass/match-arm-statics.rs b/src/test/run-pass/match-arm-statics.rs index a8f6d9c3917..6eb0a4dad1b 100644 --- a/src/test/run-pass/match-arm-statics.rs +++ b/src/test/run-pass/match-arm-statics.rs @@ -88,10 +88,10 @@ fn issue_14576() { } fn issue_13731() { - enum A { A(()) } - static B: A = A(()); + enum A { AA(()) } + static B: A = AA(()); - match A(()) { + match AA(()) { B => () } } diff --git a/src/test/run-pass/tag-align-shape.rs b/src/test/run-pass/tag-align-shape.rs index e161f6887e1..e032a5e4156 100644 --- a/src/test/run-pass/tag-align-shape.rs +++ b/src/test/run-pass/tag-align-shape.rs @@ -11,7 +11,7 @@ extern crate debug; enum a_tag { - a_tag(u64) + a_tag_var(u64) } struct t_rec { @@ -20,8 +20,8 @@ struct t_rec { } pub fn main() { - let x = t_rec {c8: 22u8, t: a_tag(44u64)}; + let x = t_rec {c8: 22u8, t: a_tag_var(44u64)}; let y = format!("{:?}", x); println!("y = {}", y); - assert_eq!(y, "t_rec{c8: 22u8, t: a_tag(44u64)}".to_string()); + assert_eq!(y, "t_rec{c8: 22u8, t: a_tag_var(44u64)}".to_string()); } diff --git a/src/test/run-pass/tag-align-u64.rs b/src/test/run-pass/tag-align-u64.rs index 8942e0b6b5d..398a0939d97 100644 --- a/src/test/run-pass/tag-align-u64.rs +++ b/src/test/run-pass/tag-align-u64.rs @@ -14,7 +14,7 @@ use std::mem; enum Tag { - Tag(u64) + TagInner(u64) } struct Rec { @@ -23,7 +23,7 @@ struct Rec { } fn mk_rec() -> Rec { - return Rec { c8:0u8, t:Tag(0u64) }; + return Rec { c8:0u8, t:TagInner(0u64) }; } fn is_8_byte_aligned(u: &Tag) -> bool { diff --git a/src/test/run-pass/xcrate-unit-struct.rs b/src/test/run-pass/xcrate-unit-struct.rs index ae8d628289d..9ba4b707268 100644 --- a/src/test/run-pass/xcrate-unit-struct.rs +++ b/src/test/run-pass/xcrate-unit-struct.rs @@ -12,7 +12,7 @@ extern crate xcrate_unit_struct; static s1: xcrate_unit_struct::Struct = xcrate_unit_struct::Struct; -static s2: xcrate_unit_struct::Unit = xcrate_unit_struct::Unit; +static s2: xcrate_unit_struct::Unit = xcrate_unit_struct::UnitVariant; static s3: xcrate_unit_struct::Unit = xcrate_unit_struct::Argument(xcrate_unit_struct::Struct); static s4: xcrate_unit_struct::Unit = xcrate_unit_struct::Argument(s1); @@ -22,7 +22,7 @@ fn f2(_: xcrate_unit_struct::Unit) {} pub fn main() { f1(xcrate_unit_struct::Struct); - f2(xcrate_unit_struct::Unit); + f2(xcrate_unit_struct::UnitVariant); f2(xcrate_unit_struct::Argument(xcrate_unit_struct::Struct)); f1(s1); -- cgit 1.4.1-3-g733a5 From 89b09440d87a8346c2e6206855ab4f0b90febe25 Mon Sep 17 00:00:00 2001 From: Florian Hahn Date: Sat, 13 Sep 2014 12:55:00 +0200 Subject: Allow syntax extensions to return multiple items, closes #16723. This patch replaces `MacItem` with `MacItems`. --- src/libsyntax/diagnostics/plugin.rs | 8 +++--- src/libsyntax/ext/base.rs | 27 ++++++++---------- .../issue_16723_multiple_items_syntax_ext.rs | 33 ++++++++++++++++++++++ .../issue_16723_multiple_items_syntax_ext.rs | 30 ++++++++++++++++++++ 4 files changed, 78 insertions(+), 20 deletions(-) create mode 100644 src/test/auxiliary/issue_16723_multiple_items_syntax_ext.rs create mode 100644 src/test/run-pass-fulldeps/issue_16723_multiple_items_syntax_ext.rs (limited to 'src/libsyntax') diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 132b59c89b2..d3c39284f55 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; use ast; use ast::{Ident, Name, TokenTree}; use codemap::Span; -use ext::base::{ExtCtxt, MacExpr, MacItem, MacResult}; +use ext::base::{ExtCtxt, MacExpr, MacResult, MacItems}; use ext::build::AstBuilder; use parse::token; use ptr::P; @@ -102,7 +102,7 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, let sym = Ident::new(token::gensym(( "__register_diagnostic_".to_string() + token::get_ident(*code).get() ).as_slice())); - MacItem::new(quote_item!(ecx, mod $sym {}).unwrap()) + MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter()) } pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, @@ -133,7 +133,7 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, (descriptions.len(), ecx.expr_vec(span, descriptions)) }) }); - MacItem::new(quote_item!(ecx, + MacItems::new(vec![quote_item!(ecx, pub static $name: [(&'static str, &'static str), ..$count] = $expr; - ).unwrap()) + ).unwrap()].into_iter()) } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 773daa4a4c5..fbbbea541a6 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -203,25 +203,20 @@ impl MacResult for MacPat { Some(self.p) } } -/// A convenience type for macros that return a single item. -pub struct MacItem { - i: P +/// A type for macros that return multiple items. +pub struct MacItems { + items: SmallVector> } -impl MacItem { - pub fn new(i: P) -> Box { - box MacItem { i: i } as Box + +impl MacItems { + pub fn new>>(mut it: I) -> Box { + box MacItems { items: it.collect() } as Box } } -impl MacResult for MacItem { - fn make_items(self: Box) -> Option>> { - Some(SmallVector::one(self.i)) - } - fn make_stmt(self: Box) -> Option> { - Some(P(codemap::respan( - self.i.span, - ast::StmtDecl( - P(codemap::respan(self.i.span, ast::DeclItem(self.i))), - ast::DUMMY_NODE_ID)))) + +impl MacResult for MacItems { + fn make_items(self: Box) -> Option>> { + Some(self.items) } } diff --git a/src/test/auxiliary/issue_16723_multiple_items_syntax_ext.rs b/src/test/auxiliary/issue_16723_multiple_items_syntax_ext.rs new file mode 100644 index 00000000000..269afea52c2 --- /dev/null +++ b/src/test/auxiliary/issue_16723_multiple_items_syntax_ext.rs @@ -0,0 +1,33 @@ +// Copyright 2012 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. +// +// ignore-stage1 +#![feature(plugin_registrar, managed_boxes, quote)] +#![crate_type = "dylib"] + +extern crate syntax; +extern crate rustc; + +use syntax::ast; +use syntax::codemap; +use syntax::ext::base::{ExtCtxt, MacResult, MacItems}; +use rustc::plugin::Registry; + +#[plugin_registrar] +pub fn plugin_registrar(reg: &mut Registry) { + reg.register_macro("multiple_items", expand) +} + +fn expand(cx: &mut ExtCtxt, _: codemap::Span, _: &[ast::TokenTree]) -> Box { + MacItems::new(vec![ + quote_item!(cx, struct Struct1;).unwrap(), + quote_item!(cx, struct Struct2;).unwrap() + ].into_iter()) +} diff --git a/src/test/run-pass-fulldeps/issue_16723_multiple_items_syntax_ext.rs b/src/test/run-pass-fulldeps/issue_16723_multiple_items_syntax_ext.rs new file mode 100644 index 00000000000..431ae1b13dd --- /dev/null +++ b/src/test/run-pass-fulldeps/issue_16723_multiple_items_syntax_ext.rs @@ -0,0 +1,30 @@ +// Copyright 2012 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. + +// ignore-stage1 +// aux-build:issue_16723_multiple_items_syntax_ext.rs +#![feature(phase)] + +#[phase(plugin)] extern crate issue_16723_multiple_items_syntax_ext; + +multiple_items!() + +impl Struct1 { + fn foo() {} +} +impl Struct2 { + fn foo() {} +} + +fn main() { + Struct1::foo(); + Struct2::foo(); + println!("hallo"); +} -- cgit 1.4.1-3-g733a5