diff --git a/mk/crates.mk b/mk/crates.mk index 77cea02f43b73..3a2def389cc24 100644 --- a/mk/crates.mk +++ b/mk/crates.mk @@ -53,8 +53,8 @@ TARGET_CRATES := libc std flate arena term \ serialize getopts collections test time rand \ log regex graphviz core rbml alloc rustrt \ unicode -HOST_CRATES := syntax rustc rustc_trans rustdoc regex_macros fmt_macros \ - rustc_llvm rustc_back +RUSTC_CRATES := rustc rustc_typeck rustc_driver rustc_trans rustc_back rustc_llvm +HOST_CRATES := syntax $(RUSTC_CRATES) rustdoc regex_macros fmt_macros CRATES := $(TARGET_CRATES) $(HOST_CRATES) TOOLS := compiletest rustdoc rustc @@ -67,12 +67,16 @@ DEPS_std := core libc rand alloc collections rustrt unicode \ native:rust_builtin native:backtrace DEPS_graphviz := std DEPS_syntax := std term serialize log fmt_macros arena libc -DEPS_rustc_trans := rustc rustc_back rustc_llvm libc +DEPS_rustc_driver := arena flate getopts graphviz libc rustc rustc_back \ + rustc_typeck log syntax serialize rustc_llvm rustc_trans +DEPS_rustc_trans := arena flate getopts graphviz libc rustc rustc_back \ + log syntax serialize rustc_llvm +DEPS_rustc_typeck := rustc syntax DEPS_rustc := syntax flate arena serialize getopts rbml \ time log graphviz rustc_llvm rustc_back DEPS_rustc_llvm := native:rustllvm libc std DEPS_rustc_back := std syntax rustc_llvm flate log libc -DEPS_rustdoc := rustc rustc_trans native:hoedown serialize getopts \ +DEPS_rustdoc := rustc rustc_driver native:hoedown serialize getopts \ test time DEPS_flate := std native:miniz DEPS_arena := std @@ -94,7 +98,7 @@ DEPS_fmt_macros = std TOOL_DEPS_compiletest := test getopts TOOL_DEPS_rustdoc := rustdoc -TOOL_DEPS_rustc := rustc_trans +TOOL_DEPS_rustc := rustc_driver TOOL_SOURCE_compiletest := $(S)src/compiletest/compiletest.rs TOOL_SOURCE_rustdoc := $(S)src/driver/driver.rs TOOL_SOURCE_rustc := $(S)src/driver/driver.rs @@ -110,8 +114,12 @@ ONLY_RLIB_unicode := 1 # You should not need to edit below this line ################################################################################ -DOC_CRATES := $(filter-out rustc, $(filter-out rustc_trans, $(filter-out syntax, $(CRATES)))) -COMPILER_DOC_CRATES := rustc rustc_trans syntax +DOC_CRATES := $(filter-out rustc, \ + $(filter-out rustc_trans, \ + $(filter-out rustc_typeck, \ + $(filter-out rustc_driver, \ + $(filter-out syntax, $(CRATES)))))) +COMPILER_DOC_CRATES := rustc rustc_trans rustc_typeck rustc_driver syntax # This macro creates some simple definitions for each crate being built, just # some munging of all of the parameters above. diff --git a/src/doc/guide.md b/src/doc/guide.md index c2d43a20ec46c..45bff480f7b6d 100644 --- a/src/doc/guide.md +++ b/src/doc/guide.md @@ -2064,8 +2064,8 @@ Great! Next up: let's compare our guess to the secret guess. ## Comparing guesses If you remember, earlier in the guide, we made a `cmp` function that compared -two numbers. Let's add that in, along with a `match` statement to compare the -guess to the secret guess: +two numbers. Let's add that in, along with a `match` statement to compare our +guess to the secret number: ```{rust,ignore} use std::io; @@ -2861,7 +2861,7 @@ parts of your library. The six levels are: * experimental: This item was only recently introduced or is otherwise in a state of flux. It may change significantly, or even be removed. No guarantee of backwards-compatibility. -* unstable: This item is still under development, but requires more testing to +* unstable: This item is still under development and requires more testing to be considered stable. No guarantee of backwards-compatibility. * stable: This item is considered stable, and will not change significantly. Guarantee of backwards-compatibility. diff --git a/src/doc/reference.md b/src/doc/reference.md index 1d27ac096df8a..9ac4469d54983 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -522,7 +522,7 @@ The two values of the boolean type are written `true` and `false`. ### Symbols ```{.ebnf .gram} -symbol : "::" "->" +symbol : "::" | "->" | '#' | '[' | ']' | '(' | ')' | '{' | '}' | ',' | ';' ; ``` @@ -994,7 +994,7 @@ An example of `use` declarations: ``` use std::iter::range_step; -use std::option::{Some, None}; +use std::option::Option::{Some, None}; use std::collections::hash_map::{mod, HashMap}; fn foo(_: T){} @@ -1004,8 +1004,8 @@ fn main() { // Equivalent to 'std::iter::range_step(0u, 10u, 2u);' range_step(0u, 10u, 2u); - // Equivalent to 'foo(vec![std::option::Some(1.0f64), - // std::option::None]);' + // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64), + // std::option::Option::None]);' foo(vec![Some(1.0f64), None]); // Both `hash_map` and `HashMap` are in scope. diff --git a/src/driver/driver.rs b/src/driver/driver.rs index 632d21d7b9c05..5c29cb4ec7276 100644 --- a/src/driver/driver.rs +++ b/src/driver/driver.rs @@ -12,6 +12,6 @@ extern crate "rustdoc" as this; #[cfg(rustc)] -extern crate "rustc_trans" as this; +extern crate "rustc_driver" as this; fn main() { this::main() } diff --git a/src/etc/gdb_rust_pretty_printing.py b/src/etc/gdb_rust_pretty_printing.py index 1af649f073176..7e5918ea39e1e 100644 --- a/src/etc/gdb_rust_pretty_printing.py +++ b/src/etc/gdb_rust_pretty_printing.py @@ -54,13 +54,14 @@ def rust_pretty_printer_lookup_function(val): return RustStructPrinter(val, false) if enum_member_count == 1: - if enum_members[0].name == None: + first_variant_name = enum_members[0].name + if first_variant_name == None: # This is a singleton enum return rust_pretty_printer_lookup_function(val[enum_members[0]]) else: - assert enum_members[0].name.startswith("RUST$ENCODED$ENUM$") + assert first_variant_name.startswith("RUST$ENCODED$ENUM$") # This is a space-optimized enum - last_separator_index = enum_members[0].name.rfind("$") + last_separator_index = first_variant_name.rfind("$") second_last_separator_index = first_variant_name.rfind("$", 0, last_separator_index) disr_field_index = first_variant_name[second_last_separator_index + 1 : last_separator_index] @@ -68,7 +69,12 @@ def rust_pretty_printer_lookup_function(val): sole_variant_val = val[enum_members[0]] disr_field = get_field_at_index(sole_variant_val, disr_field_index) - discriminant = int(sole_variant_val[disr_field]) + discriminant = sole_variant_val[disr_field] + + # If the discriminant field is a fat pointer we have to consider the + # first word as the true discriminant + if discriminant.type.code == gdb.TYPE_CODE_STRUCT: + discriminant = discriminant[get_field_at_index(discriminant, 0)] if discriminant == 0: null_variant_name = first_variant_name[last_separator_index + 1:] @@ -173,7 +179,7 @@ def to_string(self): class IdentityPrinter: def __init__(self, string): - self.string + self.string = string def to_string(self): return self.string diff --git a/src/etc/lldb_rust_formatters.py b/src/etc/lldb_rust_formatters.py index 7924d63c8e0d5..f4f1a5121d195 100644 --- a/src/etc/lldb_rust_formatters.py +++ b/src/etc/lldb_rust_formatters.py @@ -138,9 +138,14 @@ def print_enum_val(val, internal_dict): return "" % first_variant_name # Read the discriminant - disr_val = val.GetChildAtIndex(0).GetChildAtIndex(disr_field_index).GetValueAsUnsigned() + disr_val = val.GetChildAtIndex(0).GetChildAtIndex(disr_field_index) - if disr_val == 0: + # If the discriminant field is a fat pointer we have to consider the + # first word as the true discriminant + if disr_val.GetType().GetTypeClass() == lldb.eTypeClassStruct: + disr_val = disr_val.GetChildAtIndex(0) + + if disr_val.GetValueAsUnsigned() == 0: # Null case: Print the name of the null-variant null_variant_name = first_variant_name[last_separator_index + 1:] return null_variant_name diff --git a/src/etc/unicode.py b/src/etc/unicode.py index 15263919fb9b8..20edf9418f148 100755 --- a/src/etc/unicode.py +++ b/src/etc/unicode.py @@ -292,7 +292,7 @@ def escape_char(c): def emit_bsearch_range_table(f): f.write(""" fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; r.binary_search(|&(lo,hi)| { if lo <= c && c <= hi { Equal } @@ -350,10 +350,11 @@ def emit_regex_module(f, cats, w_data): def emit_conversions_module(f, lowerupper, upperlower): f.write("pub mod conversions {") f.write(""" - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; use core::tuple::Tuple2; - use core::option::{Option, Some, None}; + use core::option::Option; + use core::option::Option::{Some, None}; use core::slice; pub fn to_lower(c: char) -> char { @@ -403,7 +404,7 @@ def emit_grapheme_module(f, grapheme_table, grapheme_cats): f.write(""" } fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; match r.binary_search(|&(lo, hi, _)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } @@ -430,12 +431,13 @@ def emit_grapheme_module(f, grapheme_table, grapheme_cats): def emit_charwidth_module(f, width_table): f.write("pub mod charwidth {\n") - f.write(" use core::option::{Option, Some, None};\n") + f.write(" use core::option::Option;\n") + f.write(" use core::option::Option::{Some, None};\n") f.write(" use core::slice::SlicePrelude;\n") f.write(" use core::slice;\n") f.write(""" fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; match r.binary_search(|&(lo, hi, _, _)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } @@ -530,7 +532,7 @@ def comp_pfun(char): f.write(""" fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; use core::slice; match r.binary_search(|&(lo, hi, _)| { diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 4f744b0b2dee1..ef05279e825ea 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -22,7 +22,8 @@ use core::kinds::{Sync, Send}; use core::mem::{min_align_of, size_of, drop}; use core::mem; use core::ops::{Drop, Deref}; -use core::option::{Some, None, Option}; +use core::option::Option; +use core::option::Option::{Some, None}; use core::ptr::RawPtr; use core::ptr; use heap::deallocate; @@ -326,7 +327,8 @@ mod tests { use std::comm::channel; use std::mem::drop; use std::ops::Drop; - use std::option::{Option, Some, None}; + use std::option::Option; + use std::option::Option::{Some, None}; use std::str::Str; use std::sync::atomic; use std::task; diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 000dda59e3dda..eb483498998c5 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -19,7 +19,8 @@ use core::kinds::Sized; use core::mem; use core::option::Option; use core::raw::TraitObject; -use core::result::{Ok, Err, Result}; +use core::result::Result; +use core::result::Result::{Ok, Err}; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index 579f47ee87466..06605bfff215c 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -125,7 +125,8 @@ const MIN_ALIGN: uint = 16; #[cfg(jemalloc)] mod imp { - use core::option::{None, Option}; + use core::option::Option; + use core::option::Option::None; use core::ptr::{null_mut, null}; use core::num::Int; use libc::{c_char, c_int, c_void, size_t}; diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index e626d63937bc2..53891583edb20 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -149,10 +149,12 @@ use core::fmt; use core::kinds::marker; use core::mem::{transmute, min_align_of, size_of, forget}; use core::ops::{Deref, Drop}; -use core::option::{Option, Some, None}; +use core::option::Option; +use core::option::Option::{Some, None}; use core::ptr; use core::ptr::RawPtr; -use core::result::{Result, Ok, Err}; +use core::result::Result; +use core::result::Result::{Ok, Err}; use heap::deallocate; @@ -739,8 +741,9 @@ impl RcBoxPtr for Weak { mod tests { use super::{Rc, Weak, weak_count, strong_count}; use std::cell::RefCell; - use std::option::{Option, Some, None}; - use std::result::{Err, Ok}; + use std::option::Option; + use std::option::Option::{Some, None}; + use std::result::Result::{Err, Ok}; use std::mem::drop; use std::clone::Clone; diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 3f95bda663e15..39cdf0c456413 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -945,7 +945,7 @@ mod tests { let mut m = list_from(v.as_slice()); m.rotate_backward(); check_links(&m); m.rotate_forward(); check_links(&m); - assert_eq!(v.iter().collect::>(), m.iter().collect()); + assert_eq!(v.iter().collect::>(), m.iter().collect::>()); m.rotate_forward(); check_links(&m); m.rotate_forward(); check_links(&m); m.pop_front(); check_links(&m); @@ -953,7 +953,7 @@ mod tests { m.rotate_backward(); check_links(&m); m.push_front(9); check_links(&m); m.rotate_forward(); check_links(&m); - assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect()); + assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::>()); } #[test] diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index d21465c822f47..2cbde0168a2e8 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -397,23 +397,23 @@ mod test { fn test_iterator() { let mut e1: EnumSet = EnumSet::new(); - let elems: Vec = e1.iter().collect(); + let elems: ::vec::Vec = e1.iter().collect(); assert!(elems.is_empty()) e1.insert(A); - let elems = e1.iter().collect(); + let elems: ::vec::Vec<_> = e1.iter().collect(); assert_eq!(vec![A], elems) e1.insert(C); - let elems = e1.iter().collect(); + let elems: ::vec::Vec<_> = e1.iter().collect(); assert_eq!(vec![A,C], elems) e1.insert(C); - let elems = e1.iter().collect(); + let elems: ::vec::Vec<_> = e1.iter().collect(); assert_eq!(vec![A,C], elems) e1.insert(B); - let elems = e1.iter().collect(); + let elems: ::vec::Vec<_> = e1.iter().collect(); assert_eq!(vec![A,B,C], elems) } @@ -431,35 +431,35 @@ mod test { e2.insert(C); let e_union = e1 | e2; - let elems = e_union.iter().collect(); + let elems: ::vec::Vec<_> = e_union.iter().collect(); assert_eq!(vec![A,B,C], elems) let e_intersection = e1 & e2; - let elems = e_intersection.iter().collect(); + let elems: ::vec::Vec<_> = e_intersection.iter().collect(); assert_eq!(vec![C], elems) // Another way to express intersection let e_intersection = e1 - (e1 - e2); - let elems = e_intersection.iter().collect(); + let elems: ::vec::Vec<_> = e_intersection.iter().collect(); assert_eq!(vec![C], elems) let e_subtract = e1 - e2; - let elems = e_subtract.iter().collect(); + let elems: ::vec::Vec<_> = e_subtract.iter().collect(); assert_eq!(vec![A], elems) // Bitwise XOR of two sets, aka symmetric difference let e_symmetric_diff = e1 ^ e2; - let elems = e_symmetric_diff.iter().collect(); + let elems: ::vec::Vec<_> = e_symmetric_diff.iter().collect(); assert_eq!(vec![A,B], elems) // Another way to express symmetric difference let e_symmetric_diff = (e1 - e2) | (e2 - e1); - let elems = e_symmetric_diff.iter().collect(); + let elems: ::vec::Vec<_> = e_symmetric_diff.iter().collect(); assert_eq!(vec![A,B], elems) // Yet another way to express symmetric difference let e_symmetric_diff = (e1 | e2) - (e1 & e2); - let elems = e_symmetric_diff.iter().collect(); + let elems: ::vec::Vec<_> = e_symmetric_diff.iter().collect(); assert_eq!(vec![A,B], elems) } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index c6fa1332186ec..78cdda61104f1 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -563,6 +563,7 @@ impl<'a> Ord for MaybeOwned<'a> { } } +#[allow(deprecated)] #[deprecated = "use std::str::CowString"] impl<'a, S: Str> Equiv for MaybeOwned<'a> { #[inline] @@ -832,8 +833,10 @@ mod tests { use std::default::Default; use std::char::Char; use std::clone::Clone; - use std::cmp::{Equal, Greater, Less, Ord, PartialOrd, Equiv}; - use std::option::{Some, None}; + use std::cmp::{Ord, PartialOrd, Equiv}; + use std::cmp::Ordering::{Equal, Greater, Less}; + use std::option::Option; + use std::option::Option::{Some, None}; use std::ptr::RawPtr; use std::iter::{Iterator, IteratorExt, DoubleEndedIteratorExt}; diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 38b67fbd74451..fbb0bb5c4ce86 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -30,7 +30,7 @@ use str::{CharRange, CowString, FromStr, StrAllocating, Owned}; use vec::{DerefVec, Vec, as_vec}; /// A growable string stored as a UTF-8 encoded buffer. -#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord)] +#[deriving(Clone, PartialOrd, Eq, Ord)] #[stable] pub struct String { vec: Vec, @@ -738,6 +738,49 @@ impl Extend for String { } } +impl PartialEq for String { + #[inline] + fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) } +} + +macro_rules! impl_eq { + ($lhs:ty, $rhs: ty) => { + impl<'a> PartialEq<$rhs> for $lhs { + #[inline] + fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) } + } + + impl<'a> PartialEq<$lhs> for $rhs { + #[inline] + fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) } + } + + } +} + +impl_eq!(String, &'a str) +impl_eq!(CowString<'a>, String) + +impl<'a, 'b> PartialEq<&'b str> for CowString<'a> { + #[inline] + fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) } +} + +impl<'a, 'b> PartialEq> for &'b str { + #[inline] + fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) } +} + #[experimental = "waiting on Str stabilization"] impl Str for String { #[inline] @@ -779,7 +822,8 @@ impl hash::Hash for String { } } -#[experimental = "waiting on Equiv stabilization"] +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl<'a, S: Str> Equiv for String { #[inline] fn equiv(&self, other: &S) -> bool { @@ -967,10 +1011,12 @@ mod tests { #[test] fn test_from_utf8_lossy() { let xs = b"hello"; - assert_eq!(String::from_utf8_lossy(xs), "hello".into_cow()); + let ys: str::CowString = "hello".into_cow(); + assert_eq!(String::from_utf8_lossy(xs), ys); let xs = "ศไทย中华Việt Nam".as_bytes(); - assert_eq!(String::from_utf8_lossy(xs), "ศไทย中华Việt Nam".into_cow()); + let ys: str::CowString = "ศไทย中华Việt Nam".into_cow(); + assert_eq!(String::from_utf8_lossy(xs), ys); let xs = b"Hello\xC2 There\xFF Goodbye"; assert_eq!(String::from_utf8_lossy(xs), diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 5edd3d0b780be..2396cf8cec67c 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -535,14 +535,69 @@ impl Extend for Vec { } } -#[unstable = "waiting on PartialEq stability"] -impl PartialEq for Vec { +impl PartialEq> for Vec where A: PartialEq { #[inline] - fn eq(&self, other: &Vec) -> bool { - self.as_slice() == other.as_slice() + fn eq(&self, other: &Vec) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &Vec) -> bool { PartialEq::ne(&**self, &**other) } +} + +macro_rules! impl_eq { + ($lhs:ty, $rhs:ty) => { + impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq { + #[inline] + fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) } + } + + impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq { + #[inline] + fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) } + } } } +impl_eq!(Vec, &'b [B]) +impl_eq!(Vec, &'b mut [B]) + +impl<'a, A, B> PartialEq> for CowVec<'a, A> where A: PartialEq + Clone { + #[inline] + fn eq(&self, other: &Vec) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &Vec) -> bool { PartialEq::ne(&**self, &**other) } +} + +impl<'a, A, B> PartialEq> for Vec where A: Clone, B: PartialEq { + #[inline] + fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) } +} + +macro_rules! impl_eq_for_cowvec { + ($rhs:ty) => { + impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq + Clone { + #[inline] + fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) } + } + + impl<'a, 'b, A, B> PartialEq> for $rhs where A: Clone, B: PartialEq { + #[inline] + fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) } + #[inline] + fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) } + } + } +} + +impl_eq_for_cowvec!(&'b [B]) +impl_eq_for_cowvec!(&'b mut [B]) + #[unstable = "waiting on PartialOrd stability"] impl PartialOrd for Vec { #[inline] @@ -554,7 +609,8 @@ impl PartialOrd for Vec { #[unstable = "waiting on Eq stability"] impl Eq for Vec {} -#[experimental] +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl> Equiv for Vec { #[inline] fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } @@ -1813,13 +1869,13 @@ mod tests { let mut values = vec![1u8,2,3,4,5]; { let slice = values.slice_from_mut(2); - assert!(slice == &mut [3, 4, 5]); + assert!(slice == [3, 4, 5]); for p in slice.iter_mut() { *p += 2; } } - assert!(values.as_slice() == &[1, 2, 5, 6, 7]); + assert!(values.as_slice() == [1, 2, 5, 6, 7]); } #[test] @@ -1827,13 +1883,13 @@ mod tests { let mut values = vec![1u8,2,3,4,5]; { let slice = values.slice_to_mut(2); - assert!(slice == &mut [1, 2]); + assert!(slice == [1, 2]); for p in slice.iter_mut() { *p += 1; } } - assert!(values.as_slice() == &[2, 3, 3, 4, 5]); + assert!(values.as_slice() == [2, 3, 3, 4, 5]); } #[test] diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 5d1f996831e5b..75feb4d88289e 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -72,7 +72,8 @@ #![stable] use mem::{transmute}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 60765e82cb476..ffaf35414ea0c 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -18,6 +18,7 @@ use clone::Clone; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use fmt; use kinds::Copy; +use ops::Deref; use option::Option; // macro for implementing n-ary tuple functions and operations @@ -39,17 +40,37 @@ macro_rules! array_impls { } #[unstable = "waiting for PartialEq to stabilize"] - impl PartialEq for [T, ..$N] { + impl PartialEq<[B, ..$N]> for [A, ..$N] where A: PartialEq { #[inline] - fn eq(&self, other: &[T, ..$N]) -> bool { + fn eq(&self, other: &[B, ..$N]) -> bool { self[] == other[] } #[inline] - fn ne(&self, other: &[T, ..$N]) -> bool { + fn ne(&self, other: &[B, ..$N]) -> bool { self[] != other[] } } + impl<'a, A, B, Rhs> PartialEq for [A, ..$N] where + A: PartialEq, + Rhs: Deref<[B]>, + { + #[inline(always)] + fn eq(&self, other: &Rhs) -> bool { PartialEq::eq(self[], &**other) } + #[inline(always)] + fn ne(&self, other: &Rhs) -> bool { PartialEq::ne(self[], &**other) } + } + + impl<'a, A, B, Lhs> PartialEq<[B, ..$N]> for Lhs where + A: PartialEq, + Lhs: Deref<[A]> + { + #[inline(always)] + fn eq(&self, other: &[B, ..$N]) -> bool { PartialEq::eq(&**self, other[]) } + #[inline(always)] + fn ne(&self, other: &[B, ..$N]) -> bool { PartialEq::ne(&**self, other[]) } + } + #[unstable = "waiting for Eq to stabilize"] impl Eq for [T, ..$N] { } diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 06fda8d60928f..b44b87bd93807 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -137,6 +137,18 @@ pub enum Cow<'a, T, Sized? B: 'a> where B: ToOwned { Owned(T) } +impl<'a, T, Sized? B> Clone for Cow<'a, T, B> where B: ToOwned { + fn clone(&self) -> Cow<'a, T, B> { + match *self { + Borrowed(b) => Borrowed(b), + Owned(ref o) => { + let b: &B = BorrowFrom::borrow_from(o); + Owned(b.to_owned()) + }, + } + } +} + impl<'a, T, Sized? B> Cow<'a, T, B> where B: ToOwned { /// Acquire a mutable reference to the owned form of the data. /// @@ -196,9 +208,12 @@ impl<'a, T, Sized? B> Ord for Cow<'a, T, B> where B: Ord + ToOwned { } } -impl<'a, T, Sized? B> PartialEq for Cow<'a, T, B> where B: PartialEq + ToOwned { +impl<'a, 'b, T, U, Sized? B, Sized? C> PartialEq> for Cow<'a, T, B> where + B: PartialEq + ToOwned, + C: ToOwned, +{ #[inline] - fn eq(&self, other: &Cow<'a, T, B>) -> bool { + fn eq(&self, other: &Cow<'b, U, C>) -> bool { PartialEq::eq(&**self, &**other) } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 587bb4cb110e1..1ec2efaf801a4 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -160,7 +160,8 @@ use cmp::PartialEq; use default::Default; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; -use option::{None, Option, Some}; +use option::Option; +use option::Option::{None, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] @@ -277,12 +278,9 @@ impl RefCell { /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option> { - match self.borrow.get() { - WRITING => None, - borrow => { - self.borrow.set(borrow + 1); - Some(Ref { _parent: self }) - } + match BorrowRef::new(&self.borrow) { + Some(b) => Some(Ref { _value: unsafe { &*self.value.get() }, _borrow: b }), + None => None, } } @@ -310,12 +308,9 @@ impl RefCell { /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option> { - match self.borrow.get() { - UNUSED => { - self.borrow.set(WRITING); - Some(RefMut { _parent: self }) - }, - _ => None + match BorrowRefMut::new(&self.borrow) { + Some(b) => Some(RefMut { _value: unsafe { &mut *self.value.get() }, _borrow: b }), + None => None, } } @@ -368,29 +363,56 @@ impl PartialEq for RefCell { } } -/// Wraps a borrowed reference to a value in a `RefCell` box. -#[unstable] -pub struct Ref<'b, T:'b> { - // FIXME #12808: strange name to try to avoid interfering with - // field accesses of the contained type via Deref - _parent: &'b RefCell +struct BorrowRef<'b> { + _borrow: &'b Cell, +} + +impl<'b> BorrowRef<'b> { + fn new(borrow: &'b Cell) -> Option> { + match borrow.get() { + WRITING => None, + b => { + borrow.set(b + 1); + Some(BorrowRef { _borrow: borrow }) + }, + } + } } #[unsafe_destructor] -#[unstable] -impl<'b, T> Drop for Ref<'b, T> { +impl<'b> Drop for BorrowRef<'b> { fn drop(&mut self) { - let borrow = self._parent.borrow.get(); + let borrow = self._borrow.get(); debug_assert!(borrow != WRITING && borrow != UNUSED); - self._parent.borrow.set(borrow - 1); + self._borrow.set(borrow - 1); } } +impl<'b> Clone for BorrowRef<'b> { + fn clone(&self) -> BorrowRef<'b> { + // Since this Ref exists, we know the borrow flag + // is not set to WRITING. + let borrow = self._borrow.get(); + debug_assert!(borrow != WRITING && borrow != UNUSED); + self._borrow.set(borrow + 1); + BorrowRef { _borrow: self._borrow } + } +} + +/// Wraps a borrowed reference to a value in a `RefCell` box. +#[unstable] +pub struct Ref<'b, T:'b> { + // FIXME #12808: strange name to try to avoid interfering with + // field accesses of the contained type via Deref + _value: &'b T, + _borrow: BorrowRef<'b>, +} + #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { - unsafe { &*self._parent.value.get() } + self._value } } @@ -401,41 +423,52 @@ impl<'b, T> Deref for Ref<'b, T> { /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] -pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { - // Since this Ref exists, we know the borrow flag - // is not set to WRITING. - let borrow = orig._parent.borrow.get(); - debug_assert!(borrow != WRITING && borrow != UNUSED); - orig._parent.borrow.set(borrow + 1); - +pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> { Ref { - _parent: orig._parent, + _value: orig._value, + _borrow: orig._borrow.clone(), } } -/// Wraps a mutable borrowed reference to a value in a `RefCell` box. -#[unstable] -pub struct RefMut<'b, T:'b> { - // FIXME #12808: strange name to try to avoid interfering with - // field accesses of the contained type via Deref - _parent: &'b RefCell +struct BorrowRefMut<'b> { + _borrow: &'b Cell, } #[unsafe_destructor] -#[unstable] -impl<'b, T> Drop for RefMut<'b, T> { +impl<'b> Drop for BorrowRefMut<'b> { fn drop(&mut self) { - let borrow = self._parent.borrow.get(); + let borrow = self._borrow.get(); debug_assert!(borrow == WRITING); - self._parent.borrow.set(UNUSED); + self._borrow.set(UNUSED); } } +impl<'b> BorrowRefMut<'b> { + fn new(borrow: &'b Cell) -> Option> { + match borrow.get() { + UNUSED => { + borrow.set(WRITING); + Some(BorrowRefMut { _borrow: borrow }) + }, + _ => None, + } + } +} + +/// Wraps a mutable borrowed reference to a value in a `RefCell` box. +#[unstable] +pub struct RefMut<'b, T:'b> { + // FIXME #12808: strange name to try to avoid interfering with + // field accesses of the contained type via Deref + _value: &'b mut T, + _borrow: BorrowRefMut<'b>, +} + #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { - unsafe { &*self._parent.value.get() } + self._value } } @@ -443,7 +476,7 @@ impl<'b, T> Deref for RefMut<'b, T> { impl<'b, T> DerefMut for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { - unsafe { &mut *self._parent.value.get() } + self._value } } diff --git a/src/libcore/char.rs b/src/libcore/char.rs index a729596e9d290..2bebe87a14ce4 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -16,7 +16,8 @@ #![doc(primitive = "char")] use mem::transmute; -use option::{None, Option, Some}; +use option::Option; +use option::Option::{None, Some}; use iter::{range_step, Iterator, RangeStep}; use slice::SlicePrelude; diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 51122d0a17023..a5ba2b03b1565 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -44,7 +44,8 @@ pub use self::Ordering::*; use kinds::Sized; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; /// Trait for values that can be compared for equality and inequality. /// @@ -61,13 +62,13 @@ use option::{Option, Some, None}; /// `Eq`. #[lang="eq"] #[unstable = "Definition may change slightly after trait reform"] -pub trait PartialEq for Sized? { +pub trait PartialEq for Sized? { /// This method tests for `self` and `other` values to be equal, and is used by `==`. - fn eq(&self, other: &Self) -> bool; + fn eq(&self, other: &Rhs) -> bool; /// This method tests for `!=`. #[inline] - fn ne(&self, other: &Self) -> bool { !self.eq(other) } + fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } } /// Trait for equality comparisons which are [equivalence relations]( @@ -80,7 +81,7 @@ pub trait PartialEq for Sized? { /// - symmetric: `a == b` implies `b == a`; and /// - transitive: `a == b` and `b == c` implies `a == c`. #[unstable = "Definition may change slightly after trait reform"] -pub trait Eq for Sized?: PartialEq { +pub trait Eq for Sized?: PartialEq { // FIXME #13101: this method is used solely by #[deriving] to // assert that every component of a type implements #[deriving] // itself, the current deriving infrastructure means doing this @@ -150,7 +151,7 @@ impl Ordering { /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for /// both `==` and `>`. #[unstable = "Definition may change slightly after trait reform"] -pub trait Ord for Sized?: Eq + PartialOrd { +pub trait Ord for Sized?: Eq + PartialOrd { /// This method returns an ordering between `self` and `other` values. /// /// By convention, `self.cmp(&other)` returns the ordering matching @@ -161,7 +162,7 @@ pub trait Ord for Sized?: Eq + PartialOrd { /// assert_eq!(10u.cmp(&5), Greater); // because 10 > 5 /// assert_eq!( 5u.cmp(&5), Equal); // because 5 == 5 /// ``` - fn cmp(&self, other: &Self) -> Ordering; + fn cmp(&self, other: &Rhs) -> Ordering; } #[unstable = "Trait is unstable."] @@ -194,14 +195,14 @@ impl PartialOrd for Ordering { /// 5.11). #[lang="ord"] #[unstable = "Definition may change slightly after trait reform"] -pub trait PartialOrd for Sized?: PartialEq { +pub trait PartialOrd for Sized?: PartialEq { /// This method returns an ordering between `self` and `other` values /// if one exists. - fn partial_cmp(&self, other: &Self) -> Option; + fn partial_cmp(&self, other: &Rhs) -> Option; /// This method tests less than (for `self` and `other`) and is used by the `<` operator. #[inline] - fn lt(&self, other: &Self) -> bool { + fn lt(&self, other: &Rhs) -> bool { match self.partial_cmp(other) { Some(Less) => true, _ => false, @@ -210,7 +211,7 @@ pub trait PartialOrd for Sized?: PartialEq { /// This method tests less than or equal to (`<=`). #[inline] - fn le(&self, other: &Self) -> bool { + fn le(&self, other: &Rhs) -> bool { match self.partial_cmp(other) { Some(Less) | Some(Equal) => true, _ => false, @@ -219,7 +220,7 @@ pub trait PartialOrd for Sized?: PartialEq { /// This method tests greater than (`>`). #[inline] - fn gt(&self, other: &Self) -> bool { + fn gt(&self, other: &Rhs) -> bool { match self.partial_cmp(other) { Some(Greater) => true, _ => false, @@ -228,7 +229,7 @@ pub trait PartialOrd for Sized?: PartialEq { /// This method tests greater than or equal to (`>=`). #[inline] - fn ge(&self, other: &Self) -> bool { + fn ge(&self, other: &Rhs) -> bool { match self.partial_cmp(other) { Some(Greater) | Some(Equal) => true, _ => false, @@ -240,7 +241,7 @@ pub trait PartialOrd for Sized?: PartialEq { /// of different types. The most common use case for this relation is /// container types; e.g. it is often desirable to be able to use `&str` /// values to look up entries in a container with `String` keys. -#[experimental = "Better solutions may be discovered."] +#[deprecated = "Use overloaded core::cmp::PartialEq"] pub trait Equiv for Sized? { /// Implement this function to decide equivalent values. fn equiv(&self, other: &T) -> bool; @@ -288,10 +289,11 @@ pub fn partial_max(v1: T, v2: T) -> Option { // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types mod impls { - use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering, - Less, Greater, Equal}; + use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering}; + use cmp::Ordering::{Less, Greater, Equal}; use kinds::Sized; - use option::{Option, Some, None}; + use option::Option; + use option::Option::{Some, None}; macro_rules! partial_eq_impl( ($($t:ty)*) => ($( @@ -400,11 +402,11 @@ mod impls { // & pointers #[unstable = "Trait is unstable."] - impl<'a, Sized? T: PartialEq> PartialEq for &'a T { + impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b B> for &'a A where A: PartialEq { #[inline] - fn eq(&self, other: & &'a T) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: & &'b B) -> bool { PartialEq::eq(*self, *other) } #[inline] - fn ne(&self, other: & &'a T) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: & &'b B) -> bool { PartialEq::ne(*self, *other) } } #[unstable = "Trait is unstable."] impl<'a, Sized? T: PartialOrd> PartialOrd for &'a T { @@ -432,11 +434,11 @@ mod impls { // &mut pointers #[unstable = "Trait is unstable."] - impl<'a, Sized? T: PartialEq> PartialEq for &'a mut T { + impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b mut B> for &'a mut A where A: PartialEq { #[inline] - fn eq(&self, other: &&'a mut T) -> bool { PartialEq::eq(*self, *other) } + fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) } #[inline] - fn ne(&self, other: &&'a mut T) -> bool { PartialEq::ne(*self, *other) } + fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) } } #[unstable = "Trait is unstable."] impl<'a, Sized? T: PartialOrd> PartialOrd for &'a mut T { @@ -460,4 +462,18 @@ mod impls { } #[unstable = "Trait is unstable."] impl<'a, Sized? T: Eq> Eq for &'a mut T {} + + impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b mut B> for &'a A where A: PartialEq { + #[inline] + fn eq(&self, other: &&'b mut B) -> bool { PartialEq::eq(*self, *other) } + #[inline] + fn ne(&self, other: &&'b mut B) -> bool { PartialEq::ne(*self, *other) } + } + + impl<'a, 'b, Sized? A, Sized? B> PartialEq<&'b B> for &'a mut A where A: PartialEq { + #[inline] + fn eq(&self, other: &&'b B) -> bool { PartialEq::eq(*self, *other) } + #[inline] + fn ne(&self, other: &&'b B) -> bool { PartialEq::ne(*self, *other) } + } } diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index 1e31df8377942..400ce76baa0d2 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -20,7 +20,7 @@ use fmt; use iter::{range, DoubleEndedIteratorExt}; use num::{Float, FPNaN, FPInfinite, ToPrimitive}; use num::cast; -use result::Ok; +use result::Result::Ok; use slice::{mod, SlicePrelude}; use str::StrPrelude; diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 1d6906c13a8fa..43819501aa5cd 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -17,9 +17,10 @@ use cell::{Cell, Ref, RefMut}; use iter::{Iterator, IteratorExt, range}; use kinds::{Copy, Sized}; use mem; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use ops::Deref; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use result; use slice::SlicePrelude; use slice; diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 78c74075d4867..ece2ac6975ed1 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -10,7 +10,7 @@ //! rustc compiler intrinsics. //! -//! The corresponding definitions are in librustc/middle/trans/foreign.rs. +//! The corresponding definitions are in librustc_trans/trans/intrinsic.rs. //! //! # Volatiles //! @@ -226,7 +226,7 @@ extern "rust-intrinsic" { /// use std::mem; /// /// let v: &[u8] = unsafe { mem::transmute("L") }; - /// assert!(v == &[76u8]); + /// assert!(v == [76u8]); /// ``` pub fn transmute(e: T) -> U; diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 2d488a4b15563..c56bf382d950a 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -62,7 +62,8 @@ use cmp::Ord; use mem; use num::{ToPrimitive, Int}; use ops::{Add, Deref}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use uint; #[deprecated = "renamed to Extend"] pub use self::Extend as Extendable; @@ -2427,7 +2428,9 @@ pub fn repeat(elt: T) -> Repeat { pub mod order { use cmp; use cmp::{Eq, Ord, PartialOrd, PartialEq}; - use option::{Option, Some, None}; + use cmp::Ordering::{Equal, Less, Greater}; + use option::Option; + use option::Option::{Some, None}; use super::Iterator; /// Compare `a` and `b` for equality using `Eq` @@ -2445,11 +2448,11 @@ pub mod order { pub fn cmp, S: Iterator>(mut a: T, mut b: S) -> cmp::Ordering { loop { match (a.next(), b.next()) { - (None, None) => return cmp::Equal, - (None, _ ) => return cmp::Less, - (_ , None) => return cmp::Greater, + (None, None) => return Equal, + (None, _ ) => return Less, + (_ , None) => return Greater, (Some(x), Some(y)) => match x.cmp(&y) { - cmp::Equal => (), + Equal => (), non_eq => return non_eq, }, } @@ -2461,11 +2464,11 @@ pub mod order { -> Option { loop { match (a.next(), b.next()) { - (None, None) => return Some(cmp::Equal), - (None, _ ) => return Some(cmp::Less), - (_ , None) => return Some(cmp::Greater), + (None, None) => return Some(Equal), + (None, _ ) => return Some(Less), + (_ , None) => return Some(Greater), (Some(x), Some(y)) => match x.partial_cmp(&y) { - Some(cmp::Equal) => (), + Some(Equal) => (), non_eq => return non_eq, }, } @@ -2473,7 +2476,11 @@ pub mod order { } /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`) - pub fn eq, S: Iterator>(mut a: T, mut b: S) -> bool { + pub fn eq(mut a: L, mut b: R) -> bool where + A: PartialEq, + L: Iterator, + R: Iterator, + { loop { match (a.next(), b.next()) { (None, None) => return true, @@ -2484,7 +2491,11 @@ pub mod order { } /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`) - pub fn ne, S: Iterator>(mut a: T, mut b: S) -> bool { + pub fn ne(mut a: L, mut b: R) -> bool where + A: PartialEq, + L: Iterator, + R: Iterator, + { loop { match (a.next(), b.next()) { (None, None) => return false, diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 56a8677306079..5ad9462daf274 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -59,6 +59,7 @@ #![allow(unknown_features)] #![feature(globs, intrinsics, lang_items, macro_rules, phase)] #![feature(simd, unsafe_destructor, slicing_syntax)] +#![feature(default_type_params)] #![deny(missing_docs)] mod macros; diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index ce61bd97e1323..e6946c83cebdf 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -30,7 +30,8 @@ use kinds::Copy; use mem::size_of; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use str::{FromStr, from_str, StrPrelude}; /// Simultaneous division and remainder @@ -284,7 +285,7 @@ pub trait Int /// ``` fn checked_add(self, other: Self) -> Option; - /// Checked integer subtraction. Computes `self + other`, returning `None` + /// Checked integer subtraction. Computes `self - other`, returning `None` /// if underflow occurred. /// /// # Example @@ -297,7 +298,7 @@ pub trait Int /// ``` fn checked_sub(self, other: Self) -> Option; - /// Checked integer multiplication. Computes `self + other`, returning + /// Checked integer multiplication. Computes `self * other`, returning /// `None` if underflow or overflow occurred. /// /// # Example @@ -310,8 +311,8 @@ pub trait Int /// ``` fn checked_mul(self, other: Self) -> Option; - /// Checked integer division. Computes `self + other` returning `None` if - /// `self == 0` or the operation results in underflow or overflow. + /// Checked integer division. Computes `self / other`, returning `None` if + /// `other == 0` or the operation results in underflow or overflow. /// /// # Example /// diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 7d7b41bf7bfd8..8ba41c3575fff 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -149,7 +149,8 @@ use cmp::{Eq, Ord}; use default::Default; use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator}; use mem; -use result::{Result, Ok, Err}; +use result::Result; +use result::Result::{Ok, Err}; use slice; use slice::AsSlice; use clone::Clone; @@ -274,9 +275,9 @@ impl Option { /// let mut x = Some("Diamonds"); /// { /// let v = x.as_mut_slice(); - /// assert!(v == &mut ["Diamonds"]); + /// assert!(v == ["Diamonds"]); /// v[0] = "Dirt"; - /// assert!(v == &mut ["Dirt"]); + /// assert!(v == ["Dirt"]); /// } /// assert_eq!(x, Some("Dirt")); /// ``` @@ -554,7 +555,7 @@ impl Option { /// /// let x = None; /// let v: Vec<&str> = x.into_iter().collect(); - /// assert_eq!(v, vec![]); + /// assert!(v.is_empty()); /// ``` #[inline] #[unstable = "waiting for iterator conventions"] diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 5e2f5529e8d49..3f6ac49786d2e 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -90,9 +90,12 @@ use mem; use clone::Clone; use intrinsics; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; -use cmp::{PartialEq, Eq, PartialOrd, Equiv, Ordering, Less, Equal, Greater}; +use cmp::{PartialEq, Eq, PartialOrd, Equiv}; +use cmp::Ordering; +use cmp::Ordering::{Less, Equal, Greater}; pub use intrinsics::copy_memory; pub use intrinsics::copy_nonoverlapping_memory; @@ -321,12 +324,16 @@ impl PartialEq for *mut T { impl Eq for *mut T {} // Equivalence for pointers +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl Equiv<*mut T> for *const T { fn equiv(&self, other: &*mut T) -> bool { self.to_uint() == other.to_uint() } } +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl Equiv<*const T> for *mut T { fn equiv(&self, other: &*const T) -> bool { self.to_uint() == other.to_uint() diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 202ac46449754..5fd802e3f898c 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -236,7 +236,8 @@ use std::fmt::Show; use slice; use slice::AsSlice; use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator}; -use option::{None, Option, Some}; +use option::Option; +use option::Option::{None, Some}; /// `Result` is a type that represents either success (`Ok`) or failure (`Err`). /// @@ -407,14 +408,14 @@ impl Result { /// let mut x: Result<&str, uint> = Ok("Gold"); /// { /// let v = x.as_mut_slice(); - /// assert!(v == &mut ["Gold"]); + /// assert!(v == ["Gold"]); /// v[0] = "Silver"; - /// assert!(v == &mut ["Silver"]); + /// assert!(v == ["Silver"]); /// } /// assert_eq!(x, Ok("Silver")); /// /// let mut x: Result<&str, uint> = Err(45); - /// assert!(x.as_mut_slice() == &mut []); + /// assert!(x.as_mut_slice().is_empty()); /// ``` #[inline] #[unstable = "waiting for mut conventions"] @@ -446,13 +447,12 @@ impl Result { /// ``` /// use std::io::{BufReader, IoResult}; /// - /// let buffer = "1\n2\n3\n4\n"; - /// let mut reader = BufReader::new(buffer.as_bytes()); + /// let mut buffer = "1\n2\n3\n4\n"; /// /// let mut sum = 0; /// - /// while !reader.eof() { - /// let line: IoResult = reader.read_line(); + /// while !buffer.is_empty() { + /// let line: IoResult = buffer.read_line(); /// // Convert the string line to a number using `map` and `from_str` /// let val: IoResult = line.map(|line| { /// from_str::(line.as_slice().trim_right()).unwrap_or(0) diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 950f04a5d97e3..b8df36c91bc3e 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -36,13 +36,15 @@ use mem::transmute; use clone::Clone; -use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Less, Equal, Greater, Equiv}; +use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord, Equiv}; +use cmp::Ordering::{Less, Equal, Greater}; use cmp; use default::Default; use iter::*; use num::Int; use ops; -use option::{None, Option, Some}; +use option::Option; +use option::Option::{None, Some}; use ptr; use ptr::RawPtr; use mem; @@ -374,20 +376,20 @@ pub trait SlicePrelude for Sized? { /// // scoped to restrict the lifetime of the borrows /// { /// let (left, right) = v.split_at_mut(0); - /// assert!(left == &mut []); - /// assert!(right == &mut [1i, 2, 3, 4, 5, 6]); + /// assert!(left == []); + /// assert!(right == [1i, 2, 3, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(2); - /// assert!(left == &mut [1i, 2]); - /// assert!(right == &mut [3i, 4, 5, 6]); + /// assert!(left == [1i, 2]); + /// assert!(right == [3i, 4, 5, 6]); /// } /// /// { /// let (left, right) = v.split_at_mut(6); - /// assert!(left == &mut [1i, 2, 3, 4, 5, 6]); - /// assert!(right == &mut []); + /// assert!(left == [1i, 2, 3, 4, 5, 6]); + /// assert!(right == []); /// } /// ``` #[unstable = "waiting on final error conventions"] @@ -1702,7 +1704,8 @@ pub mod raw { use mem::transmute; use ptr::RawPtr; use raw::Slice; - use option::{None, Option, Some}; + use option::Option; + use option::Option::{None, Some}; /// Form a slice from a pointer and length (as a number of units, /// not bytes). @@ -1781,12 +1784,13 @@ pub mod bytes { /// Copies data from `src` to `dst` /// - /// `src` and `dst` must not overlap. Panics if the length of `dst` - /// is less than the length of `src`. + /// Panics if the length of `dst` is less than the length of `src`. #[inline] pub fn copy_memory(dst: &mut [u8], src: &[u8]) { let len_src = src.len(); assert!(dst.len() >= len_src); + // `dst` is unaliasable, so we know statically it doesn't overlap + // with `src`. unsafe { ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), src.as_ptr(), @@ -1802,12 +1806,12 @@ pub mod bytes { // #[unstable = "waiting for DST"] -impl PartialEq for [T] { - fn eq(&self, other: &[T]) -> bool { +impl PartialEq<[B]> for [A] where A: PartialEq { + fn eq(&self, other: &[B]) -> bool { self.len() == other.len() && order::eq(self.iter(), other.iter()) } - fn ne(&self, other: &[T]) -> bool { + fn ne(&self, other: &[B]) -> bool { self.len() != other.len() || order::ne(self.iter(), other.iter()) } @@ -1816,13 +1820,15 @@ impl PartialEq for [T] { #[unstable = "waiting for DST"] impl Eq for [T] {} -#[unstable = "waiting for DST"] +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl> Equiv for [T] { #[inline] fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } } -#[unstable = "waiting for DST"] +#[allow(deprecated)] +#[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl<'a,T:PartialEq, Sized? V: AsSlice> Equiv for &'a mut [T] { #[inline] fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() } diff --git a/src/libcore/str.rs b/src/libcore/str.rs index b9586399aec5d..1d59567cbe447 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -29,7 +29,8 @@ use iter::range; use kinds::Sized; use mem; use num::Int; -use option::{Option, None, Some}; +use option::Option; +use option::Option::{None, Some}; use ptr::RawPtr; use raw::{Repr, Slice}; use slice::{mod, SlicePrelude}; @@ -1209,9 +1210,11 @@ Section: Trait implementations #[allow(missing_docs)] pub mod traits { - use cmp::{Ord, Ordering, Less, Equal, Greater, PartialEq, PartialOrd, Equiv, Eq}; + use cmp::{Ordering, Ord, PartialEq, PartialOrd, Equiv, Eq}; + use cmp::Ordering::{Less, Equal, Greater}; use iter::IteratorExt; - use option::{Option, Some}; + use option::Option; + use option::Option::Some; use ops; use str::{Str, StrPrelude, eq_slice}; @@ -1248,6 +1251,8 @@ pub mod traits { } } + #[allow(deprecated)] + #[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl Equiv for str { #[inline] fn equiv(&self, other: &S) -> bool { eq_slice(self, other.as_slice()) } diff --git a/src/libcore/tuple/mod.rs b/src/libcore/tuple/mod.rs index 56ea7a4e7a1e9..5ad01ae67442e 100644 --- a/src/libcore/tuple/mod.rs +++ b/src/libcore/tuple/mod.rs @@ -69,7 +69,8 @@ pub use unit; use clone::Clone; use cmp::*; use default::Default; -use option::{Option, Some}; +use option::Option; +use option::Option::Some; // macro for implementing n-ary tuple functions and operations macro_rules! tuple_impls { diff --git a/src/libcoretest/mem.rs b/src/libcoretest/mem.rs index e4dde7c641e1e..75ddfd5413b31 100644 --- a/src/libcoretest/mem.rs +++ b/src/libcoretest/mem.rs @@ -109,7 +109,7 @@ fn test_transmute() { } unsafe { - assert!(vec![76u8] == transmute("L".to_string())); + assert!(vec![76u8] == transmute::<_, Vec>("L".to_string())); } } diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index 0cd1ded21d6c6..6ee3633d36c14 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -48,7 +48,8 @@ pub fn test_num(ten: T, two: T) where #[cfg(test)] mod test { - use core::option::{Option, Some, None}; + use core::option::Option; + use core::option::Option::{Some, None}; use core::num::Float; use core::num::from_str_radix; diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 1204ac18f99dc..e146e3c76eb2f 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -99,7 +99,7 @@ use self::Fail::*; use self::Optval::*; use std::fmt; -use std::result::{Err, Ok}; +use std::result::Result::{Err, Ok}; use std::result; use std::string::String; @@ -951,7 +951,7 @@ mod tests { use super::*; use super::Fail::*; - use std::result::{Err, Ok}; + use std::result::Result::{Err, Ok}; use std::result; // Tests for reqopt @@ -1392,8 +1392,8 @@ mod tests { let args_single = vec!("-e".to_string(), "foo".to_string()); let matches_single = &match getopts(args_single.as_slice(), opts.as_slice()) { - result::Ok(m) => m, - result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!() }; assert!(matches_single.opts_present(&["e".to_string()])); assert!(matches_single.opts_present(&["encrypt".to_string(), "e".to_string()])); @@ -1412,8 +1412,8 @@ mod tests { "foo".to_string()); let matches_both = &match getopts(args_both.as_slice(), opts.as_slice()) { - result::Ok(m) => m, - result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!() }; assert!(matches_both.opts_present(&["e".to_string()])); assert!(matches_both.opts_present(&["encrypt".to_string()])); @@ -1437,8 +1437,8 @@ mod tests { let opts = vec!(optmulti("L", "", "library directory", "LIB"), optmulti("M", "", "something", "MMMM")); let matches = &match getopts(args.as_slice(), opts.as_slice()) { - result::Ok(m) => m, - result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!() }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "foo".to_string()); @@ -1453,8 +1453,8 @@ mod tests { let opts = vec!(optmulti("L", "", "library directory", "LIB"), optflagmulti("v", "verbose", "Verbose")); let matches = &match getopts(args.as_slice(), opts.as_slice()) { - result::Ok(m) => m, - result::Err(e) => panic!( "{}", e ) + result::Result::Ok(m) => m, + result::Result::Err(e) => panic!( "{}", e ) }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "verbose".to_string()); diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index af1dbc2b7fca4..0a5081d07be00 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -547,7 +547,7 @@ mod tests { use self::NodeLabels::*; use super::{Id, LabelText, LabelStr, EscStr, Labeller}; use super::{Nodes, Edges, GraphWalk, render}; - use std::io::{BufReader, IoResult}; + use std::io::IoResult; use std::str; /// each node is an index in a vector in the graph. @@ -698,8 +698,7 @@ mod tests { fn test_input(g: LabelledGraph) -> IoResult { let mut writer = Vec::new(); render(&g, &mut writer).unwrap(); - let mut r = BufReader::new(writer[]); - r.read_to_string() + (&mut writer.as_slice()).read_to_string() } // All of the tests use raw-strings as the format for the expected outputs, @@ -811,8 +810,7 @@ r#"digraph hasse_diagram { edge(1, 3, ";"), edge(2, 3, ";" ))); render(&g, &mut writer).unwrap(); - let mut r = BufReader::new(writer[]); - let r = r.read_to_string(); + let r = (&mut writer.as_slice()).read_to_string(); assert_eq!(r.unwrap().as_slice(), r#"digraph syntax_tree { diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index 6482a514115aa..05932db6632ff 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -96,6 +96,7 @@ impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> { } } +#[allow(deprecated)] impl<'a, T: PartialEq, Sized? V: AsSlice> Equiv for MaybeOwnedVector<'a, T> { fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 6f3fbe1251008..f65c4f4e3edcc 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -120,7 +120,8 @@ pub mod reader { use std::io::extensions::u64_from_be_bytes; use std::mem::transmute; use std::num::Int; - use std::option::{None, Option, Some}; + use std::option::Option; + use std::option::Option::{None, Some}; use serialize; @@ -1060,7 +1061,8 @@ mod tests { use serialize::{Encodable, Decodable}; - use std::option::{None, Option, Some}; + use std::option::Option; + use std::option::Option::{None, Some}; #[test] fn test_vuint_at() { diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index a83f8afd39617..a964609e4e634 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -59,6 +59,7 @@ pub mod back { } pub mod middle { + pub mod astconv_util; pub mod astencode; pub mod borrowck; pub mod cfg; @@ -79,6 +80,7 @@ pub mod middle { pub mod fast_reject; pub mod graph; pub mod intrinsicck; + pub mod infer; pub mod lang_items; pub mod liveness; pub mod mem_categorization; @@ -93,7 +95,6 @@ pub mod middle { pub mod traits; pub mod ty; pub mod ty_fold; - pub mod typeck; pub mod weak_lang_items; } diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index aa99fe996f02a..10c0ae6d37417 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -29,8 +29,6 @@ use self::MethodContext::*; use metadata::csearch; use middle::def::*; use middle::ty::{mod, Ty}; -use middle::typeck::astconv::ast_ty_to_ty; -use middle::typeck::{mod, infer}; use middle::{def, pat_util, stability}; use middle::const_eval::{eval_const_expr_partial, const_int, const_uint}; use util::ppaux::{ty_to_string}; @@ -84,7 +82,7 @@ impl LintPass for UnusedCasts { fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { if let ast::ExprCast(ref expr, ref ty) = e.node { - let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), &**ty); + let t_t = ty::expr_ty(cx.tcx, e); if ty::expr_ty(cx.tcx, &**expr) == t_t { cx.span_lint(UNUSED_TYPECASTS, ty.span, "unnecessary type cast"); } @@ -1377,7 +1375,7 @@ impl MissingDoc { let has_doc = attrs.iter().any(|a| { match a.node.value.node { - ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true, + ast::MetaNameValue(ref name, _) if *name == "doc" => true, _ => false } }); @@ -1589,22 +1587,22 @@ impl LintPass for Stability { } ast::ExprMethodCall(i, _, _) => { span = i.span; - let method_call = typeck::MethodCall::expr(e.id); + let method_call = ty::MethodCall::expr(e.id); match cx.tcx.method_map.borrow().get(&method_call) { Some(method) => { match method.origin { - typeck::MethodStatic(def_id) => { + ty::MethodStatic(def_id) => { def_id } - typeck::MethodStaticUnboxedClosure(def_id) => { + ty::MethodStaticUnboxedClosure(def_id) => { def_id } - typeck::MethodTypeParam(typeck::MethodParam { + ty::MethodTypeParam(ty::MethodParam { ref trait_ref, method_num: index, .. }) | - typeck::MethodTraitObject(typeck::MethodObject { + ty::MethodTraitObject(ty::MethodObject { ref trait_ref, method_num: index, .. diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index c7bed838eb919..442d3aab92dba 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -26,17 +26,13 @@ use self::TargetLint::*; use middle::privacy::ExportedItems; -use middle::subst; use middle::ty::{mod, Ty}; -use middle::typeck::astconv::AstConv; -use middle::typeck::infer; use session::{early_error, Session}; use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject}; use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid}; use lint::builtin; use util::nodemap::FnvHashMap; -use std::rc::Rc; use std::cell::RefCell; use std::tuple::Tuple2; use std::mem; @@ -541,42 +537,6 @@ impl<'a, 'tcx> Context<'a, 'tcx> { } } -impl<'a, 'tcx> AstConv<'tcx> for Context<'a, 'tcx>{ - fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } - - fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype<'tcx> { - ty::lookup_item_type(self.tcx, id) - } - - fn get_trait_def(&self, id: ast::DefId) -> Rc> { - ty::lookup_trait_def(self.tcx, id) - } - - fn ty_infer(&self, _span: Span) -> Ty<'tcx> { - infer::new_infer_ctxt(self.tcx).next_ty_var() - } - - fn associated_types_of_trait_are_valid(&self, _: Ty<'tcx>, _: ast::DefId) - -> bool { - // FIXME(pcwalton): This is wrong. - true - } - - fn associated_type_binding(&self, - _: Span, - _: Option>, - trait_id: ast::DefId, - associated_type_id: ast::DefId) - -> Ty<'tcx> { - // FIXME(pcwalton): This is wrong. - let trait_def = self.get_trait_def(trait_id); - let index = ty::associated_type_parameter_index(self.tcx, - &*trait_def, - associated_type_id); - ty::mk_param(self.tcx, subst::TypeSpace, index, associated_type_id) - } -} - impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { fn visit_item(&mut self, it: &ast::Item) { self.with_lint_attrs(it.attrs.as_slice(), |cx| { diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 7f0941db6b2e4..5a8d60fbecd6c 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -105,7 +105,7 @@ fn warn_if_multiple_versions(diag: &SpanHandler, cstore: &CStore) { } fn visit_crate(e: &Env, c: &ast::Crate) { - for a in c.attrs.iter().filter(|m| m.name().equiv(&("link_args"))) { + for a in c.attrs.iter().filter(|m| m.name() == "link_args") { match a.value_str() { Some(ref linkarg) => e.sess.cstore.add_used_link_args(linkarg.get()), None => { /* fallthrough */ } @@ -205,7 +205,7 @@ fn visit_item(e: &Env, i: &ast::Item) { // First, add all of the custom link_args attributes let link_args = i.attrs.iter() - .filter_map(|at| if at.name().equiv(&("link_args")) { + .filter_map(|at| if at.name() == "link_args" { Some(at) } else { None @@ -220,7 +220,7 @@ fn visit_item(e: &Env, i: &ast::Item) { // Next, process all of the #[link(..)]-style arguments let link_args = i.attrs.iter() - .filter_map(|at| if at.name().equiv(&("link")) { + .filter_map(|at| if at.name() == "link" { Some(at) } else { None @@ -230,18 +230,18 @@ fn visit_item(e: &Env, i: &ast::Item) { match m.meta_item_list() { Some(items) => { let kind = items.iter().find(|k| { - k.name().equiv(&("kind")) + k.name() == "kind" }).and_then(|a| a.value_str()); let kind = match kind { Some(k) => { - if k.equiv(&("static")) { + if k == "static" { cstore::NativeStatic } else if e.sess.target.target.options.is_like_osx - && k.equiv(&("framework")) { + && k == "framework" { cstore::NativeFramework - } else if k.equiv(&("framework")) { + } else if k == "framework" { cstore::NativeFramework - } else if k.equiv(&("dylib")) { + } else if k == "dylib" { cstore::NativeUnknown } else { e.sess.span_err(m.span, @@ -253,7 +253,7 @@ fn visit_item(e: &Env, i: &ast::Item) { None => cstore::NativeUnknown }; let n = items.iter().find(|n| { - n.name().equiv(&("name")) + n.name() == "name" }).and_then(|a| a.value_str()); let n = match n { Some(n) => n, diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 20e3f27f2ae18..ebf5cca6a31a3 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -21,7 +21,6 @@ use middle::def; use middle::lang_items; use middle::resolve; use middle::ty; -use middle::typeck; use middle::subst::VecPerParamSpace; use rbml; @@ -268,7 +267,7 @@ pub fn get_impl_trait<'tcx>(tcx: &ty::ctxt<'tcx>, // Given a def_id for an impl, return information about its vtables pub fn get_impl_vtables<'tcx>(tcx: &ty::ctxt<'tcx>, def: ast::DefId) - -> typeck::vtable_res<'tcx> { + -> ty::vtable_res<'tcx> { let cstore = &tcx.sess.cstore; let cdata = cstore.get_crate_data(def.krate); decoder::get_impl_vtables(&*cdata, def.node, tcx) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index ec812cea3728d..f352a28df6972 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -30,7 +30,6 @@ use middle::resolve::{TraitItemKind, TypeTraitItemKind}; use middle::subst; use middle::ty::{ImplContainer, TraitContainer}; use middle::ty::{mod, Ty}; -use middle::typeck; use middle::astencode::vtable_decoder_helpers; use std::hash::Hash; @@ -422,7 +421,7 @@ pub fn get_impl_trait<'tcx>(cdata: Cmd, pub fn get_impl_vtables<'tcx>(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt<'tcx>) - -> typeck::vtable_res<'tcx> + -> ty::vtable_res<'tcx> { let item_doc = lookup_item(id, cdata.data()); let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables); diff --git a/src/librustc/middle/astconv_util.rs b/src/librustc/middle/astconv_util.rs new file mode 100644 index 0000000000000..6b90bcd60e753 --- /dev/null +++ b/src/librustc/middle/astconv_util.rs @@ -0,0 +1,89 @@ +// Copyright 2012-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. + +/*! + * This module contains a simple utility routine + * used by both `typeck` and `const_eval`. + * Almost certainly this could (and should) be refactored out of existence. + */ + +use middle::def; +use middle::ty::{mod, Ty}; +use syntax::ast; +use util::ppaux::Repr; + +pub const NO_REGIONS: uint = 1; +pub const NO_TPS: uint = 2; + +pub fn check_path_args(tcx: &ty::ctxt, + path: &ast::Path, + flags: uint) { + if (flags & NO_TPS) != 0u { + if path.segments.iter().any(|s| s.parameters.has_types()) { + span_err!(tcx.sess, path.span, E0109, + "type parameters are not allowed on this type"); + } + } + + if (flags & NO_REGIONS) != 0u { + if path.segments.iter().any(|s| s.parameters.has_lifetimes()) { + span_err!(tcx.sess, path.span, E0110, + "region parameters are not allowed on this type"); + } + } +} + +pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) + -> Option> { + match ast_ty.node { + ast::TyPath(ref path, id) => { + let a_def = match tcx.def_map.borrow().get(&id) { + None => { + tcx.sess.span_bug(ast_ty.span, + format!("unbound path {}", + path.repr(tcx)).as_slice()) + } + Some(&d) => d + }; + match a_def { + def::DefPrimTy(nty) => { + match nty { + ast::TyBool => { + check_path_args(tcx, path, NO_TPS | NO_REGIONS); + Some(ty::mk_bool()) + } + ast::TyChar => { + check_path_args(tcx, path, NO_TPS | NO_REGIONS); + Some(ty::mk_char()) + } + ast::TyInt(it) => { + check_path_args(tcx, path, NO_TPS | NO_REGIONS); + Some(ty::mk_mach_int(it)) + } + ast::TyUint(uit) => { + check_path_args(tcx, path, NO_TPS | NO_REGIONS); + Some(ty::mk_mach_uint(uit)) + } + ast::TyFloat(ft) => { + check_path_args(tcx, path, NO_TPS | NO_REGIONS); + Some(ty::mk_mach_float(ft)) + } + ast::TyStr => { + Some(ty::mk_str(tcx)) + } + } + } + _ => None + } + } + _ => None + } +} + diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 523e997a8deec..113d127503f02 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -26,8 +26,7 @@ use metadata::tyencode; use middle::mem_categorization::Typer; use middle::subst; use middle::subst::VecPerParamSpace; -use middle::typeck::{mod, MethodCall, MethodCallee, MethodOrigin}; -use middle::ty::{mod, Ty}; +use middle::ty::{mod, Ty, MethodCall, MethodCallee, MethodOrigin}; use util::ppaux::ty_to_string; use syntax::{ast, ast_map, ast_util, codemap, fold}; @@ -576,12 +575,12 @@ impl tr for ty::UpvarBorrow { trait read_method_callee_helper<'tcx> { fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) - -> (typeck::ExprAdjustment, MethodCallee<'tcx>); + -> (ty::ExprAdjustment, MethodCallee<'tcx>); } fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>, rbml_w: &mut Encoder, - adjustment: typeck::ExprAdjustment, + adjustment: ty::ExprAdjustment, method: &MethodCallee<'tcx>) { use serialize::Encoder; @@ -603,7 +602,7 @@ fn encode_method_callee<'a, 'tcx>(ecx: &e::EncodeContext<'a, 'tcx>, impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> { fn read_method_callee<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) - -> (typeck::ExprAdjustment, MethodCallee<'tcx>) { + -> (ty::ExprAdjustment, MethodCallee<'tcx>) { self.read_struct("MethodCallee", 4, |this| { let adjustment = this.read_struct_field("adjustment", 0, |this| { @@ -627,22 +626,22 @@ impl<'a, 'tcx> read_method_callee_helper<'tcx> for reader::Decoder<'a> { impl<'tcx> tr for MethodOrigin<'tcx> { fn tr(&self, dcx: &DecodeContext) -> MethodOrigin<'tcx> { match *self { - typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(dcx)), - typeck::MethodStaticUnboxedClosure(did) => { - typeck::MethodStaticUnboxedClosure(did.tr(dcx)) + ty::MethodStatic(did) => ty::MethodStatic(did.tr(dcx)), + ty::MethodStaticUnboxedClosure(did) => { + ty::MethodStaticUnboxedClosure(did.tr(dcx)) } - typeck::MethodTypeParam(ref mp) => { - typeck::MethodTypeParam( - typeck::MethodParam { + ty::MethodTypeParam(ref mp) => { + ty::MethodTypeParam( + ty::MethodParam { // def-id is already translated when we read it out trait_ref: mp.trait_ref.clone(), method_num: mp.method_num, } ) } - typeck::MethodTraitObject(ref mo) => { - typeck::MethodTraitObject( - typeck::MethodObject { + ty::MethodTraitObject(ref mo) => { + ty::MethodTraitObject( + ty::MethodObject { trait_ref: mo.trait_ref.clone(), .. *mo } @@ -687,16 +686,16 @@ pub trait vtable_decoder_helpers<'tcx> { fn read_vtable_res_with_key(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> (typeck::ExprAdjustment, typeck::vtable_res<'tcx>); + -> (ty::ExprAdjustment, ty::vtable_res<'tcx>); fn read_vtable_res(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_res<'tcx>; + -> ty::vtable_res<'tcx>; fn read_vtable_param_res(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_param_res<'tcx>; + -> ty::vtable_param_res<'tcx>; fn read_vtable_origin(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_origin<'tcx>; + -> ty::vtable_origin<'tcx>; } impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { @@ -714,7 +713,7 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { fn read_vtable_res_with_key(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> (typeck::ExprAdjustment, typeck::vtable_res<'tcx>) { + -> (ty::ExprAdjustment, ty::vtable_res<'tcx>) { self.read_struct("VtableWithKey", 2, |this| { let adjustment = this.read_struct_field("adjustment", 0, |this| { Decodable::decode(this) @@ -728,7 +727,7 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { fn read_vtable_res(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_res<'tcx> + -> ty::vtable_res<'tcx> { self.read_vec_per_param_space( |this| this.read_vtable_param_res(tcx, cdata)) @@ -736,14 +735,14 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { fn read_vtable_param_res(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_param_res<'tcx> { + -> ty::vtable_param_res<'tcx> { self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata))) .unwrap().into_iter().collect() } fn read_vtable_origin(&mut self, tcx: &ty::ctxt<'tcx>, cdata: &cstore::crate_metadata) - -> typeck::vtable_origin<'tcx> { + -> ty::vtable_origin<'tcx> { self.read_enum("vtable_origin", |this| { this.read_enum_variant(&["vtable_static", "vtable_param", @@ -752,7 +751,7 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { |this, i| { Ok(match i { 0 => { - typeck::vtable_static( + ty::vtable_static( this.read_enum_variant_arg(0u, |this| { Ok(this.read_def_id_nodcx(cdata)) }).unwrap(), @@ -765,7 +764,7 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { ) } 1 => { - typeck::vtable_param( + ty::vtable_param( this.read_enum_variant_arg(0u, |this| { Decodable::decode(this) }).unwrap(), @@ -775,14 +774,14 @@ impl<'tcx, 'a> vtable_decoder_helpers<'tcx> for reader::Decoder<'a> { ) } 2 => { - typeck::vtable_unboxed_closure( + ty::vtable_unboxed_closure( this.read_enum_variant_arg(0u, |this| { Ok(this.read_def_id_nodcx(cdata)) }).unwrap() ) } 3 => { - typeck::vtable_error + ty::vtable_error } _ => panic!("bad enum variant") }) @@ -826,7 +825,7 @@ trait rbml_writer_helpers<'tcx> { closure_type: &ty::ClosureTy<'tcx>); fn emit_method_origin<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, - method_origin: &typeck::MethodOrigin<'tcx>); + method_origin: &ty::MethodOrigin<'tcx>); fn emit_ty<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, ty: Ty<'tcx>); fn emit_tys<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, tys: &[Ty<'tcx>]); fn emit_type_param_def<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, @@ -860,25 +859,25 @@ impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> { fn emit_method_origin<'a>(&mut self, ecx: &e::EncodeContext<'a, 'tcx>, - method_origin: &typeck::MethodOrigin<'tcx>) + method_origin: &ty::MethodOrigin<'tcx>) { use serialize::Encoder; self.emit_enum("MethodOrigin", |this| { match *method_origin { - typeck::MethodStatic(def_id) => { + ty::MethodStatic(def_id) => { this.emit_enum_variant("MethodStatic", 0, 1, |this| { Ok(this.emit_def_id(def_id)) }) } - typeck::MethodStaticUnboxedClosure(def_id) => { + ty::MethodStaticUnboxedClosure(def_id) => { this.emit_enum_variant("MethodStaticUnboxedClosure", 1, 1, |this| { Ok(this.emit_def_id(def_id)) }) } - typeck::MethodTypeParam(ref p) => { + ty::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| { @@ -892,7 +891,7 @@ impl<'a, 'tcx> rbml_writer_helpers<'tcx> for Encoder<'a> { }) } - typeck::MethodTraitObject(ref o) => { + ty::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| { @@ -1330,7 +1329,7 @@ impl<'a> doc_decoder_helpers for rbml::Doc<'a> { trait rbml_decoder_decoder_helpers<'tcx> { fn read_method_origin<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) - -> typeck::MethodOrigin<'tcx>; + -> ty::MethodOrigin<'tcx>; fn read_ty<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Ty<'tcx>; fn read_tys<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) -> Vec>; fn read_trait_ref<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) @@ -1409,7 +1408,7 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> { } fn read_method_origin<'a, 'b>(&mut self, dcx: &DecodeContext<'a, 'b, 'tcx>) - -> typeck::MethodOrigin<'tcx> + -> ty::MethodOrigin<'tcx> { self.read_enum("MethodOrigin", |this| { let variants = &["MethodStatic", "MethodStaticUnboxedClosure", @@ -1418,18 +1417,18 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> { Ok(match i { 0 => { let def_id = this.read_def_id(dcx); - typeck::MethodStatic(def_id) + ty::MethodStatic(def_id) } 1 => { let def_id = this.read_def_id(dcx); - typeck::MethodStaticUnboxedClosure(def_id) + ty::MethodStaticUnboxedClosure(def_id) } 2 => { this.read_struct("MethodTypeParam", 2, |this| { - Ok(typeck::MethodTypeParam( - typeck::MethodParam { + Ok(ty::MethodTypeParam( + ty::MethodParam { trait_ref: { this.read_struct_field("trait_ref", 0, |this| { Ok(this.read_trait_ref(dcx)) @@ -1446,8 +1445,8 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> { 3 => { this.read_struct("MethodTraitObject", 2, |this| { - Ok(typeck::MethodTraitObject( - typeck::MethodObject { + Ok(ty::MethodTraitObject( + ty::MethodObject { trait_ref: { this.read_struct_field("trait_ref", 0, |this| { Ok(this.read_trait_ref(dcx)) diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index b42fb8ccc41f4..90919609e2e44 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -12,7 +12,6 @@ use middle::cfg::*; use middle::def; use middle::graph; use middle::region::CodeExtent; -use middle::typeck; use middle::ty; use syntax::ast; use syntax::ast_util; @@ -510,7 +509,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { pred: CFGIndex, func_or_rcvr: &ast::Expr, args: I) -> CFGIndex { - let method_call = typeck::MethodCall::expr(call_expr.id); + let method_call = ty::MethodCall::expr(call_expr.id); let return_ty = ty::ty_fn_ret(match self.tcx.method_map.borrow().get(&method_call) { Some(method) => method.ty, None => ty::expr_ty(self.tcx, func_or_rcvr) @@ -635,7 +634,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } fn is_method_call(&self, expr: &ast::Expr) -> bool { - let method_call = typeck::MethodCall::expr(expr.id); + let method_call = ty::MethodCall::expr(expr.id); self.tcx.method_map.borrow().contains_key(&method_call) } } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 8e0e8ee1c5ee0..92c87aacc7dc5 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -40,7 +40,7 @@ fn replace_newline_with_backslash_l(s: String) -> String { let mut last_two: Vec<_> = s.as_slice().chars().rev().take(2).collect(); last_two.reverse(); - if last_two.as_slice() != &['\\', 'l'] { + if last_two != ['\\', 'l'] { s.push_str("\\l"); } s diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 8cb63fcd82741..de140fd5c306c 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -11,7 +11,6 @@ use middle::def::*; use middle::ty; -use middle::typeck; use util::ppaux; use syntax::ast; @@ -111,7 +110,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) -> bool { } ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {} ast::ExprBinary(..) | ast::ExprUnary(..) => { - let method_call = typeck::MethodCall::expr(e.id); + let method_call = ty::MethodCall::expr(e.id); if v.tcx.method_map.borrow().contains_key(&method_call) { span_err!(v.tcx.sess, e.span, E0011, "user-defined operators are not allowed in constant \ diff --git a/src/librustc/middle/check_static.rs b/src/librustc/middle/check_static.rs index d3c7ccf65dd72..2fc85afd3935d 100644 --- a/src/librustc/middle/check_static.rs +++ b/src/librustc/middle/check_static.rs @@ -27,7 +27,7 @@ use self::Mode::*; use middle::ty; use middle::def; -use middle::typeck; +use middle::infer; use middle::traits; use middle::mem_categorization as mc; use middle::expr_use_visitor as euv; @@ -113,7 +113,7 @@ impl<'a, 'tcx> CheckStaticVisitor<'a, 'tcx> { fn check_static_type(&self, e: &ast::Expr) { let ty = ty::node_id_to_type(self.tcx, e.id); - let infcx = typeck::infer::new_infer_ctxt(self.tcx); + let infcx = infer::new_infer_ctxt(self.tcx); let mut fulfill_cx = traits::FulfillmentContext::new(); let cause = traits::ObligationCause::misc(DUMMY_SP); let obligation = traits::obligation_for_builtin_bound(self.tcx, cause, ty, diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index d5a292b9f09c6..43726f55bb989 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -17,8 +17,8 @@ pub use self::constness::*; use metadata::csearch; use middle::{astencode, def}; use middle::pat_util::def_to_path; -use middle::ty::{mod, Ty}; -use middle::typeck::{astconv, check}; +use middle::ty::{mod}; +use middle::astconv_util::{ast_ty_to_prim_ty}; use util::nodemap::DefIdMap; use syntax::ast::{mod, Expr}; @@ -277,14 +277,6 @@ impl<'a, 'tcx> ConstEvalVisitor<'a, 'tcx> { } impl<'a, 'tcx, 'v> Visitor<'v> for ConstEvalVisitor<'a, 'tcx> { - fn visit_ty(&mut self, t: &ast::Ty) { - if let ast::TyFixedLengthVec(_, ref expr) = t.node { - check::check_const_in_type(self.tcx, &**expr, ty::mk_uint()); - } - - visit::walk_ty(self, t); - } - fn visit_expr_post(&mut self, e: &Expr) { self.classify(e); } @@ -504,7 +496,7 @@ pub fn eval_const_expr_partial(tcx: &ty::ctxt, e: &Expr) -> Result MarkSymbolVisitor<'a, 'tcx> { fn lookup_and_handle_method(&mut self, id: ast::NodeId, span: codemap::Span) { - let method_call = typeck::MethodCall::expr(id); + let method_call = ty::MethodCall::expr(id); match self.tcx.method_map.borrow().get(&method_call) { Some(method) => { match method.origin { - typeck::MethodStatic(def_id) => { + ty::MethodStatic(def_id) => { match ty::provided_source(self.tcx, def_id) { Some(p_did) => self.check_def_id(p_did), None => self.check_def_id(def_id) } } - typeck::MethodStaticUnboxedClosure(_) => {} - typeck::MethodTypeParam(typeck::MethodParam { + ty::MethodStaticUnboxedClosure(_) => {} + ty::MethodTypeParam(ty::MethodParam { ref trait_ref, method_num: index, .. }) | - typeck::MethodTraitObject(typeck::MethodObject { + ty::MethodTraitObject(ty::MethodObject { ref trait_ref, method_num: index, .. diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index e67df0332dce6..dbec69f420503 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -14,7 +14,7 @@ use self::UnsafeContext::*; use middle::def; use middle::ty::{mod, Ty}; -use middle::typeck::MethodCall; +use middle::ty::MethodCall; use util::ppaux; use syntax::ast; diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index cbf36aeff512c..7d2bb7458acd5 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -24,10 +24,9 @@ use middle::{def, region, pat_util}; use middle::mem_categorization as mc; use middle::mem_categorization::Typer; use middle::ty::{mod, Ty}; -use middle::typeck::{MethodCall, MethodObject, MethodTraitObject}; -use middle::typeck::{MethodOrigin, MethodParam, MethodTypeParam}; -use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure}; -use middle::typeck; +use middle::ty::{MethodCall, MethodObject, MethodTraitObject}; +use middle::ty::{MethodOrigin, MethodParam, MethodTypeParam}; +use middle::ty::{MethodStatic, MethodStaticUnboxedClosure}; use util::ppaux::Repr; use syntax::ast; @@ -825,7 +824,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { debug!("walk_autoderefs expr={} autoderefs={}", expr.repr(self.tcx()), autoderefs); for i in range(0, autoderefs) { - let deref_id = typeck::MethodCall::autoderef(expr.id, i); + let deref_id = ty::MethodCall::autoderef(expr.id, i); match self.typer.node_method_ty(deref_id) { None => {} Some(method_ty) => { diff --git a/src/librustc/middle/typeck/infer/coercion.rs b/src/librustc/middle/infer/coercion.rs similarity index 99% rename from src/librustc/middle/typeck/infer/coercion.rs rename to src/librustc/middle/infer/coercion.rs index 51f8668692ea7..f04c519badc8c 100644 --- a/src/librustc/middle/typeck/infer/coercion.rs +++ b/src/librustc/middle/infer/coercion.rs @@ -60,14 +60,15 @@ //! sort of a minor point so I've opted to leave it for later---after all //! we may want to adjust precisely when coercions occur. +use super::{CoerceResult, resolve_type, Coercion}; +use super::combine::{CombineFields, Combine}; +use super::sub::Sub; +use super::resolve::try_resolve_tvar_shallow; + use middle::subst; use middle::ty::{AutoPtr, AutoDerefRef, AdjustDerefRef, AutoUnsize, AutoUnsafe}; use middle::ty::{mt}; use middle::ty::{mod, Ty}; -use middle::typeck::infer::{CoerceResult, resolve_type, Coercion}; -use middle::typeck::infer::combine::{CombineFields, Combine}; -use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use util::ppaux; use util::ppaux::Repr; diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/infer/combine.rs similarity index 98% rename from src/librustc/middle/typeck/infer/combine.rs rename to src/librustc/middle/infer/combine.rs index ba6ae00b6671f..ab9c5b86aeb62 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -32,6 +32,14 @@ // is also useful to track which value is the "expected" value in // terms of error reporting. +use super::equate::Equate; +use super::glb::Glb; +use super::lub::Lub; +use super::sub::Sub; +use super::unify::InferCtxtMethodsForSimplyUnifiableTypes; +use super::{InferCtxt, cres}; +use super::{MiscVariable, TypeTrace}; +use super::type_variable::{RelationDir, EqTo, SubtypeOf, SupertypeOf}; use middle::subst; use middle::subst::{ErasedRegions, NonerasedRegions, Substs}; @@ -40,15 +48,6 @@ use middle::ty::{IntType, UintType}; use middle::ty::{BuiltinBounds}; use middle::ty::{mod, Ty}; use middle::ty_fold; -use middle::typeck::infer::equate::Equate; -use middle::typeck::infer::glb::Glb; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::unify::InferCtxtMethodsForSimplyUnifiableTypes; -use middle::typeck::infer::{InferCtxt, cres}; -use middle::typeck::infer::{MiscVariable, TypeTrace}; -use middle::typeck::infer::type_variable::{RelationDir, EqTo, - SubtypeOf, SupertypeOf}; use middle::ty_fold::{TypeFoldable}; use util::ppaux::Repr; diff --git a/src/librustc/middle/typeck/infer/doc.rs b/src/librustc/middle/infer/doc.rs similarity index 100% rename from src/librustc/middle/typeck/infer/doc.rs rename to src/librustc/middle/infer/doc.rs diff --git a/src/librustc/middle/typeck/infer/equate.rs b/src/librustc/middle/infer/equate.rs similarity index 93% rename from src/librustc/middle/typeck/infer/equate.rs rename to src/librustc/middle/infer/equate.rs index 356081c199afa..a79a50b1781eb 100644 --- a/src/librustc/middle/typeck/infer/equate.rs +++ b/src/librustc/middle/infer/equate.rs @@ -11,14 +11,14 @@ use middle::ty::{BuiltinBounds}; use middle::ty::{mod, Ty}; use middle::ty::TyVar; -use middle::typeck::infer::combine::*; -use middle::typeck::infer::{cres}; -use middle::typeck::infer::glb::Glb; -use middle::typeck::infer::InferCtxt; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::{TypeTrace, Subtype}; -use middle::typeck::infer::type_variable::{EqTo}; +use middle::infer::combine::*; +use middle::infer::{cres}; +use middle::infer::glb::Glb; +use middle::infer::InferCtxt; +use middle::infer::lub::Lub; +use middle::infer::sub::Sub; +use middle::infer::{TypeTrace, Subtype}; +use middle::infer::type_variable::{EqTo}; use util::ppaux::{Repr}; use syntax::ast::{Onceness, FnStyle}; diff --git a/src/librustc/middle/typeck/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs similarity index 99% rename from src/librustc/middle/typeck/infer/error_reporting.rs rename to src/librustc/middle/infer/error_reporting.rs index 0607ccdc595a2..657ee088758d1 100644 --- a/src/librustc/middle/typeck/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -57,24 +57,25 @@ use self::FreshOrKept::*; +use super::InferCtxt; +use super::TypeTrace; +use super::SubregionOrigin; +use super::RegionVariableOrigin; +use super::ValuePairs; +use super::region_inference::RegionResolutionError; +use super::region_inference::ConcreteFailure; +use super::region_inference::SubSupConflict; +use super::region_inference::SupSupConflict; +use super::region_inference::ParamBoundFailure; +use super::region_inference::ProcessedErrors; +use super::region_inference::SameRegions; + use std::collections::HashSet; use middle::def; +use middle::infer; use middle::subst; use middle::ty::{mod, Ty}; use middle::ty::{Region, ReFree}; -use middle::typeck::infer; -use middle::typeck::infer::InferCtxt; -use middle::typeck::infer::TypeTrace; -use middle::typeck::infer::SubregionOrigin; -use middle::typeck::infer::RegionVariableOrigin; -use middle::typeck::infer::ValuePairs; -use middle::typeck::infer::region_inference::RegionResolutionError; -use middle::typeck::infer::region_inference::ConcreteFailure; -use middle::typeck::infer::region_inference::SubSupConflict; -use middle::typeck::infer::region_inference::SupSupConflict; -use middle::typeck::infer::region_inference::ParamBoundFailure; -use middle::typeck::infer::region_inference::ProcessedErrors; -use middle::typeck::infer::region_inference::SameRegions; use std::cell::{Cell, RefCell}; use std::char::from_u32; use std::rc::Rc; diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/infer/glb.rs similarity index 92% rename from src/librustc/middle/typeck/infer/glb.rs rename to src/librustc/middle/infer/glb.rs index 671d2e3837c79..4237a7af32fc1 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/infer/glb.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use super::combine::*; +use super::lattice::*; +use super::equate::Equate; +use super::higher_ranked::HigherRankedRelations; +use super::lub::Lub; +use super::sub::Sub; +use super::{cres, InferCtxt}; +use super::{TypeTrace, Subtype}; use middle::ty::{BuiltinBounds}; use middle::ty::{mod, Ty}; -use middle::typeck::infer::combine::*; -use middle::typeck::infer::lattice::*; -use middle::typeck::infer::equate::Equate; -use middle::typeck::infer::higher_ranked::HigherRankedRelations; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::{cres, InferCtxt}; -use middle::typeck::infer::{TypeTrace, Subtype}; use syntax::ast::{Many, Once, MutImmutable, MutMutable}; use syntax::ast::{NormalFn, UnsafeFn}; use syntax::ast::{Onceness, FnStyle}; diff --git a/src/librustc/middle/typeck/infer/higher_ranked/doc.rs b/src/librustc/middle/infer/higher_ranked/doc.rs similarity index 100% rename from src/librustc/middle/typeck/infer/higher_ranked/doc.rs rename to src/librustc/middle/infer/higher_ranked/doc.rs diff --git a/src/librustc/middle/typeck/infer/higher_ranked/mod.rs b/src/librustc/middle/infer/higher_ranked/mod.rs similarity index 97% rename from src/librustc/middle/typeck/infer/higher_ranked/mod.rs rename to src/librustc/middle/infer/higher_ranked/mod.rs index 2f80a574bb18b..95805ef8b944d 100644 --- a/src/librustc/middle/typeck/infer/higher_ranked/mod.rs +++ b/src/librustc/middle/infer/higher_ranked/mod.rs @@ -11,10 +11,11 @@ //! Helper routines for higher-ranked things. See the `doc` module at //! the end of the file for details. +use super::{combine, cres, InferCtxt, HigherRankedType}; +use super::combine::Combine; +use super::region_inference::{RegionMark}; + use middle::ty::{mod, Ty, replace_late_bound_regions}; -use middle::typeck::infer::{mod, combine, cres, InferCtxt}; -use middle::typeck::infer::combine::Combine; -use middle::typeck::infer::region_inference::{RegionMark}; use middle::ty_fold::{mod, HigherRankedFoldable, TypeFoldable}; use syntax::codemap::Span; use util::nodemap::FnvHashMap; @@ -62,7 +63,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C let (a_prime, _) = self.infcx().replace_late_bound_regions_with_fresh_var( self.trace().origin.span(), - infer::HigherRankedType, + HigherRankedType, a); // Second, we instantiate each bound region in the supertype with a @@ -131,10 +132,10 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C let span = self.trace().origin.span(); let (a_with_fresh, a_map) = self.infcx().replace_late_bound_regions_with_fresh_var( - span, infer::HigherRankedType, a); + span, HigherRankedType, a); let (b_with_fresh, _) = self.infcx().replace_late_bound_regions_with_fresh_var( - span, infer::HigherRankedType, b); + span, HigherRankedType, b); // Collect constraints. let result0 = @@ -221,10 +222,10 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C // Instantiate each bound region with a fresh region variable. let (a_with_fresh, a_map) = self.infcx().replace_late_bound_regions_with_fresh_var( - self.trace().origin.span(), infer::HigherRankedType, a); + self.trace().origin.span(), HigherRankedType, a); let (b_with_fresh, b_map) = self.infcx().replace_late_bound_regions_with_fresh_var( - self.trace().origin.span(), infer::HigherRankedType, b); + self.trace().origin.span(), HigherRankedType, b); let a_vars = var_ids(self, &a_map); let b_vars = var_ids(self, &b_map); diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/infer/lattice.rs similarity index 96% rename from src/librustc/middle/typeck/infer/lattice.rs rename to src/librustc/middle/infer/lattice.rs index daec959d11cd3..dd514ebee524a 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/infer/lattice.rs @@ -29,12 +29,13 @@ //! over a `LatticeValue`, which is a value defined with respect to //! a lattice. +use super::*; +use super::combine::*; +use super::glb::Glb; +use super::lub::Lub; + use middle::ty::{TyVar}; use middle::ty::{mod, Ty}; -use middle::typeck::infer::*; -use middle::typeck::infer::combine::*; -use middle::typeck::infer::glb::Glb; -use middle::typeck::infer::lub::Lub; use util::ppaux::Repr; pub trait LatticeDir<'tcx> { diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/infer/lub.rs similarity index 91% rename from src/librustc/middle/typeck/infer/lub.rs rename to src/librustc/middle/infer/lub.rs index e7bd1f3716c12..f53ba571062b2 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/infer/lub.rs @@ -8,16 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use super::combine::*; +use super::equate::Equate; +use super::glb::Glb; +use super::higher_ranked::HigherRankedRelations; +use super::lattice::*; +use super::sub::Sub; +use super::{cres, InferCtxt}; +use super::{TypeTrace, Subtype}; + use middle::ty::{BuiltinBounds}; use middle::ty::{mod, Ty}; -use middle::typeck::infer::combine::*; -use middle::typeck::infer::equate::Equate; -use middle::typeck::infer::glb::Glb; -use middle::typeck::infer::higher_ranked::HigherRankedRelations; -use middle::typeck::infer::lattice::*; -use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::{cres, InferCtxt}; -use middle::typeck::infer::{TypeTrace, Subtype}; use syntax::ast::{Many, Once}; use syntax::ast::{NormalFn, UnsafeFn}; use syntax::ast::{Onceness, FnStyle}; diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/infer/mod.rs similarity index 100% rename from src/librustc/middle/typeck/infer/mod.rs rename to src/librustc/middle/infer/mod.rs diff --git a/src/librustc/middle/typeck/infer/region_inference/doc.rs b/src/librustc/middle/infer/region_inference/doc.rs similarity index 99% rename from src/librustc/middle/typeck/infer/region_inference/doc.rs rename to src/librustc/middle/infer/region_inference/doc.rs index b4eac4c002677..686174b73060b 100644 --- a/src/librustc/middle/typeck/infer/region_inference/doc.rs +++ b/src/librustc/middle/infer/region_inference/doc.rs @@ -371,4 +371,4 @@ //! ### Skolemization //! //! For a discussion on skolemization and higher-ranked subtyping, please -//! see the module `middle::typeck::infer::higher_ranked::doc`. +//! see the module `middle::infer::higher_ranked::doc`. diff --git a/src/librustc/middle/typeck/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs similarity index 99% rename from src/librustc/middle/typeck/infer/region_inference/mod.rs rename to src/librustc/middle/infer/region_inference/mod.rs index e39fbe105dcfc..9155c18cb3b5a 100644 --- a/src/librustc/middle/typeck/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -18,14 +18,14 @@ pub use self::RegionResolutionError::*; pub use self::VarValue::*; use self::Classification::*; +use super::cres; +use super::{RegionVariableOrigin, SubregionOrigin, TypeTrace, MiscVariable}; + use middle::region; use middle::ty; use middle::ty::{BoundRegion, FreeRegion, Region, RegionVid}; use middle::ty::{ReEmpty, ReStatic, ReInfer, ReFree, ReEarlyBound}; use middle::ty::{ReLateBound, ReScope, ReVar, ReSkolemized, BrFresh}; -use middle::typeck::infer::cres; -use middle::typeck::infer::{RegionVariableOrigin, SubregionOrigin, TypeTrace}; -use middle::typeck::infer; use middle::graph; use middle::graph::{Direction, NodeIndex}; use util::common::indenter; @@ -573,7 +573,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } None => {} } - let c = self.new_region_var(infer::MiscVariable(origin.span())); + let c = self.new_region_var(MiscVariable(origin.span())); self.combine_map(t).borrow_mut().insert(vars, c); if self.in_snapshot() { self.undo_log.borrow_mut().push(AddCombination(t, vars)); diff --git a/src/librustc/middle/typeck/infer/resolve.rs b/src/librustc/middle/infer/resolve.rs similarity index 98% rename from src/librustc/middle/typeck/infer/resolve.rs rename to src/librustc/middle/infer/resolve.rs index cf5efd188ed96..eaf363ffc74c2 100644 --- a/src/librustc/middle/typeck/infer/resolve.rs +++ b/src/librustc/middle/infer/resolve.rs @@ -48,12 +48,13 @@ #![allow(non_upper_case_globals)] +use super::{fixup_err, fres, InferCtxt}; +use super::{unresolved_int_ty,unresolved_float_ty,unresolved_ty}; + use middle::ty::{FloatVar, FloatVid, IntVar, IntVid, RegionVid, TyVar, TyVid}; use middle::ty::{IntType, UintType}; use middle::ty::{mod, Ty}; use middle::ty_fold; -use middle::typeck::infer::{fixup_err, fres, InferCtxt}; -use middle::typeck::infer::{unresolved_int_ty,unresolved_float_ty,unresolved_ty}; use syntax::codemap::Span; use util::ppaux::{Repr, ty_to_string}; diff --git a/src/librustc/middle/typeck/infer/skolemize.rs b/src/librustc/middle/infer/skolemize.rs similarity index 100% rename from src/librustc/middle/typeck/infer/skolemize.rs rename to src/librustc/middle/infer/skolemize.rs diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/infer/sub.rs similarity index 92% rename from src/librustc/middle/typeck/infer/sub.rs rename to src/librustc/middle/infer/sub.rs index 65d2a5133936c..c470b2488273a 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/infer/sub.rs @@ -8,19 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use super::combine::*; +use super::{cres, CresCompare}; +use super::equate::Equate; +use super::glb::Glb; +use super::higher_ranked::HigherRankedRelations; +use super::InferCtxt; +use super::lub::Lub; +use super::{TypeTrace, Subtype}; +use super::type_variable::{SubtypeOf, SupertypeOf}; use middle::ty::{BuiltinBounds}; use middle::ty::{mod, Ty}; use middle::ty::TyVar; -use middle::typeck::infer::combine::*; -use middle::typeck::infer::{cres, CresCompare}; -use middle::typeck::infer::equate::Equate; -use middle::typeck::infer::glb::Glb; -use middle::typeck::infer::higher_ranked::HigherRankedRelations; -use middle::typeck::infer::InferCtxt; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::{TypeTrace, Subtype}; -use middle::typeck::infer::type_variable::{SubtypeOf, SupertypeOf}; use util::ppaux::{Repr}; use syntax::ast::{Onceness, FnStyle, MutImmutable, MutMutable}; diff --git a/src/librustc/middle/typeck/infer/type_variable.rs b/src/librustc/middle/infer/type_variable.rs similarity index 100% rename from src/librustc/middle/typeck/infer/type_variable.rs rename to src/librustc/middle/infer/type_variable.rs diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/infer/unify.rs similarity index 99% rename from src/librustc/middle/typeck/infer/unify.rs rename to src/librustc/middle/infer/unify.rs index 1b3413bfb0104..6f6adb84a75f5 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/infer/unify.rs @@ -14,8 +14,8 @@ use std::kinds::marker; use middle::ty::{expected_found, IntVarValue}; use middle::ty::{mod, Ty}; -use middle::typeck::infer::{uok, ures}; -use middle::typeck::infer::InferCtxt; +use middle::infer::{uok, ures}; +use middle::infer::InferCtxt; use std::cell::RefCell; use std::fmt::Show; use syntax::ast; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index fcc23d8ac5548..523c9f3330968 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,7 +111,7 @@ use self::VarKind::*; use middle::def::*; use middle::mem_categorization::Typer; -use middle::{pat_util, typeck, ty}; +use middle::{pat_util, ty}; use lint; use util::nodemap::NodeMap; @@ -1156,7 +1156,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } ast::ExprMethodCall(_, _, ref args) => { - let method_call = typeck::MethodCall::expr(expr.id); + let method_call = ty::MethodCall::expr(expr.id); let method_ty = self.ir.tcx.method_map.borrow().get(&method_call).unwrap().ty; let diverges = ty::ty_fn_ret(method_ty) == ty::FnDiverging; let succ = if diverges { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index ce166fc5de6bb..cd70d8e2b487a 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -74,7 +74,6 @@ pub use self::categorization::*; use middle::def; use middle::region; use middle::ty::{mod, Ty}; -use middle::typeck; use util::nodemap::{DefIdMap, NodeMap}; use util::ppaux::{ty_to_string, Repr}; @@ -283,7 +282,7 @@ pub type McResult = Result; pub trait Typer<'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>; fn node_ty(&self, id: ast::NodeId) -> McResult>; - fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option>; + fn node_method_ty(&self, method_call: ty::MethodCall) -> Option>; fn adjustments<'a>(&'a self) -> &'a RefCell>>; fn is_method_call(&self, id: ast::NodeId) -> bool; fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option; @@ -509,7 +508,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { } ast::ExprIndex(ref base, _) => { - let method_call = typeck::MethodCall::expr(expr.id()); + let method_call = ty::MethodCall::expr(expr.id()); match self.typer.node_method_ty(method_call) { Some(method_ty) => { // If this is an index implemented by a method call, then it will @@ -890,12 +889,12 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { implicit: bool) -> cmt<'tcx> { let adjustment = match self.typer.adjustments().borrow().get(&node.id()) { - Some(adj) if ty::adjust_is_object(adj) => typeck::AutoObject, - _ if deref_cnt != 0 => typeck::AutoDeref(deref_cnt), - _ => typeck::NoAdjustment + Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject, + _ if deref_cnt != 0 => ty::AutoDeref(deref_cnt), + _ => ty::NoAdjustment }; - let method_call = typeck::MethodCall { + let method_call = ty::MethodCall { expr_id: node.id(), adjustment: adjustment }; @@ -980,7 +979,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { //! - `elt`: the AST node being indexed //! - `base_cmt`: the cmt of `elt` - let method_call = typeck::MethodCall::expr(elt.id()); + let method_call = ty::MethodCall::expr(elt.id()); let method_ty = self.typer.node_method_ty(method_call); let element_ty = match method_ty { diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 5e182ba8337cb..5770b601a69ce 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -19,8 +19,8 @@ use std::mem::replace; use metadata::csearch; use middle::{def, resolve}; use middle::ty::{mod, Ty}; -use middle::typeck::{MethodCall, MethodMap, MethodOrigin, MethodParam, MethodTypeParam}; -use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject}; +use middle::ty::{MethodCall, MethodMap, MethodOrigin, MethodParam, MethodTypeParam}; +use middle::ty::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject}; use util::nodemap::{NodeMap, NodeSet}; use syntax::{ast, ast_map}; diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 96e1aacb0cef5..fa02c940aa754 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -17,7 +17,6 @@ use middle::def; use middle::ty; -use middle::typeck; use middle::privacy; use session::config; use util::nodemap::NodeSet; @@ -137,9 +136,9 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> { } } ast::ExprMethodCall(..) => { - let method_call = typeck::MethodCall::expr(expr.id); + let method_call = ty::MethodCall::expr(expr.id); match (*self.tcx.method_map.borrow())[method_call].origin { - typeck::MethodStatic(def_id) => { + ty::MethodStatic(def_id) => { if is_local(def_id) { if self.def_id_represents_local_inlined_item(def_id) { self.worklist.push(def_id.node) diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 0a3e6c20316be..21f57a9d57388 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -589,8 +589,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { // type declarations and other outer declarations, not those // bound in *fn types*. Region substitution of the bound // regions that appear in a function signature is done using - // the specialized routine - // `middle::typeck::check::regionmanip::replace_late_regions_in_fn_sig()`. + // the specialized routine `ty::replace_late_regions()`. match r { ty::ReEarlyBound(_, space, i, region_name) => { match self.substs.regions { diff --git a/src/librustc/middle/traits/coherence.rs b/src/librustc/middle/traits/coherence.rs index 048f394224cf0..1bce353cb0cfe 100644 --- a/src/librustc/middle/traits/coherence.rs +++ b/src/librustc/middle/traits/coherence.rs @@ -17,7 +17,7 @@ use super::util; use middle::subst; use middle::subst::Subst; use middle::ty::{mod, Ty}; -use middle::typeck::infer::{mod, InferCtxt}; +use middle::infer::{mod, InferCtxt}; use syntax::ast; use syntax::codemap::DUMMY_SP; use util::ppaux::Repr; diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index bf4273dbfd081..90ea86cc16b7d 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -10,7 +10,7 @@ use middle::mem_categorization::Typer; use middle::ty; -use middle::typeck::infer::InferCtxt; +use middle::infer::InferCtxt; use util::ppaux::Repr; use super::CodeAmbiguity; diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 34278c25cfa0b..9427872cd8581 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -18,7 +18,7 @@ pub use self::ObligationCauseCode::*; use middle::mem_categorization::Typer; use middle::subst; use middle::ty::{mod, Ty}; -use middle::typeck::infer::InferCtxt; +use middle::infer::InferCtxt; use std::rc::Rc; use std::slice::Items; use syntax::ast; diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 9ce6947731dc1..b3e7e3fe15ce6 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -30,8 +30,8 @@ use middle::fast_reject; use middle::mem_categorization::Typer; use middle::subst::{Subst, Substs, VecPerParamSpace}; use middle::ty::{mod, Ty}; -use middle::typeck::infer; -use middle::typeck::infer::{InferCtxt, TypeSkolemizer}; +use middle::infer; +use middle::infer::{InferCtxt, TypeSkolemizer}; use middle::ty_fold::TypeFoldable; use std::cell::RefCell; use std::collections::hash_map::HashMap; diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index e8b292aac6d32..4380e57762b82 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -11,7 +11,7 @@ use middle::subst; use middle::subst::{ParamSpace, Substs, VecPerParamSpace}; -use middle::typeck::infer::InferCtxt; +use middle::infer::InferCtxt; use middle::ty::{mod, Ty}; use std::collections::HashSet; use std::fmt; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 35aed356303d8..994f0c2090a57 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -35,6 +35,9 @@ pub use self::ImplOrTraitItem::*; pub use self::BoundRegion::*; pub use self::sty::*; pub use self::IntVarValue::*; +pub use self::ExprAdjustment::*; +pub use self::vtable_origin::*; +pub use self::MethodOrigin::*; use back::svh::Svh; use session::Session; @@ -53,7 +56,6 @@ use middle::stability; use middle::subst::{mod, Subst, Substs, VecPerParamSpace}; use middle::traits; use middle::ty; -use middle::typeck; use middle::ty_fold::{mod, TypeFoldable, TypeFolder, HigherRankedFoldable}; use middle; use util::ppaux::{note_and_explain_region, bound_region_ptr_to_string}; @@ -90,6 +92,17 @@ pub const INITIAL_DISCRIMINANT_VALUE: Disr = 0; // Data types +/// The complete set of all analyses described in this module. This is +/// produced by the driver and fed to trans and later passes. +pub struct CrateAnalysis<'tcx> { + pub exp_map2: middle::resolve::ExportMap2, + pub exported_items: middle::privacy::ExportedItems, + pub public_items: middle::privacy::PublicItems, + pub ty_cx: ty::ctxt<'tcx>, + pub reachable: NodeSet, + pub name: String, +} + #[deriving(PartialEq, Eq, Hash)] pub struct field<'tcx> { pub name: ast::Name, @@ -412,7 +425,161 @@ pub fn type_of_adjust<'tcx>(cx: &ctxt<'tcx>, adj: &AutoAdjustment<'tcx>) -> Opti } } +#[deriving(Clone, Encodable, Decodable, PartialEq, PartialOrd, Show)] +pub struct param_index { + pub space: subst::ParamSpace, + pub index: uint +} + +#[deriving(Clone, Show)] +pub enum MethodOrigin<'tcx> { + // fully statically resolved method + MethodStatic(ast::DefId), + + // fully statically resolved unboxed closure invocation + MethodStaticUnboxedClosure(ast::DefId), + + // method invoked on a type parameter with a bounded trait + MethodTypeParam(MethodParam<'tcx>), + + // method invoked on a trait instance + MethodTraitObject(MethodObject<'tcx>), + +} + +// details for a method invoked with a receiver whose type is a type parameter +// with a bounded trait. +#[deriving(Clone, Show)] +pub struct MethodParam<'tcx> { + // the precise trait reference that occurs as a bound -- this may + // be a supertrait of what the user actually typed. + pub trait_ref: Rc>, + + // index of uint in the list of methods for the trait + pub method_num: uint, +} + +// details for a method invoked with a receiver whose type is an object +#[deriving(Clone, Show)] +pub struct MethodObject<'tcx> { + // the (super)trait containing the method to be invoked + pub trait_ref: Rc>, + + // the actual base trait id of the object + pub object_trait_id: ast::DefId, + + // index of the method to be invoked amongst the trait's methods + pub method_num: uint, + + // index into the actual runtime vtable. + // the vtable is formed by concatenating together the method lists of + // the base object trait and all supertraits; this is the index into + // that vtable + pub real_index: uint, +} + +#[deriving(Clone)] +pub struct MethodCallee<'tcx> { + pub origin: MethodOrigin<'tcx>, + pub ty: Ty<'tcx>, + pub substs: subst::Substs<'tcx> +} + +/// With method calls, we store some extra information in +/// side tables (i.e method_map). We use +/// MethodCall as a key to index into these tables instead of +/// just directly using the expression's NodeId. The reason +/// for this being that we may apply adjustments (coercions) +/// with the resulting expression also needing to use the +/// side tables. The problem with this is that we don't +/// assign a separate NodeId to this new expression +/// and so it would clash with the base expression if both +/// needed to add to the side tables. Thus to disambiguate +/// we also keep track of whether there's an adjustment in +/// our key. +#[deriving(Clone, PartialEq, Eq, Hash, Show)] +pub struct MethodCall { + pub expr_id: ast::NodeId, + pub adjustment: ExprAdjustment +} + +#[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)] +pub enum ExprAdjustment { + NoAdjustment, + AutoDeref(uint), + AutoObject +} + +impl MethodCall { + pub fn expr(id: ast::NodeId) -> MethodCall { + MethodCall { + expr_id: id, + adjustment: NoAdjustment + } + } + + pub fn autoobject(id: ast::NodeId) -> MethodCall { + MethodCall { + expr_id: id, + adjustment: AutoObject + } + } + + pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall { + MethodCall { + expr_id: expr_id, + adjustment: AutoDeref(1 + autoderef) + } + } +} + +// maps from an expression id that corresponds to a method call to the details +// of the method to be invoked +pub type MethodMap<'tcx> = RefCell>>; +pub type vtable_param_res<'tcx> = Vec>; + +// Resolutions for bounds of all parameters, left to right, for a given path. +pub type vtable_res<'tcx> = VecPerParamSpace>; + +#[deriving(Clone)] +pub enum vtable_origin<'tcx> { + /* + Statically known vtable. def_id gives the impl item + from whence comes the vtable, and tys are the type substs. + vtable_res is the vtable itself. + */ + vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>), + + /* + Dynamic vtable, comes from a parameter that has a bound on it: + fn foo(a: T) -- a's vtable would have a + vtable_param origin + + The first argument is the param index (identifying T in the example), + and the second is the bound number (identifying baz) + */ + vtable_param(param_index, uint), + + /* + Vtable automatically generated for an unboxed closure. The def ID is the + ID of the closure expression. + */ + vtable_unboxed_closure(ast::DefId), + + /* + Asked to determine the vtable for ty_err. This is the value used + for the vtables of `Self` in a virtual call like `foo.bar()` + where `foo` is of object type. The same value is also used when + type errors occur. + */ + vtable_error, +} + + +// For every explicit cast into an object type, maps from the cast +// expr to the associated trait ref. +pub type ObjectCastMap<'tcx> = RefCell>>>; /// A restriction that certain types must be the same size. The use of /// `transmute` gives rise to these restrictions. @@ -473,7 +640,7 @@ pub struct ctxt<'tcx> { /// Maps from node-id of a trait object cast (like `foo as /// Box`) to the trait reference. - pub object_cast_map: typeck::ObjectCastMap<'tcx>, + pub object_cast_map: ObjectCastMap<'tcx>, pub map: ast_map::Map<'tcx>, pub intrinsic_defs: RefCell>>, @@ -548,7 +715,7 @@ pub struct ctxt<'tcx> { pub extern_const_statics: RefCell>, pub extern_const_variants: RefCell>, - pub method_map: typeck::MethodMap<'tcx>, + pub method_map: MethodMap<'tcx>, pub dependency_formats: RefCell, @@ -3658,7 +3825,7 @@ pub fn adjust_ty<'tcx>(cx: &ctxt<'tcx>, expr_id: ast::NodeId, unadjusted_ty: Ty<'tcx>, adjustment: Option<&AutoAdjustment<'tcx>>, - method_type: |typeck::MethodCall| -> Option>) + method_type: |MethodCall| -> Option>) -> Ty<'tcx> { if let ty_err = unadjusted_ty.sty { @@ -3699,7 +3866,7 @@ pub fn adjust_ty<'tcx>(cx: &ctxt<'tcx>, if !ty::type_is_error(adjusted_ty) { for i in range(0, adj.autoderefs) { - let method_call = typeck::MethodCall::autoderef(expr_id, i); + let method_call = MethodCall::autoderef(expr_id, i); match method_type(method_call) { Some(method_ty) => { if let ty::FnConverging(result_type) = ty_fn_ret(method_ty) { @@ -3830,7 +3997,7 @@ pub enum ExprKind { } pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind { - if tcx.method_map.borrow().contains_key(&typeck::MethodCall::expr(expr.id)) { + if tcx.method_map.borrow().contains_key(&MethodCall::expr(expr.id)) { // Overloaded operations are generally calls, and hence they are // generated via DPS, but there are a few exceptions: return match expr.node { @@ -5747,7 +5914,7 @@ impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> { Ok(ty::node_id_to_type(self, id)) } - fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option> { + fn node_method_ty(&self, method_call: MethodCall) -> Option> { self.method_map.borrow().get(&method_call).map(|method| method.ty) } @@ -5756,7 +5923,7 @@ impl<'tcx> mc::Typer<'tcx> for ty::ctxt<'tcx> { } fn is_method_call(&self, id: ast::NodeId) -> bool { - self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id)) + self.method_map.borrow().contains_key(&MethodCall::expr(id)) } fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option { @@ -6010,3 +6177,55 @@ impl<'tcx> Repr<'tcx> for TyTrait<'tcx> { self.bounds.repr(tcx)) } } + +impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> { + fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { + match *self { + vtable_static(def_id, ref tys, ref vtable_res) => { + format!("vtable_static({}:{}, {}, {})", + def_id, + ty::item_path_str(tcx, def_id), + tys.repr(tcx), + vtable_res.repr(tcx)) + } + + vtable_param(x, y) => { + format!("vtable_param({}, {})", x, y) + } + + vtable_unboxed_closure(def_id) => { + format!("vtable_unboxed_closure({})", def_id) + } + + vtable_error => { + format!("vtable_error") + } + } + } +} + +pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>, + trait_ref: &ty::TraitRef<'tcx>, + method: &ty::Method<'tcx>) + -> subst::Substs<'tcx> +{ + /*! + * Substitutes the values for the receiver's type parameters + * that are found in method, leaving the method's type parameters + * intact. + */ + + let meth_tps: Vec = + method.generics.types.get_slice(subst::FnSpace) + .iter() + .map(|def| ty::mk_param_from_def(tcx, def)) + .collect(); + let meth_regions: Vec = + method.generics.regions.get_slice(subst::FnSpace) + .iter() + .map(|def| ty::ReEarlyBound(def.def_id.node, def.space, + def.index, def.name)) + .collect(); + trait_ref.substs.clone().with_method(meth_tps, meth_regions) +} + diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 08dcbffc9287b..662d08ee21d78 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -38,7 +38,6 @@ use middle::subst; use middle::subst::VecPerParamSpace; use middle::ty::{mod, Ty}; use middle::traits; -use middle::typeck; use std::rc::Rc; use syntax::owned_slice::OwnedSlice; use util::ppaux::Repr; @@ -304,23 +303,23 @@ impl<'tcx> TypeFoldable<'tcx> for ty::AutoRef<'tcx> { } } -impl<'tcx> TypeFoldable<'tcx> for typeck::MethodOrigin<'tcx> { - fn fold_with>(&self, folder: &mut F) -> typeck::MethodOrigin<'tcx> { +impl<'tcx> TypeFoldable<'tcx> for ty::MethodOrigin<'tcx> { + fn fold_with>(&self, folder: &mut F) -> ty::MethodOrigin<'tcx> { match *self { - typeck::MethodStatic(def_id) => { - typeck::MethodStatic(def_id) + ty::MethodStatic(def_id) => { + ty::MethodStatic(def_id) } - typeck::MethodStaticUnboxedClosure(def_id) => { - typeck::MethodStaticUnboxedClosure(def_id) + ty::MethodStaticUnboxedClosure(def_id) => { + ty::MethodStaticUnboxedClosure(def_id) } - typeck::MethodTypeParam(ref param) => { - typeck::MethodTypeParam(typeck::MethodParam { + ty::MethodTypeParam(ref param) => { + ty::MethodTypeParam(ty::MethodParam { trait_ref: param.trait_ref.fold_with(folder), method_num: param.method_num }) } - typeck::MethodTraitObject(ref object) => { - typeck::MethodTraitObject(typeck::MethodObject { + ty::MethodTraitObject(ref object) => { + ty::MethodTraitObject(ty::MethodObject { trait_ref: object.trait_ref.fold_with(folder), object_trait_id: object.object_trait_id, method_num: object.method_num, @@ -331,22 +330,22 @@ impl<'tcx> TypeFoldable<'tcx> for typeck::MethodOrigin<'tcx> { } } -impl<'tcx> TypeFoldable<'tcx> for typeck::vtable_origin<'tcx> { - fn fold_with>(&self, folder: &mut F) -> typeck::vtable_origin<'tcx> { +impl<'tcx> TypeFoldable<'tcx> for ty::vtable_origin<'tcx> { + fn fold_with>(&self, folder: &mut F) -> ty::vtable_origin<'tcx> { match *self { - typeck::vtable_static(def_id, ref substs, ref origins) => { + ty::vtable_static(def_id, ref substs, ref origins) => { let r_substs = substs.fold_with(folder); let r_origins = origins.fold_with(folder); - typeck::vtable_static(def_id, r_substs, r_origins) + ty::vtable_static(def_id, r_substs, r_origins) } - typeck::vtable_param(n, b) => { - typeck::vtable_param(n, b) + ty::vtable_param(n, b) => { + ty::vtable_param(n, b) } - typeck::vtable_unboxed_closure(def_id) => { - typeck::vtable_unboxed_closure(def_id) + ty::vtable_unboxed_closure(def_id) => { + ty::vtable_unboxed_closure(def_id) } - typeck::vtable_error => { - typeck::vtable_error + ty::vtable_error => { + ty::vtable_error } } } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 3c2dbae665fa9..cbc9dd9145bfb 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -114,6 +114,59 @@ pub struct Options { pub alt_std_name: Option } +pub enum Input { + /// Load source from file + File(Path), + /// The string is the source + Str(String) +} + +impl Input { + pub fn filestem(&self) -> String { + match *self { + Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(), + Input::Str(_) => "rust_out".to_string(), + } + } +} + +#[deriving(Clone)] +pub struct OutputFilenames { + pub out_directory: Path, + pub out_filestem: String, + pub single_output_file: Option, + pub extra: String, +} + +impl OutputFilenames { + pub fn path(&self, flavor: OutputType) -> Path { + match self.single_output_file { + Some(ref path) => return path.clone(), + None => {} + } + self.temp_path(flavor) + } + + pub fn temp_path(&self, flavor: OutputType) -> Path { + let base = self.out_directory.join(self.filestem()); + match flavor { + OutputTypeBitcode => base.with_extension("bc"), + OutputTypeAssembly => base.with_extension("s"), + OutputTypeLlvmAssembly => base.with_extension("ll"), + OutputTypeObject => base.with_extension("o"), + OutputTypeExe => base, + } + } + + pub fn with_extension(&self, extension: &str) -> Path { + self.out_directory.join(self.filestem()).with_extension(extension) + } + + pub fn filestem(&self) -> String { + format!("{}{}", self.out_filestem, self.extra) + } +} + pub fn host_triple() -> &'static str { // Get the host triple out of the build environment. This ensures that our // idea of the host triple is the same as for the set of libraries we've @@ -944,7 +997,7 @@ mod test { let sessopts = build_session_options(matches); let sess = build_session(sessopts, None, registry); let cfg = build_configuration(&sess); - let mut test_items = cfg.iter().filter(|m| m.name().equiv(&("test"))); + let mut test_items = cfg.iter().filter(|m| m.name() == "test"); assert!(test_items.next().is_some()); assert!(test_items.next().is_none()); } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index b739a97f734be..1283e89c29d0c 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -23,8 +23,6 @@ use middle::ty::{ty_param, ty_ptr, ty_rptr, ty_tup, ty_open}; use middle::ty::{ty_unboxed_closure}; use middle::ty::{ty_uniq, ty_trait, ty_int, ty_uint, ty_infer}; use middle::ty; -use middle::typeck; -use middle::typeck::check::regionmanip; use std::rc::Rc; use syntax::abi; @@ -1018,7 +1016,7 @@ impl<'tcx> Repr<'tcx> for ty::FnOutput<'tcx> { } } -impl<'tcx> Repr<'tcx> for typeck::MethodCallee<'tcx> { +impl<'tcx> Repr<'tcx> for ty::MethodCallee<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { format!("MethodCallee {{origin: {}, ty: {}, {}}}", self.origin.repr(tcx), @@ -1027,26 +1025,26 @@ impl<'tcx> Repr<'tcx> for typeck::MethodCallee<'tcx> { } } -impl<'tcx> Repr<'tcx> for typeck::MethodOrigin<'tcx> { +impl<'tcx> Repr<'tcx> for ty::MethodOrigin<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { match self { - &typeck::MethodStatic(def_id) => { + &ty::MethodStatic(def_id) => { format!("MethodStatic({})", def_id.repr(tcx)) } - &typeck::MethodStaticUnboxedClosure(def_id) => { + &ty::MethodStaticUnboxedClosure(def_id) => { format!("MethodStaticUnboxedClosure({})", def_id.repr(tcx)) } - &typeck::MethodTypeParam(ref p) => { + &ty::MethodTypeParam(ref p) => { p.repr(tcx) } - &typeck::MethodTraitObject(ref p) => { + &ty::MethodTraitObject(ref p) => { p.repr(tcx) } } } } -impl<'tcx> Repr<'tcx> for typeck::MethodParam<'tcx> { +impl<'tcx> Repr<'tcx> for ty::MethodParam<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { format!("MethodParam({},{})", self.trait_ref.repr(tcx), @@ -1054,7 +1052,7 @@ impl<'tcx> Repr<'tcx> for typeck::MethodParam<'tcx> { } } -impl<'tcx> Repr<'tcx> for typeck::MethodObject<'tcx> { +impl<'tcx> Repr<'tcx> for ty::MethodObject<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { format!("MethodObject({},{},{})", self.trait_ref.repr(tcx), @@ -1293,25 +1291,6 @@ impl<'tcx> Repr<'tcx> for ty::ExplicitSelfCategory { } } - -impl<'tcx> Repr<'tcx> for regionmanip::WfConstraint<'tcx> { - fn repr(&self, tcx: &ctxt) -> String { - match *self { - regionmanip::RegionSubRegionConstraint(_, r_a, r_b) => { - format!("RegionSubRegionConstraint({}, {})", - r_a.repr(tcx), - r_b.repr(tcx)) - } - - regionmanip::RegionSubParamConstraint(_, r, p) => { - format!("RegionSubParamConstraint({}, {})", - r.repr(tcx), - p.repr(tcx)) - } - } - } -} - impl<'tcx> UserString<'tcx> for ParamTy { fn user_string(&self, tcx: &ctxt) -> String { let id = self.idx; diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index 26cc859434f2c..9c94823f86758 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -156,7 +156,7 @@ mod test { "rpath2".to_string(), "rpath1".to_string() ]); - assert!(res.as_slice() == &[ + assert!(res.as_slice() == [ "rpath1".to_string(), "rpath2".to_string() ]); @@ -176,7 +176,7 @@ mod test { "4a".to_string(), "3".to_string() ]); - assert!(res.as_slice() == &[ + assert!(res.as_slice() == [ "1a".to_string(), "2".to_string(), "4a".to_string(), diff --git a/src/librustc_trans/driver/driver.rs b/src/librustc_driver/driver.rs similarity index 88% rename from src/librustc_trans/driver/driver.rs rename to src/librustc_driver/driver.rs index aeef16276e5b5..437b0257a9759 100644 --- a/src/librustc_trans/driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -8,26 +8,22 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub use self::Input::*; - -use back::link; -use back::write; -use session::Session; -use session::config; -use lint; -use llvm::{ContextRef, ModuleRef}; -use metadata::common::LinkMeta; -use metadata::creader; -use middle::{stability, ty, typeck, reachable}; -use middle::dependency_format; -use middle; -use plugin::load::Plugins; -use plugin::registry::Registry; -use plugin; -use trans; - -use util::common::time; -use util::nodemap::{NodeSet}; +use rustc::session::Session; +use rustc::session::config::{mod, Input, OutputFilenames}; +use rustc::lint; +use rustc::metadata::creader; +use rustc::middle::{stability, ty, reachable}; +use rustc::middle::dependency_format; +use rustc::middle; +use rustc::plugin::load::Plugins; +use rustc::plugin::registry::Registry; +use rustc::plugin; +use rustc::util::common::time; +use rustc_trans::back::link; +use rustc_trans::back::write; +use rustc_trans::save; +use rustc_trans::trans; +use rustc_typeck as typeck; use serialize::{json, Encodable}; @@ -35,7 +31,6 @@ use std::io; use std::io::fs; use std::os; use arena::TypedArena; -use save; use syntax::ast; use syntax::ast_map; use syntax::attr; @@ -113,36 +108,19 @@ pub fn anon_src() -> String { pub fn source_name(input: &Input) -> String { match *input { // FIXME (#9639): This needs to handle non-utf8 paths - FileInput(ref ifile) => ifile.as_str().unwrap().to_string(), - StrInput(_) => anon_src() + Input::File(ref ifile) => ifile.as_str().unwrap().to_string(), + Input::Str(_) => anon_src() } } -pub enum Input { - /// Load source from file - FileInput(Path), - /// The string is the source - StrInput(String) -} - -impl Input { - fn filestem(&self) -> String { - match *self { - FileInput(ref ifile) => ifile.filestem_str().unwrap().to_string(), - StrInput(_) => "rust_out".to_string(), - } - } -} - - pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate { let krate = time(sess.time_passes(), "parsing", (), |_| { match *input { - FileInput(ref file) => { + Input::File(ref file) => { parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess) } - StrInput(ref src) => { + Input::Str(ref src) => { parse::parse_crate_from_source_str(anon_src().to_string(), src.to_string(), cfg.clone(), @@ -342,23 +320,13 @@ pub fn assign_node_ids_and_map<'ast>(sess: &Session, map } -pub struct CrateAnalysis<'tcx> { - pub exp_map2: middle::resolve::ExportMap2, - pub exported_items: middle::privacy::ExportedItems, - pub public_items: middle::privacy::PublicItems, - pub ty_cx: ty::ctxt<'tcx>, - pub reachable: NodeSet, - pub name: String, -} - - /// Run the resolution, typechecking, region checking and other /// miscellaneous analysis passes on the crate. Return various /// structures carrying the results of the analysis. pub fn phase_3_run_analysis_passes<'tcx>(sess: Session, ast_map: ast_map::Map<'tcx>, type_arena: &'tcx TypedArena>, - name: String) -> CrateAnalysis<'tcx> { + name: String) -> ty::CrateAnalysis<'tcx> { let time_passes = sess.time_passes(); let krate = ast_map.krate(); @@ -473,7 +441,7 @@ pub fn phase_3_run_analysis_passes<'tcx>(sess: Session, time(time_passes, "lint checking", (), |_| lint::check_crate(&ty_cx, &exported_items)); - CrateAnalysis { + ty::CrateAnalysis { exp_map2: exp_map2, ty_cx: ty_cx, exported_items: exported_items, @@ -485,7 +453,7 @@ pub fn phase_3_run_analysis_passes<'tcx>(sess: Session, pub fn phase_save_analysis(sess: &Session, krate: &ast::Crate, - analysis: &CrateAnalysis, + analysis: &ty::CrateAnalysis, odir: &Option) { if (sess.opts.debugging_opts & config::SAVE_ANALYSIS) == 0 { return; @@ -494,25 +462,10 @@ pub fn phase_save_analysis(sess: &Session, save::process_crate(sess, krate, analysis, odir)); } -pub struct ModuleTranslation { - pub llcx: ContextRef, - pub llmod: ModuleRef, -} - -pub struct CrateTranslation { - pub modules: Vec, - pub metadata_module: ModuleTranslation, - pub link: LinkMeta, - pub metadata: Vec, - pub reachable: Vec, - pub crate_formats: dependency_format::Dependencies, - pub no_builtins: bool, -} - /// Run the translation phase to LLVM, after which the AST and analysis can /// be discarded. -pub fn phase_4_translate_to_llvm<'tcx>(analysis: CrateAnalysis<'tcx>) - -> (ty::ctxt<'tcx>, CrateTranslation) { +pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>) + -> (ty::ctxt<'tcx>, trans::CrateTranslation) { let time_passes = analysis.ty_cx.sess.time_passes(); time(time_passes, "resolving dependency formats", (), |_| @@ -520,13 +473,13 @@ pub fn phase_4_translate_to_llvm<'tcx>(analysis: CrateAnalysis<'tcx>) // Option dance to work around the lack of stack once closures. time(time_passes, "translation", analysis, |analysis| - trans::base::trans_crate(analysis)) + trans::trans_crate(analysis)) } /// Run LLVM itself, producing a bitcode file, assembly file or object file /// as a side effect. pub fn phase_5_run_llvm_passes(sess: &Session, - trans: &CrateTranslation, + trans: &trans::CrateTranslation, outputs: &OutputFilenames) { if sess.opts.cg.no_integrated_as { let output_type = config::OutputTypeAssembly; @@ -554,7 +507,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session, /// Run the linker on any artifacts that resulted from the LLVM run. /// This should produce either a finished executable or library. pub fn phase_6_link_output(sess: &Session, - trans: &CrateTranslation, + trans: &trans::CrateTranslation, outputs: &OutputFilenames) { let old_path = os::getenv("PATH").unwrap_or_else(||String::new()); let mut new_path = sess.host_filesearch().get_tools_search_paths(); @@ -639,8 +592,8 @@ fn write_out_deps(sess: &Session, // Use default filename: crate source filename with extension replaced // by ".d" (true, None) => match *input { - FileInput(..) => outputs.with_extension("d"), - StrInput(..) => { + Input::File(..) => outputs.with_extension("d"), + Input::Str(..) => { sess.warn("can not write --dep-info without a filename \ when compiling stdin."); return @@ -679,19 +632,19 @@ pub fn collect_crate_types(session: &Session, let attr_types: Vec = attrs.iter().filter_map(|a| { if a.check_name("crate_type") { match a.value_str() { - Some(ref n) if n.equiv(&("rlib")) => { + Some(ref n) if *n == "rlib" => { Some(config::CrateTypeRlib) } - Some(ref n) if n.equiv(&("dylib")) => { + Some(ref n) if *n == "dylib" => { Some(config::CrateTypeDylib) } - Some(ref n) if n.equiv(&("lib")) => { + Some(ref n) if *n == "lib" => { Some(config::default_lib_output()) } - Some(ref n) if n.equiv(&("staticlib")) => { + Some(ref n) if *n == "staticlib" => { Some(config::CrateTypeStaticlib) } - Some(ref n) if n.equiv(&("bin")) => Some(config::CrateTypeExecutable), + Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable), Some(_) => { session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES, ast::CRATE_NODE_ID, @@ -751,43 +704,6 @@ pub fn collect_crate_metadata(session: &Session, session.opts.cg.metadata.clone() } -#[deriving(Clone)] -pub struct OutputFilenames { - pub out_directory: Path, - pub out_filestem: String, - pub single_output_file: Option, - extra: String, -} - -impl OutputFilenames { - pub fn path(&self, flavor: config::OutputType) -> Path { - match self.single_output_file { - Some(ref path) => return path.clone(), - None => {} - } - self.temp_path(flavor) - } - - pub fn temp_path(&self, flavor: config::OutputType) -> Path { - let base = self.out_directory.join(self.filestem()); - match flavor { - config::OutputTypeBitcode => base.with_extension("bc"), - config::OutputTypeAssembly => base.with_extension("s"), - config::OutputTypeLlvmAssembly => base.with_extension("ll"), - config::OutputTypeObject => base.with_extension("o"), - config::OutputTypeExe => base, - } - } - - pub fn with_extension(&self, extension: &str) -> Path { - self.out_directory.join(self.filestem()).with_extension(extension) - } - - fn filestem(&self) -> String { - format!("{}{}", self.out_filestem, self.extra) - } -} - pub fn build_output_filenames(input: &Input, odir: &Option, ofile: &Option, diff --git a/src/librustc_trans/driver/mod.rs b/src/librustc_driver/lib.rs similarity index 90% rename from src/librustc_trans/driver/mod.rs rename to src/librustc_driver/lib.rs index 658be9169afdd..33c009cf3291b 100644 --- a/src/librustc_trans/driver/mod.rs +++ b/src/librustc_driver/lib.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// 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. // @@ -8,15 +8,46 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub use syntax::diagnostic; +//! The Rust compiler. +//! +//! # Note +//! +//! This API is completely unstable and subject to change. + +#![crate_name = "rustc_driver"] +#![experimental] +#![crate_type = "dylib"] +#![crate_type = "rlib"] +#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "http://doc.rust-lang.org/nightly/")] + +#![feature(default_type_params, globs, if_let, import_shadowing, macro_rules, phase, quote)] +#![feature(slicing_syntax, unsafe_destructor)] +#![feature(rustc_diagnostic_macros)] + +extern crate arena; +extern crate flate; +extern crate getopts; +extern crate graphviz; +extern crate libc; +extern crate rustc; +extern crate rustc_typeck; +extern crate rustc_back; +extern crate rustc_trans; +#[phase(plugin, link)] extern crate log; +#[phase(plugin, link)] extern crate syntax; +extern crate serialize; +extern crate "rustc_llvm" as llvm; -use back::link; -use driver::driver::{Input, FileInput, StrInput}; -use session::{config, Session, build_session}; -use lint::Lint; -use lint; -use metadata; +pub use syntax::diagnostic; +use rustc_trans::back::link; +use rustc::session::{config, Session, build_session}; +use rustc::session::config::Input; +use rustc::lint::Lint; +use rustc::lint; +use rustc::metadata; use rustc::DIAGNOSTICS; use std::any::AnyRefExt; @@ -24,14 +55,15 @@ use std::io; use std::os; use std::task::TaskBuilder; -use session::early_error; +use rustc::session::early_error; use syntax::ast; use syntax::parse; use syntax::diagnostic::Emitter; use syntax::diagnostics; -use getopts; +#[cfg(test)] +pub mod test; pub mod driver; pub mod pretty; @@ -89,9 +121,9 @@ fn run_compiler(args: &[String]) { if ifile == "-" { let contents = io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); - (StrInput(src), None) + (Input::Str(src), None) } else { - (FileInput(Path::new(ifile)), Some(Path::new(ifile))) + (Input::File(Path::new(ifile)), Some(Path::new(ifile))) } } _ => early_error("multiple input filenames provided") @@ -116,11 +148,11 @@ fn run_compiler(args: &[String]) { let r = matches.opt_strs("Z"); if r.contains(&("ls".to_string())) { match input { - FileInput(ref ifile) => { + Input::File(ref ifile) => { let mut stdout = io::stdout(); list_metadata(&sess, &(*ifile), &mut stdout).unwrap(); } - StrInput(_) => { + Input::Str(_) => { early_error("can not list metadata for stdin"); } } @@ -411,12 +443,12 @@ fn print_crate_info(sess: &Session, fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec { let result = match *input { - FileInput(ref ifile) => { + Input::File(ref ifile) => { parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess) } - StrInput(ref src) => { + Input::Str(ref src) => { parse::parse_crate_attrs_from_source_str( driver::anon_src().to_string(), src.to_string(), @@ -438,13 +470,7 @@ pub fn list_metadata(sess: &Session, path: &Path, /// The diagnostic emitter yielded to the procedure should be used for reporting /// errors of the compiler. pub fn monitor(f: proc():Send) { - // FIXME: This is a hack for newsched since it doesn't support split stacks. - // rustc needs a lot of stack! When optimizations are disabled, it needs - // even *more* stack than usual as well. - #[cfg(rtopt)] - static STACK_SIZE: uint = 6000000; // 6MB - #[cfg(not(rtopt))] - static STACK_SIZE: uint = 20000000; // 20MB + static STACK_SIZE: uint = 32000000; // 32MB let (tx, rx) = channel(); let w = io::ChanWriter::new(tx); @@ -507,3 +533,9 @@ pub fn monitor(f: proc():Send) { } } +pub fn main() { + let args = std::os::args(); + let result = run(args); + std::os::set_exit_status(result); +} + diff --git a/src/librustc_driver/mod.rs b/src/librustc_driver/mod.rs new file mode 100644 index 0000000000000..1fbbc9c05213b --- /dev/null +++ b/src/librustc_driver/mod.rs @@ -0,0 +1,10 @@ +// 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. + diff --git a/src/librustc_trans/driver/pretty.rs b/src/librustc_driver/pretty.rs similarity index 97% rename from src/librustc_trans/driver/pretty.rs rename to src/librustc_driver/pretty.rs index 7bb83d7c2a819..b6441ab4944f7 100644 --- a/src/librustc_trans/driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -15,18 +15,18 @@ pub use self::PpSourceMode::*; pub use self::PpMode::*; use self::NodesMatchingUII::*; -use back::link; +use rustc_trans::back::link; -use session::{config, Session}; -use driver::driver::{mod, CrateAnalysis}; +use driver; -use middle::ty; -use middle::borrowck::{mod, FnPartsWithCFG}; -use middle::borrowck::graphviz as borrowck_dot; -use middle::cfg; -use middle::cfg::graphviz::LabelledCFG; - -use util::ppaux; +use rustc::middle::ty; +use rustc::middle::borrowck::{mod, FnPartsWithCFG}; +use rustc::middle::borrowck::graphviz as borrowck_dot; +use rustc::middle::cfg; +use rustc::middle::cfg::graphviz::LabelledCFG; +use rustc::session::Session; +use rustc::session::config::{mod, Input}; +use rustc::util::ppaux; use syntax::ast; use syntax::ast_map::{mod, blocks, NodePrinter}; @@ -242,7 +242,7 @@ impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> { struct TypedAnnotation<'tcx> { - analysis: CrateAnalysis<'tcx>, + analysis: ty::CrateAnalysis<'tcx>, } impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> { @@ -409,7 +409,7 @@ fn needs_expansion(ppm: &PpMode) -> bool { pub fn pretty_print_input(sess: Session, cfg: ast::CrateConfig, - input: &driver::Input, + input: &Input, ppm: PpMode, opt_uii: Option, ofile: Option) { @@ -536,7 +536,7 @@ pub fn pretty_print_input(sess: Session, } fn print_flowgraph(variants: Vec, - analysis: CrateAnalysis, + analysis: ty::CrateAnalysis, code: blocks::Code, mut out: W) -> io::IoResult<()> { let ty_cx = &analysis.ty_cx; diff --git a/src/librustc_trans/test.rs b/src/librustc_driver/test.rs similarity index 99% rename from src/librustc_trans/test.rs rename to src/librustc_driver/test.rs index 41fbe85576933..9244e6909e8a4 100644 --- a/src/librustc_trans/test.rs +++ b/src/librustc_driver/test.rs @@ -21,10 +21,10 @@ use middle::stability; use middle::subst; use middle::subst::Subst; use middle::ty::{mod, Ty}; -use middle::typeck::infer::combine::Combine; -use middle::typeck::infer; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::glb::Glb; +use middle::infer::combine::Combine; +use middle::infer; +use middle::infer::lub::Lub; +use middle::infer::glb::Glb; use session::{mod,config}; use syntax::{abi, ast, ast_map, ast_util}; use syntax::codemap; diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index d8cdffe210057..6057f9d908190 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -13,15 +13,13 @@ use super::archive; use super::rpath; use super::rpath::RPathConfig; use super::svh::Svh; -use driver::driver::{CrateTranslation, OutputFilenames, Input, FileInput}; use session::config; use session::config::NoDebugInfo; -use session::config::{OutputTypeBitcode, OutputTypeExe, OutputTypeObject}; +use session::config::{OutputFilenames, Input, OutputTypeBitcode, OutputTypeExe, OutputTypeObject}; use session::Session; use metadata::common::LinkMeta; use metadata::{encoder, cstore, filesearch, csearch, creader}; -use trans::context::CrateContext; -use trans::common::gensym_name; +use trans::{CrateContext, CrateTranslation, gensym_name}; use middle::ty::{mod, Ty}; use util::common::time; use util::ppaux; @@ -156,7 +154,7 @@ pub fn find_crate_name(sess: Option<&Session>, if let Some((attr, s)) = attr_crate_name { return validate(s.get().to_string(), Some(attr.span)); } - if let FileInput(ref path) = *input { + if let Input::File(ref path) = *input { if let Some(s) = path.filestem_str() { return validate(s.to_string(), None); } diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index b923bb076c301..e5ffe2675d6f4 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -10,13 +10,13 @@ use back::lto; use back::link::{get_cc_prog, remove}; -use driver::driver::{CrateTranslation, ModuleTranslation, OutputFilenames}; -use session::config::{NoDebugInfo, Passes, SomePasses, AllPasses}; +use session::config::{OutputFilenames, NoDebugInfo, Passes, SomePasses, AllPasses}; use session::Session; use session::config; use llvm; use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef}; use llvm::SMDiagnosticRef; +use trans::{CrateTranslation, ModuleTranslation}; use util::common::time; use syntax::codemap; use syntax::diagnostic; diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index 4dc8c4d173633..4e25921e0b29b 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -65,17 +65,7 @@ pub mod back { pub mod trans; pub mod save; -pub mod driver; pub mod lib { pub use llvm; } - -pub fn main() { - let args = std::os::args(); - let result = driver::run(args); - std::os::set_exit_status(result); -} - -#[cfg(test)] -pub mod test; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 7a41be1dbe46f..1482422b8d03e 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -27,10 +27,9 @@ //! the format of the output away from extracting it from the compiler. //! DxrVisitor walks the AST and processes it. -use driver::driver::CrateAnalysis; use session::Session; -use middle::{def, typeck}; +use middle::def; use middle::ty::{mod, Ty}; use std::cell::Cell; @@ -68,7 +67,7 @@ fn generated_code(span: Span) -> bool { struct DxrVisitor<'l, 'tcx: 'l> { sess: &'l Session, - analysis: &'l CrateAnalysis<'tcx>, + analysis: &'l ty::CrateAnalysis<'tcx>, collected_paths: Vec<(NodeId, ast::Path, bool, recorder::Row)>, collecting: bool, @@ -912,10 +911,10 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { ex: &ast::Expr, args: &Vec>) { let method_map = self.analysis.ty_cx.method_map.borrow(); - let method_callee = &(*method_map)[typeck::MethodCall::expr(ex.id)]; + let method_callee = &(*method_map)[ty::MethodCall::expr(ex.id)]; let (def_id, decl_id) = match method_callee.origin { - typeck::MethodStatic(def_id) | - typeck::MethodStaticUnboxedClosure(def_id) => { + ty::MethodStatic(def_id) | + ty::MethodStaticUnboxedClosure(def_id) => { // method invoked on an object with a concrete type (not a static method) let decl_id = match ty::trait_item_of_item(&self.analysis.ty_cx, @@ -936,14 +935,14 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { }; (Some(def_id), decl_id) } - typeck::MethodTypeParam(ref mp) => { + ty::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::MethodTraitObject(ref mo) => { + ty::MethodTraitObject(ref mo) => { // method invoked on a trait instance let trait_item = ty::trait_item(&self.analysis.ty_cx, mo.trait_ref.def_id, @@ -1473,7 +1472,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { pub fn process_crate(sess: &Session, krate: &ast::Crate, - analysis: &CrateAnalysis, + analysis: &ty::CrateAnalysis, odir: &Option) { if generated_code(krate.span) { return; diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 71439f5887b1a..3ace9e8a9d318 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -28,9 +28,11 @@ pub use self::ValueOrigin::*; pub use self::scalar_type::*; +use super::CrateTranslation; +use super::ModuleTranslation; + use back::link::{mangle_exported_name}; use back::{link, abi}; -use driver::driver::{CrateAnalysis, CrateTranslation, ModuleTranslation}; use lint; use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param}; use llvm; @@ -967,23 +969,14 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef, llargs: Vec , fn_ty: Ty<'tcx>, - call_info: Option, - // FIXME(15064) is_lang_item is a horrible hack, please remove it - // at the soonest opportunity. - is_lang_item: bool) + call_info: Option) -> (ValueRef, Block<'blk, 'tcx>) { let _icx = push_ctxt("invoke_"); if bcx.unreachable.get() { return (C_null(Type::i8(bcx.ccx())), bcx); } - // FIXME(15064) Lang item methods may (in the reflect case) not have proper - // types, so doing an attribute lookup will fail. - let attributes = if is_lang_item { - llvm::AttrBuilder::new() - } else { - get_fn_llvm_attributes(bcx.ccx(), fn_ty) - }; + let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty); match bcx.opt_node_id { None => { @@ -1078,12 +1071,6 @@ pub fn store_ty(cx: Block, v: ValueRef, dst: ValueRef, t: Ty) { }; } -pub fn ignore_lhs(_bcx: Block, local: &ast::Local) -> bool { - match local.pat.node { - ast::PatWild(ast::PatWildSingle) => true, _ => false - } -} - pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local) -> Block<'blk, 'tcx> { debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id); @@ -2916,12 +2903,6 @@ fn register_method(ccx: &CrateContext, id: ast::NodeId, llfn } -pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef { - unsafe { - return llvm::LLVMConstPtrToInt(v, ccx.int_type().to_ref()); - } -} - pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>, ie: encoder::EncodeInlinedItem<'a>) -> encoder::EncodeParams<'a, 'tcx> { @@ -3055,9 +3036,9 @@ fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet) { } } -pub fn trans_crate<'tcx>(analysis: CrateAnalysis<'tcx>) +pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>) -> (ty::ctxt<'tcx>, CrateTranslation) { - let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis; + let ty::CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis; let krate = tcx.map.krate(); // Before we touch LLVM, make sure that multithreading is enabled. diff --git a/src/librustc_trans/trans/cabi.rs b/src/librustc_trans/trans/cabi.rs index 0214bf29eeeb9..518b0ba73f8b7 100644 --- a/src/librustc_trans/trans/cabi.rs +++ b/src/librustc_trans/trans/cabi.rs @@ -65,8 +65,8 @@ impl ArgType { ArgType { kind: Indirect, ty: ty, - cast: option::None, - pad: option::None, + cast: option::Option::None, + pad: option::Option::None, attr: attr } } diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index 80a17465d7899..9405d6bd34b11 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -49,8 +49,7 @@ use trans::monomorphize; use trans::type_::Type; use trans::type_of; use middle::ty::{mod, Ty}; -use middle::typeck::coherence::make_substs_for_receiver_types; -use middle::typeck::MethodCall; +use middle::ty::MethodCall; use util::ppaux::Repr; use util::ppaux::ty_to_string; @@ -459,7 +458,7 @@ pub fn trans_fn_ref_with_substs<'blk, 'tcx>( // Compute the first substitution let first_subst = - make_substs_for_receiver_types(tcx, &*trait_ref, &*method) + ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method) .erase_regions(); // And compose them @@ -810,8 +809,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn, llargs, callee_ty, - call_info, - dest.is_none()); + call_info); bcx = b; llresult = llret; diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index febb33f6c54af..a8256176c2658 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -19,6 +19,7 @@ use llvm; use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef}; use llvm::{True, False, Bool}; use middle::def; +use middle::infer; use middle::lang_items::LangItem; use middle::mem_categorization as mc; use middle::region; @@ -36,8 +37,6 @@ use middle::traits; use middle::ty::{mod, Ty}; use middle::ty_fold; use middle::ty_fold::TypeFoldable; -use middle::typeck; -use middle::typeck::infer; use util::ppaux::Repr; use util::nodemap::{DefIdMap, FnvHashMap, NodeMap}; @@ -273,11 +272,6 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> { } } - pub fn out_arg_pos(&self) -> uint { - assert!(self.caller_expects_out_pointer); - 0u - } - pub fn env_arg_pos(&self) -> uint { if self.caller_expects_out_pointer { 1u @@ -468,7 +462,7 @@ impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> { Ok(node_id_type(self, id)) } - fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option> { + fn node_method_ty(&self, method_call: ty::MethodCall) -> Option> { self.tcx() .method_map .borrow() @@ -481,7 +475,7 @@ impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> { } fn is_method_call(&self, id: ast::NodeId) -> bool { - self.tcx().method_map.borrow().contains_key(&typeck::MethodCall::expr(id)) + self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id)) } fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option { @@ -870,7 +864,7 @@ pub enum ExprOrMethodCall { ExprId(ast::NodeId), // Type parameters for a method call like `a.foo::()` - MethodCall(typeck::MethodCall) + MethodCall(ty::MethodCall) } pub fn node_id_substs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, diff --git a/src/librustc_trans/trans/context.rs b/src/librustc_trans/trans/context.rs index a0b7eb02f02e4..1cd939f9b466a 100644 --- a/src/librustc_trans/trans/context.rs +++ b/src/librustc_trans/trans/context.rs @@ -346,10 +346,6 @@ impl<'tcx> SharedCrateContext<'tcx> { &self.link_meta } - pub fn symbol_hasher<'a>(&'a self) -> &'a RefCell { - &self.symbol_hasher - } - pub fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { &self.tcx } diff --git a/src/librustc_trans/trans/controlflow.rs b/src/librustc_trans/trans/controlflow.rs index 3d32f6045a771..a1574aa2f0e43 100644 --- a/src/librustc_trans/trans/controlflow.rs +++ b/src/librustc_trans/trans/controlflow.rs @@ -27,7 +27,7 @@ use trans::meth; use trans::type_::Type; use trans; use middle::ty; -use middle::typeck::MethodCall; +use middle::ty::MethodCall; use session::config::FullDebugInfo; use util::ppaux::Repr; use util::ppaux; diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index f0fd94958ee97..532ef69081866 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -352,13 +352,6 @@ impl<'tcx> Datum<'tcx, Expr> { |_| bcx.sess().bug("assert_lvalue given rvalue")) } - /// Asserts that this datum *is* an lvalue and returns it. - pub fn assert_rvalue(self, bcx: Block) -> Datum<'tcx, Rvalue> { - self.match_kind( - |_| bcx.sess().bug("assert_rvalue given lvalue"), - |r| r) - } - pub fn store_to_dest<'blk>(self, bcx: Block<'blk, 'tcx>, dest: expr::Dest, diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index e798dd4dc945f..555cb0004892f 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -1545,7 +1545,7 @@ fn compile_unit_metadata(cx: &CrateContext) { Some(ref p) if p.is_relative() => { // prepend "./" if necessary let dotdot = b".."; - let prefix = &[dotdot[0], ::std::path::SEP_BYTE]; + let prefix = [dotdot[0], ::std::path::SEP_BYTE]; let mut path_bytes = p.as_vec().to_vec(); if path_bytes.slice_to(2) != prefix && diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 646ee601a4ca4..d130dc0a55b1c 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -41,15 +41,23 @@ use middle::def; use middle::mem_categorization::Typer; use middle::subst::{mod, Subst}; use trans::{_match, adt, asm, base, callee, closure, consts, controlflow}; -use trans::{debuginfo, glue, machine, meth, inline, tvec, type_of}; use trans::base::*; use trans::build::*; use trans::cleanup::{mod, CleanupMethods}; use trans::common::*; use trans::datum::*; -use middle::ty::{mod, struct_fields, tup_fields}; -use middle::ty::{AdjustDerefRef, AdjustAddEnv, AutoUnsafe, AutoPtr, Ty}; -use middle::typeck::{mod, MethodCall}; +use trans::debuginfo; +use trans::glue; +use trans::machine; +use trans::meth; +use trans::inline; +use trans::tvec; +use trans::type_of; +use middle::ty::{struct_fields, tup_fields}; +use middle::ty::{AdjustDerefRef, AdjustAddEnv, AutoUnsafe}; +use middle::ty::{AutoPtr}; +use middle::ty::{mod, Ty}; +use middle::ty::MethodCall; use util::common::indenter; use util::ppaux::Repr; use trans::machine::{llsize_of, llsize_of_alloc}; @@ -2091,7 +2099,7 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // path (below) to dereference that `&T`. let datum = match method_call.adjustment { // Always perform an AutoPtr when applying an overloaded auto-deref - typeck::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)), + ty::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)), _ => datum }; diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index 4ed7983789696..5eb3572206ee7 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -291,7 +291,7 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let dtor_ty = ty::mk_ctor_fn(bcx.tcx(), &[get_drop_glue_type(bcx.ccx(), t)], ty::mk_nil(bcx.tcx())); - let (_, variant_cx) = invoke(variant_cx, dtor_addr, args, dtor_ty, None, false); + let (_, variant_cx) = invoke(variant_cx, dtor_addr, args, dtor_ty, None); variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope); variant_cx diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index a49b7b21627f8..ab51a88c3c4a9 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -31,8 +31,7 @@ use trans::machine; use trans::type_::Type; use trans::type_of::*; use middle::ty::{mod, Ty}; -use middle::typeck; -use middle::typeck::MethodCall; +use middle::ty::MethodCall; use util::ppaux::Repr; use std::c_str::ToCStr; @@ -119,8 +118,8 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, .unwrap(); match origin { - typeck::MethodStatic(did) | - typeck::MethodStaticUnboxedClosure(did) => { + ty::MethodStatic(did) | + ty::MethodStaticUnboxedClosure(did) => { Callee { bcx: bcx, data: Fn(callee::trans_fn_ref(bcx, @@ -129,7 +128,7 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } } - typeck::MethodTypeParam(typeck::MethodParam { + ty::MethodTypeParam(ty::MethodParam { ref trait_ref, method_num }) => { @@ -147,7 +146,7 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, method_num, origin) } - typeck::MethodTraitObject(ref mt) => { + ty::MethodTraitObject(ref mt) => { let self_expr = match self_expr { Some(self_expr) => self_expr, None => { diff --git a/src/librustc_trans/trans/mod.rs b/src/librustc_trans/trans/mod.rs index fe7697447acda..c00c477f4b8d2 100644 --- a/src/librustc_trans/trans/mod.rs +++ b/src/librustc_trans/trans/mod.rs @@ -8,40 +8,64 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub mod doc; -pub mod macros; -pub mod inline; -pub mod monomorphize; -pub mod controlflow; -pub mod glue; -pub mod datum; -pub mod callee; -pub mod expr; -pub mod common; -pub mod context; -pub mod consts; -pub mod type_of; -pub mod build; -pub mod builder; -pub mod base; -pub mod _match; -pub mod closure; -pub mod tvec; -pub mod meth; -pub mod cabi; -pub mod cabi_x86; -pub mod cabi_x86_64; -pub mod cabi_x86_win64; -pub mod cabi_arm; -pub mod cabi_mips; -pub mod foreign; -pub mod intrinsic; -pub mod debuginfo; -pub mod machine; -pub mod adt; -pub mod asm; -pub mod type_; -pub mod value; -pub mod basic_block; -pub mod llrepr; -pub mod cleanup; +use llvm::{ContextRef, ModuleRef}; +use metadata::common::LinkMeta; +use middle::dependency_format; + +pub use self::base::trans_crate; +pub use self::context::CrateContext; +pub use self::common::gensym_name; + +mod doc; +mod macros; +mod inline; +mod monomorphize; +mod controlflow; +mod glue; +mod datum; +mod callee; +mod expr; +mod common; +mod context; +mod consts; +mod type_of; +mod build; +mod builder; +mod base; +mod _match; +mod closure; +mod tvec; +mod meth; +mod cabi; +mod cabi_x86; +mod cabi_x86_64; +mod cabi_x86_win64; +mod cabi_arm; +mod cabi_mips; +mod foreign; +mod intrinsic; +mod debuginfo; +mod machine; +mod adt; +mod asm; +mod type_; +mod value; +mod basic_block; +mod llrepr; +mod cleanup; + +pub struct ModuleTranslation { + pub llcx: ContextRef, + pub llmod: ModuleRef, +} + +pub struct CrateTranslation { + pub modules: Vec, + pub metadata_module: ModuleTranslation, + pub link: LinkMeta, + pub metadata: Vec, + pub reachable: Vec, + pub crate_formats: dependency_format::Dependencies, + pub no_builtins: bool, +} + diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc_typeck/astconv.rs similarity index 95% rename from src/librustc/middle/typeck/astconv.rs rename to src/librustc_typeck/astconv.rs index 89c004fc64596..c39b83b9946e6 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -46,17 +46,17 @@ //! Note that the self region for the `foo` defaulted to `&` in the first //! case but `&a` in the second. Basically, defaults that appear inside //! an rptr (`&r.T`) use the region `r` that appears in the rptr. + +use middle::astconv_util::{ast_ty_to_prim_ty, check_path_args, NO_TPS, NO_REGIONS}; use middle::const_eval; use middle::def; use middle::resolve_lifetime as rl; use middle::subst::{FnSpace, TypeSpace, AssocSpace, SelfSpace, Subst, Substs}; use middle::subst::{VecPerParamSpace}; use middle::ty::{mod, Ty}; -use middle::typeck::lookup_def_tcx; -use middle::typeck::rscope::{UnelidableRscope, RegionScope, SpecificRscope, - ShiftedRscope, BindingRscope}; -use middle::typeck::rscope; -use middle::typeck::TypeAndSubsts; +use rscope::{mod, UnelidableRscope, RegionScope, SpecificRscope, + ShiftedRscope, BindingRscope}; +use TypeAndSubsts; use util::common::ErrorReported; use util::nodemap::DefIdMap; use util::ppaux::{mod, Repr, UserString}; @@ -428,9 +428,9 @@ pub fn instantiate_trait_ref<'tcx,AC,RS>(this: &AC, where AC: AstConv<'tcx>, RS: RegionScope { - match lookup_def_tcx(this.tcx(), - ast_trait_ref.path.span, - ast_trait_ref.ref_id) { + match ::lookup_def_tcx(this.tcx(), + ast_trait_ref.path.span, + ast_trait_ref.ref_id) { def::DefTrait(trait_def_id) => { let trait_ref = Rc::new(ast_path_to_trait_ref(this, rscope, trait_def_id, self_ty, &ast_trait_ref.path)); @@ -553,74 +553,6 @@ pub fn ast_path_to_ty_relaxed<'tcx,AC,RS>( } } -pub const NO_REGIONS: uint = 1; -pub const NO_TPS: uint = 2; - -fn check_path_args(tcx: &ty::ctxt, - path: &ast::Path, - flags: uint) { - if (flags & NO_TPS) != 0u { - if path.segments.iter().any(|s| s.parameters.has_types()) { - span_err!(tcx.sess, path.span, E0109, - "type parameters are not allowed on this type"); - } - } - - if (flags & NO_REGIONS) != 0u { - if path.segments.iter().any(|s| s.parameters.has_lifetimes()) { - span_err!(tcx.sess, path.span, E0110, - "region parameters are not allowed on this type"); - } - } -} - -pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) - -> Option> { - match ast_ty.node { - ast::TyPath(ref path, id) => { - let a_def = match tcx.def_map.borrow().get(&id) { - None => { - tcx.sess.span_bug(ast_ty.span, - format!("unbound path {}", - path.repr(tcx)).as_slice()) - } - Some(&d) => d - }; - match a_def { - def::DefPrimTy(nty) => { - match nty { - ast::TyBool => { - check_path_args(tcx, path, NO_TPS | NO_REGIONS); - Some(ty::mk_bool()) - } - ast::TyChar => { - check_path_args(tcx, path, NO_TPS | NO_REGIONS); - Some(ty::mk_char()) - } - ast::TyInt(it) => { - check_path_args(tcx, path, NO_TPS | NO_REGIONS); - Some(ty::mk_mach_int(it)) - } - ast::TyUint(uit) => { - check_path_args(tcx, path, NO_TPS | NO_REGIONS); - Some(ty::mk_mach_uint(uit)) - } - ast::TyFloat(ft) => { - check_path_args(tcx, path, NO_TPS | NO_REGIONS); - Some(ty::mk_mach_float(ft)) - } - ast::TyStr => { - Some(ty::mk_str(tcx)) - } - } - } - _ => None - } - } - _ => None - } -} - /// Converts the given AST type to a built-in type. A "built-in type" is, at /// present, either a core numeric type, a string, or `Box`. pub fn ast_ty_to_builtin_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>( @@ -715,7 +647,7 @@ fn ast_ty_to_trait_ref<'tcx,AC,RS>(this: &AC, match ty.node { ast::TyRptr(None, ref mut_ty) => { span_note!(this.tcx().sess, ty.span, - "perhaps you meant `&{}({} +{})`? (per RFC 248)", + "perhaps you meant `&{}({} +{})`? (per RFC 438)", ppaux::mutability_to_string(mut_ty.mutbl), pprust::ty_to_string(&*mut_ty.ty), pprust::bounds_to_string(bounds)); @@ -723,7 +655,7 @@ fn ast_ty_to_trait_ref<'tcx,AC,RS>(this: &AC, ast::TyRptr(Some(ref lt), ref mut_ty) => { span_note!(this.tcx().sess, ty.span, - "perhaps you meant `&{} {}({} +{})`? (per RFC 248)", + "perhaps you meant `&{} {}({} +{})`? (per RFC 438)", pprust::lifetime_to_string(lt), ppaux::mutability_to_string(mut_ty.mutbl), pprust::ty_to_string(&*mut_ty.ty), @@ -732,7 +664,7 @@ fn ast_ty_to_trait_ref<'tcx,AC,RS>(this: &AC, _ => { span_note!(this.tcx().sess, ty.span, - "perhaps you forgot parentheses? (per RFC 248)"); + "perhaps you forgot parentheses? (per RFC 438)"); } } Err(ErrorReported) @@ -1544,7 +1476,7 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt, for &ast_bound in ast_bounds.iter() { match *ast_bound { ast::TraitTyParamBound(ref b) => { - match lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) { + match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) { def::DefTrait(trait_did) => { match trait_def_ids.get(&trait_did) { // Already seen this trait. We forbid diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs similarity index 98% rename from src/librustc/middle/typeck/check/_match.rs rename to src/librustc_typeck/check/_match.rs index cdfd607d06710..7dcf0aa3e2189 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -9,13 +9,13 @@ // except according to those terms. use middle::def; +use middle::infer::{mod, resolve}; use middle::pat_util::{PatIdMap, pat_id_map, pat_is_binding, pat_is_const}; use middle::subst::{Subst, Substs}; use middle::ty::{mod, Ty}; -use middle::typeck::check::{check_expr, check_expr_has_type, demand, FnCtxt}; -use middle::typeck::check::{instantiate_path, structurally_resolved_type, valid_range_bounds}; -use middle::typeck::infer::{mod, resolve}; -use middle::typeck::require_same_types; +use check::{check_expr, check_expr_has_type, demand, FnCtxt}; +use check::{instantiate_path, structurally_resolved_type, valid_range_bounds}; +use require_same_types; use util::nodemap::FnvHashMap; use std::cmp; diff --git a/src/librustc/middle/typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs similarity index 99% rename from src/librustc/middle/typeck/check/closure.rs rename to src/librustc_typeck/check/closure.rs index 0a93b3a5ec7dc..34030ae4493a2 100644 --- a/src/librustc/middle/typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -14,11 +14,11 @@ use super::check_fn; use super::{Expectation, ExpectCastableToType, ExpectHasType, NoExpectation}; use super::FnCtxt; +use astconv; +use middle::infer; use middle::subst; use middle::ty::{mod, Ty}; -use middle::typeck::astconv; -use middle::typeck::infer; -use middle::typeck::rscope::RegionScope; +use rscope::RegionScope; use syntax::abi; use syntax::ast; use syntax::ast_util; diff --git a/src/librustc/middle/typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs similarity index 81% rename from src/librustc/middle/typeck/check/demand.rs rename to src/librustc_typeck/check/demand.rs index 1e45d059b849b..9eb0e17b8e5be 100644 --- a/src/librustc/middle/typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -9,14 +9,13 @@ // except according to those terms. +use check::FnCtxt; use middle::ty::{mod, Ty}; -use middle::typeck::check::FnCtxt; -use middle::typeck::infer; -use middle::typeck::infer::resolve_type; -use middle::typeck::infer::resolve::try_resolve_tvar_shallow; +use middle::infer; +use middle::infer::resolve_type; +use middle::infer::resolve::try_resolve_tvar_shallow; -use std::result::{Err, Ok}; -use std::result; +use std::result::Result::{Err, Ok}; use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; @@ -29,12 +28,6 @@ pub fn suptype<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) }) } -pub fn subtype<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, - expected: Ty<'tcx>, actual: Ty<'tcx>) { - suptype_with_fn(fcx, sp, true, actual, expected, - |sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) }) -} - pub fn suptype_with_fn<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, b_is_expected: bool, @@ -44,8 +37,8 @@ pub fn suptype_with_fn<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // n.b.: order of actual, expected is reversed match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp), ty_b, ty_a) { - result::Ok(()) => { /* ok */ } - result::Err(ref err) => { + Ok(()) => { /* ok */ } + Err(ref err) => { handle_err(sp, ty_a, ty_b, err); } } @@ -75,8 +68,8 @@ pub fn coerce<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, try_resolve_tvar_shallow).unwrap_or(expected) } else { expected }; match fcx.mk_assignty(expr, expr_ty, expected) { - result::Ok(()) => { /* ok */ } - result::Err(ref err) => { + Ok(()) => { /* ok */ } + Err(ref err) => { fcx.report_mismatched_types(sp, expected, expr_ty, err); } } diff --git a/src/librustc/middle/typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs similarity index 99% rename from src/librustc/middle/typeck/check/method/confirm.rs rename to src/librustc_typeck/check/method/confirm.rs index e866627be3d29..1fe73f0478d56 100644 --- a/src/librustc/middle/typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -10,13 +10,14 @@ use super::probe; +use check::{mod, FnCtxt, NoPreference, PreferMutLvalue}; use middle::subst::{mod, Subst}; use middle::traits; use middle::ty::{mod, Ty}; -use middle::typeck::check::{mod, FnCtxt, NoPreference, PreferMutLvalue}; -use middle::typeck::{MethodCall, MethodCallee, MethodObject, MethodOrigin, - MethodParam, MethodStatic, MethodTraitObject, MethodTypeParam}; -use middle::typeck::infer::{mod, InferCtxt}; +use middle::ty::{MethodCall, MethodCallee, MethodObject, MethodOrigin, + MethodParam, MethodStatic, MethodTraitObject, MethodTypeParam}; +use middle::infer; +use middle::infer::InferCtxt; use middle::ty_fold::HigherRankedFoldable; use syntax::ast; use syntax::codemap::Span; diff --git a/src/librustc/middle/typeck/check/method/doc.rs b/src/librustc_typeck/check/method/doc.rs similarity index 100% rename from src/librustc/middle/typeck/check/method/doc.rs rename to src/librustc_typeck/check/method/doc.rs diff --git a/src/librustc/middle/typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs similarity index 98% rename from src/librustc/middle/typeck/check/method/mod.rs rename to src/librustc_typeck/check/method/mod.rs index 34c3292f8cd69..f87a4c9294bab 100644 --- a/src/librustc/middle/typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -10,19 +10,17 @@ //! Method lookup: the secret sauce of Rust. See `doc.rs`. +use astconv::AstConv; +use check::{FnCtxt}; +use check::{impl_self_ty}; +use check::vtable; +use check::vtable::select_new_fcx_obligations; use middle::subst; use middle::subst::{Subst}; use middle::traits; use middle::ty::*; use middle::ty; -use middle::typeck::astconv::AstConv; -use middle::typeck::check::{FnCtxt}; -use middle::typeck::check::{impl_self_ty}; -use middle::typeck::check::vtable; -use middle::typeck::check::vtable::select_new_fcx_obligations; -use middle::typeck::infer; -use middle::typeck::{MethodCallee}; -use middle::typeck::{MethodParam, MethodTypeParam}; +use middle::infer; use util::ppaux::{Repr, UserString}; use std::rc::Rc; diff --git a/src/librustc/middle/typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs similarity index 99% rename from src/librustc/middle/typeck/check/method/probe.rs rename to src/librustc_typeck/check/method/probe.rs index 484d72130e61d..6ff276edbce7e 100644 --- a/src/librustc/middle/typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -12,17 +12,17 @@ use super::{MethodError,Ambiguity,NoMatch}; use super::MethodIndex; use super::{CandidateSource,ImplSource,TraitSource}; +use check; +use check::{FnCtxt, NoPreference}; use middle::fast_reject; use middle::subst; use middle::subst::Subst; use middle::traits; use middle::ty::{mod, Ty}; +use middle::ty::{MethodObject}; use middle::ty_fold::HigherRankedFoldable; -use middle::typeck::check; -use middle::typeck::check::{FnCtxt, NoPreference}; -use middle::typeck::{MethodObject}; -use middle::typeck::infer; -use middle::typeck::infer::InferCtxt; +use middle::infer; +use middle::infer::InferCtxt; use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; use std::collections::HashSet; diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs similarity index 99% rename from src/librustc/middle/typeck/check/mod.rs rename to src/librustc_typeck/check/mod.rs index 641cbd11d64e0..b819350f8f92c 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -31,7 +31,7 @@ can be broken down into several distinct phases: In the process of checking, various constraints will be placed on these type variables through the subtyping relationships requested - through the `demand` module. The `typeck::infer` module is in charge + through the `demand` module. The `infer` module is in charge of resolving those constraints. - regionck: after main is complete, the regionck pass goes over all @@ -82,8 +82,10 @@ pub use self::Expectation::*; use self::IsBinopAssignment::*; use self::TupleArgumentsFlag::*; -use session::Session; +use astconv::{mod, ast_region_to_region, ast_ty_to_ty, AstConv}; +use check::_match::pat_ctxt; use middle::{const_eval, def, traits}; +use middle::infer; use middle::lang_items::IteratorItem; use middle::mem_categorization::{mod, McResult}; use middle::pat_util::{mod, pat_id_map}; @@ -93,12 +95,12 @@ use middle::ty::{FnSig, VariantInfo, Polytype}; use middle::ty::{Disr, ParamTy, ParameterEnvironment}; use middle::ty::{mod, Ty}; use middle::ty::liberate_late_bound_regions; +use middle::ty::{MethodCall, MethodCallee, MethodMap, ObjectCastMap}; use middle::ty_fold::TypeFolder; -use middle::typeck::astconv::{mod, ast_region_to_region, ast_ty_to_ty, AstConv}; -use middle::typeck::check::_match::pat_ctxt; -use middle::typeck::rscope::RegionScope; -use middle::typeck::{mod, CrateCtxt, infer, lookup_def_ccx, no_params, require_same_types}; -use middle::typeck::{MethodCall, MethodCallee, MethodMap, ObjectCastMap, TypeAndSubsts}; +use rscope::RegionScope; +use session::Session; +use {CrateCtxt, lookup_def_ccx, no_params, require_same_types}; +use TypeAndSubsts; use middle::lang_items::TypeIdLangItem; use lint; use util::common::{block_query, indenter, loop_query}; @@ -279,7 +281,7 @@ impl<'a, 'tcx> mem_categorization::Typer<'tcx> for FnCtxt<'a, 'tcx> { fn node_ty(&self, id: ast::NodeId) -> McResult> { Ok(self.node_ty(id)) } - fn node_method_ty(&self, method_call: typeck::MethodCall) + fn node_method_ty(&self, method_call: ty::MethodCall) -> Option> { self.inh.method_map.borrow().get(&method_call).map(|m| m.ty) } @@ -287,7 +289,7 @@ impl<'a, 'tcx> mem_categorization::Typer<'tcx> for FnCtxt<'a, 'tcx> { &self.inh.adjustments } fn is_method_call(&self, id: ast::NodeId) -> bool { - self.inh.method_map.borrow().contains_key(&typeck::MethodCall::expr(id)) + self.inh.method_map.borrow().contains_key(&ty::MethodCall::expr(id)) } fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option { self.tcx().temporary_scope(rvalue_id) @@ -359,6 +361,17 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckItemTypesVisitor<'a, 'tcx> { check_item(self.ccx, i); visit::walk_item(self, i); } + + fn visit_ty(&mut self, t: &ast::Ty) { + match t.node { + ast::TyFixedLengthVec(_, ref expr) => { + check_const_in_type(self.ccx, &**expr, ty::mk_uint()); + } + _ => {} + } + + visit::walk_ty(self, t); + } } pub fn check_item_types(ccx: &CrateCtxt) { @@ -393,7 +406,7 @@ fn check_bare_fn<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, decl, id, body, &inh); vtable::select_all_fcx_obligations_or_error(&fcx); - regionck::regionck_fn(&fcx, id, body); + regionck::regionck_fn(&fcx, id, decl, body); fcx.default_diverging_type_variables_to_nil(); writeback::resolve_type_vars_in_fn(&fcx, decl, body); } @@ -1860,13 +1873,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - /// Fetch type of `expr` after applying adjustments that have been recorded in the fcx. - pub fn expr_ty_adjusted(&self, expr: &ast::Expr) -> Ty<'tcx> { - let adjustments = self.inh.adjustments.borrow(); - let adjustment = adjustments.get(&expr.id); - self.adjust_expr_ty(expr, adjustment) - } - /// Apply `adjustment` to the type of `expr` pub fn adjust_expr_ty(&self, expr: &ast::Expr, @@ -1919,16 +1925,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { infer::mk_subty(self.infcx(), a_is_expected, origin, sub, sup) } - pub fn can_mk_subty(&self, sub: Ty<'tcx>, sup: Ty<'tcx>) - -> Result<(), ty::type_err<'tcx>> { - infer::can_mk_subty(self.infcx(), sub, sup) - } - - pub fn can_mk_eqty(&self, sub: Ty<'tcx>, sup: Ty<'tcx>) - -> Result<(), ty::type_err<'tcx>> { - infer::can_mk_eqty(self.infcx(), sub, sup) - } - pub fn mk_assignty(&self, expr: &ast::Expr, sub: Ty<'tcx>, @@ -3260,7 +3256,7 @@ fn check_expr_with_unifier<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, Some(method) => { let method_ty = method.ty; // HACK(eddyb) Fully qualified path to work around a resolve bug. - let method_call = ::middle::typeck::MethodCall::expr(op_ex.id); + let method_call = ::middle::ty::MethodCall::expr(op_ex.id); fcx.inh.method_map.borrow_mut().insert(method_call, method); match check_method_argument_types(fcx, op_ex.span, @@ -4670,25 +4666,18 @@ fn check_block_with_expected<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, /// Checks a constant appearing in a type. At the moment this is just the /// length expression in a fixed-length vector, but someday it might be /// extended to type-level numeric literals. -pub fn check_const_in_type<'tcx>(tcx: &ty::ctxt<'tcx>, - expr: &ast::Expr, - expected_type: Ty<'tcx>) { - // Synthesize a crate context. The trait map is not needed here (though I - // imagine it will be if we have associated statics --pcwalton), so we - // leave it blank. - let ccx = CrateCtxt { - trait_map: NodeMap::new(), - tcx: tcx, - }; - let inh = static_inherited_fields(&ccx); - let fcx = blank_fn_ctxt(&ccx, &inh, ty::FnConverging(expected_type), expr.id); +fn check_const_in_type<'a,'tcx>(ccx: &'a CrateCtxt<'a,'tcx>, + expr: &ast::Expr, + expected_type: Ty<'tcx>) { + let inh = static_inherited_fields(ccx); + let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(expected_type), expr.id); check_const_with_ty(&fcx, expr.span, expr, expected_type); } -pub fn check_const(ccx: &CrateCtxt, - sp: Span, - e: &ast::Expr, - id: ast::NodeId) { +fn check_const(ccx: &CrateCtxt, + sp: Span, + e: &ast::Expr, + id: ast::NodeId) { let inh = static_inherited_fields(ccx); let rty = ty::node_id_to_type(ccx.tcx, id); let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(rty), e.id); @@ -4696,10 +4685,10 @@ pub fn check_const(ccx: &CrateCtxt, check_const_with_ty(&fcx, sp, e, declty); } -pub fn check_const_with_ty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, - _: Span, - e: &ast::Expr, - declty: Ty<'tcx>) { +fn check_const_with_ty<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, + _: Span, + e: &ast::Expr, + declty: Ty<'tcx>) { // Gather locals in statics (because of block expressions). // This is technically unnecessary because locals in static items are forbidden, // but prevents type checking from blowing up before const checking can properly diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs similarity index 98% rename from src/librustc/middle/typeck/check/regionck.rs rename to src/librustc_typeck/check/regionck.rs index 08f7f9cf5e37f..80ee2cce4ce70 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -114,20 +114,19 @@ //! then mean that all later passes would have to check for these figments //! and report an error, and it just seems like more mess in the end.) +use astconv::AstConv; +use check::FnCtxt; +use check::regionmanip; +use check::vtable; use middle::def; use middle::mem_categorization as mc; use middle::region::CodeExtent; use middle::traits; use middle::ty::{ReScope}; -use middle::ty::{mod, Ty}; -use middle::typeck::astconv::AstConv; -use middle::typeck::check::FnCtxt; -use middle::typeck::check::regionmanip; -use middle::typeck::check::vtable; -use middle::typeck::infer::resolve_and_force_all_but_regions; -use middle::typeck::infer::resolve_type; -use middle::typeck::infer; -use middle::typeck::MethodCall; +use middle::ty::{mod, Ty, MethodCall}; +use middle::infer::resolve_and_force_all_but_regions; +use middle::infer::resolve_type; +use middle::infer; use middle::pat_util; use util::nodemap::{DefIdMap, NodeMap, FnvHashMap}; use util::ppaux::{ty_to_string, Repr}; @@ -159,11 +158,11 @@ pub fn regionck_item(fcx: &FnCtxt, item: &ast::Item) { fcx.infcx().resolve_regions_and_report_errors(); } -pub fn regionck_fn(fcx: &FnCtxt, id: ast::NodeId, blk: &ast::Block) { +pub fn regionck_fn(fcx: &FnCtxt, id: ast::NodeId, decl: &ast::FnDecl, blk: &ast::Block) { let mut rcx = Rcx::new(fcx, blk.id); if fcx.err_count_since_creation() == 0 { // regionck assumes typeck succeeded - rcx.visit_fn_body(id, blk); + rcx.visit_fn_body(id, decl, blk); } // Region checking a fn can introduce new trait obligations, @@ -329,6 +328,7 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { fn visit_fn_body(&mut self, id: ast::NodeId, + fn_decl: &ast::FnDecl, body: &ast::Block) { // When we enter a function, we can derive @@ -344,6 +344,7 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { let len = self.region_param_pairs.len(); self.relate_free_regions(fn_sig.as_slice(), body.id); + link_fn_args(self, CodeExtent::from_node_id(body.id), fn_decl.inputs.as_slice()); self.visit_block(body); self.visit_region_obligations(body.id); self.region_param_pairs.truncate(len); @@ -481,9 +482,9 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> { // hierarchy, and in particular the relationships between free // regions, until regionck, as described in #3238. - fn visit_fn(&mut self, _fk: visit::FnKind<'v>, _fd: &'v ast::FnDecl, + fn visit_fn(&mut self, _fk: visit::FnKind<'v>, fd: &'v ast::FnDecl, b: &'v ast::Block, _s: Span, id: ast::NodeId) { - self.visit_fn_body(id, b) + self.visit_fn_body(id, fd, b) } fn visit_item(&mut self, i: &ast::Item) { visit_item(self, i); } @@ -1289,7 +1290,6 @@ fn link_local(rcx: &Rcx, local: &ast::Local) { /// then ensures that the lifetime of the resulting pointer is /// linked to the lifetime of its guarantor (if any). fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) { - debug!("regionck::for_match()"); let mc = mc::MemCategorizationContext::new(rcx); let discr_cmt = ignore_err!(mc.cat_expr(discr)); @@ -1301,12 +1301,32 @@ fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) { } } +/// Computes the guarantors for any ref bindings in a match and +/// then ensures that the lifetime of the resulting pointer is +/// linked to the lifetime of its guarantor (if any). +fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[ast::Arg]) { + debug!("regionck::link_fn_args(body_scope={})", body_scope); + let mc = mc::MemCategorizationContext::new(rcx); + for arg in args.iter() { + let arg_ty = rcx.fcx.node_ty(arg.id); + let re_scope = ty::ReScope(body_scope); + let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty); + debug!("arg_ty={} arg_cmt={}", + arg_ty.repr(rcx.tcx()), + arg_cmt.repr(rcx.tcx())); + link_pattern(rcx, mc, arg_cmt, &*arg.pat); + } +} + /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if /// needed. fn link_pattern<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, mc: mc::MemCategorizationContext>, discr_cmt: mc::cmt<'tcx>, root_pat: &ast::Pat) { + debug!("link_pattern(discr_cmt={}, root_pat={})", + discr_cmt.repr(rcx.tcx()), + root_pat.repr(rcx.tcx())); let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| { match sub_pat.node { // `ref x` pattern diff --git a/src/librustc/middle/typeck/check/regionmanip.rs b/src/librustc_typeck/check/regionmanip.rs similarity index 96% rename from src/librustc/middle/typeck/check/regionmanip.rs rename to src/librustc_typeck/check/regionmanip.rs index 55214618aa90b..92dfd8b5f56d2 100644 --- a/src/librustc/middle/typeck/check/regionmanip.rs +++ b/src/librustc_typeck/check/regionmanip.rs @@ -380,3 +380,22 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { } } } + +impl<'tcx> Repr<'tcx> for WfConstraint<'tcx> { + fn repr(&self, tcx: &ty::ctxt) -> String { + match *self { + RegionSubRegionConstraint(_, r_a, r_b) => { + format!("RegionSubRegionConstraint({}, {})", + r_a.repr(tcx), + r_b.repr(tcx)) + } + + RegionSubParamConstraint(_, r, p) => { + format!("RegionSubParamConstraint({}, {})", + r.repr(tcx), + p.repr(tcx)) + } + } + } +} + diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc_typeck/check/vtable.rs similarity index 99% rename from src/librustc/middle/typeck/check/vtable.rs rename to src/librustc_typeck/check/vtable.rs index 84cb74b4de248..c2b263885bd73 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc_typeck/check/vtable.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use check::{FnCtxt, structurally_resolved_type}; use middle::subst::{SelfSpace, FnSpace}; use middle::traits; use middle::traits::{SelectionError, OutputTypeParameterMismatch, Overflow, Unimplemented}; @@ -15,9 +16,7 @@ use middle::traits::{Obligation, obligation_for_builtin_bound}; use middle::traits::{FulfillmentError, CodeSelectionError, CodeAmbiguity}; use middle::traits::{ObligationCause}; use middle::ty::{mod, Ty}; -use middle::typeck::check::{FnCtxt, - structurally_resolved_type}; -use middle::typeck::infer; +use middle::infer; use std::rc::Rc; use syntax::ast; use syntax::codemap::Span; diff --git a/src/librustc/middle/typeck/check/wf.rs b/src/librustc_typeck/check/wf.rs similarity index 99% rename from src/librustc/middle/typeck/check/wf.rs rename to src/librustc_typeck/check/wf.rs index 8535ec4fa6e80..1769c588ec1de 100644 --- a/src/librustc/middle/typeck/check/wf.rs +++ b/src/librustc_typeck/check/wf.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use astconv::AstConv; +use check::{FnCtxt, Inherited, blank_fn_ctxt, vtable, regionck}; +use CrateCtxt; use middle::region; use middle::subst; use middle::subst::{Subst}; @@ -15,9 +18,6 @@ use middle::traits; use middle::ty::{mod, Ty}; use middle::ty::liberate_late_bound_regions; use middle::ty_fold::{TypeFolder, TypeFoldable}; -use middle::typeck::astconv::AstConv; -use middle::typeck::check::{FnCtxt, Inherited, blank_fn_ctxt, vtable, regionck}; -use middle::typeck::CrateCtxt; use util::ppaux::Repr; use std::collections::HashSet; diff --git a/src/librustc/middle/typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs similarity index 97% rename from src/librustc/middle/typeck/check/writeback.rs rename to src/librustc_typeck/check/writeback.rs index 23af30b44d935..777f354bec126 100644 --- a/src/librustc/middle/typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -13,18 +13,17 @@ // substitutions. use self::ResolveReason::*; +use astconv::AstConv; +use check::FnCtxt; use middle::def; use middle::pat_util; -use middle::ty::{mod, Ty}; +use middle::ty::{mod, Ty, MethodCall, MethodCallee}; use middle::ty_fold::{TypeFolder,TypeFoldable}; -use middle::typeck::astconv::AstConv; -use middle::typeck::check::FnCtxt; -use middle::typeck::infer::{force_all, resolve_all, resolve_region}; -use middle::typeck::infer::resolve_type; -use middle::typeck::infer; -use middle::typeck::{MethodCall, MethodCallee}; -use middle::typeck::write_substs_to_tcx; -use middle::typeck::write_ty_to_tcx; +use middle::infer::{force_all, resolve_all, resolve_region}; +use middle::infer::resolve_type; +use middle::infer; +use write_substs_to_tcx; +use write_ty_to_tcx; use util::ppaux::Repr; use std::cell::Cell; diff --git a/src/librustc/middle/typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs similarity index 94% rename from src/librustc/middle/typeck/coherence/mod.rs rename to src/librustc_typeck/coherence/mod.rs index 758608b79c2cb..b8642ddde4082 100644 --- a/src/librustc/middle/typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -19,7 +19,6 @@ use metadata::csearch::{each_impl, get_impl_trait}; use metadata::csearch; use middle::subst; -use middle::subst::{Substs}; use middle::ty::{ImplContainer, ImplOrTraitItemId, MethodTraitItemId}; use middle::ty::{TypeTraitItemId, lookup_item_type}; use middle::ty::{Ty, ty_bool, ty_char, ty_enum, ty_err}; @@ -31,10 +30,10 @@ use middle::ty::{ty_closure}; use middle::ty::type_is_ty_var; use middle::subst::Subst; use middle::ty; -use middle::typeck::CrateCtxt; -use middle::typeck::infer::combine::Combine; -use middle::typeck::infer::InferCtxt; -use middle::typeck::infer::{new_infer_ctxt, resolve_ivar, resolve_type}; +use CrateCtxt; +use middle::infer::combine::Combine; +use middle::infer::InferCtxt; +use middle::infer::{new_infer_ctxt, resolve_ivar, resolve_type}; use std::collections::{HashSet}; use std::cell::RefCell; use std::rc::Rc; @@ -477,27 +476,6 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { } } -/// Substitutes the values for the receiver's type parameters that are found in method, leaving the -/// method's type parameters intact. -pub fn make_substs_for_receiver_types<'tcx>(tcx: &ty::ctxt<'tcx>, - trait_ref: &ty::TraitRef<'tcx>, - method: &ty::Method<'tcx>) - -> subst::Substs<'tcx> -{ - let meth_tps: Vec = - method.generics.types.get_slice(subst::FnSpace) - .iter() - .map(|def| ty::mk_param_from_def(tcx, def)) - .collect(); - let meth_regions: Vec = - method.generics.regions.get_slice(subst::FnSpace) - .iter() - .map(|def| ty::ReEarlyBound(def.def_id.node, def.space, - def.index, def.name)) - .collect(); - trait_ref.substs.clone().with_method(meth_tps, meth_regions) -} - fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, impl_id: ast::DefId, impl_poly_type: &ty::Polytype<'tcx>, @@ -507,7 +485,7 @@ fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, provided_source: Option) -> ty::Method<'tcx> { - let combined_substs = make_substs_for_receiver_types(tcx, trait_ref, method); + let combined_substs = ty::make_substs_for_receiver_types(tcx, trait_ref, method); debug!("subst_receiver_types_in_method_ty: combined_substs={}", combined_substs.repr(tcx)); diff --git a/src/librustc/middle/typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs similarity index 100% rename from src/librustc/middle/typeck/coherence/orphan.rs rename to src/librustc_typeck/coherence/orphan.rs diff --git a/src/librustc/middle/typeck/coherence/overlap.rs b/src/librustc_typeck/coherence/overlap.rs similarity index 98% rename from src/librustc/middle/typeck/coherence/overlap.rs rename to src/librustc_typeck/coherence/overlap.rs index 9f10a58f45852..0e74d4578d95b 100644 --- a/src/librustc/middle/typeck/coherence/overlap.rs +++ b/src/librustc_typeck/coherence/overlap.rs @@ -13,8 +13,7 @@ use middle::traits; use middle::ty; -use middle::typeck::infer::{new_infer_ctxt}; -use middle::typeck::infer; +use middle::infer::{mod, new_infer_ctxt}; use syntax::ast::{DefId}; use syntax::ast::{LOCAL_CRATE}; use syntax::ast; diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc_typeck/collect.rs similarity index 99% rename from src/librustc/middle/typeck/collect.rs rename to src/librustc_typeck/collect.rs index 6e989dd73dbef..717e886029a3d 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -32,6 +32,9 @@ as `ty_param()` instances. use self::ConvertMethodContext::*; use self::CreateTypeParametersForAssociatedTypesFlag::*; +use astconv::{AstConv, ty_of_arg}; +use astconv::{ast_ty_to_ty, ast_region_to_region}; +use astconv; use metadata::csearch; use middle::def; use middle::lang_items::SizedTraitLangItem; @@ -43,13 +46,9 @@ use middle::ty::{ImplContainer, ImplOrTraitItemContainer, TraitContainer}; use middle::ty::{Polytype}; use middle::ty::{mod, Ty}; use middle::ty_fold::TypeFolder; -use middle::typeck::astconv::{AstConv, ty_of_arg}; -use middle::typeck::astconv::{ast_ty_to_ty, ast_region_to_region}; -use middle::typeck::astconv; -use middle::typeck::infer; -use middle::typeck::rscope::*; -use middle::typeck::{CrateCtxt, lookup_def_tcx, no_params, write_ty_to_tcx}; -use middle::typeck; +use middle::infer; +use rscope::*; +use {CrateCtxt, lookup_def_tcx, no_params, write_ty_to_tcx}; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux; use util::ppaux::{Repr,UserString}; @@ -2159,13 +2158,13 @@ fn check_method_self_type<'a, 'tcx, RS:RegionScope>( base_type.repr(crate_context.tcx), base_type_free.repr(crate_context.tcx)); let infcx = infer::new_infer_ctxt(crate_context.tcx); - drop(typeck::require_same_types(crate_context.tcx, - Some(&infcx), - false, - explicit_self.span, - base_type_free, - required_type_free, - || { + drop(::require_same_types(crate_context.tcx, + Some(&infcx), + false, + explicit_self.span, + base_type_free, + required_type_free, + || { format!("mismatched self type: expected `{}`", ppaux::ty_to_string(crate_context.tcx, required_type)) })); diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs new file mode 100644 index 0000000000000..36e81f18103b8 --- /dev/null +++ b/src/librustc_typeck/diagnostics.rs @@ -0,0 +1,151 @@ +// 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. + +#![allow(non_snake_case)] + +register_diagnostic!(E0001, r##" + This error suggests that the expression arm corresponding to the noted pattern + will never be reached as for all possible values of the expression being matched, + one of the preceeding patterns will match. + + This means that perhaps some of the preceeding patterns are too general, this + one is too specific or the ordering is incorrect. +"##) + +register_diagnostics!( + E0002, + E0003, + E0004, + E0005, + E0006, + E0007, + E0008, + E0009, + E0010, + E0011, + E0012, + E0013, + E0014, + E0015, + E0016, + E0017, + E0018, + E0019, + E0020, + E0022, + E0023, + E0024, + E0025, + E0026, + E0027, + E0029, + E0030, + E0031, + E0033, + E0034, + E0035, + E0036, + E0038, + E0040, + E0044, + E0045, + E0046, + E0049, + E0050, + E0051, + E0052, + E0053, + E0054, + E0055, + E0056, + E0057, + E0059, + E0060, + E0061, + E0062, + E0063, + E0066, + E0067, + E0068, + E0069, + E0070, + E0071, + E0072, + E0073, + E0074, + E0075, + E0076, + E0077, + E0079, + E0080, + E0081, + E0082, + E0083, + E0084, + E0085, + E0086, + E0087, + E0088, + E0089, + E0090, + E0091, + E0092, + E0093, + E0094, + E0100, + E0101, + E0102, + E0103, + E0104, + E0106, + E0107, + E0108, + E0109, + E0110, + E0116, + E0117, + E0118, + E0119, + E0120, + E0121, + E0122, + E0124, + E0127, + E0128, + E0129, + E0130, + E0131, + E0132, + E0133, + E0134, + E0135, + E0136, + E0137, + E0138, + E0139, + E0140, + E0141, + E0152, + E0153, + E0157, + E0158, + E0159, + E0161, + E0162, + E0163, + E0164, + E0165, + E0166, + E0167, + E0168, + E0169, + E0171, + E0172 +) diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc_typeck/lib.rs similarity index 60% rename from src/librustc/middle/typeck/mod.rs rename to src/librustc_typeck/lib.rs index 501dfcb2e2d9e..2f5b473567faa 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc_typeck/lib.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT +// 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. // @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/* +/*! typeck.rs, an introduction @@ -57,16 +57,40 @@ independently: all subtyping and assignment constraints are met. In essence, the check module specifies the constraints, and the infer module solves them. +# Note + +This API is completely unstable and subject to change. + */ +#![crate_name = "rustc_typeck"] +#![experimental] +#![crate_type = "dylib"] +#![crate_type = "rlib"] +#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "http://doc.rust-lang.org/nightly/")] + +#![feature(default_type_params, globs, if_let, import_shadowing, macro_rules, phase, quote)] +#![feature(slicing_syntax, tuple_indexing, unsafe_destructor)] +#![feature(rustc_diagnostic_macros)] #![allow(non_camel_case_types)] -pub use self::ExprAdjustment::*; -pub use self::vtable_origin::*; -pub use self::MethodOrigin::*; +#[phase(plugin, link)] extern crate log; +#[phase(plugin, link)] extern crate syntax; + +extern crate arena; +extern crate rustc; + +pub use rustc::lint; +pub use rustc::metadata; +pub use rustc::middle; +pub use rustc::session; +pub use rustc::util; use middle::def; use middle::resolve; +use middle::infer; use middle::subst; use middle::subst::VecPerParamSpace; use middle::ty::{mod, Ty}; @@ -74,222 +98,40 @@ use session::config; use util::common::time; use util::ppaux::Repr; use util::ppaux; -use util::nodemap::{NodeMap, FnvHashMap}; -use std::cell::RefCell; -use std::rc::Rc; use syntax::codemap::Span; use syntax::print::pprust::*; use syntax::{ast, ast_map, abi}; -pub mod check; -pub mod rscope; -pub mod astconv; -pub mod infer; -pub mod collect; -pub mod coherence; -pub mod variance; - -#[deriving(Clone, Encodable, Decodable, PartialEq, PartialOrd, Show)] -pub struct param_index { - pub space: subst::ParamSpace, - pub index: uint -} - -#[deriving(Clone, Show)] -pub enum MethodOrigin<'tcx> { - // fully statically resolved method - MethodStatic(ast::DefId), - - // fully statically resolved unboxed closure invocation - MethodStaticUnboxedClosure(ast::DefId), +#[cfg(stage0)] +mod diagnostics; - // method invoked on a type parameter with a bounded trait - MethodTypeParam(MethodParam<'tcx>), - - // method invoked on a trait instance - MethodTraitObject(MethodObject<'tcx>), - -} - -// details for a method invoked with a receiver whose type is a type parameter -// with a bounded trait. -#[deriving(Clone, Show)] -pub struct MethodParam<'tcx> { - // the precise trait reference that occurs as a bound -- this may - // be a supertrait of what the user actually typed. - pub trait_ref: Rc>, - - // index of uint in the list of methods for the trait - pub method_num: uint, -} - -// details for a method invoked with a receiver whose type is an object -#[deriving(Clone, Show)] -pub struct MethodObject<'tcx> { - // the (super)trait containing the method to be invoked - pub trait_ref: Rc>, - - // the actual base trait id of the object - pub object_trait_id: ast::DefId, - - // index of the method to be invoked amongst the trait's methods - pub method_num: uint, - - // index into the actual runtime vtable. - // the vtable is formed by concatenating together the method lists of - // the base object trait and all supertraits; this is the index into - // that vtable - pub real_index: uint, -} - -#[deriving(Clone)] -pub struct MethodCallee<'tcx> { - pub origin: MethodOrigin<'tcx>, - pub ty: Ty<'tcx>, - pub substs: subst::Substs<'tcx> -} - -/// With method calls, we store some extra information in -/// side tables (i.e method_map). We use -/// MethodCall as a key to index into these tables instead of -/// just directly using the expression's NodeId. The reason -/// for this being that we may apply adjustments (coercions) -/// with the resulting expression also needing to use the -/// side tables. The problem with this is that we don't -/// assign a separate NodeId to this new expression -/// and so it would clash with the base expression if both -/// needed to add to the side tables. Thus to disambiguate -/// we also keep track of whether there's an adjustment in -/// our key. -#[deriving(Clone, PartialEq, Eq, Hash, Show)] -pub struct MethodCall { - pub expr_id: ast::NodeId, - pub adjustment: ExprAdjustment -} - -#[deriving(Clone, PartialEq, Eq, Hash, Show, Encodable, Decodable)] -pub enum ExprAdjustment { - NoAdjustment, - AutoDeref(uint), - AutoObject -} +mod check; +mod rscope; +mod astconv; +mod collect; +mod coherence; +mod variance; -pub struct TypeAndSubsts<'tcx> { +struct TypeAndSubsts<'tcx> { pub substs: subst::Substs<'tcx>, pub ty: Ty<'tcx>, } -impl MethodCall { - pub fn expr(id: ast::NodeId) -> MethodCall { - MethodCall { - expr_id: id, - adjustment: NoAdjustment - } - } - - pub fn autoobject(id: ast::NodeId) -> MethodCall { - MethodCall { - expr_id: id, - adjustment: AutoObject - } - } - - pub fn autoderef(expr_id: ast::NodeId, autoderef: uint) -> MethodCall { - MethodCall { - expr_id: expr_id, - adjustment: AutoDeref(1 + autoderef) - } - } -} - -// maps from an expression id that corresponds to a method call to the details -// of the method to be invoked -pub type MethodMap<'tcx> = RefCell>>; - -pub type vtable_param_res<'tcx> = Vec>; - -// Resolutions for bounds of all parameters, left to right, for a given path. -pub type vtable_res<'tcx> = VecPerParamSpace>; - -#[deriving(Clone)] -pub enum vtable_origin<'tcx> { - /* - Statically known vtable. def_id gives the impl item - from whence comes the vtable, and tys are the type substs. - vtable_res is the vtable itself. - */ - vtable_static(ast::DefId, subst::Substs<'tcx>, vtable_res<'tcx>), - - /* - Dynamic vtable, comes from a parameter that has a bound on it: - fn foo(a: T) -- a's vtable would have a - vtable_param origin - - The first argument is the param index (identifying T in the example), - and the second is the bound number (identifying baz) - */ - vtable_param(param_index, uint), - - /* - Vtable automatically generated for an unboxed closure. The def ID is the - ID of the closure expression. - */ - vtable_unboxed_closure(ast::DefId), - - /* - Asked to determine the vtable for ty_err. This is the value used - for the vtables of `Self` in a virtual call like `foo.bar()` - where `foo` is of object type. The same value is also used when - type errors occur. - */ - vtable_error, -} - -impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> { - fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { - match *self { - vtable_static(def_id, ref tys, ref vtable_res) => { - format!("vtable_static({}:{}, {}, {})", - def_id, - ty::item_path_str(tcx, def_id), - tys.repr(tcx), - vtable_res.repr(tcx)) - } - - vtable_param(x, y) => { - format!("vtable_param({}, {})", x, y) - } - - vtable_unboxed_closure(def_id) => { - format!("vtable_unboxed_closure({})", def_id) - } - - vtable_error => { - format!("vtable_error") - } - } - } -} - -// For every explicit cast into an object type, maps from the cast -// expr to the associated trait ref. -pub type ObjectCastMap<'tcx> = RefCell>>>; - -pub struct CrateCtxt<'a, 'tcx: 'a> { +struct CrateCtxt<'a, 'tcx: 'a> { // A mapping from method call sites to traits that have that method. trait_map: resolve::TraitMap, tcx: &'a ty::ctxt<'tcx> } // Functions that write types into the node type table -pub fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) { +fn write_ty_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, ty: Ty<'tcx>) { debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_string(tcx, ty)); assert!(!ty::type_needs_infer(ty)); tcx.node_types.borrow_mut().insert(node_id, ty); } -pub fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, +fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, node_id: ast::NodeId, item_substs: ty::ItemSubsts<'tcx>) { if !item_substs.is_noop() { @@ -302,7 +144,7 @@ pub fn write_substs_to_tcx<'tcx>(tcx: &ty::ctxt<'tcx>, tcx.item_substs.borrow_mut().insert(node_id, item_substs); } } -pub fn lookup_def_tcx(tcx:&ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def { +fn lookup_def_tcx(tcx:&ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def { match tcx.def_map.borrow().get(&id) { Some(x) => x.clone(), _ => { @@ -311,12 +153,12 @@ pub fn lookup_def_tcx(tcx:&ty::ctxt, sp: Span, id: ast::NodeId) -> def::Def { } } -pub fn lookup_def_ccx(ccx: &CrateCtxt, sp: Span, id: ast::NodeId) +fn lookup_def_ccx(ccx: &CrateCtxt, sp: Span, id: ast::NodeId) -> def::Def { lookup_def_tcx(ccx.tcx, sp, id) } -pub fn no_params<'tcx>(t: Ty<'tcx>) -> ty::Polytype<'tcx> { +fn no_params<'tcx>(t: Ty<'tcx>) -> ty::Polytype<'tcx> { ty::Polytype { generics: ty::Generics {types: VecPerParamSpace::empty(), regions: VecPerParamSpace::empty()}, @@ -324,7 +166,7 @@ pub fn no_params<'tcx>(t: Ty<'tcx>) -> ty::Polytype<'tcx> { } } -pub fn require_same_types<'a, 'tcx>(tcx: &ty::ctxt<'tcx>, +fn require_same_types<'a, 'tcx>(tcx: &ty::ctxt<'tcx>, maybe_infcx: Option<&infer::InferCtxt<'a, 'tcx>>, t1_is_expected: bool, span: Span, diff --git a/src/librustc/middle/typeck/rscope.rs b/src/librustc_typeck/rscope.rs similarity index 100% rename from src/librustc/middle/typeck/rscope.rs rename to src/librustc_typeck/rscope.rs diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc_typeck/variance.rs similarity index 100% rename from src/librustc/middle/typeck/variance.rs rename to src/librustc_typeck/variance.rs diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 6f1ddaff3605f..7e02891160ad2 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -39,7 +39,6 @@ use syntax::parse::token; use syntax::ptr::P; use rustc_trans::back::link; -use rustc_trans::driver::driver; use rustc::metadata::cstore; use rustc::metadata::csearch; use rustc::metadata::decoder; @@ -48,6 +47,7 @@ use rustc::middle::subst; use rustc::middle::subst::VecPerParamSpace; use rustc::middle::ty; use rustc::middle::stability; +use rustc::session::config; use std::rc::Rc; use std::u32; @@ -131,7 +131,7 @@ impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b)); // Figure out the name of this crate - let input = driver::FileInput(cx.src.clone()); + let input = config::Input::File(cx.src.clone()); let name = link::find_crate_name(None, self.attrs.as_slice(), &input); // Clean the crate, translating the entire libsyntax AST to one that is diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index b040a4bfd2a09..4cd88bca51e93 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -9,7 +9,7 @@ // except according to those terms. pub use self::MaybeTyped::*; -use rustc_trans::driver::driver; +use rustc_driver::driver; use rustc::session::{mod, config}; use rustc::middle::{privacy, ty}; use rustc::lint; @@ -83,7 +83,7 @@ pub fn run_core(libs: Vec, cfgs: Vec, externs: Externs, // Parse, resolve, and typecheck the given crate. - let input = driver::FileInput(cpath.clone()); + let input = config::Input::File(cpath.clone()); let warning_lint = lint::builtin::WARNINGS.name_lower(); @@ -122,7 +122,7 @@ pub fn run_core(libs: Vec, cfgs: Vec, externs: Externs, let ast_map = driver::assign_node_ids_and_map(&sess, &mut forest); let type_arena = TypedArena::new(); - let driver::CrateAnalysis { + let ty::CrateAnalysis { exported_items, public_items, ty_cx, .. } = driver::phase_3_run_analysis_passes(sess, ast_map, &type_arena, name); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index c592474b057ff..1e7de50cf879d 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -21,6 +21,7 @@ extern crate getopts; extern crate libc; extern crate rustc; extern crate rustc_trans; +extern crate rustc_driver; extern crate serialize; extern crate syntax; extern crate "test" as testing; @@ -163,7 +164,7 @@ pub fn main_args(args: &[String]) -> int { usage(args[0].as_slice()); return 0; } else if matches.opt_present("version") { - match rustc_trans::driver::version("rustdoc", &matches) { + match rustc_driver::version("rustdoc", &matches) { Some(err) => { println!("{}", err); return 1 @@ -172,7 +173,7 @@ pub fn main_args(args: &[String]) -> int { } } - if matches.opt_strs("passes").as_slice() == &["list".to_string()] { + if matches.opt_strs("passes") == ["list"] { println!("Available passes for running rustdoc:"); for &(name, _, description) in PASSES.iter() { println!("{:>20} - {}", name, description); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 2a5972bb3d90b..7ca7ae4b21149 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -19,7 +19,7 @@ use std::string::String; use std::collections::{HashSet, HashMap}; use testing; use rustc::session::{mod, config}; -use rustc_trans::driver::driver; +use rustc_driver::driver; use syntax::ast; use syntax::codemap::{CodeMap, dummy_spanned}; use syntax::diagnostic; @@ -42,7 +42,7 @@ pub fn run(input: &str, crate_name: Option) -> int { let input_path = Path::new(input); - let input = driver::FileInput(input_path.clone()); + let input = config::Input::File(input_path.clone()); let sessopts = config::Options { maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()), @@ -110,7 +110,7 @@ fn runtest(test: &str, cratename: &str, libs: Vec, externs: core::Externs, // the test harness wants its own `main` & top level functions, so // never wrap the test in `fn main() { ... }` let test = maketest(test, Some(cratename), true, as_test_harness); - let input = driver::StrInput(test.to_string()); + let input = config::Input::Str(test.to_string()); let sessopts = config::Options { maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()), diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 403ca9d14321a..8fc3c23e88f15 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -19,7 +19,8 @@ use core::kinds::Sized; use fmt; use iter::IteratorExt; use mem; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use slice::{SlicePrelude, AsSlice}; use str::{Str, StrPrelude}; use string::{String, IntoString}; diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index d8023dd3e4e3b..8a90c06f0385c 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -149,9 +149,9 @@ macro_rules! bitflags { #[inline] pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> { if (bits & !$BitFlags::all().bits()) != 0 { - ::std::option::None + ::std::option::Option::None } else { - ::std::option::Some($BitFlags { bits: bits }) + ::std::option::Option::Some($BitFlags { bits: bits }) } } @@ -261,7 +261,7 @@ macro_rules! bitflags { #[allow(non_upper_case_globals)] mod tests { use hash; - use option::{Some, None}; + use option::Option::{Some, None}; use ops::{BitOr, BitAnd, BitXor, Sub, Not}; bitflags! { diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index 1f94d7b4fa611..f89876f7245e6 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -38,7 +38,8 @@ use kinds::Send; use mem; use ops::Drop; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use ptr::RawPtr; use ptr; use raw; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 50a00714ea06c..8f879bd50d0b3 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -23,10 +23,12 @@ use hash::{Hash, Hasher, RandomSipHasher}; use iter::{mod, Iterator, IteratorExt, FromIterator, Extend}; use kinds::Sized; use mem::{mod, replace}; -use num::UnsignedInt; +use num::{Int, UnsignedInt}; use ops::{Deref, Index, IndexMut}; -use option::{Some, None, Option}; -use result::{Result, Ok, Err}; +use option::Option; +use option::Option::{Some, None}; +use result::Result; +use result::Result::{Ok, Err}; use super::table; use super::table::{ @@ -41,45 +43,53 @@ use super::table::{ SafeHash }; -// FIXME(conventions): update capacity management to match other collections (no auto-shrink) - const INITIAL_LOG2_CAP: uint = 5; pub const INITIAL_CAPACITY: uint = 1 << INITIAL_LOG2_CAP; // 2^5 /// The default behavior of HashMap implements a load factor of 90.9%. -/// This behavior is characterized by the following conditions: +/// This behavior is characterized by the following condition: /// -/// - if size > 0.909 * capacity: grow -/// - if size < 0.25 * capacity: shrink (if this won't bring capacity lower -/// than the minimum) +/// - if size > 0.909 * capacity: grow the map #[deriving(Clone)] -struct DefaultResizePolicy { - /// Doubled minimal capacity. The capacity must never drop below - /// the minimum capacity. (The check happens before the capacity - /// is potentially halved.) - minimum_capacity2: uint -} +struct DefaultResizePolicy; impl DefaultResizePolicy { - fn new(new_capacity: uint) -> DefaultResizePolicy { - DefaultResizePolicy { - minimum_capacity2: new_capacity << 1 - } + fn new() -> DefaultResizePolicy { + DefaultResizePolicy } #[inline] - fn capacity_range(&self, new_size: uint) -> (uint, uint) { - // Here, we are rephrasing the logic by specifying the ranges: + fn min_capacity(&self, usable_size: uint) -> uint { + // Here, we are rephrasing the logic by specifying the lower limit + // on capacity: // - // - if `size * 1.1 < cap < size * 4`: don't resize - // - if `cap < minimum_capacity * 2`: don't shrink - // - otherwise, resize accordingly - ((new_size * 11) / 10, max(new_size << 2, self.minimum_capacity2)) + // - if `cap < size * 1.1`: grow the map + usable_size * 11 / 10 } + /// An inverse of `min_capacity`, approximately. #[inline] - fn reserve(&mut self, new_capacity: uint) { - self.minimum_capacity2 = new_capacity << 1; + fn usable_capacity(&self, cap: uint) -> uint { + // As the number of entries approaches usable capacity, + // min_capacity(size) must be smaller than the internal capacity, + // so that the map is not resized: + // `min_capacity(usable_capacity(x)) <= x`. + // The lef-hand side can only be smaller due to flooring by integer + // division. + // + // This doesn't have to be checked for overflow since allocation size + // in bytes will overflow earlier than multiplication by 10. + cap * 10 / 11 + } +} + +#[test] +fn test_resize_policy() { + use prelude::*; + let rp = DefaultResizePolicy; + for n in range(0u, 1000) { + assert!(rp.min_capacity(rp.usable_capacity(n)) <= n); + assert!(rp.usable_capacity(rp.min_capacity(n)) <= n); } } @@ -282,7 +292,6 @@ pub struct HashMap { table: RawTable, - // We keep this at the end since it might as well have tail padding. resize_policy: DefaultResizePolicy, } @@ -425,12 +434,14 @@ impl, V, S, H: Hasher> HashMap { table::make_hash(&self.hasher, x) } + #[allow(deprecated)] fn search_equiv<'a, Sized? Q: Hash + Equiv>(&'a self, q: &Q) -> Option> { let hash = self.make_hash(q); search_hashed(&self.table, &hash, |k| q.equiv(k)).into_option() } + #[allow(deprecated)] fn search_equiv_mut<'a, Sized? Q: Hash + Equiv>(&'a mut self, q: &Q) -> Option> { let hash = self.make_hash(q); @@ -529,7 +540,7 @@ impl, V, S, H: Hasher> HashMap { pub fn with_hasher(hasher: H) -> HashMap { HashMap { hasher: hasher, - resize_policy: DefaultResizePolicy::new(INITIAL_CAPACITY), + resize_policy: DefaultResizePolicy::new(), table: RawTable::new(0), } } @@ -554,20 +565,39 @@ impl, V, S, H: Hasher> HashMap { /// ``` #[inline] pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap { - let cap = max(INITIAL_CAPACITY, capacity).next_power_of_two(); + let resize_policy = DefaultResizePolicy::new(); + let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity)); + let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow"); + assert!(internal_cap >= capacity, "capacity overflow"); HashMap { hasher: hasher, - resize_policy: DefaultResizePolicy::new(cap), - table: RawTable::new(cap), + resize_policy: resize_policy, + table: RawTable::new(internal_cap), } } - /// The hashtable will never try to shrink below this size. You can use - /// this function to reduce reallocations if your hashtable frequently - /// grows and shrinks by large amounts. + /// Returns the number of elements the map can hold without reallocating. + /// + /// # Example + /// + /// ``` + /// use std::collections::HashMap; + /// let map: HashMap = HashMap::with_capacity(100); + /// assert!(map.capacity() >= 100); + /// ``` + #[inline] + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn capacity(&self) -> uint { + self.resize_policy.usable_capacity(self.table.capacity()) + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `HashMap`. The collection may reserve more space to avoid + /// frequent reallocations. /// - /// This function has no effect on the operational semantics of the - /// hashtable, only on performance. + /// # Panics + /// + /// Panics if the new allocation size overflows `uint`. /// /// # Example /// @@ -576,13 +606,18 @@ impl, V, S, H: Hasher> HashMap { /// let mut map: HashMap<&str, int> = HashMap::new(); /// map.reserve(10); /// ``` - pub fn reserve(&mut self, new_minimum_capacity: uint) { - let cap = max(INITIAL_CAPACITY, new_minimum_capacity).next_power_of_two(); + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn reserve(&mut self, additional: uint) { + let new_size = self.len().checked_add(additional).expect("capacity overflow"); + let min_cap = self.resize_policy.min_capacity(new_size); - self.resize_policy.reserve(cap); + // An invalid value shouldn't make us run out of space. This includes + // an overflow check. + assert!(new_size <= min_cap); - if self.table.capacity() < cap { - self.resize(cap); + if self.table.capacity() < min_cap { + let new_capacity = max(min_cap.next_power_of_two(), INITIAL_CAPACITY); + self.resize(new_capacity); } } @@ -601,94 +636,106 @@ impl, V, S, H: Hasher> HashMap { return; } - if new_capacity < old_table.capacity() { - // Shrink the table. Naive algorithm for resizing: - for (h, k, v) in old_table.into_iter() { - self.insert_hashed_nocheck(h, k, v); - } - } else { - // Grow the table. - // Specialization of the other branch. - let mut bucket = Bucket::first(&mut old_table); - - // "So a few of the first shall be last: for many be called, - // but few chosen." - // - // We'll most likely encounter a few buckets at the beginning that - // have their initial buckets near the end of the table. They were - // placed at the beginning as the probe wrapped around the table - // during insertion. We must skip forward to a bucket that won't - // get reinserted too early and won't unfairly steal others spot. - // This eliminates the need for robin hood. - loop { - bucket = match bucket.peek() { - Full(full) => { - if full.distance() == 0 { - // This bucket occupies its ideal spot. - // It indicates the start of another "cluster". - bucket = full.into_bucket(); - break; - } - // Leaving this bucket in the last cluster for later. - full.into_bucket() - } - Empty(b) => { - // Encountered a hole between clusters. - b.into_bucket() - } - }; - bucket.next(); - } + // Grow the table. + // Specialization of the other branch. + let mut bucket = Bucket::first(&mut old_table); - // This is how the buckets might be laid out in memory: - // ($ marks an initialized bucket) - // ________________ - // |$$$_$$$$$$_$$$$$| - // - // But we've skipped the entire initial cluster of buckets - // and will continue iteration in this order: - // ________________ - // |$$$$$$_$$$$$ - // ^ wrap around once end is reached - // ________________ - // $$$_____________| - // ^ exit once table.size == 0 - loop { - bucket = match bucket.peek() { - Full(bucket) => { - let h = bucket.hash(); - let (b, k, v) = bucket.take(); - self.insert_hashed_ordered(h, k, v); - { - let t = b.table(); // FIXME "lifetime too short". - if t.size() == 0 { break } - }; - b.into_bucket() + // "So a few of the first shall be last: for many be called, + // but few chosen." + // + // We'll most likely encounter a few buckets at the beginning that + // have their initial buckets near the end of the table. They were + // placed at the beginning as the probe wrapped around the table + // during insertion. We must skip forward to a bucket that won't + // get reinserted too early and won't unfairly steal others spot. + // This eliminates the need for robin hood. + loop { + bucket = match bucket.peek() { + Full(full) => { + if full.distance() == 0 { + // This bucket occupies its ideal spot. + // It indicates the start of another "cluster". + bucket = full.into_bucket(); + break; } - Empty(b) => b.into_bucket() - }; - bucket.next(); - } + // Leaving this bucket in the last cluster for later. + full.into_bucket() + } + Empty(b) => { + // Encountered a hole between clusters. + b.into_bucket() + } + }; + bucket.next(); + } + + // This is how the buckets might be laid out in memory: + // ($ marks an initialized bucket) + // ________________ + // |$$$_$$$$$$_$$$$$| + // + // But we've skipped the entire initial cluster of buckets + // and will continue iteration in this order: + // ________________ + // |$$$$$$_$$$$$ + // ^ wrap around once end is reached + // ________________ + // $$$_____________| + // ^ exit once table.size == 0 + loop { + bucket = match bucket.peek() { + Full(bucket) => { + let h = bucket.hash(); + let (b, k, v) = bucket.take(); + self.insert_hashed_ordered(h, k, v); + { + let t = b.table(); // FIXME "lifetime too short". + if t.size() == 0 { break } + }; + b.into_bucket() + } + Empty(b) => b.into_bucket() + }; + bucket.next(); } assert_eq!(self.table.size(), old_size); } - /// Performs any necessary resize operations, such that there's space for - /// new_size elements. - fn make_some_room(&mut self, new_size: uint) { - let (grow_at, shrink_at) = self.resize_policy.capacity_range(new_size); - let cap = self.table.capacity(); + /// Shrinks the capacity of the map as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// # Example + /// + /// ``` + /// use std::collections::HashMap; + /// + /// let mut map: HashMap = HashMap::with_capacity(100); + /// map.insert(1, 2); + /// map.insert(3, 4); + /// assert!(map.capacity() >= 100); + /// map.shrink_to_fit(); + /// assert!(map.capacity() >= 2); + /// ``` + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn shrink_to_fit(&mut self) { + let min_capacity = self.resize_policy.min_capacity(self.len()); + let min_capacity = max(min_capacity.next_power_of_two(), INITIAL_CAPACITY); // An invalid value shouldn't make us run out of space. - debug_assert!(grow_at >= new_size); + debug_assert!(self.len() <= min_capacity); - if cap <= grow_at { - let new_capacity = max(cap << 1, INITIAL_CAPACITY); - self.resize(new_capacity); - } else if shrink_at <= cap { - let new_capacity = cap >> 1; - self.resize(new_capacity); + if self.table.capacity() != min_capacity { + let old_table = replace(&mut self.table, RawTable::new(min_capacity)); + let old_size = old_table.size(); + + // Shrink the table. Naive algorithm for resizing: + for (h, k, v) in old_table.into_iter() { + self.insert_hashed_nocheck(h, k, v); + } + + debug_assert_eq!(self.table.size(), old_size); } } @@ -775,8 +822,7 @@ impl, V, S, H: Hasher> HashMap { return None } - let potential_new_size = self.table.size() - 1; - self.make_some_room(potential_new_size); + self.reserve(1); match self.search_equiv_mut(k) { Some(bucket) => { @@ -907,12 +953,8 @@ impl, V, S, H: Hasher> HashMap { /// Gets the given key's corresponding entry in the map for in-place manipulation pub fn entry<'a>(&'a mut self, key: K) -> Entry<'a, K, V> { - // Gotta resize now, and we don't know which direction, so try both? - let size = self.table.size(); - self.make_some_room(size + 1); - if size > 0 { - self.make_some_room(size - 1); - } + // Gotta resize now. + self.reserve(1); let hash = self.make_hash(&key); search_entry_hashed(&mut self.table, hash, key) @@ -964,10 +1006,6 @@ impl, V, S, H: Hasher> HashMap { /// ``` #[unstable = "matches collection reform specification, waiting for dust to settle"] pub fn clear(&mut self) { - // Prevent reallocations from happening from now on. Makes it possible - // for the map to be reused but has a downside: reserves permanently. - self.resize_policy.reserve(self.table.size()); - let cap = self.table.capacity(); let mut buckets = Bucket::first(&mut self.table); @@ -1100,8 +1138,7 @@ impl, V, S, H: Hasher> HashMap { #[unstable = "matches collection reform specification, waiting for dust to settle"] pub fn insert(&mut self, k: K, v: V) -> Option { let hash = self.make_hash(&k); - let potential_new_size = self.table.size() + 1; - self.make_some_room(potential_new_size); + self.reserve(1); let mut retval = None; self.insert_or_replace_with(hash, k, v, |_, val_ref, val| { @@ -1141,9 +1178,6 @@ impl, V, S, H: Hasher> HashMap { return None } - let potential_new_size = self.table.size() - 1; - self.make_some_room(potential_new_size); - self.search_mut(k).map(|bucket| { let (_k, val) = pop_internal(bucket); val @@ -1894,7 +1928,7 @@ mod test_map { } #[test] - fn test_resize_policy() { + fn test_behavior_resize_policy() { let mut m = HashMap::new(); assert_eq!(m.len(), 0); @@ -1905,7 +1939,7 @@ mod test_map { m.remove(&0); assert!(m.is_empty()); let initial_cap = m.table.capacity(); - m.reserve(initial_cap * 2); + m.reserve(initial_cap); let cap = m.table.capacity(); assert_eq!(cap, initial_cap * 2); @@ -1935,15 +1969,55 @@ mod test_map { assert_eq!(m.table.capacity(), new_cap); } // A little more than one quarter full. - // Shrinking starts as we remove more elements: + m.shrink_to_fit(); + assert_eq!(m.table.capacity(), cap); + // again, a little more than half full for _ in range(0, cap / 2 - 1) { i -= 1; m.remove(&i); } + m.shrink_to_fit(); assert_eq!(m.len(), i); assert!(!m.is_empty()); - assert_eq!(m.table.capacity(), cap); + assert_eq!(m.table.capacity(), initial_cap); + } + + #[test] + fn test_reserve_shrink_to_fit() { + let mut m = HashMap::new(); + m.insert(0u, 0u); + m.remove(&0); + assert!(m.capacity() >= m.len()); + for i in range(0, 128) { + m.insert(i, i); + } + m.reserve(256); + + let usable_cap = m.capacity(); + for i in range(128, 128+256) { + m.insert(i, i); + assert_eq!(m.capacity(), usable_cap); + } + + for i in range(100, 128+256) { + assert_eq!(m.remove(&i), Some(i)); + } + m.shrink_to_fit(); + + assert_eq!(m.len(), 100); + assert!(!m.is_empty()); + assert!(m.capacity() >= m.len()); + + for i in range(0, 100) { + assert_eq!(m.remove(&i), Some(i)); + } + m.shrink_to_fit(); + m.insert(0, 0); + + assert_eq!(m.len(), 1); + assert!(m.capacity() >= m.len()); + assert_eq!(m.remove(&0), Some(0)); } #[test] diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index f6d526cca395d..fd32d207e79e0 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -19,13 +19,12 @@ use fmt; use hash::{Hash, Hasher, RandomSipHasher}; use iter::{Iterator, IteratorExt, FromIterator, FilterMap, Chain, Repeat, Zip, Extend, repeat}; use iter; -use option::{Some, None}; -use result::{Ok, Err}; +use option::Option::{Some, None}; +use result::Result::{Ok, Err}; use super::map::{HashMap, Entries, MoveEntries, INITIAL_CAPACITY}; // FIXME(conventions): implement BitOr, BitAnd, BitXor, and Sub -// FIXME(conventions): update capacity management to match other collections (no auto-shrink) // Future Optimization (FIXME!) @@ -172,7 +171,28 @@ impl, S, H: Hasher> HashSet { HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) } } - /// Reserve space for at least `n` elements in the hash table. + /// Returns the number of elements the set can hold without reallocating. + /// + /// # Example + /// + /// ``` + /// use std::collections::HashSet; + /// let set: HashSet = HashSet::with_capacity(100); + /// assert!(set.capacity() >= 100); + /// ``` + #[inline] + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn capacity(&self) -> uint { + self.map.capacity() + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the `HashSet`. The collection may reserve more space to avoid + /// frequent reallocations. + /// + /// # Panics + /// + /// Panics if the new allocation size overflows `uint`. /// /// # Example /// @@ -181,8 +201,30 @@ impl, S, H: Hasher> HashSet { /// let mut set: HashSet = HashSet::new(); /// set.reserve(10); /// ``` - pub fn reserve(&mut self, n: uint) { - self.map.reserve(n) + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn reserve(&mut self, additional: uint) { + self.map.reserve(additional) + } + + /// Shrinks the capacity of the set as much as possible. It will drop + /// down as much as possible while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// # Example + /// + /// ``` + /// use std::collections::HashSet; + /// + /// let mut set: HashSet = HashSet::with_capacity(100); + /// set.insert(1); + /// set.insert(2); + /// assert!(set.capacity() >= 100); + /// set.shrink_to_fit(); + /// assert!(set.capacity() >= 2); + /// ``` + #[unstable = "matches collection reform specification, waiting for dust to settle"] + pub fn shrink_to_fit(&mut self) { + self.map.shrink_to_fit() } /// Deprecated: use `contains` and `BorrowFrom`. diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index f41ccea0aaf03..de06a1e0bbd6e 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -21,7 +21,8 @@ use mem::{min_align_of, size_of}; use mem; use num::{Int, UnsignedInt}; use ops::{Deref, DerefMut, Drop}; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; use ptr::{RawPtr, copy_nonoverlapping_memory, zero_memory}; use ptr; use rt::heap::{allocate, deallocate}; diff --git a/src/libstd/collections/lru_cache.rs b/src/libstd/collections/lru_cache.rs index 94bea37d18728..adbc135364be7 100644 --- a/src/libstd/collections/lru_cache.rs +++ b/src/libstd/collections/lru_cache.rs @@ -44,10 +44,11 @@ use hash::Hash; use iter::{range, Iterator, Extend}; use mem; use ops::Drop; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; use boxed::Box; use ptr; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; // FIXME(conventions): implement iterators? // FIXME(conventions): implement indexing? diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index 3cd0c0eeaf290..b40990addddfb 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -280,7 +280,8 @@ pub mod dl { use libc; use os; use ptr; - use result::{Ok, Err, Result}; + use result::Result; + use result::Result::{Ok, Err}; use slice::SlicePrelude; use str::StrPrelude; use str; diff --git a/src/libstd/error.rs b/src/libstd/error.rs index 82ad893f88a1a..9ad2655f6e9db 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -78,7 +78,8 @@ //! } //! ``` -use option::{Option, None}; +use option::Option; +use option::Option::None; use kinds::Send; use string::String; diff --git a/src/libstd/failure.rs b/src/libstd/failure.rs index d839c1484e562..58a41f4d7d5a1 100644 --- a/src/libstd/failure.rs +++ b/src/libstd/failure.rs @@ -16,8 +16,9 @@ use cell::RefCell; use fmt; use io::{Writer, IoResult}; use kinds::Send; -use option::{Some, None, Option}; -use result::Ok; +use option::Option; +use option::Option::{Some, None}; +use result::Result::Ok; use rt::backtrace; use rustrt::{Stderr, Stdio}; use rustrt::local::Local; diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 7e1bfd704a927..6a2047d1cef30 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -406,7 +406,7 @@ use io::Writer; use io; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use string; use vec::Vec; diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index e92bad592d126..0b2c6843c968e 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -16,8 +16,9 @@ use cmp; use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; use iter::ExactSizeIterator; use ops::Drop; -use option::{Some, None, Option}; -use result::{Ok, Err}; +use option::Option; +use option::Option::{Some, None}; +use result::Result::{Ok, Err}; use slice::{SlicePrelude}; use slice; use vec::Vec; @@ -406,7 +407,7 @@ mod test { use prelude::*; use super::*; use super::super::{IoResult, EndOfFile}; - use super::super::mem::{MemReader, BufReader}; + use super::super::mem::MemReader; use self::test::Bencher; use str::StrPrelude; @@ -626,14 +627,14 @@ mod test { #[test] fn read_char_buffered() { let buf = [195u8, 159u8]; - let mut reader = BufferedReader::with_capacity(1, BufReader::new(&buf)); + let mut reader = BufferedReader::with_capacity(1, buf[]); assert_eq!(reader.read_char(), Ok('ß')); } #[test] fn test_chars() { let buf = [195u8, 159u8, b'a']; - let mut reader = BufferedReader::with_capacity(1, BufReader::new(&buf)); + let mut reader = BufferedReader::with_capacity(1, buf[]); let mut it = reader.chars(); assert_eq!(it.next(), Some(Ok('ß'))); assert_eq!(it.next(), Some(Ok('a'))); diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index a90b6bbbb8e8e..3de0a7be95e8b 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -12,8 +12,8 @@ use clone::Clone; use cmp; use comm::{Sender, Receiver}; use io; -use option::{None, Some}; -use result::{Ok, Err}; +use option::Option::{None, Some}; +use result::Result::{Ok, Err}; use slice::{bytes, CloneSliceAllocPrelude, SlicePrelude}; use super::{Buffer, Reader, Writer, IoResult}; use vec::Vec; diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index 4b2ffb4d559c4..1bdf99f6d6dce 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -19,9 +19,10 @@ use io::{IoError, IoResult, Reader}; use io; use iter::Iterator; use num::Int; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use ptr::RawPtr; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use slice::{SlicePrelude, AsSlice}; /// An iterator that reads a single byte on each iteration, diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index bd334f52628fe..838ca981765c8 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -53,15 +53,17 @@ use clone::Clone; use io::standard_error; use io::{FilePermission, Write, Open, FileAccess, FileMode, FileType}; -use io::{IoResult, IoError, FileStat, SeekStyle, Seek, Writer, Reader}; +use io::{IoResult, IoError, InvalidInput}; +use io::{FileStat, SeekStyle, Seek, Writer, Reader}; use io::{Read, Truncate, ReadWrite, Append}; use io::UpdateIoError; use io; use iter::{Iterator, Extend}; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; use path::{Path, GenericPath}; use path; -use result::{Err, Ok}; +use result::Result::{Err, Ok}; use slice::SlicePrelude; use string::String; use vec::Vec; @@ -134,13 +136,26 @@ impl File { pub fn open_mode(path: &Path, mode: FileMode, access: FileAccess) -> IoResult { - fs_imp::open(path, mode, access).map(|fd| { - File { - path: path.clone(), - fd: fd, - last_nread: -1 + fs_imp::open(path, mode, access).and_then(|fd| { + // On *BSD systems, we can open a directory as a file and read from it: + // fd=open("/tmp", O_RDONLY); read(fd, buf, N); + // due to an old tradition before the introduction of opendir(3). + // We explicitly reject it because there are few use cases. + if cfg!(not(any(windows, target_os = "linux", target_os = "android"))) && + try!(fd.fstat()).kind == FileType::Directory { + Err(IoError { + kind: InvalidInput, + desc: "is a directory", + detail: None + }) + } else { + Ok(File { + path: path.clone(), + fd: fd, + last_nread: -1 + }) } - }).update_err("couldn't open file", |e| { + }).update_err("couldn't open path as file", |e| { format!("{}; path={}; mode={}; access={}", e, path.display(), mode_string(mode), access_string(access)) }) @@ -237,7 +252,7 @@ impl File { } /// Queries information about the underlying file. - pub fn stat(&mut self) -> IoResult { + pub fn stat(&self) -> IoResult { self.fd.fstat() .update_err("couldn't fstat file", |e| format!("{}; path={}", e, self.path.display())) @@ -1528,7 +1543,7 @@ mod test { check!(File::create(&tmpdir.join("test")).write(&bytes)); let actual = check!(File::open(&tmpdir.join("test")).read_to_end()); - assert!(actual.as_slice() == &bytes); + assert!(actual == bytes.as_slice()); } #[test] diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index f27951f263da2..39ddbab0bd58d 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -15,8 +15,8 @@ #![allow(deprecated)] use cmp::min; -use option::None; -use result::{Err, Ok}; +use option::Option::None; +use result::Result::{Err, Ok}; use io; use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult}; use slice::{mod, AsSlice, SlicePrelude}; @@ -206,6 +206,41 @@ impl Buffer for MemReader { fn consume(&mut self, amt: uint) { self.pos += amt; } } +impl<'a> Reader for &'a [u8] { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> IoResult { + if self.is_empty() { return Err(io::standard_error(io::EndOfFile)); } + + let write_len = min(buf.len(), self.len()); + { + let input = self[..write_len]; + let output = buf[mut ..write_len]; + slice::bytes::copy_memory(output, input); + } + + *self = self.slice_from(write_len); + + Ok(write_len) + } +} + +impl<'a> Buffer for &'a [u8] { + #[inline] + fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { + if self.is_empty() { + Err(io::standard_error(io::EndOfFile)) + } else { + Ok(*self) + } + } + + #[inline] + fn consume(&mut self, amt: uint) { + *self = self[amt..]; + } +} + + /// Writes to a fixed-size byte slice /// /// If a write will not fit in the buffer, it returns an error and does not @@ -280,10 +315,10 @@ impl<'a> Seek for BufWriter<'a> { /// # #![allow(unused_must_use)] /// use std::io::BufReader; /// -/// let mut buf = [0, 1, 2, 3]; -/// let mut r = BufReader::new(&mut buf); +/// let buf = [0, 1, 2, 3]; +/// let mut r = BufReader::new(&buf); /// -/// assert_eq!(r.read_to_end().unwrap(), vec!(0, 1, 2, 3)); +/// assert_eq!(r.read_to_end().unwrap(), vec![0, 1, 2, 3]); /// ``` pub struct BufReader<'a> { buf: &'a [u8], @@ -362,6 +397,16 @@ mod test { use self::test::Bencher; use str::StrPrelude; + #[test] + fn test_vec_writer() { + let mut writer = Vec::new(); + writer.write(&[0]).unwrap(); + writer.write(&[1, 2, 3]).unwrap(); + writer.write(&[4, 5, 6, 7]).unwrap(); + let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; + assert_eq!(writer.as_slice(), b); + } + #[test] fn test_mem_writer() { let mut writer = MemWriter::new(); @@ -385,6 +430,8 @@ mod test { assert_eq!(writer.tell(), Ok(8)); writer.write(&[]).unwrap(); assert_eq!(writer.tell(), Ok(8)); + + assert!(writer.write(&[1]).is_err()); } let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(buf.as_slice(), b); @@ -457,6 +504,32 @@ mod test { assert!(reader.read(&mut buf).is_err()); } + #[test] + fn test_slice_reader() { + let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7]; + let mut reader = &mut in_buf.as_slice(); + let mut buf = []; + assert_eq!(reader.read(&mut buf), Ok(0)); + let mut buf = [0]; + assert_eq!(reader.read(&mut buf), Ok(1)); + assert_eq!(reader.len(), 7); + let b: &[_] = &[0]; + assert_eq!(buf.as_slice(), b); + let mut buf = [0, ..4]; + assert_eq!(reader.read(&mut buf), Ok(4)); + assert_eq!(reader.len(), 3); + let b: &[_] = &[1, 2, 3, 4]; + assert_eq!(buf.as_slice(), b); + assert_eq!(reader.read(&mut buf), Ok(3)); + let b: &[_] = &[5, 6, 7]; + assert_eq!(buf[0..3], b); + assert!(reader.read(&mut buf).is_err()); + let mut reader = &mut in_buf.as_slice(); + assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); + assert_eq!(reader.read_until(3).unwrap(), vec!(4, 5, 6, 7)); + assert!(reader.read(&mut buf).is_err()); + } + #[test] fn test_buf_reader() { let in_buf = vec![0, 1, 2, 3, 4, 5, 6, 7]; diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 5ed10eab15b80..9d5aa648cb003 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -233,10 +233,12 @@ use int; use iter::{Iterator, IteratorExt}; use mem::transmute; use ops::{BitOr, BitXor, BitAnd, Sub, Not}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use os; use boxed::Box; -use result::{Ok, Err, Result}; +use result::Result; +use result::Result::{Ok, Err}; use sys; use slice::{AsSlice, SlicePrelude}; use str::{Str, StrPrelude}; diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/io/net/addrinfo.rs index 7de7869213091..fea8372733c29 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/io/net/addrinfo.rs @@ -22,7 +22,8 @@ pub use self::Protocol::*; use iter::IteratorExt; use io::{IoResult}; use io::net::ip::{SocketAddr, IpAddr}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use sys; use vec::Vec; diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index 4812e911cc481..9c0fbbe274b3e 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -21,8 +21,9 @@ use fmt; use io::{mod, IoResult, IoError}; use io::net; use iter::{Iterator, IteratorExt}; -use option::{Option, None, Some}; -use result::{Ok, Err}; +use option::Option; +use option::Option::{None, Some}; +use result::Result::{Ok, Err}; use str::{FromStr, StrPrelude}; use slice::{CloneSlicePrelude, SlicePrelude}; use vec::Vec; diff --git a/src/libstd/io/net/mod.rs b/src/libstd/io/net/mod.rs index 5b1747876d7e0..09e5639bea944 100644 --- a/src/libstd/io/net/mod.rs +++ b/src/libstd/io/net/mod.rs @@ -11,8 +11,8 @@ //! Networking I/O use io::{IoError, IoResult, InvalidInput}; -use option::None; -use result::{Ok, Err}; +use option::Option::None; +use result::Result::{Ok, Err}; use self::ip::{SocketAddr, ToSocketAddr}; pub use self::addrinfo::get_host_addresses; diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index aa2234175917c..a7b1b077eff0b 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -19,11 +19,12 @@ use clone::Clone; use io::IoResult; -use result::Err; +use result::Result::Err; use io::net::ip::{SocketAddr, ToSocketAddr}; use io::{Reader, Writer, Listener, Acceptor}; use io::{standard_error, TimedOut}; -use option::{None, Some, Option}; +use option::Option; +use option::Option::{None, Some}; use time::Duration; use sys::tcp::TcpStream as TcpStreamImp; diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index a7239ca0f2f98..a2ad365dd2a0e 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -19,7 +19,7 @@ use clone::Clone; use io::net::ip::{SocketAddr, IpAddr, ToSocketAddr}; use io::{Reader, Writer, IoResult}; use option::Option; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use sys::udp::UdpSocket as UdpSocketImp; use sys_common; diff --git a/src/libstd/io/result.rs b/src/libstd/io/result.rs index 305bcf9ecbc9c..32965d23971ed 100644 --- a/src/libstd/io/result.rs +++ b/src/libstd/io/result.rs @@ -15,7 +15,7 @@ //! as a `Reader` without unwrapping the result first. use clone::Clone; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use super::{Reader, Writer, Listener, Acceptor, Seek, SeekStyle, IoResult}; impl Writer for IoResult { diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 665000eae8837..74525785dc93b 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -36,8 +36,9 @@ use io::{Reader, Writer, IoResult, IoError, OtherIoError, use kinds::Send; use libc; use mem; -use option::{Option, Some, None}; -use result::{Ok, Err}; +use option::Option; +use option::Option::{Some, None}; +use result::Result::{Ok, Err}; use rustrt; use rustrt::local::Local; use rustrt::task::Task; diff --git a/src/libstd/io/tempfile.rs b/src/libstd/io/tempfile.rs index 4788ba79b7fa8..f3a119399952d 100644 --- a/src/libstd/io/tempfile.rs +++ b/src/libstd/io/tempfile.rs @@ -14,10 +14,11 @@ use io::{fs, IoResult}; use io; use libc; use ops::Drop; -use option::{Option, None, Some}; +use option::Option; +use option::Option::{None, Some}; use os; use path::{Path, GenericPath}; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use sync::atomic; /// A wrapper for a path to temporary directory implementing automatic diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 393283ff64c5b..e78bd1dd33f32 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -273,7 +273,7 @@ impl> Reader for IterReader { #[cfg(test)] mod test { - use io::{MemReader, BufReader, ByRefReader}; + use io::{MemReader, ByRefReader}; use io; use boxed::Box; use super::*; @@ -395,8 +395,7 @@ mod test { #[test] fn limit_reader_buffer() { - let data = "0123456789\n0123456789\n"; - let mut r = BufReader::new(data.as_bytes()); + let r = &mut b"0123456789\n0123456789\n"; { let mut r = LimitReader::new(r.by_ref(), 3); assert_eq!(r.read_line(), Ok("012".to_string())); diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 90203709627ff..88d1d0d0482dc 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -40,14 +40,16 @@ use libc::{c_void, c_int}; use libc; use boxed::Box; use ops::Drop; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; use os; use path::{Path, GenericPath, BytesContainer}; use sys; use sys::os as os_imp; use ptr::RawPtr; use ptr; -use result::{Err, Ok, Result}; +use result::Result; +use result::Result::{Err, Ok}; use slice::{AsSlice, SlicePrelude, PartialEqSlicePrelude}; use slice::CloneSliceAllocPrelude; use str::{Str, StrPrelude, StrAllocating}; @@ -160,7 +162,8 @@ pub fn getcwd() -> IoResult { pub mod windows { use libc::types::os::arch::extra::DWORD; use libc; - use option::{None, Option}; + use option::Option; + use option::Option::None; use option; use os::TMPBUF_SZ; use slice::{SlicePrelude}; @@ -196,7 +199,7 @@ pub mod windows { // set `res` to None and continue. let s = String::from_utf16(sub) .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16"); - res = option::Some(s) + res = option::Option::Some(s) } } return res; @@ -1799,7 +1802,7 @@ mod tests { fn test_setenv() { let n = make_rand_name(); setenv(n.as_slice(), "VALUE"); - assert_eq!(getenv(n.as_slice()), option::Some("VALUE".to_string())); + assert_eq!(getenv(n.as_slice()), option::Option::Some("VALUE".to_string())); } #[test] @@ -1807,7 +1810,7 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), "VALUE"); unsetenv(n.as_slice()); - assert_eq!(getenv(n.as_slice()), option::None); + assert_eq!(getenv(n.as_slice()), option::Option::None); } #[test] @@ -1816,9 +1819,9 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), "1"); setenv(n.as_slice(), "2"); - assert_eq!(getenv(n.as_slice()), option::Some("2".to_string())); + assert_eq!(getenv(n.as_slice()), option::Option::Some("2".to_string())); setenv(n.as_slice(), ""); - assert_eq!(getenv(n.as_slice()), option::Some("".to_string())); + assert_eq!(getenv(n.as_slice()), option::Option::Some("".to_string())); } // Windows GetEnvironmentVariable requires some extra work to make sure @@ -1835,7 +1838,7 @@ mod tests { let n = make_rand_name(); setenv(n.as_slice(), s.as_slice()); debug!("{}", s.clone()); - assert_eq!(getenv(n.as_slice()), option::Some(s)); + assert_eq!(getenv(n.as_slice()), option::Option::Some(s)); } #[test] @@ -1872,7 +1875,7 @@ mod tests { // MingW seems to set some funky environment variables like // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned // from env() but not visible from getenv(). - assert!(v2.is_none() || v2 == option::Some(v)); + assert!(v2.is_none() || v2 == option::Option::Some(v)); } } @@ -1959,7 +1962,7 @@ mod tests { #[test] fn memory_map_rw() { - use result::{Ok, Err}; + use result::Result::{Ok, Err}; let chunk = match os::MemoryMap::new(16, &[ os::MapReadable, @@ -1978,7 +1981,7 @@ mod tests { #[test] fn memory_map_file() { - use result::{Ok, Err}; + use result::Result::{Ok, Err}; use os::*; use libc::*; use io::fs; @@ -2034,7 +2037,7 @@ mod tests { fn split_paths_windows() { fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { split_paths(unparsed) == - parsed.iter().map(|s| Path::new(*s)).collect() + parsed.iter().map(|s| Path::new(*s)).collect::>() } assert!(check_parse("", &mut [""])); @@ -2054,7 +2057,7 @@ mod tests { fn split_paths_unix() { fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { split_paths(unparsed) == - parsed.iter().map(|s| Path::new(*s)).collect() + parsed.iter().map(|s| Path::new(*s)).collect::>() } assert!(check_parse("", &mut [""])); diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index b17106e811f62..01b42395471fc 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -66,7 +66,8 @@ use c_str::CString; use clone::Clone; use fmt; use iter::IteratorExt; -use option::{Option, None, Some}; +use option::Option; +use option::Option::{None, Some}; use str; use str::{CowString, MaybeOwned, Str, StrPrelude}; use string::String; diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index cc8fcccf14a06..d6d27daf4ae8b 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -17,7 +17,8 @@ use hash; use io::Writer; use iter::{DoubleEndedIteratorExt, AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map}; -use option::{Option, None, Some}; +use option::Option; +use option::Option::{None, Some}; use kinds::Sized; use str::{FromStr, Str}; use str; @@ -443,7 +444,6 @@ static dot_dot_static: &'static [u8] = b".."; mod tests { use prelude::*; use super::*; - use mem; use str; use str::StrPrelude; @@ -601,10 +601,8 @@ mod tests { macro_rules! t( (s: $path:expr, $op:ident, $exp:expr) => ( { - unsafe { - let path = Path::new($path); - assert!(path.$op() == mem::transmute(($exp).as_bytes())); - } + let path = Path::new($path); + assert!(path.$op() == ($exp).as_bytes()); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( @@ -616,11 +614,9 @@ mod tests { ); (v: $path:expr, $op:ident, $exp:expr) => ( { - unsafe { - let arg = $path; - let path = Path::new(arg); - assert!(path.$op() == mem::transmute($exp)); - } + let arg = $path; + let path = Path::new(arg); + assert!(path.$op() == $exp); } ); ) @@ -668,9 +664,8 @@ mod tests { t!(v: b"hi/there.txt", extension, Some(b"txt")); t!(v: b"hi/there\x80.txt", extension, Some(b"txt")); t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt")); - let no: Option<&'static [u8]> = None; - t!(v: b"hi/there", extension, no); - t!(v: b"hi/there\x80", extension, no); + t!(v: b"hi/there", extension, None); + t!(v: b"hi/there\x80", extension, None); t!(s: "hi/there.txt", extension, Some("txt"), opt); t!(s: "hi/there", extension, None, opt); t!(s: "there.txt", extension, Some("txt"), opt); @@ -959,62 +954,57 @@ mod tests { macro_rules! t( (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { - unsafe { - let path = $path; - let filename = $filename; - assert!(path.filename_str() == filename, - "{}.filename_str(): Expected `{}`, found {}", - path.as_str().unwrap(), filename, path.filename_str()); - let dirname = $dirname; - assert!(path.dirname_str() == dirname, - "`{}`.dirname_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), dirname, path.dirname_str()); - let filestem = $filestem; - assert!(path.filestem_str() == filestem, - "`{}`.filestem_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filestem, path.filestem_str()); - let ext = $ext; - assert!(path.extension_str() == mem::transmute(ext), - "`{}`.extension_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), ext, path.extension_str()); - } + let path = $path; + let filename = $filename; + assert!(path.filename_str() == filename, + "{}.filename_str(): Expected `{}`, found {}", + path.as_str().unwrap(), filename, path.filename_str()); + let dirname = $dirname; + assert!(path.dirname_str() == dirname, + "`{}`.dirname_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), dirname, path.dirname_str()); + let filestem = $filestem; + assert!(path.filestem_str() == filestem, + "`{}`.filestem_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), filestem, path.filestem_str()); + let ext = $ext; + assert!(path.extension_str() == ext, + "`{}`.extension_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), ext, path.extension_str()); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { - unsafe { - let path = $path; - assert!(path.filename() == mem::transmute($filename)); - assert!(path.dirname() == mem::transmute($dirname)); - assert!(path.filestem() == mem::transmute($filestem)); - assert!(path.extension() == mem::transmute($ext)); - } + let path = $path; + assert!(path.filename() == $filename); + assert!(path.dirname() == $dirname); + assert!(path.filestem() == $filestem); + assert!(path.extension() == $ext); } ) ) - let no: Option<&'static str> = None; - t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), no); - t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), no); + t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None); + t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None); t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi", Some(b"there"), Some(b"\xFF")); - t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), no); - t!(s: Path::new("."), None, Some("."), None, no); - t!(s: Path::new("/"), None, Some("/"), None, no); - t!(s: Path::new(".."), None, Some(".."), None, no); - t!(s: Path::new("../.."), None, Some("../.."), None, no); + t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None); + t!(s: Path::new("."), None, Some("."), None, None); + t!(s: Path::new("/"), None, Some("/"), None, None); + t!(s: Path::new(".."), None, Some(".."), None, None); + t!(s: Path::new("../.."), None, Some("../.."), None, None); t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"), Some("there"), Some("txt")); - t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), no); + t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), None); t!(s: Path::new("hi/there."), Some("there."), Some("hi"), Some("there"), Some("")); - t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), no); + t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None); t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"), Some("."), Some("there")); - t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, no); + t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None); t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt")); - t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), no); - t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), no); + t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None); + t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None); } #[test] diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 6a6551af4999b..08e318d32b9fc 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -23,7 +23,8 @@ use io::Writer; use iter::{AdditiveIterator, DoubleEndedIteratorExt, Extend}; use iter::{Iterator, IteratorExt, Map}; use mem; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use slice::{AsSlice, SlicePrelude}; use str::{CharSplits, FromStr, Str, StrAllocating, StrVector, StrPrelude}; use string::String; @@ -1115,7 +1116,6 @@ fn prefix_len(p: Option) -> uint { #[cfg(test)] mod tests { - use mem; use prelude::*; use super::*; use super::parse_prefix; @@ -1358,11 +1358,9 @@ mod tests { macro_rules! t( (s: $path:expr, $op:ident, $exp:expr) => ( { - unsafe { - let path = $path; - let path = Path::new(path); - assert!(path.$op() == Some(mem::transmute($exp))); - } + let path = $path; + let path = Path::new(path); + assert!(path.$op() == Some($exp)); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( @@ -1375,11 +1373,9 @@ mod tests { ); (v: $path:expr, $op:ident, $exp:expr) => ( { - unsafe { - let path = $path; - let path = Path::new(path); - assert!(path.$op() == mem::transmute($exp)); - } + let path = $path; + let path = Path::new(path); + assert!(path.$op() == $exp); } ) ) @@ -1464,8 +1460,7 @@ mod tests { // filestem is based on filename, so we don't need the full set of prefix tests t!(v: b"hi\\there.txt", extension, Some(b"txt")); - let no: Option<&'static [u8]> = None; - t!(v: b"hi\\there", extension, no); + t!(v: b"hi\\there", extension, None); t!(s: "hi\\there.txt", extension_str, Some("txt"), opt); t!(s: "hi\\there", extension_str, None, opt); t!(s: "there.txt", extension_str, Some("txt"), opt); @@ -1872,53 +1867,48 @@ mod tests { macro_rules! t( (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { - unsafe { - let path = $path; - let filename = $filename; - assert!(path.filename_str() == filename, - "`{}`.filename_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filename, path.filename_str()); - let dirname = $dirname; - assert!(path.dirname_str() == dirname, - "`{}`.dirname_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), dirname, path.dirname_str()); - let filestem = $filestem; - assert!(path.filestem_str() == filestem, - "`{}`.filestem_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filestem, path.filestem_str()); - let ext = $ext; - assert!(path.extension_str() == mem::transmute(ext), - "`{}`.extension_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), ext, path.extension_str()); - } + let path = $path; + let filename = $filename; + assert!(path.filename_str() == filename, + "`{}`.filename_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), filename, path.filename_str()); + let dirname = $dirname; + assert!(path.dirname_str() == dirname, + "`{}`.dirname_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), dirname, path.dirname_str()); + let filestem = $filestem; + assert!(path.filestem_str() == filestem, + "`{}`.filestem_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), filestem, path.filestem_str()); + let ext = $ext; + assert!(path.extension_str() == ext, + "`{}`.extension_str(): Expected `{}`, found `{}`", + path.as_str().unwrap(), ext, path.extension_str()); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { - unsafe { - let path = $path; - assert!(path.filename() == mem::transmute($filename)); - assert!(path.dirname() == mem::transmute($dirname)); - assert!(path.filestem() == mem::transmute($filestem)); - assert!(path.extension() == mem::transmute($ext)); - } + let path = $path; + assert!(path.filename() == $filename); + assert!(path.dirname() == $dirname); + assert!(path.filestem() == $filestem); + assert!(path.extension() == $ext); } ) ) - let no: Option<&'static str> = None; - t!(v: Path::new(b"a\\b\\c"), Some(b"c"), b"a\\b", Some(b"c"), no); - t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), no); - t!(s: Path::new("."), None, Some("."), None, no); - t!(s: Path::new("\\"), None, Some("\\"), None, no); - t!(s: Path::new(".."), None, Some(".."), None, no); - t!(s: Path::new("..\\.."), None, Some("..\\.."), None, no); + t!(v: Path::new(b"a\\b\\c"), Some(b"c"), b"a\\b", Some(b"c"), None); + t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), None); + t!(s: Path::new("."), None, Some("."), None, None); + t!(s: Path::new("\\"), None, Some("\\"), None, None); + t!(s: Path::new(".."), None, Some(".."), None, None); + t!(s: Path::new("..\\.."), None, Some("..\\.."), None, None); t!(s: Path::new("hi\\there.txt"), Some("there.txt"), Some("hi"), Some("there"), Some("txt")); - t!(s: Path::new("hi\\there"), Some("there"), Some("hi"), Some("there"), no); + t!(s: Path::new("hi\\there"), Some("there"), Some("hi"), Some("there"), None); t!(s: Path::new("hi\\there."), Some("there."), Some("hi"), Some("there"), Some("")); - t!(s: Path::new("hi\\.there"), Some(".there"), Some("hi"), Some(".there"), no); + t!(s: Path::new("hi\\.there"), Some(".there"), Some("hi"), Some(".there"), None); t!(s: Path::new("hi\\..there"), Some("..there"), Some("hi"), Some("."), Some("there")); diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index da690f5d154df..413d9267152eb 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -227,7 +227,7 @@ use io::IoResult; use iter::{Iterator, IteratorExt}; use mem; use rc::Rc; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use vec::Vec; #[cfg(not(target_word_size="64"))] diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 2a4d8347c30c9..37628b65388e7 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -23,7 +23,7 @@ mod imp { use path::Path; use rand::Rng; use rand::reader::ReaderRng; - use result::{Ok, Err}; + use result::Result::{Ok, Err}; use slice::SlicePrelude; use mem; use os::errno; @@ -173,7 +173,7 @@ mod imp { use mem; use os; use rand::Rng; - use result::{Ok}; + use result::Result::{Ok}; use self::libc::{c_int, size_t}; use slice::{SlicePrelude}; @@ -240,7 +240,7 @@ mod imp { use ops::Drop; use os; use rand::Rng; - use result::{Ok, Err}; + use result::Result::{Ok, Err}; use self::libc::{DWORD, BYTE, LPCSTR, BOOL}; use self::libc::types::os::arch::extra::{LONG_PTR}; use slice::{SlicePrelude}; diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index 796bf7853f73b..ca6322247c2ab 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -12,7 +12,7 @@ use io::Reader; use rand::Rng; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use slice::SlicePrelude; /// An RNG that reads random bytes straight from a `Reader`. This will diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index 0103fe670e76f..f55cb5404304b 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -14,9 +14,9 @@ use io::{IoResult, Writer}; use iter::{Iterator, IteratorExt}; -use option::{Some, None}; +use option::Option::{Some, None}; use os; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use str::{StrPrelude, from_str}; use sync::atomic; use unicode::char::UnicodeChar; @@ -236,8 +236,9 @@ mod imp { use io::{IoResult, Writer}; use libc; use mem; - use option::{Some, None, Option}; - use result::{Ok, Err}; + use option::Option; + use option::Option::{Some, None}; + use result::Result::{Ok, Err}; use rustrt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; /// As always - iOS on arm uses SjLj exceptions and @@ -664,9 +665,9 @@ mod imp { use libc; use mem; use ops::Drop; - use option::{Some, None}; + use option::Option::{Some, None}; use path::Path; - use result::{Ok, Err}; + use result::Result::{Ok, Err}; use rustrt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; use slice::SlicePrelude; use str::StrPrelude; diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 92657d1b59bee..ce359c7b0e006 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -9,7 +9,8 @@ // except according to those terms. use libc::uintptr_t; -use option::{Some, None, Option}; +use option::Option; +use option::Option::{Some, None}; use os; use str::{FromStr, from_str, Str}; use sync::atomic; diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 4b47b768d600c..a773ef7e31747 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -20,7 +20,7 @@ use prelude::*; use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode}; use io::{IoResult, FileStat, SeekStyle, Reader}; use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append}; -use result::{Ok, Err}; +use result::Result::{Ok, Err}; use sys::retry; use sys_common::{keep_going, eof, mkerr_libc}; diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 9c4ffb926b5ae..9402c63dcf558 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -131,7 +131,7 @@ impl FileDesc { return ret; } - pub fn fstat(&mut self) -> IoResult { + pub fn fstat(&self) -> IoResult { let mut stat: libc::stat = unsafe { mem::zeroed() }; match unsafe { libc::fstat(self.fd(), &mut stat) } { 0 => Ok(mkstat(&stat)), diff --git a/src/libstd/task.rs b/src/libstd/task.rs index a0ee08570d90d..8b4dbf61c181d 100644 --- a/src/libstd/task.rs +++ b/src/libstd/task.rs @@ -49,7 +49,8 @@ use boxed::Box; use comm::channel; use io::{Writer, stdio}; use kinds::{Send, marker}; -use option::{None, Some, Option}; +use option::Option; +use option::Option::{None, Some}; use result::Result; use rustrt::local::Local; use rustrt::task::Task; @@ -172,9 +173,10 @@ impl TaskBuilder { /// # Return value /// /// If the child task executes successfully (without panicking) then the - /// future returns `result::Ok` containing the value returned by the - /// function. If the child task panics then the future returns `result::Err` - /// containing the argument to `panic!(...)` as an `Any` trait object. + /// future returns `result::Result::Ok` containing the value returned by the + /// function. If the child task panics then the future returns + /// `result::Result::Err` containing the argument to `panic!(...)` as an + /// `Any` trait object. #[experimental = "Futures are experimental."] pub fn try_future(self, f: proc():Send -> T) -> Future>> { @@ -268,7 +270,7 @@ mod test { use borrow::IntoCow; use boxed::BoxAny; use prelude::*; - use result::{Ok, Err}; + use result::Result::{Ok, Err}; use result; use std::io::{ChanReader, ChanWriter}; use string::String; @@ -330,7 +332,7 @@ mod test { match try(proc() { "Success!".to_string() }).as_ref().map(|s| s.as_slice()) { - result::Ok("Success!") => (), + result::Result::Ok("Success!") => (), _ => panic!() } } @@ -340,8 +342,8 @@ mod test { match try(proc() { panic!() }) { - result::Err(_) => (), - result::Ok(()) => panic!() + result::Result::Err(_) => (), + result::Result::Ok(()) => panic!() } } diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e2e8461ea54d4..029b8bf113877 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -115,7 +115,7 @@ macro_rules! thread_local( use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::KeyInner as __KeyInner; use std::option::Option as __Option; - use std::option::None as __None; + use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } @@ -132,7 +132,7 @@ macro_rules! thread_local( use std::cell::UnsafeCell as __UnsafeCell; use std::thread_local::KeyInner as __KeyInner; use std::option::Option as __Option; - use std::option::None as __None; + use std::option::Option::None as __None; __thread_local_inner!(static __KEY: __UnsafeCell<__Option<$t>> = { __UnsafeCell { value: __None } @@ -198,7 +198,7 @@ macro_rules! __thread_local_inner( inner: ::std::cell::UnsafeCell { value: $init }, os: ::std::thread_local::OsStaticKey { inner: ::std::thread_local::OS_INIT_INNER, - dtor: ::std::option::Some(__destroy), + dtor: ::std::option::Option::Some(__destroy), }, } }; diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index ec2d62ff85cb1..63eb9a9873624 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -14,9 +14,11 @@ use {fmt, i64}; use ops::{Add, Sub, Mul, Div, Neg}; -use option::{Option, Some, None}; +use option::Option; +use option::Option::{Some, None}; use num::Int; -use result::{Result, Ok, Err}; +use result::Result; +use result::Result::{Ok, Err}; /// The number of nanoseconds in a microsecond. const NANOS_PER_MICRO: i32 = 1000; @@ -387,7 +389,7 @@ fn div_rem_64(this: i64, other: i64) -> (i64, i64) { mod tests { use super::{Duration, MIN, MAX}; use {i32, i64}; - use option::{Some, None}; + use option::Option::{Some, None}; use string::ToString; #[test] diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index fdfa275549a2c..a2811681efd37 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -287,11 +287,11 @@ pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr { // FIXME (#2809)---validate the usage of #[inline] and #[inline] attrs.iter().fold(InlineNone, |ia,attr| { match attr.node.value.node { - MetaWord(ref n) if n.equiv(&("inline")) => { + MetaWord(ref n) if *n == "inline" => { mark_used(attr); InlineHint } - MetaList(ref n, ref items) if n.equiv(&("inline")) => { + MetaList(ref n, ref items) if *n == "inline" => { mark_used(attr); if contains_name(items.as_slice(), "always") { InlineAlways @@ -409,7 +409,7 @@ pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P]) { pub fn find_repr_attrs(diagnostic: &SpanHandler, attr: &Attribute) -> Vec { let mut acc = Vec::new(); match attr.node.value.node { - ast::MetaList(ref s, ref items) if s.equiv(&("repr")) => { + ast::MetaList(ref s, ref items) if *s == "repr" => { mark_used(attr); for item in items.iter() { match item.node { diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 5f4e675aad5d5..2be11a236d3b7 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -45,15 +45,6 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, [ast::TtToken(_, token::Ident(code, _))] => code, _ => unreachable!() }; - with_registered_diagnostics(|diagnostics| { - if !diagnostics.contains_key(&code.name) { - ecx.span_err(span, format!( - "unknown diagnostic code {}; add to librustc/diagnostics.rs", - token::get_ident(code).get() - ).as_slice()); - } - () - }); with_used_diagnostics(|diagnostics| { match diagnostics.insert(code.name, span) { Some(previous_span) => { @@ -106,25 +97,19 @@ pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, _ => unreachable!() }; - let (count, expr) = with_used_diagnostics(|diagnostics_in_use| { + let (count, expr) = with_registered_diagnostics(|diagnostics| { - let descriptions: Vec> = diagnostics - .iter().filter_map(|(code, description)| { - if !diagnostics_in_use.contains_key(code) { - ecx.span_warn(span, format!( - "diagnostic code {} never used", token::get_name(*code).get() - ).as_slice()); - } - description.map(|description| { - ecx.expr_tuple(span, vec![ - ecx.expr_str(span, token::get_name(*code)), - ecx.expr_str(span, token::get_name(description)) - ]) - }) - }).collect(); + let descriptions: Vec> = + diagnostics.iter().filter_map(|(code, description)| { + description.map(|description| { + ecx.expr_tuple(span, vec![ + ecx.expr_str(span, token::get_name(*code)), + ecx.expr_str(span, token::get_name(description))]) + }) + }).collect(); (descriptions.len(), ecx.expr_vec(span, descriptions)) - }) - }); + }); + MacItems::new(vec![quote_item!(ecx, pub static $name: [(&'static str, &'static str), ..$count] = $expr; ).unwrap()].into_iter()) diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index a0999d9eee96e..b138811187ba9 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -148,7 +148,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let (s, _str_style) = p.parse_str(); - if OPTIONS.iter().any(|opt| s.equiv(opt)) { + if OPTIONS.iter().any(|&opt| s == opt) { cx.span_warn(p.last_span, "expected a clobber, found an option"); } clobs.push(s); @@ -157,13 +157,13 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Options => { let (option, _str_style) = p.parse_str(); - if option.equiv(&("volatile")) { + if option == "volatile" { // Indicates that the inline assembly has side effects // and must not be optimized out along with its outputs. volatile = true; - } else if option.equiv(&("alignstack")) { + } else if option == "alignstack" { alignstack = true; - } else if option.equiv(&("intel")) { + } else if option == "intel" { dialect = ast::AsmIntel; } else { cx.span_warn(p.last_span, "unrecognized option"); diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index bd01e5e643020..b4bb1a1a52963 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -680,6 +680,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let some = vec!( self.ident_of("std"), self.ident_of("option"), + self.ident_of("Option"), self.ident_of("Some")); self.expr_call_global(sp, some, vec!(expr)) } @@ -688,6 +689,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let none = self.path_global(sp, vec!( self.ident_of("std"), self.ident_of("option"), + self.ident_of("Option"), self.ident_of("None"))); self.expr_path(none) } @@ -732,6 +734,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let ok = vec!( self.ident_of("std"), self.ident_of("result"), + self.ident_of("Result"), self.ident_of("Ok")); self.expr_call_global(sp, ok, vec!(expr)) } @@ -740,6 +743,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let err = vec!( self.ident_of("std"), self.ident_of("result"), + self.ident_of("Result"), self.ident_of("Err")); self.expr_call_global(sp, err, vec!(expr)) } @@ -810,6 +814,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let some = vec!( self.ident_of("std"), self.ident_of("option"), + self.ident_of("Option"), self.ident_of("Some")); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) @@ -819,6 +824,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let some = vec!( self.ident_of("std"), self.ident_of("option"), + self.ident_of("Option"), self.ident_of("None")); let path = self.path_global(span, some); self.pat_enum(span, path, vec!()) @@ -828,6 +834,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let some = vec!( self.ident_of("std"), self.ident_of("result"), + self.ident_of("Result"), self.ident_of("Ok")); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) @@ -837,6 +844,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { let some = vec!( self.ident_of("std"), self.ident_of("result"), + self.ident_of("Result"), self.ident_of("Err")); let path = self.path_global(span, some); self.pat_enum(span, path, vec!(pat)) diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 98345e1dd6724..787c6e844d514 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -105,6 +105,7 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, let ordering = cx.path_global(span, vec!(cx.ident_of("std"), cx.ident_of("cmp"), + cx.ident_of("Ordering"), cx.ident_of("Equal"))); let ordering = cx.expr_path(ordering); let equals_expr = cx.expr_some(span, ordering); @@ -120,9 +121,9 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, Builds: let __test = ::std::cmp::PartialOrd::partial_cmp(&self_field1, &other_field1); - if __test == ::std::option::Some(::std::cmp::Equal) { + if __test == ::std::option::Option::Some(::std::cmp::Ordering::Equal) { let __test = ::std::cmp::PartialOrd::partial_cmp(&self_field2, &other_field2); - if __test == ::std::option::Some(::std::cmp::Equal) { + if __test == ::std::option::Option::Some(::std::cmp::Ordering::Equal) { ... } else { __test @@ -139,7 +140,7 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt, span: Span, false, |cx, span, old, self_f, other_fs| { // let __test = new; - // if __test == Some(::std::cmp::Equal) { + // if __test == Some(::std::cmp::Ordering::Equal) { // old // } else { // __test diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index d84ad677e5df5..83af45462ec6e 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -70,9 +70,9 @@ pub fn cs_cmp(cx: &mut ExtCtxt, span: Span, Builds: let __test = self_field1.cmp(&other_field2); - if other == ::std::cmp::Equal { + if other == ::std::cmp::Ordering::Equal { let __test = self_field2.cmp(&other_field2); - if __test == ::std::cmp::Equal { + if __test == ::std::cmp::Ordering::Equal { ... } else { __test @@ -89,7 +89,7 @@ pub fn cs_cmp(cx: &mut ExtCtxt, span: Span, false, |cx, span, old, new| { // let __test = new; - // if __test == ::std::cmp::Equal { + // if __test == ::std::cmp::Ordering::Equal { // old // } else { // __test diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 87e257c52cd25..e6a44c57f1b65 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -36,6 +36,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT true, vec!(cx.ident_of("std"), cx.ident_of("option"), + cx.ident_of("Option"), cx.ident_of("None")), Vec::new(), vec!(cx.ty_rptr(sp, @@ -50,6 +51,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT cx.expr_call_global(sp, vec!(cx.ident_of("std"), cx.ident_of("option"), + cx.ident_of("Option"), cx.ident_of("Some")), vec!(cx.expr_str(sp, token::intern_and_get_ident( diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 3fca110a881c8..45752499ad592 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -450,9 +450,8 @@ pub fn expand_quote_ty(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box { - let e_param_colons = cx.expr_lit(sp, ast::LitBool(false)); let expanded = expand_parse_call(cx, sp, "parse_ty", - vec!(e_param_colons), tts); + vec![], tts); base::MacExpr::new(expanded) } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 7453da6374e00..5ece63fd48d69 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -65,13 +65,13 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("unboxed_closures", Active), ("import_shadowing", Active), ("advanced_slice_patterns", Active), - ("tuple_indexing", Active), + ("tuple_indexing", Accepted), ("associated_types", Active), ("visible_private_types", Active), ("slicing_syntax", Active), - ("if_let", Active), - ("while_let", Active), + ("if_let", Accepted), + ("while_let", Accepted), // if you change this list without updating src/doc/reference.md, cmr will be sad @@ -172,12 +172,12 @@ impl<'a, 'v> Visitor<'v> for Context<'a> { fn visit_item(&mut self, i: &ast::Item) { for attr in i.attrs.iter() { - if attr.name().equiv(&("thread_local")) { + if attr.name() == "thread_local" { self.gate_feature("thread_local", i.span, "`#[thread_local]` is an experimental feature, and does not \ currently handle destructors. There is no corresponding \ `#[task_local]` mapping to the task model"); - } else if attr.name().equiv(&("linkage")) { + } else if attr.name() == "linkage" { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") @@ -309,24 +309,11 @@ impl<'a, 'v> Visitor<'v> for Context<'a> { "unboxed closures are a work-in-progress \ feature with known bugs"); } - ast::ExprTupField(..) => { - self.gate_feature("tuple_indexing", - e.span, - "tuple indexing is experimental"); - } - ast::ExprIfLet(..) => { - self.gate_feature("if_let", e.span, - "`if let` syntax is experimental"); - } ast::ExprSlice(..) => { self.gate_feature("slicing_syntax", e.span, "slicing syntax is experimental"); } - ast::ExprWhileLet(..) => { - self.gate_feature("while_let", e.span, - "`while let` syntax is experimental"); - } _ => {} } visit::walk_expr(self, e); @@ -429,7 +416,7 @@ pub fn check_crate(span_handler: &SpanHandler, krate: &ast::Crate) -> (Features, } }; match KNOWN_FEATURES.iter() - .find(|& &(n, _)| name.equiv(&n)) { + .find(|& &(n, _)| name == n) { Some(&(name, Active)) => { cx.features.push(name); } Some(&(_, Removed)) => { span_handler.span_err(mi.span, "feature has been removed"); diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index db7bc6c323f89..41fee1556abff 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -212,7 +212,7 @@ impl<'a> ParserAttr for Parser<'a> { fn parse_meta_seq(&mut self) -> Vec> { self.parse_seq(&token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), - seq_sep_trailing_disallowed(token::Comma), + seq_sep_trailing_allowed(token::Comma), |p| p.parse_meta_item()).node } diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index 3842170d67777..a96bf1ce10b79 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -19,18 +19,13 @@ pub struct SeqSep { pub trailing_sep_allowed: bool } -pub fn seq_sep_trailing_disallowed(t: token::Token) -> SeqSep { - SeqSep { - sep: Some(t), - trailing_sep_allowed: false, - } -} pub fn seq_sep_trailing_allowed(t: token::Token) -> SeqSep { SeqSep { sep: Some(t), trailing_sep_allowed: true, } } + pub fn seq_sep_none() -> SeqSep { SeqSep { sep: None, diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 57983a6dee6be..27b65e0f52798 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -764,6 +764,15 @@ impl<'a> StringReader<'a> { } } + // SNAP c9f6d69 + #[allow(unused)] + fn old_escape_warning(&mut self, sp: Span) { + self.span_diagnostic + .span_warn(sp, "\\U00ABCD12 and \\uABCD escapes are deprecated"); + self.span_diagnostic + .span_help(sp, "use \\u{ABCD12} escapes instead"); + } + /// Scan for a single (possibly escaped) byte or char /// in a byte, (non-raw) byte string, char, or (non-raw) string literal. /// `start` is the position of `first_source_char`, which is already consumed. @@ -782,12 +791,24 @@ impl<'a> StringReader<'a> { Some(e) => { return match e { 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true, - 'x' => self.scan_hex_digits(2u, delim, !ascii_only), + 'x' => self.scan_byte_escape(delim, !ascii_only), 'u' if !ascii_only => { - self.scan_hex_digits(4u, delim, false) + if self.curr == Some('{') { + self.scan_unicode_escape(delim) + } else { + let res = self.scan_hex_digits(4u, delim, false); + // SNAP c9f6d69 + //let sp = codemap::mk_sp(escaped_pos, self.last_pos); + //self.old_escape_warning(sp); + res + } } 'U' if !ascii_only => { - self.scan_hex_digits(8u, delim, false) + let res = self.scan_hex_digits(8u, delim, false); + // SNAP c9f6d69 + //let sp = codemap::mk_sp(escaped_pos, self.last_pos); + //self.old_escape_warning(sp); + res } '\n' if delim == '"' => { self.consume_whitespace(); @@ -848,6 +869,56 @@ impl<'a> StringReader<'a> { true } + /// Scan over a \u{...} escape + /// + /// At this point, we have already seen the \ and the u, the { is the current character. We + /// will read at least one digit, and up to 6, and pass over the }. + fn scan_unicode_escape(&mut self, delim: char) -> bool { + self.bump(); // past the { + let start_bpos = self.last_pos; + let mut count: uint = 0; + let mut accum_int = 0; + + while !self.curr_is('}') && count <= 6 { + let c = match self.curr { + Some(c) => c, + None => { + self.fatal_span_(start_bpos, self.last_pos, + "unterminated unicode escape (found EOF)"); + } + }; + accum_int *= 16; + accum_int += c.to_digit(16).unwrap_or_else(|| { + if c == delim { + self.fatal_span_(self.last_pos, self.pos, + "unterminated unicode escape (needed a `}`)"); + } else { + self.fatal_span_char(self.last_pos, self.pos, + "illegal character in unicode escape", c); + } + }) as u32; + self.bump(); + count += 1; + } + + if count > 6 { + self.fatal_span_(start_bpos, self.last_pos, + "overlong unicode escape (can have at most 6 hex digits)"); + } + + self.bump(); // past the ending } + + let mut valid = count >= 1 && count <= 6; + if char::from_u32(accum_int).is_none() { + valid = false; + } + + if !valid { + self.fatal_span_(start_bpos, self.last_pos, "illegal unicode character escape"); + } + valid + } + /// Scan over a float exponent. fn scan_float_exponent(&mut self) { if self.curr_is('e') || self.curr_is('E') { @@ -1273,6 +1344,10 @@ impl<'a> StringReader<'a> { return token::Byte(id); } + fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool { + self.scan_hex_digits(2, delim, below_0x7f_only) + } + fn scan_byte_string(&mut self) -> token::Lit { self.bump(); let start = self.last_pos; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index b46f7cdfe22ad..8d0c2de048a56 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -393,16 +393,28 @@ pub fn char_lit(lit: &str) -> (char, int) { let msg = format!("lexer should have rejected a bad character escape {}", lit); let msg2 = msg.as_slice(); - let esc: |uint| -> Option<(char, int)> = |len| + fn esc(len: uint, lit: &str) -> Option<(char, int)> { num::from_str_radix(lit.slice(2, len), 16) .and_then(char::from_u32) - .map(|x| (x, len as int)); + .map(|x| (x, len as int)) + } + + let unicode_escape: || -> Option<(char, int)> = || + if lit.as_bytes()[2] == b'{' { + let idx = lit.find('}').expect(msg2); + let subslice = lit.slice(3, idx); + num::from_str_radix(subslice, 16) + .and_then(char::from_u32) + .map(|x| (x, subslice.char_len() as int + 4)) + } else { + esc(6, lit) + }; // Unicode escapes return match lit.as_bytes()[1] as char { - 'x' | 'X' => esc(4), - 'u' => esc(6), - 'U' => esc(10), + 'x' | 'X' => esc(4, lit), + 'u' => unicode_escape(), + 'U' => esc(10, lit), _ => None, }.expect(msg2); } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 86a96fc521642..650f8295d01a6 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -117,7 +117,7 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { fn is_obsolete_ident(&mut self, ident: &str) -> bool { match self.token { token::Ident(sid, _) => { - token::get_ident(sid).equiv(&ident) + token::get_ident(sid) == ident } _ => false } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 920bcc3a951ae..e7efe97da4489 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1381,7 +1381,7 @@ impl<'a> Parser<'a> { // clauses (i.e., not when parsing something like // `FnMut() -> T + Send`, where the `+` is legal). if self.token == token::BinOp(token::Plus) { - self.warn("deprecated syntax: `()` are required, see RFC 248 for details"); + self.warn("deprecated syntax: `()` are required, see RFC 438 for details"); } Return(t) @@ -3111,6 +3111,11 @@ impl<'a> Parser<'a> { first = false; } else { self.expect(&token::Comma); + + if self.token == token::CloseDelim(token::Bracket) + && (before_slice || after.len() != 0) { + break + } } if before_slice { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 37df2bf14c2e1..52b54bc7f2d6d 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -623,12 +623,35 @@ impl fmt::Show for InternedString { } } +#[allow(deprecated)] impl<'a> Equiv<&'a str> for InternedString { fn equiv(&self, other: & &'a str) -> bool { (*other) == self.string.as_slice() } } +impl<'a> PartialEq<&'a str> for InternedString { + #[inline(always)] + fn eq(&self, other: & &'a str) -> bool { + PartialEq::eq(self.string.as_slice(), *other) + } + #[inline(always)] + fn ne(&self, other: & &'a str) -> bool { + PartialEq::ne(self.string.as_slice(), *other) + } +} + +impl<'a> PartialEq for &'a str { + #[inline(always)] + fn eq(&self, other: &InternedString) -> bool { + PartialEq::eq(*self, other.string.as_slice()) + } + #[inline(always)] + fn ne(&self, other: &InternedString) -> bool { + PartialEq::ne(*self, other.string.as_slice()) + } +} + impl, E> Decodable for InternedString { fn decode(d: &mut D) -> Result { Ok(get_name(get_ident_interner().intern( diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index c4b3288d44db8..d56e4f704499e 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -224,10 +224,10 @@ mod test { assert_eq!(Vec::new(), v); let v = SmallVector::one(1i); - assert_eq!(vec!(1i), v.into_iter().collect()); + assert_eq!(vec!(1i), v.into_iter().collect::>()); let v = SmallVector::many(vec!(1i, 2i, 3i)); - assert_eq!(vec!(1i, 2i, 3i), v.into_iter().collect()); + assert_eq!(vec!(1i, 2i, 3i), v.into_iter().collect::>()); } #[test] diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index 62a49c5d90270..3c909a3c70842 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -576,19 +576,19 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result ,String> { #[cfg(test)] mod test { use super::{expand,Param,Words,Variables,Number}; - use std::result::Ok; + use std::result::Result::Ok; #[test] fn test_basic_setabf() { let s = b"\\E[48;5;%p1%dm"; assert_eq!(expand(s, &[Number(1)], &mut Variables::new()).unwrap(), - "\\E[48;5;1m".bytes().collect()); + "\\E[48;5;1m".bytes().collect::>()); } #[test] fn test_multiple_int_constants() { assert_eq!(expand(b"%{1}%{2}%d%d", &[], &mut Variables::new()).unwrap(), - "21".bytes().collect()); + "21".bytes().collect::>()); } #[test] @@ -596,9 +596,9 @@ mod test { let mut vars = Variables::new(); assert_eq!(expand(b"%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d", &[Number(1),Number(2),Number(3)], &mut vars), - Ok("123233".bytes().collect())); + Ok("123233".bytes().collect::>())); assert_eq!(expand(b"%p1%d%p2%d%i%p1%d%p2%d", &[], &mut vars), - Ok("0011".bytes().collect())); + Ok("0011".bytes().collect::>())); } #[test] @@ -672,15 +672,15 @@ mod test { let res = expand(s, &[Number(1)], &mut vars); assert!(res.is_ok(), res.unwrap_err()); assert_eq!(res.unwrap(), - "\\E[31m".bytes().collect()); + "\\E[31m".bytes().collect::>()); let res = expand(s, &[Number(8)], &mut vars); assert!(res.is_ok(), res.unwrap_err()); assert_eq!(res.unwrap(), - "\\E[90m".bytes().collect()); + "\\E[90m".bytes().collect::>()); let res = expand(s, &[Number(42)], &mut vars); assert!(res.is_ok(), res.unwrap_err()); assert_eq!(res.unwrap(), - "\\E[38;5;42m".bytes().collect()); + "\\E[38;5;42m".bytes().collect::>()); } #[test] @@ -692,13 +692,13 @@ mod test { Words("foo".to_string()), Words("f".to_string()), Words("foo".to_string())], vars), - Ok("foofoo ffo".bytes().collect())); + Ok("foofoo ffo".bytes().collect::>())); assert_eq!(expand(b"%p1%:-4.2s", &[Words("foo".to_string())], vars), - Ok("fo ".bytes().collect())); + Ok("fo ".bytes().collect::>())); assert_eq!(expand(b"%p1%d%p1%.3d%p1%5d%p1%:+d", &[Number(1)], vars), - Ok("1001 1+1".bytes().collect())); + Ok("1001 1+1".bytes().collect::>())); assert_eq!(expand(b"%p1%o%p1%#o%p2%6.4x%p2%#6.4X", &[Number(15), Number(27)], vars), - Ok("17017 001b0X001B".bytes().collect())); + Ok("17017 001b0X001B".bytes().collect::>())); } } diff --git a/src/libtime/lib.rs b/src/libtime/lib.rs index 1d5268b975481..06a0df852b936 100644 --- a/src/libtime/lib.rs +++ b/src/libtime/lib.rs @@ -32,7 +32,6 @@ use self::Fmt::*; use std::fmt::Show; use std::fmt; -use std::io::BufReader; use std::num::SignedInt; use std::string::String; use std::time::Duration; @@ -1187,7 +1186,7 @@ pub fn strptime(s: &str, format: &str) -> Result { } } - let mut rdr = BufReader::new(format.as_bytes()); + let mut rdr: &[u8] = format.as_bytes(); let mut tm = Tm { tm_sec: 0_i32, tm_min: 0_i32, @@ -1211,13 +1210,13 @@ pub fn strptime(s: &str, format: &str) -> Result { let next = range.next; let mut buf = [0]; - let c = match rdr.read(&mut buf) { + let c = match (&mut rdr).read(&mut buf) { Ok(..) => buf[0] as char, Err(..) => break }; match c { '%' => { - let ch = match rdr.read(&mut buf) { + let ch = match (&mut rdr).read(&mut buf) { Ok(..) => buf[0] as char, Err(..) => break }; @@ -1233,7 +1232,7 @@ pub fn strptime(s: &str, format: &str) -> Result { } } - if pos == len && rdr.tell().unwrap() == format.len() as u64 { + if pos == len && (&mut rdr).is_empty() { Ok(Tm { tm_sec: tm.tm_sec, tm_min: tm.tm_min, @@ -1263,7 +1262,7 @@ mod tests { InvalidFormatSpecifier}; use std::f64; - use std::result::{Err, Ok}; + use std::result::Result::{Err, Ok}; use std::time::Duration; use self::test::Bencher; diff --git a/src/libunicode/normalize.rs b/src/libunicode/normalize.rs index cd46fc6a56dd0..29a8b1204b856 100644 --- a/src/libunicode/normalize.rs +++ b/src/libunicode/normalize.rs @@ -10,8 +10,9 @@ //! Functions for computing canonical and compatible decompositions for Unicode characters. -use core::cmp::{Equal, Less, Greater}; -use core::option::{Option, Some, None}; +use core::cmp::Ordering::{Equal, Less, Greater}; +use core::option::Option; +use core::option::Option::{Some, None}; use core::slice; use core::slice::SlicePrelude; use tables::normalization::{canonical_table, compatibility_table, composition_table}; diff --git a/src/libunicode/tables.rs b/src/libunicode/tables.rs index 7cece6701dc85..c91ce5c6464e8 100644 --- a/src/libunicode/tables.rs +++ b/src/libunicode/tables.rs @@ -17,7 +17,7 @@ pub const UNICODE_VERSION: (uint, uint, uint) = (7, 0, 0); fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; r.binary_search(|&(lo,hi)| { if lo <= c && c <= hi { Equal } @@ -6241,7 +6241,7 @@ pub mod normalization { fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; use core::slice; match r.binary_search(|&(lo, hi, _)| { @@ -6366,10 +6366,11 @@ pub mod normalization { } pub mod conversions { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; use core::slice::SlicePrelude; use core::tuple::Tuple2; - use core::option::{Option, Some, None}; + use core::option::Option; + use core::option::Option::{Some, None}; use core::slice; pub fn to_lower(c: char) -> char { @@ -6934,12 +6935,13 @@ pub mod conversions { } pub mod charwidth { - use core::option::{Option, Some, None}; + use core::option::Option; + use core::option::Option::{Some, None}; use core::slice::SlicePrelude; use core::slice; fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; match r.binary_search(|&(lo, hi, _, _)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } @@ -7154,7 +7156,7 @@ pub mod grapheme { } fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat { - use core::cmp::{Equal, Less, Greater}; + use core::cmp::Ordering::{Equal, Less, Greater}; match r.binary_search(|&(lo, hi, _)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } diff --git a/src/libunicode/u_str.rs b/src/libunicode/u_str.rs index a5f7614257595..e4b2b682b2cff 100644 --- a/src/libunicode/u_str.rs +++ b/src/libunicode/u_str.rs @@ -21,7 +21,8 @@ use core::slice::SlicePrelude; use core::iter::{Filter, AdditiveIterator, Iterator, IteratorExt}; use core::iter::{DoubleEndedIterator, DoubleEndedIteratorExt}; use core::kinds::Sized; -use core::option::{Option, None, Some}; +use core::option::Option; +use core::option::Option::{None, Some}; use core::str::{CharSplits, StrPrelude}; use u_char::UnicodeChar; use tables::grapheme::GraphemeCat; diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 4005c11e6b614..45d2cbea8fad9 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -77,8 +77,8 @@ fn sort_and_fmt(mm: &HashMap , uint>, total: uint) -> String { fn find(mm: &HashMap , uint>, key: String) -> uint { let key = key.into_ascii().as_slice().to_lowercase().into_string(); match mm.get(key.as_bytes()) { - option::None => { return 0u; } - option::Some(&num) => { return num; } + option::Option::None => { return 0u; } + option::Option::Some(&num) => { return num; } } } @@ -190,8 +190,8 @@ fn main() { // start processing if this is the one ('>', false) => { match line.as_slice().slice_from(1).find_str("THREE") { - option::Some(_) => { proc_mode = true; } - option::None => { } + option::Option::Some(_) => { proc_mode = true; } + option::Option::None => { } } } diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 9cc86e91fbed7..15a5cb0c9bfff 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -21,7 +21,7 @@ extern crate getopts; use std::os; -use std::result::{Ok, Err}; +use std::result::Result::{Ok, Err}; use std::task; use std::time::Duration; diff --git a/src/test/compile-fail/borrow-tuple-fields.rs b/src/test/compile-fail/borrow-tuple-fields.rs index 519bad4e627b7..1d09143c24d1d 100644 --- a/src/test/compile-fail/borrow-tuple-fields.rs +++ b/src/test/compile-fail/borrow-tuple-fields.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - struct Foo(Box, int); struct Bar(int, int); diff --git a/src/test/compile-fail/if-let.rs b/src/test/compile-fail/if-let.rs index b82fb7a94c95f..88b6854bb1d2c 100644 --- a/src/test/compile-fail/if-let.rs +++ b/src/test/compile-fail/if-let.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(macro_rules,if_let)] +#![feature(macro_rules)] fn macros() { macro_rules! foo{ diff --git a/src/test/compile-fail/issue-18566.rs b/src/test/compile-fail/issue-18566.rs index 89b1d8540d8c5..f64d8fee2d8b3 100644 --- a/src/test/compile-fail/issue-18566.rs +++ b/src/test/compile-fail/issue-18566.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - struct MyPtr<'a>(&'a mut uint); impl<'a> Deref for MyPtr<'a> { fn deref<'b>(&'b self) -> &'b uint { self.0 } diff --git a/src/test/compile-fail/issue-19121.rs b/src/test/compile-fail/issue-19121.rs new file mode 100644 index 0000000000000..998c6a8253539 --- /dev/null +++ b/src/test/compile-fail/issue-19121.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 that a partially specified trait object with unspecified associated +// type does not ICE. + +#![feature(associated_types)] + +trait Foo { + type A; +} + +fn bar(x: &Foo) {} //~ERROR missing type for associated type `A` + +pub fn main() {} diff --git a/src/test/compile-fail/issue-19244-1.rs b/src/test/compile-fail/issue-19244-1.rs index 4fcbb87889054..7ca83f21305f1 100644 --- a/src/test/compile-fail/issue-19244-1.rs +++ b/src/test/compile-fail/issue-19244-1.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - const TUP: (uint,) = (42,); fn main() { diff --git a/src/test/compile-fail/issue-5806.rs b/src/test/compile-fail/issue-5806.rs index 702f02c721d86..597366a1b35df 100644 --- a/src/test/compile-fail/issue-5806.rs +++ b/src/test/compile-fail/issue-5806.rs @@ -18,9 +18,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-freebsd FIXME #12460 - #[path = "../compile-fail"] -mod foo; //~ ERROR: illegal operation on a directory +mod foo; //~ ERROR: a directory fn main() {} diff --git a/src/test/compile-fail/lint-unnecessary-parens.rs b/src/test/compile-fail/lint-unnecessary-parens.rs index 826a4ea5a8080..b71effa6f861b 100644 --- a/src/test/compile-fail/lint-unnecessary-parens.rs +++ b/src/test/compile-fail/lint-unnecessary-parens.rs @@ -9,7 +9,6 @@ // except according to those terms. #![deny(unused_parens)] -#![feature(if_let,while_let)] #[deriving(Eq, PartialEq)] struct X { y: bool } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index d9bf722f73e42..b1a6c82a734fe 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -18,8 +18,8 @@ use std::mem::*; // shouldn't get errors for not using // everything imported // Should get errors for both 'Some' and 'None' -use std::option::{Some, None}; //~ ERROR unused import - //~^ ERROR unused import +use std::option::Option::{Some, None}; //~ ERROR unused import + //~^ ERROR unused import use test::A; //~ ERROR unused import // Be sure that if we just bring some methods into scope that they're also diff --git a/src/test/compile-fail/move-fragments-1.rs b/src/test/compile-fail/move-fragments-1.rs index ccf12cf79e1d6..e45862a7fc6e4 100644 --- a/src/test/compile-fail/move-fragments-1.rs +++ b/src/test/compile-fail/move-fragments-1.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - // Test that we correctly compute the move fragments for a fn. // // Note that the code below is not actually incorrect; the diff --git a/src/test/compile-fail/move-out-of-tuple-field.rs b/src/test/compile-fail/move-out-of-tuple-field.rs index 7f55a78e8b784..7fcb54e04672d 100644 --- a/src/test/compile-fail/move-out-of-tuple-field.rs +++ b/src/test/compile-fail/move-out-of-tuple-field.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - struct Foo(Box); fn main() { diff --git a/src/test/compile-fail/new-unicode-escapes-1.rs b/src/test/compile-fail/new-unicode-escapes-1.rs new file mode 100644 index 0000000000000..f2422830a21cc --- /dev/null +++ b/src/test/compile-fail/new-unicode-escapes-1.rs @@ -0,0 +1,13 @@ +// 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. + +pub fn main() { + let s = "\u{2603"; //~ ERROR unterminated unicode escape (needed a `}`) +} diff --git a/src/test/compile-fail/new-unicode-escapes-2.rs b/src/test/compile-fail/new-unicode-escapes-2.rs new file mode 100644 index 0000000000000..5da8674c37ea5 --- /dev/null +++ b/src/test/compile-fail/new-unicode-escapes-2.rs @@ -0,0 +1,13 @@ +// 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. + +pub fn main() { + let s = "\u{260311111111}"; //~ ERROR overlong unicode escape (can have at most 6 hex digits) +} diff --git a/src/test/compile-fail/new-unicode-escapes-3.rs b/src/test/compile-fail/new-unicode-escapes-3.rs new file mode 100644 index 0000000000000..7c64d02efd746 --- /dev/null +++ b/src/test/compile-fail/new-unicode-escapes-3.rs @@ -0,0 +1,13 @@ +// 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. + +pub fn main() { + let s = "\u{d805}"; //~ ERROR illegal unicode character escape +} diff --git a/src/test/compile-fail/new-unicode-escapes-4.rs b/src/test/compile-fail/new-unicode-escapes-4.rs new file mode 100644 index 0000000000000..ffc2b11e0c13c --- /dev/null +++ b/src/test/compile-fail/new-unicode-escapes-4.rs @@ -0,0 +1,13 @@ +// 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. + +pub fn main() { + let s = "\u{lol}"; //~ ERROR illegal character in unicode escape +} diff --git a/src/test/compile-fail/trailing-comma-array-repeat.rs b/src/test/compile-fail/trailing-comma-array-repeat.rs new file mode 100644 index 0000000000000..dadd657158384 --- /dev/null +++ b/src/test/compile-fail/trailing-comma-array-repeat.rs @@ -0,0 +1,13 @@ +// 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() { + let [_, ..,] = [(), ()]; //~ ERROR unexpected token: `]` +} diff --git a/src/test/compile-fail/tuple-index-not-tuple.rs b/src/test/compile-fail/tuple-index-not-tuple.rs index d4ef0e20b266d..33aeebb369166 100644 --- a/src/test/compile-fail/tuple-index-not-tuple.rs +++ b/src/test/compile-fail/tuple-index-not-tuple.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - struct Point { x: int, y: int } struct Empty; diff --git a/src/test/compile-fail/tuple-index-out-of-bounds.rs b/src/test/compile-fail/tuple-index-out-of-bounds.rs index f9bf2746794ac..609e34f2274b7 100644 --- a/src/test/compile-fail/tuple-index-out-of-bounds.rs +++ b/src/test/compile-fail/tuple-index-out-of-bounds.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(tuple_indexing)] - struct Point(int, int); fn main() { diff --git a/src/test/compile-fail/while-let.rs b/src/test/compile-fail/while-let.rs index 0dd442ec3f66a..ccf3d2dd75076 100644 --- a/src/test/compile-fail/while-let.rs +++ b/src/test/compile-fail/while-let.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(macro_rules,while_let)] +#![feature(macro_rules)] fn macros() { macro_rules! foo{ diff --git a/src/test/debuginfo/gdb-pretty-struct-and-enums.rs b/src/test/debuginfo/gdb-pretty-struct-and-enums.rs index 9a42cd92fdc87..76cf3c1149dd5 100644 --- a/src/test/debuginfo/gdb-pretty-struct-and-enums.rs +++ b/src/test/debuginfo/gdb-pretty-struct-and-enums.rs @@ -58,11 +58,17 @@ // gdb-command: print none // gdb-check:$12 = None +// gdb-command: print some_fat +// gdb-check:$13 = Some = {"abc"} + +// gdb-command: print none_fat +// gdb-check:$14 = None + // gdb-command: print nested_variant1 -// gdb-check:$13 = NestedVariant1 = {NestedStruct = {regular_struct = RegularStruct = {the_first_field = 111, the_second_field = 112.5, the_third_field = true, the_fourth_field = "NestedStructString1"}, tuple_struct = TupleStruct = {113.5, 114}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar2, mixed_enum = MixedEnumTupleVar = {115, 116, false}}} +// gdb-check:$15 = NestedVariant1 = {NestedStruct = {regular_struct = RegularStruct = {the_first_field = 111, the_second_field = 112.5, the_third_field = true, the_fourth_field = "NestedStructString1"}, tuple_struct = TupleStruct = {113.5, 114}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar2, mixed_enum = MixedEnumTupleVar = {115, 116, false}}} // gdb-command: print nested_variant2 -// gdb-check:$14 = NestedVariant2 = {abc = NestedStruct = {regular_struct = RegularStruct = {the_first_field = 117, the_second_field = 118.5, the_third_field = false, the_fourth_field = "NestedStructString10"}, tuple_struct = TupleStruct = {119.5, 120}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar3, mixed_enum = MixedEnumStructVar = {field1 = 121.5, field2 = -122}}} +// gdb-check:$16 = NestedVariant2 = {abc = NestedStruct = {regular_struct = RegularStruct = {the_first_field = 117, the_second_field = 118.5, the_third_field = false, the_fourth_field = "NestedStructString10"}, tuple_struct = TupleStruct = {119.5, 120}, empty_struct = EmptyStruct, c_style_enum = CStyleEnumVar3, mixed_enum = MixedEnumStructVar = {field1 = 121.5, field2 = -122}}} use self::CStyleEnum::{CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3}; use self::MixedEnum::{MixedEnumCStyleVar, MixedEnumTupleVar, MixedEnumStructVar}; @@ -129,6 +135,8 @@ fn main() { let some = Some(110u); let none: Option = None; + let some_fat = Some("abc"); + let none_fat: Option<&'static str> = None; let nested_variant1 = NestedVariant1( NestedStruct { diff --git a/src/test/debuginfo/option-like-enum.rs b/src/test/debuginfo/option-like-enum.rs index 11c594bac599a..333a430e35111 100644 --- a/src/test/debuginfo/option-like-enum.rs +++ b/src/test/debuginfo/option-like-enum.rs @@ -61,6 +61,12 @@ // lldb-command:print void_droid // lldb-check:[...]$5 = Void +// lldb-command:print some_str +// lldb-check:[...]$6 = Some(&str { data_ptr: [...], length: 3 }) + +// lldb-command:print none_str +// lldb-check:[...]$7 = None + // If a struct has exactly two variants, one of them is empty, and the other one // contains a non-nullable pointer, then this value is used as the discriminator. @@ -96,6 +102,9 @@ struct NamedFieldsRepr<'a> { fn main() { + let some_str: Option<&'static str> = Some("abc"); + let none_str: Option<&'static str> = None; + let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678u) }); let none: Option<&u32> = None; diff --git a/src/test/run-fail/result-get-panic.rs b/src/test/run-fail/result-get-panic.rs index 6098b97c79a94..df14efd6c3a97 100644 --- a/src/test/run-fail/result-get-panic.rs +++ b/src/test/run-fail/result-get-panic.rs @@ -10,8 +10,8 @@ // error-pattern:called `Result::unwrap()` on an `Err` value -use std::result; +use std::result::Result::Err; fn main() { - println!("{}", result::Err::("kitty".to_string()).unwrap()); + println!("{}", Err::("kitty".to_string()).unwrap()); } diff --git a/src/test/run-pass/deriving-cmp-shortcircuit.rs b/src/test/run-pass/deriving-cmp-shortcircuit.rs index fd59b804da376..b68d8058381d2 100644 --- a/src/test/run-pass/deriving-cmp-shortcircuit.rs +++ b/src/test/run-pass/deriving-cmp-shortcircuit.rs @@ -39,5 +39,5 @@ pub fn main() { assert!(a != b); assert!(a < b); - assert_eq!(a.cmp(&b), ::std::cmp::Less); + assert_eq!(a.cmp(&b), ::std::cmp::Ordering::Less); } diff --git a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs index 1187a9a8bc4a7..d63c264479a93 100644 --- a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs +++ b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs @@ -10,7 +10,7 @@ // ignore-test FIXME #11820: & is unreliable in deriving -use std::cmp::{Less,Equal,Greater}; +use std::cmp::Ordering::{Less,Equal,Greater}; #[deriving(Eq,Ord)] struct A<'a> { diff --git a/src/test/run-pass/enum-nullable-const-null-with-fields.rs b/src/test/run-pass/enum-nullable-const-null-with-fields.rs index a48f3bcd59ca4..4b839d740fc7a 100644 --- a/src/test/run-pass/enum-nullable-const-null-with-fields.rs +++ b/src/test/run-pass/enum-nullable-const-null-with-fields.rs @@ -8,7 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::result::{Result,Ok}; +use std::result::Result; +use std::result::Result::Ok; static C: Result<(), Box> = Ok(()); diff --git a/src/test/run-pass/eq-multidispatch.rs b/src/test/run-pass/eq-multidispatch.rs new file mode 100644 index 0000000000000..018e8cddc71c6 --- /dev/null +++ b/src/test/run-pass/eq-multidispatch.rs @@ -0,0 +1,37 @@ +// 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. + +#![feature(default_type_params)] + +#[deriving(PartialEq)] +struct Bar; +struct Baz; +struct Foo; +struct Fu; + +impl PartialEq for Baz { fn eq(&self, _: &Baz) -> bool { true } } + +impl PartialEq for Foo { fn eq(&self, _: &Fu) -> bool { true } } +impl PartialEq for Fu { fn eq(&self, _: &Foo) -> bool { true } } + +impl PartialEq for Foo { fn eq(&self, _: &Bar) -> bool { false } } +impl PartialEq for Bar { fn eq(&self, _: &Foo) -> bool { false } } + +fn main() { + assert!(Bar != Foo); + assert!(Foo != Bar); + + assert!(Bar == Bar); + + assert!(Baz == Baz); + + assert!(Foo == Fu); + assert!(Fu == Foo); +} diff --git a/src/test/run-pass/issue-15080.rs b/src/test/run-pass/issue-15080.rs index c2c370ae504c7..76b8463a41701 100644 --- a/src/test/run-pass/issue-15080.rs +++ b/src/test/run-pass/issue-15080.rs @@ -26,5 +26,5 @@ fn main() { break } } - assert!(result.as_slice() == &[2, 4]); + assert!(result == [2, 4]); } diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index ec19b95ab1a48..6f1f2cea8ec3c 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -24,14 +24,14 @@ enum object { fn lookup(table: json::Object, key: String, default: String) -> String { match table.find(&key.to_string()) { - option::Some(&Json::String(ref s)) => { + option::Option::Some(&Json::String(ref s)) => { s.to_string() } - option::Some(value) => { + option::Option::Some(value) => { println!("{} was expected to be a string but is a {}", key, value); default } - option::None => { + option::Option::None => { default } } diff --git a/src/test/run-pass/issue-3424.rs b/src/test/run-pass/issue-3424.rs index 2dac64b2ec81f..81efacb9bcbad 100644 --- a/src/test/run-pass/issue-3424.rs +++ b/src/test/run-pass/issue-3424.rs @@ -20,7 +20,7 @@ type rsrc_loader = proc(path: &Path):'static -> result::Result; fn tester() { let loader: rsrc_loader = proc(_path) { - result::Ok("more blah".to_string()) + result::Result::Ok("more blah".to_string()) }; let path = path::Path::new("blah"); diff --git a/src/test/run-pass/issue-7784.rs b/src/test/run-pass/issue-7784.rs index f0310cd8df3c8..666847517efde 100644 --- a/src/test/run-pass/issue-7784.rs +++ b/src/test/run-pass/issue-7784.rs @@ -33,6 +33,6 @@ fn main() { let out = bar("baz", "foo"); let [a, xs.., d] = out; assert_eq!(a, "baz"); - assert!(xs == &["foo", "foo"]); + assert!(xs == ["foo", "foo"]); assert_eq!(d, "baz"); } diff --git a/src/test/run-pass/new-unicode-escapes.rs b/src/test/run-pass/new-unicode-escapes.rs new file mode 100644 index 0000000000000..2888389bcceab --- /dev/null +++ b/src/test/run-pass/new-unicode-escapes.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. + +pub fn main() { + let s = "\u{2603}"; + assert_eq!(s, "☃"); + + let s = "\u{2a10}\u{2A01}\u{2Aa0}"; + assert_eq!(s, "⨐⨁⪠"); + + let s = "\\{20}"; + let mut correct_s = String::from_str("\\"); + correct_s.push_str("{20}"); + assert_eq!(s, correct_s.as_slice()); +} diff --git a/src/test/run-pass/nullable-pointer-iotareduction.rs b/src/test/run-pass/nullable-pointer-iotareduction.rs index 520d067bca326..da1ad094df6a0 100644 --- a/src/test/run-pass/nullable-pointer-iotareduction.rs +++ b/src/test/run-pass/nullable-pointer-iotareduction.rs @@ -41,9 +41,9 @@ macro_rules! check_option { check_option!($e: $T, |ptr| assert!(*ptr == $e)); }}; ($e:expr: $T:ty, |$v:ident| $chk:expr) => {{ - assert!(option::None::<$T>.is_none()); + assert!(option::Option::None::<$T>.is_none()); let e = $e; - let s_ = option::Some::<$T>(e); + let s_ = option::Option::Some::<$T>(e); let $v = s_.as_ref().unwrap(); $chk }} diff --git a/src/test/run-pass/regions-link-fn-args.rs b/src/test/run-pass/regions-link-fn-args.rs new file mode 100644 index 0000000000000..2823622bdf6d9 --- /dev/null +++ b/src/test/run-pass/regions-link-fn-args.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 that region inference correctly links up the regions when a +// `ref` borrow occurs inside a fn argument. + +#![allow(dead_code)] + +fn with<'a>(_: |&'a Vec| -> &'a Vec) { } + +fn foo() { + with(|&ref ints| ints); +} + +fn main() { } diff --git a/src/test/run-pass/send_str_hashmap.rs b/src/test/run-pass/send_str_hashmap.rs index ef485723c7e2b..1b0f2ec0a327f 100644 --- a/src/test/run-pass/send_str_hashmap.rs +++ b/src/test/run-pass/send_str_hashmap.rs @@ -11,7 +11,7 @@ extern crate collections; use std::collections::HashMap; -use std::option::Some; +use std::option::Option::Some; use std::str::SendStr; pub fn main() { diff --git a/src/test/run-pass/send_str_treemap.rs b/src/test/run-pass/send_str_treemap.rs index f72ca109b6e68..9334b673b515e 100644 --- a/src/test/run-pass/send_str_treemap.rs +++ b/src/test/run-pass/send_str_treemap.rs @@ -11,7 +11,7 @@ extern crate collections; use self::collections::TreeMap; -use std::option::Some; +use std::option::Option::Some; use std::str::SendStr; use std::string::ToString; diff --git a/src/test/run-pass/trailing-comma.rs b/src/test/run-pass/trailing-comma.rs index 5e93f8eedb7eb..00e050640805b 100644 --- a/src/test/run-pass/trailing-comma.rs +++ b/src/test/run-pass/trailing-comma.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(advanced_slice_patterns,)] + fn f(_: T,) {} struct Foo; @@ -24,9 +26,13 @@ enum Baz { Qux(int,), } +#[allow(unused,)] pub fn main() { f::(0i,); let (_, _,) = (1i, 1i,); + let [_, _,] = [1i, 1,]; + let [_, _, .., _,] = [1i, 1, 1, 1,]; + let [_, _, _.., _,] = [1i, 1, 1, 1,]; let x: Foo = Foo::;