]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #22952 - huonw:missing-stable, r=alexcrichton
authorManish Goregaokar <manishsmail@gmail.com>
Tue, 3 Mar 2015 08:43:09 +0000 (14:13 +0530)
committerManish Goregaokar <manishsmail@gmail.com>
Tue, 3 Mar 2015 11:32:22 +0000 (17:02 +0530)
 Unstable is the conservative choice.

cc #22950.

172 files changed:
src/compiletest/runtest.rs
src/compiletest/util.rs
src/doc/intro.md
src/doc/reference.md
src/doc/trpl/guessing-game.md
src/etc/unicode.py
src/liballoc/arc.rs
src/libcollections/bit.rs
src/libcollections/enum_set.rs
src/libcollections/fmt.rs
src/libcollections/slice.rs
src/libcollections/str.rs
src/libcollections/string.rs
src/libcollections/vec.rs
src/libcollections/vec_deque.rs
src/libcore/atomic.rs
src/libcore/fmt/float.rs
src/libcore/fmt/num.rs
src/libcore/hash/mod.rs
src/libcore/iter.rs
src/libcore/lib.rs
src/libcore/num/f32.rs
src/libcore/num/f64.rs
src/libcore/num/int.rs [deleted file]
src/libcore/num/int_macros.rs
src/libcore/num/mod.rs
src/libcore/num/uint.rs [deleted file]
src/libcore/num/uint_macros.rs
src/libcore/raw.rs
src/libcore/slice.rs
src/libcore/str/mod.rs
src/libcoretest/iter.rs
src/libcoretest/num/int.rs [deleted file]
src/libcoretest/num/int_macros.rs
src/libcoretest/num/mod.rs
src/libcoretest/num/uint.rs [deleted file]
src/libcoretest/num/uint_macros.rs
src/libflate/lib.rs
src/libgetopts/lib.rs
src/libgraphviz/lib.rs
src/liblibc/lib.rs
src/librand/distributions/mod.rs
src/librand/isaac.rs
src/librand/lib.rs
src/librand/rand_impls.rs
src/librand/reseeding.rs
src/librbml/io.rs
src/librbml/lib.rs
src/librustc/lint/context.rs
src/librustc/lint/mod.rs
src/librustc/metadata/common.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/filesearch.rs
src/librustc/metadata/tydecode.rs
src/librustc/metadata/tyencode.rs
src/librustc/middle/astencode.rs
src/librustc/middle/dataflow.rs
src/librustc/middle/fast_reject.rs
src/librustc/middle/infer/combine.rs
src/librustc/middle/lang_items.rs
src/librustc/middle/liveness.rs
src/librustc/middle/mem_categorization.rs
src/librustc/middle/region.rs
src/librustc/middle/traits/project.rs
src/librustc/middle/traits/select.rs
src/librustc/middle/ty.rs
src/librustc/middle/ty_fold.rs
src/librustc/middle/ty_walk.rs
src/librustc/util/ppaux.rs
src/librustc_back/archive.rs
src/librustc_back/fs.rs
src/librustc_borrowck/borrowck/mod.rs
src/librustc_borrowck/borrowck/move_data.rs
src/librustc_driver/lib.rs
src/librustc_driver/test.rs
src/librustc_lint/builtin.rs
src/librustc_privacy/lib.rs
src/librustc_trans/back/link.rs
src/librustc_trans/trans/_match.rs
src/librustc_trans/trans/adt.rs
src/librustc_trans/trans/base.rs
src/librustc_trans/trans/callee.rs
src/librustc_trans/trans/closure.rs
src/librustc_trans/trans/datum.rs
src/librustc_trans/trans/debuginfo.rs
src/librustc_trans/trans/glue.rs
src/librustc_trans/trans/meth.rs
src/librustc_typeck/check/callee.rs
src/librustc_typeck/check/closure.rs
src/librustc_typeck/check/dropck.rs
src/librustc_typeck/check/implicator.rs
src/librustc_typeck/check/method/probe.rs
src/librustc_typeck/check/regionck.rs
src/librustc_typeck/coherence/mod.rs
src/librustc_typeck/diagnostics.rs
src/librustdoc/flock.rs
src/librustdoc/lib.rs
src/libserialize/hex.rs
src/libstd/ffi/os_str.rs
src/libstd/io/lazy.rs [new file with mode: 0644]
src/libstd/io/mod.rs
src/libstd/io/stdio.rs [new file with mode: 0644]
src/libstd/lib.rs
src/libstd/net/tcp.rs
src/libstd/num/strconv.rs
src/libstd/old_io/mod.rs
src/libstd/old_io/stdio.rs
src/libstd/process.rs
src/libstd/rand/mod.rs
src/libstd/rand/os.rs
src/libstd/sync/mpsc/mod.rs
src/libstd/sync/mpsc/select.rs
src/libstd/sync/mutex.rs
src/libstd/sync/rwlock.rs
src/libstd/sys/common/wtf8.rs
src/libstd/sys/unix/c.rs
src/libstd/sys/unix/mod.rs
src/libstd/sys/unix/os_str.rs
src/libstd/sys/unix/stdio.rs [new file with mode: 0644]
src/libstd/sys/windows/c.rs
src/libstd/sys/windows/handle.rs
src/libstd/sys/windows/mod.rs
src/libstd/sys/windows/os.rs
src/libstd/sys/windows/os_str.rs
src/libstd/sys/windows/stdio.rs [new file with mode: 0644]
src/libstd/thread.rs
src/libstd/thread_local/scoped.rs
src/libsyntax/abi.rs
src/libsyntax/diagnostic.rs
src/libsyntax/ext/asm.rs
src/libsyntax/feature_gate.rs
src/libsyntax/parse/lexer/comments.rs
src/libsyntax/parse/token.rs
src/libsyntax/print/pp.rs
src/libtest/stats.rs
src/libunicode/tables.rs
src/test/bench/shootout-k-nucleotide.rs
src/test/bench/sudoku.rs
src/test/compile-fail/asm-misplaced-option.rs
src/test/compile-fail/dropck_no_diverge_on_nonregular_1.rs [new file with mode: 0644]
src/test/compile-fail/dropck_no_diverge_on_nonregular_2.rs [new file with mode: 0644]
src/test/compile-fail/dropck_no_diverge_on_nonregular_3.rs [new file with mode: 0644]
src/test/compile-fail/feature-gate-static-assert.rs [new file with mode: 0644]
src/test/compile-fail/huge-array-simple.rs
src/test/compile-fail/issue-22912.rs [new file with mode: 0644]
src/test/compile-fail/issue-4335.rs
src/test/compile-fail/issue-6804.rs
src/test/compile-fail/issue-8460-const.rs
src/test/compile-fail/nonbool_static_assert.rs
src/test/compile-fail/regions-proc-bound-capture.rs
src/test/compile-fail/regions-steal-closure.rs
src/test/compile-fail/send-is-not-static-ensures-scoping.rs
src/test/compile-fail/static-assert.rs
src/test/compile-fail/static-assert2.rs
src/test/compile-fail/unboxed-closure-region.rs
src/test/compile-fail/unnecessary-private.rs
src/test/run-fail/bounds-check-no-overflow.rs
src/test/run-fail/hashmap-capacity-overflow.rs
src/test/run-pass-valgrind/cleanup-stdin.rs
src/test/run-pass/associated-types-binding-in-where-clause.rs
src/test/run-pass/associated-types-eq-obj.rs
src/test/run-pass/associated-types-return.rs
src/test/run-pass/issue-13304.rs
src/test/run-pass/issue-14456.rs
src/test/run-pass/issue-16671.rs
src/test/run-pass/issue-17322.rs
src/test/run-pass/issue-22777.rs [new file with mode: 0644]
src/test/run-pass/issue-4333.rs
src/test/run-pass/macro-attributes.rs
src/test/run-pass/process-spawn-with-unicode-params.rs
src/test/run-pass/static-assert.rs
src/test/run-pass/vector-sort-panic-safe.rs

index 85bbd2cb42e6983ce121cefe047f9ce431dae786..7ac8a9b041c8327f33c8b6a38f2d8d9f518ca56f 100644 (file)
@@ -127,7 +127,7 @@ fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
     };
 
     // The value our Makefile configures valgrind to return on failure
-    static VALGRIND_ERR: int = 100;
+    const VALGRIND_ERR: int = 100;
     if proc_res.status.matches_exit_status(VALGRIND_ERR) {
         fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
     }
@@ -139,7 +139,7 @@ fn run_rfail_test(config: &Config, props: &TestProps, testfile: &Path) {
 
 fn check_correct_failure_status(proc_res: &ProcRes) {
     // The value the rust runtime returns on failure
-    static RUST_ERR: int = 101;
+    const RUST_ERR: int = 101;
     if !proc_res.status.matches_exit_status(RUST_ERR) {
         fatal_proc_rec(
             &format!("failure produced the wrong error: {:?}",
index 778629dd2028f53ed838dd533198e2705045c358..c0d7c59ef6a1bbf2c1fdc42a002c31cda8a52562 100644 (file)
@@ -14,7 +14,7 @@
 use std::env;
 
 /// Conversion table from triple OS name to Rust SYSNAME
-static OS_TABLE: &'static [(&'static str, &'static str)] = &[
+const OS_TABLE: &'static [(&'static str, &'static str)] = &[
     ("mingw32", "windows"),
     ("win32", "windows"),
     ("windows", "windows"),
index 07a90959deb693b30fbf629a50d950c9c52cc03c..d145eaada2b0e0f1f81c87bfaf2f3a6ba82d3ea3 100644 (file)
@@ -510,10 +510,10 @@ numbers[1] is 3
 numbers[0] is 2
 ```
 
-Each time, we can get a slithtly different output because the threads
-are not quaranteed to run in any set order. If you get the same order
-every time it is because each of these threads are very small and
-complete too fast for their indeterminate behavior to surface.
+Each time, we can get a slightly different output because the threads are not
+guaranteed to run in any set order. If you get the same order every time it is
+because each of these threads are very small and complete too fast for their
+indeterminate behavior to surface.
 
 The important part here is that the Rust compiler was able to use ownership to
 give us assurance _at compile time_ that we weren't doing something incorrect
index 2f047d2c173f82a5d23b93f4cc2c11624f219644..333d6fddbbdf2f7a6fc27626962be24977b53d8e 100644 (file)
@@ -2495,6 +2495,12 @@ The currently implemented features of the reference compiler are:
 
 * `staged_api` - Allows usage of stability markers and `#![staged_api]` in a crate
 
+* `static_assert` - The `#[static_assert]` functionality is experimental and
+                    unstable. The attribute can be attached to a `static` of
+                    type `bool` and the compiler will error if the `bool` is
+                    `false` at compile time. This version of this functionality
+                    is unintuitive and suboptimal.
+
 * `start` - Allows use of the `#[start]` attribute, which changes the entry point
             into a Rust program. This capabiilty, especially the signature for the
             annotated function, is subject to change.
index a40374fe30fadde9235a6607f6f010307eaf0649..4e7222269a8ff1954f4fcffccd2271e0762816c0 100644 (file)
@@ -422,11 +422,11 @@ In this case, we say `x` is a `u32` explicitly, so Rust is able to properly
 tell `random()` what to generate. In a similar fashion, both of these work:
 
 ```{rust,ignore}
-let input_num = "5".parse::<u32>(); // input_num: Option<u32>
-let input_num: Result<u32, _> = "5".parse(); // input_num: Result<u32, <u32 as FromStr>::Err>
+let input_num_option = "5".parse::<u32>().ok(); // input_num: Option<u32>
+let input_num_result: Result<u32, _> = "5".parse(); // input_num: Result<u32, <u32 as FromStr>::Err>
 ```
 
-Here we're converting the `Result` returned by `parse` to an `Option` by using
+Above, we're converting the `Result` returned by `parse` to an `Option` by using
 the `ok` method as well.  Anyway, with us now converting our input to a number,
 our code looks like this:
 
@@ -470,14 +470,14 @@ Let's try it out!
 ```bash
 $ cargo build
    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
-src/main.rs:22:15: 22:24 error: mismatched types: expected `u32` but found `core::option::Option<u32>` (expected u32 but found enum core::option::Option)
-src/main.rs:22     match cmp(input_num, secret_number) {
+src/main.rs:21:15: 21:24 error: mismatched types: expected `u32`, found `core::result::Result<u32, core::num::ParseIntError>` (expected u32, found enum `core::result::Result`) [E0308]
+src/main.rs:21     match cmp(input_num, secret_number) {
                              ^~~~~~~~~
 error: aborting due to previous error
 ```
 
-Oh yeah! Our `input_num` has the type `Option<u32>`, rather than `u32`. We
-need to unwrap the Option. If you remember from before, `match` is a great way
+Oh yeah! Our `input_num` has the type `Result<u32, <some error>>`, rather than `u32`. We
+need to unwrap the Result. If you remember from before, `match` is a great way
 to do that. Try this code:
 
 ```{rust,no_run}
@@ -500,7 +500,7 @@ fn main() {
     let input_num: Result<u32, _> = input.parse();
 
     let num = match input_num {
-        Ok(num) => num,
+        Ok(n) => n,
         Err(_) => {
             println!("Please input a number!");
             return;
@@ -524,7 +524,7 @@ fn cmp(a: u32, b: u32) -> Ordering {
 }
 ```
 
-We use a `match` to either give us the `u32` inside of the `Option`, or else
+We use a `match` to either give us the `u32` inside of the `Result`, or else
 print an error message and return. Let's give this a shot:
 
 ```bash
index dc8716d1378df6ce3296716f204ad70a444f0c88..5472ba3c7eda118fc60e72af2238aae2dace405b 100755 (executable)
@@ -290,11 +290,11 @@ def emit_bsearch_range_table(f):
 fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
     use core::cmp::Ordering::{Equal, Less, Greater};
     use core::slice::SliceExt;
-    r.binary_search(|&(lo,hi)| {
+    r.binary_search_by(|&(lo,hi)| {
         if lo <= c && c <= hi { Equal }
         else if hi < c { Less }
         else { Greater }
-    }).found().is_some()
+    }).is_ok()
 }\n
 """)
 
@@ -303,7 +303,7 @@ def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
     pub_string = ""
     if is_pub:
         pub_string = "pub "
-    f.write("    %sstatic %s: %s = &[\n" % (pub_string, name, t_type))
+    f.write("    %sconst %s: %s = &[\n" % (pub_string, name, t_type))
     data = ""
     first = True
     for dat in t_data:
@@ -329,14 +329,14 @@ def emit_property_module(f, mod, tbl, emit_fn):
 def emit_regex_module(f, cats, w_data):
     f.write("pub mod regex {\n")
     regex_class = "&'static [(char, char)]"
-    class_table = "&'static [(&'static str, &'static %s)]" % regex_class
+    class_table = "&'static [(&'static str, %s)]" % regex_class
 
     emit_table(f, "UNICODE_CLASSES", cats, class_table,
-        pfun=lambda x: "(\"%s\",&super::%s::%s_table)" % (x[0], x[1], x[0]))
+        pfun=lambda x: "(\"%s\",super::%s::%s_table)" % (x[0], x[1], x[0]))
 
-    f.write("    pub static PERLD: &'static %s = &super::general_category::Nd_table;\n\n"
+    f.write("    pub const PERLD: %s = super::general_category::Nd_table;\n\n"
             % regex_class)
-    f.write("    pub static PERLS: &'static %s = &super::property::White_Space_table;\n\n"
+    f.write("    pub const PERLS: %s = super::property::White_Space_table;\n\n"
             % regex_class)
 
     emit_table(f, "PERLW", w_data, regex_class)
@@ -350,7 +350,7 @@ def emit_conversions_module(f, lowerupper, upperlower):
     use core::slice::SliceExt;
     use core::option::Option;
     use core::option::Option::{Some, None};
-    use core::slice;
+    use core::result::Result::{Ok, Err};
 
     pub fn to_lower(c: char) -> char {
         match bsearch_case_table(c, LuLl_table) {
@@ -367,13 +367,13 @@ def emit_conversions_module(f, lowerupper, upperlower):
     }
 
     fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<usize> {
-        match table.binary_search(|&(key, _)| {
+        match table.binary_search_by(|&(key, _)| {
             if c == key { Equal }
             else if key < c { Less }
             else { Greater }
         }) {
-            slice::BinarySearchResult::Found(i) => Some(i),
-            slice::BinarySearchResult::NotFound(_) => None,
+            Ok(i) => Some(i),
+            Err(_) => None,
         }
     }
 
@@ -386,10 +386,9 @@ def emit_conversions_module(f, lowerupper, upperlower):
 
 def emit_grapheme_module(f, grapheme_table, grapheme_cats):
     f.write("""pub mod grapheme {
-    use core::kinds::Copy;
     use core::slice::SliceExt;
     pub use self::GraphemeCat::*;
-    use core::slice;
+    use core::result::Result::{Ok, Err};
 
     #[allow(non_camel_case_types)]
     #[derive(Clone, Copy)]
@@ -401,16 +400,16 @@ def emit_grapheme_module(f, grapheme_table, grapheme_cats):
 
     fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat {
         use core::cmp::Ordering::{Equal, Less, Greater};
-        match r.binary_search(|&(lo, hi, _)| {
+        match r.binary_search_by(|&(lo, hi, _)| {
             if lo <= c && c <= hi { Equal }
             else if hi < c { Less }
             else { Greater }
         }) {
-            slice::BinarySearchResult::Found(idx) => {
+            Ok(idx) => {
                 let (_, _, cat) = r[idx];
                 cat
             }
-            slice::BinarySearchResult::NotFound(_) => GC_Any
+            Err(_) => GC_Any
         }
     }
 
@@ -430,20 +429,20 @@ def emit_charwidth_module(f, width_table):
     f.write("    use core::option::Option;\n")
     f.write("    use core::option::Option::{Some, None};\n")
     f.write("    use core::slice::SliceExt;\n")
-    f.write("    use core::slice;\n")
+    f.write("    use core::result::Result::{Ok, Err};\n")
     f.write("""
     fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
         use core::cmp::Ordering::{Equal, Less, Greater};
-        match r.binary_search(|&(lo, hi, _, _)| {
+        match r.binary_search_by(|&(lo, hi, _, _)| {
             if lo <= c && c <= hi { Equal }
             else if hi < c { Less }
             else { Greater }
         }) {
-            slice::BinarySearchResult::Found(idx) => {
+            Ok(idx) => {
                 let (_, _, r_ncjk, r_cjk) = r[idx];
                 if is_cjk { r_cjk } else { r_ncjk }
             }
-            slice::BinarySearchResult::NotFound(_) => 1
+            Err(_) => 1
         }
     }
 """)
@@ -530,17 +529,17 @@ def emit_norm_module(f, canon, compat, combine, norm_props):
     fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
         use core::cmp::Ordering::{Equal, Less, Greater};
         use core::slice::SliceExt;
-        use core::slice;
-        match r.binary_search(|&(lo, hi, _)| {
+        use core::result::Result::{Ok, Err};
+        match r.binary_search_by(|&(lo, hi, _)| {
             if lo <= c && c <= hi { Equal }
             else if hi < c { Less }
             else { Greater }
         }) {
-            slice::BinarySearchResult::Found(idx) => {
+            Ok(idx) => {
                 let (_, _, result) = r[idx];
                 result
             }
-            slice::BinarySearchResult::NotFound(_) => 0
+            Err(_) => 0
         }
     }\n
 """)
@@ -609,7 +608,7 @@ if __name__ == "__main__":
             unicode_version = re.search(pattern, readme.read()).groups()
         rf.write("""
 /// The version of [Unicode](http://www.unicode.org/)
-/// that the `UnicodeChar` and `UnicodeStrPrelude` traits are based on.
+/// that the unicode parts of `CharExt` and `UnicodeStrPrelude` traits are based on.
 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
 """ % unicode_version)
         (canon_decomp, compat_decomp, gencats, combines,
index 88a3752c88a1d6774b8b288a2a12f2af0e566e61..c95b413b397edb1fd489298ddde673707e4fce7a 100644 (file)
@@ -201,10 +201,11 @@ pub fn downgrade(&self) -> Weak<T> {
 impl<T> Arc<T> {
     #[inline]
     fn inner(&self) -> &ArcInner<T> {
-        // This unsafety is ok because while this arc is alive we're guaranteed that the inner
-        // pointer is valid. Furthermore, we know that the `ArcInner` structure itself is `Sync`
-        // because the inner data is `Sync` as well, so we're ok loaning out an immutable pointer
-        // to these contents.
+        // This unsafety is ok because while this arc is alive we're guaranteed
+        // that the inner pointer is valid. Furthermore, we know that the
+        // `ArcInner` structure itself is `Sync` because the inner data is
+        // `Sync` as well, so we're ok loaning out an immutable pointer to these
+        // contents.
         unsafe { &**self._ptr }
     }
 }
@@ -236,13 +237,15 @@ impl<T> Clone for Arc<T> {
     /// ```
     #[inline]
     fn clone(&self) -> Arc<T> {
-        // Using a relaxed ordering is alright here, as knowledge of the original reference
-        // prevents other threads from erroneously deleting the object.
+        // Using a relaxed ordering is alright here, as knowledge of the
+        // original reference prevents other threads from erroneously deleting
+        // the object.
         //
-        // As explained in the [Boost documentation][1], Increasing the reference counter can
-        // always be done with memory_order_relaxed: New references to an object can only be formed
-        // from an existing reference, and passing an existing reference from one thread to another
-        // must already provide any required synchronization.
+        // As explained in the [Boost documentation][1], Increasing the
+        // reference counter can always be done with memory_order_relaxed: New
+        // references to an object can only be formed from an existing
+        // reference, and passing an existing reference from one thread to
+        // another must already provide any required synchronization.
         //
         // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
         self.inner().strong.fetch_add(1, Relaxed);
index 5b19de42ac919240167e67892b48ba519dd55b63..8c2a687b17957af72691c810c9e791cc39ebf517 100644 (file)
@@ -189,17 +189,17 @@ fn blocks_for_bits(bits: usize) -> usize {
     //
     // Note that we can technically avoid this branch with the expression
     // `(nbits + u32::BITS - 1) / 32::BITS`, but if nbits is almost usize::MAX this will overflow.
-    if bits % u32::BITS == 0 {
-        bits / u32::BITS
+    if bits % u32::BITS as usize == 0 {
+        bits / u32::BITS as usize
     } else {
-        bits / u32::BITS + 1
+        bits / u32::BITS as usize + 1
     }
 }
 
 /// Computes the bitmask for the final word of the vector
 fn mask_for_bits(bits: usize) -> u32 {
     // Note especially that a perfect multiple of u32::BITS should mask all 1s.
-    !0u32 >> (u32::BITS - bits % u32::BITS) % u32::BITS
+    !0u32 >> (u32::BITS as usize - bits % u32::BITS as usize) % u32::BITS as usize
 }
 
 impl BitVec {
@@ -237,7 +237,7 @@ fn blocks(&self) -> Blocks {
     /// An operation might screw up the unused bits in the last block of the
     /// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
     fn fix_last_block(&mut self) {
-        let extra_bits = self.len() % u32::BITS;
+        let extra_bits = self.len() % u32::BITS as usize;
         if extra_bits > 0 {
             let mask = (1 << extra_bits) - 1;
             let storage_len = self.storage.len();
@@ -313,7 +313,7 @@ pub fn with_capacity(nbits: usize) -> BitVec {
     ///                     false, false, true, false]));
     /// ```
     pub fn from_bytes(bytes: &[u8]) -> BitVec {
-        let len = bytes.len().checked_mul(u8::BITS).expect("capacity overflow");
+        let len = bytes.len().checked_mul(u8::BITS as usize).expect("capacity overflow");
         let mut bit_vec = BitVec::with_capacity(len);
         let complete_words = bytes.len() / 4;
         let extra_bytes = bytes.len() % 4;
@@ -380,8 +380,8 @@ pub fn get(&self, i: usize) -> Option<bool> {
         if i >= self.nbits {
             return None;
         }
-        let w = i / u32::BITS;
-        let b = i % u32::BITS;
+        let w = i / u32::BITS as usize;
+        let b = i % u32::BITS as usize;
         self.storage.get(w).map(|&block|
             (block & (1 << b)) != 0
         )
@@ -407,8 +407,8 @@ pub fn get(&self, i: usize) -> Option<bool> {
                reason = "panic semantics are likely to change in the future")]
     pub fn set(&mut self, i: usize, x: bool) {
         assert!(i < self.nbits);
-        let w = i / u32::BITS;
-        let b = i % u32::BITS;
+        let w = i / u32::BITS as usize;
+        let b = i % u32::BITS as usize;
         let flag = 1 << b;
         let val = if x { self.storage[w] | flag }
                   else { self.storage[w] & !flag };
@@ -789,7 +789,7 @@ pub fn reserve_exact(&mut self, additional: usize) {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn capacity(&self) -> usize {
-        self.storage.capacity().checked_mul(u32::BITS).unwrap_or(usize::MAX)
+        self.storage.capacity().checked_mul(u32::BITS as usize).unwrap_or(usize::MAX)
     }
 
     /// Grows the `BitVec` in-place, adding `n` copies of `value` to the `BitVec`.
@@ -819,7 +819,7 @@ pub fn grow(&mut self, n: usize, value: bool) {
 
         // Correct the old tail word, setting or clearing formerly unused bits
         let old_last_word = blocks_for_bits(self.nbits) - 1;
-        if self.nbits % u32::BITS > 0 {
+        if self.nbits % u32::BITS as usize > 0 {
             let mask = mask_for_bits(self.nbits);
             if value {
                 self.storage[old_last_word] |= !mask;
@@ -868,7 +868,7 @@ pub fn pop(&mut self) -> Option<bool> {
             // (3)
             self.set(i, false);
             self.nbits = i;
-            if self.nbits % u32::BITS == 0 {
+            if self.nbits % u32::BITS as usize == 0 {
                 // (2)
                 self.storage.pop();
             }
@@ -890,7 +890,7 @@ pub fn pop(&mut self) -> Option<bool> {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn push(&mut self, elem: bool) {
-        if self.nbits % u32::BITS == 0 {
+        if self.nbits % u32::BITS as usize == 0 {
             self.storage.push(0);
         }
         let insert_pos = self.nbits;
@@ -1406,7 +1406,7 @@ pub fn shrink_to_fit(&mut self) {
         // Truncate
         let trunc_len = cmp::max(old_len - n, 1);
         bit_vec.storage.truncate(trunc_len);
-        bit_vec.nbits = trunc_len * u32::BITS;
+        bit_vec.nbits = trunc_len * u32::BITS as usize;
     }
 
     /// Iterator over each u32 stored in the `BitSet`.
@@ -1663,7 +1663,7 @@ pub fn symmetric_difference_with(&mut self, other: &BitSet) {
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn len(&self) -> usize  {
-        self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones())
+        self.bit_vec.blocks().fold(0, |acc, n| acc + n.count_ones() as usize)
     }
 
     /// Returns whether there are no bits set in this set
@@ -1831,13 +1831,13 @@ impl<'a> Iterator for TwoBitPositions<'a> {
     fn next(&mut self) -> Option<usize> {
         while self.next_idx < self.set.bit_vec.len() ||
               self.next_idx < self.other.bit_vec.len() {
-            let bit_idx = self.next_idx % u32::BITS;
+            let bit_idx = self.next_idx % u32::BITS as usize;
             if bit_idx == 0 {
                 let s_bit_vec = &self.set.bit_vec;
                 let o_bit_vec = &self.other.bit_vec;
                 // Merging the two words is a bit of an awkward dance since
                 // one BitVec might be longer than the other
-                let word_idx = self.next_idx / u32::BITS;
+                let word_idx = self.next_idx / u32::BITS as usize;
                 let w1 = if word_idx < s_bit_vec.storage.len() {
                              s_bit_vec.storage[word_idx]
                          } else { 0 };
@@ -2441,43 +2441,43 @@ fn test_big_bit_vec_tests() {
 
     #[test]
     fn test_bit_vec_push_pop() {
-        let mut s = BitVec::from_elem(5 * u32::BITS - 2, false);
-        assert_eq!(s.len(), 5 * u32::BITS - 2);
-        assert_eq!(s[5 * u32::BITS - 3], false);
+        let mut s = BitVec::from_elem(5 * u32::BITS as usize - 2, false);
+        assert_eq!(s.len(), 5 * u32::BITS as usize - 2);
+        assert_eq!(s[5 * u32::BITS as usize - 3], false);
         s.push(true);
         s.push(true);
-        assert_eq!(s[5 * u32::BITS - 2], true);
-        assert_eq!(s[5 * u32::BITS - 1], true);
+        assert_eq!(s[5 * u32::BITS as usize - 2], true);
+        assert_eq!(s[5 * u32::BITS as usize - 1], true);
         // Here the internal vector will need to be extended
         s.push(false);
-        assert_eq!(s[5 * u32::BITS], false);
+        assert_eq!(s[5 * u32::BITS as usize], false);
         s.push(false);
-        assert_eq!(s[5 * u32::BITS + 1], false);
-        assert_eq!(s.len(), 5 * u32::BITS + 2);
+        assert_eq!(s[5 * u32::BITS as usize + 1], false);
+        assert_eq!(s.len(), 5 * u32::BITS as usize + 2);
         // Pop it all off
         assert_eq!(s.pop(), Some(false));
         assert_eq!(s.pop(), Some(false));
         assert_eq!(s.pop(), Some(true));
         assert_eq!(s.pop(), Some(true));
-        assert_eq!(s.len(), 5 * u32::BITS - 2);
+        assert_eq!(s.len(), 5 * u32::BITS as usize - 2);
     }
 
     #[test]
     fn test_bit_vec_truncate() {
-        let mut s = BitVec::from_elem(5 * u32::BITS, true);
+        let mut s = BitVec::from_elem(5 * u32::BITS as usize, true);
 
-        assert_eq!(s, BitVec::from_elem(5 * u32::BITS, true));
-        assert_eq!(s.len(), 5 * u32::BITS);
-        s.truncate(4 * u32::BITS);
-        assert_eq!(s, BitVec::from_elem(4 * u32::BITS, true));
-        assert_eq!(s.len(), 4 * u32::BITS);
+        assert_eq!(s, BitVec::from_elem(5 * u32::BITS as usize, true));
+        assert_eq!(s.len(), 5 * u32::BITS as usize);
+        s.truncate(4 * u32::BITS as usize);
+        assert_eq!(s, BitVec::from_elem(4 * u32::BITS as usize, true));
+        assert_eq!(s.len(), 4 * u32::BITS as usize);
         // Truncating to a size > s.len() should be a noop
-        s.truncate(5 * u32::BITS);
-        assert_eq!(s, BitVec::from_elem(4 * u32::BITS, true));
-        assert_eq!(s.len(), 4 * u32::BITS);
-        s.truncate(3 * u32::BITS - 10);
-        assert_eq!(s, BitVec::from_elem(3 * u32::BITS - 10, true));
-        assert_eq!(s.len(), 3 * u32::BITS - 10);
+        s.truncate(5 * u32::BITS as usize);
+        assert_eq!(s, BitVec::from_elem(4 * u32::BITS as usize, true));
+        assert_eq!(s.len(), 4 * u32::BITS as usize);
+        s.truncate(3 * u32::BITS as usize - 10);
+        assert_eq!(s, BitVec::from_elem(3 * u32::BITS as usize - 10, true));
+        assert_eq!(s.len(), 3 * u32::BITS as usize - 10);
         s.truncate(0);
         assert_eq!(s, BitVec::from_elem(0, true));
         assert_eq!(s.len(), 0);
@@ -2485,26 +2485,26 @@ fn test_bit_vec_truncate() {
 
     #[test]
     fn test_bit_vec_reserve() {
-        let mut s = BitVec::from_elem(5 * u32::BITS, true);
+        let mut s = BitVec::from_elem(5 * u32::BITS as usize, true);
         // Check capacity
-        assert!(s.capacity() >= 5 * u32::BITS);
-        s.reserve(2 * u32::BITS);
-        assert!(s.capacity() >= 7 * u32::BITS);
-        s.reserve(7 * u32::BITS);
-        assert!(s.capacity() >= 12 * u32::BITS);
-        s.reserve_exact(7 * u32::BITS);
-        assert!(s.capacity() >= 12 * u32::BITS);
-        s.reserve(7 * u32::BITS + 1);
-        assert!(s.capacity() >= 12 * u32::BITS + 1);
+        assert!(s.capacity() >= 5 * u32::BITS as usize);
+        s.reserve(2 * u32::BITS as usize);
+        assert!(s.capacity() >= 7 * u32::BITS as usize);
+        s.reserve(7 * u32::BITS as usize);
+        assert!(s.capacity() >= 12 * u32::BITS as usize);
+        s.reserve_exact(7 * u32::BITS as usize);
+        assert!(s.capacity() >= 12 * u32::BITS as usize);
+        s.reserve(7 * u32::BITS as usize + 1);
+        assert!(s.capacity() >= 12 * u32::BITS as usize + 1);
         // Check that length hasn't changed
-        assert_eq!(s.len(), 5 * u32::BITS);
+        assert_eq!(s.len(), 5 * u32::BITS as usize);
         s.push(true);
         s.push(false);
         s.push(true);
-        assert_eq!(s[5 * u32::BITS - 1], true);
-        assert_eq!(s[5 * u32::BITS - 0], true);
-        assert_eq!(s[5 * u32::BITS + 1], false);
-        assert_eq!(s[5 * u32::BITS + 2], true);
+        assert_eq!(s[5 * u32::BITS as usize - 1], true);
+        assert_eq!(s[5 * u32::BITS as usize - 0], true);
+        assert_eq!(s[5 * u32::BITS as usize + 1], false);
+        assert_eq!(s[5 * u32::BITS as usize + 2], true);
     }
 
     #[test]
@@ -2544,7 +2544,7 @@ mod bit_vec_bench {
 
     use super::BitVec;
 
-    static BENCH_BITS : usize = 1 << 14;
+    const BENCH_BITS : usize = 1 << 14;
 
     fn rng() -> rand::IsaacRng {
         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@@ -2557,7 +2557,7 @@ fn bench_usize_small(b: &mut Bencher) {
         let mut bit_vec = 0 as usize;
         b.iter(|| {
             for _ in 0..100 {
-                bit_vec |= 1 << ((r.next_u32() as usize) % u32::BITS);
+                bit_vec |= 1 << ((r.next_u32() as usize) % u32::BITS as usize);
             }
             black_box(&bit_vec);
         });
@@ -2590,10 +2590,10 @@ fn bench_bit_set_big_variable(b: &mut Bencher) {
     #[bench]
     fn bench_bit_set_small(b: &mut Bencher) {
         let mut r = rng();
-        let mut bit_vec = BitVec::from_elem(u32::BITS, false);
+        let mut bit_vec = BitVec::from_elem(u32::BITS as usize, false);
         b.iter(|| {
             for _ in 0..100 {
-                bit_vec.set((r.next_u32() as usize) % u32::BITS, true);
+                bit_vec.set((r.next_u32() as usize) % u32::BITS as usize, true);
             }
             black_box(&bit_vec);
         });
@@ -2610,7 +2610,7 @@ fn bench_bit_vec_big_union(b: &mut Bencher) {
 
     #[bench]
     fn bench_bit_vec_small_iter(b: &mut Bencher) {
-        let bit_vec = BitVec::from_elem(u32::BITS, false);
+        let bit_vec = BitVec::from_elem(u32::BITS as usize, false);
         b.iter(|| {
             let mut sum = 0;
             for _ in 0..10 {
@@ -3039,7 +3039,7 @@ mod bit_set_bench {
 
     use super::{BitVec, BitSet};
 
-    static BENCH_BITS : usize = 1 << 14;
+    const BENCH_BITS : usize = 1 << 14;
 
     fn rng() -> rand::IsaacRng {
         let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
@@ -3052,7 +3052,7 @@ fn bench_bit_vecset_small(b: &mut Bencher) {
         let mut bit_vec = BitSet::new();
         b.iter(|| {
             for _ in 0..100 {
-                bit_vec.insert((r.next_u32() as usize) % u32::BITS);
+                bit_vec.insert((r.next_u32() as usize) % u32::BITS as usize);
             }
             black_box(&bit_vec);
         });
index 62dd91915211b85a37aa1295c52ffa6b4439e6b8..4c966c0d44b4d992ab833029f88735d6c339855d 100644 (file)
@@ -78,7 +78,7 @@ pub trait CLike {
 fn bit<E:CLike>(e: &E) -> usize {
     use core::usize;
     let value = e.to_usize();
-    assert!(value < usize::BITS,
+    assert!(value < usize::BITS as usize,
             "EnumSet only supports up to {} variants.", usize::BITS - 1);
     1 << value
 }
@@ -95,7 +95,7 @@ pub fn new() -> EnumSet<E> {
     #[unstable(feature = "collections",
                reason = "matches collection reform specification, waiting for dust to settle")]
     pub fn len(&self) -> usize {
-        self.bits.count_ones()
+        self.bits.count_ones() as usize
     }
 
     /// Returns true if the `EnumSet` is empty.
@@ -250,7 +250,7 @@ fn next(&mut self) -> Option<E> {
     }
 
     fn size_hint(&self) -> (usize, Option<usize>) {
-        let exact = self.bits.count_ones();
+        let exact = self.bits.count_ones() as usize;
         (exact, Some(exact))
     }
 }
index 98673af3c68a84ab3b6e7b3a9cea8094ec8d2796..5a20ba4b49f0f2bd15d683e32f4fd20fe970a5b7 100644 (file)
 //!     * `o` - precedes the argument with a "0o"
 //! * '0' - This is used to indicate for integer formats that the padding should
 //!         both be done with a `0` character as well as be sign-aware. A format
-//!         like `{:08d}` would yield `00000001` for the integer `1`, while the
+//!         like `{:08}` would yield `00000001` for the integer `1`, while the
 //!         same format would yield `-0000001` for the integer `-1`. Notice that
 //!         the negative version has one fewer zero than the positive version.
 //!
index a2924f8fe53082bb2b6ff4843f20abd07a61c57a..f4c8abbcff131d512f10e464305a2ffc215ed7d8 100644 (file)
@@ -1343,8 +1343,8 @@ fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O
 
 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
     // warning: this wildly uses unsafe.
-    static BASE_INSERTION: usize = 32;
-    static LARGE_INSERTION: usize = 16;
+    const BASE_INSERTION: usize = 32;
+    const LARGE_INSERTION: usize = 16;
 
     // FIXME #12092: smaller insertion runs seems to make sorting
     // vectors of large elements a little faster on some platforms,
index 86fcac3e4b8a09ca34e98ab499568c3bb83153f4..599b92d05ddd7e21d3337ae2d9045bd1f082d8d4 100644 (file)
@@ -756,6 +756,7 @@ fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P> {
     /// ```
     #[unstable(feature = "collections")]
     #[deprecated(since = "1.0.0", reason = "use `split()` with a `&str`")]
+    #[allow(deprecated) /* for SplitStr */]
     fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P> {
         core_str::StrExt::split_str(&self[..], pat)
     }
index 94abffa3db61cf6c33d24e87807af67e419fe1a1..33189bd68bdc64782e0798808ac9b3cb945888ec 100644 (file)
@@ -153,8 +153,8 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> {
             }
         }
 
-        static TAG_CONT_U8: u8 = 128u8;
-        static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
+        const TAG_CONT_U8: u8 = 128u8;
+        const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8
         let total = v.len();
         fn unsafe_get(xs: &[u8], i: usize) -> u8 {
             unsafe { *xs.get_unchecked(i) }
index 805e4623396b849b22041fc1281d42b3406f7067..a4d39974c70135338f8c5881c978caef8dc9a5e8 100644 (file)
@@ -1499,9 +1499,9 @@ fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
 __impl_slice_eq1! { Vec<A>, Vec<B> }
 __impl_slice_eq2! { Vec<A>, &'b [B] }
 __impl_slice_eq2! { Vec<A>, &'b mut [B] }
-__impl_slice_eq2! { CowVec<'a, A>, &'b [B], Clone }
-__impl_slice_eq2! { CowVec<'a, A>, &'b mut [B], Clone }
-__impl_slice_eq2! { CowVec<'a, A>, Vec<B>, Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, &'b [B], Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B], Clone }
+__impl_slice_eq2! { Cow<'a, [A]>, Vec<B>, Clone }
 
 macro_rules! array_impls {
     ($($N: expr)+) => {
@@ -1510,9 +1510,9 @@ macro_rules! array_impls {
             __impl_slice_eq2! { Vec<A>, [B; $N] }
             __impl_slice_eq2! { Vec<A>, &'b [B; $N] }
             // __impl_slice_eq2! { Vec<A>, &'b mut [B; $N] }
-            // __impl_slice_eq2! { CowVec<'a, A>, [B; $N], Clone }
-            // __impl_slice_eq2! { CowVec<'a, A>, &'b [B; $N], Clone }
-            // __impl_slice_eq2! { CowVec<'a, A>, &'b mut [B; $N], Clone }
+            // __impl_slice_eq2! { Cow<'a, [A]>, [B; $N], Clone }
+            // __impl_slice_eq2! { Cow<'a, [A]>, &'b [B; $N], Clone }
+            // __impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
         )+
     }
 }
index abcc0cef9f1feae7ad86e659f1475133de50a471..59ec066b83ed4f6263787f74e8f4a19ba76624d5 100644 (file)
@@ -39,8 +39,8 @@
 #[unstable(feature = "collections")]
 pub use VecDeque as RingBuf;
 
-static INITIAL_CAPACITY: usize = 7; // 2^3 - 1
-static MINIMUM_CAPACITY: usize = 1; // 2 - 1
+const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
+const MINIMUM_CAPACITY: usize = 1; // 2 - 1
 
 /// `VecDeque` is a growable ring buffer, which can be used as a
 /// double-ended queue efficiently.
index 38e2bd98ef9e3d64629f9e247850a376c5d2ba6a..c316236a8041291efd6ff1b588ecab8325b21921 100644 (file)
@@ -1067,6 +1067,7 @@ pub struct AtomicInt {
     v: UnsafeCell<int>,
 }
 
+#[allow(deprecated)]
 unsafe impl Sync for AtomicInt {}
 
 #[unstable(feature = "core")]
@@ -1077,6 +1078,7 @@ pub struct AtomicUint {
     v: UnsafeCell<uint>,
 }
 
+#[allow(deprecated)]
 unsafe impl Sync for AtomicUint {}
 
 #[unstable(feature = "core")]
index f92e631c1f25c4becc028f0056484346b26fa603..2eeb564859cbcd2cf555b93c59d0eaf2d57830a7 100644 (file)
@@ -53,7 +53,7 @@ pub enum SignFormat {
     SignNeg
 }
 
-static DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
+const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
 
 /// Converts a number to its string representation as a byte vector.
 /// This is meant to be a common base implementation for all numeric string
@@ -156,7 +156,7 @@ pub fn float_to_str_bytes_common<T: Float, U, F>(
         deccum = deccum / radix_gen;
         deccum = deccum.trunc();
 
-        let c = char::from_digit(current_digit.to_int().unwrap() as u32, radix);
+        let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix);
         buf[end] = c.unwrap() as u8;
         end += 1;
 
@@ -211,7 +211,7 @@ pub fn float_to_str_bytes_common<T: Float, U, F>(
             // See note in first loop.
             let current_digit = deccum.trunc().abs();
 
-            let c = char::from_digit(current_digit.to_int().unwrap() as u32,
+            let c = char::from_digit(current_digit.to_isize().unwrap() as u32,
                                      radix);
             buf[end] = c.unwrap() as u8;
             end += 1;
index 0175e21c8da6152b47bfbbae924118a19bc3bc64..045442e28ac5dfc57161dc0ec3302054c685139a 100644 (file)
@@ -84,7 +84,7 @@ fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
 
 /// A hexadecimal (base 16) radix, formatted with upper-case characters
 #[derive(Clone, PartialEq)]
-pub struct UpperHex;
+struct UpperHex;
 
 macro_rules! radix {
     ($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
@@ -156,7 +156,7 @@ pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
 }
 
 macro_rules! radix_fmt {
-    ($T:ty as $U:ty, $fmt:ident, $S:expr) => {
+    ($T:ty as $U:ty, $fmt:ident) => {
         #[stable(feature = "rust1", since = "1.0.0")]
         impl fmt::Debug for RadixFmt<$T, Radix> {
             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -182,8 +182,8 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-macro_rules! show {
-    ($T:ident with $S:expr) => {
+macro_rules! debug {
+    ($T:ident) => {
         #[stable(feature = "rust1", since = "1.0.0")]
         impl fmt::Debug for $T {
             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -194,27 +194,24 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 }
 macro_rules! integer {
     ($Int:ident, $Uint:ident) => {
-        integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
-    };
-    ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
         int_base! { Display  for $Int as $Int   -> Decimal }
         int_base! { Binary   for $Int as $Uint  -> Binary }
         int_base! { Octal    for $Int as $Uint  -> Octal }
         int_base! { LowerHex for $Int as $Uint  -> LowerHex }
         int_base! { UpperHex for $Int as $Uint  -> UpperHex }
-        radix_fmt! { $Int as $Int, fmt_int, $SI }
-        show! { $Int with $SI }
+        radix_fmt! { $Int as $Int, fmt_int }
+        debug! { $Int }
 
         int_base! { Display  for $Uint as $Uint -> Decimal }
         int_base! { Binary   for $Uint as $Uint -> Binary }
         int_base! { Octal    for $Uint as $Uint -> Octal }
         int_base! { LowerHex for $Uint as $Uint -> LowerHex }
         int_base! { UpperHex for $Uint as $Uint -> UpperHex }
-        radix_fmt! { $Uint as $Uint, fmt_int, $SU }
-        show! { $Uint with $SU }
+        radix_fmt! { $Uint as $Uint, fmt_int }
+        debug! { $Uint }
     }
 }
-integer! { isize, usize, "i", "u" }
+integer! { isize, usize }
 integer! { i8, u8 }
 integer! { i16, u16 }
 integer! { i32, u32 }
index edc4b7e10ee49b04b024a3b3076d2f425f12358a..4b545435ea171345a5041daf53a2b260a7231bfd 100644 (file)
@@ -182,7 +182,7 @@ fn hash<H: Hasher>(&self, state: &mut H) {
                 }
 
                 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
-                    let newlen = data.len() * ::$ty::BYTES;
+                    let newlen = data.len() * ::$ty::BYTES as usize;
                     let ptr = data.as_ptr() as *const u8;
                     state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
                 }
index 57a6613debd583d4d3cbaf550548f84f02809c55..13d219ec674bce849ed942cd4f1e14a9ca814098 100644 (file)
@@ -2469,7 +2469,7 @@ fn size_hint(&self) -> (usize, Option<usize>) {
             Some(a) => {
                 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
                 match sz {
-                    Some(Some(bound)) => bound.to_uint(),
+                    Some(Some(bound)) => bound.to_usize(),
                     _ => None,
                 }
             },
@@ -2477,7 +2477,7 @@ fn size_hint(&self) -> (usize, Option<usize>) {
                 Some(a) => {
                     let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
                     match sz {
-                        Some(Some(bound)) => bound.to_uint(),
+                        Some(Some(bound)) => bound.to_usize(),
                         _ => None
                     }
                 },
@@ -2743,7 +2743,7 @@ fn size_hint(&self) -> (usize, Option<usize>) {
         if self.start >= self.end {
             (0, Some(0))
         } else {
-            let length = (self.end - self.start).to_uint();
+            let length = (self.end - self.start).to_usize();
             (length.unwrap_or(0), length)
         }
     }
index a9d699735908529c52614531693ecc54adacbed7..7cc963bed358f9aa666ff401bc3f520a3d84109a 100644 (file)
@@ -39,7 +39,7 @@
 //!   distribution.
 //!
 //! * `rust_begin_unwind` - This function takes three arguments, a
-//!   `fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate
+//!   `fmt::Arguments`, a `&str`, and a `usize`. These three arguments dictate
 //!   the panic message, the file at which panic was invoked, and the line.
 //!   It is up to consumers of this core library to define this panic
 //!   function; it is only required to never return.
 #[macro_use]
 mod uint_macros;
 
-#[path = "num/int.rs"]  pub mod int;
 #[path = "num/isize.rs"]  pub mod isize;
 #[path = "num/i8.rs"]   pub mod i8;
 #[path = "num/i16.rs"]  pub mod i16;
 #[path = "num/i32.rs"]  pub mod i32;
 #[path = "num/i64.rs"]  pub mod i64;
 
-#[path = "num/uint.rs"] pub mod uint;
 #[path = "num/usize.rs"] pub mod usize;
 #[path = "num/u8.rs"]   pub mod u8;
 #[path = "num/u16.rs"]  pub mod u16;
index b542c9d47f7d4a386d9ac5148b7275ae245d008b..0d8e3044eccea1374cb06a9c54737cbc45d202b5 100644 (file)
 use option::Option;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const RADIX: uint = 2;
+pub const RADIX: u32 = 2;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MANTISSA_DIGITS: uint = 24;
+pub const MANTISSA_DIGITS: u32 = 24;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const DIGITS: uint = 6;
+pub const DIGITS: u32 = 6;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub const EPSILON: f32 = 1.19209290e-07_f32;
 pub const MAX: f32 = 3.40282347e+38_f32;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_EXP: int = -125;
+pub const MIN_EXP: i32 = -125;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_EXP: int = 128;
+pub const MAX_EXP: i32 = 128;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_10_EXP: int = -37;
+pub const MIN_10_EXP: i32 = -37;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_10_EXP: int = 38;
+pub const MAX_10_EXP: i32 = 38;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub const NAN: f32 = 0.0_f32/0.0_f32;
@@ -193,12 +193,12 @@ fn classify(self) -> Fp {
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn mantissa_digits(_: Option<f32>) -> uint { MANTISSA_DIGITS }
+    fn mantissa_digits(_: Option<f32>) -> uint { MANTISSA_DIGITS as uint }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn digits(_: Option<f32>) -> uint { DIGITS }
+    fn digits(_: Option<f32>) -> uint { DIGITS as uint }
 
     #[inline]
     #[unstable(feature = "core")]
@@ -208,22 +208,22 @@ fn epsilon() -> f32 { EPSILON }
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn min_exp(_: Option<f32>) -> int { MIN_EXP }
+    fn min_exp(_: Option<f32>) -> int { MIN_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn max_exp(_: Option<f32>) -> int { MAX_EXP }
+    fn max_exp(_: Option<f32>) -> int { MAX_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn min_10_exp(_: Option<f32>) -> int { MIN_10_EXP }
+    fn min_10_exp(_: Option<f32>) -> int { MIN_10_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn max_10_exp(_: Option<f32>) -> int { MAX_10_EXP }
+    fn max_10_exp(_: Option<f32>) -> int { MAX_10_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
index 2aae7107548c6f3ecab3fa7d632635b7c277933e..d7e91058a46fbcb9fc38d91adc3185cd8020a897 100644 (file)
 // members of `Bounded` and `Float`.
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const RADIX: uint = 2;
+pub const RADIX: u32 = 2;
 
-pub const MANTISSA_DIGITS: uint = 53;
+pub const MANTISSA_DIGITS: u32 = 53;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const DIGITS: uint = 15;
+pub const DIGITS: u32 = 15;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub const EPSILON: f64 = 2.2204460492503131e-16_f64;
 pub const MAX: f64 = 1.7976931348623157e+308_f64;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_EXP: int = -1021;
+pub const MIN_EXP: i32 = -1021;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_EXP: int = 1024;
+pub const MAX_EXP: i32 = 1024;
 
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MIN_10_EXP: int = -307;
+pub const MIN_10_EXP: i32 = -307;
 #[unstable(feature = "core", reason = "pending integer conventions")]
-pub const MAX_10_EXP: int = 308;
+pub const MAX_10_EXP: i32 = 308;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub const NAN: f64 = 0.0_f64/0.0_f64;
@@ -200,12 +200,12 @@ fn classify(self) -> Fp {
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS }
+    fn mantissa_digits(_: Option<f64>) -> uint { MANTISSA_DIGITS as uint }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn digits(_: Option<f64>) -> uint { DIGITS }
+    fn digits(_: Option<f64>) -> uint { DIGITS as uint }
 
     #[inline]
     #[unstable(feature = "core")]
@@ -215,22 +215,22 @@ fn epsilon() -> f64 { EPSILON }
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn min_exp(_: Option<f64>) -> int { MIN_EXP }
+    fn min_exp(_: Option<f64>) -> int { MIN_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn max_exp(_: Option<f64>) -> int { MAX_EXP }
+    fn max_exp(_: Option<f64>) -> int { MAX_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP }
+    fn min_10_exp(_: Option<f64>) -> int { MIN_10_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
     #[deprecated(since = "1.0.0")]
-    fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP }
+    fn max_10_exp(_: Option<f64>) -> int { MAX_10_EXP as int }
 
     #[inline]
     #[unstable(feature = "core")]
diff --git a/src/libcore/num/int.rs b/src/libcore/num/int.rs
deleted file mode 100644 (file)
index 2132b95..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! Deprecated: replaced by `isize`.
-//!
-//! The rollout of the new type will gradually take place over the
-//! alpha cycle along with the development of clearer conventions
-//! around integer types.
-
-#![unstable(feature = "core")]
-#![deprecated(since = "1.0.0", reason = "replaced by isize")]
-
-#[cfg(target_pointer_width = "32")] int_module! { int, 32 }
-#[cfg(target_pointer_width = "64")] int_module! { int, 64 }
index 954c8a08e64d6bafdd15a6ef6c2fe9e6ad29e8c9..fe0d6d13c4c06483649bdbf737fe89c68048cf43 100644 (file)
@@ -15,11 +15,11 @@ macro_rules! int_module { ($T:ty, $bits:expr) => (
 // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
 // calling the `mem::size_of` function.
 #[unstable(feature = "core")]
-pub const BITS : uint = $bits;
+pub const BITS : u32 = $bits;
 // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
 // calling the `mem::size_of` function.
 #[unstable(feature = "core")]
-pub const BYTES : uint = ($bits / 8);
+pub const BYTES : u32 = ($bits / 8);
 
 // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
 // calling the `Bounded::min_value` function.
index 318799f59a8101f48a41e9f02d6aa89f6ddc88ff..d77a1eb4203c6b4bf786a6c5c6c93f29537c75ba 100644 (file)
@@ -86,7 +86,7 @@ pub trait Int
     /// ```
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
-    fn count_ones(self) -> uint;
+    fn count_ones(self) -> u32;
 
     /// Returns the number of zeros in the binary representation of `self`.
     ///
@@ -102,7 +102,7 @@ pub trait Int
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
     #[inline]
-    fn count_zeros(self) -> uint {
+    fn count_zeros(self) -> u32 {
         (!self).count_ones()
     }
 
@@ -120,7 +120,7 @@ fn count_zeros(self) -> uint {
     /// ```
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
-    fn leading_zeros(self) -> uint;
+    fn leading_zeros(self) -> u32;
 
     /// Returns the number of trailing zeros in the binary representation
     /// of `self`.
@@ -136,7 +136,7 @@ fn count_zeros(self) -> uint {
     /// ```
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
-    fn trailing_zeros(self) -> uint;
+    fn trailing_zeros(self) -> u32;
 
     /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
     /// the truncated bits to the end of the resulting integer.
@@ -153,7 +153,7 @@ fn count_zeros(self) -> uint {
     /// ```
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
-    fn rotate_left(self, n: uint) -> Self;
+    fn rotate_left(self, n: u32) -> Self;
 
     /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
     /// the truncated bits to the beginning of the resulting integer.
@@ -170,7 +170,7 @@ fn count_zeros(self) -> uint {
     /// ```
     #[unstable(feature = "core",
                reason = "pending integer conventions")]
-    fn rotate_right(self, n: uint) -> Self;
+    fn rotate_right(self, n: u32) -> Self;
 
     /// Reverses the byte order of the integer.
     ///
@@ -418,23 +418,23 @@ fn min_value() -> $T { 0 }
             fn max_value() -> $T { -1 }
 
             #[inline]
-            fn count_ones(self) -> uint { unsafe { $ctpop(self as $ActualT) as uint } }
+            fn count_ones(self) -> u32 { unsafe { $ctpop(self as $ActualT) as u32 } }
 
             #[inline]
-            fn leading_zeros(self) -> uint { unsafe { $ctlz(self as $ActualT) as uint } }
+            fn leading_zeros(self) -> u32 { unsafe { $ctlz(self as $ActualT) as u32 } }
 
             #[inline]
-            fn trailing_zeros(self) -> uint { unsafe { $cttz(self as $ActualT) as uint } }
+            fn trailing_zeros(self) -> u32 { unsafe { $cttz(self as $ActualT) as u32 } }
 
             #[inline]
-            fn rotate_left(self, n: uint) -> $T {
+            fn rotate_left(self, n: u32) -> $T {
                 // Protect against undefined behaviour for over-long bit shifts
                 let n = n % $BITS;
                 (self << n) | (self >> (($BITS - n) % $BITS))
             }
 
             #[inline]
-            fn rotate_right(self, n: uint) -> $T {
+            fn rotate_right(self, n: u32) -> $T {
                 // Protect against undefined behaviour for over-long bit shifts
                 let n = n % $BITS;
                 (self >> n) | (self << (($BITS - n) % $BITS))
@@ -549,19 +549,19 @@ fn min_value() -> $T { (-1 as $T) << ($BITS - 1) }
             fn max_value() -> $T { let min: $T = Int::min_value(); !min }
 
             #[inline]
-            fn count_ones(self) -> uint { (self as $UnsignedT).count_ones() }
+            fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
 
             #[inline]
-            fn leading_zeros(self) -> uint { (self as $UnsignedT).leading_zeros() }
+            fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() }
 
             #[inline]
-            fn trailing_zeros(self) -> uint { (self as $UnsignedT).trailing_zeros() }
+            fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() }
 
             #[inline]
-            fn rotate_left(self, n: uint) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
+            fn rotate_left(self, n: u32) -> $T { (self as $UnsignedT).rotate_left(n) as $T }
 
             #[inline]
-            fn rotate_right(self, n: uint) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
+            fn rotate_right(self, n: u32) -> $T { (self as $UnsignedT).rotate_right(n) as $T }
 
             #[inline]
             fn swap_bytes(self) -> $T { (self as $UnsignedT).swap_bytes() as $T }
@@ -706,7 +706,7 @@ fn is_power_of_two(self) -> bool {
     fn next_power_of_two(self) -> Self {
         let bits = size_of::<Self>() * 8;
         let one: Self = Int::one();
-        one << ((bits - (self - one).leading_zeros()) % bits)
+        one << ((bits - (self - one).leading_zeros() as usize) % bits)
     }
 
     /// Returns the smallest power of two greater than or equal to `n`. If the
@@ -743,8 +743,16 @@ impl UnsignedInt for u64 {}
 pub trait ToPrimitive {
     /// Converts the value of `self` to an `int`.
     #[inline]
+    #[unstable(feature = "core")]
+    #[deprecated(since = "1.0.0", reason = "use to_isize")]
     fn to_int(&self) -> Option<int> {
-        self.to_i64().and_then(|x| x.to_int())
+        self.to_i64().and_then(|x| x.to_isize())
+    }
+
+    /// Converts the value of `self` to an `isize`.
+    #[inline]
+    fn to_isize(&self) -> Option<isize> {
+        self.to_i64().and_then(|x| x.to_isize())
     }
 
     /// Converts the value of `self` to an `i8`.
@@ -770,8 +778,16 @@ fn to_i32(&self) -> Option<i32> {
 
     /// Converts the value of `self` to an `uint`.
     #[inline]
+    #[unstable(feature = "core")]
+    #[deprecated(since = "1.0.0", reason = "use to_usize")]
     fn to_uint(&self) -> Option<uint> {
-        self.to_u64().and_then(|x| x.to_uint())
+        self.to_u64().and_then(|x| x.to_usize())
+    }
+
+    /// Converts the value of `self` to a `usize`.
+    #[inline]
+    fn to_usize(&self) -> Option<usize> {
+        self.to_u64().and_then(|x| x.to_usize())
     }
 
     /// Converts the value of `self` to an `u8`.
@@ -848,6 +864,8 @@ impl ToPrimitive for $T {
             #[inline]
             fn to_int(&self) -> Option<int> { impl_to_primitive_int_to_int!($T, int, *self) }
             #[inline]
+            fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
+            #[inline]
             fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
             #[inline]
             fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
@@ -859,6 +877,8 @@ fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self)
             #[inline]
             fn to_uint(&self) -> Option<uint> { impl_to_primitive_int_to_uint!($T, uint, *self) }
             #[inline]
+            fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
+            #[inline]
             fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
             #[inline]
             fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
@@ -875,7 +895,7 @@ fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
     )
 }
 
-impl_to_primitive_int! { int }
+impl_to_primitive_int! { isize }
 impl_to_primitive_int! { i8 }
 impl_to_primitive_int! { i16 }
 impl_to_primitive_int! { i32 }
@@ -918,6 +938,8 @@ impl ToPrimitive for $T {
             #[inline]
             fn to_int(&self) -> Option<int> { impl_to_primitive_uint_to_int!(int, *self) }
             #[inline]
+            fn to_isize(&self) -> Option<int> { impl_to_primitive_uint_to_int!(isize, *self) }
+            #[inline]
             fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
             #[inline]
             fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
@@ -929,6 +951,8 @@ fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
             #[inline]
             fn to_uint(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, uint, *self) }
             #[inline]
+            fn to_usize(&self) -> Option<uint> { impl_to_primitive_uint_to_uint!($T, usize, *self) }
+            #[inline]
             fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
             #[inline]
             fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
@@ -945,7 +969,7 @@ fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
     )
 }
 
-impl_to_primitive_uint! { uint }
+impl_to_primitive_uint! { usize }
 impl_to_primitive_uint! { u8 }
 impl_to_primitive_uint! { u16 }
 impl_to_primitive_uint! { u32 }
@@ -973,6 +997,8 @@ impl ToPrimitive for $T {
             #[inline]
             fn to_int(&self) -> Option<int> { Some(*self as int) }
             #[inline]
+            fn to_isize(&self) -> Option<int> { Some(*self as isize) }
+            #[inline]
             fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
             #[inline]
             fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
@@ -984,6 +1010,8 @@ fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
             #[inline]
             fn to_uint(&self) -> Option<uint> { Some(*self as uint) }
             #[inline]
+            fn to_usize(&self) -> Option<uint> { Some(*self as usize) }
+            #[inline]
             fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
             #[inline]
             fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
@@ -1009,10 +1037,19 @@ pub trait FromPrimitive : ::marker::Sized {
     /// Convert an `int` to return an optional value of this type. If the
     /// value cannot be represented by this value, the `None` is returned.
     #[inline]
+    #[unstable(feature = "core")]
+    #[deprecated(since = "1.0.0", reason = "use from_isize")]
     fn from_int(n: int) -> Option<Self> {
         FromPrimitive::from_i64(n as i64)
     }
 
+    /// Convert an `isize` to return an optional value of this type. If the
+    /// value cannot be represented by this value, the `None` is returned.
+    #[inline]
+    fn from_isize(n: isize) -> Option<Self> {
+        FromPrimitive::from_i64(n as i64)
+    }
+
     /// Convert an `i8` to return an optional value of this type. If the
     /// type cannot be represented by this value, the `None` is returned.
     #[inline]
@@ -1041,10 +1078,19 @@ fn from_i32(n: i32) -> Option<Self> {
     /// Convert an `uint` to return an optional value of this type. If the
     /// type cannot be represented by this value, the `None` is returned.
     #[inline]
+    #[unstable(feature = "core")]
+    #[deprecated(since = "1.0.0", reason = "use from_usize")]
     fn from_uint(n: uint) -> Option<Self> {
         FromPrimitive::from_u64(n as u64)
     }
 
+    /// Convert a `usize` to return an optional value of this type. If the
+    /// type cannot be represented by this value, the `None` is returned.
+    #[inline]
+    fn from_usize(n: usize) -> Option<Self> {
+        FromPrimitive::from_u64(n as u64)
+    }
+
     /// Convert an `u8` to return an optional value of this type. If the
     /// type cannot be represented by this value, the `None` is returned.
     #[inline]
@@ -1087,8 +1133,15 @@ fn from_f64(n: f64) -> Option<Self> {
 
 /// A utility function that just calls `FromPrimitive::from_int`.
 #[unstable(feature = "core", reason = "likely to be removed")]
+#[deprecated(since = "1.0.0", reason = "use from_isize")]
 pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> {
-    FromPrimitive::from_int(n)
+    FromPrimitive::from_isize(n)
+}
+
+/// A utility function that just calls `FromPrimitive::from_isize`.
+#[unstable(feature = "core", reason = "likely to be removed")]
+pub fn from_isize<A: FromPrimitive>(n: isize) -> Option<A> {
+    FromPrimitive::from_isize(n)
 }
 
 /// A utility function that just calls `FromPrimitive::from_i8`.
@@ -1117,8 +1170,15 @@ pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> {
 
 /// A utility function that just calls `FromPrimitive::from_uint`.
 #[unstable(feature = "core", reason = "likely to be removed")]
+#[deprecated(since = "1.0.0", reason = "use from_uint")]
 pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> {
-    FromPrimitive::from_uint(n)
+    FromPrimitive::from_usize(n)
+}
+
+/// A utility function that just calls `FromPrimitive::from_usize`.
+#[unstable(feature = "core", reason = "likely to be removed")]
+pub fn from_usize<A: FromPrimitive>(n: usize) -> Option<A> {
+    FromPrimitive::from_usize(n)
 }
 
 /// A utility function that just calls `FromPrimitive::from_u8`.
@@ -1718,12 +1778,12 @@ fn from_str_radix(src: &str, radix: u32)
         }
     }
 }
-from_str_radix_int_impl! { int }
+from_str_radix_int_impl! { isize }
 from_str_radix_int_impl! { i8 }
 from_str_radix_int_impl! { i16 }
 from_str_radix_int_impl! { i32 }
 from_str_radix_int_impl! { i64 }
-from_str_radix_int_impl! { uint }
+from_str_radix_int_impl! { usize }
 from_str_radix_int_impl! { u8 }
 from_str_radix_int_impl! { u16 }
 from_str_radix_int_impl! { u32 }
diff --git a/src/libcore/num/uint.rs b/src/libcore/num/uint.rs
deleted file mode 100644 (file)
index f66a0ee..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! Deprecated: replaced by `usize`.
-//!
-//! The rollout of the new type will gradually take place over the
-//! alpha cycle along with the development of clearer conventions
-//! around integer types.
-
-#![unstable(feature = "core")]
-#![deprecated(since = "1.0.0", reason = "replaced by usize")]
-
-uint_module! { uint, int, ::int::BITS }
index 06502be54aaccded31e2541928248cde27f77407..330f0b91bf18303c6f7bde9deda735b2b9b6a6c5 100644 (file)
@@ -13,9 +13,9 @@
 macro_rules! uint_module { ($T:ty, $T_SIGNED:ty, $bits:expr) => (
 
 #[unstable(feature = "core")]
-pub const BITS : uint = $bits;
+pub const BITS : u32 = $bits;
 #[unstable(feature = "core")]
-pub const BYTES : uint = ($bits / 8);
+pub const BYTES : u32 = ($bits / 8);
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub const MIN: $T = 0 as $T;
index 5cc210df5b464e5d6581614df4d17a2012a6f323..35dfc7626872705f3378f8c3a0ad17161a6d9cee 100644 (file)
@@ -70,6 +70,7 @@ impl<T> Copy for Slice<T> {}
 #[deprecated(reason = "unboxed new closures do not have a universal representation; \
                        `&Fn` (etc) trait objects should use `TraitObject` instead",
              since= "1.0.0")]
+#[allow(deprecated) /* for deriving Copy impl */]
 pub struct Closure {
     pub code: *mut (),
     pub env: *mut (),
index 5b78da34eddde0e7dd363383b3fd0d4b719c5640..f99cfbaab5d702570e42723709e48cefaf9aeb9a 100644 (file)
@@ -1167,13 +1167,23 @@ fn size_hint(&self) -> (usize, Option<usize>) {
 forward_iterator! { RSplitNMut: T, &'a mut [T] }
 
 /// An iterator over overlapping subslices of length `size`.
-#[derive(Clone)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Windows<'a, T:'a> {
     v: &'a [T],
     size: usize
 }
 
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T> Clone for Windows<'a, T> {
+    fn clone(&self) -> Windows<'a, T> {
+        Windows {
+            v: self.v,
+            size: self.size,
+        }
+    }
+}
+
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, T> Iterator for Windows<'a, T> {
     type Item = &'a [T];
@@ -1239,13 +1249,23 @@ fn idx(&mut self, index: usize) -> Option<&'a [T]> {
 ///
 /// When the slice len is not evenly divided by the chunk size, the last slice
 /// of the iteration will be the remainder.
-#[derive(Clone)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Chunks<'a, T:'a> {
     v: &'a [T],
     size: usize
 }
 
+// FIXME(#19839) Remove in favor of `#[derive(Clone)]`
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, T> Clone for Chunks<'a, T> {
+    fn clone(&self) -> Chunks<'a, T> {
+        Chunks {
+            v: self.v,
+            size: self.size,
+        }
+    }
+}
+
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, T> Iterator for Chunks<'a, T> {
     type Item = &'a [T];
index b354116993c23a1e750be1fa8c900dc95261ab85..e73bb2105e00eddc7747efd76df93989f36c60cd 100644 (file)
@@ -134,12 +134,23 @@ impl FromStr for bool {
 
     /// Parse a `bool` from a string.
     ///
-    /// Yields an `Option<bool>`, because `s` may or may not actually be
-    /// parseable.
+    /// Yields a `Result<bool, ParseBoolError>`, because `s` may or may not
+    /// actually be parseable.
     ///
     /// # Examples
     ///
     /// ```rust
+    /// use std::str::FromStr;
+    ///
+    /// assert_eq!(FromStr::from_str("true"), Ok(true));
+    /// assert_eq!(FromStr::from_str("false"), Ok(false));
+    /// assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
+    /// ```
+    ///
+    /// Note, in many cases, the StrExt::parse() which is based on
+    /// this FromStr::from_str() is more proper.
+    ///
+    /// ```rust
     /// assert_eq!("true".parse(), Ok(true));
     /// assert_eq!("false".parse(), Ok(false));
     /// assert!("not even a boolean".parse::<bool>().is_err());
@@ -935,6 +946,7 @@ fn next(&mut self) -> Option<(usize, usize)> {
 #[unstable(feature = "core")]
 #[deprecated(since = "1.0.0", reason = "use `Split` with a `&str`")]
 pub struct SplitStr<'a, P: Pattern<'a>>(Split<'a, P>);
+#[allow(deprecated)]
 impl<'a, P: Pattern<'a>> Iterator for SplitStr<'a, P> {
     type Item = &'a str;
 
@@ -1325,6 +1337,7 @@ pub trait StrExt {
     fn split_terminator<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitTerminator<'a, P>;
     fn rsplitn<'a, P: Pattern<'a>>(&'a self, count: usize, pat: P) -> RSplitN<'a, P>;
     fn match_indices<'a, P: Pattern<'a>>(&'a self, pat: P) -> MatchIndices<'a, P>;
+    #[allow(deprecated) /* for SplitStr */]
     fn split_str<'a, P: Pattern<'a>>(&'a self, pat: P) -> SplitStr<'a, P>;
     fn lines<'a>(&'a self) -> Lines<'a>;
     fn lines_any<'a>(&'a self) -> LinesAny<'a>;
index 8a27400389f4ada601d595879b3b0ed651c46ff4..abf88583c03ffac03f1a6a40a0c9c51a86e20060 100644 (file)
@@ -12,7 +12,7 @@
 use core::iter::order::*;
 use core::iter::MinMaxResult::*;
 use core::num::SignedInt;
-use core::uint;
+use core::usize;
 use core::cmp;
 
 use test::Bencher;
@@ -292,7 +292,7 @@ fn count(st: &mut uint) -> Option<uint> {
 fn test_cycle() {
     let cycle_len = 3;
     let it = count(0, 1).take(cycle_len).cycle();
-    assert_eq!(it.size_hint(), (uint::MAX, None));
+    assert_eq!(it.size_hint(), (usize::MAX, None));
     for (i, x) in it.take(100).enumerate() {
         assert_eq!(i % cycle_len, x);
     }
@@ -365,19 +365,19 @@ fn test_iterator_size_hint() {
     let v2 = &[10, 11, 12];
     let vi = v.iter();
 
-    assert_eq!(c.size_hint(), (uint::MAX, None));
+    assert_eq!(c.size_hint(), (usize::MAX, None));
     assert_eq!(vi.clone().size_hint(), (10, Some(10)));
 
     assert_eq!(c.clone().take(5).size_hint(), (5, Some(5)));
     assert_eq!(c.clone().skip(5).size_hint().1, None);
     assert_eq!(c.clone().take_while(|_| false).size_hint(), (0, None));
     assert_eq!(c.clone().skip_while(|_| false).size_hint(), (0, None));
-    assert_eq!(c.clone().enumerate().size_hint(), (uint::MAX, None));
-    assert_eq!(c.clone().chain(vi.clone().cloned()).size_hint(), (uint::MAX, None));
+    assert_eq!(c.clone().enumerate().size_hint(), (usize::MAX, None));
+    assert_eq!(c.clone().chain(vi.clone().cloned()).size_hint(), (usize::MAX, None));
     assert_eq!(c.clone().zip(vi.clone()).size_hint(), (10, Some(10)));
     assert_eq!(c.clone().scan(0, |_,_| Some(0)).size_hint(), (0, None));
     assert_eq!(c.clone().filter(|_| false).size_hint(), (0, None));
-    assert_eq!(c.clone().map(|_| 0).size_hint(), (uint::MAX, None));
+    assert_eq!(c.clone().map(|_| 0).size_hint(), (usize::MAX, None));
     assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
 
     assert_eq!(vi.clone().take(5).size_hint(), (5, Some(5)));
@@ -753,7 +753,7 @@ fn test_range() {
 
     assert_eq!((0..100).size_hint(), (100, Some(100)));
     // this test is only meaningful when sizeof uint < sizeof u64
-    assert_eq!((uint::MAX - 1..uint::MAX).size_hint(), (1, Some(1)));
+    assert_eq!((usize::MAX - 1..usize::MAX).size_hint(), (1, Some(1)));
     assert_eq!((-10..-1).size_hint(), (9, Some(9)));
     assert_eq!((-1..-10).size_hint(), (0, Some(0)));
 }
diff --git a/src/libcoretest/num/int.rs b/src/libcoretest/num/int.rs
deleted file mode 100644 (file)
index be8dfd0..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-int_module!(int, int);
index c33729876ccf3c5777fdaed6d4f51cde5c14039c..fa41167cae8a6dda7742850facc156fa30f3e26d 100644 (file)
@@ -12,7 +12,7 @@ macro_rules! int_module { ($T:ty, $T_i:ident) => (
 #[cfg(test)]
 mod tests {
     use core::$T_i::*;
-    use core::int;
+    use core::isize;
     use core::num::{FromStrRadix, Int, SignedInt};
     use core::ops::{Shl, Shr, Not, BitXor, BitAnd, BitOr};
     use num;
@@ -70,12 +70,12 @@ fn test_bitwise_operators() {
         assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not());
     }
 
-    static A: $T = 0b0101100;
-    static B: $T = 0b0100001;
-    static C: $T = 0b1111001;
+    const A: $T = 0b0101100;
+    const B: $T = 0b0100001;
+    const C: $T = 0b1111001;
 
-    static _0: $T = 0;
-    static _1: $T = !0;
+    const _0: $T = 0;
+    const _1: $T = !0;
 
     #[test]
     fn test_count_ones() {
@@ -153,7 +153,7 @@ fn test_be() {
     fn test_signed_checked_div() {
         assert!(10.checked_div(2) == Some(5));
         assert!(5.checked_div(0) == None);
-        assert!(int::MIN.checked_div(-1) == None);
+        assert!(isize::MIN.checked_div(-1) == None);
     }
 
     #[test]
index 03f6e51a3498a4c72f1ce88639172695add9b5cc..1cd1989c11dc3e5088cf210b06ff74965677d0e0 100644 (file)
@@ -21,7 +21,6 @@
 mod i16;
 mod i32;
 mod i64;
-mod int;
 
 #[macro_use]
 mod uint_macros;
@@ -30,7 +29,6 @@
 mod u16;
 mod u32;
 mod u64;
-mod uint;
 
 /// Helper function for testing numeric operations
 pub fn test_num<T>(ten: T, two: T) where
diff --git a/src/libcoretest/num/uint.rs b/src/libcoretest/num/uint.rs
deleted file mode 100644 (file)
index 395e55c..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-uint_module!(uint, uint);
index 5c6efc857f1f98fb5d6433543bc0f54124b90994..39e41a4fad3b7d5092c834aa43c69a443b1018b7 100644 (file)
@@ -38,12 +38,12 @@ fn test_bitwise_operators() {
         assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not());
     }
 
-    static A: $T = 0b0101100;
-    static B: $T = 0b0100001;
-    static C: $T = 0b1111001;
+    const A: $T = 0b0101100;
+    const B: $T = 0b0100001;
+    const C: $T = 0b1111001;
 
-    static _0: $T = 0;
-    static _1: $T = !0;
+    const _0: $T = 0;
+    const _1: $T = !0;
 
     #[test]
     fn test_count_ones() {
index 2ce52cdec2560a92ee1e32559e2ae4392b73e37e..585318300438b7158132c31982a86ff24e5c3c65 100644 (file)
@@ -73,9 +73,9 @@ fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
                                     -> *mut c_void;
 }
 
-static LZ_NORM : c_int = 0x80;  // LZ with 128 probes, "normal"
-static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
-static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
+const LZ_NORM: c_int = 0x80;  // LZ with 128 probes, "normal"
+const TINFL_FLAG_PARSE_ZLIB_HEADER: c_int = 0x1; // parse zlib header and adler32 checksum
+const TDEFL_WRITE_ZLIB_HEADER: c_int = 0x01000; // write zlib header and adler32 checksum
 
 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
     unsafe {
index 4e329897e1ab21958e6dd520aabdaea04b3b34ff..6240b0e6afdd50861f59ced7b8a752cd8dd626b9 100644 (file)
@@ -963,7 +963,7 @@ fn t(s: &str, i: uint, u: &[String]) {
         "little lamb".to_string(),
         "Little lamb".to_string()
     ]);
-    t("\nMary had a little lamb\nLittle lamb\n", ::std::uint::MAX,
+    t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX,
         &["Mary had a little lamb\nLittle lamb".to_string()]);
 }
 
index 09fbf4935e4c1e7a86ade0c5bdb543854bb313a8..2f60a9e2cca2a84c6d06daac67391a75a2067e43 100644 (file)
@@ -37,7 +37,7 @@
 //! Each node label is derived directly from the int representing the node,
 //! while the edge labels are all empty strings.
 //!
-//! This example also illustrates how to use `CowVec` to return
+//! This example also illustrates how to use `Cow<[T]>` to return
 //! an owned vector or a borrowed slice as appropriate: we construct the
 //! node vector from scratch, but borrow the edge list (rather than
 //! constructing a copy of all the edges from scratch).
@@ -502,7 +502,7 @@ pub fn suffix_line(self, suffix: LabelText) -> LabelText<'static> {
 /// that is bound by the self lifetime `'a`.
 ///
 /// The `nodes` and `edges` method each return instantiations of
-/// `CowVec` to leave implementers the freedom to create
+/// `Cow<[T]>` to leave implementers the freedom to create
 /// entirely new vectors or to pass back slices into internally owned
 /// vectors.
 pub trait GraphWalk<'a, N, E> {
index 74a95b3aba056cdd194a1637b1950d5f5ba5bafa..42143b06ca0e391678583b6e9cfced390ffa897c 100644 (file)
@@ -1115,7 +1115,6 @@ pub mod c99 {
             pub mod posix88 {
                 pub type off_t = i64;
                 pub type dev_t = u32;
-                pub type ino_t = u32;
                 pub type pid_t = i32;
                 pub type uid_t = u32;
                 pub type gid_t = u32;
index 5a85552dc384eb10536faa8520621827fe5416cd..12794ed69be38c7edd263b879969342f02a673bb 100644 (file)
@@ -223,7 +223,7 @@ fn ziggurat<R: Rng, P, Z>(
             mut pdf: P,
             mut zero_case: Z)
             -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 {
-    static SCALE: f64 = (1u64 << 53) as f64;
+    const SCALE: f64 = (1u64 << 53) as f64;
     loop {
         // reimplement the f64 generation as an optimisation suggested
         // by the Doornik paper: we have a lot of precision-space
index 701749ff3443f6e0280ad1308001854ea645cfe2..51d54f27f0912ddf48ed660388d6aabde1812d38 100644 (file)
@@ -127,7 +127,7 @@ fn isaac(&mut self) {
         let mut a = self.a;
         let mut b = self.b + self.c;
 
-        static MIDPOINT: uint = (RAND_SIZE / 2) as uint;
+        const MIDPOINT: uint = (RAND_SIZE / 2) as uint;
 
         macro_rules! ind {
             ($x:expr) => ( self.mem[(($x >> 2) as uint & ((RAND_SIZE - 1) as uint))] )
index 583c658dfe0582f3b02847e71aab3d4770620237..3458d519af5cda5b440566c1abf386510094886b 100644 (file)
@@ -52,7 +52,7 @@
 use distributions::range::SampleRange;
 
 #[cfg(test)]
-static RAND_BENCH_N: u64 = 100;
+const RAND_BENCH_N: u64 = 100;
 
 pub mod distributions;
 pub mod isaac;
@@ -342,7 +342,7 @@ impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
     type Item = char;
 
     fn next(&mut self) -> Option<char> {
-        static GEN_ASCII_STR_CHARSET: &'static [u8] =
+        const GEN_ASCII_STR_CHARSET: &'static [u8] =
             b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
               abcdefghijklmnopqrstuvwxyz\
               0123456789";
index d5c5d5004657e7facfdee32003e8ef9440d5a073..c8a757079c348577c00b4d8ad20624ddf00b7251 100644 (file)
 
 use core::prelude::*;
 use core::char;
-use core::int;
-use core::uint;
+use core::isize;
+use core::usize;
 
 use {Rand,Rng};
 
-impl Rand for int {
+impl Rand for isize {
     #[inline]
-    fn rand<R: Rng>(rng: &mut R) -> int {
-        if int::BITS == 32 {
-            rng.gen::<i32>() as int
+    fn rand<R: Rng>(rng: &mut R) -> isize {
+        if isize::BITS == 32 {
+            rng.gen::<i32>() as isize
         } else {
-            rng.gen::<i64>() as int
+            rng.gen::<i64>() as isize
         }
     }
 }
@@ -56,13 +56,13 @@ fn rand<R: Rng>(rng: &mut R) -> i64 {
     }
 }
 
-impl Rand for uint {
+impl Rand for usize {
     #[inline]
-    fn rand<R: Rng>(rng: &mut R) -> uint {
-        if uint::BITS == 32 {
-            rng.gen::<u32>() as uint
+    fn rand<R: Rng>(rng: &mut R) -> usize {
+        if usize::BITS == 32 {
+            rng.gen::<u32>() as usize
         } else {
-            rng.gen::<u64>() as uint
+            rng.gen::<u64>() as usize
         }
     }
 }
@@ -141,7 +141,7 @@ impl Rand for char {
     #[inline]
     fn rand<R: Rng>(rng: &mut R) -> char {
         // a char is 21 bits
-        static CHAR_MASK: u32 = 0x001f_ffff;
+        const CHAR_MASK: u32 = 0x001f_ffff;
         loop {
             // Rejection sampling. About 0.2% of numbers with at most
             // 21-bits are invalid codepoints (surrogates), so this
index 06828911471466d2e1e3eb58786eb04567aacf1a..0072c555d1412cc1bed6e81ccb3422d037d65853 100644 (file)
@@ -18,7 +18,7 @@
 
 /// How many bytes of entropy the underling RNG is allowed to generate
 /// before it is reseeded.
-static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;
+const DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;
 
 /// A wrapper around any RNG which reseeds the underlying RNG after it
 /// has generated a certain number of random bytes.
@@ -212,7 +212,7 @@ fn test_rng_reseed() {
         assert_eq!(string1, string2);
     }
 
-    static FILL_BYTES_V_LEN: uint = 13579;
+    const FILL_BYTES_V_LEN: uint = 13579;
     #[test]
     fn test_rng_fill_bytes() {
         let mut v = repeat(0u8).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
index c52465a889907b57c4357f19d4a801677ab8b6c5..4ef3c5bc20634f3ccb7f8a162a30cc900eb8a1f5 100644 (file)
@@ -13,7 +13,7 @@
 use std::slice;
 use std::iter::repeat;
 
-static BUF_CAPACITY: uint = 128;
+const BUF_CAPACITY: uint = 128;
 
 fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {
     // compute offset as signed and clamp to prevent overflow
index 05cd24de7368c6a831597d8e9aa4e096c916adf8..844d097bdafa95f32b2c166ed25ee56e5d2a6306 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-//! Really Bad Markup Language (rbml) is a temporary measure until we migrate
-//! the rust object metadata to a better serialization format. It is not
-//! intended to be used by users.
+//! Really Bad Markup Language (rbml) is an internal serialization format of rustc.
+//! This is not intended to be used by users.
 //!
-//! It is loosely based on the Extensible Binary Markup Language (ebml):
-//!     http://www.matroska.org/technical/specs/rfc/index.html
+//! Originally based on the Extensible Binary Markup Language
+//! (ebml; http://www.matroska.org/technical/specs/rfc/index.html),
+//! it is now a separate format tuned for the rust object metadata.
+//!
+//! # Encoding
+//!
+//! RBML document consists of the tag, length and data.
+//! The encoded data can contain multiple RBML documents concatenated.
+//!
+//! **Tags** are a hint for the following data.
+//! Tags are a number from 0x000 to 0xfff, where 0xf0 through 0xff is reserved.
+//! Tags less than 0xf0 are encoded in one literal byte.
+//! Tags greater than 0xff are encoded in two big-endian bytes,
+//! where the tag number is ORed with 0xf000. (E.g. tag 0x123 = `f1 23`)
+//!
+//! **Lengths** encode the length of the following data.
+//! It is a variable-length unsigned int, and one of the following forms:
+//!
+//! - `80` through `fe` for lengths up to 0x7e;
+//! - `40 ff` through `7f ff` for lengths up to 0x3fff;
+//! - `20 40 00` through `3f ff ff` for lengths up to 0x1fffff;
+//! - `10 20 00 00` through `1f ff ff ff` for lengths up to 0xfffffff.
+//!
+//! The "overlong" form is allowed so that the length can be encoded
+//! without the prior knowledge of the encoded data.
+//! For example, the length 0 can be represented either by `80`, `40 00`,
+//! `20 00 00` or `10 00 00 00`.
+//! The encoder tries to minimize the length if possible.
+//! Also, some predefined tags listed below are so commonly used that
+//! their lengths are omitted ("implicit length").
+//!
+//! **Data** can be either binary bytes or zero or more nested RBML documents.
+//! Nested documents cannot overflow, and should be entirely contained
+//! within a parent document.
+//!
+//! # Predefined Tags
+//!
+//! Most RBML tags are defined by the application.
+//! (For the rust object metadata, see also `rustc::metadata::common`.)
+//! RBML itself does define a set of predefined tags however,
+//! intended for the auto-serialization implementation.
+//!
+//! Predefined tags with an implicit length:
+//!
+//! - `U8`  (`00`): 1-byte unsigned integer.
+//! - `U16` (`01`): 2-byte big endian unsigned integer.
+//! - `U32` (`02`): 4-byte big endian unsigned integer.
+//! - `U64` (`03`): 8-byte big endian unsigned integer.
+//!   Any of `U*` tags can be used to encode primitive unsigned integer types,
+//!   as long as it is no greater than the actual size.
+//!   For example, `u8` can only be represented via the `U8` tag.
+//!
+//! - `I8`  (`04`): 1-byte signed integer.
+//! - `I16` (`05`): 2-byte big endian signed integer.
+//! - `I32` (`06`): 4-byte big endian signed integer.
+//! - `I64` (`07`): 8-byte big endian signed integer.
+//!   Similar to `U*` tags. Always uses two's complement encoding.
+//!
+//! - `Bool` (`08`): 1-byte boolean value, `00` for false and `01` for true.
+//!
+//! - `Char` (`09`): 4-byte big endian Unicode scalar value.
+//!   Surrogate pairs or out-of-bound values are invalid.
+//!
+//! - `F32` (`0a`): 4-byte big endian unsigned integer representing
+//!   IEEE 754 binary32 floating-point format.
+//! - `F64` (`0b`): 8-byte big endian unsigned integer representing
+//!   IEEE 754 binary64 floating-point format.
+//!
+//! - `Sub8`  (`0c`): 1-byte unsigned integer for supplementary information.
+//! - `Sub32` (`0d`): 4-byte unsigned integer for supplementary information.
+//!   Those two tags normally occur as the first subdocument of certain tags,
+//!   namely `Enum`, `Vec` and `Map`, to provide a variant or size information.
+//!   They can be used interchangably.
+//!
+//! Predefined tags with an explicit length:
+//!
+//! - `Str` (`10`): A UTF-8-encoded string.
+//!
+//! - `Enum` (`11`): An enum.
+//!   The first subdocument should be `Sub*` tags with a variant ID.
+//!   Subsequent subdocuments, if any, encode variant arguments.
+//!
+//! - `Vec` (`12`): A vector (sequence).
+//! - `VecElt` (`13`): A vector element.
+//!   The first subdocument should be `Sub*` tags with the number of elements.
+//!   Subsequent subdocuments should be `VecElt` tag per each element.
+//!
+//! - `Map` (`14`): A map (associated array).
+//! - `MapKey` (`15`): A key part of the map entry.
+//! - `MapVal` (`16`): A value part of the map entry.
+//!   The first subdocument should be `Sub*` tags with the number of entries.
+//!   Subsequent subdocuments should be an alternating sequence of
+//!   `MapKey` and `MapVal` tags per each entry.
+//!
+//! - `Opaque` (`17`): An opaque, custom-format tag.
+//!   Used to wrap ordinary custom tags or data in the auto-serialized context.
+//!   Rustc typically uses this to encode type informations.
+//!
+//! First 0x20 tags are reserved by RBML; custom tags start at 0x20.
 
 #![crate_name = "rbml"]
 #![unstable(feature = "rustc_private")]
@@ -64,6 +160,10 @@ pub fn get<'a>(&'a self, tag: uint) -> Doc<'a> {
         reader::get_doc(*self, tag)
     }
 
+    pub fn is_empty(&self) -> bool {
+        self.start == self.end
+    }
+
     pub fn as_str_slice<'a>(&'a self) -> &'a str {
         str::from_utf8(&self.data[self.start..self.end]).unwrap()
     }
@@ -80,41 +180,51 @@ pub struct TaggedDoc<'a> {
 
 #[derive(Copy, Debug)]
 pub enum EbmlEncoderTag {
-    EsUint,     // 0
-    EsU64,      // 1
-    EsU32,      // 2
-    EsU16,      // 3
-    EsU8,       // 4
-    EsInt,      // 5
-    EsI64,      // 6
-    EsI32,      // 7
-    EsI16,      // 8
-    EsI8,       // 9
-    EsBool,     // 10
-    EsChar,     // 11
-    EsStr,      // 12
-    EsF64,      // 13
-    EsF32,      // 14
-    EsFloat,    // 15
-    EsEnum,     // 16
-    EsEnumVid,  // 17
-    EsEnumBody, // 18
-    EsVec,      // 19
-    EsVecLen,   // 20
-    EsVecElt,   // 21
-    EsMap,      // 22
-    EsMapLen,   // 23
-    EsMapKey,   // 24
-    EsMapVal,   // 25
-
-    EsOpaque,
-
-    EsLabel, // Used only when debugging
+    // tags 00..1f are reserved for auto-serialization.
+    // first NUM_IMPLICIT_TAGS tags are implicitly sized and lengths are not encoded.
+
+    EsU8       = 0x00, // + 1 byte
+    EsU16      = 0x01, // + 2 bytes
+    EsU32      = 0x02, // + 4 bytes
+    EsU64      = 0x03, // + 8 bytes
+    EsI8       = 0x04, // + 1 byte
+    EsI16      = 0x05, // + 2 bytes
+    EsI32      = 0x06, // + 4 bytes
+    EsI64      = 0x07, // + 8 bytes
+    EsBool     = 0x08, // + 1 byte
+    EsChar     = 0x09, // + 4 bytes
+    EsF32      = 0x0a, // + 4 bytes
+    EsF64      = 0x0b, // + 8 bytes
+    EsSub8     = 0x0c, // + 1 byte
+    EsSub32    = 0x0d, // + 4 bytes
+    // 0x0e and 0x0f are reserved
+
+    EsStr      = 0x10,
+    EsEnum     = 0x11, // encodes the variant id as the first EsSub*
+    EsVec      = 0x12, // encodes the # of elements as the first EsSub*
+    EsVecElt   = 0x13,
+    EsMap      = 0x14, // encodes the # of pairs as the first EsSub*
+    EsMapKey   = 0x15,
+    EsMapVal   = 0x16,
+    EsOpaque   = 0x17,
 }
 
+const NUM_TAGS: uint = 0x1000;
+const NUM_IMPLICIT_TAGS: uint = 0x0e;
+
+static TAG_IMPLICIT_LEN: [i8; NUM_IMPLICIT_TAGS] = [
+    1, 2, 4, 8, // EsU*
+    1, 2, 4, 8, // ESI*
+    1, // EsBool
+    4, // EsChar
+    4, 8, // EsF*
+    1, 4, // EsSub*
+];
+
 #[derive(Debug)]
 pub enum Error {
     IntTooBig(uint),
+    InvalidTag(uint),
     Expected(String),
     IoError(std::old_io::IoError),
     ApplicationError(String)
@@ -138,11 +248,11 @@ pub mod reader {
 
     use serialize;
 
-    use super::{ ApplicationError, EsVec, EsMap, EsEnum, EsVecLen, EsVecElt,
-        EsMapLen, EsMapKey, EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64,
+    use super::{ ApplicationError, EsVec, EsMap, EsEnum, EsSub8, EsSub32,
+        EsVecElt, EsMapKey, EsU64, EsU32, EsU16, EsU8, EsI64,
         EsI32, EsI16, EsI8, EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal,
-        EsEnumBody, EsUint, EsOpaque, EsLabel, EbmlEncoderTag, Doc, TaggedDoc,
-        Error, IntTooBig, Expected };
+        EsOpaque, EbmlEncoderTag, Doc, TaggedDoc,
+        Error, IntTooBig, InvalidTag, Expected, NUM_IMPLICIT_TAGS, TAG_IMPLICIT_LEN };
 
     pub type DecodeResult<T> = Result<T, Error>;
     // rbml reading
@@ -165,6 +275,18 @@ pub struct Res {
         pub next: uint
     }
 
+    pub fn tag_at(data: &[u8], start: uint) -> DecodeResult<Res> {
+        let v = data[start] as uint;
+        if v < 0xf0 {
+            Ok(Res { val: v, next: start + 1 })
+        } else if v > 0xf0 {
+            Ok(Res { val: ((v & 0xf) << 8) | data[start + 1] as uint, next: start + 2 })
+        } else {
+            // every tag starting with byte 0xf0 is an overlong form, which is prohibited.
+            Err(InvalidTag(v))
+        }
+    }
+
     #[inline(never)]
     fn vuint_at_slow(data: &[u8], start: uint) -> DecodeResult<Res> {
         let a = data[start];
@@ -237,9 +359,17 @@ pub fn vuint_at(data: &[u8], start: uint) -> DecodeResult<Res> {
         }
     }
 
+    pub fn tag_len_at(data: &[u8], tag: Res) -> DecodeResult<Res> {
+        if tag.val < NUM_IMPLICIT_TAGS && TAG_IMPLICIT_LEN[tag.val] >= 0 {
+            Ok(Res { val: TAG_IMPLICIT_LEN[tag.val] as uint, next: tag.next })
+        } else {
+            vuint_at(data, tag.next)
+        }
+    }
+
     pub fn doc_at<'a>(data: &'a [u8], start: uint) -> DecodeResult<TaggedDoc<'a>> {
-        let elt_tag = try!(vuint_at(data, start));
-        let elt_size = try!(vuint_at(data, elt_tag.next));
+        let elt_tag = try!(tag_at(data, start));
+        let elt_size = try!(tag_len_at(data, elt_tag));
         let end = elt_size.next + elt_size.val;
         Ok(TaggedDoc {
             tag: elt_tag.val,
@@ -250,8 +380,8 @@ pub fn doc_at<'a>(data: &'a [u8], start: uint) -> DecodeResult<TaggedDoc<'a>> {
     pub fn maybe_get_doc<'a>(d: Doc<'a>, tg: uint) -> Option<Doc<'a>> {
         let mut pos = d.start;
         while pos < d.end {
-            let elt_tag = try_or!(vuint_at(d.data, pos), None);
-            let elt_size = try_or!(vuint_at(d.data, elt_tag.next), None);
+            let elt_tag = try_or!(tag_at(d.data, pos), None);
+            let elt_size = try_or!(tag_len_at(d.data, elt_tag), None);
             pos = elt_size.next + elt_size.val;
             if elt_tag.val == tg {
                 return Some(Doc { data: d.data, start: elt_size.next,
@@ -276,8 +406,8 @@ pub fn docs<F>(d: Doc, mut it: F) -> bool where
     {
         let mut pos = d.start;
         while pos < d.end {
-            let elt_tag = try_or!(vuint_at(d.data, pos), false);
-            let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
+            let elt_tag = try_or!(tag_at(d.data, pos), false);
+            let elt_size = try_or!(tag_len_at(d.data, elt_tag), false);
             pos = elt_size.next + elt_size.val;
             let doc = Doc { data: d.data, start: elt_size.next, end: pos };
             if !it(elt_tag.val, doc) {
@@ -292,8 +422,8 @@ pub fn tagged_docs<F>(d: Doc, tg: uint, mut it: F) -> bool where
     {
         let mut pos = d.start;
         while pos < d.end {
-            let elt_tag = try_or!(vuint_at(d.data, pos), false);
-            let elt_size = try_or!(vuint_at(d.data, elt_tag.next), false);
+            let elt_tag = try_or!(tag_at(d.data, pos), false);
+            let elt_size = try_or!(tag_len_at(d.data, elt_tag), false);
             pos = elt_size.next + elt_size.val;
             if elt_tag.val == tg {
                 let doc = Doc { data: d.data, start: elt_size.next,
@@ -357,23 +487,6 @@ pub fn new(d: Doc<'doc>) -> Decoder<'doc> {
             }
         }
 
-        fn _check_label(&mut self, lbl: &str) -> DecodeResult<()> {
-            if self.pos < self.parent.end {
-                let TaggedDoc { tag: r_tag, doc: r_doc } =
-                    try!(doc_at(self.parent.data, self.pos));
-
-                if r_tag == (EsLabel as uint) {
-                    self.pos = r_doc.end;
-                    let str = r_doc.as_str_slice();
-                    if lbl != str {
-                        return Err(Expected(format!("Expected label {:?} but \
-                                                     found {:?}", lbl, str)));
-                    }
-                }
-            }
-            Ok(())
-        }
-
         fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<Doc<'doc>> {
             debug!(". next_doc(exp_tag={:?})", exp_tag);
             if self.pos >= self.parent.end {
@@ -416,10 +529,66 @@ fn push_doc<T, F>(&mut self, exp_tag: EbmlEncoderTag, f: F) -> DecodeResult<T> w
             Ok(r)
         }
 
-        fn _next_uint(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult<uint> {
-            let r = doc_as_u32(try!(self.next_doc(exp_tag)));
-            debug!("_next_uint exp_tag={:?} result={:?}", exp_tag, r);
-            Ok(r as uint)
+        fn _next_sub(&mut self) -> DecodeResult<uint> {
+            // empty vector/map optimization
+            if self.parent.is_empty() {
+                return Ok(0);
+            }
+
+            let TaggedDoc { tag: r_tag, doc: r_doc } =
+                try!(doc_at(self.parent.data, self.pos));
+            let r = if r_tag == (EsSub8 as uint) {
+                doc_as_u8(r_doc) as uint
+            } else if r_tag == (EsSub32 as uint) {
+                doc_as_u32(r_doc) as uint
+            } else {
+                return Err(Expected(format!("expected EBML doc with tag {:?} or {:?} but \
+                                             found tag {:?}", EsSub8, EsSub32, r_tag)));
+            };
+            if r_doc.end > self.parent.end {
+                return Err(Expected(format!("invalid EBML, child extends to \
+                                             {:#x}, parent to {:#x}",
+                                            r_doc.end, self.parent.end)));
+            }
+            self.pos = r_doc.end;
+            debug!("_next_sub result={:?}", r);
+            Ok(r)
+        }
+
+        // variable-length unsigned integer with different tags.
+        // `first_tag` should be a tag for u8 or i8.
+        // `last_tag` should be the largest allowed integer tag with the matching signedness.
+        // all tags between them should be valid, in the order of u8, u16, u32 and u64.
+        fn _next_int(&mut self,
+                     first_tag: EbmlEncoderTag,
+                     last_tag: EbmlEncoderTag) -> DecodeResult<u64> {
+            if self.pos >= self.parent.end {
+                return Err(Expected(format!("no more documents in \
+                                             current node!")));
+            }
+
+            let TaggedDoc { tag: r_tag, doc: r_doc } =
+                try!(doc_at(self.parent.data, self.pos));
+            let r = if first_tag as uint <= r_tag && r_tag <= last_tag as uint {
+                match r_tag - first_tag as uint {
+                    0 => doc_as_u8(r_doc) as u64,
+                    1 => doc_as_u16(r_doc) as u64,
+                    2 => doc_as_u32(r_doc) as u64,
+                    3 => doc_as_u64(r_doc) as u64,
+                    _ => unreachable!(),
+                }
+            } else {
+                return Err(Expected(format!("expected EBML doc with tag {:?} through {:?} but \
+                                             found tag {:?}", first_tag, last_tag, r_tag)));
+            };
+            if r_doc.end > self.parent.end {
+                return Err(Expected(format!("invalid EBML, child extends to \
+                                             {:#x}, parent to {:#x}",
+                                            r_doc.end, self.parent.end)));
+            }
+            self.pos = r_doc.end;
+            debug!("_next_int({:?}, {:?}) result={:?}", first_tag, last_tag, r);
+            Ok(r)
         }
 
         pub fn read_opaque<R, F>(&mut self, op: F) -> DecodeResult<R> where
@@ -443,12 +612,12 @@ impl<'doc> serialize::Decoder for Decoder<'doc> {
         type Error = Error;
         fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) }
 
-        fn read_u64(&mut self) -> DecodeResult<u64> { Ok(doc_as_u64(try!(self.next_doc(EsU64)))) }
-        fn read_u32(&mut self) -> DecodeResult<u32> { Ok(doc_as_u32(try!(self.next_doc(EsU32)))) }
-        fn read_u16(&mut self) -> DecodeResult<u16> { Ok(doc_as_u16(try!(self.next_doc(EsU16)))) }
-        fn read_u8 (&mut self) -> DecodeResult<u8 > { Ok(doc_as_u8 (try!(self.next_doc(EsU8 )))) }
+        fn read_u64(&mut self) -> DecodeResult<u64> { self._next_int(EsU8, EsU64) }
+        fn read_u32(&mut self) -> DecodeResult<u32> { Ok(try!(self._next_int(EsU8, EsU32)) as u32) }
+        fn read_u16(&mut self) -> DecodeResult<u16> { Ok(try!(self._next_int(EsU8, EsU16)) as u16) }
+        fn read_u8(&mut self) -> DecodeResult<u8> { Ok(doc_as_u8(try!(self.next_doc(EsU8)))) }
         fn read_uint(&mut self) -> DecodeResult<uint> {
-            let v = doc_as_u64(try!(self.next_doc(EsUint)));
+            let v = try!(self._next_int(EsU8, EsU64));
             if v > (::std::usize::MAX as u64) {
                 Err(IntTooBig(v as uint))
             } else {
@@ -456,20 +625,12 @@ fn read_uint(&mut self) -> DecodeResult<uint> {
             }
         }
 
-        fn read_i64(&mut self) -> DecodeResult<i64> {
-            Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64)
-        }
-        fn read_i32(&mut self) -> DecodeResult<i32> {
-            Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32)
-        }
-        fn read_i16(&mut self) -> DecodeResult<i16> {
-            Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16)
-        }
-        fn read_i8 (&mut self) -> DecodeResult<i8> {
-            Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8)
-        }
+        fn read_i64(&mut self) -> DecodeResult<i64> { Ok(try!(self._next_int(EsI8, EsI64)) as i64) }
+        fn read_i32(&mut self) -> DecodeResult<i32> { Ok(try!(self._next_int(EsI8, EsI32)) as i32) }
+        fn read_i16(&mut self) -> DecodeResult<i16> { Ok(try!(self._next_int(EsI8, EsI16)) as i16) }
+        fn read_i8(&mut self) -> DecodeResult<i8> { Ok(doc_as_u8(try!(self.next_doc(EsI8))) as i8) }
         fn read_int(&mut self) -> DecodeResult<int> {
-            let v = doc_as_u64(try!(self.next_doc(EsInt))) as i64;
+            let v = try!(self._next_int(EsI8, EsI64)) as i64;
             if v > (isize::MAX as i64) || v < (isize::MIN as i64) {
                 debug!("FIXME \\#6122: Removing this makes this function miscompile");
                 Err(IntTooBig(v as uint))
@@ -502,7 +663,6 @@ fn read_enum<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T> where
             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
         {
             debug!("read_enum({})", name);
-            try!(self._check_label(name));
 
             let doc = try!(self.next_doc(EsEnum));
 
@@ -522,20 +682,10 @@ fn read_enum_variant<T, F>(&mut self, _: &[&str],
             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
         {
             debug!("read_enum_variant()");
-            let idx = try!(self._next_uint(EsEnumVid));
+            let idx = try!(self._next_sub());
             debug!("  idx={}", idx);
 
-            let doc = try!(self.next_doc(EsEnumBody));
-
-            let (old_parent, old_pos) = (self.parent, self.pos);
-            self.parent = doc;
-            self.pos = self.parent.start;
-
-            let result = try!(f(self, idx));
-
-            self.parent = old_parent;
-            self.pos = old_pos;
-            Ok(result)
+            f(self, idx)
         }
 
         fn read_enum_variant_arg<T, F>(&mut self, idx: uint, f: F) -> DecodeResult<T> where
@@ -550,20 +700,10 @@ fn read_enum_struct_variant<T, F>(&mut self, _: &[&str],
             where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult<T>,
         {
             debug!("read_enum_struct_variant()");
-            let idx = try!(self._next_uint(EsEnumVid));
+            let idx = try!(self._next_sub());
             debug!("  idx={}", idx);
 
-            let doc = try!(self.next_doc(EsEnumBody));
-
-            let (old_parent, old_pos) = (self.parent, self.pos);
-            self.parent = doc;
-            self.pos = self.parent.start;
-
-            let result = try!(f(self, idx));
-
-            self.parent = old_parent;
-            self.pos = old_pos;
-            Ok(result)
+            f(self, idx)
         }
 
         fn read_enum_struct_variant_field<T, F>(&mut self,
@@ -588,7 +728,6 @@ fn read_struct_field<T, F>(&mut self, name: &str, idx: uint, f: F) -> DecodeResu
             F: FnOnce(&mut Decoder<'doc>) -> DecodeResult<T>,
         {
             debug!("read_struct_field(name={}, idx={})", name, idx);
-            try!(self._check_label(name));
             f(self)
         }
 
@@ -652,7 +791,7 @@ fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where
         {
             debug!("read_seq()");
             self.push_doc(EsVec, move |d| {
-                let len = try!(d._next_uint(EsVecLen));
+                let len = try!(d._next_sub());
                 debug!("  len={}", len);
                 f(d, len)
             })
@@ -670,7 +809,7 @@ fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where
         {
             debug!("read_map()");
             self.push_doc(EsMap, move |d| {
-                let len = try!(d._next_uint(EsMapLen));
+                let len = try!(d._next_sub());
                 debug!("  len={}", len);
                 f(d, len)
             })
@@ -701,11 +840,14 @@ pub mod writer {
     use std::num::Int;
     use std::old_io::{Writer, Seek};
     use std::old_io;
+    use std::slice::bytes;
+    use std::num::ToPrimitive;
 
-    use super::{ EsVec, EsMap, EsEnum, EsVecLen, EsVecElt, EsMapLen, EsMapKey,
-        EsEnumVid, EsU64, EsU32, EsU16, EsU8, EsInt, EsI64, EsI32, EsI16, EsI8,
-        EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal, EsEnumBody, EsUint,
-        EsOpaque, EsLabel, EbmlEncoderTag };
+    use super::{ EsVec, EsMap, EsEnum, EsSub8, EsSub32, EsVecElt, EsMapKey,
+        EsU64, EsU32, EsU16, EsU8, EsI64, EsI32, EsI16, EsI8,
+        EsBool, EsF64, EsF32, EsChar, EsStr, EsMapVal,
+        EsOpaque, NUM_IMPLICIT_TAGS, NUM_TAGS };
+    use super::io::SeekableMemWriter;
 
     use serialize;
 
@@ -713,9 +855,24 @@ pub mod writer {
     pub type EncodeResult = old_io::IoResult<()>;
 
     // rbml writing
-    pub struct Encoder<'a, W:'a> {
-        pub writer: &'a mut W,
+    pub struct Encoder<'a> {
+        pub writer: &'a mut SeekableMemWriter,
         size_positions: Vec<uint>,
+        relax_limit: u64, // do not move encoded bytes before this position
+    }
+
+    fn write_tag<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
+        if n < 0xf0 {
+            w.write_all(&[n as u8])
+        } else if 0x100 <= n && n < NUM_TAGS {
+            w.write_all(&[0xf0 | (n >> 8) as u8, n as u8])
+        } else {
+            Err(old_io::IoError {
+                kind: old_io::OtherIoError,
+                desc: "invalid tag",
+                detail: Some(format!("{}", n))
+            })
+        }
     }
 
     fn write_sized_vuint<W: Writer>(w: &mut W, n: uint, size: uint) -> EncodeResult {
@@ -746,27 +903,30 @@ fn write_vuint<W: Writer>(w: &mut W, n: uint) -> EncodeResult {
         })
     }
 
-    impl<'a, W: Writer + Seek> Encoder<'a, W> {
-        pub fn new(w: &'a mut W) -> Encoder<'a, W> {
+    impl<'a> Encoder<'a> {
+        pub fn new(w: &'a mut SeekableMemWriter) -> Encoder<'a> {
             Encoder {
                 writer: w,
                 size_positions: vec!(),
+                relax_limit: 0,
             }
         }
 
         /// FIXME(pcwalton): Workaround for badness in trans. DO NOT USE ME.
-        pub unsafe fn unsafe_clone(&self) -> Encoder<'a, W> {
+        pub unsafe fn unsafe_clone(&self) -> Encoder<'a> {
             Encoder {
                 writer: mem::transmute_copy(&self.writer),
                 size_positions: self.size_positions.clone(),
+                relax_limit: self.relax_limit,
             }
         }
 
         pub fn start_tag(&mut self, tag_id: uint) -> EncodeResult {
             debug!("Start tag {:?}", tag_id);
+            assert!(tag_id >= NUM_IMPLICIT_TAGS);
 
             // Write the enum ID:
-            try!(write_vuint(self.writer, tag_id));
+            try!(write_tag(self.writer, tag_id));
 
             // Write a placeholder four-byte size.
             self.size_positions.push(try!(self.writer.tell()) as uint);
@@ -779,11 +939,29 @@ pub fn end_tag(&mut self) -> EncodeResult {
             let cur_pos = try!(self.writer.tell());
             try!(self.writer.seek(last_size_pos as i64, old_io::SeekSet));
             let size = cur_pos as uint - last_size_pos - 4;
-            try!(write_sized_vuint(self.writer, size, 4));
-            let r = try!(self.writer.seek(cur_pos as i64, old_io::SeekSet));
+
+            // relax the size encoding for small tags (bigger tags are costly to move).
+            // we should never try to move the stable positions, however.
+            const RELAX_MAX_SIZE: uint = 0x100;
+            if size <= RELAX_MAX_SIZE && last_size_pos >= self.relax_limit as uint {
+                // we can't alter the buffer in place, so have a temporary buffer
+                let mut buf = [0u8; RELAX_MAX_SIZE];
+                {
+                    let data = &self.writer.get_ref()[last_size_pos+4..cur_pos as uint];
+                    bytes::copy_memory(&mut buf, data);
+                }
+
+                // overwrite the size and data and continue
+                try!(write_vuint(self.writer, size));
+                try!(self.writer.write_all(&buf[..size]));
+            } else {
+                // overwrite the size with an overlong encoding and skip past the data
+                try!(write_sized_vuint(self.writer, size, 4));
+                try!(self.writer.seek(cur_pos as i64, old_io::SeekSet));
+            }
 
             debug!("End tag (size = {:?})", size);
-            Ok(r)
+            Ok(())
         }
 
         pub fn wr_tag<F>(&mut self, tag_id: uint, blk: F) -> EncodeResult where
@@ -795,7 +973,8 @@ pub fn wr_tag<F>(&mut self, tag_id: uint, blk: F) -> EncodeResult where
         }
 
         pub fn wr_tagged_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult {
-            try!(write_vuint(self.writer, tag_id));
+            assert!(tag_id >= NUM_IMPLICIT_TAGS);
+            try!(write_tag(self.writer, tag_id));
             try!(write_vuint(self.writer, b.len()));
             self.writer.write_all(b)
         }
@@ -839,6 +1018,47 @@ pub fn wr_tagged_str(&mut self, tag_id: uint, v: &str) -> EncodeResult {
             self.wr_tagged_bytes(tag_id, v.as_bytes())
         }
 
+        // for auto-serialization
+        fn wr_tagged_raw_bytes(&mut self, tag_id: uint, b: &[u8]) -> EncodeResult {
+            try!(write_tag(self.writer, tag_id));
+            self.writer.write_all(b)
+        }
+
+        fn wr_tagged_raw_u64(&mut self, tag_id: uint, v: u64) -> EncodeResult {
+            let bytes: [u8; 8] = unsafe { mem::transmute(v.to_be()) };
+            self.wr_tagged_raw_bytes(tag_id, &bytes)
+        }
+
+        fn wr_tagged_raw_u32(&mut self, tag_id: uint, v: u32)  -> EncodeResult{
+            let bytes: [u8; 4] = unsafe { mem::transmute(v.to_be()) };
+            self.wr_tagged_raw_bytes(tag_id, &bytes)
+        }
+
+        fn wr_tagged_raw_u16(&mut self, tag_id: uint, v: u16) -> EncodeResult {
+            let bytes: [u8; 2] = unsafe { mem::transmute(v.to_be()) };
+            self.wr_tagged_raw_bytes(tag_id, &bytes)
+        }
+
+        fn wr_tagged_raw_u8(&mut self, tag_id: uint, v: u8) -> EncodeResult {
+            self.wr_tagged_raw_bytes(tag_id, &[v])
+        }
+
+        fn wr_tagged_raw_i64(&mut self, tag_id: uint, v: i64) -> EncodeResult {
+            self.wr_tagged_raw_u64(tag_id, v as u64)
+        }
+
+        fn wr_tagged_raw_i32(&mut self, tag_id: uint, v: i32) -> EncodeResult {
+            self.wr_tagged_raw_u32(tag_id, v as u32)
+        }
+
+        fn wr_tagged_raw_i16(&mut self, tag_id: uint, v: i16) -> EncodeResult {
+            self.wr_tagged_raw_u16(tag_id, v as u16)
+        }
+
+        fn wr_tagged_raw_i8(&mut self, tag_id: uint, v: i8) -> EncodeResult {
+            self.wr_tagged_raw_bytes(tag_id, &[v as u8])
+        }
+
         pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult {
             debug!("Write {:?} bytes", b.len());
             self.writer.write_all(b)
@@ -848,38 +1068,36 @@ pub fn wr_str(&mut self, s: &str) -> EncodeResult {
             debug!("Write str: {:?}", s);
             self.writer.write_all(s.as_bytes())
         }
-    }
-
-    // FIXME (#2743): optionally perform "relaxations" on end_tag to more
-    // efficiently encode sizes; this is a fixed point iteration
-
-    // Set to true to generate more debugging in EBML code.
-    // Totally lame approach.
-    #[cfg(not(ndebug))]
-    static DEBUG: bool = true;
-    #[cfg(ndebug)]
-    static DEBUG: bool = false;
 
-    impl<'a, W: Writer + Seek> Encoder<'a, W> {
-        // used internally to emit things like the vector length and so on
-        fn _emit_tagged_uint(&mut self, t: EbmlEncoderTag, v: uint) -> EncodeResult {
-            assert!(v <= 0xFFFF_FFFF);
-            self.wr_tagged_u32(t as uint, v as u32)
+        /// Returns the current position while marking it stable, i.e.
+        /// generated bytes so far woundn't be affected by relaxation.
+        pub fn mark_stable_position(&mut self) -> u64 {
+            let pos = self.writer.tell().unwrap();
+            if self.relax_limit < pos {
+                self.relax_limit = pos;
+            }
+            pos
         }
+    }
 
-        fn _emit_label(&mut self, label: &str) -> EncodeResult {
-            // There are various strings that we have access to, such as
-            // the name of a record field, which do not actually appear in
-            // the encoded EBML (normally).  This is just for
-            // efficiency.  When debugging, though, we can emit such
-            // labels and then they will be checked by decoder to
-            // try and check panics more quickly.
-            if DEBUG { self.wr_tagged_str(EsLabel as uint, label) }
-            else { Ok(()) }
+    impl<'a> Encoder<'a> {
+        // used internally to emit things like the vector length and so on
+        fn _emit_tagged_sub(&mut self, v: uint) -> EncodeResult {
+            if let Some(v) = v.to_u8() {
+                self.wr_tagged_raw_u8(EsSub8 as uint, v)
+            } else if let Some(v) = v.to_u32() {
+                self.wr_tagged_raw_u32(EsSub32 as uint, v)
+            } else {
+                Err(old_io::IoError {
+                    kind: old_io::OtherIoError,
+                    desc: "length or variant id too big",
+                    detail: Some(format!("{}", v))
+                })
+            }
         }
 
         pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder) -> EncodeResult,
         {
             try!(self.start_tag(EsOpaque as uint));
             try!(f(self));
@@ -887,7 +1105,7 @@ pub fn emit_opaque<F>(&mut self, f: F) -> EncodeResult where
         }
     }
 
-    impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> {
+    impl<'a> serialize::Encoder for Encoder<'a> {
         type Error = old_io::IoError;
 
         fn emit_nil(&mut self) -> EncodeResult {
@@ -895,61 +1113,78 @@ fn emit_nil(&mut self) -> EncodeResult {
         }
 
         fn emit_uint(&mut self, v: uint) -> EncodeResult {
-            self.wr_tagged_u64(EsUint as uint, v as u64)
+            self.emit_u64(v as u64)
         }
         fn emit_u64(&mut self, v: u64) -> EncodeResult {
-            self.wr_tagged_u64(EsU64 as uint, v)
+            match v.to_u32() {
+                Some(v) => self.emit_u32(v),
+                None => self.wr_tagged_raw_u64(EsU64 as uint, v)
+            }
         }
         fn emit_u32(&mut self, v: u32) -> EncodeResult {
-            self.wr_tagged_u32(EsU32 as uint, v)
+            match v.to_u16() {
+                Some(v) => self.emit_u16(v),
+                None => self.wr_tagged_raw_u32(EsU32 as uint, v)
+            }
         }
         fn emit_u16(&mut self, v: u16) -> EncodeResult {
-            self.wr_tagged_u16(EsU16 as uint, v)
+            match v.to_u8() {
+                Some(v) => self.emit_u8(v),
+                None => self.wr_tagged_raw_u16(EsU16 as uint, v)
+            }
         }
         fn emit_u8(&mut self, v: u8) -> EncodeResult {
-            self.wr_tagged_u8(EsU8 as uint, v)
+            self.wr_tagged_raw_u8(EsU8 as uint, v)
         }
 
         fn emit_int(&mut self, v: int) -> EncodeResult {
-            self.wr_tagged_i64(EsInt as uint, v as i64)
+            self.emit_i64(v as i64)
         }
         fn emit_i64(&mut self, v: i64) -> EncodeResult {
-            self.wr_tagged_i64(EsI64 as uint, v)
+            match v.to_i32() {
+                Some(v) => self.emit_i32(v),
+                None => self.wr_tagged_raw_i64(EsI64 as uint, v)
+            }
         }
         fn emit_i32(&mut self, v: i32) -> EncodeResult {
-            self.wr_tagged_i32(EsI32 as uint, v)
+            match v.to_i16() {
+                Some(v) => self.emit_i16(v),
+                None => self.wr_tagged_raw_i32(EsI32 as uint, v)
+            }
         }
         fn emit_i16(&mut self, v: i16) -> EncodeResult {
-            self.wr_tagged_i16(EsI16 as uint, v)
+            match v.to_i8() {
+                Some(v) => self.emit_i8(v),
+                None => self.wr_tagged_raw_i16(EsI16 as uint, v)
+            }
         }
         fn emit_i8(&mut self, v: i8) -> EncodeResult {
-            self.wr_tagged_i8(EsI8 as uint, v)
+            self.wr_tagged_raw_i8(EsI8 as uint, v)
         }
 
         fn emit_bool(&mut self, v: bool) -> EncodeResult {
-            self.wr_tagged_u8(EsBool as uint, v as u8)
+            self.wr_tagged_raw_u8(EsBool as uint, v as u8)
         }
 
         fn emit_f64(&mut self, v: f64) -> EncodeResult {
             let bits = unsafe { mem::transmute(v) };
-            self.wr_tagged_u64(EsF64 as uint, bits)
+            self.wr_tagged_raw_u64(EsF64 as uint, bits)
         }
         fn emit_f32(&mut self, v: f32) -> EncodeResult {
             let bits = unsafe { mem::transmute(v) };
-            self.wr_tagged_u32(EsF32 as uint, bits)
+            self.wr_tagged_raw_u32(EsF32 as uint, bits)
         }
         fn emit_char(&mut self, v: char) -> EncodeResult {
-            self.wr_tagged_u32(EsChar as uint, v as u32)
+            self.wr_tagged_raw_u32(EsChar as uint, v as u32)
         }
 
         fn emit_str(&mut self, v: &str) -> EncodeResult {
             self.wr_tagged_str(EsStr as uint, v)
         }
 
-        fn emit_enum<F>(&mut self, name: &str, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+        fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
-            try!(self._emit_label(name));
             try!(self.start_tag(EsEnum as uint));
             try!(f(self));
             self.end_tag()
@@ -960,16 +1195,14 @@ fn emit_enum_variant<F>(&mut self,
                                 v_id: uint,
                                 _: uint,
                                 f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
-            try!(self._emit_tagged_uint(EsEnumVid, v_id));
-            try!(self.start_tag(EsEnumBody as uint));
-            try!(f(self));
-            self.end_tag()
+            try!(self._emit_tagged_sub(v_id));
+            f(self)
         }
 
         fn emit_enum_variant_arg<F>(&mut self, _: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             f(self)
         }
@@ -979,7 +1212,7 @@ fn emit_enum_struct_variant<F>(&mut self,
                                        v_id: uint,
                                        cnt: uint,
                                        f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_enum_variant(v_name, v_id, cnt, f)
         }
@@ -988,48 +1221,47 @@ fn emit_enum_struct_variant_field<F>(&mut self,
                                              _: &str,
                                              idx: uint,
                                              f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_enum_variant_arg(idx, f)
         }
 
         fn emit_struct<F>(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             f(self)
         }
 
-        fn emit_struct_field<F>(&mut self, name: &str, _: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+        fn emit_struct_field<F>(&mut self, _name: &str, _: uint, f: F) -> EncodeResult where
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
-            try!(self._emit_label(name));
             f(self)
         }
 
         fn emit_tuple<F>(&mut self, len: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_seq(len, f)
         }
         fn emit_tuple_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_seq_elt(idx, f)
         }
 
         fn emit_tuple_struct<F>(&mut self, _: &str, len: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_seq(len, f)
         }
         fn emit_tuple_struct_arg<F>(&mut self, idx: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_seq_elt(idx, f)
         }
 
         fn emit_option<F>(&mut self, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             self.emit_enum("Option", f)
         }
@@ -1037,24 +1269,28 @@ fn emit_option_none(&mut self) -> EncodeResult {
             self.emit_enum_variant("None", 0, 0, |_| Ok(()))
         }
         fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
 
             self.emit_enum_variant("Some", 1, 1, f)
         }
 
         fn emit_seq<F>(&mut self, len: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
+            if len == 0 {
+                // empty vector optimization
+                return self.wr_tagged_bytes(EsVec as uint, &[]);
+            }
 
             try!(self.start_tag(EsVec as uint));
-            try!(self._emit_tagged_uint(EsVecLen, len));
+            try!(self._emit_tagged_sub(len));
             try!(f(self));
             self.end_tag()
         }
 
         fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
 
             try!(self.start_tag(EsVecElt as uint));
@@ -1063,17 +1299,21 @@ fn emit_seq_elt<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
         }
 
         fn emit_map<F>(&mut self, len: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
+            if len == 0 {
+                // empty map optimization
+                return self.wr_tagged_bytes(EsMap as uint, &[]);
+            }
 
             try!(self.start_tag(EsMap as uint));
-            try!(self._emit_tagged_uint(EsMapLen, len));
+            try!(self._emit_tagged_sub(len));
             try!(f(self));
             self.end_tag()
         }
 
         fn emit_map_elt_key<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
 
             try!(self.start_tag(EsMapKey as uint));
@@ -1082,7 +1322,7 @@ fn emit_map_elt_key<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
         }
 
         fn emit_map_elt_val<F>(&mut self, _idx: uint, f: F) -> EncodeResult where
-            F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult,
+            F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
         {
             try!(self.start_tag(EsMapVal as uint));
             try!(f(self));
index 2b968736ffd9a6240c5bbca23197535fb00d3349..a777e1f7f75e6ad13c59cd12ae0e84ba52b20f87 100644 (file)
@@ -568,9 +568,9 @@ fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) {
         })
     }
 
-    // FIXME(#10894) should continue recursing
     fn visit_ty(&mut self, t: &ast::Ty) {
         run_lints!(self, check_ty, t);
+        visit::walk_ty(self, t);
     }
 
     fn visit_ident(&mut self, sp: Span, id: ast::Ident) {
@@ -612,7 +612,7 @@ fn visit_generics(&mut self, g: &ast::Generics) {
     }
 
     fn visit_trait_item(&mut self, m: &ast::TraitItem) {
-        run_lints!(self, check_trait_method, m);
+        run_lints!(self, check_trait_item, m);
         visit::walk_trait_item(self, m);
     }
 
index f3fa3b8846ca2b6d6d6eb175f68873cff5bed564..506d20133bdc78e8679f1dd8253b7284cedea232 100644 (file)
@@ -144,7 +144,7 @@ fn check_generics(&mut self, _: &Context, _: &ast::Generics) { }
     fn check_fn(&mut self, _: &Context,
         _: FnKind, _: &ast::FnDecl, _: &ast::Block, _: Span, _: ast::NodeId) { }
     fn check_ty_method(&mut self, _: &Context, _: &ast::TypeMethod) { }
-    fn check_trait_method(&mut self, _: &Context, _: &ast::TraitItem) { }
+    fn check_trait_item(&mut self, _: &Context, _: &ast::TraitItem) { }
     fn check_struct_def(&mut self, _: &Context,
         _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, _: ast::NodeId) { }
     fn check_struct_def_post(&mut self, _: &Context,
index 4930eddb35a53213ebad184791eebf6c9b4d8713..a58ef53de9a7135591de41d12b98c66777411a62 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
 
 use back::svh::Svh;
 
-// EBML enum definitions and utils shared by the encoder and decoder
+// RBML enum definitions and utils shared by the encoder and decoder
+//
+// 0x00..0x1f: reserved for RBML generic type tags
+// 0x20..0xef: free for use, preferred for frequent tags
+// 0xf0..0xff: internally used by RBML to encode 0x100..0xfff in two bytes
+// 0x100..0xfff: free for use, preferred for infrequent tags
 
-pub const tag_items: uint = 0x00;
+pub const tag_items: uint = 0x100; // top-level only
 
-pub const tag_paths_data_name: uint = 0x01;
+pub const tag_paths_data_name: uint = 0x20;
 
-pub const tag_def_id: uint = 0x02;
+pub const tag_def_id: uint = 0x21;
 
-pub const tag_items_data: uint = 0x03;
+pub const tag_items_data: uint = 0x22;
 
-pub const tag_items_data_item: uint = 0x04;
+pub const tag_items_data_item: uint = 0x23;
 
-pub const tag_items_data_item_family: uint = 0x05;
+pub const tag_items_data_item_family: uint = 0x24;
 
-pub const tag_items_data_item_type: uint = 0x07;
+pub const tag_items_data_item_type: uint = 0x25;
 
-pub const tag_items_data_item_symbol: uint = 0x08;
+pub const tag_items_data_item_symbol: uint = 0x26;
 
-pub const tag_items_data_item_variant: uint = 0x09;
+pub const tag_items_data_item_variant: uint = 0x27;
 
-pub const tag_items_data_parent_item: uint = 0x0a;
+pub const tag_items_data_parent_item: uint = 0x28;
 
-pub const tag_items_data_item_is_tuple_struct_ctor: uint = 0x0b;
+pub const tag_items_data_item_is_tuple_struct_ctor: uint = 0x29;
 
-pub const tag_index: uint = 0x0c;
+pub const tag_index: uint = 0x2a;
 
-pub const tag_index_buckets: uint = 0x0d;
+pub const tag_index_buckets: uint = 0x2b;
 
-pub const tag_index_buckets_bucket: uint = 0x0e;
+pub const tag_index_buckets_bucket: uint = 0x2c;
 
-pub const tag_index_buckets_bucket_elt: uint = 0x0f;
+pub const tag_index_buckets_bucket_elt: uint = 0x2d;
 
-pub const tag_index_table: uint = 0x10;
+pub const tag_index_table: uint = 0x2e;
 
-pub const tag_meta_item_name_value: uint = 0x11;
+pub const tag_meta_item_name_value: uint = 0x2f;
 
-pub const tag_meta_item_name: uint = 0x12;
+pub const tag_meta_item_name: uint = 0x30;
 
-pub const tag_meta_item_value: uint = 0x13;
+pub const tag_meta_item_value: uint = 0x31;
 
-pub const tag_attributes: uint = 0x14;
+pub const tag_attributes: uint = 0x101; // top-level only
 
-pub const tag_attribute: uint = 0x15;
+pub const tag_attribute: uint = 0x32;
 
-pub const tag_meta_item_word: uint = 0x16;
+pub const tag_meta_item_word: uint = 0x33;
 
-pub const tag_meta_item_list: uint = 0x17;
+pub const tag_meta_item_list: uint = 0x34;
 
 // The list of crates that this crate depends on
-pub const tag_crate_deps: uint = 0x18;
+pub const tag_crate_deps: uint = 0x102; // top-level only
 
 // A single crate dependency
-pub const tag_crate_dep: uint = 0x19;
+pub const tag_crate_dep: uint = 0x35;
 
-pub const tag_crate_hash: uint = 0x1a;
-pub const tag_crate_crate_name: uint = 0x1b;
+pub const tag_crate_hash: uint = 0x103; // top-level only
+pub const tag_crate_crate_name: uint = 0x104; // top-level only
 
-pub const tag_crate_dep_crate_name: uint = 0x1d;
-pub const tag_crate_dep_hash: uint = 0x1e;
+pub const tag_crate_dep_crate_name: uint = 0x36;
+pub const tag_crate_dep_hash: uint = 0x37;
 
-pub const tag_mod_impl: uint = 0x1f;
+pub const tag_mod_impl: uint = 0x38;
 
-pub const tag_item_trait_item: uint = 0x20;
+pub const tag_item_trait_item: uint = 0x39;
 
-pub const tag_item_trait_ref: uint = 0x21;
-pub const tag_item_super_trait_ref: uint = 0x22;
+pub const tag_item_trait_ref: uint = 0x3a;
+pub const tag_item_super_trait_ref: uint = 0x3b;
 
 // discriminator value for variants
-pub const tag_disr_val: uint = 0x23;
+pub const tag_disr_val: uint = 0x3c;
 
 // used to encode ast_map::PathElem
-pub const tag_path: uint = 0x24;
-pub const tag_path_len: uint = 0x25;
-pub const tag_path_elem_mod: uint = 0x26;
-pub const tag_path_elem_name: uint = 0x27;
-pub const tag_item_field: uint = 0x28;
-pub const tag_item_field_origin: uint = 0x29;
-
-pub const tag_item_variances: uint = 0x2a;
+pub const tag_path: uint = 0x3d;
+pub const tag_path_len: uint = 0x3e;
+pub const tag_path_elem_mod: uint = 0x3f;
+pub const tag_path_elem_name: uint = 0x40;
+pub const tag_item_field: uint = 0x41;
+pub const tag_item_field_origin: uint = 0x42;
+
+pub const tag_item_variances: uint = 0x43;
 /*
   trait items contain tag_item_trait_item elements,
   impl items contain tag_item_impl_item elements, and classes
@@ -101,60 +106,59 @@ impl items contain tag_item_impl_item elements, and classes
   both, tag_item_trait_item and tag_item_impl_item have to be two
   different tags.
  */
-pub const tag_item_impl_item: uint = 0x30;
-pub const tag_item_trait_method_explicit_self: uint = 0x31;
+pub const tag_item_impl_item: uint = 0x44;
+pub const tag_item_trait_method_explicit_self: uint = 0x45;
 
 
 // Reexports are found within module tags. Each reexport contains def_ids
 // and names.
-pub const tag_items_data_item_reexport: uint = 0x38;
-pub const tag_items_data_item_reexport_def_id: uint = 0x39;
-pub const tag_items_data_item_reexport_name: uint = 0x3a;
+pub const tag_items_data_item_reexport: uint = 0x46;
+pub const tag_items_data_item_reexport_def_id: uint = 0x47;
+pub const tag_items_data_item_reexport_name: uint = 0x48;
 
 // used to encode crate_ctxt side tables
 #[derive(Copy, PartialEq, FromPrimitive)]
 #[repr(uint)]
-pub enum astencode_tag { // Reserves 0x40 -- 0x5f
-    tag_ast = 0x40,
-
-    tag_tree = 0x41,
-
-    tag_id_range = 0x42,
-
-    tag_table = 0x43,
-    tag_table_id = 0x44,
-    tag_table_val = 0x45,
-    tag_table_def = 0x46,
-    tag_table_node_type = 0x47,
-    tag_table_item_subst = 0x48,
-    tag_table_freevars = 0x49,
-    tag_table_tcache = 0x4a,
-    tag_table_param_defs = 0x4b,
-    tag_table_mutbl = 0x4c,
-    tag_table_last_use = 0x4d,
-    tag_table_spill = 0x4e,
-    tag_table_method_map = 0x4f,
-    tag_table_vtable_map = 0x50,
-    tag_table_adjustments = 0x51,
-    tag_table_moves_map = 0x52,
-    tag_table_capture_map = 0x53,
-    tag_table_closure_tys = 0x54,
-    tag_table_closure_kinds = 0x55,
-    tag_table_upvar_capture_map = 0x56,
-    tag_table_capture_modes = 0x57,
-    tag_table_object_cast_map = 0x58,
-    tag_table_const_qualif = 0x59,
+pub enum astencode_tag { // Reserves 0x50 -- 0x6f
+    tag_ast = 0x50,
+
+    tag_tree = 0x51,
+
+    tag_id_range = 0x52,
+
+    tag_table = 0x53,
+    // GAP 0x54, 0x55
+    tag_table_def = 0x56,
+    tag_table_node_type = 0x57,
+    tag_table_item_subst = 0x58,
+    tag_table_freevars = 0x59,
+    tag_table_tcache = 0x5a,
+    tag_table_param_defs = 0x5b,
+    tag_table_mutbl = 0x5c,
+    tag_table_last_use = 0x5d,
+    tag_table_spill = 0x5e,
+    tag_table_method_map = 0x5f,
+    tag_table_vtable_map = 0x60,
+    tag_table_adjustments = 0x61,
+    tag_table_moves_map = 0x62,
+    tag_table_capture_map = 0x63,
+    tag_table_closure_tys = 0x64,
+    tag_table_closure_kinds = 0x65,
+    tag_table_upvar_capture_map = 0x66,
+    tag_table_capture_modes = 0x67,
+    tag_table_object_cast_map = 0x68,
+    tag_table_const_qualif = 0x69,
 }
 
-pub const tag_item_trait_item_sort: uint = 0x60;
+pub const tag_item_trait_item_sort: uint = 0x70;
 
-pub const tag_item_trait_parent_sort: uint = 0x61;
+pub const tag_item_trait_parent_sort: uint = 0x71;
 
-pub const tag_item_impl_type_basename: uint = 0x62;
+pub const tag_item_impl_type_basename: uint = 0x72;
 
-pub const tag_crate_triple: uint = 0x66;
+pub const tag_crate_triple: uint = 0x105; // top-level only
 
-pub const tag_dylib_dependency_formats: uint = 0x67;
+pub const tag_dylib_dependency_formats: uint = 0x106; // top-level only
 
 // Language items are a top-level directory (for speed). Hierarchy:
 //
@@ -163,51 +167,47 @@ pub enum astencode_tag { // Reserves 0x40 -- 0x5f
 //   - tag_lang_items_item_id: u32
 //   - tag_lang_items_item_node_id: u32
 
-pub const tag_lang_items: uint = 0x70;
-pub const tag_lang_items_item: uint = 0x71;
-pub const tag_lang_items_item_id: uint = 0x72;
-pub const tag_lang_items_item_node_id: uint = 0x73;
-pub const tag_lang_items_missing: uint = 0x74;
+pub const tag_lang_items: uint = 0x107; // top-level only
+pub const tag_lang_items_item: uint = 0x73;
+pub const tag_lang_items_item_id: uint = 0x74;
+pub const tag_lang_items_item_node_id: uint = 0x75;
+pub const tag_lang_items_missing: uint = 0x76;
 
-pub const tag_item_unnamed_field: uint = 0x75;
-pub const tag_items_data_item_visibility: uint = 0x76;
+pub const tag_item_unnamed_field: uint = 0x77;
+pub const tag_items_data_item_visibility: uint = 0x78;
 
 pub const tag_item_method_tps: uint = 0x79;
 pub const tag_item_method_fty: uint = 0x7a;
 
 pub const tag_mod_child: uint = 0x7b;
-pub const tag_misc_info: uint = 0x7c;
-pub const tag_misc_info_crate_items: uint = 0x7d;
-
-pub const tag_item_method_provided_source: uint = 0x7e;
-pub const tag_item_impl_vtables: uint = 0x7f;
+pub const tag_misc_info: uint = 0x108; // top-level only
+pub const tag_misc_info_crate_items: uint = 0x7c;
 
-pub const tag_impls: uint = 0x80;
-pub const tag_impls_impl: uint = 0x81;
+pub const tag_item_method_provided_source: uint = 0x7d;
+pub const tag_item_impl_vtables: uint = 0x7e;
 
-pub const tag_items_data_item_inherent_impl: uint = 0x82;
-pub const tag_items_data_item_extension_impl: uint = 0x83;
+pub const tag_impls: uint = 0x109; // top-level only
+pub const tag_impls_impl: uint = 0x7f;
 
-// GAP 0x84, 0x85, 0x86
+pub const tag_items_data_item_inherent_impl: uint = 0x80;
+pub const tag_items_data_item_extension_impl: uint = 0x81;
 
-pub const tag_native_libraries: uint = 0x87;
-pub const tag_native_libraries_lib: uint = 0x88;
-pub const tag_native_libraries_name: uint = 0x89;
-pub const tag_native_libraries_kind: uint = 0x8a;
+pub const tag_native_libraries: uint = 0x10a; // top-level only
+pub const tag_native_libraries_lib: uint = 0x82;
+pub const tag_native_libraries_name: uint = 0x83;
+pub const tag_native_libraries_kind: uint = 0x84;
 
-pub const tag_plugin_registrar_fn: uint = 0x8b;
+pub const tag_plugin_registrar_fn: uint = 0x10b; // top-level only
 
-// GAP 0x8c, 0x8d
+pub const tag_method_argument_names: uint = 0x85;
+pub const tag_method_argument_name: uint = 0x86;
 
-pub const tag_method_argument_names: uint = 0x8e;
-pub const tag_method_argument_name: uint = 0x8f;
+pub const tag_reachable_extern_fns: uint = 0x10c; // top-level only
+pub const tag_reachable_extern_fn_id: uint = 0x87;
 
-pub const tag_reachable_extern_fns: uint = 0x90;
-pub const tag_reachable_extern_fn_id: uint = 0x91;
+pub const tag_items_data_item_stability: uint = 0x88;
 
-pub const tag_items_data_item_stability: uint = 0x92;
-
-pub const tag_items_data_item_repr: uint = 0x93;
+pub const tag_items_data_item_repr: uint = 0x89;
 
 #[derive(Clone, Debug)]
 pub struct LinkMeta {
@@ -215,42 +215,40 @@ pub struct LinkMeta {
     pub crate_hash: Svh,
 }
 
-// GAP 0x94...0x98
-
-pub const tag_struct_fields: uint = 0x99;
-pub const tag_struct_field: uint = 0x9a;
-pub const tag_struct_field_id: uint = 0x9b;
+pub const tag_struct_fields: uint = 0x10d; // top-level only
+pub const tag_struct_field: uint = 0x8a;
+pub const tag_struct_field_id: uint = 0x8b;
 
-pub const tag_attribute_is_sugared_doc: uint = 0x9c;
+pub const tag_attribute_is_sugared_doc: uint = 0x8c;
 
-pub const tag_trait_def_bounds: uint = 0x9d;
+pub const tag_trait_def_bounds: uint = 0x8d;
 
-pub const tag_items_data_region: uint = 0x9e;
+pub const tag_items_data_region: uint = 0x8e;
 
-pub const tag_region_param_def: uint = 0xa0;
-pub const tag_region_param_def_ident: uint = 0xa1;
-pub const tag_region_param_def_def_id: uint = 0xa2;
-pub const tag_region_param_def_space: uint = 0xa3;
-pub const tag_region_param_def_index: uint = 0xa4;
+pub const tag_region_param_def: uint = 0x8f;
+pub const tag_region_param_def_ident: uint = 0x90;
+pub const tag_region_param_def_def_id: uint = 0x91;
+pub const tag_region_param_def_space: uint = 0x92;
+pub const tag_region_param_def_index: uint = 0x93;
 
-pub const tag_type_param_def: uint = 0xa5;
+pub const tag_type_param_def: uint = 0x94;
 
-pub const tag_item_generics: uint = 0xa6;
-pub const tag_method_ty_generics: uint = 0xa7;
+pub const tag_item_generics: uint = 0x95;
+pub const tag_method_ty_generics: uint = 0x96;
 
-pub const tag_predicate: uint = 0xa8;
-pub const tag_predicate_space: uint = 0xa9;
-pub const tag_predicate_data: uint = 0xb0;
+pub const tag_predicate: uint = 0x97;
+pub const tag_predicate_space: uint = 0x98;
+pub const tag_predicate_data: uint = 0x99;
 
-pub const tag_unsafety: uint = 0xb1;
+pub const tag_unsafety: uint = 0x9a;
 
-pub const tag_associated_type_names: uint = 0xb2;
-pub const tag_associated_type_name: uint = 0xb3;
+pub const tag_associated_type_names: uint = 0x9b;
+pub const tag_associated_type_name: uint = 0x9c;
 
-pub const tag_polarity: uint = 0xb4;
+pub const tag_polarity: uint = 0x9d;
 
-pub const tag_macro_defs: uint = 0xb5;
-pub const tag_macro_def: uint = 0xb6;
-pub const tag_macro_def_body: uint = 0xb7;
+pub const tag_macro_defs: uint = 0x10e; // top-level only
+pub const tag_macro_def: uint = 0x9e;
+pub const tag_macro_def_body: uint = 0x9f;
 
-pub const tag_paren_sugar: uint = 0xb8;
+pub const tag_paren_sugar: uint = 0xa0;
index ee2745ca66bc59980a675bd7dd7da2f24129d447..131a299cc500fc9af6e4fd5ad050be88e6b274c4 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
@@ -46,7 +46,7 @@
 use syntax::visit::Visitor;
 use syntax::visit;
 use syntax;
-use rbml::writer;
+use rbml::writer::Encoder;
 use rbml::io::SeekableMemWriter;
 
 /// A borrowed version of `ast::InlinedItem`.
@@ -57,8 +57,6 @@ pub enum InlinedItemRef<'a> {
     IIForeignRef(&'a ast::ForeignItem)
 }
 
-pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
-
 pub type EncodeInlinedItem<'a> =
     Box<FnMut(&EncodeContext, &mut Encoder, InlinedItemRef) + 'a>;
 
@@ -115,15 +113,13 @@ fn encode_trait_ref<'a, 'tcx>(rbml_w: &mut Encoder,
     };
 
     rbml_w.start_tag(tag);
-    tyencode::enc_trait_ref(rbml_w.writer, ty_str_ctxt, trait_ref);
+    tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
     rbml_w.end_tag();
 }
 
 // Item info table encoding
 fn encode_family(rbml_w: &mut Encoder, c: char) {
-    rbml_w.start_tag(tag_items_data_item_family);
-    rbml_w.writer.write_all(&[c as u8]);
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_u8(tag_items_data_item_family, c as u8);
 }
 
 pub fn def_to_string(did: DefId) -> String {
@@ -157,14 +153,9 @@ fn encode_bounds_and_type<'a, 'tcx>(rbml_w: &mut Encoder,
 }
 
 fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) {
-    rbml_w.start_tag(tag_items_data_item_variant);
     let s = def_to_string(vid);
-    rbml_w.writer.write_all(s.as_bytes());
-    rbml_w.end_tag();
-
-    rbml_w.start_tag(tag_mod_child);
-    rbml_w.wr_str(&s[..]);
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_items_data_item_variant, &s[..]);
+    rbml_w.wr_tagged_str(tag_mod_child, &s[..]);
 }
 
 pub fn write_closure_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
@@ -176,7 +167,7 @@ pub fn write_closure_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
         tcx: ecx.tcx,
         abbrevs: &ecx.type_abbrevs
     };
-    tyencode::enc_closure_ty(rbml_w.writer, ty_str_ctxt, closure_type);
+    tyencode::enc_closure_ty(rbml_w, ty_str_ctxt, closure_type);
 }
 
 pub fn write_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
@@ -188,7 +179,7 @@ pub fn write_type<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
         tcx: ecx.tcx,
         abbrevs: &ecx.type_abbrevs
     };
-    tyencode::enc_ty(rbml_w.writer, ty_str_ctxt, typ);
+    tyencode::enc_ty(rbml_w, ty_str_ctxt, typ);
 }
 
 pub fn write_trait_ref<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
@@ -200,7 +191,7 @@ pub fn write_trait_ref<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
         tcx: ecx.tcx,
         abbrevs: &ecx.type_abbrevs
     };
-    tyencode::enc_trait_ref(rbml_w.writer, ty_str_ctxt, trait_ref);
+    tyencode::enc_trait_ref(rbml_w, ty_str_ctxt, trait_ref);
 }
 
 pub fn write_region(ecx: &EncodeContext,
@@ -212,7 +203,7 @@ pub fn write_region(ecx: &EncodeContext,
         tcx: ecx.tcx,
         abbrevs: &ecx.type_abbrevs
     };
-    tyencode::enc_region(rbml_w.writer, ty_str_ctxt, r);
+    tyencode::enc_region(rbml_w, ty_str_ctxt, r);
 }
 
 fn encode_bounds<'a, 'tcx>(rbml_w: &mut Encoder,
@@ -225,7 +216,7 @@ fn encode_bounds<'a, 'tcx>(rbml_w: &mut Encoder,
                                         ds: def_to_string,
                                         tcx: ecx.tcx,
                                         abbrevs: &ecx.type_abbrevs };
-    tyencode::enc_bounds(rbml_w.writer, ty_str_ctxt, bounds);
+    tyencode::enc_bounds(rbml_w, ty_str_ctxt, bounds);
 
     rbml_w.end_tag();
 }
@@ -257,7 +248,7 @@ fn encode_method_fty<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
         tcx: ecx.tcx,
         abbrevs: &ecx.type_abbrevs
     };
-    tyencode::enc_bare_fn_ty(rbml_w.writer, ty_str_ctxt, typ);
+    tyencode::enc_bare_fn_ty(rbml_w, ty_str_ctxt, typ);
 
     rbml_w.end_tag();
 }
@@ -265,34 +256,26 @@ fn encode_method_fty<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>,
 fn encode_symbol(ecx: &EncodeContext,
                  rbml_w: &mut Encoder,
                  id: NodeId) {
-    rbml_w.start_tag(tag_items_data_item_symbol);
     match ecx.item_symbols.borrow().get(&id) {
         Some(x) => {
             debug!("encode_symbol(id={}, str={})", id, *x);
-            rbml_w.writer.write_all(x.as_bytes());
+            rbml_w.wr_tagged_str(tag_items_data_item_symbol, x);
         }
         None => {
             ecx.diag.handler().bug(
                 &format!("encode_symbol: id not found {}", id));
         }
     }
-    rbml_w.end_tag();
 }
 
 fn encode_disr_val(_: &EncodeContext,
                    rbml_w: &mut Encoder,
                    disr_val: ty::Disr) {
-    rbml_w.start_tag(tag_disr_val);
-    let s = disr_val.to_string();
-    rbml_w.writer.write_all(s.as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_disr_val, &disr_val.to_string());
 }
 
 fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) {
-    rbml_w.start_tag(tag_items_data_parent_item);
-    let s = def_to_string(id);
-    rbml_w.writer.write_all(s.as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_items_data_parent_item, &def_to_string(id));
 }
 
 fn encode_struct_fields(rbml_w: &mut Encoder,
@@ -307,10 +290,7 @@ fn encode_struct_fields(rbml_w: &mut Encoder,
         }
         encode_struct_field_family(rbml_w, f.vis);
         encode_def_id(rbml_w, f.id);
-        rbml_w.start_tag(tag_item_field_origin);
-        let s = def_to_string(origin);
-        rbml_w.writer.write_all(s.as_bytes());
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_item_field_origin, &def_to_string(origin));
         rbml_w.end_tag();
     }
 }
@@ -330,7 +310,7 @@ fn encode_enum_variant_info(ecx: &EncodeContext,
         let def_id = local_def(variant.node.id);
         index.push(entry {
             val: variant.node.id as i64,
-            pos: rbml_w.writer.tell().unwrap(),
+            pos: rbml_w.mark_stable_position(),
         });
         rbml_w.start_tag(tag_items_data_item);
         encode_def_id(rbml_w, def_id);
@@ -393,14 +373,11 @@ fn encode_reexported_static_method(rbml_w: &mut Encoder,
     debug!("(encode reexported static method) {}::{}",
             exp.name, token::get_name(method_name));
     rbml_w.start_tag(tag_items_data_item_reexport);
-    rbml_w.start_tag(tag_items_data_item_reexport_def_id);
-    rbml_w.wr_str(&def_to_string(method_def_id));
-    rbml_w.end_tag();
-    rbml_w.start_tag(tag_items_data_item_reexport_name);
-    rbml_w.wr_str(&format!("{}::{}",
-                          exp.name,
-                          token::get_name(method_name)));
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_items_data_item_reexport_def_id,
+                         &def_to_string(method_def_id));
+    rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
+                         &format!("{}::{}", exp.name,
+                                            token::get_name(method_name)));
     rbml_w.end_tag();
 }
 
@@ -536,12 +513,10 @@ fn encode_reexports(ecx: &EncodeContext,
                        exp.def_id.node,
                        id);
                 rbml_w.start_tag(tag_items_data_item_reexport);
-                rbml_w.start_tag(tag_items_data_item_reexport_def_id);
-                rbml_w.wr_str(&def_to_string(exp.def_id));
-                rbml_w.end_tag();
-                rbml_w.start_tag(tag_items_data_item_reexport_name);
-                rbml_w.wr_str(exp.name.as_str());
-                rbml_w.end_tag();
+                rbml_w.wr_tagged_str(tag_items_data_item_reexport_def_id,
+                                     &def_to_string(exp.def_id));
+                rbml_w.wr_tagged_str(tag_items_data_item_reexport_name,
+                                     exp.name.as_str());
                 rbml_w.end_tag();
                 encode_reexported_static_methods(ecx, rbml_w, path.clone(), exp);
             }
@@ -569,15 +544,12 @@ fn encode_info_for_mod(ecx: &EncodeContext,
 
     // Encode info about all the module children.
     for item in &md.items {
-        rbml_w.start_tag(tag_mod_child);
-        rbml_w.wr_str(&def_to_string(local_def(item.id)));
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_mod_child,
+                             &def_to_string(local_def(item.id)));
 
         each_auxiliary_node_id(&**item, |auxiliary_node_id| {
-            rbml_w.start_tag(tag_mod_child);
-            rbml_w.wr_str(&def_to_string(local_def(
-                        auxiliary_node_id)));
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_mod_child,
+                                 &def_to_string(local_def(auxiliary_node_id)));
             true
         });
 
@@ -587,9 +559,8 @@ fn encode_info_for_mod(ecx: &EncodeContext,
                    token::get_ident(ident),
                    did, ecx.tcx.map.node_to_string(did));
 
-            rbml_w.start_tag(tag_mod_impl);
-            rbml_w.wr_str(&def_to_string(local_def(did)));
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_mod_impl,
+                                 &def_to_string(local_def(did)));
         }
     }
 
@@ -618,67 +589,56 @@ fn encode_struct_field_family(rbml_w: &mut Encoder,
 }
 
 fn encode_visibility(rbml_w: &mut Encoder, visibility: ast::Visibility) {
-    rbml_w.start_tag(tag_items_data_item_visibility);
     let ch = match visibility {
         ast::Public => 'y',
         ast::Inherited => 'i',
     };
-    rbml_w.wr_str(&ch.to_string());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_u8(tag_items_data_item_visibility, ch as u8);
 }
 
 fn encode_explicit_self(rbml_w: &mut Encoder,
                         explicit_self: &ty::ExplicitSelfCategory) {
-    rbml_w.start_tag(tag_item_trait_method_explicit_self);
+    let tag = tag_item_trait_method_explicit_self;
 
     // Encode the base self type.
     match *explicit_self {
         ty::StaticExplicitSelfCategory => {
-            rbml_w.writer.write_all(&[ 's' as u8 ]);
+            rbml_w.wr_tagged_bytes(tag, &['s' as u8]);
         }
         ty::ByValueExplicitSelfCategory => {
-            rbml_w.writer.write_all(&[ 'v' as u8 ]);
+            rbml_w.wr_tagged_bytes(tag, &['v' as u8]);
         }
         ty::ByBoxExplicitSelfCategory => {
-            rbml_w.writer.write_all(&[ '~' as u8 ]);
+            rbml_w.wr_tagged_bytes(tag, &['~' as u8]);
         }
         ty::ByReferenceExplicitSelfCategory(_, m) => {
             // FIXME(#4846) encode custom lifetime
-            rbml_w.writer.write_all(&['&' as u8]);
-            encode_mutability(rbml_w, m);
+            let ch = encode_mutability(m);
+            rbml_w.wr_tagged_bytes(tag, &['&' as u8, ch]);
         }
     }
 
-    rbml_w.end_tag();
-
-    fn encode_mutability(rbml_w: &mut Encoder,
-                         m: ast::Mutability) {
+    fn encode_mutability(m: ast::Mutability) -> u8 {
         match m {
-            ast::MutImmutable => { rbml_w.writer.write_all(&[ 'i' as u8 ]); }
-            ast::MutMutable => { rbml_w.writer.write_all(&[ 'm' as u8 ]); }
+            ast::MutImmutable => 'i' as u8,
+            ast::MutMutable => 'm' as u8,
         }
     }
 }
 
 fn encode_item_sort(rbml_w: &mut Encoder, sort: char) {
-    rbml_w.start_tag(tag_item_trait_item_sort);
-    rbml_w.writer.write_all(&[ sort as u8 ]);
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_u8(tag_item_trait_item_sort, sort as u8);
 }
 
 fn encode_parent_sort(rbml_w: &mut Encoder, sort: char) {
-    rbml_w.start_tag(tag_item_trait_parent_sort);
-    rbml_w.writer.write_all(&[ sort as u8 ]);
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_u8(tag_item_trait_parent_sort, sort as u8);
 }
 
 fn encode_provided_source(rbml_w: &mut Encoder,
                           source_opt: Option<DefId>) {
     if let Some(source) = source_opt {
-        rbml_w.start_tag(tag_item_method_provided_source);
-        let s = def_to_string(source);
-        rbml_w.writer.write_all(s.as_bytes());
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_item_method_provided_source,
+                             &def_to_string(source));
     }
 }
 
@@ -697,10 +657,11 @@ fn encode_info_for_struct(ecx: &EncodeContext,
         let nm = field.name;
         let id = field.id.node;
 
-        index.push(entry {val: id as i64, pos: rbml_w.writer.tell().unwrap()});
+        let pos = rbml_w.mark_stable_position();
+        index.push(entry {val: id as i64, pos: pos});
         global_index.push(entry {
             val: id as i64,
-            pos: rbml_w.writer.tell().unwrap(),
+            pos: pos,
         });
         rbml_w.start_tag(tag_items_data_item);
         debug!("encode_info_for_struct: doing {} {}",
@@ -726,7 +687,7 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext,
                                struct_id: NodeId) {
     index.push(entry {
         val: ctor_id as i64,
-        pos: rbml_w.writer.tell().unwrap(),
+        pos: rbml_w.mark_stable_position(),
     });
 
     rbml_w.start_tag(tag_items_data_item);
@@ -747,8 +708,7 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext,
     // indicate that this is a tuple struct ctor, because downstream users will normally want
     // the tuple struct definition, but without this there is no way for them to tell that
     // they actually have a ctor rather than a normal function
-    rbml_w.start_tag(tag_items_data_item_is_tuple_struct_ctor);
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_bytes(tag_items_data_item_is_tuple_struct_ctor, &[]);
 
     rbml_w.end_tag();
 }
@@ -770,7 +730,7 @@ fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder,
     };
     for param in generics.types.iter() {
         rbml_w.start_tag(tag_type_param_def);
-        tyencode::enc_type_param_def(rbml_w.writer, ty_str_ctxt, param);
+        tyencode::enc_type_param_def(rbml_w, ty_str_ctxt, param);
         rbml_w.end_tag();
     }
 
@@ -804,7 +764,7 @@ fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder,
         rbml_w.wr_tagged_u8(tag_predicate_space, space as u8);
 
         rbml_w.start_tag(tag_predicate_data);
-        tyencode::enc_predicate(rbml_w.writer, ty_str_ctxt, predicate);
+        tyencode::enc_predicate(rbml_w, ty_str_ctxt, predicate);
         rbml_w.end_tag();
 
         rbml_w.end_tag();
@@ -919,12 +879,13 @@ fn encode_method_argument_names(rbml_w: &mut Encoder,
                                 decl: &ast::FnDecl) {
     rbml_w.start_tag(tag_method_argument_names);
     for arg in &decl.inputs {
-        rbml_w.start_tag(tag_method_argument_name);
+        let tag = tag_method_argument_name;
         if let ast::PatIdent(_, ref path1, _) = arg.pat.node {
             let name = token::get_ident(path1.node);
-            rbml_w.writer.write_all(name.as_bytes());
+            rbml_w.wr_tagged_bytes(tag, name.as_bytes());
+        } else {
+            rbml_w.wr_tagged_bytes(tag, &[]);
         }
-        rbml_w.end_tag();
     }
     rbml_w.end_tag();
 }
@@ -1002,11 +963,11 @@ fn encode_info_for_item(ecx: &EncodeContext,
                         vis: ast::Visibility) {
     let tcx = ecx.tcx;
 
-    fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
+    fn add_to_index(item: &ast::Item, rbml_w: &mut Encoder,
                     index: &mut Vec<entry<i64>>) {
         index.push(entry {
             val: item.id as i64,
-            pos: rbml_w.writer.tell().unwrap(),
+            pos: rbml_w.mark_stable_position(),
         });
     }
 
@@ -1091,9 +1052,8 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
 
         // Encode all the items in this module.
         for foreign_item in &fm.items {
-            rbml_w.start_tag(tag_mod_child);
-            rbml_w.wr_str(&def_to_string(local_def(foreign_item.id)));
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_mod_child,
+                                 &def_to_string(local_def(foreign_item.id)));
         }
         encode_visibility(rbml_w, vis);
         encode_stability(rbml_w, stab);
@@ -1263,7 +1223,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
 
             index.push(entry {
                 val: trait_item_def_id.def_id().node as i64,
-                pos: rbml_w.writer.tell().unwrap(),
+                pos: rbml_w.mark_stable_position(),
             });
 
             let trait_item_type =
@@ -1339,9 +1299,8 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
             }
             rbml_w.end_tag();
 
-            rbml_w.start_tag(tag_mod_child);
-            rbml_w.wr_str(&def_to_string(method_def_id.def_id()));
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_mod_child,
+                                 &def_to_string(method_def_id.def_id()));
         }
         encode_path(rbml_w, path.clone());
 
@@ -1362,7 +1321,7 @@ fn add_to_index(item: &ast::Item, rbml_w: &Encoder,
 
             index.push(entry {
                 val: item_def_id.def_id().node as i64,
-                pos: rbml_w.writer.tell().unwrap(),
+                pos: rbml_w.mark_stable_position(),
             });
 
             rbml_w.start_tag(tag_items_data_item);
@@ -1467,7 +1426,7 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext,
                                 abi: abi::Abi) {
     index.push(entry {
         val: nitem.id as i64,
-        pos: rbml_w.writer.tell().unwrap(),
+        pos: rbml_w.mark_stable_position(),
     });
 
     rbml_w.start_tag(tag_items_data_item);
@@ -1567,7 +1526,7 @@ fn encode_info_for_items(ecx: &EncodeContext,
     rbml_w.start_tag(tag_items_data);
     index.push(entry {
         val: ast::CRATE_NODE_ID as i64,
-        pos: rbml_w.writer.tell().unwrap(),
+        pos: rbml_w.mark_stable_position(),
     });
     encode_info_for_mod(ecx,
                         rbml_w,
@@ -1607,7 +1566,7 @@ fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn:
     let mut bucket_locs = Vec::new();
     rbml_w.start_tag(tag_index_buckets);
     for bucket in &buckets {
-        bucket_locs.push(rbml_w.writer.tell().unwrap());
+        bucket_locs.push(rbml_w.mark_stable_position());
         rbml_w.start_tag(tag_index_buckets_bucket);
         for elt in bucket {
             rbml_w.start_tag(tag_index_buckets_bucket_elt);
@@ -1642,21 +1601,15 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
     match mi.node {
       ast::MetaWord(ref name) => {
         rbml_w.start_tag(tag_meta_item_word);
-        rbml_w.start_tag(tag_meta_item_name);
-        rbml_w.writer.write_all(name.as_bytes());
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_meta_item_name, name);
         rbml_w.end_tag();
       }
       ast::MetaNameValue(ref name, ref value) => {
         match value.node {
           ast::LitStr(ref value, _) => {
             rbml_w.start_tag(tag_meta_item_name_value);
-            rbml_w.start_tag(tag_meta_item_name);
-            rbml_w.writer.write_all(name.as_bytes());
-            rbml_w.end_tag();
-            rbml_w.start_tag(tag_meta_item_value);
-            rbml_w.writer.write_all(value.as_bytes());
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_meta_item_name, name);
+            rbml_w.wr_tagged_str(tag_meta_item_value, value);
             rbml_w.end_tag();
           }
           _ => {/* FIXME (#623): encode other variants */ }
@@ -1664,9 +1617,7 @@ fn encode_meta_item(rbml_w: &mut Encoder, mi: &ast::MetaItem) {
       }
       ast::MetaList(ref name, ref items) => {
         rbml_w.start_tag(tag_meta_item_list);
-        rbml_w.start_tag(tag_meta_item_name);
-        rbml_w.writer.write_all(name.as_bytes());
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_meta_item_name, name);
         for inner_item in items {
             encode_meta_item(rbml_w, &**inner_item);
         }
@@ -1760,22 +1711,9 @@ fn encode_lang_items(ecx: &EncodeContext, rbml_w: &mut Encoder) {
         if let Some(id) = def_id {
             if id.krate == ast::LOCAL_CRATE {
                 rbml_w.start_tag(tag_lang_items_item);
-
-                rbml_w.start_tag(tag_lang_items_item_id);
-                {
-                    let wr: &mut SeekableMemWriter = rbml_w.writer;
-                    wr.write_be_u32(i as u32);
-                }
-                rbml_w.end_tag();   // tag_lang_items_item_id
-
-                rbml_w.start_tag(tag_lang_items_item_node_id);
-                {
-                    let wr: &mut SeekableMemWriter = rbml_w.writer;
-                    wr.write_be_u32(id.node as u32);
-                }
-                rbml_w.end_tag();   // tag_lang_items_item_node_id
-
-                rbml_w.end_tag();   // tag_lang_items_item
+                rbml_w.wr_tagged_u32(tag_lang_items_item_id, i as u32);
+                rbml_w.wr_tagged_u32(tag_lang_items_item_node_id, id.node as u32);
+                rbml_w.end_tag();
             }
         }
     }
@@ -1796,15 +1734,8 @@ fn encode_native_libraries(ecx: &EncodeContext, rbml_w: &mut Encoder) {
             cstore::NativeStatic => {} // these libraries are not propagated
             cstore::NativeFramework | cstore::NativeUnknown => {
                 rbml_w.start_tag(tag_native_libraries_lib);
-
-                rbml_w.start_tag(tag_native_libraries_kind);
-                rbml_w.writer.write_be_u32(kind as u32);
-                rbml_w.end_tag();
-
-                rbml_w.start_tag(tag_native_libraries_name);
-                rbml_w.writer.write_all(lib.as_bytes());
-                rbml_w.end_tag();
-
+                rbml_w.wr_tagged_u32(tag_native_libraries_kind, kind as u32);
+                rbml_w.wr_tagged_str(tag_native_libraries_name, lib);
                 rbml_w.end_tag();
             }
         }
@@ -1830,9 +1761,8 @@ fn encode_macro_defs(rbml_w: &mut Encoder,
         encode_name(rbml_w, def.ident.name);
         encode_attributes(rbml_w, &def.attrs);
 
-        rbml_w.start_tag(tag_macro_def_body);
-        rbml_w.wr_str(&pprust::tts_to_string(&def.body));
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_macro_def_body,
+                             &pprust::tts_to_string(&def.body));
 
         rbml_w.end_tag();
     }
@@ -1917,15 +1847,12 @@ fn encode_misc_info(ecx: &EncodeContext,
     rbml_w.start_tag(tag_misc_info);
     rbml_w.start_tag(tag_misc_info_crate_items);
     for item in &krate.module.items {
-        rbml_w.start_tag(tag_mod_child);
-        rbml_w.wr_str(&def_to_string(local_def(item.id)));
-        rbml_w.end_tag();
+        rbml_w.wr_tagged_str(tag_mod_child,
+                             &def_to_string(local_def(item.id)));
 
         each_auxiliary_node_id(&**item, |auxiliary_node_id| {
-            rbml_w.start_tag(tag_mod_child);
-            rbml_w.wr_str(&def_to_string(local_def(
-                        auxiliary_node_id)));
-            rbml_w.end_tag();
+            rbml_w.wr_tagged_str(tag_mod_child,
+                                 &def_to_string(local_def(auxiliary_node_id)));
             true
         });
     }
@@ -1956,35 +1883,25 @@ fn encode_reachable_extern_fns(ecx: &EncodeContext, rbml_w: &mut Encoder) {
 fn encode_crate_dep(rbml_w: &mut Encoder,
                     dep: decoder::CrateDep) {
     rbml_w.start_tag(tag_crate_dep);
-    rbml_w.start_tag(tag_crate_dep_crate_name);
-    rbml_w.writer.write_all(dep.name.as_bytes());
-    rbml_w.end_tag();
-    rbml_w.start_tag(tag_crate_dep_hash);
-    rbml_w.writer.write_all(dep.hash.as_str().as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_crate_dep_crate_name, &dep.name);
+    rbml_w.wr_tagged_str(tag_crate_dep_hash, dep.hash.as_str());
     rbml_w.end_tag();
 }
 
 fn encode_hash(rbml_w: &mut Encoder, hash: &Svh) {
-    rbml_w.start_tag(tag_crate_hash);
-    rbml_w.writer.write_all(hash.as_str().as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_crate_hash, hash.as_str());
 }
 
 fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) {
-    rbml_w.start_tag(tag_crate_crate_name);
-    rbml_w.writer.write_all(crate_name.as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_crate_crate_name, crate_name);
 }
 
 fn encode_crate_triple(rbml_w: &mut Encoder, triple: &str) {
-    rbml_w.start_tag(tag_crate_triple);
-    rbml_w.writer.write_all(triple.as_bytes());
-    rbml_w.end_tag();
+    rbml_w.wr_tagged_str(tag_crate_triple, triple);
 }
 
 fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) {
-    rbml_w.start_tag(tag_dylib_dependency_formats);
+    let tag = tag_dylib_dependency_formats;
     match ecx.tcx.dependency_formats.borrow().get(&config::CrateTypeDylib) {
         Some(arr) => {
             let s = arr.iter().enumerate().filter_map(|(i, slot)| {
@@ -1993,21 +1910,28 @@ fn encode_dylib_dependency_formats(rbml_w: &mut Encoder, ecx: &EncodeContext) {
                     cstore::RequireStatic => "s",
                 })).to_string())
             }).collect::<Vec<String>>();
-            rbml_w.writer.write_all(s.connect(",").as_bytes());
+            rbml_w.wr_tagged_str(tag, &s.connect(","));
+        }
+        None => {
+            rbml_w.wr_tagged_str(tag, "");
         }
-        None => {}
     }
-    rbml_w.end_tag();
 }
 
 // NB: Increment this as you change the metadata encoding version.
 #[allow(non_upper_case_globals)]
-pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 1 ];
+pub const metadata_encoding_version : &'static [u8] = &[b'r', b'u', b's', b't', 0, 0, 0, 2 ];
 
 pub fn encode_metadata(parms: EncodeParams, krate: &ast::Crate) -> Vec<u8> {
     let mut wr = SeekableMemWriter::new();
     encode_metadata_inner(&mut wr, parms, krate);
+
+    // RBML compacts the encoded bytes whenever appropriate,
+    // so there are some garbages left after the end of the data.
+    let metalen = wr.tell().unwrap() as uint;
     let mut v = wr.unwrap();
+    v.truncate(metalen);
+    assert_eq!(v.len(), metalen);
 
     // And here we run into yet another obscure archive bug: in which metadata
     // loaded from archives may have trailing garbage bytes. Awhile back one of
@@ -2089,7 +2013,7 @@ struct Stats {
         reachable: reachable,
      };
 
-    let mut rbml_w = writer::Encoder::new(wr);
+    let mut rbml_w = Encoder::new(wr);
 
     encode_crate_name(&mut rbml_w, &ecx.link_meta.crate_name);
     encode_crate_triple(&mut rbml_w,
@@ -2180,7 +2104,7 @@ struct Stats {
 // Get the encoded string for a type
 pub fn encoded_ty<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> String {
     let mut wr = SeekableMemWriter::new();
-    tyencode::enc_ty(&mut wr, &tyencode::ctxt {
+    tyencode::enc_ty(&mut Encoder::new(&mut wr), &tyencode::ctxt {
         diag: tcx.sess.diagnostic(),
         ds: def_to_string,
         tcx: tcx,
index a8d39f95739326174f2f3714ef3085173ffcbfa4..d1091b1d3f76ac34963bd6a2902bb6e9db839389 100644 (file)
@@ -202,9 +202,9 @@ fn canonicalize(path: Option<Path>) -> Option<Path> {
 }
 
 #[cfg(windows)]
-static PATH_ENTRY_SEPARATOR: &'static str = ";";
+const PATH_ENTRY_SEPARATOR: char = ';';
 #[cfg(not(windows))]
-static PATH_ENTRY_SEPARATOR: &'static str = ":";
+const PATH_ENTRY_SEPARATOR: char = ':';
 
 /// Returns RUST_PATH as a string, without default paths added
 pub fn get_rust_path() -> Option<String> {
index baecfb7eb22c5ec6cb95898ee8ca45f60e93f003..b33839f33e8203d7a08a8ea0be86294b9f47ec33 100644 (file)
@@ -555,11 +555,9 @@ fn parse_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> Ty<'tcx> w
       'k' => {
           assert_eq!(next(st), '[');
           let did = parse_def_(st, ClosureSource, conv);
-          let region = parse_region_(st, conv);
           let substs = parse_substs_(st, conv);
           assert_eq!(next(st), ']');
-          return ty::mk_closure(st.tcx, did,
-                  st.tcx.mk_region(region), st.tcx.mk_substs(substs));
+          return ty::mk_closure(st.tcx, did, st.tcx.mk_substs(substs));
       }
       'P' => {
           assert_eq!(next(st), '[');
index 76a365259aa5713a3eb952a9a3eadfffeefb0bba..86f1605b8bfaa706fa0de0f511703893d3f1c9a6 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
@@ -27,9 +27,9 @@
 use syntax::diagnostic::SpanHandler;
 use syntax::parse::token;
 
-use rbml::io::SeekableMemWriter;
+use rbml::writer::Encoder;
 
-macro_rules! mywrite { ($($arg:tt)*) => ({ write!($($arg)*); }) }
+macro_rules! mywrite { ($w:expr, $($arg:tt)*) => ({ write!($w.writer, $($arg)*); }) }
 
 pub struct ctxt<'a, 'tcx: 'a> {
     pub diag: &'a SpanHandler,
@@ -49,12 +49,14 @@ pub struct ty_abbrev {
 
 pub type abbrev_map<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>;
 
-pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
+pub fn enc_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
     match cx.abbrevs.borrow_mut().get(&t) {
-        Some(a) => { w.write_all(a.s.as_bytes()); return; }
+        Some(a) => { w.writer.write_all(a.s.as_bytes()); return; }
         None => {}
     }
-    let pos = w.tell().unwrap();
+
+    // type abbreviations needs a stable position
+    let pos = w.mark_stable_position();
 
     match t.sty {
         ty::ty_bool => mywrite!(w, "b"),
@@ -139,9 +141,8 @@ pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'t
             enc_substs(w, cx, substs);
             mywrite!(w, "]");
         }
-        ty::ty_closure(def, region, substs) => {
+        ty::ty_closure(def, substs) => {
             mywrite!(w, "k[{}|", (cx.ds)(def));
-            enc_region(w, cx, *region);
             enc_substs(w, cx, substs);
             mywrite!(w, "]");
         }
@@ -155,7 +156,7 @@ pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'t
         }
     }
 
-    let end = w.tell().unwrap();
+    let end = w.mark_stable_position();
     let len = end - pos;
     fn estimate_sz(u: u64) -> u64 {
         let mut n = u;
@@ -172,21 +173,21 @@ fn estimate_sz(u: u64) -> u64 {
     }
 }
 
-fn enc_mutability(w: &mut SeekableMemWriter, mt: ast::Mutability) {
+fn enc_mutability(w: &mut Encoder, mt: ast::Mutability) {
     match mt {
         ast::MutImmutable => (),
         ast::MutMutable => mywrite!(w, "m"),
     }
 }
 
-fn enc_mt<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+fn enc_mt<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                     mt: ty::mt<'tcx>) {
     enc_mutability(w, mt.mutbl);
     enc_ty(w, cx, mt.ty);
 }
 
-fn enc_opt<T, F>(w: &mut SeekableMemWriter, t: Option<T>, enc_f: F) where
-    F: FnOnce(&mut SeekableMemWriter, T),
+fn enc_opt<T, F>(w: &mut Encoder, t: Option<T>, enc_f: F) where
+    F: FnOnce(&mut Encoder, T),
 {
     match t {
         None => mywrite!(w, "n"),
@@ -197,11 +198,11 @@ fn enc_opt<T, F>(w: &mut SeekableMemWriter, t: Option<T>, enc_f: F) where
     }
 }
 
-fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut SeekableMemWriter,
+fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut Encoder,
                                            cx: &ctxt<'a, 'tcx>,
                                            v: &VecPerParamSpace<T>,
                                            mut op: F) where
-    F: FnMut(&mut SeekableMemWriter, &ctxt<'a, 'tcx>, &T),
+    F: FnMut(&mut Encoder, &ctxt<'a, 'tcx>, &T),
 {
     for &space in &subst::ParamSpace::all() {
         mywrite!(w, "[");
@@ -212,14 +213,14 @@ fn enc_vec_per_param_space<'a, 'tcx, T, F>(w: &mut SeekableMemWriter,
     }
 }
 
-pub fn enc_substs<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_substs<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                             substs: &subst::Substs<'tcx>) {
     enc_region_substs(w, cx, &substs.regions);
     enc_vec_per_param_space(w, cx, &substs.types,
                             |w, cx, &ty| enc_ty(w, cx, ty));
 }
 
-fn enc_region_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::RegionSubsts) {
+fn enc_region_substs(w: &mut Encoder, cx: &ctxt, substs: &subst::RegionSubsts) {
     match *substs {
         subst::ErasedRegions => {
             mywrite!(w, "e");
@@ -232,7 +233,7 @@ fn enc_region_substs(w: &mut SeekableMemWriter, cx: &ctxt, substs: &subst::Regio
     }
 }
 
-pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {
+pub fn enc_region(w: &mut Encoder, cx: &ctxt, r: ty::Region) {
     match r {
         ty::ReLateBound(id, br) => {
             mywrite!(w, "b[{}|", id.depth);
@@ -271,7 +272,7 @@ pub fn enc_region(w: &mut SeekableMemWriter, cx: &ctxt, r: ty::Region) {
     }
 }
 
-fn enc_scope(w: &mut SeekableMemWriter, _cx: &ctxt, scope: region::CodeExtent) {
+fn enc_scope(w: &mut Encoder, _cx: &ctxt, scope: region::CodeExtent) {
     match scope {
         region::CodeExtent::Misc(node_id) => mywrite!(w, "M{}", node_id),
         region::CodeExtent::Remainder(region::BlockRemainder {
@@ -280,12 +281,12 @@ fn enc_scope(w: &mut SeekableMemWriter, _cx: &ctxt, scope: region::CodeExtent) {
     }
 }
 
-fn enc_destruction_scope_data(w: &mut SeekableMemWriter,
+fn enc_destruction_scope_data(w: &mut Encoder,
                               d: region::DestructionScopeData) {
     mywrite!(w, "{}", d.node_id);
 }
 
-fn enc_bound_region(w: &mut SeekableMemWriter, cx: &ctxt, br: ty::BoundRegion) {
+fn enc_bound_region(w: &mut Encoder, cx: &ctxt, br: ty::BoundRegion) {
     match br {
         ty::BrAnon(idx) => {
             mywrite!(w, "a{}|", idx);
@@ -304,40 +305,40 @@ fn enc_bound_region(w: &mut SeekableMemWriter, cx: &ctxt, br: ty::BoundRegion) {
     }
 }
 
-pub fn enc_trait_ref<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_trait_ref<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                                s: &ty::TraitRef<'tcx>) {
     mywrite!(w, "{}|", (cx.ds)(s.def_id));
     enc_substs(w, cx, s.substs);
 }
 
-fn enc_unsafety(w: &mut SeekableMemWriter, p: ast::Unsafety) {
+fn enc_unsafety(w: &mut Encoder, p: ast::Unsafety) {
     match p {
         ast::Unsafety::Normal => mywrite!(w, "n"),
         ast::Unsafety::Unsafe => mywrite!(w, "u"),
     }
 }
 
-fn enc_abi(w: &mut SeekableMemWriter, abi: Abi) {
+fn enc_abi(w: &mut Encoder, abi: Abi) {
     mywrite!(w, "[");
     mywrite!(w, "{}", abi.name());
     mywrite!(w, "]")
 }
 
-pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_bare_fn_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                                 ft: &ty::BareFnTy<'tcx>) {
     enc_unsafety(w, ft.unsafety);
     enc_abi(w, ft.abi);
     enc_fn_sig(w, cx, &ft.sig);
 }
 
-pub fn enc_closure_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_closure_ty<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                                 ft: &ty::ClosureTy<'tcx>) {
     enc_unsafety(w, ft.unsafety);
     enc_fn_sig(w, cx, &ft.sig);
     enc_abi(w, ft.abi);
 }
 
-fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+fn enc_fn_sig<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                         fsig: &ty::PolyFnSig<'tcx>) {
     mywrite!(w, "[");
     for ty in &fsig.0.inputs {
@@ -359,7 +360,7 @@ fn enc_fn_sig<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
     }
 }
 
-pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::BuiltinBounds) {
+pub fn enc_builtin_bounds(w: &mut Encoder, _cx: &ctxt, bs: &ty::BuiltinBounds) {
     for bound in bs {
         match bound {
             ty::BoundSend => mywrite!(w, "S"),
@@ -372,7 +373,7 @@ pub fn enc_builtin_bounds(w: &mut SeekableMemWriter, _cx: &ctxt, bs: &ty::Builti
     mywrite!(w, ".");
 }
 
-pub fn enc_existential_bounds<'a,'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_existential_bounds<'a,'tcx>(w: &mut Encoder,
                                        cx: &ctxt<'a,'tcx>,
                                        bs: &ty::ExistentialBounds<'tcx>) {
     let param_bounds = ty::ParamBounds { trait_bounds: vec!(),
@@ -382,7 +383,7 @@ pub fn enc_existential_bounds<'a,'tcx>(w: &mut SeekableMemWriter,
     enc_bounds(w, cx, &param_bounds);
 }
 
-pub fn enc_bounds<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_bounds<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                             bs: &ty::ParamBounds<'tcx>) {
     enc_builtin_bounds(w, cx, &bs.builtin_bounds);
 
@@ -401,7 +402,7 @@ pub fn enc_bounds<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
     mywrite!(w, ".");
 }
 
-pub fn enc_region_bounds<'a, 'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_region_bounds<'a, 'tcx>(w: &mut Encoder,
                             cx: &ctxt<'a, 'tcx>,
                             rs: &[ty::Region]) {
     for &r in rs {
@@ -412,7 +413,7 @@ pub fn enc_region_bounds<'a, 'tcx>(w: &mut SeekableMemWriter,
     mywrite!(w, ".");
 }
 
-pub fn enc_type_param_def<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>,
+pub fn enc_type_param_def<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
                                     v: &ty::TypeParameterDef<'tcx>) {
     mywrite!(w, "{}:{}|{}|{}|",
              token::get_name(v.name), (cx.ds)(v.def_id),
@@ -421,7 +422,7 @@ pub fn enc_type_param_def<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tc
     enc_object_lifetime_default(w, cx, v.object_lifetime_default);
 }
 
-fn enc_object_lifetime_default<'a, 'tcx>(w: &mut SeekableMemWriter,
+fn enc_object_lifetime_default<'a, 'tcx>(w: &mut Encoder,
                                          cx: &ctxt<'a, 'tcx>,
                                          default: Option<ty::ObjectLifetimeDefault>)
 {
@@ -435,7 +436,7 @@ fn enc_object_lifetime_default<'a, 'tcx>(w: &mut SeekableMemWriter,
     }
 }
 
-pub fn enc_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
+pub fn enc_predicate<'a, 'tcx>(w: &mut Encoder,
                                cx: &ctxt<'a, 'tcx>,
                                p: &ty::Predicate<'tcx>)
 {
@@ -466,7 +467,7 @@ pub fn enc_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
     }
 }
 
-fn enc_projection_predicate<'a, 'tcx>(w: &mut SeekableMemWriter,
+fn enc_projection_predicate<'a, 'tcx>(w: &mut Encoder,
                                       cx: &ctxt<'a, 'tcx>,
                                       data: &ty::ProjectionPredicate<'tcx>) {
     enc_trait_ref(w, cx, &*data.projection_ty.trait_ref);
index 5983829ed8fbef20e56b6124b2a1e868201aaf0d..599dde4b70155affa34456593f110b4f4f1675e3 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
 use std::num::FromPrimitive;
 use std::rc::Rc;
 
-use rbml::io::SeekableMemWriter;
-use rbml::{reader, writer};
+use rbml::reader;
+use rbml::writer::Encoder;
 use rbml;
 use serialize;
 use serialize::{Decodable, Decoder, DecoderHelpers, Encodable};
 use serialize::{EncoderHelpers};
 
+#[cfg(test)] use rbml::io::SeekableMemWriter;
 #[cfg(test)] use syntax::parse;
 #[cfg(test)] use syntax::print::pprust;
 
@@ -68,8 +69,6 @@ trait tr_intern {
     fn tr_intern(&self, dcx: &DecodeContext) -> ast::DefId;
 }
 
-pub type Encoder<'a> = writer::Encoder<'a, SeekableMemWriter>;
-
 // ______________________________________________________________________
 // Top-level methods.
 
@@ -414,9 +413,8 @@ fn decode_ast(par_doc: rbml::Doc) -> ast::InlinedItem {
 // ______________________________________________________________________
 // Encoding and decoding of ast::def
 
-fn decode_def(dcx: &DecodeContext, doc: rbml::Doc) -> def::Def {
-    let mut dsr = reader::Decoder::new(doc);
-    let def: def::Def = Decodable::decode(&mut dsr).unwrap();
+fn decode_def(dcx: &DecodeContext, dsr: &mut reader::Decoder) -> def::Def {
+    let def: def::Def = Decodable::decode(dsr).unwrap();
     def.tr(dcx)
 }
 
@@ -911,7 +909,7 @@ fn emit_trait_ref<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
     fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
                                type_param_def: &ty::TypeParameterDef<'tcx>) {
         self.emit_opaque(|this| {
-            Ok(tyencode::enc_type_param_def(this.writer,
+            Ok(tyencode::enc_type_param_def(this,
                                          &ecx.ty_str_ctxt(),
                                          type_param_def))
         });
@@ -920,7 +918,7 @@ fn emit_type_param_def<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
     fn emit_predicate<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
                           predicate: &ty::Predicate<'tcx>) {
         self.emit_opaque(|this| {
-            Ok(tyencode::enc_predicate(this.writer,
+            Ok(tyencode::enc_predicate(this,
                                        &ecx.ty_str_ctxt(),
                                        predicate))
         });
@@ -954,20 +952,20 @@ fn emit_type_scheme<'b>(&mut self,
 
     fn emit_existential_bounds<'b>(&mut self, ecx: &e::EncodeContext<'b,'tcx>,
                                    bounds: &ty::ExistentialBounds<'tcx>) {
-        self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this.writer,
+        self.emit_opaque(|this| Ok(tyencode::enc_existential_bounds(this,
                                                                     &ecx.ty_str_ctxt(),
                                                                     bounds)));
     }
 
     fn emit_builtin_bounds(&mut self, ecx: &e::EncodeContext, bounds: &ty::BuiltinBounds) {
-        self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this.writer,
+        self.emit_opaque(|this| Ok(tyencode::enc_builtin_bounds(this,
                                                                 &ecx.ty_str_ctxt(),
                                                                 bounds)));
     }
 
     fn emit_substs<'b>(&mut self, ecx: &e::EncodeContext<'b, 'tcx>,
                        substs: &subst::Substs<'tcx>) {
-        self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer,
+        self.emit_opaque(|this| Ok(tyencode::enc_substs(this,
                                                            &ecx.ty_str_ctxt(),
                                                            substs)));
     }
@@ -1115,7 +1113,7 @@ fn tag<F>(&mut self,
     }
 
     fn id(&mut self, id: ast::NodeId) {
-        self.wr_tagged_u64(c::tag_table_id as uint, id as u64);
+        id.encode(self).unwrap();
     }
 }
 
@@ -1152,51 +1150,44 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
     if let Some(def) = tcx.def_map.borrow().get(&id).map(|d| d.full_def()) {
         rbml_w.tag(c::tag_table_def, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| def.encode(rbml_w).unwrap());
+            def.encode(rbml_w).unwrap();
         })
     }
 
     if let Some(ty) = tcx.node_types.borrow().get(&id) {
         rbml_w.tag(c::tag_table_node_type, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_ty(ecx, *ty);
-            })
+            rbml_w.emit_ty(ecx, *ty);
         })
     }
 
     if let Some(item_substs) = tcx.item_substs.borrow().get(&id) {
         rbml_w.tag(c::tag_table_item_subst, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_substs(ecx, &item_substs.substs);
-            })
+            rbml_w.emit_substs(ecx, &item_substs.substs);
         })
     }
 
     if let Some(fv) = tcx.freevars.borrow().get(&id) {
         rbml_w.tag(c::tag_table_freevars, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
-                    Ok(encode_freevar_entry(rbml_w, fv_entry))
-                });
-            })
+            rbml_w.emit_from_vec(fv, |rbml_w, fv_entry| {
+                Ok(encode_freevar_entry(rbml_w, fv_entry))
+            });
         });
 
         for freevar in fv {
             rbml_w.tag(c::tag_table_upvar_capture_map, |rbml_w| {
                 rbml_w.id(id);
-                rbml_w.tag(c::tag_table_val, |rbml_w| {
-                    let var_id = freevar.def.def_id().node;
-                    let upvar_id = ty::UpvarId {
-                        var_id: var_id,
-                        closure_expr_id: id
-                    };
-                    let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
-                    var_id.encode(rbml_w);
-                    upvar_capture.encode(rbml_w);
-                })
+
+                let var_id = freevar.def.def_id().node;
+                let upvar_id = ty::UpvarId {
+                    var_id: var_id,
+                    closure_expr_id: id
+                };
+                let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone();
+                var_id.encode(rbml_w);
+                upvar_capture.encode(rbml_w);
             })
         }
     }
@@ -1205,18 +1196,14 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
     if let Some(type_scheme) = tcx.tcache.borrow().get(&lid) {
         rbml_w.tag(c::tag_table_tcache, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_type_scheme(ecx, type_scheme.clone());
-            })
+            rbml_w.emit_type_scheme(ecx, type_scheme.clone());
         })
     }
 
     if let Some(type_param_def) = tcx.ty_param_defs.borrow().get(&id) {
         rbml_w.tag(c::tag_table_param_defs, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_type_param_def(ecx, type_param_def)
-            })
+            rbml_w.emit_type_param_def(ecx, type_param_def)
         })
     }
 
@@ -1224,18 +1211,14 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
     if let Some(method) = tcx.method_map.borrow().get(&method_call) {
         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
-            })
+            encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
         })
     }
 
     if let Some(trait_ref) = tcx.object_cast_map.borrow().get(&id) {
         rbml_w.tag(c::tag_table_object_cast_map, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
-            })
+            rbml_w.emit_trait_ref(ecx, &*trait_ref.0);
         })
     }
 
@@ -1246,9 +1229,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
                 if let Some(method) = tcx.method_map.borrow().get(&method_call) {
                     rbml_w.tag(c::tag_table_method_map, |rbml_w| {
                         rbml_w.id(id);
-                        rbml_w.tag(c::tag_table_val, |rbml_w| {
-                            encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
-                        })
+                        encode_method_callee(ecx, rbml_w, method_call.adjustment, method)
                     })
                 }
             }
@@ -1259,10 +1240,8 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
                     if let Some(method) = tcx.method_map.borrow().get(&method_call) {
                         rbml_w.tag(c::tag_table_method_map, |rbml_w| {
                             rbml_w.id(id);
-                            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                                encode_method_callee(ecx, rbml_w,
-                                                     method_call.adjustment, method)
-                            })
+                            encode_method_callee(ecx, rbml_w,
+                                                 method_call.adjustment, method)
                         })
                     }
                 }
@@ -1274,36 +1253,28 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext,
 
         rbml_w.tag(c::tag_table_adjustments, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_auto_adjustment(ecx, adjustment);
-            })
+            rbml_w.emit_auto_adjustment(ecx, adjustment);
         })
     }
 
     if let Some(closure_type) = tcx.closure_tys.borrow().get(&ast_util::local_def(id)) {
         rbml_w.tag(c::tag_table_closure_tys, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                rbml_w.emit_closure_type(ecx, closure_type);
-            })
+            rbml_w.emit_closure_type(ecx, closure_type);
         })
     }
 
     if let Some(closure_kind) = tcx.closure_kinds.borrow().get(&ast_util::local_def(id)) {
         rbml_w.tag(c::tag_table_closure_kinds, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                encode_closure_kind(rbml_w, *closure_kind)
-            })
+            encode_closure_kind(rbml_w, *closure_kind)
         })
     }
 
     for &qualif in tcx.const_qualif_map.borrow().get(&id).iter() {
         rbml_w.tag(c::tag_table_const_qualif, |rbml_w| {
             rbml_w.id(id);
-            rbml_w.tag(c::tag_table_val, |rbml_w| {
-                qualif.encode(rbml_w).unwrap()
-            })
+            qualif.encode(rbml_w).unwrap()
         })
     }
 }
@@ -1831,13 +1802,14 @@ fn decode_side_tables(dcx: &DecodeContext,
                       ast_doc: rbml::Doc) {
     let tbl_doc = ast_doc.get(c::tag_table as uint);
     reader::docs(tbl_doc, |tag, entry_doc| {
-        let id0 = entry_doc.get(c::tag_table_id as uint).as_int();
-        let id = dcx.tr_id(id0 as ast::NodeId);
+        let mut entry_dsr = reader::Decoder::new(entry_doc);
+        let id0: ast::NodeId = Decodable::decode(&mut entry_dsr).unwrap();
+        let id = dcx.tr_id(id0);
 
         debug!(">> Side table document with tag 0x{:x} \
                 found for id {} (orig {})",
                tag, id, id0);
-        let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_uint(tag);
+        let decoded_tag: Option<c::astencode_tag> = FromPrimitive::from_usize(tag);
         match decoded_tag {
             None => {
                 dcx.tcx.sess.bug(
@@ -1845,13 +1817,11 @@ fn decode_side_tables(dcx: &DecodeContext,
                             tag));
             }
             Some(value) => {
-                let val_doc = entry_doc.get(c::tag_table_val as uint);
-                let mut val_dsr = reader::Decoder::new(val_doc);
-                let val_dsr = &mut val_dsr;
+                let val_dsr = &mut entry_dsr;
 
                 match value {
                     c::tag_table_def => {
-                        let def = decode_def(dcx, val_doc);
+                        let def = decode_def(dcx, val_dsr);
                         dcx.tcx.def_map.borrow_mut().insert(id, def::PathResolution {
                             base_def: def,
                             // This doesn't matter cross-crate.
@@ -1995,7 +1965,7 @@ fn mk_ctxt() -> parse::ParseSess {
 fn roundtrip(in_item: Option<P<ast::Item>>) {
     let in_item = in_item.unwrap();
     let mut wr = SeekableMemWriter::new();
-    encode_item_ast(&mut writer::Encoder::new(&mut wr), &*in_item);
+    encode_item_ast(&mut Encoder::new(&mut wr), &*in_item);
     let rbml_doc = rbml::Doc::new(wr.get_ref());
     let out_item = decode_item_ast(rbml_doc);
 
index 1718df702553f0f94886f0b365fd880ad55ad439..faed3f5977fdcb01b67747b6867ac5d6ecf909dc 100644 (file)
@@ -205,7 +205,7 @@ pub fn new(tcx: &'a ty::ctxt<'tcx>,
                oper: O,
                id_range: IdRange,
                bits_per_id: uint) -> DataFlowContext<'a, 'tcx, O> {
-        let words_per_id = (bits_per_id + usize::BITS - 1) / usize::BITS;
+        let words_per_id = (bits_per_id + usize::BITS as usize - 1) / usize::BITS as usize;
         let num_nodes = cfg.graph.all_nodes().len();
 
         debug!("DataFlowContext::new(analysis_name: {}, id_range={:?}, \
@@ -377,7 +377,7 @@ fn each_bit<F>(&self, words: &[uint], mut f: F) -> bool where
 
         for (word_index, &word) in words.iter().enumerate() {
             if word != 0 {
-                let base_index = word_index * usize::BITS;
+                let base_index = word_index * usize::BITS as usize;
                 for offset in 0..usize::BITS {
                     let bit = 1 << offset;
                     if (word & bit) != 0 {
@@ -390,7 +390,7 @@ fn each_bit<F>(&self, words: &[uint], mut f: F) -> bool where
                         // whether the bit_index is greater than the
                         // actual value the user specified and stop
                         // iterating if so.
-                        let bit_index = base_index + offset;
+                        let bit_index = base_index + offset as usize;
                         if bit_index >= self.bits_per_id {
                             return true;
                         } else if !f(bit_index) {
@@ -609,8 +609,8 @@ fn bitwise<Op:BitwiseOperator>(out_vec: &mut [uint],
 fn set_bit(words: &mut [uint], bit: uint) -> bool {
     debug!("set_bit: words={} bit={}",
            mut_bits_to_string(words), bit_str(bit));
-    let word = bit / usize::BITS;
-    let bit_in_word = bit % usize::BITS;
+    let word = bit / usize::BITS as usize;
+    let bit_in_word = bit % usize::BITS as usize;
     let bit_mask = 1 << bit_in_word;
     debug!("word={} bit_in_word={} bit_mask={}", word, bit_in_word, word);
     let oldv = words[word];
index 7584a2e44cc7c0b3316be2718c153705e530ec03..063845c6c34255df36dcf0dad2fc04c8bb2c39d3 100644 (file)
@@ -74,7 +74,7 @@ pub fn simplify_type(tcx: &ty::ctxt,
             let def_id = tcx.lang_items.owned_box().unwrap();
             Some(StructSimplifiedType(def_id))
         }
-        ty::ty_closure(def_id, _, _) => {
+        ty::ty_closure(def_id, _) => {
             Some(ClosureSimplifiedType(def_id))
         }
         ty::ty_tup(ref tys) => {
index b782a655d89ff11155bf156793000776a9c6bbed..be94a73df37ba82d7b4c02c4427b8a58588ef67b 100644 (file)
@@ -503,15 +503,14 @@ pub fn super_tys<'tcx, C>(this: &C,
             Ok(ty::mk_struct(tcx, a_id, tcx.mk_substs(substs)))
         }
 
-        (&ty::ty_closure(a_id, a_region, a_substs),
-         &ty::ty_closure(b_id, b_region, b_substs))
+        (&ty::ty_closure(a_id, a_substs),
+         &ty::ty_closure(b_id, b_substs))
           if a_id == b_id => {
             // All ty_closure types with the same id represent
             // the (anonymous) type of the same closure expression. So
             // all of their regions should be equated.
-            let region = try!(this.equate().regions(*a_region, *b_region));
             let substs = try!(this.substs_variances(None, a_substs, b_substs));
-            Ok(ty::mk_closure(tcx, a_id, tcx.mk_region(region), tcx.mk_substs(substs)))
+            Ok(ty::mk_closure(tcx, a_id, tcx.mk_substs(substs)))
         }
 
         (&ty::ty_uniq(a_inner), &ty::ty_uniq(b_inner)) => {
index 56c5928a132b14cd56ac92d19588bc227c912c55..3525d46a1f2f1ee02070a104642ac10e03676be3 100644 (file)
@@ -71,7 +71,7 @@ pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> {
     }
 
     pub fn item_name(index: uint) -> &'static str {
-        let item: Option<LangItem> = FromPrimitive::from_uint(index);
+        let item: Option<LangItem> = FromPrimitive::from_usize(index);
         match item {
             $( Some($variant) => $name, )*
             None => "???"
index 2ac019aa964dc6f1f0f15c9c4a17e917d8085a13..892452ccc1c29d3b348a94ec1880a33baa562c55 100644 (file)
@@ -51,8 +51,8 @@
 //! enclosing function.  On the way down the tree, it identifies those AST
 //! nodes and variable IDs that will be needed for the liveness analysis
 //! and assigns them contiguous IDs.  The liveness id for an AST node is
-//! called a `live_node` (it's a newtype'd uint) and the id for a variable
-//! is called a `variable` (another newtype'd uint).
+//! called a `live_node` (it's a newtype'd usize) and the id for a variable
+//! is called a `variable` (another newtype'd usize).
 //!
 //! On the way back up the tree, as we are about to exit from a function
 //! declaration we allocate a `liveness` instance.  Now that we know
 use lint;
 use util::nodemap::NodeMap;
 
-use std::{fmt, old_io, uint};
+use std::{fmt, old_io, usize};
 use std::rc::Rc;
 use std::iter::repeat;
 use syntax::ast::{self, NodeId, Expr};
@@ -138,17 +138,17 @@ enum LoopKind<'a> {
 }
 
 #[derive(Copy, PartialEq)]
-struct Variable(uint);
+struct Variable(usize);
 
 #[derive(Copy, PartialEq)]
-struct LiveNode(uint);
+struct LiveNode(usize);
 
 impl Variable {
-    fn get(&self) -> uint { let Variable(v) = *self; v }
+    fn get(&self) -> usize { let Variable(v) = *self; v }
 }
 
 impl LiveNode {
-    fn get(&self) -> uint { let LiveNode(v) = *self; v }
+    fn get(&self) -> usize { let LiveNode(v) = *self; v }
 }
 
 impl Clone for LiveNode {
@@ -232,11 +232,11 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 impl LiveNode {
     fn is_valid(&self) -> bool {
-        self.get() != uint::MAX
+        self.get() != usize::MAX
     }
 }
 
-fn invalid_node() -> LiveNode { LiveNode(uint::MAX) }
+fn invalid_node() -> LiveNode { LiveNode(usize::MAX) }
 
 struct CaptureInfo {
     ln: LiveNode,
@@ -260,8 +260,8 @@ enum VarKind {
 struct IrMaps<'a, 'tcx: 'a> {
     tcx: &'a ty::ctxt<'tcx>,
 
-    num_live_nodes: uint,
-    num_vars: uint,
+    num_live_nodes: usize,
+    num_vars: usize,
     live_node_map: NodeMap<LiveNode>,
     variable_map: NodeMap<Variable>,
     capture_info_map: NodeMap<Rc<Vec<CaptureInfo>>>,
@@ -540,9 +540,9 @@ struct Specials {
     clean_exit_var: Variable
 }
 
-static ACC_READ: uint = 1;
-static ACC_WRITE: uint = 2;
-static ACC_USE: uint = 4;
+const ACC_READ: u32 = 1;
+const ACC_WRITE: u32 = 2;
+const ACC_USE: u32 = 4;
 
 struct Liveness<'a, 'tcx: 'a> {
     ir: &'a mut IrMaps<'a, 'tcx>,
@@ -631,7 +631,7 @@ fn define_bindings_in_arm_pats(&mut self, pat: Option<&ast::Pat>, succ: LiveNode
         succ
     }
 
-    fn idx(&self, ln: LiveNode, var: Variable) -> uint {
+    fn idx(&self, ln: LiveNode, var: Variable) -> usize {
         ln.get() * self.ir.num_vars + var.get()
     }
 
@@ -670,7 +670,7 @@ fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
     }
 
     fn indices2<F>(&mut self, ln: LiveNode, succ_ln: LiveNode, mut op: F) where
-        F: FnMut(&mut Liveness<'a, 'tcx>, uint, uint),
+        F: FnMut(&mut Liveness<'a, 'tcx>, usize, usize),
     {
         let node_base_idx = self.idx(ln, Variable(0));
         let succ_base_idx = self.idx(succ_ln, Variable(0));
@@ -684,7 +684,7 @@ fn write_vars<F>(&self,
                      ln: LiveNode,
                      mut test: F)
                      -> old_io::IoResult<()> where
-        F: FnMut(uint) -> LiveNode,
+        F: FnMut(usize) -> LiveNode,
     {
         let node_base_idx = self.idx(ln, Variable(0));
         for var_idx in 0..self.ir.num_vars {
@@ -807,7 +807,7 @@ fn define(&mut self, writer: LiveNode, var: Variable) {
     }
 
     // Either read, write, or both depending on the acc bitset
-    fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) {
+    fn acc(&mut self, ln: LiveNode, var: Variable, acc: u32) {
         debug!("{:?} accesses[{:x}] {:?}: {}",
                ln, acc, var, self.ln_str(ln));
 
@@ -1283,7 +1283,7 @@ fn propagate_through_lvalue_components(&mut self,
     }
 
     // see comment on propagate_through_lvalue()
-    fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
+    fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
                     -> LiveNode {
         match expr.node {
           ast::ExprPath(..) => {
@@ -1298,7 +1298,7 @@ fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
         }
     }
 
-    fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: uint)
+    fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
                    -> LiveNode {
         match self.ir.tcx.def_map.borrow()[expr.id].full_def() {
           DefLocal(nid) => {
@@ -1496,7 +1496,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
     fn fn_ret(&self, id: NodeId) -> ty::PolyFnOutput<'tcx> {
         let fn_ty = ty::node_id_to_type(self.ir.tcx, id);
         match fn_ty.sty {
-            ty::ty_closure(closure_def_id, _, substs) =>
+            ty::ty_closure(closure_def_id, substs) =>
                 self.ir.tcx.closure_type(closure_def_id, substs).sig.output(),
             _ =>
                 ty::ty_fn_ret(fn_ty),
index c4446b87855ca622d6a5ebd4fcca78f7ca0b9042..1f02f13a4a17823312e934e27c912d5e8a7e45e0 100644 (file)
@@ -607,7 +607,7 @@ pub fn cat_def(&self,
           def::DefUpvar(var_id, fn_node_id) => {
               let ty = try!(self.node_ty(fn_node_id));
               match ty.sty {
-                  ty::ty_closure(closure_id, _, _) => {
+                  ty::ty_closure(closure_id, _) => {
                       match self.typer.closure_kind(closure_id) {
                           Some(kind) => {
                               self.cat_upvar(id, span, var_id, fn_node_id, kind)
index 7db1138ac72f6e58a168ce6ca3fb08719141208b..b4db3aba7867dc72cbaec8a3519dd07c5725a32f 100644 (file)
@@ -320,8 +320,10 @@ fn to_code_extent(&self) -> Option<CodeExtent> {
 
 #[derive(Debug, Copy)]
 pub struct Context {
+    /// the scope that contains any new variables declared
     var_parent: InnermostDeclaringBlock,
 
+    /// region parent of expressions etc
     parent: InnermostEnclosingExpr,
 }
 
index 7d4febb38e678186ff6b5380f55e53ec20bb1a2c..b9a863f4fe46f51738edc029115ad6dca2304fe6 100644 (file)
@@ -154,7 +154,7 @@ fn consider_unification_despite_ambiguity<'cx,'tcx>(selcx: &mut SelectionContext
     debug!("consider_unification_despite_ambiguity: self_ty.sty={:?}",
            self_ty.sty);
     match self_ty.sty {
-        ty::ty_closure(closure_def_id, _, substs) => {
+        ty::ty_closure(closure_def_id, substs) => {
             let closure_typer = selcx.closure_typer();
             let closure_type = closure_typer.closure_type(closure_def_id, substs);
             let ty::Binder((_, ret_type)) =
index d8c62780a781fa124bbb02ca0ea3b0dc35a673a5..470315c78f81d8d15ac1908c4b1988be543155df 100644 (file)
@@ -293,7 +293,7 @@ fn consider_unification_despite_ambiguity(&mut self, obligation: &TraitObligatio
         // lifetimes can appear inside the self-type.
         let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
         let (closure_def_id, substs) = match self_ty.sty {
-            ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
+            ty::ty_closure(id, ref substs) => (id, substs.clone()),
             _ => { return; }
         };
         assert!(!substs.has_escaping_regions());
@@ -1054,7 +1054,7 @@ fn assemble_closure_candidates(&mut self,
 
         let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
         let (closure_def_id, substs) = match self_ty.sty {
-            ty::ty_closure(id, _, ref substs) => (id, substs.clone()),
+            ty::ty_closure(id, ref substs) => (id, substs.clone()),
             ty::ty_infer(ty::TyVar(_)) => {
                 debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
                 candidates.ambiguous = true;
@@ -1533,7 +1533,7 @@ fn builtin_bound(&mut self,
             // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
             ty::ty_tup(ref tys) => Ok(If(tys.clone())),
 
-            ty::ty_closure(def_id, _, substs) => {
+            ty::ty_closure(def_id, substs) => {
                 // FIXME -- This case is tricky. In the case of by-ref
                 // closures particularly, we need the results of
                 // inference to decide how to reflect the type of each
@@ -1687,7 +1687,7 @@ fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Option<Vec<Ty<'tcx>>> {
                 Some(tys.clone())
             }
 
-            ty::ty_closure(def_id, _, substs) => {
+            ty::ty_closure(def_id, substs) => {
                 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
 
                 match self.closure_typer.closure_upvars(def_id, substs) {
index 635ec09d3394cd52039a4ebba05b6bf026b45e86..c69f2d214f0c49aee4407407311cde8e0c295fc7 100644 (file)
@@ -76,7 +76,7 @@
 use std::mem;
 use std::ops;
 use std::rc::Rc;
-use std::vec::{CowVec, IntoIter};
+use std::vec::IntoIter;
 use collections::enum_set::{EnumSet, CLike};
 use std::collections::{HashMap, HashSet};
 use syntax::abi;
@@ -1367,7 +1367,7 @@ pub enum sty<'tcx> {
     ty_trait(Box<TyTrait<'tcx>>),
     ty_struct(DefId, &'tcx Substs<'tcx>),
 
-    ty_closure(DefId, &'tcx Region, &'tcx Substs<'tcx>),
+    ty_closure(DefId, &'tcx Substs<'tcx>),
 
     ty_tup(Vec<Ty<'tcx>>),
 
@@ -2658,8 +2658,7 @@ fn add_sty(&mut self, st: &sty) {
                 }
             }
 
-            &ty_closure(_, region, substs) => {
-                self.add_region(*region);
+            &ty_closure(_, substs) => {
                 self.add_substs(substs);
             }
 
@@ -2927,10 +2926,9 @@ pub fn mk_struct<'tcx>(cx: &ctxt<'tcx>, struct_id: ast::DefId,
     mk_t(cx, ty_struct(struct_id, substs))
 }
 
-pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId,
-                        region: &'tcx Region, substs: &'tcx Substs<'tcx>)
+pub fn mk_closure<'tcx>(cx: &ctxt<'tcx>, closure_id: ast::DefId, substs: &'tcx Substs<'tcx>)
                         -> Ty<'tcx> {
-    mk_t(cx, ty_closure(closure_id, region, substs))
+    mk_t(cx, ty_closure(closure_id, substs))
 }
 
 pub fn mk_var<'tcx>(cx: &ctxt<'tcx>, v: TyVid) -> Ty<'tcx> {
@@ -3513,13 +3511,11 @@ fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
                 apply_lang_items(cx, did, res)
             }
 
-            ty_closure(did, r, substs) => {
+            ty_closure(did, substs) => {
                 // FIXME(#14449): `borrowed_contents` below assumes `&mut` closure.
                 let param_env = ty::empty_parameter_environment(cx);
                 let upvars = closure_upvars(&param_env, did, substs).unwrap();
-                TypeContents::union(&upvars,
-                                    |f| tc_ty(cx, &f.ty, cache))
-                    | borrowed_contents(*r, MutMutable)
+                TypeContents::union(&upvars, |f| tc_ty(cx, &f.ty, cache))
             }
 
             ty_tup(ref tys) => {
@@ -5175,7 +5171,7 @@ pub fn ty_to_def_id(ty: Ty) -> Option<ast::DefId> {
             Some(tt.principal_def_id()),
         ty_struct(id, _) |
         ty_enum(id, _) |
-        ty_closure(id, _, _) =>
+        ty_closure(id, _) =>
             Some(id),
         _ =>
             None
@@ -5584,7 +5580,7 @@ pub fn predicates<'tcx>(
 
 /// Get the attributes of a definition.
 pub fn get_attrs<'tcx>(tcx: &'tcx ctxt, did: DefId)
-                       -> CowVec<'tcx, ast::Attribute> {
+                       -> Cow<'tcx, [ast::Attribute]> {
     if is_local(did) {
         let item = tcx.map.expect_item(did.node);
         Cow::Borrowed(&item.attrs)
@@ -5757,22 +5753,22 @@ pub fn closure_upvars<'tcx>(typer: &mc::Typer<'tcx>,
 
 pub fn is_binopable<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>, op: ast::BinOp) -> bool {
     #![allow(non_upper_case_globals)]
-    static tycat_other: int = 0;
-    static tycat_bool: int = 1;
-    static tycat_char: int = 2;
-    static tycat_int: int = 3;
-    static tycat_float: int = 4;
-    static tycat_raw_ptr: int = 6;
-
-    static opcat_add: int = 0;
-    static opcat_sub: int = 1;
-    static opcat_mult: int = 2;
-    static opcat_shift: int = 3;
-    static opcat_rel: int = 4;
-    static opcat_eq: int = 5;
-    static opcat_bit: int = 6;
-    static opcat_logic: int = 7;
-    static opcat_mod: int = 8;
+    const tycat_other: int = 0;
+    const tycat_bool: int = 1;
+    const tycat_char: int = 2;
+    const tycat_int: int = 3;
+    const tycat_float: int = 4;
+    const tycat_raw_ptr: int = 6;
+
+    const opcat_add: int = 0;
+    const opcat_sub: int = 1;
+    const opcat_mult: int = 2;
+    const opcat_shift: int = 3;
+    const opcat_rel: int = 4;
+    const opcat_eq: int = 5;
+    const opcat_bit: int = 6;
+    const opcat_logic: int = 7;
+    const opcat_mod: int = 8;
 
     fn opcat(op: ast::BinOp) -> int {
         match op.node {
@@ -5811,8 +5807,8 @@ fn tycat<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> int {
         }
     }
 
-    static t: bool = true;
-    static f: bool = false;
+    const t: bool = true;
+    const f: bool = false;
 
     let tbl = [
     //           +, -, *, shift, rel, ==, bit, logic, mod
@@ -6301,10 +6297,9 @@ macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
                 }
                 ty_infer(_) => unreachable!(),
                 ty_err => byte!(21),
-                ty_closure(d, r, _) => {
+                ty_closure(d, _) => {
                     byte!(22);
                     did(state, d);
-                    region(state, *r);
                 }
                 ty_projection(ref data) => {
                     byte!(23);
@@ -6618,8 +6613,7 @@ pub fn accumulate_lifetimes_in_type(accumulator: &mut Vec<ty::Region>,
             ty_struct(_, substs) => {
                 accum_substs(accumulator, substs);
             }
-            ty_closure(_, region, substs) => {
-                accumulator.push(*region);
+            ty_closure(_, substs) => {
                 accum_substs(accumulator, substs);
             }
             ty_bool |
index 4bf47c3a75f8003761a99ca641a540b8ae4a7f96..1b904aacc301210558fabc24baedcab941a0643d 100644 (file)
@@ -650,10 +650,9 @@ pub fn super_fold_ty<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
             let substs = substs.fold_with(this);
             ty::ty_struct(did, this.tcx().mk_substs(substs))
         }
-        ty::ty_closure(did, ref region, ref substs) => {
-            let r = region.fold_with(this);
+        ty::ty_closure(did, ref substs) => {
             let s = substs.fold_with(this);
-            ty::ty_closure(did, this.tcx().mk_region(r), this.tcx().mk_substs(s))
+            ty::ty_closure(did, this.tcx().mk_substs(s))
         }
         ty::ty_projection(ref data) => {
             ty::ty_projection(data.fold_with(this))
index 3336e7ee8bf71e6186107a989782913d8dd13f2f..5b5eac451783a8502edb0844d53bd9c221dde5bf 100644 (file)
@@ -45,7 +45,7 @@ fn push_subtypes(&mut self, parent_ty: Ty<'tcx>) {
             }
             ty::ty_enum(_, ref substs) |
             ty::ty_struct(_, ref substs) |
-            ty::ty_closure(_, _, ref substs) => {
+            ty::ty_closure(_, ref substs) => {
                 self.push_reversed(substs.types.as_slice());
             }
             ty::ty_tup(ref ts) => {
index 15b3c6d9d0602c7ed65a0ce39c560de1e99f4414..0eeb746022c0d74e1a9ad29cc34fdd96ef3c1d54 100644 (file)
@@ -406,7 +406,7 @@ fn infer_ty_to_string(cx: &ctxt, ty: ty::InferTy) -> String {
                     data.item_name.user_string(cx))
         }
         ty_str => "str".to_string(),
-        ty_closure(ref did, _, substs) => {
+        ty_closure(ref did, substs) => {
             let closure_tys = cx.closure_tys.borrow();
             closure_tys.get(did).map(|closure_type| {
                 closure_to_string(cx, &closure_type.subst(cx, substs))
index 3fcae6a8034c207ac3408c2beb3ea76bdf2f97cb..97b1a8aaaba0304d7a0f5ced6e103d84646d4801 100644 (file)
@@ -18,7 +18,7 @@
 use std::str;
 use syntax::diagnostic::Handler as ErrorHandler;
 
-pub static METADATA_FILENAME: &'static str = "rust.metadata.bin";
+pub const METADATA_FILENAME: &'static str = "rust.metadata.bin";
 
 pub struct ArchiveConfig<'a> {
     pub handler: &'a ErrorHandler,
@@ -242,7 +242,7 @@ pub fn build(self) -> Archive<'a> {
         // Don't allow the total size of `args` to grow beyond 32,000 bytes.
         // Windows will raise an error if the argument string is longer than
         // 32,768, and we leave a bit of extra space for the program name.
-        static ARG_LENGTH_LIMIT: uint = 32000;
+        const ARG_LENGTH_LIMIT: uint = 32_000;
 
         for member_name in &self.members {
             let len = member_name.as_vec().len();
index 99a1df95a80cddf398549aa2226f3d48fb2be119..56d71820176b419b4d5a02ec145555a0c2c139f0 100644 (file)
@@ -15,7 +15,7 @@
 /// Returns an absolute path in the filesystem that `path` points to. The
 /// returned path does not contain any symlinks in its hierarchy.
 pub fn realpath(original: &Path) -> old_io::IoResult<Path> {
-    static MAX_LINKS_FOLLOWED: uint = 256;
+    const MAX_LINKS_FOLLOWED: uint = 256;
     let original = try!(os::getcwd()).join(original);
 
     // Right now lstat on windows doesn't work quite well
index 67462ab01003e29ec33f3f21e3a1cd1998ee3bfa..f6df2acce597b4c52d699fbe966f822ea2a9bdbd 100644 (file)
@@ -312,7 +312,7 @@ fn to_type(&self) -> ty::Ty<'tcx> { self.ty }
 // FIXME (pnkfelix): See discussion here
 // https://github.com/pnkfelix/rust/commit/
 //     b2b39e8700e37ad32b486b9a8409b50a8a53aa51#commitcomment-7892003
-static DOWNCAST_PRINTED_OPERATOR : &'static str = " as ";
+const DOWNCAST_PRINTED_OPERATOR: &'static str = " as ";
 
 // A local, "cleaned" version of `mc::InteriorKind` that drops
 // information that is not relevant to loan-path analysis. (In
index 0f7f8e61e37e0a1788c2a20ae0d79a48fd14ff22..8846f70fbd335febf9b005813b07dfc2b885bb03 100644 (file)
@@ -91,8 +91,7 @@ fn clone(&self) -> MovePathIndex {
 }
 
 #[allow(non_upper_case_globals)]
-static InvalidMovePathIndex: MovePathIndex =
-    MovePathIndex(usize::MAX);
+const InvalidMovePathIndex: MovePathIndex = MovePathIndex(usize::MAX);
 
 /// Index into `MoveData.moves`, used like a pointer
 #[derive(Copy, PartialEq)]
@@ -105,8 +104,7 @@ fn get(&self) -> uint {
 }
 
 #[allow(non_upper_case_globals)]
-static InvalidMoveIndex: MoveIndex =
-    MoveIndex(usize::MAX);
+const InvalidMoveIndex: MoveIndex = MoveIndex(usize::MAX);
 
 pub struct MovePath<'tcx> {
     /// Loan path corresponding to this move path
index d08fb2b313ef6776dde2c2a2ed1486cfbb1f2499..15fae351ddbf21d8b3fe2bf19038a34b1da71969 100644 (file)
@@ -93,7 +93,7 @@
 pub mod pretty;
 
 
-static BUG_REPORT_URL: &'static str =
+const BUG_REPORT_URL: &'static str =
     "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
 
 
@@ -770,7 +770,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) ->
 /// The diagnostic emitter yielded to the procedure should be used for reporting
 /// errors of the compiler.
 pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
-    static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
+    const STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
 
     let (tx, rx) = channel();
     let w = old_io::ChanWriter::new(tx);
index cdbee9da334228d42b0ea48443c0456d6ce7d7b7..23f07c8e25c1145126c61554503a2e269110d82f 100644 (file)
@@ -44,7 +44,7 @@ struct RH<'a> {
     sub: &'a [RH<'a>]
 }
 
-static EMPTY_SOURCE_STR: &'static str = "#![feature(no_std)] #![no_std]";
+const EMPTY_SOURCE_STR: &'static str = "#![feature(no_std)] #![no_std]";
 
 struct ExpectErrorEmitter {
     messages: Vec<String>
index d0fccf6495a0a47d9b83d39ac637cc60819a7308..22311a7158378cede0e4cf155c88b2df362dfe20 100644 (file)
@@ -28,8 +28,6 @@
 //! Use the former for unit-like structs and the latter for structs with
 //! a `pub fn new()`.
 
-use self::MethodContext::*;
-
 use metadata::{csearch, decoder};
 use middle::def::*;
 use middle::subst::Substs;
@@ -228,7 +226,9 @@ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
                             ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
                                 let int_type = if let ast::TyIs(_) = t {
                                     cx.sess().target.int_type
-                                } else { t };
+                                } else {
+                                    t
+                                };
                                 let (min, max) = int_ty_range(int_type);
                                 let negative = self.negated_expr_id == e.id;
 
@@ -245,14 +245,16 @@ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
                     ty::ty_uint(t) => {
                         let uint_type = if let ast::TyUs(_) = t {
                             cx.sess().target.uint_type
-                        } else { t };
+                        } else {
+                            t
+                        };
                         let (min, max) = uint_ty_range(uint_type);
                         let lit_val: u64 = match lit.node {
                             ast::LitByte(_v) => return,  // _v is u8, within range by definition
                             ast::LitInt(v, _) => v,
                             _ => panic!()
                         };
-                        if  lit_val < min || lit_val > max {
+                        if lit_val < min || lit_val > max {
                             cx.span_lint(OVERFLOWING_LITERALS, e.span,
                                          &*format!("literal out of range for {:?}", t));
                         }
@@ -262,9 +264,9 @@ fn check_expr(&mut self, cx: &Context, e: &ast::Expr) {
                         let lit_val: f64 = match lit.node {
                             ast::LitFloat(ref v, _) |
                             ast::LitFloatUnsuffixed(ref v) => {
-                                match v.parse().ok() {
-                                    Some(f) => f,
-                                    None => return
+                                match v.parse() {
+                                    Ok(f) => f,
+                                    Err(_) => return
                                 }
                             }
                             _ => panic!()
@@ -302,52 +304,52 @@ fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
             })
         }
 
-        // for int & uint, be conservative with the warnings, so that the
+        // for isize & usize, be conservative with the warnings, so that the
         // warnings are consistent between 32- and 64-bit platforms
         fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
             match int_ty {
-                ast::TyIs(_) =>    (i64::MIN,        i64::MAX),
-                ast::TyI8 =>   (i8::MIN  as i64, i8::MAX  as i64),
-                ast::TyI16 =>  (i16::MIN as i64, i16::MAX as i64),
-                ast::TyI32 =>  (i32::MIN as i64, i32::MAX as i64),
-                ast::TyI64 =>  (i64::MIN,        i64::MAX)
+                ast::TyIs(_) => (i64::MIN,        i64::MAX),
+                ast::TyI8 =>    (i8::MIN  as i64, i8::MAX  as i64),
+                ast::TyI16 =>   (i16::MIN as i64, i16::MAX as i64),
+                ast::TyI32 =>   (i32::MIN as i64, i32::MAX as i64),
+                ast::TyI64 =>   (i64::MIN,        i64::MAX)
             }
         }
 
         fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
             match uint_ty {
-                ast::TyUs(_) =>   (u64::MIN,         u64::MAX),
-                ast::TyU8 =>  (u8::MIN   as u64, u8::MAX   as u64),
-                ast::TyU16 => (u16::MIN  as u64, u16::MAX  as u64),
-                ast::TyU32 => (u32::MIN  as u64, u32::MAX  as u64),
-                ast::TyU64 => (u64::MIN,         u64::MAX)
+                ast::TyUs(_) => (u64::MIN,         u64::MAX),
+                ast::TyU8 =>    (u8::MIN   as u64, u8::MAX   as u64),
+                ast::TyU16 =>   (u16::MIN  as u64, u16::MAX  as u64),
+                ast::TyU32 =>   (u32::MIN  as u64, u32::MAX  as u64),
+                ast::TyU64 =>   (u64::MIN,         u64::MAX)
             }
         }
 
         fn float_ty_range(float_ty: ast::FloatTy) -> (f64, f64) {
             match float_ty {
-                ast::TyF32  => (f32::MIN as f64, f32::MAX as f64),
-                ast::TyF64  => (f64::MIN,        f64::MAX)
+                ast::TyF32 => (f32::MIN as f64, f32::MAX as f64),
+                ast::TyF64 => (f64::MIN,        f64::MAX)
             }
         }
 
         fn int_ty_bits(int_ty: ast::IntTy, target_int_ty: ast::IntTy) -> u64 {
             match int_ty {
-                ast::TyIs(_) =>    int_ty_bits(target_int_ty, target_int_ty),
-                ast::TyI8 =>   i8::BITS  as u64,
-                ast::TyI16 =>  i16::BITS as u64,
-                ast::TyI32 =>  i32::BITS as u64,
-                ast::TyI64 =>  i64::BITS as u64
+                ast::TyIs(_) => int_ty_bits(target_int_ty, target_int_ty),
+                ast::TyI8 =>    i8::BITS  as u64,
+                ast::TyI16 =>   i16::BITS as u64,
+                ast::TyI32 =>   i32::BITS as u64,
+                ast::TyI64 =>   i64::BITS as u64
             }
         }
 
         fn uint_ty_bits(uint_ty: ast::UintTy, target_uint_ty: ast::UintTy) -> u64 {
             match uint_ty {
-                ast::TyUs(_) =>    uint_ty_bits(target_uint_ty, target_uint_ty),
-                ast::TyU8 =>   u8::BITS  as u64,
-                ast::TyU16 =>  u16::BITS as u64,
-                ast::TyU32 =>  u32::BITS as u64,
-                ast::TyU64 =>  u64::BITS as u64
+                ast::TyUs(_) => uint_ty_bits(target_uint_ty, target_uint_ty),
+                ast::TyU8 =>    u8::BITS  as u64,
+                ast::TyU16 =>   u16::BITS as u64,
+                ast::TyU32 =>   u32::BITS as u64,
+                ast::TyU64 =>   u64::BITS as u64
             }
         }
 
@@ -360,7 +362,11 @@ fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
             };
             // Normalize the binop so that the literal is always on the RHS in
             // the comparison
-            let norm_binop = if swap { rev_binop(binop) } else { binop };
+            let norm_binop = if swap {
+                rev_binop(binop)
+            } else {
+                binop
+            };
             match ty::expr_ty(tcx, expr).sty {
                 ty::ty_int(int_ty) => {
                     let (min, max) = int_ty_range(int_ty);
@@ -432,9 +438,9 @@ fn check_def(&mut self, sp: Span, id: ast::NodeId) {
 
                 if !ty::is_ffi_safe(self.cx.tcx, tty) {
                     self.cx.span_lint(IMPROPER_CTYPES, sp,
-                                      "found type without foreign-function-safe
-                                      representation annotation in foreign module, consider \
-                                      adding a #[repr(...)] attribute to the type");
+                                      "found type without foreign-function-safe \
+                                       representation annotation in foreign module, consider \
+                                       adding a #[repr(...)] attribute to the type");
                 }
             }
             _ => ()
@@ -565,7 +571,7 @@ struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
 
 impl<'a, 'tcx, 'v> Visitor<'v> for RawPtrDeriveVisitor<'a, 'tcx> {
     fn visit_ty(&mut self, ty: &ast::Ty) {
-        static MSG: &'static str = "use of `#[derive]` with a raw pointer";
+        const MSG: &'static str = "use of `#[derive]` with a raw pointer";
         if let ast::TyPtr(..) = ty.node {
             self.cx.span_lint(RAW_POINTER_DERIVE, ty.span, MSG);
         }
@@ -595,7 +601,7 @@ fn get_lints(&self) -> LintArray {
 
     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
         if !attr::contains_name(&item.attrs, "automatically_derived") {
-            return
+            return;
         }
         let did = match item.node {
             ast::ItemImpl(_, _, _, ref t_ref_opt, _, _) => {
@@ -603,7 +609,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
                 if let &Some(ref trait_ref) = t_ref_opt {
                     let def_id = ty::trait_ref_to_def_id(cx.tcx, trait_ref);
                     if Some(def_id) == cx.tcx.lang_items.copy_trait() {
-                        return
+                        return;
                     }
                 }
 
@@ -615,12 +621,16 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
             }
             _ => return,
         };
-        if !ast_util::is_local(did) { return }
+        if !ast_util::is_local(did) {
+            return;
+        }
         let item = match cx.tcx.map.find(did.node) {
             Some(ast_map::NodeItem(item)) => item,
             _ => return,
         };
-        if !self.checked_raw_pointers.insert(item.id) { return }
+        if !self.checked_raw_pointers.insert(item.id) {
+            return;
+        }
         match item.node {
             ast::ItemStruct(..) | ast::ItemEnum(..) => {
                 let mut visitor = RawPtrDeriveVisitor { cx: cx };
@@ -646,6 +656,7 @@ fn get_lints(&self) -> LintArray {
     }
 
     fn check_attribute(&mut self, cx: &Context, attr: &ast::Attribute) {
+        // Note that check_name() marks the attribute as used if it matches.
         for &(ref name, ty) in KNOWN_ATTRIBUTES {
             match ty {
                 AttributeType::Whitelisted
@@ -730,23 +741,24 @@ fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
         }
 
         let t = ty::expr_ty(cx.tcx, expr);
-        let mut warned = false;
-        match t.sty {
+        let warned = match t.sty {
             ty::ty_tup(ref tys) if tys.is_empty() => return,
             ty::ty_bool => return,
             ty::ty_struct(did, _) |
             ty::ty_enum(did, _) => {
                 if ast_util::is_local(did) {
                     if let ast_map::NodeItem(it) = cx.tcx.map.get(did.node) {
-                        warned |= check_must_use(cx, &it.attrs, s.span);
+                        check_must_use(cx, &it.attrs, s.span)
+                    } else {
+                        false
                     }
                 } else {
                     let attrs = csearch::get_item_attrs(&cx.sess().cstore, did);
-                    warned |= check_must_use(cx, &attrs[..], s.span);
+                    check_must_use(cx, &attrs[..], s.span)
                 }
             }
-            _ => {}
-        }
+            _ => false,
+        };
         if !warned {
             cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
         }
@@ -785,7 +797,9 @@ impl NonCamelCaseTypes {
     fn check_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
         fn is_camel_case(ident: ast::Ident) -> bool {
             let ident = token::get_ident(ident);
-            if ident.is_empty() { return true; }
+            if ident.is_empty() {
+                return true;
+            }
             let ident = ident.trim_matches('_');
 
             // start with a non-lowercase letter rather than non-uppercase
@@ -795,8 +809,11 @@ fn is_camel_case(ident: ast::Ident) -> bool {
 
         fn to_camel_case(s: &str) -> String {
             s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
-                if i == 0 { c.to_uppercase() }
-                else { c }
+                if i == 0 {
+                    c.to_uppercase()
+                } else {
+                    c
+                }
             )).collect()
         }
 
@@ -820,11 +837,13 @@ fn get_lints(&self) -> LintArray {
     }
 
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
-        let has_extern_repr = it.attrs.iter().map(|attr| {
+        let has_extern_repr = it.attrs.iter().any(|attr| {
             attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
                 .any(|r| r == &attr::ReprExtern)
-        }).any(|x| x);
-        if has_extern_repr { return }
+        });
+        if has_extern_repr {
+            return;
+        }
 
         match it.node {
             ast::ItemTy(..) | ast::ItemStruct(..) => {
@@ -834,7 +853,9 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
                 self.check_case(cx, "trait", it.ident, it.span)
             }
             ast::ItemEnum(ref enum_definition, _) => {
-                if has_extern_repr { return }
+                if has_extern_repr {
+                    return;
+                }
                 self.check_case(cx, "type", it.ident, it.span);
                 for variant in &enum_definition.variants {
                     self.check_case(cx, "variant", variant.node.name, variant.span);
@@ -866,32 +887,28 @@ fn method_context(cx: &Context, m: &ast::Method) -> MethodContext {
 
     match cx.tcx.impl_or_trait_items.borrow().get(&did).cloned() {
         None => cx.sess().span_bug(m.span, "missing method descriptor?!"),
-        Some(md) => {
-            match md {
-                ty::MethodTraitItem(md) => {
-                    match md.container {
-                        ty::TraitContainer(..) => TraitDefaultImpl,
-                        ty::ImplContainer(cid) => {
-                            match ty::impl_trait_ref(cx.tcx, cid) {
-                                Some(..) => TraitImpl,
-                                None => PlainImpl
-                            }
-                        }
+        Some(ty::MethodTraitItem(md)) => {
+            match md.container {
+                ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
+                ty::ImplContainer(cid) => {
+                    match ty::impl_trait_ref(cx.tcx, cid) {
+                        Some(..) => MethodContext::TraitImpl,
+                        None => MethodContext::PlainImpl
                     }
                 }
-                ty::TypeTraitItem(typedef) => {
-                    match typedef.container {
-                        ty::TraitContainer(..) => TraitDefaultImpl,
-                        ty::ImplContainer(cid) => {
-                            match ty::impl_trait_ref(cx.tcx, cid) {
-                                Some(..) => TraitImpl,
-                                None => PlainImpl
-                            }
-                        }
+            }
+        },
+        Some(ty::TypeTraitItem(typedef)) => {
+            match typedef.container {
+                ty::TraitContainer(..) => MethodContext::TraitDefaultImpl,
+                ty::ImplContainer(cid) => {
+                    match ty::impl_trait_ref(cx.tcx, cid) {
+                        Some(..) => MethodContext::TraitImpl,
+                        None => MethodContext::PlainImpl
                     }
                 }
             }
-        }
+        },
     }
 }
 
@@ -912,12 +929,16 @@ fn to_snake_case(mut str: &str) -> String {
             if c == '_' {
                 words.push(String::new());
                 true
-            } else { false }
+            } else {
+                false
+            }
         });
         for s in str.split('_') {
             let mut last_upper = false;
             let mut buf = String::new();
-            if s.is_empty() { continue; }
+            if s.is_empty() {
+                continue;
+            }
             for ch in s.chars() {
                 if !buf.is_empty() && buf != "'"
                                    && ch.is_uppercase()
@@ -936,7 +957,9 @@ fn to_snake_case(mut str: &str) -> String {
     fn check_snake_case(&self, cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
         fn is_snake_case(ident: ast::Ident) -> bool {
             let ident = token::get_ident(ident);
-            if ident.is_empty() { return true; }
+            if ident.is_empty() {
+                return true;
+            }
             let ident = ident.trim_left_matches('\'');
             let ident = ident.trim_matches('_');
 
@@ -979,14 +1002,17 @@ fn check_fn(&mut self, cx: &Context,
                 _: &ast::Block, span: Span, _: ast::NodeId) {
         match fk {
             visit::FkMethod(ident, _, m) => match method_context(cx, m) {
-                PlainImpl
-                    => self.check_snake_case(cx, "method", ident, span),
-                TraitDefaultImpl
-                    => self.check_snake_case(cx, "trait method", ident, span),
+                MethodContext::PlainImpl => {
+                    self.check_snake_case(cx, "method", ident, span)
+                },
+                MethodContext::TraitDefaultImpl => {
+                    self.check_snake_case(cx, "trait method", ident, span)
+                },
                 _ => (),
             },
-            visit::FkItemFn(ident, _, _, _)
-                => self.check_snake_case(cx, "function", ident, span),
+            visit::FkItemFn(ident, _, _, _) => {
+                self.check_snake_case(cx, "function", ident, span)
+            },
             _ => (),
         }
     }
@@ -1015,7 +1041,7 @@ fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
     }
 
     fn check_struct_def(&mut self, cx: &Context, s: &ast::StructDef,
-            _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
+                        _: ast::Ident, _: &ast::Generics, _: ast::NodeId) {
         for sf in &s.fields {
             if let ast::StructField_ { kind: ast::NamedField(ident, _), .. } = sf.node {
                 self.check_snake_case(cx, "structure field", ident, sf.span);
@@ -1094,13 +1120,12 @@ fn check_pat(&mut self, cx: &Context, p: &ast::Pat) {
 
 impl UnusedParens {
     fn check_unused_parens_core(&self, cx: &Context, value: &ast::Expr, msg: &str,
-                                     struct_lit_needs_parens: bool) {
+                                struct_lit_needs_parens: bool) {
         if let ast::ExprParen(ref inner) = value.node {
             let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
             if !necessary {
                 cx.span_lint(UNUSED_PARENS, value.span,
-                             &format!("unnecessary parentheses around {}",
-                                     msg))
+                             &format!("unnecessary parentheses around {}", msg))
             }
         }
 
@@ -1193,26 +1218,17 @@ fn get_lints(&self) -> LintArray {
     }
 
     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
-        match item.node {
-            ast::ItemUse(ref view_path) => {
-                match view_path.node {
-                    ast::ViewPathList(_, ref items) => {
-                        if items.len() == 1 {
-                            match items[0].node {
-                                ast::PathListIdent {ref name, ..} => {
-                                    let m = format!("braces around {} is unnecessary",
-                                                    &token::get_ident(*name));
-                                    cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
-                                                 &m[..]);
-                                },
-                                _ => ()
-                            }
-                        }
+        if let ast::ItemUse(ref view_path) = item.node {
+            if let ast::ViewPathList(_, ref items) = view_path.node {
+                if items.len() == 1 {
+                    if let ast::PathListIdent {ref name, ..} = items[0].node {
+                        let m = format!("braces around {} is unnecessary",
+                                        &token::get_ident(*name));
+                        cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
+                                     &m[..]);
                     }
-                    _ => ()
                 }
-            },
-            _ => ()
+            }
         }
     }
 }
@@ -1234,9 +1250,10 @@ fn get_lints(&self) -> LintArray {
     fn check_pat(&mut self, cx: &Context, pat: &ast::Pat) {
         let def_map = cx.tcx.def_map.borrow();
         if let ast::PatStruct(_, ref v, _) = pat.node {
-            let field_pats = v.iter()
-                              .filter(|fieldpat| !fieldpat.node.is_shorthand)
-                              .filter(|fieldpat| {
+            let field_pats = v.iter().filter(|fieldpat| {
+                if fieldpat.node.is_shorthand {
+                    return false;
+                }
                 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
                 def == Some(def::DefLocal(fieldpat.node.pat.id))
             });
@@ -1482,10 +1499,14 @@ fn check_missing_docs_attrs(&self,
                                desc: &'static str) {
         // If we're building a test harness, then warning about
         // documentation is probably not really relevant right now.
-        if cx.sess().opts.test { return }
+        if cx.sess().opts.test {
+            return;
+        }
 
         // `#[doc(hidden)]` disables missing_docs check.
-        if self.doc_hidden() { return }
+        if self.doc_hidden() {
+            return;
+        }
 
         // Only check publicly-visible items, using the result from the privacy pass.
         // It's an option so the crate root can also use this function (it doesn't
@@ -1504,7 +1525,7 @@ fn check_missing_docs_attrs(&self,
         });
         if !has_doc {
             cx.span_lint(MISSING_DOCS, sp,
-                &format!("missing documentation for {}", desc));
+                         &format!("missing documentation for {}", desc));
         }
     }
 }
@@ -1528,20 +1549,19 @@ fn exit_lint_attrs(&mut self, _: &Context, _: &[ast::Attribute]) {
         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
     }
 
-    fn check_struct_def(&mut self, _: &Context,
-        _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+    fn check_struct_def(&mut self, _: &Context, _: &ast::StructDef,
+                        _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
         self.struct_def_stack.push(id);
     }
 
-    fn check_struct_def_post(&mut self, _: &Context,
-        _: &ast::StructDef, _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
+    fn check_struct_def_post(&mut self, _: &Context, _: &ast::StructDef,
+                             _: ast::Ident, _: &ast::Generics, id: ast::NodeId) {
         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
         assert!(popped == id);
     }
 
     fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) {
-        self.check_missing_docs_attrs(cx, None, &krate.attrs,
-                                     krate.span, "crate");
+        self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
     }
 
     fn check_item(&mut self, cx: &Context, it: &ast::Item) {
@@ -1554,30 +1574,28 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
             ast::ItemTy(..) => "a type alias",
             _ => return
         };
-        self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs,
-                                     it.span, desc);
+        self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
     }
 
-    fn check_fn(&mut self, cx: &Context,
-            fk: visit::FnKind, _: &ast::FnDecl,
-            _: &ast::Block, _: Span, _: ast::NodeId) {
+    fn check_fn(&mut self, cx: &Context, fk: visit::FnKind, _: &ast::FnDecl,
+                _: &ast::Block, _: Span, _: ast::NodeId) {
         if let visit::FkMethod(_, _, m) = fk {
             // If the method is an impl for a trait, don't doc.
-            if method_context(cx, m) == TraitImpl { return; }
+            if method_context(cx, m) == MethodContext::TraitImpl {
+                return;
+            }
 
             // Otherwise, doc according to privacy. This will also check
             // doc for default methods defined on traits.
-            self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs,
-                                          m.span, "a method");
+            self.check_missing_docs_attrs(cx, Some(m.id), &m.attrs, m.span, "a method");
         }
     }
 
     fn check_ty_method(&mut self, cx: &Context, tm: &ast::TypeMethod) {
-        self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs,
-                                     tm.span, "a type method");
+        self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs, tm.span, "a type method");
     }
 
-    fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
+    fn check_trait_item(&mut self, cx: &Context, it: &ast::TraitItem) {
         if let ast::TraitItem::TypeTraitItem(ref ty) = *it {
             let assoc_ty = &ty.ty_param;
             self.check_missing_docs_attrs(cx, Some(assoc_ty.id), &ty.attrs,
@@ -1598,8 +1616,7 @@ fn check_struct_field(&mut self, cx: &Context, sf: &ast::StructField) {
     }
 
     fn check_variant(&mut self, cx: &Context, v: &ast::Variant, _: &ast::Generics) {
-        self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs,
-                                     v.span, "a variant");
+        self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
         assert!(!self.in_variant);
         self.in_variant = true;
     }
@@ -1626,18 +1643,18 @@ fn get_lints(&self) -> LintArray {
 
     fn check_item(&mut self, cx: &Context, item: &ast::Item) {
         if !cx.exported_items.contains(&item.id) {
-            return
+            return;
         }
         if cx.tcx
              .destructor_for_type
              .borrow()
              .contains_key(&ast_util::local_def(item.id)) {
-            return
+            return;
         }
         let ty = match item.node {
             ast::ItemStruct(_, ref ast_generics) => {
                 if ast_generics.is_parameterized() {
-                    return
+                    return;
                 }
                 ty::mk_struct(cx.tcx,
                               ast_util::local_def(item.id),
@@ -1645,7 +1662,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
             }
             ast::ItemEnum(_, ref ast_generics) => {
                 if ast_generics.is_parameterized() {
-                    return
+                    return;
                 }
                 ty::mk_enum(cx.tcx,
                             ast_util::local_def(item.id),
@@ -1655,7 +1672,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
         };
         let parameter_environment = ty::empty_parameter_environment(cx.tcx);
         if !ty::type_moves_by_default(&parameter_environment, item.span, ty) {
-            return
+            return;
         }
         if ty::can_type_implement_copy(&parameter_environment, item.span, ty).is_ok() {
             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
@@ -1709,10 +1726,10 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
             let impls = match impls.get(&debug) {
                 Some(impls) => {
                     impls.borrow().iter()
-                        .filter(|d| d.krate == ast::LOCAL_CRATE)
-                        .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
-                        .map(|d| d.node)
-                        .collect()
+                         .filter(|d| d.krate == ast::LOCAL_CRATE)
+                         .filter_map(|d| ty::ty_to_def_id(ty::node_id_to_type(cx.tcx, d.node)))
+                         .map(|d| d.node)
+                         .collect()
                 }
                 None => NodeSet(),
             };
@@ -1741,8 +1758,7 @@ fn check_item(&mut self, cx: &Context, item: &ast::Item) {
 
 impl Stability {
     fn lint(&self, cx: &Context, _id: ast::DefId, span: Span, stability: &Option<attr::Stability>) {
-
-        // deprecated attributes apply in-crate and cross-crate
+        // Deprecated attributes apply in-crate and cross-crate.
         let (lint, label) = match *stability {
             Some(attr::Stability { deprecated_since: Some(_), .. }) =>
                 (DEPRECATED, "deprecated"),
@@ -1857,25 +1873,27 @@ fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
         let mut visited = BitSet::new();
 
         while let Some(idx) = work_queue.pop() {
-            let cfg_id = idx.node_id();
             if idx == cfg.exit {
                 // found a path!
                 reached_exit_without_self_call = true;
-                break
-            } else if visited.contains(&cfg_id) {
+                break;
+            }
+
+            let cfg_id = idx.node_id();
+            if visited.contains(&cfg_id) {
                 // already done
-                continue
+                continue;
             }
             visited.insert(cfg_id);
+
             let node_id = cfg.graph.node_data(idx).id();
 
             // is this a recursive call?
             if node_id != ast::DUMMY_NODE_ID && checker(cx.tcx, impl_node_id, id, name, node_id) {
-
                 self_call_spans.push(cx.tcx.map.span(node_id));
                 // this is a self call, so we shouldn't explore past
                 // this node in the CFG.
-                continue
+                continue;
             }
             // add the successors of this node to explore the graph further.
             cfg.graph.each_outgoing_edge(idx, |_, edge| {
@@ -1888,7 +1906,7 @@ fn check_fn(&mut self, cx: &Context, fn_kind: visit::FnKind, _: &ast::FnDecl,
             });
         }
 
-        // check the number of sell calls because a function that
+        // Check the number of self calls because a function that
         // doesn't return (e.g. calls a `-> !` function or `loop { /*
         // no break */ }`) shouldn't be linted unless it actually
         // recurs.
@@ -1920,7 +1938,7 @@ fn id_refers_to_this_fn<'tcx>(tcx: &ty::ctxt<'tcx>,
                                       _: ast::Ident,
                                       id: ast::NodeId) -> bool {
             tcx.def_map.borrow().get(&id)
-                .map_or(false, |def| def.def_id() == ast_util::local_def(fn_id))
+               .map_or(false, |def| def.def_id() == ast_util::local_def(fn_id))
         }
 
         // check if the method call `id` refers to method `method_id`
@@ -1962,7 +1980,7 @@ fn id_refers_to_this_method<'tcx>(tcx: &ty::ctxt<'tcx>,
                                 tcx.map.span(id),
                                 "non-method call expr behaving like a method call?")
                         };
-                        // it matches if it comes from the same impl,
+                        // It matches if it comes from the same impl,
                         // and has the same method name.
                         return ast_util::is_local(impl_def_id)
                             && impl_def_id.node == impl_id
@@ -2013,7 +2031,7 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
 
         if decoder::get_plugin_registrar_fn(md.data()).is_some() {
             cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
-                "compiler plugin used as an ordinary library");
+                         "compiler plugin used as an ordinary library");
         }
     }
 }
@@ -2069,7 +2087,7 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
                     // Const items do not refer to a particular location in memory, and therefore
                     // don't have anything to attach a symbol to
                     let msg = "const items should never be #[no_mangle], consider instead using \
-                        `pub static`";
+                               `pub static`";
                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
                 }
             }
@@ -2082,15 +2100,17 @@ fn check_item(&mut self, cx: &Context, it: &ast::Item) {
 #[derive(Copy)]
 pub struct UnstableFeatures;
 
-declare_lint!(UNSTABLE_FEATURES, Allow,
-              "enabling unstable features");
+declare_lint! {
+    UNSTABLE_FEATURES,
+    Allow,
+    "enabling unstable features"
+}
 
 impl LintPass for UnstableFeatures {
     fn get_lints(&self) -> LintArray {
         lint_array!(UNSTABLE_FEATURES)
     }
     fn check_attribute(&mut self, ctx: &Context, attr: &ast::Attribute) {
-        use syntax::attr;
         if attr::contains_name(&[attr.node.value.clone()], "feature") {
             ctx.span_lint(UNSTABLE_FEATURES, attr.span, "unstable feature");
         }
index 46729988bb6bd976c658bb1c23e4be691c0e8c38..ab3b56c31b62a93d70d5147e23478e8ac8d6167c 100644 (file)
@@ -1376,10 +1376,11 @@ fn visit_item(&mut self, item: &ast::Item) {
                             }
                         }
                         Some(ref tr) => {
-                            // Any private types in a trait impl fall into two
+                            // Any private types in a trait impl fall into three
                             // categories.
                             // 1. mentioned in the trait definition
                             // 2. mentioned in the type params/generics
+                            // 3. mentioned in the associated types of the impl
                             //
                             // Those in 1. can only occur if the trait is in
                             // this crate and will've been warned about on the
@@ -1389,6 +1390,16 @@ fn visit_item(&mut self, item: &ast::Item) {
                             // Those in 2. are warned via walk_generics and this
                             // call here.
                             visit::walk_path(self, &tr.path);
+
+                            // Those in 3. are warned with this call.
+                            for impl_item in impl_items {
+                                match *impl_item {
+                                    ast::MethodImplItem(..) => {},
+                                    ast::TypeImplItem(ref typedef) => {
+                                        self.visit_ty(&typedef.typ);
+                                    }
+                                }
+                            }
                         }
                     }
                 } else if trait_ref.is_none() && self_is_public_path {
index ea5001aa814b49ab5dab7f8be7c047e8f6456498..7b377ac3611b68131c002c8e235e77f530369571 100644 (file)
@@ -317,7 +317,7 @@ pub fn mangle_exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, path: PathEl
     // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
     // generate unique characters from the node id. For now
     // hopefully 3 characters is enough to avoid collisions.
-    static EXTRA_CHARS: &'static str =
+    const EXTRA_CHARS: &'static str =
         "abcdefghijklmnopqrstuvwxyz\
          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
          0123456789";
index 48ff4c8332022aac0972c153eade715fbbe7be42..2ab6f5b0f952178b3637b9998fdb3d290b207c55 100644 (file)
@@ -789,7 +789,7 @@ fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
 
         // Irrefutable columns always go first, they'd only be duplicated in the branches.
         if total_score == 0 {
-            std::uint::MAX
+            std::usize::MAX
         } else {
             total_score
         }
index 3ea14d3c58929dd5967c0a9893bb29a7e1233ca8..36c4a354cbf52ab39424aa00a1beb3c9344215bf 100644 (file)
@@ -169,7 +169,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
             Univariant(mk_struct(cx, &ftys[..], packed, t), dtor)
         }
-        ty::ty_closure(def_id, _, substs) => {
+        ty::ty_closure(def_id, substs) => {
             let typer = NormalizingClosureTyper::new(cx.tcx());
             let upvars = typer.closure_upvars(def_id, substs).unwrap();
             let upvar_types = upvars.iter().map(|u| u.ty).collect::<Vec<_>>();
@@ -487,12 +487,12 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp
     debug!("range_to_inttype: {:?} {:?}", hint, bounds);
     // Lists of sizes to try.  u64 is always allowed as a fallback.
     #[allow(non_upper_case_globals)]
-    static choose_shortest: &'static[IntType] = &[
+    const choose_shortest: &'static [IntType] = &[
         attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
         attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
     #[allow(non_upper_case_globals)]
-    static at_least_32: &'static[IntType] = &[
+    const at_least_32: &'static [IntType] = &[
         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
 
     let attempts;
@@ -1000,7 +1000,7 @@ pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, r: &Repr<'tcx
             let fcx = bcx.fcx;
             let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
             let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
-                bcx, tcx.types.bool, "drop_flag", false,
+                bcx, tcx.types.bool, "drop_flag",
                 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
             ));
             bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
index fdeef11f36c84c2adc4f2f373ae21b1ca284a394..2949dfb67c57d0c9eafc8f4678cb03bf65ad5f72 100644 (file)
@@ -291,7 +291,7 @@ pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
         ty::ty_bare_fn(_, ref f) => {
             (&f.sig, f.abi, None)
         }
-        ty::ty_closure(closure_did, _, substs) => {
+        ty::ty_closure(closure_did, substs) => {
             let typer = common::NormalizingClosureTyper::new(ccx.tcx());
             function_type = typer.closure_type(closure_did, substs);
             let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
@@ -685,7 +685,7 @@ fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
               }
           })
       }
-      ty::ty_closure(def_id, _, substs) => {
+      ty::ty_closure(def_id, substs) => {
           let repr = adt::represent_type(cx.ccx(), t);
           let typer = common::NormalizingClosureTyper::new(cx.tcx());
           let upvars = typer.closure_upvars(def_id, substs).unwrap();
@@ -1203,21 +1203,6 @@ pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
     Alloca(cx, ty, name)
 }
 
-pub fn alloca_zeroed<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty: Ty<'tcx>,
-                                 name: &str) -> ValueRef {
-    let llty = type_of::type_of(cx.ccx(), ty);
-    if cx.unreachable.get() {
-        unsafe {
-            return llvm::LLVMGetUndef(llty.ptr_to().to_ref());
-        }
-    }
-    let p = alloca_no_lifetime(cx, llty, name);
-    let b = cx.fcx.ccx.builder();
-    b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
-    memzero(&b, p, ty);
-    p
-}
-
 // Creates the alloca slot which holds the pointer to the slot for the final return value
 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
                                           output_type: Ty<'tcx>) -> ValueRef {
@@ -1547,7 +1532,6 @@ fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
                                   datum::lvalue_scratch_datum(bcx,
                                                               arg_ty,
                                                               "tupled_args",
-                                                              false,
                                                               tuple_args_scope_id,
                                                               (),
                                                               |(),
@@ -2435,32 +2419,34 @@ pub fn get_fn_llvm_attributes<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<
     use middle::ty::{BrAnon, ReLateBound};
 
     let function_type;
-    let (fn_sig, abi, has_env) = match fn_ty.sty {
-        ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, false),
-        ty::ty_closure(closure_did, _, substs) => {
+    let (fn_sig, abi, env_ty) = match fn_ty.sty {
+        ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, None),
+        ty::ty_closure(closure_did, substs) => {
             let typer = common::NormalizingClosureTyper::new(ccx.tcx());
             function_type = typer.closure_type(closure_did, substs);
-            (&function_type.sig, RustCall, true)
+            let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
+            (&function_type.sig, RustCall, Some(self_type))
         }
         _ => ccx.sess().bug("expected closure or function.")
     };
 
     let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
 
-    // Since index 0 is the return value of the llvm func, we start
-    // at either 1 or 2 depending on whether there's an env slot or not
-    let mut first_arg_offset = if has_env { 2 } else { 1 };
     let mut attrs = llvm::AttrBuilder::new();
     let ret_ty = fn_sig.output;
 
     // These have an odd calling convention, so we need to manually
     // unpack the input ty's
     let input_tys = match fn_ty.sty {
-        ty::ty_closure(_, _, _) => {
+        ty::ty_closure(..) => {
             assert!(abi == RustCall);
 
             match fn_sig.inputs[0].sty {
-                ty::ty_tup(ref inputs) => inputs.clone(),
+                ty::ty_tup(ref inputs) => {
+                    let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
+                    full_inputs.push_all(inputs);
+                    full_inputs
+                }
                 _ => ccx.sess().bug("expected tuple'd inputs")
             }
         },
@@ -2478,6 +2464,8 @@ pub fn get_fn_llvm_attributes<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<
         _ => fn_sig.inputs.clone()
     };
 
+    // Index 0 is the return value of the llvm func, so we start at 1
+    let mut first_arg_offset = 1;
     if let ty::FnConverging(ret_ty) = ret_ty {
         // A function pointer is called without the declaration
         // available, so we have to apply any attributes with ABI
index 4f234fac9a4a0e65dba0040513c2e2d83a08c8fb..861233bafdfac01405d6a51f847d5af276bcc7ab 100644 (file)
@@ -603,7 +603,18 @@ pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
     let _icx = push_ctxt("trans_method_call");
     debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
     let method_call = MethodCall::expr(call_expr.id);
-    let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
+    let method_ty = match bcx.tcx().method_map.borrow().get(&method_call) {
+        Some(method) => match method.origin {
+            ty::MethodTraitObject(_) => match method.ty.sty {
+                ty::ty_bare_fn(_, ref fty) => {
+                    ty::mk_bare_fn(bcx.tcx(), None, meth::opaque_method_ty(bcx.tcx(), fty))
+                }
+                _ => method.ty
+            },
+            _ => method.ty
+        },
+        None => panic!("method not found in trans_method_call")
+    };
     trans_call_inner(
         bcx,
         call_expr.debug_loc(),
@@ -927,20 +938,21 @@ fn trans_args_under_call_abi<'blk, 'tcx>(
                                                           tuple_expr.id));
             let repr = adt::represent_type(bcx.ccx(), tuple_type);
             let repr_ptr = &*repr;
-            for i in 0..field_types.len() {
+            llargs.extend(field_types.iter().enumerate().map(|(i, field_type)| {
                 let arg_datum = tuple_lvalue_datum.get_element(
                     bcx,
-                    field_types[i],
+                    field_type,
                     |srcval| {
                         adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
-                    });
-                let arg_datum = arg_datum.to_expr_datum();
-                let arg_datum =
-                    unpack_datum!(bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
-                let arg_datum =
-                    unpack_datum!(bcx, arg_datum.to_appropriate_datum(bcx));
-                llargs.push(arg_datum.add_clean(bcx.fcx, arg_cleanup_scope));
-            }
+                    }).to_expr_datum();
+                unpack_result!(bcx, trans_arg_datum(
+                    bcx,
+                    field_type,
+                    arg_datum,
+                    arg_cleanup_scope,
+                    DontAutorefArg)
+                )
+            }));
         }
         _ => {
             bcx.sess().span_bug(tuple_expr.span,
index 1d4bbd79d71057baecdc624201e5d7a367355068..7fa26a7c1284196292c92c22ffe6bf4d5f30c3c3 100644 (file)
@@ -138,7 +138,7 @@ pub fn get_or_create_declaration_if_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tc
     // duplicate declarations
     let function_type = erase_regions(ccx.tcx(), &function_type);
     let params = match function_type.sty {
-        ty::ty_closure(_, _, substs) => &substs.types,
+        ty::ty_closure(_, substs) => &substs.types,
         _ => unreachable!()
     };
     let mono_id = MonoId {
index 6ca71254868f3f62d339852a4276319acf9d7f45..e181df545e6fc06aa63f4b0e2a39f2ea835d9dea 100644 (file)
@@ -195,24 +195,18 @@ pub fn immediate_rvalue_bcx<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 
 /// Allocates temporary space on the stack using alloca() and returns a by-ref Datum pointing to
 /// it. The memory will be dropped upon exit from `scope`. The callback `populate` should
-/// initialize the memory. If `zero` is true, the space will be zeroed when it is allocated; this
-/// is not necessary unless `bcx` does not dominate the end of `scope`.
+/// initialize the memory.
 pub fn lvalue_scratch_datum<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
                                               ty: Ty<'tcx>,
                                               name: &str,
-                                              zero: bool,
                                               scope: cleanup::ScopeId,
                                               arg: A,
                                               populate: F)
                                               -> DatumBlock<'blk, 'tcx, Lvalue> where
     F: FnOnce(A, Block<'blk, 'tcx>, ValueRef) -> Block<'blk, 'tcx>,
 {
-    let scratch = if zero {
-        alloca_zeroed(bcx, ty, name)
-    } else {
-        let llty = type_of::type_of(bcx.ccx(), ty);
-        alloca(bcx, llty, name)
-    };
+    let llty = type_of::type_of(bcx.ccx(), ty);
+    let scratch = alloca(bcx, llty, name);
 
     // Subtle. Populate the scratch memory *before* scheduling cleanup.
     let bcx = populate(arg, bcx, scratch);
@@ -383,7 +377,7 @@ pub fn to_lvalue_datum_in_scope<'blk>(self,
 
             ByValue => {
                 lvalue_scratch_datum(
-                    bcx, self.ty, name, false, scope, self,
+                    bcx, self.ty, name, scope, self,
                     |this, bcx, llval| this.store_to(bcx, llval))
             }
         }
index d70a904b81189fde012837d6b320799e493eabe5..f3b7058336b2fc350bf0a0257606a5a508976314 100644 (file)
@@ -472,7 +472,7 @@ fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
                     }
                 }
             },
-            ty::ty_closure(def_id, _, substs) => {
+            ty::ty_closure(def_id, substs) => {
                 let typer = NormalizingClosureTyper::new(cx.tcx());
                 let closure_ty = typer.closure_type(def_id, substs);
                 self.get_unique_type_id_of_closure_type(cx,
@@ -2983,7 +2983,7 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
         ty::ty_bare_fn(_, ref barefnty) => {
             subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
         }
-        ty::ty_closure(def_id, _, substs) => {
+        ty::ty_closure(def_id, substs) => {
             let typer = NormalizingClosureTyper::new(cx.tcx());
             let sig = typer.closure_type(def_id, substs).sig;
             subroutine_type_metadata(cx, unique_type_id, &sig, usage_site_span)
index 9491c8377a655fdbe10eee9e63cc2200f29092f2..1151b11d21f35ce4faebacb7c8b606b7c0062c25 100644 (file)
@@ -313,8 +313,7 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
                                      ty::mk_nil(bcx.tcx()));
         let (_, variant_cx) = invoke(variant_cx, dtor_addr, &args[..], dtor_ty, DebugLoc::None);
 
-        variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope);
-        variant_cx
+        variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope)
     })
 }
 
index 4423cd2774446a8df5dea1bb2aa5ebabc706f485..c07de3a87ec271accd0e8f69a763c2f46ee0cb4b 100644 (file)
@@ -45,7 +45,7 @@
 use syntax::codemap::DUMMY_SP;
 
 // drop_glue pointer, size, align.
-static VTABLE_OFFSET: uint = 3;
+const VTABLE_OFFSET: uint = 3;
 
 /// The main "translation" pass for methods.  Generates code
 /// for non-monomorphized methods only.  Other methods will
@@ -589,15 +589,16 @@ pub fn trans_object_shim<'a, 'tcx>(
     };
     let fty = monomorphize::apply_param_substs(tcx, &object_substs, &method_ty.fty);
     let fty = tcx.mk_bare_fn(fty);
-    debug!("trans_object_shim: fty={}", fty.repr(tcx));
+    let method_ty = opaque_method_ty(tcx, fty);
+    debug!("trans_object_shim: fty={} method_ty={}", fty.repr(tcx), method_ty.repr(tcx));
 
     //
-    let method_bare_fn_ty =
-        ty::mk_bare_fn(tcx, None, fty);
+    let shim_fn_ty = ty::mk_bare_fn(tcx, None, fty);
+    let method_bare_fn_ty = ty::mk_bare_fn(tcx, None, method_ty);
     let function_name =
-        link::mangle_internal_name_by_type_and_seq(ccx, method_bare_fn_ty, "object_shim");
+        link::mangle_internal_name_by_type_and_seq(ccx, shim_fn_ty, "object_shim");
     let llfn =
-        decl_internal_rust_fn(ccx, method_bare_fn_ty, &function_name);
+        decl_internal_rust_fn(ccx, shim_fn_ty, &function_name);
 
     let sig = ty::erase_late_bound_regions(ccx.tcx(), &fty.sig);
 
@@ -866,3 +867,20 @@ pub fn trans_trait_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 
     bcx
 }
+
+/// Replace the self type (&Self or Box<Self>) with an opaque pointer.
+pub fn opaque_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>, method_ty: &ty::BareFnTy<'tcx>)
+        -> &'tcx ty::BareFnTy<'tcx> {
+    let mut inputs = method_ty.sig.0.inputs.clone();
+    inputs[0] = ty::mk_mut_ptr(tcx, ty::mk_mach_int(tcx, ast::TyI8));
+
+    tcx.mk_bare_fn(ty::BareFnTy {
+        unsafety: method_ty.unsafety,
+        abi: method_ty.abi,
+        sig: ty::Binder(ty::FnSig {
+            inputs: inputs,
+            output: method_ty.sig.0.output,
+            variadic: method_ty.sig.0.variadic,
+        }),
+    })
+}
index 0ad15456df98f16daab554c59b289287426b0523..f9495af79c5b0c5969a5bba8a2d157ee272eb39d 100644 (file)
@@ -137,7 +137,7 @@ fn try_overloaded_call_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
             return Some(CallStep::Builtin);
         }
 
-        ty::ty_closure(def_id, _, substs) => {
+        ty::ty_closure(def_id, substs) => {
             assert_eq!(def_id.krate, ast::LOCAL_CRATE);
 
             // Check whether this is a call to a closure where we
index 0b7c5b04aaa44d5802f117f8312ed294b6018ad9..0d4edc01a4c1d73ae16c821e52de1a940b8d6f09 100644 (file)
@@ -16,7 +16,6 @@
 use middle::region;
 use middle::subst;
 use middle::ty::{self, ToPolyTraitRef, Ty};
-use rscope::RegionScope;
 use syntax::abi;
 use syntax::ast;
 use syntax::ast_util;
@@ -61,17 +60,8 @@ fn check_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
         abi::RustCall,
         expected_sig);
 
-    let region = match fcx.anon_regions(expr.span, 1) {
-        Err(_) => {
-            fcx.ccx.tcx.sess.span_bug(expr.span,
-                                      "can't make anon regions here?!")
-        }
-        Ok(regions) => regions[0],
-    };
-
     let closure_type = ty::mk_closure(fcx.ccx.tcx,
                                       expr_def_id,
-                                      fcx.ccx.tcx.mk_region(region),
                                       fcx.ccx.tcx.mk_substs(
                                         fcx.inh.param_env.free_substs.clone()));
 
index 083523f7ba92f97fce223becfadf59dccc1003e7..cffd74ccd7218c3da9458131a756bfd3e1578cb6 100644 (file)
@@ -14,8 +14,9 @@
 use middle::region;
 use middle::subst;
 use middle::ty::{self, Ty};
-use util::ppaux::{Repr};
+use util::ppaux::{Repr, UserString};
 
+use syntax::ast;
 use syntax::codemap::Span;
 
 pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
@@ -28,29 +29,98 @@ pub fn check_safety_of_destructor_if_necessary<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>
     // types that have been traversed so far by `traverse_type_if_unseen`
     let mut breadcrumbs: Vec<Ty<'tcx>> = Vec::new();
 
-    iterate_over_potentially_unsafe_regions_in_type(
+    let result = iterate_over_potentially_unsafe_regions_in_type(
         rcx,
         &mut breadcrumbs,
+        TypeContext::Root,
         typ,
         span,
         scope,
+        0,
         0);
+    match result {
+        Ok(()) => {}
+        Err(Error::Overflow(ref ctxt, ref detected_on_typ)) => {
+            let tcx = rcx.tcx();
+            span_err!(tcx.sess, span, E0320,
+                      "overflow while adding drop-check rules for {}",
+                      typ.user_string(rcx.tcx()));
+            match *ctxt {
+                TypeContext::Root => {
+                    // no need for an additional note if the overflow
+                    // was somehow on the root.
+                }
+                TypeContext::EnumVariant { def_id, variant, arg_index } => {
+                    // FIXME (pnkfelix): eventually lookup arg_name
+                    // for the given index on struct variants.
+                    span_note!(
+                        rcx.tcx().sess,
+                        span,
+                        "overflowed on enum {} variant {} argument {} type: {}",
+                        ty::item_path_str(tcx, def_id),
+                        variant,
+                        arg_index,
+                        detected_on_typ.user_string(rcx.tcx()));
+                }
+                TypeContext::Struct { def_id, field } => {
+                    span_note!(
+                        rcx.tcx().sess,
+                        span,
+                        "overflowed on struct {} field {} type: {}",
+                        ty::item_path_str(tcx, def_id),
+                        field,
+                        detected_on_typ.user_string(rcx.tcx()));
+                }
+            }
+        }
+    }
+}
+
+enum Error<'tcx> {
+    Overflow(TypeContext, ty::Ty<'tcx>),
+}
+
+enum TypeContext {
+    Root,
+    EnumVariant {
+        def_id: ast::DefId,
+        variant: ast::Name,
+        arg_index: usize,
+    },
+    Struct {
+        def_id: ast::DefId,
+        field: ast::Name,
+    }
 }
 
+// The `depth` counts the number of calls to this function;
+// the `xref_depth` counts the subset of such calls that go
+// across a `Box<T>` or `PhantomData<T>`.
 fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
     rcx: &mut Rcx<'a, 'tcx>,
     breadcrumbs: &mut Vec<Ty<'tcx>>,
+    context: TypeContext,
     ty_root: ty::Ty<'tcx>,
     span: Span,
     scope: region::CodeExtent,
-    depth: uint)
+    depth: uint,
+    xref_depth: uint) -> Result<(), Error<'tcx>>
 {
+    // Issue #22443: Watch out for overflow. While we are careful to
+    // handle regular types properly, non-regular ones cause problems.
+    let recursion_limit = rcx.tcx().sess.recursion_limit.get();
+    if xref_depth >= recursion_limit {
+        return Err(Error::Overflow(context, ty_root))
+    }
+
     let origin = || infer::SubregionOrigin::SafeDestructor(span);
     let mut walker = ty_root.walk();
     let opt_phantom_data_def_id = rcx.tcx().lang_items.phantom_data();
 
     let destructor_for_type = rcx.tcx().destructor_for_type.borrow();
 
+    let xref_depth_orig = xref_depth;
+
     while let Some(typ) = walker.next() {
         // Avoid recursing forever.
         if breadcrumbs.contains(&typ) {
@@ -61,20 +131,33 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
         // If we encounter `PhantomData<T>`, then we should replace it
         // with `T`, the type it represents as owned by the
         // surrounding context, before doing further analysis.
-        let typ = if let ty::ty_struct(struct_did, substs) = typ.sty {
-            if opt_phantom_data_def_id == Some(struct_did) {
-                let item_type = ty::lookup_item_type(rcx.tcx(), struct_did);
-                let tp_def = item_type.generics.types
-                    .opt_get(subst::TypeSpace, 0).unwrap();
-                let new_typ = substs.type_for_def(tp_def);
-                debug!("replacing phantom {} with {}",
+        let (typ, xref_depth) = match typ.sty {
+            ty::ty_struct(struct_did, substs) => {
+                if opt_phantom_data_def_id == Some(struct_did) {
+                    let item_type = ty::lookup_item_type(rcx.tcx(), struct_did);
+                    let tp_def = item_type.generics.types
+                        .opt_get(subst::TypeSpace, 0).unwrap();
+                    let new_typ = substs.type_for_def(tp_def);
+                    debug!("replacing phantom {} with {}",
+                           typ.repr(rcx.tcx()), new_typ.repr(rcx.tcx()));
+                    (new_typ, xref_depth_orig + 1)
+                } else {
+                    (typ, xref_depth_orig)
+                }
+            }
+
+            // Note: When ty_uniq is removed from compiler, the
+            // definition of `Box<T>` must carry a PhantomData that
+            // puts us into the previous case.
+            ty::ty_uniq(new_typ) => {
+                debug!("replacing ty_uniq {} with {}",
                        typ.repr(rcx.tcx()), new_typ.repr(rcx.tcx()));
-                new_typ
-            } else {
-                typ
+                (new_typ, xref_depth_orig + 1)
+            }
+
+            _ => {
+                (typ, xref_depth_orig)
             }
-        } else {
-            typ
         };
 
         let opt_type_did = match typ.sty {
@@ -87,9 +170,9 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
             opt_type_did.and_then(|did| destructor_for_type.get(&did));
 
         debug!("iterate_over_potentially_unsafe_regions_in_type \
-                {}typ: {} scope: {:?} opt_dtor: {:?}",
+                {}typ: {} scope: {:?} opt_dtor: {:?} xref: {}",
                (0..depth).map(|_| ' ').collect::<String>(),
-               typ.repr(rcx.tcx()), scope, opt_dtor);
+               typ.repr(rcx.tcx()), scope, opt_dtor, xref_depth);
 
         // If `typ` has a destructor, then we must ensure that all
         // borrowed data reachable via `typ` must outlive the parent
@@ -228,6 +311,8 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
 
             match typ.sty {
                 ty::ty_struct(struct_did, substs) => {
+                    debug!("typ: {} is struct; traverse structure and not type-expression",
+                           typ.repr(rcx.tcx()));
                     // Don't recurse; we extract type's substructure,
                     // so do not process subparts of type expression.
                     walker.skip_current_subtree();
@@ -240,17 +325,24 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
                                                   struct_did,
                                                   field.id,
                                                   substs);
-                        iterate_over_potentially_unsafe_regions_in_type(
+                        try!(iterate_over_potentially_unsafe_regions_in_type(
                             rcx,
                             breadcrumbs,
+                            TypeContext::Struct {
+                                def_id: struct_did,
+                                field: field.name,
+                            },
                             field_type,
                             span,
                             scope,
-                            depth+1)
+                            depth+1,
+                            xref_depth))
                     }
                 }
 
                 ty::ty_enum(enum_did, substs) => {
+                    debug!("typ: {} is enum; traverse structure and not type-expression",
+                           typ.repr(rcx.tcx()));
                     // Don't recurse; we extract type's substructure,
                     // so do not process subparts of type expression.
                     walker.skip_current_subtree();
@@ -260,14 +352,20 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
                                                  enum_did,
                                                  substs);
                     for variant_info in all_variant_info.iter() {
-                        for argument_type in variant_info.args.iter() {
-                            iterate_over_potentially_unsafe_regions_in_type(
+                        for (i, arg_type) in variant_info.args.iter().enumerate() {
+                            try!(iterate_over_potentially_unsafe_regions_in_type(
                                 rcx,
                                 breadcrumbs,
-                                *argument_type,
+                                TypeContext::EnumVariant {
+                                    def_id: enum_did,
+                                    variant: variant_info.name,
+                                    arg_index: i,
+                                },
+                                *arg_type,
                                 span,
                                 scope,
-                                depth+1)
+                                depth+1,
+                                xref_depth));
                         }
                     }
                 }
@@ -290,4 +388,6 @@ fn iterate_over_potentially_unsafe_regions_in_type<'a, 'tcx>(
             // is done.
         }
     }
+
+    return Ok(());
 }
index f65e585d23edd3c8c11e2ac3c11db443db9bd7ed..f99ba8940297dbc6c2a9a7e747bd3d5e72cbc9d7 100644 (file)
@@ -29,6 +29,7 @@
 pub enum Implication<'tcx> {
     RegionSubRegion(Option<Ty<'tcx>>, ty::Region, ty::Region),
     RegionSubGeneric(Option<Ty<'tcx>>, ty::Region, GenericKind<'tcx>),
+    RegionSubClosure(Option<Ty<'tcx>>, ty::Region, ast::DefId, &'tcx Substs<'tcx>),
     Predicate(ast::DefId, ty::Predicate<'tcx>),
 }
 
@@ -91,29 +92,9 @@ fn accumulate_from_ty(&mut self, ty: Ty<'tcx>) {
                 // No borrowed content reachable here.
             }
 
-            ty::ty_closure(_, region, _) => {
-                // An "closure type" is basically
-                // modeled here as equivalent to a struct like
-                //
-                //     struct TheClosure<'b> {
-                //         ...
-                //     }
-                //
-                // where the `'b` is the lifetime bound of the
-                // contents (i.e., all contents must outlive 'b).
-                //
-                // Even though closures are glorified structs
-                // of upvars, we do not need to consider them as they
-                // can't generate any new constraints.  The
-                // substitutions on the closure are equal to the free
-                // substitutions of the enclosing parameter
-                // environment.  An upvar captured by value has the
-                // same type as the original local variable which is
-                // already checked for consistency.  If the upvar is
-                // captured by reference it must also outlive the
-                // region bound on the closure, but this is explicitly
-                // handled by logic in regionck.
-                self.push_region_constraint_from_top(*region);
+            ty::ty_closure(def_id, substs) => {
+                let &(r_a, opt_ty) = self.stack.last().unwrap();
+                self.out.push(Implication::RegionSubClosure(opt_ty, r_a, def_id, substs));
             }
 
             ty::ty_trait(ref t) => {
@@ -448,6 +429,13 @@ fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
                         p.repr(tcx))
             }
 
+            Implication::RegionSubClosure(_, ref a, ref b, ref c) => {
+                format!("RegionSubClosure({}, {}, {})",
+                        a.repr(tcx),
+                        b.repr(tcx),
+                        c.repr(tcx))
+            }
+
             Implication::Predicate(ref def_id, ref p) => {
                 format!("Predicate({}, {})",
                         def_id.repr(tcx),
index f24da78bc7d3974ea304f5c8f38f9d1f80a237ec..fbf002b709ee54e7cc2514eadf75d73b70ed3cc9 100644 (file)
@@ -278,7 +278,7 @@ fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
             }
             ty::ty_enum(did, _) |
             ty::ty_struct(did, _) |
-            ty::ty_closure(did, _, _) => {
+            ty::ty_closure(did, _) => {
                 self.assemble_inherent_impl_candidates_for_type(did);
             }
             ty::ty_uniq(_) => {
@@ -641,8 +641,8 @@ fn assemble_closure_candidates(&mut self,
         // If so, add "synthetic impls".
         let steps = self.steps.clone();
         for step in &*steps {
-            let (closure_def_id, _, _) = match step.self_ty.sty {
-                ty::ty_closure(a, b, ref c) => (a, b, c),
+            let closure_def_id = match step.self_ty.sty {
+                ty::ty_closure(a, _) => a,
                 _ => continue,
             };
 
index 1518a09e7dc063656d2dba73782be746a686cbb7..a3e98b0c4c6582b9df464e50e649906c148b1069 100644 (file)
 use check::FnCtxt;
 use check::implicator;
 use check::vtable;
-use middle::def;
 use middle::mem_categorization as mc;
 use middle::region::CodeExtent;
+use middle::subst::Substs;
 use middle::traits;
-use middle::ty::{ReScope};
-use middle::ty::{self, Ty, MethodCall};
+use middle::ty::{self, ClosureTyper, ReScope, Ty, MethodCall};
 use middle::infer::{self, GenericKind};
 use middle::pat_util;
 use util::ppaux::{ty_to_string, Repr};
@@ -179,20 +178,6 @@ pub struct Rcx<'a, 'tcx: 'a> {
 
 }
 
-/// Returns the validity region of `def` -- that is, how long is `def` valid?
-fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region {
-    let tcx = fcx.tcx();
-    match def {
-        def::DefLocal(node_id) | def::DefUpvar(node_id, _) => {
-            tcx.region_maps.var_region(node_id)
-        }
-        _ => {
-            tcx.sess.bug(&format!("unexpected def in region_of_def: {:?}",
-                                 def))
-        }
-    }
-}
-
 struct RepeatingScope(ast::NodeId);
 pub enum SubjectNode { Subject(ast::NodeId), None }
 
@@ -368,7 +353,15 @@ fn relate_free_regions(&mut self,
                                                              ty::ReInfer(ty::ReVar(vid_b))) => {
                         self.fcx.inh.infcx.add_given(free_a, vid_b);
                     }
-                    implicator::Implication::RegionSubRegion(..) => {
+                    implicator::Implication::RegionSubGeneric(_, r_a, ref generic_b) => {
+                        debug!("RegionSubGeneric: {} <= {}",
+                               r_a.repr(tcx), generic_b.repr(tcx));
+
+                        self.region_bound_pairs.push((r_a, generic_b.clone()));
+                    }
+                    implicator::Implication::RegionSubRegion(..) |
+                    implicator::Implication::RegionSubClosure(..) |
+                    implicator::Implication::Predicate(..) => {
                         // In principle, we could record (and take
                         // advantage of) every relationship here, but
                         // we are also free not to -- it simply means
@@ -379,13 +372,6 @@ fn relate_free_regions(&mut self,
                         // relationship that arises here, but
                         // presently we do not.)
                     }
-                    implicator::Implication::RegionSubGeneric(_, r_a, ref generic_b) => {
-                        debug!("RegionSubGeneric: {} <= {}",
-                               r_a.repr(tcx), generic_b.repr(tcx));
-
-                        self.region_bound_pairs.push((r_a, generic_b.clone()));
-                    }
-                    implicator::Implication::Predicate(..) => { }
                 }
             }
         }
@@ -792,124 +778,9 @@ fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
 fn check_expr_fn_block(rcx: &mut Rcx,
                        expr: &ast::Expr,
                        body: &ast::Block) {
-    let tcx = rcx.fcx.tcx();
-    let function_type = rcx.resolve_node_type(expr.id);
-
-    match function_type.sty {
-        ty::ty_closure(_, region, _) => {
-            ty::with_freevars(tcx, expr.id, |freevars| {
-                constrain_captured_variables(rcx, *region, expr, freevars);
-            })
-        }
-        _ => { }
-    }
-
     let repeating_scope = rcx.set_repeating_scope(body.id);
     visit::walk_expr(rcx, expr);
     rcx.set_repeating_scope(repeating_scope);
-
-    match function_type.sty {
-        ty::ty_closure(_, region, _) => {
-            ty::with_freevars(tcx, expr.id, |freevars| {
-                let bounds = ty::region_existential_bound(*region);
-                ensure_free_variable_types_outlive_closure_bound(rcx, &bounds, expr, freevars);
-            })
-        }
-        _ => {}
-    }
-
-    /// Make sure that the type of all free variables referenced inside a closure/proc outlive the
-    /// closure/proc's lifetime bound. This is just a special case of the usual rules about closed
-    /// over values outliving the object's lifetime bound.
-    fn ensure_free_variable_types_outlive_closure_bound(
-        rcx: &mut Rcx,
-        bounds: &ty::ExistentialBounds,
-        expr: &ast::Expr,
-        freevars: &[ty::Freevar])
-    {
-        let tcx = rcx.fcx.ccx.tcx;
-
-        debug!("ensure_free_variable_types_outlive_closure_bound({}, {})",
-               bounds.region_bound.repr(tcx), expr.repr(tcx));
-
-        for freevar in freevars {
-            let var_node_id = {
-                let def_id = freevar.def.def_id();
-                assert!(def_id.krate == ast::LOCAL_CRATE);
-                def_id.node
-            };
-
-            // Compute the type of the field in the environment that
-            // represents `var_node_id`.  For a by-value closure, this
-            // will be the same as the type of the variable.  For a
-            // by-reference closure, this will be `&T` where `T` is
-            // the type of the variable.
-            let raw_var_ty = rcx.resolve_node_type(var_node_id);
-            let upvar_id = ty::UpvarId { var_id: var_node_id,
-                                         closure_expr_id: expr.id };
-            let var_ty = match rcx.fcx.inh.upvar_capture_map.borrow()[upvar_id] {
-                ty::UpvarCapture::ByRef(ref upvar_borrow) => {
-                    ty::mk_rptr(rcx.tcx(),
-                                rcx.tcx().mk_region(upvar_borrow.region),
-                                ty::mt { mutbl: upvar_borrow.kind.to_mutbl_lossy(),
-                                         ty: raw_var_ty })
-                }
-                ty::UpvarCapture::ByValue => raw_var_ty,
-            };
-
-            // Check that the type meets the criteria of the existential bounds:
-            for builtin_bound in &bounds.builtin_bounds {
-                let code = traits::ClosureCapture(var_node_id, expr.span, builtin_bound);
-                let cause = traits::ObligationCause::new(freevar.span, rcx.fcx.body_id, code);
-                rcx.fcx.register_builtin_bound(var_ty, builtin_bound, cause);
-            }
-
-            type_must_outlive(
-                rcx, infer::FreeVariable(expr.span, var_node_id),
-                var_ty, bounds.region_bound);
-        }
-    }
-
-    /// Make sure that all free variables referenced inside the closure outlive the closure's
-    /// lifetime bound. Also, create an entry in the upvar_borrows map with a region.
-    fn constrain_captured_variables(
-        rcx: &mut Rcx,
-        region_bound: ty::Region,
-        expr: &ast::Expr,
-        freevars: &[ty::Freevar])
-    {
-        let tcx = rcx.fcx.ccx.tcx;
-        debug!("constrain_captured_variables({}, {})",
-               region_bound.repr(tcx), expr.repr(tcx));
-        for freevar in freevars {
-            debug!("constrain_captured_variables: freevar.def={:?}", freevar.def);
-
-            // Identify the variable being closed over and its node-id.
-            let def = freevar.def;
-            let var_node_id = {
-                let def_id = def.def_id();
-                assert!(def_id.krate == ast::LOCAL_CRATE);
-                def_id.node
-            };
-            let upvar_id = ty::UpvarId { var_id: var_node_id,
-                                         closure_expr_id: expr.id };
-
-            match rcx.fcx.inh.upvar_capture_map.borrow()[upvar_id] {
-                ty::UpvarCapture::ByValue => { }
-                ty::UpvarCapture::ByRef(upvar_borrow) => {
-                    rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
-                                    region_bound, upvar_borrow.region);
-
-                    // Guarantee that the closure does not outlive the variable itself.
-                    let enclosing_region = region_of_def(rcx.fcx, def);
-                    debug!("constrain_captured_variables: enclosing_region = {}",
-                           enclosing_region.repr(tcx));
-                    rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
-                                    region_bound, enclosing_region);
-                }
-            }
-        }
-    }
 }
 
 fn constrain_callee(rcx: &mut Rcx,
@@ -1538,6 +1409,9 @@ pub fn type_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
                 let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
                 generic_must_outlive(rcx, o1, r_a, generic_b);
             }
+            implicator::Implication::RegionSubClosure(_, r_a, def_id, substs) => {
+                closure_must_outlive(rcx, origin.clone(), r_a, def_id, substs);
+            }
             implicator::Implication::Predicate(def_id, predicate) => {
                 let cause = traits::ObligationCause::new(origin.span(),
                                                          rcx.body_id,
@@ -1549,6 +1423,23 @@ pub fn type_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
     }
 }
 
+fn closure_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
+                                  origin: infer::SubregionOrigin<'tcx>,
+                                  region: ty::Region,
+                                  def_id: ast::DefId,
+                                  substs: &'tcx Substs<'tcx>) {
+    debug!("closure_must_outlive(region={}, def_id={}, substs={})",
+           region.repr(rcx.tcx()), def_id.repr(rcx.tcx()), substs.repr(rcx.tcx()));
+
+    let upvars = rcx.fcx.closure_upvars(def_id, substs).unwrap();
+    for upvar in upvars {
+        let var_id = upvar.def.def_id().local_id();
+        type_must_outlive(
+            rcx, infer::FreeVariable(origin.span(), var_id),
+            upvar.ty, region);
+    }
+}
+
 fn generic_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
                                   origin: infer::SubregionOrigin<'tcx>,
                                   region: ty::Region,
index 1913b55f1d8e69d03da3fc0b368345b055522ed5..58b67d31ab5803458fa02b9b6be6f4ce41451368 100644 (file)
@@ -397,7 +397,7 @@ fn populate_destructor_table(&self) {
             match self_type.ty.sty {
                 ty::ty_enum(type_def_id, _) |
                 ty::ty_struct(type_def_id, _) |
-                ty::ty_closure(type_def_id, _, _) => {
+                ty::ty_closure(type_def_id, _) => {
                     tcx.destructor_for_type
                        .borrow_mut()
                        .insert(type_def_id, method_def_id.def_id());
index 7b43a9fef06dcd36d604f5b42425fd42b3cecf72..3bd15fbc7dbea774fb55ebad140bd1ab85fed0ff 100644 (file)
     E0249, // expected constant expr for array length
     E0250, // expected constant expr for array length
     E0318, // can't create default impls for traits outside their crates
-    E0319  // trait impls for defaulted traits allowed just for structs/enums
+    E0319, // trait impls for defaulted traits allowed just for structs/enums
+    E0320  // recursive overflow during dropck
 }
 
 __build_diagnostic_array! { DIAGNOSTICS }
index 6b2676eca3d026ef4061ca442ab265236c7f7402..79e348cb03e49296912d38208064c976db4d1c19 100644 (file)
@@ -167,7 +167,7 @@ mod imp {
     use std::os;
     use std::ptr;
 
-    static LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
+    const LOCKFILE_EXCLUSIVE_LOCK: libc::DWORD = 0x00000002;
 
     #[allow(non_snake_case)]
     extern "system" {
index e58239a82c603b2487570641ec122241fa96dc7c..fc304884ec9d8e6e440bbfc72742206ce4186dac 100644 (file)
@@ -94,7 +94,7 @@ pub mod html {
              fn(clean::Crate) -> plugins::PluginResult,         // fn
              &'static str);                                     // description
 
-static PASSES: &'static [Pass] = &[
+const PASSES: &'static [Pass] = &[
     ("strip-hidden", passes::strip_hidden,
      "strips all doc(hidden) items from the output"),
     ("unindent-comments", passes::unindent_comments,
@@ -105,7 +105,7 @@ pub mod html {
      "strips all private items from a crate which cannot be seen externally"),
 ];
 
-static DEFAULT_PASSES: &'static [&'static str] = &[
+const DEFAULT_PASSES: &'static [&'static str] = &[
     "strip-hidden",
     "strip-private",
     "collapse-docs",
index a3cc2d6b935d9fab31d9bea4d38968ea822132e1..970ae06763c70dc208f3906efe3e6782e6b0501d 100644 (file)
@@ -24,7 +24,7 @@ pub trait ToHex {
     fn to_hex(&self) -> String;
 }
 
-static CHARS: &'static[u8] = b"0123456789abcdef";
+const CHARS: &'static [u8] = b"0123456789abcdef";
 
 impl ToHex for [u8] {
     /// Turn a vector of `u8` bytes into a hexadecimal string.
index fe0df1728efc0bd34559941d394346acc3d0a63d..926d8e03f2c3b91575dd902a188448ae1488340c 100644 (file)
 
 use core::prelude::*;
 
-use borrow::{Borrow, ToOwned};
+use borrow::{Borrow, Cow, ToOwned};
 use fmt::{self, Debug};
 use mem;
-use string::{String, CowString};
+use string::String;
 use ops;
 use cmp;
 use hash::{Hash, Hasher};
@@ -183,10 +183,10 @@ pub fn to_str(&self) -> Option<&str> {
         self.inner.to_str()
     }
 
-    /// Convert an `OsStr` to a `CowString`.
+    /// Convert an `OsStr` to a `Cow<str>`.
     ///
     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
-    pub fn to_string_lossy(&self) -> CowString {
+    pub fn to_string_lossy(&self) -> Cow<str> {
         self.inner.to_string_lossy()
     }
 
diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs
new file mode 100644 (file)
index 0000000..c9b105f
--- /dev/null
@@ -0,0 +1,59 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use prelude::v1::*;
+
+use boxed;
+use cell::UnsafeCell;
+use rt;
+use sync::{StaticMutex, Arc};
+
+pub struct Lazy<T> {
+    pub lock: StaticMutex,
+    pub ptr: UnsafeCell<*mut Arc<T>>,
+    pub init: fn() -> Arc<T>,
+}
+
+unsafe impl<T> Sync for Lazy<T> {}
+
+macro_rules! lazy_init {
+    ($init:expr) => (::io::lazy::Lazy {
+        lock: ::sync::MUTEX_INIT,
+        ptr: ::cell::UnsafeCell { value: 0 as *mut _ },
+        init: $init,
+    })
+}
+
+impl<T: Send + Sync + 'static> Lazy<T> {
+    pub fn get(&'static self) -> Option<Arc<T>> {
+        let _g = self.lock.lock();
+        unsafe {
+            let mut ptr = *self.ptr.get();
+            if ptr.is_null() {
+                ptr = boxed::into_raw(self.init());
+                *self.ptr.get() = ptr;
+            } else if ptr as usize == 1 {
+                return None
+            }
+            Some((*ptr).clone())
+        }
+    }
+
+    fn init(&'static self) -> Box<Arc<T>> {
+        rt::at_exit(move || unsafe {
+            let g = self.lock.lock();
+            let ptr = *self.ptr.get();
+            *self.ptr.get() = 1 as *mut _;
+            drop(g);
+            drop(Box::from_raw(ptr))
+        });
+        Box::new((self.init)())
+    }
+}
index 3b4e15953c4613958adfea8d2015625ae32e0017..5510c0203e6cff3c3af5e7c487cf2ad2112ba909 100644 (file)
 pub use self::cursor::Cursor;
 pub use self::error::{Result, Error, ErrorKind};
 pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
+pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
+pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
+
+#[macro_use] mod lazy;
 
 pub mod prelude;
 mod buffered;
@@ -46,6 +50,7 @@
 mod error;
 mod impls;
 mod util;
+mod stdio;
 
 const DEFAULT_BUF_SIZE: usize = 64 * 1024;
 
diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs
new file mode 100644 (file)
index 0000000..61ad990
--- /dev/null
@@ -0,0 +1,325 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use prelude::v1::*;
+use io::prelude::*;
+
+use cmp;
+use fmt;
+use io::lazy::Lazy;
+use io::{self, BufReader, LineWriter};
+use sync::{Arc, Mutex, MutexGuard};
+use sys::stdio;
+
+/// A handle to a raw instance of the standard input stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stdin_raw` function.
+pub struct StdinRaw(stdio::Stdin);
+
+/// A handle to a raw instance of the standard output stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stdout_raw` function.
+pub struct StdoutRaw(stdio::Stdout);
+
+/// A handle to a raw instance of the standard output stream of this process.
+///
+/// This handle is not synchronized or buffered in any fashion. Constructed via
+/// the `std::io::stderr_raw` function.
+pub struct StderrRaw(stdio::Stderr);
+
+/// Construct a new raw handle to the standard input of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
+/// handles is **not** available to raw handles returned from this function.
+///
+/// The returned handle has no external synchronization or buffering.
+pub fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
+
+/// Construct a new raw handle to the standard input stream of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdout`. Note that data is buffered by the
+/// `std::io::stdin` handles so writes which happen via this raw handle may
+/// appear before previous writes.
+///
+/// The returned handle has no external synchronization or buffering layered on
+/// top.
+pub fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
+
+/// Construct a new raw handle to the standard input stream of this process.
+///
+/// The returned handle does not interact with any other handles created nor
+/// handles returned by `std::io::stdout`.
+///
+/// The returned handle has no external synchronization or buffering layered on
+/// top.
+pub fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
+
+impl Read for StdinRaw {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
+}
+impl Write for StdoutRaw {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+}
+impl Write for StderrRaw {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+}
+
+/// A handle to the standard input stream of a process.
+///
+/// Each handle is a shared reference to a global buffer of input data to this
+/// process. A handle can be `lock`'d to gain full access to `BufRead` methods
+/// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
+/// to other writes.
+///
+/// This handle implements the `Read` trait, but beware that concurrent reads
+/// of `Stdin` must be executed with care.
+pub struct Stdin {
+    inner: Arc<Mutex<BufReader<StdinRaw>>>,
+}
+
+/// A locked reference to the a `Stdin` handle.
+///
+/// This handle implements both the `Read` and `BufRead` traits and is
+/// constructed via the `lock` method on `Stdin`.
+pub struct StdinLock<'a> {
+    inner: MutexGuard<'a, BufReader<StdinRaw>>,
+}
+
+/// Create a new handle to the global standard input stream of this process.
+///
+/// The handle returned refers to a globally shared buffer between all threads.
+/// Access is synchronized and can be explicitly controlled with the `lock()`
+/// method.
+///
+/// The `Read` trait is implemented for the returned value but the `BufRead`
+/// trait is not due to the global nature of the standard input stream. The
+/// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
+///
+/// To avoid locking and buffering altogether, it is recommended to use the
+/// `stdin_raw` constructor.
+pub fn stdin() -> Stdin {
+    static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
+    return Stdin {
+        inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
+    };
+
+    fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
+        // The default buffer capacity is 64k, but apparently windows
+        // doesn't like 64k reads on stdin. See #13304 for details, but the
+        // idea is that on windows we use a slightly smaller buffer that's
+        // been seen to be acceptable.
+        Arc::new(Mutex::new(if cfg!(windows) {
+            BufReader::with_capacity(8 * 1024, stdin_raw())
+        } else {
+            BufReader::new(stdin_raw())
+        }))
+    }
+}
+
+impl Stdin {
+    /// Lock this handle to the standard input stream, returning a readable
+    /// guard.
+    ///
+    /// The lock is released when the returned lock goes out of scope. The
+    /// returned guard also implements the `Read` and `BufRead` traits for
+    /// accessing the underlying data.
+    pub fn lock(&self) -> StdinLock {
+        StdinLock { inner: self.inner.lock().unwrap() }
+    }
+}
+
+impl Read for Stdin {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.lock().read(buf)
+    }
+
+    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
+        self.lock().read_to_end(buf)
+    }
+
+    fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
+        self.lock().read_to_string(buf)
+    }
+}
+
+impl<'a> Read for StdinLock<'a> {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        // Flush stdout so that weird issues like a print!'d prompt not being
+        // shown until after the user hits enter.
+        drop(stdout().flush());
+        self.inner.read(buf)
+    }
+}
+impl<'a> BufRead for StdinLock<'a> {
+    fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
+    fn consume(&mut self, n: usize) { self.inner.consume(n) }
+}
+
+// As with stdin on windows, stdout often can't handle writes of large
+// sizes. For an example, see #14940. For this reason, don't try to
+// write the entire output buffer on windows. On unix we can just
+// write the whole buffer all at once.
+//
+// For some other references, it appears that this problem has been
+// encountered by others [1] [2]. We choose the number 8KB just because
+// libuv does the same.
+//
+// [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
+// [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
+#[cfg(windows)]
+const OUT_MAX: usize = 8192;
+#[cfg(unix)]
+const OUT_MAX: usize = ::usize::MAX;
+
+/// A handle to the global standard output stream of the current process.
+///
+/// Each handle shares a global buffer of data to be written to the standard
+/// output stream. Access is also synchronized via a lock and explicit control
+/// over locking is available via the `lock` method.
+pub struct Stdout {
+    // FIXME: this should be LineWriter or BufWriter depending on the state of
+    //        stdout (tty or not). Note that if this is not line buffered it
+    //        should also flush-on-panic or some form of flush-on-abort.
+    inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
+}
+
+/// A locked reference to the a `Stdout` handle.
+///
+/// This handle implements the `Write` trait and is constructed via the `lock`
+/// method on `Stdout`.
+pub struct StdoutLock<'a> {
+    inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
+}
+
+/// Constructs a new reference to the standard output of the current process.
+///
+/// Each handle returned is a reference to a shared global buffer whose access
+/// is synchronized via a mutex. Explicit control over synchronization is
+/// provided via the `lock` method.
+///
+/// The returned handle implements the `Write` trait.
+///
+/// To avoid locking and buffering altogether, it is recommended to use the
+/// `stdout_raw` constructor.
+pub fn stdout() -> Stdout {
+    static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
+    return Stdout {
+        inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
+    };
+
+    fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
+        Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
+    }
+}
+
+impl Stdout {
+    /// Lock this handle to the standard output stream, returning a writable
+    /// guard.
+    ///
+    /// The lock is released when the returned lock goes out of scope. The
+    /// returned guard also implements the `Write` trait for writing data.
+    pub fn lock(&self) -> StdoutLock {
+        StdoutLock { inner: self.inner.lock().unwrap() }
+    }
+}
+
+impl Write for Stdout {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.lock().write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> {
+        self.lock().flush()
+    }
+    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
+        self.lock().write_all(buf)
+    }
+    fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
+        self.lock().write_fmt(fmt)
+    }
+}
+impl<'a> Write for StdoutLock<'a> {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+
+/// A handle to the standard error stream of a process.
+///
+/// For more information, see `stderr`
+pub struct Stderr {
+    inner: Arc<Mutex<StderrRaw>>,
+}
+
+/// A locked reference to the a `Stderr` handle.
+///
+/// This handle implements the `Write` trait and is constructed via the `lock`
+/// method on `Stderr`.
+pub struct StderrLock<'a> {
+    inner: MutexGuard<'a, StderrRaw>,
+}
+
+/// Constructs a new reference to the standard error stream of a process.
+///
+/// Each returned handle is synchronized amongst all other handles created from
+/// this function. No handles are buffered, however.
+///
+/// The returned handle implements the `Write` trait.
+///
+/// To avoid locking altogether, it is recommended to use the `stderr_raw`
+/// constructor.
+pub fn stderr() -> Stderr {
+    static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
+    return Stderr {
+        inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
+    };
+
+    fn stderr_init() -> Arc<Mutex<StderrRaw>> {
+        Arc::new(Mutex::new(stderr_raw()))
+    }
+}
+
+impl Stderr {
+    /// Lock this handle to the standard error stream, returning a writable
+    /// guard.
+    ///
+    /// The lock is released when the returned lock goes out of scope. The
+    /// returned guard also implements the `Write` trait for writing data.
+    pub fn lock(&self) -> StderrLock {
+        StderrLock { inner: self.inner.lock().unwrap() }
+    }
+}
+
+impl Write for Stderr {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.lock().write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> {
+        self.lock().flush()
+    }
+    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
+        self.lock().write_all(buf)
+    }
+    fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
+        self.lock().write_fmt(fmt)
+    }
+}
+impl<'a> Write for StderrLock<'a> {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
index b5bdeb7f181b0ddab0bebb3c25491c619d385ddc..7957bc35b76b5c3e90507df79c6b624e9b2c6326 100644 (file)
 #![feature(box_syntax)]
 #![feature(collections)]
 #![feature(core)]
-#![feature(int_uint)]
+#![feature(hash)]
 #![feature(lang_items)]
 #![feature(libc)]
 #![feature(linkage, thread_local, asm)]
 mod uint_macros;
 
 #[path = "num/isize.rs"]  pub mod isize;
-pub use isize as int;
 #[path = "num/i8.rs"]   pub mod i8;
 #[path = "num/i16.rs"]  pub mod i16;
 #[path = "num/i32.rs"]  pub mod i32;
 #[path = "num/i64.rs"]  pub mod i64;
 
 #[path = "num/usize.rs"] pub mod usize;
-pub use usize as uint;
 #[path = "num/u8.rs"]   pub mod u8;
 #[path = "num/u16.rs"]  pub mod u16;
 #[path = "num/u32.rs"]  pub mod u32;
index f99cd2b1d1be9eeb59887f081817a4787236af95..6ce3a939c6a4976ac9dacb5df04af3ac483125b1 100644 (file)
@@ -425,7 +425,7 @@ fn connect(i: usize, addr: SocketAddr) {
 
     #[test]
     fn multiple_connect_interleaved_lazy_schedule_ip4() {
-        static MAX: usize = 10;
+        const MAX: usize = 10;
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
index f6d05f961e1736efc5e54908730b70c37ba99463..a9fdeed13f08040eb28cf1ecf590a99086f8fe60 100644 (file)
@@ -253,7 +253,7 @@ pub fn float_to_str_bytes_common<T: Float>(
         deccum = deccum / radix_gen;
         deccum = deccum.trunc();
 
-        buf.push(char::from_digit(current_digit.to_int().unwrap() as u32, radix)
+        buf.push(char::from_digit(current_digit.to_isize().unwrap() as u32, radix)
              .unwrap() as u8);
 
         // No more digits to calculate for the non-fractional part -> break
@@ -310,7 +310,7 @@ pub fn float_to_str_bytes_common<T: Float>(
             let current_digit = deccum.trunc().abs();
 
             buf.push(char::from_digit(
-                current_digit.to_int().unwrap() as u32, radix).unwrap() as u8);
+                current_digit.to_isize().unwrap() as u32, radix).unwrap() as u8);
 
             // Decrease the deccumulator one fractional digit at a time
             deccum = deccum.fract();
@@ -422,8 +422,8 @@ pub fn float_to_str_common<T: Float>(
 
 // Some constants for from_str_bytes_common's input validation,
 // they define minimum radix values for which the character is a valid digit.
-static DIGIT_P_RADIX: u32 = ('p' as u32) - ('a' as u32) + 11;
-static DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
+const DIGIT_P_RADIX: u32 = ('p' as u32) - ('a' as u32) + 11;
+const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
 
 #[cfg(test)]
 mod tests {
index b82572fc08957380c68f439b2ae1919d7ccca064..728a5dac4e4c9316a8bf2e8211bff2f4436c0641 100644 (file)
@@ -714,28 +714,28 @@ fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
     ///
     /// The number of bytes returned is system-dependent.
     fn read_le_uint(&mut self) -> IoResult<uint> {
-        self.read_le_uint_n(usize::BYTES).map(|i| i as uint)
+        self.read_le_uint_n(usize::BYTES as usize).map(|i| i as uint)
     }
 
     /// Reads a little-endian integer.
     ///
     /// The number of bytes returned is system-dependent.
     fn read_le_int(&mut self) -> IoResult<int> {
-        self.read_le_int_n(isize::BYTES).map(|i| i as int)
+        self.read_le_int_n(isize::BYTES as usize).map(|i| i as int)
     }
 
     /// Reads a big-endian unsigned integer.
     ///
     /// The number of bytes returned is system-dependent.
     fn read_be_uint(&mut self) -> IoResult<uint> {
-        self.read_be_uint_n(usize::BYTES).map(|i| i as uint)
+        self.read_be_uint_n(usize::BYTES as usize).map(|i| i as uint)
     }
 
     /// Reads a big-endian integer.
     ///
     /// The number of bytes returned is system-dependent.
     fn read_be_int(&mut self) -> IoResult<int> {
-        self.read_be_int_n(isize::BYTES).map(|i| i as int)
+        self.read_be_int_n(isize::BYTES as usize).map(|i| i as int)
     }
 
     /// Reads a big-endian `u64`.
@@ -1098,25 +1098,25 @@ fn write_uint(&mut self, n: uint) -> IoResult<()> {
     /// Write a little-endian uint (number of bytes depends on system).
     #[inline]
     fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
-        extensions::u64_to_le_bytes(n as u64, usize::BYTES, |v| self.write_all(v))
+        extensions::u64_to_le_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
     }
 
     /// Write a little-endian int (number of bytes depends on system).
     #[inline]
     fn write_le_int(&mut self, n: int) -> IoResult<()> {
-        extensions::u64_to_le_bytes(n as u64, isize::BYTES, |v| self.write_all(v))
+        extensions::u64_to_le_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
     }
 
     /// Write a big-endian uint (number of bytes depends on system).
     #[inline]
     fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
-        extensions::u64_to_be_bytes(n as u64, usize::BYTES, |v| self.write_all(v))
+        extensions::u64_to_be_bytes(n as u64, usize::BYTES as usize, |v| self.write_all(v))
     }
 
     /// Write a big-endian int (number of bytes depends on system).
     #[inline]
     fn write_be_int(&mut self, n: int) -> IoResult<()> {
-        extensions::u64_to_be_bytes(n as u64, isize::BYTES, |v| self.write_all(v))
+        extensions::u64_to_be_bytes(n as u64, isize::BYTES as usize, |v| self.write_all(v))
     }
 
     /// Write a big-endian u64 (8 bytes).
index 56a707c24a6c9789c5c8b751e31759d91c7fef5f..a5df21749e22e3023580e1ae8ef4b6a48a130c67 100644 (file)
@@ -224,10 +224,10 @@ pub fn stdin() -> StdinReader {
 
     unsafe {
         ONCE.call_once(|| {
-            // The default buffer capacity is 64k, but apparently windows doesn't like
-            // 64k reads on stdin. See #13304 for details, but the idea is that on
-            // windows we use a slightly smaller buffer that's been seen to be
-            // acceptable.
+            // The default buffer capacity is 64k, but apparently windows
+            // doesn't like 64k reads on stdin. See #13304 for details, but the
+            // idea is that on windows we use a slightly smaller buffer that's
+            // been seen to be acceptable.
             let stdin = if cfg!(windows) {
                 BufferedReader::with_capacity(8 * 1024, stdin_raw())
             } else {
index c24b08deec2dc482d8395a7038214f22fc7762c9..b578b5e3d600a8b28467f05613d048e81b06d00d 100644 (file)
@@ -10,7 +10,7 @@
 
 //! Working with processes.
 
-#![unstable(feature = "process", reason = "recently added via RFC 579")]
+#![stable(feature = "process", since = "1.0.0")]
 #![allow(non_upper_case_globals)]
 
 use prelude::v1::*;
@@ -48,6 +48,7 @@
 /// let contents = output.stdout;
 /// assert!(output.status.success());
 /// ```
+#[stable(feature = "process", since = "1.0.0")]
 pub struct Child {
     handle: ProcessImp,
 
@@ -55,20 +56,25 @@ pub struct Child {
     status: Option<ExitStatusImp>,
 
     /// The handle for writing to the child's stdin, if it has been captured
+    #[stable(feature = "process", since = "1.0.0")]
     pub stdin: Option<ChildStdin>,
 
     /// The handle for reading from the child's stdout, if it has been captured
+    #[stable(feature = "process", since = "1.0.0")]
     pub stdout: Option<ChildStdout>,
 
     /// The handle for reading from the child's stderr, if it has been captured
+    #[stable(feature = "process", since = "1.0.0")]
     pub stderr: Option<ChildStderr>,
 }
 
 /// A handle to a child procesess's stdin
+#[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStdin {
     inner: AnonPipe
 }
 
+#[stable(feature = "process", since = "1.0.0")]
 impl Write for ChildStdin {
     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
         self.inner.write(buf)
@@ -80,10 +86,12 @@ fn flush(&mut self) -> io::Result<()> {
 }
 
 /// A handle to a child procesess's stdout
+#[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStdout {
     inner: AnonPipe
 }
 
+#[stable(feature = "process", since = "1.0.0")]
 impl Read for ChildStdout {
     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
         self.inner.read(buf)
@@ -91,10 +99,12 @@ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 }
 
 /// A handle to a child procesess's stderr
+#[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStderr {
     inner: AnonPipe
 }
 
+#[stable(feature = "process", since = "1.0.0")]
 impl Read for ChildStderr {
     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
         self.inner.read(buf)
@@ -108,8 +118,6 @@ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 /// to be changed (for example, by adding arguments) prior to spawning:
 ///
 /// ```
-/// # #![feature(process)]
-///
 /// use std::process::Command;
 ///
 /// let output = Command::new("sh").arg("-c").arg("echo hello").output().unwrap_or_else(|e| {
@@ -117,6 +125,7 @@ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
 /// });
 /// let hello = output.stdout;
 /// ```
+#[stable(feature = "process", since = "1.0.0")]
 pub struct Command {
     inner: CommandImp,
 
@@ -137,6 +146,7 @@ impl Command {
     ///
     /// Builder methods are provided to change these defaults and
     /// otherwise configure the process.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn new<S: AsOsStr + ?Sized>(program: &S) -> Command {
         Command {
             inner: CommandImp::new(program.as_os_str()),
@@ -147,12 +157,14 @@ pub fn new<S: AsOsStr + ?Sized>(program: &S) -> Command {
     }
 
     /// Add an argument to pass to the program.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn arg<S: AsOsStr + ?Sized>(&mut self, arg: &S) -> &mut Command {
         self.inner.arg(arg.as_os_str());
         self
     }
 
     /// Add multiple arguments to pass to the program.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn args<S: AsOsStr>(&mut self, args: &[S]) -> &mut Command {
         self.inner.args(args.iter().map(AsOsStr::as_os_str));
         self
@@ -162,26 +174,30 @@ pub fn args<S: AsOsStr>(&mut self, args: &[S]) -> &mut Command {
     ///
     /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
     /// and case-sensitive on all other platforms.
-    pub fn env<S: ?Sized, T: ?Sized>(&mut self, key: &S, val: &T) -> &mut Command where
-        S: AsOsStr, T: AsOsStr
+    #[stable(feature = "process", since = "1.0.0")]
+    pub fn env<K: ?Sized, V: ?Sized>(&mut self, key: &K, val: &V) -> &mut Command
+        where K: AsOsStr, V: AsOsStr
     {
         self.inner.env(key.as_os_str(), val.as_os_str());
         self
     }
 
     /// Removes an environment variable mapping.
-    pub fn env_remove<S: ?Sized + AsOsStr>(&mut self, key: &S) -> &mut Command {
+    #[stable(feature = "process", since = "1.0.0")]
+    pub fn env_remove<K: ?Sized + AsOsStr>(&mut self, key: &K) -> &mut Command {
         self.inner.env_remove(key.as_os_str());
         self
     }
 
     /// Clears the entire environment map for the child process.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn env_clear(&mut self) -> &mut Command {
         self.inner.env_clear();
         self
     }
 
     /// Set the working directory for the child process.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn current_dir<P: AsPath + ?Sized>(&mut self, dir: &P) -> &mut Command {
         self.inner.cwd(dir.as_path().as_os_str());
         self
@@ -189,6 +205,7 @@ pub fn current_dir<P: AsPath + ?Sized>(&mut self, dir: &P) -> &mut Command {
 
     /// Configuration for the child process's stdin handle (file descriptor 0).
     /// Defaults to `CreatePipe(true, false)` so the input can be written to.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
         self.stdin = Some(cfg.0);
         self
@@ -196,6 +213,7 @@ pub fn stdin(&mut self, cfg: Stdio) -> &mut Command {
 
     /// Configuration for the child process's stdout handle (file descriptor 1).
     /// Defaults to `CreatePipe(false, true)` so the output can be collected.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
         self.stdout = Some(cfg.0);
         self
@@ -203,6 +221,7 @@ pub fn stdout(&mut self, cfg: Stdio) -> &mut Command {
 
     /// Configuration for the child process's stderr handle (file descriptor 2).
     /// Defaults to `CreatePipe(false, true)` so the output can be collected.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn stderr(&mut self, cfg: Stdio) -> &mut Command {
         self.stderr = Some(cfg.0);
         self
@@ -234,6 +253,7 @@ fn spawn_inner(&self, default_io: StdioImp) -> io::Result<Child> {
     /// Executes the command as a child process, returning a handle to it.
     ///
     /// By default, stdin, stdout and stderr are inherited by the parent.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn spawn(&mut self) -> io::Result<Child> {
         self.spawn_inner(StdioImp::Inherit)
     }
@@ -258,8 +278,9 @@ pub fn spawn(&mut self) -> io::Result<Child> {
     /// println!("stdout: {}", String::from_utf8_lossy(output.stdout.as_slice()));
     /// println!("stderr: {}", String::from_utf8_lossy(output.stderr.as_slice()));
     /// ```
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn output(&mut self) -> io::Result<Output> {
-        self.spawn_inner(StdioImp::Capture).and_then(|p| p.wait_with_output())
+        self.spawn_inner(StdioImp::Piped).and_then(|p| p.wait_with_output())
     }
 
     /// Executes a command as a child process, waiting for it to finish and
@@ -279,6 +300,7 @@ pub fn output(&mut self) -> io::Result<Output> {
     ///
     /// println!("process exited with: {}", status);
     /// ```
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn status(&mut self) -> io::Result<ExitStatus> {
         self.spawn().and_then(|mut p| p.wait())
     }
@@ -317,7 +339,7 @@ fn setup_io(io: &StdioImp, fd: libc::c_int, readable: bool)
         Inherit => {
             (Some(AnonPipe::from_fd(fd)), None)
         }
-        Capture => {
+        Piped => {
             let (reader, writer) = try!(unsafe { pipe2::anon_pipe() });
             if readable {
                 (Some(reader), Some(writer))
@@ -330,45 +352,60 @@ fn setup_io(io: &StdioImp, fd: libc::c_int, readable: bool)
 
 /// The output of a finished process.
 #[derive(PartialEq, Eq, Clone)]
+#[stable(feature = "process", since = "1.0.0")]
 pub struct Output {
     /// The status (exit code) of the process.
+    #[stable(feature = "process", since = "1.0.0")]
     pub status: ExitStatus,
     /// The data that the process wrote to stdout.
+    #[stable(feature = "process", since = "1.0.0")]
     pub stdout: Vec<u8>,
     /// The data that the process wrote to stderr.
+    #[stable(feature = "process", since = "1.0.0")]
     pub stderr: Vec<u8>,
 }
 
 /// Describes what to do with a standard io stream for a child process.
+#[stable(feature = "process", since = "1.0.0")]
 pub struct Stdio(StdioImp);
 
 // The internal enum for stdio setup; see below for descriptions.
 #[derive(Clone)]
 enum StdioImp {
-    Capture,
+    Piped,
     Inherit,
     Null,
 }
 
 impl Stdio {
     /// A new pipe should be arranged to connect the parent and child processes.
-    pub fn capture() -> Stdio { Stdio(StdioImp::Capture) }
+    #[unstable(feature = "process_capture")]
+    #[deprecated(since = "1.0.0", reason = "renamed to `Stdio::piped`")]
+    pub fn capture() -> Stdio { Stdio::piped() }
+
+    /// A new pipe should be arranged to connect the parent and child processes.
+    #[stable(feature = "process", since = "1.0.0")]
+    pub fn piped() -> Stdio { Stdio(StdioImp::Piped) }
 
     /// The child inherits from the corresponding parent descriptor.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn inherit() -> Stdio { Stdio(StdioImp::Inherit) }
 
     /// This stream will be ignored. This is the equivalent of attaching the
     /// stream to `/dev/null`
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn null() -> Stdio { Stdio(StdioImp::Null) }
 }
 
 /// Describes the result of a process after it has terminated.
 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
+#[stable(feature = "process", since = "1.0.0")]
 pub struct ExitStatus(ExitStatusImp);
 
 impl ExitStatus {
     /// Was termination successful? Signal termination not considered a success,
     /// and success is defined as a zero exit status.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn success(&self) -> bool {
         self.0.success()
     }
@@ -378,6 +415,7 @@ pub fn success(&self) -> bool {
     /// On Unix, this will return `None` if the process was terminated
     /// by a signal; `std::os::unix` provides an extension trait for
     /// extracting the signal and other details from the `ExitStatus`.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn code(&self) -> Option<i32> {
         self.0.code()
     }
@@ -387,6 +425,7 @@ impl AsInner<ExitStatusImp> for ExitStatus {
     fn as_inner(&self) -> &ExitStatusImp { &self.0 }
 }
 
+#[stable(feature = "process", since = "1.0.0")]
 impl fmt::Display for ExitStatus {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         self.0.fmt(f)
@@ -396,6 +435,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 impl Child {
     /// Forces the child to exit. This is equivalent to sending a
     /// SIGKILL on unix platforms.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn kill(&mut self) -> io::Result<()> {
         #[cfg(unix)] fn collect_status(p: &mut Child) {
             // On Linux (and possibly other unices), a process that has exited will
@@ -436,6 +476,7 @@ pub fn kill(&mut self) -> io::Result<()> {
     /// before waiting. This helps avoid deadlock: it ensures that the
     /// child does not block waiting for input from the parent, while
     /// the parent waits for the child to exit.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn wait(&mut self) -> io::Result<ExitStatus> {
         drop(self.stdin.take());
         match self.status {
@@ -456,6 +497,7 @@ pub fn wait(&mut self) -> io::Result<ExitStatus> {
     /// before waiting. This helps avoid deadlock: it ensures that the
     /// child does not block waiting for input from the parent, while
     /// the parent waits for the child to exit.
+    #[stable(feature = "process", since = "1.0.0")]
     pub fn wait_with_output(mut self) -> io::Result<Output> {
         drop(self.stdin.take());
         fn read<T: Read + Send + 'static>(stream: Option<T>) -> Receiver<io::Result<Vec<u8>>> {
@@ -557,7 +599,7 @@ pub fn run_output(mut cmd: Command) -> String {
     #[test]
     fn stdout_works() {
         let mut cmd = Command::new("echo");
-        cmd.arg("foobar").stdout(Stdio::capture());
+        cmd.arg("foobar").stdout(Stdio::piped());
         assert_eq!(run_output(cmd), "foobar\n");
     }
 
@@ -567,7 +609,7 @@ fn set_current_dir_works() {
         let mut cmd = Command::new("/bin/sh");
         cmd.arg("-c").arg("pwd")
            .current_dir("/")
-           .stdout(Stdio::capture());
+           .stdout(Stdio::piped());
         assert_eq!(run_output(cmd), "/\n");
     }
 
@@ -576,8 +618,8 @@ fn set_current_dir_works() {
     fn stdin_works() {
         let mut p = Command::new("/bin/sh")
                             .arg("-c").arg("read line; echo $line")
-                            .stdin(Stdio::capture())
-                            .stdout(Stdio::capture())
+                            .stdin(Stdio::piped())
+                            .stdout(Stdio::piped())
                             .spawn().unwrap();
         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
         drop(p.stdin.take());
@@ -675,7 +717,7 @@ fn test_finish_twice() {
     #[cfg(not(target_os="android"))]
     #[test]
     fn test_wait_with_output_once() {
-        let prog = Command::new("echo").arg("hello").stdout(Stdio::capture())
+        let prog = Command::new("echo").arg("hello").stdout(Stdio::piped())
             .spawn().unwrap();
         let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
         let output_str = str::from_utf8(stdout.as_slice()).unwrap();
index 5c891441198039940cab0e08776a06379d9bf860..7fe20c37c6cd9b70dfa51e807e1ca741019fccb7 100644 (file)
@@ -321,7 +321,7 @@ fn reseed(&mut self, rng: &mut StdRng) {
         }
     }
 }
-static THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
+const THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
 
 /// The thread-local RNG.
@@ -638,19 +638,18 @@ fn test_std_rng_reseed() {
     }
 }
 
-#[cfg(test)]
-static RAND_BENCH_N: u64 = 100;
-
 #[cfg(test)]
 mod bench {
     extern crate test;
     use prelude::v1::*;
 
     use self::test::Bencher;
-    use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N};
+    use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng};
     use super::{OsRng, weak_rng};
     use mem::size_of;
 
+    const RAND_BENCH_N: u64 = 100;
+
     #[bench]
     fn rand_xorshift(b: &mut Bencher) {
         let mut rng: XorShiftRng = OsRng::new().unwrap().gen();
index 1a13405633d2ede6f2218e4caa596c67baf7d4e1..c2ead2675787b9ec08169ae371c28c0fd84a0f3d 100644 (file)
@@ -281,9 +281,9 @@ pub struct OsRng {
         hcryptprov: HCRYPTPROV
     }
 
-    static PROV_RSA_FULL: DWORD = 1;
-    static CRYPT_SILENT: DWORD = 64;
-    static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
+    const PROV_RSA_FULL: DWORD = 1;
+    const CRYPT_SILENT: DWORD = 64;
+    const CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
 
     #[allow(non_snake_case)]
     extern "system" {
index 1310d476f8ee20f15540b6bc75f7df4a64eb7acc..ee8bef50d89991c9dc9cfc1d4e6ad80cb2f10042 100644 (file)
@@ -1157,8 +1157,8 @@ fn stress() {
 
     #[test]
     fn stress_shared() {
-        static AMT: u32 = 10000;
-        static NTHREADS: u32 = 8;
+        const AMT: u32 = 10000;
+        const NTHREADS: u32 = 8;
         let (tx, rx) = channel::<i32>();
 
         let t = thread::spawn(move|| {
@@ -1663,8 +1663,8 @@ fn stress() {
 
     #[test]
     fn stress_shared() {
-        static AMT: u32 = 1000;
-        static NTHREADS: u32 = 8;
+        const AMT: u32 = 1000;
+        const NTHREADS: u32 = 8;
         let (tx, rx) = sync_channel::<i32>(0);
         let (dtx, drx) = sync_channel::<()>(0);
 
index 8de5bbc6206658c10d740bc67974e19edb00434f..2c14c9fe3f199020cd1edb9682123c4d1a759c6b 100644 (file)
@@ -473,7 +473,7 @@ fn both_ready() {
 
     #[test]
     fn stress() {
-        static AMT: i32 = 10000;
+        const AMT: i32 = 10000;
         let (tx1, rx1) = channel::<i32>();
         let (tx2, rx2) = channel::<i32>();
         let (tx3, rx3) = channel::<()>();
index 4c3b5d98a3cb172e13673201c2296d49b27f1c54..6f0febd61e80376b8d5d826c9609037436950923 100644 (file)
@@ -390,8 +390,8 @@ fn smoke_static() {
     fn lots_and_lots() {
         static M: StaticMutex = MUTEX_INIT;
         static mut CNT: u32 = 0;
-        static J: u32 = 1000;
-        static K: u32 = 3;
+        const J: u32 = 1000;
+        const K: u32 = 3;
 
         fn inc() {
             for _ in 0..J {
index 454c5b4f0cf7b20eb6bca82ca9cc7d9d3a73a89f..e9ff6c0bf9df0fa2123c09316de7a965fddc0063 100644 (file)
@@ -436,8 +436,8 @@ fn static_smoke() {
     #[test]
     fn frob() {
         static R: StaticRwLock = RW_LOCK_INIT;
-        static N: usize = 10;
-        static M: usize = 1000;
+        const N: usize = 10;
+        const M: usize = 1000;
 
         let (tx, rx) = channel::<()>();
         for _ in 0..N {
index fb9d6fef1faa7e0071343937f6aad0eea519eba4..31bdaee1e346acc2b9056fb5f9a5f546766a944e 100644 (file)
 use ops;
 use slice;
 use str;
-use string::{String, CowString};
+use string::String;
 use sys_common::AsInner;
 use unicode::str::{Utf16Item, utf16_items};
 use vec::Vec;
 
-static UTF8_REPLACEMENT_CHARACTER: &'static [u8] = b"\xEF\xBF\xBD";
+const UTF8_REPLACEMENT_CHARACTER: &'static [u8] = b"\xEF\xBF\xBD";
 
 /// A Unicode code point: from U+0000 to U+10FFFF.
 ///
@@ -530,7 +530,7 @@ pub fn as_str(&self) -> Option<&str> {
     /// Surrogates are replaced with `"\u{FFFD}"` (the replacement character “�”).
     ///
     /// This only copies the data if necessary (if it contains any surrogate).
-    pub fn to_string_lossy(&self) -> CowString {
+    pub fn to_string_lossy(&self) -> Cow<str> {
         let surrogate_pos = match self.next_surrogate(0) {
             None => return Cow::Borrowed(unsafe { str::from_utf8_unchecked(&self.bytes) }),
             Some((pos, _)) => pos,
@@ -844,7 +844,6 @@ mod tests {
     use borrow::Cow;
     use super::*;
     use mem::transmute;
-    use string::CowString;
 
     #[test]
     fn code_point_from_u32() {
@@ -1224,7 +1223,7 @@ fn wtf8_to_string_lossy() {
         assert_eq!(Wtf8::from_str("aé 💩").to_string_lossy(), Cow::Borrowed("aé 💩"));
         let mut string = Wtf8Buf::from_str("aé 💩");
         string.push(CodePoint::from_u32(0xD800).unwrap());
-        let expected: CowString = Cow::Owned(String::from_str("aé 💩�"));
+        let expected: Cow<str> = Cow::Owned(String::from_str("aé 💩�"));
         assert_eq!(string.to_string_lossy(), expected);
     }
 
index 14394a653b0ed5f4d848d51ca0143b43af8c7d03..4e9f9c80a1821c9996dba6a4c6fe6fac8309b3fc 100644 (file)
@@ -194,12 +194,12 @@ mod select {
     #[repr(C)]
     pub struct fd_set {
         // FIXME: shouldn't this be a c_ulong?
-        fds_bits: [libc::uintptr_t; (FD_SETSIZE / usize::BITS)]
+        fds_bits: [libc::uintptr_t; (FD_SETSIZE / usize::BITS as usize)]
     }
 
     pub fn fd_set(set: &mut fd_set, fd: i32) {
         let fd = fd as uint;
-        set.fds_bits[fd / usize::BITS] |= 1 << (fd % usize::BITS);
+        set.fds_bits[fd / usize::BITS as usize] |= 1 << (fd % usize::BITS as usize);
     }
 }
 
index 632270bc5ccbf250286bc176d1f7c08ce9ea4935..80bfd57e933c42af7cb23da3a33006a8f553c59f 100644 (file)
@@ -63,6 +63,7 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 pub mod timer;
 pub mod tty;
 pub mod udp;
+pub mod stdio;
 
 pub mod addrinfo {
     pub use sys_common::net::get_host_addresses;
index 023d951dc4f8a8aad9152e24f5fc2d527b859425..c8ac524876b5bdfd651ee2d976604f6ea2a90ca8 100644 (file)
 
 use core::prelude::*;
 
+use borrow::Cow;
 use fmt::{self, Debug};
 use vec::Vec;
 use slice::SliceExt as StdSliceExt;
 use str;
-use string::{String, CowString};
+use string::String;
 use mem;
 
 #[derive(Clone, Hash)]
@@ -76,7 +77,7 @@ pub fn to_str(&self) -> Option<&str> {
         str::from_utf8(&self.inner).ok()
     }
 
-    pub fn to_string_lossy(&self) -> CowString {
+    pub fn to_string_lossy(&self) -> Cow<str> {
         String::from_utf8_lossy(&self.inner)
     }
 
diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs
new file mode 100644 (file)
index 0000000..2f9610f
--- /dev/null
@@ -0,0 +1,52 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use prelude::v1::*;
+
+use io;
+use libc;
+use sys::fd::FileDesc;
+
+pub struct Stdin(());
+pub struct Stdout(());
+pub struct Stderr(());
+
+impl Stdin {
+    pub fn new() -> Stdin { Stdin(()) }
+
+    pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
+        let fd = FileDesc::new(libc::STDIN_FILENO);
+        let ret = fd.read(data);
+        fd.into_raw();
+        return ret;
+    }
+}
+
+impl Stdout {
+    pub fn new() -> Stdout { Stdout(()) }
+
+    pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+        let fd = FileDesc::new(libc::STDOUT_FILENO);
+        let ret = fd.write(data);
+        fd.into_raw();
+        return ret;
+    }
+}
+
+impl Stderr {
+    pub fn new() -> Stderr { Stderr(()) }
+
+    pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+        let fd = FileDesc::new(libc::STDERR_FILENO);
+        let ret = fd.write(data);
+        fd.into_raw();
+        return ret;
+    }
+}
index 2d1a5e10bd63f73a6e815452f8ea9abb41e35cf6..8ed7302b6653f74327da76665a0455137a8abae2 100644 (file)
 pub const ERROR_NO_MORE_FILES: libc::DWORD = 18;
 pub const TOKEN_READ: libc::DWORD = 0x20008;
 
+// Note that these are not actually HANDLEs, just values to pass to GetStdHandle
+pub const STD_INPUT_HANDLE: libc::DWORD = -10;
+pub const STD_OUTPUT_HANDLE: libc::DWORD = -11;
+pub const STD_ERROR_HANDLE: libc::DWORD = -12;
+
 #[repr(C)]
 #[cfg(target_arch = "x86")]
 pub struct WSADATA {
@@ -427,6 +432,7 @@ pub fn OpenProcessToken(ProcessHandle: libc::HANDLE,
                             DesiredAccess: libc::DWORD,
                             TokenHandle: *mut libc::HANDLE) -> libc::BOOL;
     pub fn GetCurrentProcess() -> libc::HANDLE;
+    pub fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
 }
 
 #[link(name = "userenv")]
index 99de659be41edf7986b81236f3cea90305bb9fc3..0089dcad455df2f731608871524b6edf803f329a 100644 (file)
 
 use prelude::v1::*;
 
-use libc::{self, HANDLE};
-use io;
 use io::ErrorKind;
+use io;
+use libc::{self, HANDLE};
+use mem;
 use ptr;
 use sys::cvt;
 
@@ -28,6 +29,12 @@ pub fn new(handle: HANDLE) -> Handle {
 
     pub fn raw(&self) -> HANDLE { self.0 }
 
+    pub fn into_raw(self) -> HANDLE {
+        let ret = self.0;
+        unsafe { mem::forget(self) }
+        return ret;
+    }
+
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
         read(self.0, buf)
     }
index 5bb2a134533ed0217b7dd9135b51e070e56fd346..3bdadbb9012e04da91a39f5635bfb779614b5e42 100644 (file)
@@ -61,6 +61,7 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 pub mod timer;
 pub mod tty;
 pub mod udp;
+pub mod stdio;
 
 pub mod addrinfo {
     pub use sys_common::net::get_host_addresses;
index 587ab7924fd1dc541fd7751cb82a61ff077f3362..89cf8a08a68f9448dffb18582f02d8672a68bda8 100644 (file)
@@ -59,8 +59,8 @@ fn FormatMessageW(flags: DWORD,
                           -> DWORD;
     }
 
-    static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
-    static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
+    const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
+    const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
 
     // This value is calculated from the macro
     // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
index af94b56bf1f71aaf39433a4072093ca4ee64475e..ad1e6c4b0e727eeb0f0776f3ae4bf8c6f2e802a4 100644 (file)
 /// The underlying OsString/OsStr implementation on Windows is a
 /// wrapper around the "WTF-8" encoding; see the `wtf8` module for more.
 
+use borrow::Cow;
 use fmt::{self, Debug};
 use sys_common::wtf8::{Wtf8, Wtf8Buf};
-use string::{String, CowString};
+use string::String;
 use result::Result;
 use option::Option;
 use mem;
@@ -70,7 +71,7 @@ pub fn to_str(&self) -> Option<&str> {
         self.inner.as_str()
     }
 
-    pub fn to_string_lossy(&self) -> CowString {
+    pub fn to_string_lossy(&self) -> Cow<str> {
         self.inner.to_string_lossy()
     }
 
diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs
new file mode 100644 (file)
index 0000000..72ce8b7
--- /dev/null
@@ -0,0 +1,155 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use prelude::v1::*;
+use io::prelude::*;
+
+use io::{self, Cursor};
+use iter::repeat;
+use libc;
+use ptr;
+use str;
+use sync::Mutex;
+use sys::c;
+use sys::cvt;
+use sys::handle::Handle;
+
+struct NoClose(Option<Handle>);
+
+enum Output {
+    Console(NoClose),
+    Pipe(NoClose),
+}
+
+pub struct Stdin {
+    handle: Output,
+    utf8: Mutex<io::Cursor<Vec<u8>>>,
+}
+pub struct Stdout(Output);
+pub struct Stderr(Output);
+
+fn get(handle: libc::DWORD) -> io::Result<Output> {
+    let handle = unsafe { c::GetStdHandle(handle) };
+    if handle == libc::INVALID_HANDLE_VALUE {
+        Err(io::Error::last_os_error())
+    } else if handle.is_null() {
+        Err(io::Error::new(io::ErrorKind::Other,
+                           "no stdio handle available for this process", None))
+    } else {
+        let ret = NoClose::new(handle);
+        let mut out = 0;
+        match unsafe { c::GetConsoleMode(handle, &mut out) } {
+            0 => Ok(Output::Pipe(ret)),
+            _ => Ok(Output::Console(ret)),
+        }
+    }
+}
+
+fn write(out: &Output, data: &[u8]) -> io::Result<usize> {
+    let handle = match *out {
+        Output::Console(ref c) => c.get().raw(),
+        Output::Pipe(ref p) => return p.get().write(data),
+    };
+    let utf16 = match str::from_utf8(data).ok() {
+        Some(utf8) => utf8.utf16_units().collect::<Vec<u16>>(),
+        None => return Err(invalid_encoding()),
+    };
+    let mut written = 0;
+    try!(cvt(unsafe {
+        c::WriteConsoleW(handle,
+                         utf16.as_ptr() as libc::LPCVOID,
+                         utf16.len() as u32,
+                         &mut written,
+                         ptr::null_mut())
+    }));
+
+    // FIXME if this only partially writes the utf16 buffer then we need to
+    //       figure out how many bytes of `data` were actually written
+    assert_eq!(written as usize, utf16.len());
+    Ok(data.len())
+}
+
+impl Stdin {
+    pub fn new() -> Stdin {
+        Stdin {
+            handle: get(c::STD_INPUT_HANDLE).unwrap(),
+            utf8: Mutex::new(Cursor::new(Vec::new())),
+        }
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let handle = match self.handle {
+            Output::Console(ref c) => c.get().raw(),
+            Output::Pipe(ref p) => return p.get().read(buf),
+        };
+        let mut utf8 = self.utf8.lock().unwrap();
+        // Read more if the buffer is empty
+        if utf8.position() as usize == utf8.get_ref().len() {
+            let mut utf16: Vec<u16> = repeat(0u16).take(0x1000).collect();
+            let mut num = 0;
+            try!(cvt(unsafe {
+                c::ReadConsoleW(handle,
+                                utf16.as_mut_ptr() as libc::LPVOID,
+                                utf16.len() as u32,
+                                &mut num,
+                                ptr::null_mut())
+            }));
+            utf16.truncate(num as usize);
+            // FIXME: what to do about this data that has already been read?
+            let data = match String::from_utf16(&utf16) {
+                Ok(utf8) => utf8.into_bytes(),
+                Err(..) => return Err(invalid_encoding()),
+            };
+            *utf8 = Cursor::new(data);
+        }
+
+        // MemReader shouldn't error here since we just filled it
+        utf8.read(buf)
+    }
+}
+
+impl Stdout {
+    pub fn new() -> Stdout {
+        Stdout(get(c::STD_OUTPUT_HANDLE).unwrap())
+    }
+
+    pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+        write(&self.0, data)
+    }
+}
+
+impl Stderr {
+    pub fn new() -> Stderr {
+        Stderr(get(c::STD_ERROR_HANDLE).unwrap())
+    }
+
+    pub fn write(&self, data: &[u8]) -> io::Result<usize> {
+        write(&self.0, data)
+    }
+}
+
+impl NoClose {
+    fn new(handle: libc::HANDLE) -> NoClose {
+        NoClose(Some(Handle::new(handle)))
+    }
+
+    fn get(&self) -> &Handle { self.0.as_ref().unwrap() }
+}
+
+impl Drop for NoClose {
+    fn drop(&mut self) {
+        self.0.take().unwrap().into_raw();
+    }
+}
+
+fn invalid_encoding() -> io::Error {
+    io::Error::new(io::ErrorKind::InvalidInput, "text was not valid unicode",
+                   None)
+}
index 6aad2bbcc7f08b47ab57f6dbd0f097cedbd2ce08..0f0bca5e8b2a07a2c86710081d6abd729768d05d 100644 (file)
 //! a thread will unwind the stack, running destructors and freeing
 //! owned resources. Thread panic is unrecoverable from within
 //! the panicking thread (i.e. there is no 'try/catch' in Rust), but
-//! panic may optionally be detected from a different thread. If
-//! the main thread panics the application will exit with a non-zero
+//! the panic may optionally be detected from a different thread. If
+//! the main thread panics, the application will exit with a non-zero
 //! exit code.
 //!
 //! When the main thread of a Rust program terminates, the entire program shuts
 //! down, even if other threads are still running. However, this module provides
 //! convenient facilities for automatically waiting for the termination of a
-//! child thread (i.e., join), described below.
+//! child thread (i.e., join).
 //!
 //! ## The `Thread` type
 //!
-//! Already-running threads are represented via the `Thread` type, which you can
+//! Threads are represented via the `Thread` type, which you can
 //! get in one of two ways:
 //!
-//! * By spawning a new thread, e.g. using the `thread::spawn` constructor;
+//! * By spawning a new thread, e.g. using the `thread::spawn` function.
 //! * By requesting the current thread, using the `thread::current` function.
 //!
 //! Threads can be named, and provide some built-in support for low-level
-//! synchronization described below.
+//! synchronization (described below).
 //!
 //! The `thread::current()` function is available even for threads not spawned
 //! by the APIs of this module.
 //! use std::thread;
 //!
 //! thread::spawn(move || {
-//!     println!("Hello, World!");
-//!     // some computation here
+//!     // some work here
 //! });
 //! ```
 //!
 //! In this example, the spawned thread is "detached" from the current
-//! thread, meaning that it can outlive the thread that spawned
-//! it. (Note, however, that when the main thread terminates all
-//! detached threads are terminated as well.)
+//! thread. This means that it can outlive its parent (the thread that spawned
+//! it), unless this parent is the main thread.
 //!
 //! ## Scoped threads
 //!
 //! Often a parent thread uses a child thread to perform some particular task,
 //! and at some point must wait for the child to complete before continuing.
-//! For this scenario, use the `scoped` constructor:
+//! For this scenario, use the `thread::scoped` function:
 //!
 //! ```rust
 //! use std::thread;
 //!
 //! let guard = thread::scoped(move || {
-//!     println!("Hello, World!");
-//!     // some computation here
+//!     // some work here
 //! });
+//!
 //! // do some other work in the meantime
 //! let output = guard.join();
 //! ```
 //! terminates) when it is dropped. You can join the child thread in
 //! advance by calling the `join` method on the guard, which will also
 //! return the result produced by the thread.  A handle to the thread
-//! itself is available via the `thread` method on the join guard.
-//!
-//! (Note: eventually, the `scoped` constructor will allow the parent and child
-//! threads to data that lives on the parent thread's stack, but some language
-//! changes are needed before this is possible.)
+//! itself is available via the `thread` method of the join guard.
 //!
 //! ## Configuring threads
 //!
 //! use std::thread;
 //!
 //! thread::Builder::new().name("child1".to_string()).spawn(move || {
-//!     println!("Hello, world!")
+//!     println!("Hello, world!");
 //! });
 //! ```
 //!
 //! initially not present:
 //!
 //! * The `thread::park()` function blocks the current thread unless or until
-//!   the token is available for its thread handle, at which point It atomically
+//!   the token is available for its thread handle, at which point it atomically
 //!   consumes the token. It may also return *spuriously*, without consuming the
 //!   token. `thread::park_timeout()` does the same, but allows specifying a
 //!   maximum time to block the thread for.
 //! * It avoids the need to allocate mutexes and condvars when building new
 //!   synchronization primitives; the threads already provide basic blocking/signaling.
 //!
-//! * It can be implemented highly efficiently on many platforms.
+//! * It can be implemented very efficiently on many platforms.
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
@@ -170,7 +164,7 @@ pub struct Builder {
     // A name for the thread-to-be, for identification in panic messages
     name: Option<String>,
     // The size of the stack for the spawned thread
-    stack_size: Option<uint>,
+    stack_size: Option<usize>,
     // Thread-local stdout
     stdout: Option<Box<Writer + Send + 'static>>,
     // Thread-local stderr
@@ -200,7 +194,7 @@ pub fn name(mut self, name: String) -> Builder {
 
     /// Set the size of the stack for the new thread.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn stack_size(mut self, size: uint) -> Builder {
+    pub fn stack_size(mut self, size: usize) -> Builder {
         self.stack_size = Some(size);
         self
     }
@@ -283,8 +277,8 @@ fn spawn_inner<T: Send>(self, f: Thunk<(), T>) -> io::Result<JoinInner<T>> {
         // address at which our stack started).
         let main = move || {
             let something_around_the_top_of_the_stack = 1;
-            let addr = &something_around_the_top_of_the_stack as *const int;
-            let my_stack_top = addr as uint;
+            let addr = &something_around_the_top_of_the_stack as *const isize;
+            let my_stack_top = addr as usize;
             let my_stack_bottom = my_stack_top - stack_size + 1024;
             unsafe {
                 stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top);
@@ -779,7 +773,7 @@ fn test_spawn_sched() {
 
         let (tx, rx) = channel();
 
-        fn f(i: int, tx: Sender<()>) {
+        fn f(i: i32, tx: Sender<()>) {
             let tx = tx.clone();
             thread::spawn(move|| {
                 if i == 0 {
@@ -808,13 +802,13 @@ fn test_spawn_sched_childs_on_default_sched() {
     }
 
     fn avoid_copying_the_body<F>(spawnfn: F) where F: FnOnce(Thunk<'static>) {
-        let (tx, rx) = channel::<uint>();
+        let (tx, rx) = channel::<u32>();
 
         let x = box 1;
-        let x_in_parent = (&*x) as *const int as uint;
+        let x_in_parent = (&*x) as *const isize as u32;
 
         spawnfn(Thunk::new(move|| {
-            let x_in_child = (&*x) as *const int as uint;
+            let x_in_child = (&*x) as *const isize as u32;
             tx.send(x_in_child).unwrap();
         }));
 
@@ -853,8 +847,8 @@ fn test_child_doesnt_ref_parent() {
         // climbing the task tree to dereference each ancestor. (See #1789)
         // (well, it would if the constant were 8000+ - I lowered it to be more
         // valgrind-friendly. try this at home, instead..!)
-        static GENERATIONS: uint = 16;
-        fn child_no(x: uint) -> Thunk<'static> {
+        const GENERATIONS: usize = 16;
+        fn child_no(x: usize) -> Thunk<'static> {
             return Thunk::new(move|| {
                 if x < GENERATIONS {
                     thread::spawn(move|| child_no(x+1).invoke(()));
index a2a5d8b81f40458e43b018fe77bb9d5426ee294d..d89d69e9497167e9fdddedcc25da927de7411616 100644 (file)
@@ -119,7 +119,7 @@ macro_rules! __scoped_thread_local_inner {
         const _INIT: __Key<$t> = __Key {
             inner: ::std::thread_local::scoped::__impl::KeyInner {
                 inner: ::std::thread_local::scoped::__impl::OS_INIT,
-                marker: ::std::marker::InvariantType,
+                marker: ::std::marker::PhantomData::<::std::cell::Cell<$t>>,
             }
         };
 
@@ -244,12 +244,13 @@ pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
           target_arch = "aarch64"))]
 mod imp {
     use marker;
+    use std::cell::Cell;
     use sys_common::thread_local::StaticKey as OsStaticKey;
 
     #[doc(hidden)]
     pub struct KeyInner<T> {
         pub inner: OsStaticKey,
-        pub marker: marker::InvariantType<T>,
+        pub marker: marker::PhantomData<Cell<T>>,
     }
 
     unsafe impl<T> ::marker::Sync for KeyInner<T> { }
index 2cf157bd245227f3710a0243b14c4b52919a0d4c..896e638deb46540ccb910309fd3f8d345aaf94a1 100644 (file)
@@ -77,11 +77,11 @@ pub enum AbiArchitecture {
 }
 
 #[allow(non_upper_case_globals)]
-static AbiDatas: &'static [AbiData] = &[
+const AbiDatas: &'static [AbiData] = &[
     // Platform-specific ABIs
     AbiData {abi: Cdecl, name: "cdecl" },
     AbiData {abi: Stdcall, name: "stdcall" },
-    AbiData {abi: Fastcall, name:"fastcall" },
+    AbiData {abi: Fastcall, name: "fastcall" },
     AbiData {abi: Aapcs, name: "aapcs" },
     AbiData {abi: Win64, name: "win64" },
 
index 27219774cf148c52f68f8e009fc8d7130691fdd8..a6f4974502c211e582b161e6b7e3f8bc2c74c28d 100644 (file)
@@ -25,7 +25,7 @@
 use term;
 
 /// maximum number of lines we will print for each error; arbitrary.
-static MAX_LINES: usize = 6;
+const MAX_LINES: usize = 6;
 
 #[derive(Clone, Copy)]
 pub enum RenderSpan {
index ae48084947e4393b5531c9dc3c6de0a6c9e206af..e58a3de41c05c2d9270fe42f5c6345cb55ba3dc9 100644 (file)
@@ -45,7 +45,7 @@ fn next(&self) -> State {
     }
 }
 
-static OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"];
+const OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"];
 
 pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
                        -> Box<base::MacResult+'cx> {
index ffc136d5a1d1a19b41bab604f7774b2e8fabfb54..18d3f85f4b58ed80d11fb26c53b81f4d72a234ee 100644 (file)
@@ -45,7 +45,7 @@
 // stable (active).
 // NB: The featureck.py script parses this information directly out of the source
 // so take care when modifying it.
-static KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
+const KNOWN_FEATURES: &'static [(&'static str, &'static str, Status)] = &[
     ("globs", "1.0.0", Accepted),
     ("macro_rules", "1.0.0", Accepted),
     ("struct_variant", "1.0.0", Accepted),
 
     // Allows the use of rustc_* attributes; RFC 572
     ("rustc_attrs", "1.0.0", Active),
+
+    // Allows the use of `static_assert`
+    ("static_assert", "1.0.0", Active),
 ];
 // (changing above list without updating src/doc/reference.md makes @cmr sad)
 
@@ -159,7 +162,7 @@ enum Status {
 }
 
 // Attributes that have a special meaning to rustc or rustdoc
-pub static KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
+pub const KNOWN_ATTRIBUTES: &'static [(&'static str, AttributeType)] = &[
     // Normal attributes
 
     ("warn", Normal),
@@ -173,6 +176,7 @@ enum Status {
     ("plugin_registrar", Normal),
 
     ("cfg", Normal),
+    ("cfg_attr", Normal),
     ("main", Normal),
     ("start", Normal),
     ("test", Normal),
@@ -241,7 +245,8 @@ enum Status {
     ("no_split_stack", Whitelisted),
     ("no_stack_check", Whitelisted),
     ("packed", Whitelisted),
-    ("static_assert", Whitelisted),
+    ("static_assert", Gated("static_assert",
+                            "`#[static_assert]` is an experimental feature, and has a poor API")),
     ("no_debug", Whitelisted),
     ("omit_gdb_pretty_printer_section", Whitelisted),
     ("unsafe_no_drop_flag", Gated("unsafe_no_drop_flag",
@@ -769,4 +774,3 @@ pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
                       |ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
                                                      krate))
 }
-
index 7a5d75581a511447cf5cd4c16950f2c80dadaf38..3ad1d96a45da77f3edb63e837d8afc2abc83ff43 100644 (file)
@@ -124,8 +124,8 @@ fn horizontal_trim(lines: Vec<String> ) -> Vec<String> {
     }
 
     // one-line comments lose their prefix
-    static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
-    for prefix in ONLINERS {
+    const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
+    for prefix in ONELINERS {
         if comment.starts_with(*prefix) {
             return (&comment[prefix.len()..]).to_string();
         }
index 2797ef084d9caf36185d985b3bd46ed437f9b755..61a3a5ca82a326e34bd32721a1c36019115fb374 100644 (file)
@@ -425,10 +425,10 @@ pub mod keywords {
         $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
     }
 ) => {
-    static STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
-    static STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
-    static RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
-    static RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
+    const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
+    const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
+    const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
+    const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);
 
     pub mod special_idents {
         use ast;
index 5b3fde8535b3df4dfd1a8a189a722047e0d8e02b..4cef7ed469faf794fa99504b878b34f43525f570 100644 (file)
@@ -159,7 +159,7 @@ pub struct PrintStackElem {
     pbreak: PrintStackBreak
 }
 
-static SIZE_INFINITY: isize = 0xffff;
+const SIZE_INFINITY: isize = 0xffff;
 
 pub fn mk_printer(out: Box<old_io::Writer+'static>, linewidth: usize) -> Printer {
     // Yes 3, it makes the ring buffers big enough to never
index 7cc07e926b267b4b27b97c82e2f7c2adfd47b046..42812e1e597bccdf64514b733bb19852f01b2a1a 100644 (file)
@@ -210,11 +210,11 @@ fn max(&self) -> T {
 
     fn mean(&self) -> T {
         assert!(self.len() != 0);
-        self.sum() / FromPrimitive::from_uint(self.len()).unwrap()
+        self.sum() / FromPrimitive::from_usize(self.len()).unwrap()
     }
 
     fn median(&self) -> T {
-        self.percentile(FromPrimitive::from_uint(50).unwrap())
+        self.percentile(FromPrimitive::from_usize(50).unwrap())
     }
 
     fn var(&self) -> T {
@@ -230,7 +230,7 @@ fn var(&self) -> T {
             // NB: this is _supposed to be_ len-1, not len. If you
             // change it back to len, you will be calculating a
             // population variance, not a sample variance.
-            let denom = FromPrimitive::from_uint(self.len()-1).unwrap();
+            let denom = FromPrimitive::from_usize(self.len()-1).unwrap();
             v/denom
         }
     }
@@ -240,7 +240,7 @@ fn std_dev(&self) -> T {
     }
 
     fn std_dev_pct(&self) -> T {
-        let hundred = FromPrimitive::from_uint(100).unwrap();
+        let hundred = FromPrimitive::from_usize(100).unwrap();
         (self.std_dev() / self.mean()) * hundred
     }
 
@@ -254,7 +254,7 @@ fn median_abs_dev(&self) -> T {
     }
 
     fn median_abs_dev_pct(&self) -> T {
-        let hundred = FromPrimitive::from_uint(100).unwrap();
+        let hundred = FromPrimitive::from_usize(100).unwrap();
         (self.median_abs_dev() / self.median()) * hundred
     }
 
@@ -267,11 +267,11 @@ fn percentile(&self, pct: T) -> T {
     fn quartiles(&self) -> (T,T,T) {
         let mut tmp = self.to_vec();
         local_sort(&mut tmp);
-        let first = FromPrimitive::from_uint(25).unwrap();
+        let first = FromPrimitive::from_usize(25).unwrap();
         let a = percentile_of_sorted(&tmp, first);
-        let secound = FromPrimitive::from_uint(50).unwrap();
+        let secound = FromPrimitive::from_usize(50).unwrap();
         let b = percentile_of_sorted(&tmp, secound);
-        let third = FromPrimitive::from_uint(75).unwrap();
+        let third = FromPrimitive::from_usize(75).unwrap();
         let c = percentile_of_sorted(&tmp, third);
         (a,b,c)
     }
@@ -293,16 +293,16 @@ fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T],
     }
     let zero: T = Float::zero();
     assert!(zero <= pct);
-    let hundred = FromPrimitive::from_uint(100).unwrap();
+    let hundred = FromPrimitive::from_usize(100).unwrap();
     assert!(pct <= hundred);
     if pct == hundred {
         return sorted_samples[sorted_samples.len() - 1];
     }
-    let length = FromPrimitive::from_uint(sorted_samples.len() - 1).unwrap();
+    let length = FromPrimitive::from_usize(sorted_samples.len() - 1).unwrap();
     let rank = (pct / hundred) * length;
     let lrank = rank.floor();
     let d = rank - lrank;
-    let n = lrank.to_uint().unwrap();
+    let n = lrank.to_usize().unwrap();
     let lo = sorted_samples[n];
     let hi = sorted_samples[n+1];
     lo + (hi - lo) * d
@@ -319,7 +319,7 @@ pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {
     let mut tmp = samples.to_vec();
     local_sort(&mut tmp);
     let lo = percentile_of_sorted(&tmp, pct);
-    let hundred: T = FromPrimitive::from_uint(100).unwrap();
+    let hundred: T = FromPrimitive::from_usize(100).unwrap();
     let hi = percentile_of_sorted(&tmp, hundred-pct);
     for samp in samples {
         if *samp > hi {
index 61f447a3dd3b687a836c4f17f308aabd76ab41ca..99a6b6aa1806f56b0883678f6529e47a49c5863a 100644 (file)
@@ -27,7 +27,7 @@ fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
 }
 
 pub mod general_category {
-    pub static C_table: &'static [(char, char)] = &[
+    pub const C_table: &'static [(char, char)] = &[
         ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), ('\u{ad}', '\u{ad}'), ('\u{378}', '\u{379}'),
         ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), ('\u{38d}', '\u{38d}'), ('\u{3a2}',
         '\u{3a2}'), ('\u{530}', '\u{530}'), ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'),
@@ -216,7 +216,7 @@ pub mod general_category {
         ('\u{e01f0}', '\u{10ffff}')
     ];
 
-    pub static Cc_table: &'static [(char, char)] = &[
+    pub const Cc_table: &'static [(char, char)] = &[
         ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}')
     ];
 
@@ -224,7 +224,7 @@ pub fn Cc(c: char) -> bool {
         super::bsearch_range_table(c, Cc_table)
     }
 
-    pub static Cf_table: &'static [(char, char)] = &[
+    pub const Cf_table: &'static [(char, char)] = &[
         ('\u{ad}', '\u{ad}'), ('\u{600}', '\u{605}'), ('\u{61c}', '\u{61c}'), ('\u{6dd}',
         '\u{6dd}'), ('\u{70f}', '\u{70f}'), ('\u{180e}', '\u{180e}'), ('\u{200b}', '\u{200f}'),
         ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), ('\u{2066}', '\u{206f}'), ('\u{feff}',
@@ -233,7 +233,7 @@ pub fn Cc(c: char) -> bool {
         '\u{e007f}')
     ];
 
-    pub static Cn_table: &'static [(char, char)] = &[
+    pub const Cn_table: &'static [(char, char)] = &[
         ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), ('\u{38d}',
         '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), ('\u{557}', '\u{558}'),
         ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), ('\u{58b}', '\u{58c}'), ('\u{590}',
@@ -422,12 +422,12 @@ pub fn Cc(c: char) -> bool {
         ('\u{10fffe}', '\u{10ffff}')
     ];
 
-    pub static Co_table: &'static [(char, char)] = &[
+    pub const Co_table: &'static [(char, char)] = &[
         ('\u{e000}', '\u{e000}'), ('\u{f8ff}', '\u{f8ff}'), ('\u{f0000}', '\u{f0000}'),
         ('\u{ffffd}', '\u{ffffd}'), ('\u{100000}', '\u{100000}'), ('\u{10fffd}', '\u{10fffd}')
     ];
 
-    pub static L_table: &'static [(char, char)] = &[
+    pub const L_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
         ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'),
         ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}',
@@ -593,7 +593,7 @@ pub fn Cc(c: char) -> bool {
         ('\u{2b81d}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
     ];
 
-    pub static LC_table: &'static [(char, char)] = &[
+    pub const LC_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), ('\u{c0}', '\u{d6}'),
         ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c4}', '\u{293}'),
         ('\u{295}', '\u{2af}'), ('\u{370}', '\u{373}'), ('\u{376}', '\u{377}'), ('\u{37b}',
@@ -631,7 +631,7 @@ pub fn Cc(c: char) -> bool {
         ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}')
     ];
 
-    pub static Ll_table: &'static [(char, char)] = &[
+    pub const Ll_table: &'static [(char, char)] = &[
         ('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), ('\u{df}', '\u{f6}'), ('\u{f8}', '\u{ff}'),
         ('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'), ('\u{105}', '\u{105}'), ('\u{107}',
         '\u{107}'), ('\u{109}', '\u{109}'), ('\u{10b}', '\u{10b}'), ('\u{10d}', '\u{10d}'),
@@ -814,7 +814,7 @@ pub fn Cc(c: char) -> bool {
         '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7c9}'), ('\u{1d7cb}', '\u{1d7cb}')
     ];
 
-    pub static Lm_table: &'static [(char, char)] = &[
+    pub const Lm_table: &'static [(char, char)] = &[
         ('\u{2b0}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}',
         '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{374}', '\u{374}'), ('\u{37a}', '\u{37a}'),
         ('\u{559}', '\u{559}'), ('\u{640}', '\u{640}'), ('\u{6e5}', '\u{6e6}'), ('\u{7f4}',
@@ -834,7 +834,7 @@ pub fn Cc(c: char) -> bool {
         '\u{16f9f}')
     ];
 
-    pub static Lo_table: &'static [(char, char)] = &[
+    pub const Lo_table: &'static [(char, char)] = &[
         ('\u{aa}', '\u{aa}'), ('\u{ba}', '\u{ba}'), ('\u{1bb}', '\u{1bb}'), ('\u{1c0}', '\u{1c3}'),
         ('\u{294}', '\u{294}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{620}',
         '\u{63f}'), ('\u{641}', '\u{64a}'), ('\u{66e}', '\u{66f}'), ('\u{671}', '\u{6d3}'),
@@ -964,13 +964,13 @@ pub fn Cc(c: char) -> bool {
         ('\u{2b740}', '\u{2b740}'), ('\u{2b81d}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
     ];
 
-    pub static Lt_table: &'static [(char, char)] = &[
+    pub const Lt_table: &'static [(char, char)] = &[
         ('\u{1c5}', '\u{1c5}'), ('\u{1c8}', '\u{1c8}'), ('\u{1cb}', '\u{1cb}'), ('\u{1f2}',
         '\u{1f2}'), ('\u{1f88}', '\u{1f8f}'), ('\u{1f98}', '\u{1f9f}'), ('\u{1fa8}', '\u{1faf}'),
         ('\u{1fbc}', '\u{1fbc}'), ('\u{1fcc}', '\u{1fcc}'), ('\u{1ffc}', '\u{1ffc}')
     ];
 
-    pub static Lu_table: &'static [(char, char)] = &[
+    pub const Lu_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), ('\u{100}', '\u{100}'),
         ('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), ('\u{106}', '\u{106}'), ('\u{108}',
         '\u{108}'), ('\u{10a}', '\u{10a}'), ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'),
@@ -1153,7 +1153,7 @@ pub fn Cc(c: char) -> bool {
         '\u{1d7ca}')
     ];
 
-    pub static M_table: &'static [(char, char)] = &[
+    pub const M_table: &'static [(char, char)] = &[
         ('\u{300}', '\u{36f}'), ('\u{483}', '\u{489}'), ('\u{591}', '\u{5bd}'), ('\u{5bf}',
         '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'),
         ('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), ('\u{670}', '\u{670}'), ('\u{6d6}',
@@ -1224,7 +1224,7 @@ pub fn Cc(c: char) -> bool {
         ('\u{1e8d0}', '\u{1e8d6}'), ('\u{e0100}', '\u{e01ef}')
     ];
 
-    pub static Mc_table: &'static [(char, char)] = &[
+    pub const Mc_table: &'static [(char, char)] = &[
         ('\u{903}', '\u{903}'), ('\u{93b}', '\u{93b}'), ('\u{93e}', '\u{940}'), ('\u{949}',
         '\u{94c}'), ('\u{94e}', '\u{94f}'), ('\u{982}', '\u{983}'), ('\u{9be}', '\u{9c0}'),
         ('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9cc}'), ('\u{9d7}', '\u{9d7}'), ('\u{a03}',
@@ -1271,12 +1271,12 @@ pub fn Cc(c: char) -> bool {
         ('\u{1d165}', '\u{1d166}'), ('\u{1d16d}', '\u{1d172}')
     ];
 
-    pub static Me_table: &'static [(char, char)] = &[
+    pub const Me_table: &'static [(char, char)] = &[
         ('\u{488}', '\u{489}'), ('\u{1abe}', '\u{1abe}'), ('\u{20dd}', '\u{20e0}'), ('\u{20e2}',
         '\u{20e4}'), ('\u{a670}', '\u{a672}')
     ];
 
-    pub static Mn_table: &'static [(char, char)] = &[
+    pub const Mn_table: &'static [(char, char)] = &[
         ('\u{300}', '\u{36f}'), ('\u{483}', '\u{487}'), ('\u{591}', '\u{5bd}'), ('\u{5bf}',
         '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'),
         ('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), ('\u{670}', '\u{670}'), ('\u{6d6}',
@@ -1355,7 +1355,7 @@ pub fn Cc(c: char) -> bool {
         '\u{1e8d6}'), ('\u{e0100}', '\u{e01ef}')
     ];
 
-    pub static N_table: &'static [(char, char)] = &[
+    pub const N_table: &'static [(char, char)] = &[
         ('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), ('\u{7c0}',
         '\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), ('\u{a66}', '\u{a6f}'),
         ('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), ('\u{be6}', '\u{bef}'), ('\u{c66}',
@@ -1381,7 +1381,7 @@ pub fn N(c: char) -> bool {
         super::bsearch_range_table(c, N_table)
     }
 
-    pub static Nd_table: &'static [(char, char)] = &[
+    pub const Nd_table: &'static [(char, char)] = &[
         ('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), ('\u{7c0}',
         '\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), ('\u{a66}', '\u{a6f}'),
         ('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), ('\u{be6}', '\u{bef}'), ('\u{c66}',
@@ -1399,14 +1399,14 @@ pub fn N(c: char) -> bool {
         ('\u{16a60}', '\u{16a69}'), ('\u{16b50}', '\u{16b59}'), ('\u{1d7ce}', '\u{1d7ff}')
     ];
 
-    pub static Nl_table: &'static [(char, char)] = &[
+    pub const Nl_table: &'static [(char, char)] = &[
         ('\u{16ee}', '\u{16f0}'), ('\u{2160}', '\u{2182}'), ('\u{2185}', '\u{2188}'), ('\u{3007}',
         '\u{3007}'), ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303a}'), ('\u{a6e6}', '\u{a6ef}'),
         ('\u{10140}', '\u{10174}'), ('\u{10341}', '\u{10341}'), ('\u{1034a}', '\u{1034a}'),
         ('\u{103d1}', '\u{103d5}'), ('\u{12400}', '\u{1246e}')
     ];
 
-    pub static No_table: &'static [(char, char)] = &[
+    pub const No_table: &'static [(char, char)] = &[
         ('\u{b2}', '\u{b3}'), ('\u{b9}', '\u{b9}'), ('\u{bc}', '\u{be}'), ('\u{9f4}', '\u{9f9}'),
         ('\u{b72}', '\u{b77}'), ('\u{bf0}', '\u{bf2}'), ('\u{c78}', '\u{c7e}'), ('\u{d70}',
         '\u{d75}'), ('\u{f2a}', '\u{f33}'), ('\u{1369}', '\u{137c}'), ('\u{17f0}', '\u{17f9}'),
@@ -1425,7 +1425,7 @@ pub fn N(c: char) -> bool {
         '\u{1d371}'), ('\u{1e8c7}', '\u{1e8cf}'), ('\u{1f100}', '\u{1f10c}')
     ];
 
-    pub static P_table: &'static [(char, char)] = &[
+    pub const P_table: &'static [(char, char)] = &[
         ('\u{21}', '\u{23}'), ('\u{25}', '\u{2a}'), ('\u{2c}', '\u{2f}'), ('\u{3a}', '\u{3b}'),
         ('\u{3f}', '\u{40}'), ('\u{5b}', '\u{5d}'), ('\u{5f}', '\u{5f}'), ('\u{7b}', '\u{7b}'),
         ('\u{7d}', '\u{7d}'), ('\u{a1}', '\u{a1}'), ('\u{a7}', '\u{a7}'), ('\u{ab}', '\u{ab}'),
@@ -1474,12 +1474,12 @@ pub fn N(c: char) -> bool {
         '\u{1bc9f}')
     ];
 
-    pub static Pc_table: &'static [(char, char)] = &[
+    pub const Pc_table: &'static [(char, char)] = &[
         ('\u{5f}', '\u{5f}'), ('\u{203f}', '\u{2040}'), ('\u{2054}', '\u{2054}'), ('\u{fe33}',
         '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), ('\u{ff3f}', '\u{ff3f}')
     ];
 
-    pub static Pd_table: &'static [(char, char)] = &[
+    pub const Pd_table: &'static [(char, char)] = &[
         ('\u{2d}', '\u{2d}'), ('\u{58a}', '\u{58a}'), ('\u{5be}', '\u{5be}'), ('\u{1400}',
         '\u{1400}'), ('\u{1806}', '\u{1806}'), ('\u{2010}', '\u{2015}'), ('\u{2e17}', '\u{2e17}'),
         ('\u{2e1a}', '\u{2e1a}'), ('\u{2e3a}', '\u{2e3b}'), ('\u{2e40}', '\u{2e40}'), ('\u{301c}',
@@ -1487,7 +1487,7 @@ pub fn N(c: char) -> bool {
         ('\u{fe58}', '\u{fe58}'), ('\u{fe63}', '\u{fe63}'), ('\u{ff0d}', '\u{ff0d}')
     ];
 
-    pub static Pe_table: &'static [(char, char)] = &[
+    pub const Pe_table: &'static [(char, char)] = &[
         ('\u{29}', '\u{29}'), ('\u{5d}', '\u{5d}'), ('\u{7d}', '\u{7d}'), ('\u{f3b}', '\u{f3b}'),
         ('\u{f3d}', '\u{f3d}'), ('\u{169c}', '\u{169c}'), ('\u{2046}', '\u{2046}'), ('\u{207e}',
         '\u{207e}'), ('\u{208e}', '\u{208e}'), ('\u{2309}', '\u{2309}'), ('\u{230b}', '\u{230b}'),
@@ -1511,20 +1511,20 @@ pub fn N(c: char) -> bool {
         '\u{ff60}'), ('\u{ff63}', '\u{ff63}')
     ];
 
-    pub static Pf_table: &'static [(char, char)] = &[
+    pub const Pf_table: &'static [(char, char)] = &[
         ('\u{bb}', '\u{bb}'), ('\u{2019}', '\u{2019}'), ('\u{201d}', '\u{201d}'), ('\u{203a}',
         '\u{203a}'), ('\u{2e03}', '\u{2e03}'), ('\u{2e05}', '\u{2e05}'), ('\u{2e0a}', '\u{2e0a}'),
         ('\u{2e0d}', '\u{2e0d}'), ('\u{2e1d}', '\u{2e1d}'), ('\u{2e21}', '\u{2e21}')
     ];
 
-    pub static Pi_table: &'static [(char, char)] = &[
+    pub const Pi_table: &'static [(char, char)] = &[
         ('\u{ab}', '\u{ab}'), ('\u{2018}', '\u{2018}'), ('\u{201b}', '\u{201c}'), ('\u{201f}',
         '\u{201f}'), ('\u{2039}', '\u{2039}'), ('\u{2e02}', '\u{2e02}'), ('\u{2e04}', '\u{2e04}'),
         ('\u{2e09}', '\u{2e09}'), ('\u{2e0c}', '\u{2e0c}'), ('\u{2e1c}', '\u{2e1c}'), ('\u{2e20}',
         '\u{2e20}')
     ];
 
-    pub static Po_table: &'static [(char, char)] = &[
+    pub const Po_table: &'static [(char, char)] = &[
         ('\u{21}', '\u{23}'), ('\u{25}', '\u{27}'), ('\u{2a}', '\u{2a}'), ('\u{2c}', '\u{2c}'),
         ('\u{2e}', '\u{2f}'), ('\u{3a}', '\u{3b}'), ('\u{3f}', '\u{40}'), ('\u{5c}', '\u{5c}'),
         ('\u{a1}', '\u{a1}'), ('\u{a7}', '\u{a7}'), ('\u{b6}', '\u{b7}'), ('\u{bf}', '\u{bf}'),
@@ -1572,7 +1572,7 @@ pub fn N(c: char) -> bool {
         '\u{1bc9f}')
     ];
 
-    pub static Ps_table: &'static [(char, char)] = &[
+    pub const Ps_table: &'static [(char, char)] = &[
         ('\u{28}', '\u{28}'), ('\u{5b}', '\u{5b}'), ('\u{7b}', '\u{7b}'), ('\u{f3a}', '\u{f3a}'),
         ('\u{f3c}', '\u{f3c}'), ('\u{169b}', '\u{169b}'), ('\u{201a}', '\u{201a}'), ('\u{201e}',
         '\u{201e}'), ('\u{2045}', '\u{2045}'), ('\u{207d}', '\u{207d}'), ('\u{208d}', '\u{208d}'),
@@ -1597,7 +1597,7 @@ pub fn N(c: char) -> bool {
         ('\u{ff62}', '\u{ff62}')
     ];
 
-    pub static S_table: &'static [(char, char)] = &[
+    pub const S_table: &'static [(char, char)] = &[
         ('\u{24}', '\u{24}'), ('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), ('\u{5e}', '\u{5e}'),
         ('\u{60}', '\u{60}'), ('\u{7c}', '\u{7c}'), ('\u{7e}', '\u{7e}'), ('\u{a2}', '\u{a6}'),
         ('\u{a8}', '\u{a9}'), ('\u{ac}', '\u{ac}'), ('\u{ae}', '\u{b1}'), ('\u{b4}', '\u{b4}'),
@@ -1663,7 +1663,7 @@ pub fn N(c: char) -> bool {
         '\u{1f887}'), ('\u{1f890}', '\u{1f8ad}')
     ];
 
-    pub static Sc_table: &'static [(char, char)] = &[
+    pub const Sc_table: &'static [(char, char)] = &[
         ('\u{24}', '\u{24}'), ('\u{a2}', '\u{a5}'), ('\u{58f}', '\u{58f}'), ('\u{60b}', '\u{60b}'),
         ('\u{9f2}', '\u{9f3}'), ('\u{9fb}', '\u{9fb}'), ('\u{af1}', '\u{af1}'), ('\u{bf9}',
         '\u{bf9}'), ('\u{e3f}', '\u{e3f}'), ('\u{17db}', '\u{17db}'), ('\u{20a0}', '\u{20bd}'),
@@ -1671,7 +1671,7 @@ pub fn N(c: char) -> bool {
         '\u{ff04}'), ('\u{ffe0}', '\u{ffe1}'), ('\u{ffe5}', '\u{ffe6}')
     ];
 
-    pub static Sk_table: &'static [(char, char)] = &[
+    pub const Sk_table: &'static [(char, char)] = &[
         ('\u{5e}', '\u{5e}'), ('\u{60}', '\u{60}'), ('\u{a8}', '\u{a8}'), ('\u{af}', '\u{af}'),
         ('\u{b4}', '\u{b4}'), ('\u{b8}', '\u{b8}'), ('\u{2c2}', '\u{2c5}'), ('\u{2d2}', '\u{2df}'),
         ('\u{2e5}', '\u{2eb}'), ('\u{2ed}', '\u{2ed}'), ('\u{2ef}', '\u{2ff}'), ('\u{375}',
@@ -1682,7 +1682,7 @@ pub fn N(c: char) -> bool {
         '\u{ff3e}'), ('\u{ff40}', '\u{ff40}'), ('\u{ffe3}', '\u{ffe3}')
     ];
 
-    pub static Sm_table: &'static [(char, char)] = &[
+    pub const Sm_table: &'static [(char, char)] = &[
         ('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), ('\u{7c}', '\u{7c}'), ('\u{7e}', '\u{7e}'),
         ('\u{ac}', '\u{ac}'), ('\u{b1}', '\u{b1}'), ('\u{d7}', '\u{d7}'), ('\u{f7}', '\u{f7}'),
         ('\u{3f6}', '\u{3f6}'), ('\u{606}', '\u{608}'), ('\u{2044}', '\u{2044}'), ('\u{2052}',
@@ -1704,7 +1704,7 @@ pub fn N(c: char) -> bool {
         '\u{1d7c3}'), ('\u{1eef0}', '\u{1eef1}')
     ];
 
-    pub static So_table: &'static [(char, char)] = &[
+    pub const So_table: &'static [(char, char)] = &[
         ('\u{a6}', '\u{a6}'), ('\u{a9}', '\u{a9}'), ('\u{ae}', '\u{ae}'), ('\u{b0}', '\u{b0}'),
         ('\u{482}', '\u{482}'), ('\u{58d}', '\u{58e}'), ('\u{60e}', '\u{60f}'), ('\u{6de}',
         '\u{6de}'), ('\u{6e9}', '\u{6e9}'), ('\u{6fd}', '\u{6fe}'), ('\u{7f6}', '\u{7f6}'),
@@ -1757,21 +1757,21 @@ pub fn N(c: char) -> bool {
         '\u{1f887}'), ('\u{1f890}', '\u{1f8ad}')
     ];
 
-    pub static Z_table: &'static [(char, char)] = &[
+    pub const Z_table: &'static [(char, char)] = &[
         ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), ('\u{2000}',
         '\u{200a}'), ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'),
         ('\u{3000}', '\u{3000}')
     ];
 
-    pub static Zl_table: &'static [(char, char)] = &[
+    pub const Zl_table: &'static [(char, char)] = &[
         ('\u{2028}', '\u{2028}')
     ];
 
-    pub static Zp_table: &'static [(char, char)] = &[
+    pub const Zp_table: &'static [(char, char)] = &[
         ('\u{2029}', '\u{2029}')
     ];
 
-    pub static Zs_table: &'static [(char, char)] = &[
+    pub const Zs_table: &'static [(char, char)] = &[
         ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), ('\u{2000}',
         '\u{200a}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}')
     ];
@@ -1779,7 +1779,7 @@ pub fn N(c: char) -> bool {
 }
 
 pub mod derived_property {
-    pub static Alphabetic_table: &'static [(char, char)] = &[
+    pub const Alphabetic_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
         ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'),
         ('\u{1bb}', '\u{1bb}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}',
@@ -2057,7 +2057,7 @@ pub fn Alphabetic(c: char) -> bool {
         super::bsearch_range_table(c, Alphabetic_table)
     }
 
-    pub static Default_Ignorable_Code_Point_table: &'static [(char, char)] = &[
+    pub const Default_Ignorable_Code_Point_table: &'static [(char, char)] = &[
         ('\u{ad}', '\u{ad}'), ('\u{34f}', '\u{34f}'), ('\u{61c}', '\u{61c}'), ('\u{115f}',
         '\u{1160}'), ('\u{17b4}', '\u{17b5}'), ('\u{180b}', '\u{180d}'), ('\u{180e}', '\u{180e}'),
         ('\u{200b}', '\u{200f}'), ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), ('\u{2065}',
@@ -2068,7 +2068,7 @@ pub fn Alphabetic(c: char) -> bool {
         '\u{e00ff}'), ('\u{e0100}', '\u{e01ef}'), ('\u{e01f0}', '\u{e0fff}')
     ];
 
-    pub static Lowercase_table: &'static [(char, char)] = &[
+    pub const Lowercase_table: &'static [(char, char)] = &[
         ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'),
         ('\u{df}', '\u{f6}'), ('\u{f8}', '\u{ff}'), ('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'),
         ('\u{105}', '\u{105}'), ('\u{107}', '\u{107}'), ('\u{109}', '\u{109}'), ('\u{10b}',
@@ -2261,7 +2261,7 @@ pub fn Lowercase(c: char) -> bool {
         super::bsearch_range_table(c, Lowercase_table)
     }
 
-    pub static Uppercase_table: &'static [(char, char)] = &[
+    pub const Uppercase_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), ('\u{100}', '\u{100}'),
         ('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), ('\u{106}', '\u{106}'), ('\u{108}',
         '\u{108}'), ('\u{10a}', '\u{10a}'), ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'),
@@ -2449,7 +2449,7 @@ pub fn Uppercase(c: char) -> bool {
         super::bsearch_range_table(c, Uppercase_table)
     }
 
-    pub static XID_Continue_table: &'static [(char, char)] = &[
+    pub const XID_Continue_table: &'static [(char, char)] = &[
         ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'),
         ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{b7}', '\u{b7}'), ('\u{ba}', '\u{ba}'),
         ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bb}', '\u{1bb}'),
@@ -2775,7 +2775,7 @@ pub fn XID_Continue(c: char) -> bool {
         super::bsearch_range_table(c, XID_Continue_table)
     }
 
-    pub static XID_Start_table: &'static [(char, char)] = &[
+    pub const XID_Start_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'),
         ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'),
         ('\u{1bb}', '\u{1bb}'), ('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}',
@@ -2967,7 +2967,7 @@ pub fn XID_Start(c: char) -> bool {
 }
 
 pub mod script {
-    pub static Arabic_table: &'static [(char, char)] = &[
+    pub const Arabic_table: &'static [(char, char)] = &[
         ('\u{600}', '\u{604}'), ('\u{606}', '\u{608}'), ('\u{609}', '\u{60a}'), ('\u{60b}',
         '\u{60b}'), ('\u{60d}', '\u{60d}'), ('\u{60e}', '\u{60f}'), ('\u{610}', '\u{61a}'),
         ('\u{61e}', '\u{61e}'), ('\u{620}', '\u{63f}'), ('\u{641}', '\u{64a}'), ('\u{656}',
@@ -2994,17 +2994,17 @@ pub mod script {
         ('\u{1eef0}', '\u{1eef1}')
     ];
 
-    pub static Armenian_table: &'static [(char, char)] = &[
+    pub const Armenian_table: &'static [(char, char)] = &[
         ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{55a}', '\u{55f}'), ('\u{561}',
         '\u{587}'), ('\u{58a}', '\u{58a}'), ('\u{58d}', '\u{58e}'), ('\u{58f}', '\u{58f}'),
         ('\u{fb13}', '\u{fb17}')
     ];
 
-    pub static Avestan_table: &'static [(char, char)] = &[
+    pub const Avestan_table: &'static [(char, char)] = &[
         ('\u{10b00}', '\u{10b35}'), ('\u{10b39}', '\u{10b3f}')
     ];
 
-    pub static Balinese_table: &'static [(char, char)] = &[
+    pub const Balinese_table: &'static [(char, char)] = &[
         ('\u{1b00}', '\u{1b03}'), ('\u{1b04}', '\u{1b04}'), ('\u{1b05}', '\u{1b33}'), ('\u{1b34}',
         '\u{1b34}'), ('\u{1b35}', '\u{1b35}'), ('\u{1b36}', '\u{1b3a}'), ('\u{1b3b}', '\u{1b3b}'),
         ('\u{1b3c}', '\u{1b3c}'), ('\u{1b3d}', '\u{1b41}'), ('\u{1b42}', '\u{1b42}'), ('\u{1b43}',
@@ -3012,22 +3012,22 @@ pub mod script {
         ('\u{1b61}', '\u{1b6a}'), ('\u{1b6b}', '\u{1b73}'), ('\u{1b74}', '\u{1b7c}')
     ];
 
-    pub static Bamum_table: &'static [(char, char)] = &[
+    pub const Bamum_table: &'static [(char, char)] = &[
         ('\u{a6a0}', '\u{a6e5}'), ('\u{a6e6}', '\u{a6ef}'), ('\u{a6f0}', '\u{a6f1}'), ('\u{a6f2}',
         '\u{a6f7}'), ('\u{16800}', '\u{16a38}')
     ];
 
-    pub static Bassa_Vah_table: &'static [(char, char)] = &[
+    pub const Bassa_Vah_table: &'static [(char, char)] = &[
         ('\u{16ad0}', '\u{16aed}'), ('\u{16af0}', '\u{16af4}'), ('\u{16af5}', '\u{16af5}')
     ];
 
-    pub static Batak_table: &'static [(char, char)] = &[
+    pub const Batak_table: &'static [(char, char)] = &[
         ('\u{1bc0}', '\u{1be5}'), ('\u{1be6}', '\u{1be6}'), ('\u{1be7}', '\u{1be7}'), ('\u{1be8}',
         '\u{1be9}'), ('\u{1bea}', '\u{1bec}'), ('\u{1bed}', '\u{1bed}'), ('\u{1bee}', '\u{1bee}'),
         ('\u{1bef}', '\u{1bf1}'), ('\u{1bf2}', '\u{1bf3}'), ('\u{1bfc}', '\u{1bff}')
     ];
 
-    pub static Bengali_table: &'static [(char, char)] = &[
+    pub const Bengali_table: &'static [(char, char)] = &[
         ('\u{980}', '\u{980}'), ('\u{981}', '\u{981}'), ('\u{982}', '\u{983}'), ('\u{985}',
         '\u{98c}'), ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'),
         ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), ('\u{9bc}', '\u{9bc}'), ('\u{9bd}',
@@ -3038,60 +3038,60 @@ pub mod script {
         '\u{9f9}'), ('\u{9fa}', '\u{9fa}'), ('\u{9fb}', '\u{9fb}')
     ];
 
-    pub static Bopomofo_table: &'static [(char, char)] = &[
+    pub const Bopomofo_table: &'static [(char, char)] = &[
         ('\u{2ea}', '\u{2eb}'), ('\u{3105}', '\u{312d}'), ('\u{31a0}', '\u{31ba}')
     ];
 
-    pub static Brahmi_table: &'static [(char, char)] = &[
+    pub const Brahmi_table: &'static [(char, char)] = &[
         ('\u{11000}', '\u{11000}'), ('\u{11001}', '\u{11001}'), ('\u{11002}', '\u{11002}'),
         ('\u{11003}', '\u{11037}'), ('\u{11038}', '\u{11046}'), ('\u{11047}', '\u{1104d}'),
         ('\u{11052}', '\u{11065}'), ('\u{11066}', '\u{1106f}'), ('\u{1107f}', '\u{1107f}')
     ];
 
-    pub static Braille_table: &'static [(char, char)] = &[
+    pub const Braille_table: &'static [(char, char)] = &[
         ('\u{2800}', '\u{28ff}')
     ];
 
-    pub static Buginese_table: &'static [(char, char)] = &[
+    pub const Buginese_table: &'static [(char, char)] = &[
         ('\u{1a00}', '\u{1a16}'), ('\u{1a17}', '\u{1a18}'), ('\u{1a19}', '\u{1a1a}'), ('\u{1a1b}',
         '\u{1a1b}'), ('\u{1a1e}', '\u{1a1f}')
     ];
 
-    pub static Buhid_table: &'static [(char, char)] = &[
+    pub const Buhid_table: &'static [(char, char)] = &[
         ('\u{1740}', '\u{1751}'), ('\u{1752}', '\u{1753}')
     ];
 
-    pub static Canadian_Aboriginal_table: &'static [(char, char)] = &[
+    pub const Canadian_Aboriginal_table: &'static [(char, char)] = &[
         ('\u{1400}', '\u{1400}'), ('\u{1401}', '\u{166c}'), ('\u{166d}', '\u{166e}'), ('\u{166f}',
         '\u{167f}'), ('\u{18b0}', '\u{18f5}')
     ];
 
-    pub static Carian_table: &'static [(char, char)] = &[
+    pub const Carian_table: &'static [(char, char)] = &[
         ('\u{102a0}', '\u{102d0}')
     ];
 
-    pub static Caucasian_Albanian_table: &'static [(char, char)] = &[
+    pub const Caucasian_Albanian_table: &'static [(char, char)] = &[
         ('\u{10530}', '\u{10563}'), ('\u{1056f}', '\u{1056f}')
     ];
 
-    pub static Chakma_table: &'static [(char, char)] = &[
+    pub const Chakma_table: &'static [(char, char)] = &[
         ('\u{11100}', '\u{11102}'), ('\u{11103}', '\u{11126}'), ('\u{11127}', '\u{1112b}'),
         ('\u{1112c}', '\u{1112c}'), ('\u{1112d}', '\u{11134}'), ('\u{11136}', '\u{1113f}'),
         ('\u{11140}', '\u{11143}')
     ];
 
-    pub static Cham_table: &'static [(char, char)] = &[
+    pub const Cham_table: &'static [(char, char)] = &[
         ('\u{aa00}', '\u{aa28}'), ('\u{aa29}', '\u{aa2e}'), ('\u{aa2f}', '\u{aa30}'), ('\u{aa31}',
         '\u{aa32}'), ('\u{aa33}', '\u{aa34}'), ('\u{aa35}', '\u{aa36}'), ('\u{aa40}', '\u{aa42}'),
         ('\u{aa43}', '\u{aa43}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa4c}', '\u{aa4c}'), ('\u{aa4d}',
         '\u{aa4d}'), ('\u{aa50}', '\u{aa59}'), ('\u{aa5c}', '\u{aa5f}')
     ];
 
-    pub static Cherokee_table: &'static [(char, char)] = &[
+    pub const Cherokee_table: &'static [(char, char)] = &[
         ('\u{13a0}', '\u{13f4}')
     ];
 
-    pub static Common_table: &'static [(char, char)] = &[
+    pub const Common_table: &'static [(char, char)] = &[
         ('\u{0}', '\u{1f}'), ('\u{20}', '\u{20}'), ('\u{21}', '\u{23}'), ('\u{24}', '\u{24}'),
         ('\u{25}', '\u{27}'), ('\u{28}', '\u{28}'), ('\u{29}', '\u{29}'), ('\u{2a}', '\u{2a}'),
         ('\u{2b}', '\u{2b}'), ('\u{2c}', '\u{2c}'), ('\u{2d}', '\u{2d}'), ('\u{2e}', '\u{2f}'),
@@ -3261,22 +3261,22 @@ pub mod script {
         ('\u{1f890}', '\u{1f8ad}'), ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}')
     ];
 
-    pub static Coptic_table: &'static [(char, char)] = &[
+    pub const Coptic_table: &'static [(char, char)] = &[
         ('\u{3e2}', '\u{3ef}'), ('\u{2c80}', '\u{2ce4}'), ('\u{2ce5}', '\u{2cea}'), ('\u{2ceb}',
         '\u{2cee}'), ('\u{2cef}', '\u{2cf1}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2cf9}', '\u{2cfc}'),
         ('\u{2cfd}', '\u{2cfd}'), ('\u{2cfe}', '\u{2cff}')
     ];
 
-    pub static Cuneiform_table: &'static [(char, char)] = &[
+    pub const Cuneiform_table: &'static [(char, char)] = &[
         ('\u{12000}', '\u{12398}'), ('\u{12400}', '\u{1246e}'), ('\u{12470}', '\u{12474}')
     ];
 
-    pub static Cypriot_table: &'static [(char, char)] = &[
+    pub const Cypriot_table: &'static [(char, char)] = &[
         ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', '\u{10835}'),
         ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{1083f}')
     ];
 
-    pub static Cyrillic_table: &'static [(char, char)] = &[
+    pub const Cyrillic_table: &'static [(char, char)] = &[
         ('\u{400}', '\u{481}'), ('\u{482}', '\u{482}'), ('\u{483}', '\u{484}'), ('\u{487}',
         '\u{487}'), ('\u{488}', '\u{489}'), ('\u{48a}', '\u{52f}'), ('\u{1d2b}', '\u{1d2b}'),
         ('\u{1d78}', '\u{1d78}'), ('\u{2de0}', '\u{2dff}'), ('\u{a640}', '\u{a66d}'), ('\u{a66e}',
@@ -3285,11 +3285,11 @@ pub mod script {
         '\u{a69b}'), ('\u{a69c}', '\u{a69d}'), ('\u{a69f}', '\u{a69f}')
     ];
 
-    pub static Deseret_table: &'static [(char, char)] = &[
+    pub const Deseret_table: &'static [(char, char)] = &[
         ('\u{10400}', '\u{1044f}')
     ];
 
-    pub static Devanagari_table: &'static [(char, char)] = &[
+    pub const Devanagari_table: &'static [(char, char)] = &[
         ('\u{900}', '\u{902}'), ('\u{903}', '\u{903}'), ('\u{904}', '\u{939}'), ('\u{93a}',
         '\u{93a}'), ('\u{93b}', '\u{93b}'), ('\u{93c}', '\u{93c}'), ('\u{93d}', '\u{93d}'),
         ('\u{93e}', '\u{940}'), ('\u{941}', '\u{948}'), ('\u{949}', '\u{94c}'), ('\u{94d}',
@@ -3299,21 +3299,21 @@ pub mod script {
         ('\u{a8f2}', '\u{a8f7}'), ('\u{a8f8}', '\u{a8fa}'), ('\u{a8fb}', '\u{a8fb}')
     ];
 
-    pub static Duployan_table: &'static [(char, char)] = &[
+    pub const Duployan_table: &'static [(char, char)] = &[
         ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', '\u{1bc88}'),
         ('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9c}', '\u{1bc9c}'), ('\u{1bc9d}', '\u{1bc9e}'),
         ('\u{1bc9f}', '\u{1bc9f}')
     ];
 
-    pub static Egyptian_Hieroglyphs_table: &'static [(char, char)] = &[
+    pub const Egyptian_Hieroglyphs_table: &'static [(char, char)] = &[
         ('\u{13000}', '\u{1342e}')
     ];
 
-    pub static Elbasan_table: &'static [(char, char)] = &[
+    pub const Elbasan_table: &'static [(char, char)] = &[
         ('\u{10500}', '\u{10527}')
     ];
 
-    pub static Ethiopic_table: &'static [(char, char)] = &[
+    pub const Ethiopic_table: &'static [(char, char)] = &[
         ('\u{1200}', '\u{1248}'), ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}',
         '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'),
         ('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}',
@@ -3326,22 +3326,22 @@ pub mod script {
         '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}')
     ];
 
-    pub static Georgian_table: &'static [(char, char)] = &[
+    pub const Georgian_table: &'static [(char, char)] = &[
         ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), ('\u{10d0}',
         '\u{10fa}'), ('\u{10fc}', '\u{10fc}'), ('\u{10fd}', '\u{10ff}'), ('\u{2d00}', '\u{2d25}'),
         ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}')
     ];
 
-    pub static Glagolitic_table: &'static [(char, char)] = &[
+    pub const Glagolitic_table: &'static [(char, char)] = &[
         ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}')
     ];
 
-    pub static Gothic_table: &'static [(char, char)] = &[
+    pub const Gothic_table: &'static [(char, char)] = &[
         ('\u{10330}', '\u{10340}'), ('\u{10341}', '\u{10341}'), ('\u{10342}', '\u{10349}'),
         ('\u{1034a}', '\u{1034a}')
     ];
 
-    pub static Grantha_table: &'static [(char, char)] = &[
+    pub const Grantha_table: &'static [(char, char)] = &[
         ('\u{11301}', '\u{11301}'), ('\u{11302}', '\u{11303}'), ('\u{11305}', '\u{1130c}'),
         ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'),
         ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133c}', '\u{1133c}'),
@@ -3351,7 +3351,7 @@ pub mod script {
         ('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}')
     ];
 
-    pub static Greek_table: &'static [(char, char)] = &[
+    pub const Greek_table: &'static [(char, char)] = &[
         ('\u{370}', '\u{373}'), ('\u{375}', '\u{375}'), ('\u{376}', '\u{377}'), ('\u{37a}',
         '\u{37a}'), ('\u{37b}', '\u{37d}'), ('\u{37f}', '\u{37f}'), ('\u{384}', '\u{384}'),
         ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}',
@@ -3371,7 +3371,7 @@ pub mod script {
         '\u{1d245}')
     ];
 
-    pub static Gujarati_table: &'static [(char, char)] = &[
+    pub const Gujarati_table: &'static [(char, char)] = &[
         ('\u{a81}', '\u{a82}'), ('\u{a83}', '\u{a83}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}',
         '\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'),
         ('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{abc}'), ('\u{abd}', '\u{abd}'), ('\u{abe}',
@@ -3381,7 +3381,7 @@ pub mod script {
         ('\u{af1}', '\u{af1}')
     ];
 
-    pub static Gurmukhi_table: &'static [(char, char)] = &[
+    pub const Gurmukhi_table: &'static [(char, char)] = &[
         ('\u{a01}', '\u{a02}'), ('\u{a03}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}',
         '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'),
         ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), ('\u{a3e}',
@@ -3390,7 +3390,7 @@ pub mod script {
         '\u{a6f}'), ('\u{a70}', '\u{a71}'), ('\u{a72}', '\u{a74}'), ('\u{a75}', '\u{a75}')
     ];
 
-    pub static Han_table: &'static [(char, char)] = &[
+    pub const Han_table: &'static [(char, char)] = &[
         ('\u{2e80}', '\u{2e99}'), ('\u{2e9b}', '\u{2ef3}'), ('\u{2f00}', '\u{2fd5}'), ('\u{3005}',
         '\u{3005}'), ('\u{3007}', '\u{3007}'), ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303a}'),
         ('\u{303b}', '\u{303b}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fcc}'), ('\u{f900}',
@@ -3398,18 +3398,18 @@ pub mod script {
         '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2f800}', '\u{2fa1d}')
     ];
 
-    pub static Hangul_table: &'static [(char, char)] = &[
+    pub const Hangul_table: &'static [(char, char)] = &[
         ('\u{1100}', '\u{11ff}'), ('\u{302e}', '\u{302f}'), ('\u{3131}', '\u{318e}'), ('\u{3200}',
         '\u{321e}'), ('\u{3260}', '\u{327e}'), ('\u{a960}', '\u{a97c}'), ('\u{ac00}', '\u{d7a3}'),
         ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}',
         '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}')
     ];
 
-    pub static Hanunoo_table: &'static [(char, char)] = &[
+    pub const Hanunoo_table: &'static [(char, char)] = &[
         ('\u{1720}', '\u{1731}'), ('\u{1732}', '\u{1734}')
     ];
 
-    pub static Hebrew_table: &'static [(char, char)] = &[
+    pub const Hebrew_table: &'static [(char, char)] = &[
         ('\u{591}', '\u{5bd}'), ('\u{5be}', '\u{5be}'), ('\u{5bf}', '\u{5bf}'), ('\u{5c0}',
         '\u{5c0}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c3}', '\u{5c3}'), ('\u{5c4}', '\u{5c5}'),
         ('\u{5c6}', '\u{5c6}'), ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}',
@@ -3419,16 +3419,16 @@ pub mod script {
         ('\u{fb46}', '\u{fb4f}')
     ];
 
-    pub static Hiragana_table: &'static [(char, char)] = &[
+    pub const Hiragana_table: &'static [(char, char)] = &[
         ('\u{3041}', '\u{3096}'), ('\u{309d}', '\u{309e}'), ('\u{309f}', '\u{309f}'), ('\u{1b001}',
         '\u{1b001}'), ('\u{1f200}', '\u{1f200}')
     ];
 
-    pub static Imperial_Aramaic_table: &'static [(char, char)] = &[
+    pub const Imperial_Aramaic_table: &'static [(char, char)] = &[
         ('\u{10840}', '\u{10855}'), ('\u{10857}', '\u{10857}'), ('\u{10858}', '\u{1085f}')
     ];
 
-    pub static Inherited_table: &'static [(char, char)] = &[
+    pub const Inherited_table: &'static [(char, char)] = &[
         ('\u{300}', '\u{36f}'), ('\u{485}', '\u{486}'), ('\u{64b}', '\u{655}'), ('\u{670}',
         '\u{670}'), ('\u{951}', '\u{952}'), ('\u{1ab0}', '\u{1abd}'), ('\u{1abe}', '\u{1abe}'),
         ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1ce0}'), ('\u{1ce2}', '\u{1ce8}'), ('\u{1ced}',
@@ -3441,29 +3441,29 @@ pub mod script {
         '\u{1d1ad}'), ('\u{e0100}', '\u{e01ef}')
     ];
 
-    pub static Inscriptional_Pahlavi_table: &'static [(char, char)] = &[
+    pub const Inscriptional_Pahlavi_table: &'static [(char, char)] = &[
         ('\u{10b60}', '\u{10b72}'), ('\u{10b78}', '\u{10b7f}')
     ];
 
-    pub static Inscriptional_Parthian_table: &'static [(char, char)] = &[
+    pub const Inscriptional_Parthian_table: &'static [(char, char)] = &[
         ('\u{10b40}', '\u{10b55}'), ('\u{10b58}', '\u{10b5f}')
     ];
 
-    pub static Javanese_table: &'static [(char, char)] = &[
+    pub const Javanese_table: &'static [(char, char)] = &[
         ('\u{a980}', '\u{a982}'), ('\u{a983}', '\u{a983}'), ('\u{a984}', '\u{a9b2}'), ('\u{a9b3}',
         '\u{a9b3}'), ('\u{a9b4}', '\u{a9b5}'), ('\u{a9b6}', '\u{a9b9}'), ('\u{a9ba}', '\u{a9bb}'),
         ('\u{a9bc}', '\u{a9bc}'), ('\u{a9bd}', '\u{a9c0}'), ('\u{a9c1}', '\u{a9cd}'), ('\u{a9d0}',
         '\u{a9d9}'), ('\u{a9de}', '\u{a9df}')
     ];
 
-    pub static Kaithi_table: &'static [(char, char)] = &[
+    pub const Kaithi_table: &'static [(char, char)] = &[
         ('\u{11080}', '\u{11081}'), ('\u{11082}', '\u{11082}'), ('\u{11083}', '\u{110af}'),
         ('\u{110b0}', '\u{110b2}'), ('\u{110b3}', '\u{110b6}'), ('\u{110b7}', '\u{110b8}'),
         ('\u{110b9}', '\u{110ba}'), ('\u{110bb}', '\u{110bc}'), ('\u{110bd}', '\u{110bd}'),
         ('\u{110be}', '\u{110c1}')
     ];
 
-    pub static Kannada_table: &'static [(char, char)] = &[
+    pub const Kannada_table: &'static [(char, char)] = &[
         ('\u{c81}', '\u{c81}'), ('\u{c82}', '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}',
         '\u{c90}'), ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'),
         ('\u{cbc}', '\u{cbc}'), ('\u{cbd}', '\u{cbd}'), ('\u{cbe}', '\u{cbe}'), ('\u{cbf}',
@@ -3473,25 +3473,25 @@ pub mod script {
         ('\u{cf1}', '\u{cf2}')
     ];
 
-    pub static Katakana_table: &'static [(char, char)] = &[
+    pub const Katakana_table: &'static [(char, char)] = &[
         ('\u{30a1}', '\u{30fa}'), ('\u{30fd}', '\u{30fe}'), ('\u{30ff}', '\u{30ff}'), ('\u{31f0}',
         '\u{31ff}'), ('\u{32d0}', '\u{32fe}'), ('\u{3300}', '\u{3357}'), ('\u{ff66}', '\u{ff6f}'),
         ('\u{ff71}', '\u{ff9d}'), ('\u{1b000}', '\u{1b000}')
     ];
 
-    pub static Kayah_Li_table: &'static [(char, char)] = &[
+    pub const Kayah_Li_table: &'static [(char, char)] = &[
         ('\u{a900}', '\u{a909}'), ('\u{a90a}', '\u{a925}'), ('\u{a926}', '\u{a92d}'), ('\u{a92f}',
         '\u{a92f}')
     ];
 
-    pub static Kharoshthi_table: &'static [(char, char)] = &[
+    pub const Kharoshthi_table: &'static [(char, char)] = &[
         ('\u{10a00}', '\u{10a00}'), ('\u{10a01}', '\u{10a03}'), ('\u{10a05}', '\u{10a06}'),
         ('\u{10a0c}', '\u{10a0f}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'),
         ('\u{10a19}', '\u{10a33}'), ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'),
         ('\u{10a40}', '\u{10a47}'), ('\u{10a50}', '\u{10a58}')
     ];
 
-    pub static Khmer_table: &'static [(char, char)] = &[
+    pub const Khmer_table: &'static [(char, char)] = &[
         ('\u{1780}', '\u{17b3}'), ('\u{17b4}', '\u{17b5}'), ('\u{17b6}', '\u{17b6}'), ('\u{17b7}',
         '\u{17bd}'), ('\u{17be}', '\u{17c5}'), ('\u{17c6}', '\u{17c6}'), ('\u{17c7}', '\u{17c8}'),
         ('\u{17c9}', '\u{17d3}'), ('\u{17d4}', '\u{17d6}'), ('\u{17d7}', '\u{17d7}'), ('\u{17d8}',
@@ -3499,18 +3499,18 @@ pub mod script {
         ('\u{17e0}', '\u{17e9}'), ('\u{17f0}', '\u{17f9}'), ('\u{19e0}', '\u{19ff}')
     ];
 
-    pub static Khojki_table: &'static [(char, char)] = &[
+    pub const Khojki_table: &'static [(char, char)] = &[
         ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), ('\u{1122c}', '\u{1122e}'),
         ('\u{1122f}', '\u{11231}'), ('\u{11232}', '\u{11233}'), ('\u{11234}', '\u{11234}'),
         ('\u{11235}', '\u{11235}'), ('\u{11236}', '\u{11237}'), ('\u{11238}', '\u{1123d}')
     ];
 
-    pub static Khudawadi_table: &'static [(char, char)] = &[
+    pub const Khudawadi_table: &'static [(char, char)] = &[
         ('\u{112b0}', '\u{112de}'), ('\u{112df}', '\u{112df}'), ('\u{112e0}', '\u{112e2}'),
         ('\u{112e3}', '\u{112ea}'), ('\u{112f0}', '\u{112f9}')
     ];
 
-    pub static Lao_table: &'static [(char, char)] = &[
+    pub const Lao_table: &'static [(char, char)] = &[
         ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}',
         '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'),
         ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}',
@@ -3520,7 +3520,7 @@ pub mod script {
         ('\u{edc}', '\u{edf}')
     ];
 
-    pub static Latin_table: &'static [(char, char)] = &[
+    pub const Latin_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{ba}', '\u{ba}'),
         ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), ('\u{1bb}', '\u{1bb}'),
         ('\u{1bc}', '\u{1bf}'), ('\u{1c0}', '\u{1c3}'), ('\u{1c4}', '\u{293}'), ('\u{294}',
@@ -3537,47 +3537,47 @@ pub mod script {
         '\u{ab64}'), ('\u{fb00}', '\u{fb06}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff41}', '\u{ff5a}')
     ];
 
-    pub static Lepcha_table: &'static [(char, char)] = &[
+    pub const Lepcha_table: &'static [(char, char)] = &[
         ('\u{1c00}', '\u{1c23}'), ('\u{1c24}', '\u{1c2b}'), ('\u{1c2c}', '\u{1c33}'), ('\u{1c34}',
         '\u{1c35}'), ('\u{1c36}', '\u{1c37}'), ('\u{1c3b}', '\u{1c3f}'), ('\u{1c40}', '\u{1c49}'),
         ('\u{1c4d}', '\u{1c4f}')
     ];
 
-    pub static Limbu_table: &'static [(char, char)] = &[
+    pub const Limbu_table: &'static [(char, char)] = &[
         ('\u{1900}', '\u{191e}'), ('\u{1920}', '\u{1922}'), ('\u{1923}', '\u{1926}'), ('\u{1927}',
         '\u{1928}'), ('\u{1929}', '\u{192b}'), ('\u{1930}', '\u{1931}'), ('\u{1932}', '\u{1932}'),
         ('\u{1933}', '\u{1938}'), ('\u{1939}', '\u{193b}'), ('\u{1940}', '\u{1940}'), ('\u{1944}',
         '\u{1945}'), ('\u{1946}', '\u{194f}')
     ];
 
-    pub static Linear_A_table: &'static [(char, char)] = &[
+    pub const Linear_A_table: &'static [(char, char)] = &[
         ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', '\u{10767}')
     ];
 
-    pub static Linear_B_table: &'static [(char, char)] = &[
+    pub const Linear_B_table: &'static [(char, char)] = &[
         ('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'),
         ('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'),
         ('\u{10080}', '\u{100fa}')
     ];
 
-    pub static Lisu_table: &'static [(char, char)] = &[
+    pub const Lisu_table: &'static [(char, char)] = &[
         ('\u{a4d0}', '\u{a4f7}'), ('\u{a4f8}', '\u{a4fd}'), ('\u{a4fe}', '\u{a4ff}')
     ];
 
-    pub static Lycian_table: &'static [(char, char)] = &[
+    pub const Lycian_table: &'static [(char, char)] = &[
         ('\u{10280}', '\u{1029c}')
     ];
 
-    pub static Lydian_table: &'static [(char, char)] = &[
+    pub const Lydian_table: &'static [(char, char)] = &[
         ('\u{10920}', '\u{10939}'), ('\u{1093f}', '\u{1093f}')
     ];
 
-    pub static Mahajani_table: &'static [(char, char)] = &[
+    pub const Mahajani_table: &'static [(char, char)] = &[
         ('\u{11150}', '\u{11172}'), ('\u{11173}', '\u{11173}'), ('\u{11174}', '\u{11175}'),
         ('\u{11176}', '\u{11176}')
     ];
 
-    pub static Malayalam_table: &'static [(char, char)] = &[
+    pub const Malayalam_table: &'static [(char, char)] = &[
         ('\u{d01}', '\u{d01}'), ('\u{d02}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}',
         '\u{d10}'), ('\u{d12}', '\u{d3a}'), ('\u{d3d}', '\u{d3d}'), ('\u{d3e}', '\u{d40}'),
         ('\u{d41}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4c}'), ('\u{d4d}',
@@ -3586,16 +3586,16 @@ pub mod script {
         '\u{d79}'), ('\u{d7a}', '\u{d7f}')
     ];
 
-    pub static Mandaic_table: &'static [(char, char)] = &[
+    pub const Mandaic_table: &'static [(char, char)] = &[
         ('\u{840}', '\u{858}'), ('\u{859}', '\u{85b}'), ('\u{85e}', '\u{85e}')
     ];
 
-    pub static Manichaean_table: &'static [(char, char)] = &[
+    pub const Manichaean_table: &'static [(char, char)] = &[
         ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac8}', '\u{10ac8}'), ('\u{10ac9}', '\u{10ae4}'),
         ('\u{10ae5}', '\u{10ae6}'), ('\u{10aeb}', '\u{10aef}'), ('\u{10af0}', '\u{10af6}')
     ];
 
-    pub static Meetei_Mayek_table: &'static [(char, char)] = &[
+    pub const Meetei_Mayek_table: &'static [(char, char)] = &[
         ('\u{aae0}', '\u{aaea}'), ('\u{aaeb}', '\u{aaeb}'), ('\u{aaec}', '\u{aaed}'), ('\u{aaee}',
         '\u{aaef}'), ('\u{aaf0}', '\u{aaf1}'), ('\u{aaf2}', '\u{aaf2}'), ('\u{aaf3}', '\u{aaf4}'),
         ('\u{aaf5}', '\u{aaf5}'), ('\u{aaf6}', '\u{aaf6}'), ('\u{abc0}', '\u{abe2}'), ('\u{abe3}',
@@ -3604,42 +3604,42 @@ pub mod script {
         '\u{abed}'), ('\u{abf0}', '\u{abf9}')
     ];
 
-    pub static Mende_Kikakui_table: &'static [(char, char)] = &[
+    pub const Mende_Kikakui_table: &'static [(char, char)] = &[
         ('\u{1e800}', '\u{1e8c4}'), ('\u{1e8c7}', '\u{1e8cf}'), ('\u{1e8d0}', '\u{1e8d6}')
     ];
 
-    pub static Meroitic_Cursive_table: &'static [(char, char)] = &[
+    pub const Meroitic_Cursive_table: &'static [(char, char)] = &[
         ('\u{109a0}', '\u{109b7}'), ('\u{109be}', '\u{109bf}')
     ];
 
-    pub static Meroitic_Hieroglyphs_table: &'static [(char, char)] = &[
+    pub const Meroitic_Hieroglyphs_table: &'static [(char, char)] = &[
         ('\u{10980}', '\u{1099f}')
     ];
 
-    pub static Miao_table: &'static [(char, char)] = &[
+    pub const Miao_table: &'static [(char, char)] = &[
         ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f51}', '\u{16f7e}'),
         ('\u{16f8f}', '\u{16f92}'), ('\u{16f93}', '\u{16f9f}')
     ];
 
-    pub static Modi_table: &'static [(char, char)] = &[
+    pub const Modi_table: &'static [(char, char)] = &[
         ('\u{11600}', '\u{1162f}'), ('\u{11630}', '\u{11632}'), ('\u{11633}', '\u{1163a}'),
         ('\u{1163b}', '\u{1163c}'), ('\u{1163d}', '\u{1163d}'), ('\u{1163e}', '\u{1163e}'),
         ('\u{1163f}', '\u{11640}'), ('\u{11641}', '\u{11643}'), ('\u{11644}', '\u{11644}'),
         ('\u{11650}', '\u{11659}')
     ];
 
-    pub static Mongolian_table: &'static [(char, char)] = &[
+    pub const Mongolian_table: &'static [(char, char)] = &[
         ('\u{1800}', '\u{1801}'), ('\u{1804}', '\u{1804}'), ('\u{1806}', '\u{1806}'), ('\u{1807}',
         '\u{180a}'), ('\u{180b}', '\u{180d}'), ('\u{180e}', '\u{180e}'), ('\u{1810}', '\u{1819}'),
         ('\u{1820}', '\u{1842}'), ('\u{1843}', '\u{1843}'), ('\u{1844}', '\u{1877}'), ('\u{1880}',
         '\u{18a8}'), ('\u{18a9}', '\u{18a9}'), ('\u{18aa}', '\u{18aa}')
     ];
 
-    pub static Mro_table: &'static [(char, char)] = &[
+    pub const Mro_table: &'static [(char, char)] = &[
         ('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16a6e}', '\u{16a6f}')
     ];
 
-    pub static Myanmar_table: &'static [(char, char)] = &[
+    pub const Myanmar_table: &'static [(char, char)] = &[
         ('\u{1000}', '\u{102a}'), ('\u{102b}', '\u{102c}'), ('\u{102d}', '\u{1030}'), ('\u{1031}',
         '\u{1031}'), ('\u{1032}', '\u{1037}'), ('\u{1038}', '\u{1038}'), ('\u{1039}', '\u{103a}'),
         ('\u{103b}', '\u{103c}'), ('\u{103d}', '\u{103e}'), ('\u{103f}', '\u{103f}'), ('\u{1040}',
@@ -3657,56 +3657,56 @@ pub mod script {
         ('\u{aa7e}', '\u{aa7f}')
     ];
 
-    pub static Nabataean_table: &'static [(char, char)] = &[
+    pub const Nabataean_table: &'static [(char, char)] = &[
         ('\u{10880}', '\u{1089e}'), ('\u{108a7}', '\u{108af}')
     ];
 
-    pub static New_Tai_Lue_table: &'static [(char, char)] = &[
+    pub const New_Tai_Lue_table: &'static [(char, char)] = &[
         ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c0}'), ('\u{19c1}', '\u{19c7}'), ('\u{19c8}',
         '\u{19c9}'), ('\u{19d0}', '\u{19d9}'), ('\u{19da}', '\u{19da}'), ('\u{19de}', '\u{19df}')
     ];
 
-    pub static Nko_table: &'static [(char, char)] = &[
+    pub const Nko_table: &'static [(char, char)] = &[
         ('\u{7c0}', '\u{7c9}'), ('\u{7ca}', '\u{7ea}'), ('\u{7eb}', '\u{7f3}'), ('\u{7f4}',
         '\u{7f5}'), ('\u{7f6}', '\u{7f6}'), ('\u{7f7}', '\u{7f9}'), ('\u{7fa}', '\u{7fa}')
     ];
 
-    pub static Ogham_table: &'static [(char, char)] = &[
+    pub const Ogham_table: &'static [(char, char)] = &[
         ('\u{1680}', '\u{1680}'), ('\u{1681}', '\u{169a}'), ('\u{169b}', '\u{169b}'), ('\u{169c}',
         '\u{169c}')
     ];
 
-    pub static Ol_Chiki_table: &'static [(char, char)] = &[
+    pub const Ol_Chiki_table: &'static [(char, char)] = &[
         ('\u{1c50}', '\u{1c59}'), ('\u{1c5a}', '\u{1c77}'), ('\u{1c78}', '\u{1c7d}'), ('\u{1c7e}',
         '\u{1c7f}')
     ];
 
-    pub static Old_Italic_table: &'static [(char, char)] = &[
+    pub const Old_Italic_table: &'static [(char, char)] = &[
         ('\u{10300}', '\u{1031f}'), ('\u{10320}', '\u{10323}')
     ];
 
-    pub static Old_North_Arabian_table: &'static [(char, char)] = &[
+    pub const Old_North_Arabian_table: &'static [(char, char)] = &[
         ('\u{10a80}', '\u{10a9c}'), ('\u{10a9d}', '\u{10a9f}')
     ];
 
-    pub static Old_Permic_table: &'static [(char, char)] = &[
+    pub const Old_Permic_table: &'static [(char, char)] = &[
         ('\u{10350}', '\u{10375}'), ('\u{10376}', '\u{1037a}')
     ];
 
-    pub static Old_Persian_table: &'static [(char, char)] = &[
+    pub const Old_Persian_table: &'static [(char, char)] = &[
         ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d0}', '\u{103d0}'),
         ('\u{103d1}', '\u{103d5}')
     ];
 
-    pub static Old_South_Arabian_table: &'static [(char, char)] = &[
+    pub const Old_South_Arabian_table: &'static [(char, char)] = &[
         ('\u{10a60}', '\u{10a7c}'), ('\u{10a7d}', '\u{10a7e}'), ('\u{10a7f}', '\u{10a7f}')
     ];
 
-    pub static Old_Turkic_table: &'static [(char, char)] = &[
+    pub const Old_Turkic_table: &'static [(char, char)] = &[
         ('\u{10c00}', '\u{10c48}')
     ];
 
-    pub static Oriya_table: &'static [(char, char)] = &[
+    pub const Oriya_table: &'static [(char, char)] = &[
         ('\u{b01}', '\u{b01}'), ('\u{b02}', '\u{b03}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}',
         '\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'),
         ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b3c}'), ('\u{b3d}', '\u{b3d}'), ('\u{b3e}',
@@ -3717,75 +3717,75 @@ pub mod script {
         '\u{b71}'), ('\u{b72}', '\u{b77}')
     ];
 
-    pub static Osmanya_table: &'static [(char, char)] = &[
+    pub const Osmanya_table: &'static [(char, char)] = &[
         ('\u{10480}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}')
     ];
 
-    pub static Pahawh_Hmong_table: &'static [(char, char)] = &[
+    pub const Pahawh_Hmong_table: &'static [(char, char)] = &[
         ('\u{16b00}', '\u{16b2f}'), ('\u{16b30}', '\u{16b36}'), ('\u{16b37}', '\u{16b3b}'),
         ('\u{16b3c}', '\u{16b3f}'), ('\u{16b40}', '\u{16b43}'), ('\u{16b44}', '\u{16b44}'),
         ('\u{16b45}', '\u{16b45}'), ('\u{16b50}', '\u{16b59}'), ('\u{16b5b}', '\u{16b61}'),
         ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}')
     ];
 
-    pub static Palmyrene_table: &'static [(char, char)] = &[
+    pub const Palmyrene_table: &'static [(char, char)] = &[
         ('\u{10860}', '\u{10876}'), ('\u{10877}', '\u{10878}'), ('\u{10879}', '\u{1087f}')
     ];
 
-    pub static Pau_Cin_Hau_table: &'static [(char, char)] = &[
+    pub const Pau_Cin_Hau_table: &'static [(char, char)] = &[
         ('\u{11ac0}', '\u{11af8}')
     ];
 
-    pub static Phags_Pa_table: &'static [(char, char)] = &[
+    pub const Phags_Pa_table: &'static [(char, char)] = &[
         ('\u{a840}', '\u{a873}'), ('\u{a874}', '\u{a877}')
     ];
 
-    pub static Phoenician_table: &'static [(char, char)] = &[
+    pub const Phoenician_table: &'static [(char, char)] = &[
         ('\u{10900}', '\u{10915}'), ('\u{10916}', '\u{1091b}'), ('\u{1091f}', '\u{1091f}')
     ];
 
-    pub static Psalter_Pahlavi_table: &'static [(char, char)] = &[
+    pub const Psalter_Pahlavi_table: &'static [(char, char)] = &[
         ('\u{10b80}', '\u{10b91}'), ('\u{10b99}', '\u{10b9c}'), ('\u{10ba9}', '\u{10baf}')
     ];
 
-    pub static Rejang_table: &'static [(char, char)] = &[
+    pub const Rejang_table: &'static [(char, char)] = &[
         ('\u{a930}', '\u{a946}'), ('\u{a947}', '\u{a951}'), ('\u{a952}', '\u{a953}'), ('\u{a95f}',
         '\u{a95f}')
     ];
 
-    pub static Runic_table: &'static [(char, char)] = &[
+    pub const Runic_table: &'static [(char, char)] = &[
         ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f0}'), ('\u{16f1}', '\u{16f8}')
     ];
 
-    pub static Samaritan_table: &'static [(char, char)] = &[
+    pub const Samaritan_table: &'static [(char, char)] = &[
         ('\u{800}', '\u{815}'), ('\u{816}', '\u{819}'), ('\u{81a}', '\u{81a}'), ('\u{81b}',
         '\u{823}'), ('\u{824}', '\u{824}'), ('\u{825}', '\u{827}'), ('\u{828}', '\u{828}'),
         ('\u{829}', '\u{82d}'), ('\u{830}', '\u{83e}')
     ];
 
-    pub static Saurashtra_table: &'static [(char, char)] = &[
+    pub const Saurashtra_table: &'static [(char, char)] = &[
         ('\u{a880}', '\u{a881}'), ('\u{a882}', '\u{a8b3}'), ('\u{a8b4}', '\u{a8c3}'), ('\u{a8c4}',
         '\u{a8c4}'), ('\u{a8ce}', '\u{a8cf}'), ('\u{a8d0}', '\u{a8d9}')
     ];
 
-    pub static Sharada_table: &'static [(char, char)] = &[
+    pub const Sharada_table: &'static [(char, char)] = &[
         ('\u{11180}', '\u{11181}'), ('\u{11182}', '\u{11182}'), ('\u{11183}', '\u{111b2}'),
         ('\u{111b3}', '\u{111b5}'), ('\u{111b6}', '\u{111be}'), ('\u{111bf}', '\u{111c0}'),
         ('\u{111c1}', '\u{111c4}'), ('\u{111c5}', '\u{111c8}'), ('\u{111cd}', '\u{111cd}'),
         ('\u{111d0}', '\u{111d9}'), ('\u{111da}', '\u{111da}')
     ];
 
-    pub static Shavian_table: &'static [(char, char)] = &[
+    pub const Shavian_table: &'static [(char, char)] = &[
         ('\u{10450}', '\u{1047f}')
     ];
 
-    pub static Siddham_table: &'static [(char, char)] = &[
+    pub const Siddham_table: &'static [(char, char)] = &[
         ('\u{11580}', '\u{115ae}'), ('\u{115af}', '\u{115b1}'), ('\u{115b2}', '\u{115b5}'),
         ('\u{115b8}', '\u{115bb}'), ('\u{115bc}', '\u{115bd}'), ('\u{115be}', '\u{115be}'),
         ('\u{115bf}', '\u{115c0}'), ('\u{115c1}', '\u{115c9}')
     ];
 
-    pub static Sinhala_table: &'static [(char, char)] = &[
+    pub const Sinhala_table: &'static [(char, char)] = &[
         ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}',
         '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'),
         ('\u{dcf}', '\u{dd1}'), ('\u{dd2}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}',
@@ -3793,42 +3793,42 @@ pub mod script {
         ('\u{111e1}', '\u{111f4}')
     ];
 
-    pub static Sora_Sompeng_table: &'static [(char, char)] = &[
+    pub const Sora_Sompeng_table: &'static [(char, char)] = &[
         ('\u{110d0}', '\u{110e8}'), ('\u{110f0}', '\u{110f9}')
     ];
 
-    pub static Sundanese_table: &'static [(char, char)] = &[
+    pub const Sundanese_table: &'static [(char, char)] = &[
         ('\u{1b80}', '\u{1b81}'), ('\u{1b82}', '\u{1b82}'), ('\u{1b83}', '\u{1ba0}'), ('\u{1ba1}',
         '\u{1ba1}'), ('\u{1ba2}', '\u{1ba5}'), ('\u{1ba6}', '\u{1ba7}'), ('\u{1ba8}', '\u{1ba9}'),
         ('\u{1baa}', '\u{1baa}'), ('\u{1bab}', '\u{1bad}'), ('\u{1bae}', '\u{1baf}'), ('\u{1bb0}',
         '\u{1bb9}'), ('\u{1bba}', '\u{1bbf}'), ('\u{1cc0}', '\u{1cc7}')
     ];
 
-    pub static Syloti_Nagri_table: &'static [(char, char)] = &[
+    pub const Syloti_Nagri_table: &'static [(char, char)] = &[
         ('\u{a800}', '\u{a801}'), ('\u{a802}', '\u{a802}'), ('\u{a803}', '\u{a805}'), ('\u{a806}',
         '\u{a806}'), ('\u{a807}', '\u{a80a}'), ('\u{a80b}', '\u{a80b}'), ('\u{a80c}', '\u{a822}'),
         ('\u{a823}', '\u{a824}'), ('\u{a825}', '\u{a826}'), ('\u{a827}', '\u{a827}'), ('\u{a828}',
         '\u{a82b}')
     ];
 
-    pub static Syriac_table: &'static [(char, char)] = &[
+    pub const Syriac_table: &'static [(char, char)] = &[
         ('\u{700}', '\u{70d}'), ('\u{70f}', '\u{70f}'), ('\u{710}', '\u{710}'), ('\u{711}',
         '\u{711}'), ('\u{712}', '\u{72f}'), ('\u{730}', '\u{74a}'), ('\u{74d}', '\u{74f}')
     ];
 
-    pub static Tagalog_table: &'static [(char, char)] = &[
+    pub const Tagalog_table: &'static [(char, char)] = &[
         ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), ('\u{1712}', '\u{1714}')
     ];
 
-    pub static Tagbanwa_table: &'static [(char, char)] = &[
+    pub const Tagbanwa_table: &'static [(char, char)] = &[
         ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1772}', '\u{1773}')
     ];
 
-    pub static Tai_Le_table: &'static [(char, char)] = &[
+    pub const Tai_Le_table: &'static [(char, char)] = &[
         ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}')
     ];
 
-    pub static Tai_Tham_table: &'static [(char, char)] = &[
+    pub const Tai_Tham_table: &'static [(char, char)] = &[
         ('\u{1a20}', '\u{1a54}'), ('\u{1a55}', '\u{1a55}'), ('\u{1a56}', '\u{1a56}'), ('\u{1a57}',
         '\u{1a57}'), ('\u{1a58}', '\u{1a5e}'), ('\u{1a60}', '\u{1a60}'), ('\u{1a61}', '\u{1a61}'),
         ('\u{1a62}', '\u{1a62}'), ('\u{1a63}', '\u{1a64}'), ('\u{1a65}', '\u{1a6c}'), ('\u{1a6d}',
@@ -3837,20 +3837,20 @@ pub mod script {
         '\u{1aad}')
     ];
 
-    pub static Tai_Viet_table: &'static [(char, char)] = &[
+    pub const Tai_Viet_table: &'static [(char, char)] = &[
         ('\u{aa80}', '\u{aaaf}'), ('\u{aab0}', '\u{aab0}'), ('\u{aab1}', '\u{aab1}'), ('\u{aab2}',
         '\u{aab4}'), ('\u{aab5}', '\u{aab6}'), ('\u{aab7}', '\u{aab8}'), ('\u{aab9}', '\u{aabd}'),
         ('\u{aabe}', '\u{aabf}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac1}', '\u{aac1}'), ('\u{aac2}',
         '\u{aac2}'), ('\u{aadb}', '\u{aadc}'), ('\u{aadd}', '\u{aadd}'), ('\u{aade}', '\u{aadf}')
     ];
 
-    pub static Takri_table: &'static [(char, char)] = &[
+    pub const Takri_table: &'static [(char, char)] = &[
         ('\u{11680}', '\u{116aa}'), ('\u{116ab}', '\u{116ab}'), ('\u{116ac}', '\u{116ac}'),
         ('\u{116ad}', '\u{116ad}'), ('\u{116ae}', '\u{116af}'), ('\u{116b0}', '\u{116b5}'),
         ('\u{116b6}', '\u{116b6}'), ('\u{116b7}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}')
     ];
 
-    pub static Tamil_table: &'static [(char, char)] = &[
+    pub const Tamil_table: &'static [(char, char)] = &[
         ('\u{b82}', '\u{b82}'), ('\u{b83}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}',
         '\u{b90}'), ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'),
         ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}',
@@ -3860,7 +3860,7 @@ pub mod script {
         ('\u{bf3}', '\u{bf8}'), ('\u{bf9}', '\u{bf9}'), ('\u{bfa}', '\u{bfa}')
     ];
 
-    pub static Telugu_table: &'static [(char, char)] = &[
+    pub const Telugu_table: &'static [(char, char)] = &[
         ('\u{c00}', '\u{c00}'), ('\u{c01}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}',
         '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'),
         ('\u{c3e}', '\u{c40}'), ('\u{c41}', '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}',
@@ -3869,17 +3869,17 @@ pub mod script {
         '\u{c7f}')
     ];
 
-    pub static Thaana_table: &'static [(char, char)] = &[
+    pub const Thaana_table: &'static [(char, char)] = &[
         ('\u{780}', '\u{7a5}'), ('\u{7a6}', '\u{7b0}'), ('\u{7b1}', '\u{7b1}')
     ];
 
-    pub static Thai_table: &'static [(char, char)] = &[
+    pub const Thai_table: &'static [(char, char)] = &[
         ('\u{e01}', '\u{e30}'), ('\u{e31}', '\u{e31}'), ('\u{e32}', '\u{e33}'), ('\u{e34}',
         '\u{e3a}'), ('\u{e40}', '\u{e45}'), ('\u{e46}', '\u{e46}'), ('\u{e47}', '\u{e4e}'),
         ('\u{e4f}', '\u{e4f}'), ('\u{e50}', '\u{e59}'), ('\u{e5a}', '\u{e5b}')
     ];
 
-    pub static Tibetan_table: &'static [(char, char)] = &[
+    pub const Tibetan_table: &'static [(char, char)] = &[
         ('\u{f00}', '\u{f00}'), ('\u{f01}', '\u{f03}'), ('\u{f04}', '\u{f12}'), ('\u{f13}',
         '\u{f13}'), ('\u{f14}', '\u{f14}'), ('\u{f15}', '\u{f17}'), ('\u{f18}', '\u{f19}'),
         ('\u{f1a}', '\u{f1f}'), ('\u{f20}', '\u{f29}'), ('\u{f2a}', '\u{f33}'), ('\u{f34}',
@@ -3893,12 +3893,12 @@ pub mod script {
         ('\u{fd0}', '\u{fd4}'), ('\u{fd9}', '\u{fda}')
     ];
 
-    pub static Tifinagh_table: &'static [(char, char)] = &[
+    pub const Tifinagh_table: &'static [(char, char)] = &[
         ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d70}', '\u{2d70}'), ('\u{2d7f}',
         '\u{2d7f}')
     ];
 
-    pub static Tirhuta_table: &'static [(char, char)] = &[
+    pub const Tirhuta_table: &'static [(char, char)] = &[
         ('\u{11480}', '\u{114af}'), ('\u{114b0}', '\u{114b2}'), ('\u{114b3}', '\u{114b8}'),
         ('\u{114b9}', '\u{114b9}'), ('\u{114ba}', '\u{114ba}'), ('\u{114bb}', '\u{114be}'),
         ('\u{114bf}', '\u{114c0}'), ('\u{114c1}', '\u{114c1}'), ('\u{114c2}', '\u{114c3}'),
@@ -3906,21 +3906,21 @@ pub mod script {
         ('\u{114d0}', '\u{114d9}')
     ];
 
-    pub static Ugaritic_table: &'static [(char, char)] = &[
+    pub const Ugaritic_table: &'static [(char, char)] = &[
         ('\u{10380}', '\u{1039d}'), ('\u{1039f}', '\u{1039f}')
     ];
 
-    pub static Vai_table: &'static [(char, char)] = &[
+    pub const Vai_table: &'static [(char, char)] = &[
         ('\u{a500}', '\u{a60b}'), ('\u{a60c}', '\u{a60c}'), ('\u{a60d}', '\u{a60f}'), ('\u{a610}',
         '\u{a61f}'), ('\u{a620}', '\u{a629}'), ('\u{a62a}', '\u{a62b}')
     ];
 
-    pub static Warang_Citi_table: &'static [(char, char)] = &[
+    pub const Warang_Citi_table: &'static [(char, char)] = &[
         ('\u{118a0}', '\u{118df}'), ('\u{118e0}', '\u{118e9}'), ('\u{118ea}', '\u{118f2}'),
         ('\u{118ff}', '\u{118ff}')
     ];
 
-    pub static Yi_table: &'static [(char, char)] = &[
+    pub const Yi_table: &'static [(char, char)] = &[
         ('\u{a000}', '\u{a014}'), ('\u{a015}', '\u{a015}'), ('\u{a016}', '\u{a48c}'), ('\u{a490}',
         '\u{a4c6}')
     ];
@@ -3928,11 +3928,11 @@ pub mod script {
 }
 
 pub mod property {
-    pub static Join_Control_table: &'static [(char, char)] = &[
+    pub const Join_Control_table: &'static [(char, char)] = &[
         ('\u{200c}', '\u{200d}')
     ];
 
-    pub static Noncharacter_Code_Point_table: &'static [(char, char)] = &[
+    pub const Noncharacter_Code_Point_table: &'static [(char, char)] = &[
         ('\u{fdd0}', '\u{fdef}'), ('\u{fffe}', '\u{ffff}'), ('\u{1fffe}', '\u{1ffff}'),
         ('\u{2fffe}', '\u{2ffff}'), ('\u{3fffe}', '\u{3ffff}'), ('\u{4fffe}', '\u{4ffff}'),
         ('\u{5fffe}', '\u{5ffff}'), ('\u{6fffe}', '\u{6ffff}'), ('\u{7fffe}', '\u{7ffff}'),
@@ -3941,7 +3941,7 @@ pub mod property {
         ('\u{efffe}', '\u{effff}'), ('\u{ffffe}', '\u{fffff}')
     ];
 
-    pub static White_Space_table: &'static [(char, char)] = &[
+    pub const White_Space_table: &'static [(char, char)] = &[
         ('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), ('\u{a0}', '\u{a0}'),
         ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), ('\u{2028}', '\u{2028}'), ('\u{2029}',
         '\u{2029}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}')
@@ -3954,111 +3954,110 @@ pub fn White_Space(c: char) -> bool {
 }
 
 pub mod regex {
-    pub static UNICODE_CLASSES: &'static [(&'static str, &'static &'static [(char, char)])] = &[
-        ("Alphabetic", &super::derived_property::Alphabetic_table), ("Arabic",
-        &super::script::Arabic_table), ("Armenian", &super::script::Armenian_table), ("Avestan",
-        &super::script::Avestan_table), ("Balinese", &super::script::Balinese_table), ("Bamum",
-        &super::script::Bamum_table), ("Bassa_Vah", &super::script::Bassa_Vah_table), ("Batak",
-        &super::script::Batak_table), ("Bengali", &super::script::Bengali_table), ("Bopomofo",
-        &super::script::Bopomofo_table), ("Brahmi", &super::script::Brahmi_table), ("Braille",
-        &super::script::Braille_table), ("Buginese", &super::script::Buginese_table), ("Buhid",
-        &super::script::Buhid_table), ("C", &super::general_category::C_table),
-        ("Canadian_Aboriginal", &super::script::Canadian_Aboriginal_table), ("Carian",
-        &super::script::Carian_table), ("Caucasian_Albanian",
-        &super::script::Caucasian_Albanian_table), ("Cc", &super::general_category::Cc_table),
-        ("Cf", &super::general_category::Cf_table), ("Chakma", &super::script::Chakma_table),
-        ("Cham", &super::script::Cham_table), ("Cherokee", &super::script::Cherokee_table), ("Cn",
-        &super::general_category::Cn_table), ("Co", &super::general_category::Co_table), ("Common",
-        &super::script::Common_table), ("Coptic", &super::script::Coptic_table), ("Cuneiform",
-        &super::script::Cuneiform_table), ("Cypriot", &super::script::Cypriot_table), ("Cyrillic",
-        &super::script::Cyrillic_table), ("Default_Ignorable_Code_Point",
-        &super::derived_property::Default_Ignorable_Code_Point_table), ("Deseret",
-        &super::script::Deseret_table), ("Devanagari", &super::script::Devanagari_table),
-        ("Duployan", &super::script::Duployan_table), ("Egyptian_Hieroglyphs",
-        &super::script::Egyptian_Hieroglyphs_table), ("Elbasan", &super::script::Elbasan_table),
-        ("Ethiopic", &super::script::Ethiopic_table), ("Georgian", &super::script::Georgian_table),
-        ("Glagolitic", &super::script::Glagolitic_table), ("Gothic", &super::script::Gothic_table),
-        ("Grantha", &super::script::Grantha_table), ("Greek", &super::script::Greek_table),
-        ("Gujarati", &super::script::Gujarati_table), ("Gurmukhi", &super::script::Gurmukhi_table),
-        ("Han", &super::script::Han_table), ("Hangul", &super::script::Hangul_table), ("Hanunoo",
-        &super::script::Hanunoo_table), ("Hebrew", &super::script::Hebrew_table), ("Hiragana",
-        &super::script::Hiragana_table), ("Imperial_Aramaic",
-        &super::script::Imperial_Aramaic_table), ("Inherited", &super::script::Inherited_table),
-        ("Inscriptional_Pahlavi", &super::script::Inscriptional_Pahlavi_table),
-        ("Inscriptional_Parthian", &super::script::Inscriptional_Parthian_table), ("Javanese",
-        &super::script::Javanese_table), ("Join_Control", &super::property::Join_Control_table),
-        ("Kaithi", &super::script::Kaithi_table), ("Kannada", &super::script::Kannada_table),
-        ("Katakana", &super::script::Katakana_table), ("Kayah_Li", &super::script::Kayah_Li_table),
-        ("Kharoshthi", &super::script::Kharoshthi_table), ("Khmer", &super::script::Khmer_table),
-        ("Khojki", &super::script::Khojki_table), ("Khudawadi", &super::script::Khudawadi_table),
-        ("L", &super::general_category::L_table), ("LC", &super::general_category::LC_table),
-        ("Lao", &super::script::Lao_table), ("Latin", &super::script::Latin_table), ("Lepcha",
-        &super::script::Lepcha_table), ("Limbu", &super::script::Limbu_table), ("Linear_A",
-        &super::script::Linear_A_table), ("Linear_B", &super::script::Linear_B_table), ("Lisu",
-        &super::script::Lisu_table), ("Ll", &super::general_category::Ll_table), ("Lm",
-        &super::general_category::Lm_table), ("Lo", &super::general_category::Lo_table),
-        ("Lowercase", &super::derived_property::Lowercase_table), ("Lt",
-        &super::general_category::Lt_table), ("Lu", &super::general_category::Lu_table), ("Lycian",
-        &super::script::Lycian_table), ("Lydian", &super::script::Lydian_table), ("M",
-        &super::general_category::M_table), ("Mahajani", &super::script::Mahajani_table),
-        ("Malayalam", &super::script::Malayalam_table), ("Mandaic", &super::script::Mandaic_table),
-        ("Manichaean", &super::script::Manichaean_table), ("Mc",
-        &super::general_category::Mc_table), ("Me", &super::general_category::Me_table),
-        ("Meetei_Mayek", &super::script::Meetei_Mayek_table), ("Mende_Kikakui",
-        &super::script::Mende_Kikakui_table), ("Meroitic_Cursive",
-        &super::script::Meroitic_Cursive_table), ("Meroitic_Hieroglyphs",
-        &super::script::Meroitic_Hieroglyphs_table), ("Miao", &super::script::Miao_table), ("Mn",
-        &super::general_category::Mn_table), ("Modi", &super::script::Modi_table), ("Mongolian",
-        &super::script::Mongolian_table), ("Mro", &super::script::Mro_table), ("Myanmar",
-        &super::script::Myanmar_table), ("N", &super::general_category::N_table), ("Nabataean",
-        &super::script::Nabataean_table), ("Nd", &super::general_category::Nd_table),
-        ("New_Tai_Lue", &super::script::New_Tai_Lue_table), ("Nko", &super::script::Nko_table),
-        ("Nl", &super::general_category::Nl_table), ("No", &super::general_category::No_table),
-        ("Noncharacter_Code_Point", &super::property::Noncharacter_Code_Point_table), ("Ogham",
-        &super::script::Ogham_table), ("Ol_Chiki", &super::script::Ol_Chiki_table), ("Old_Italic",
-        &super::script::Old_Italic_table), ("Old_North_Arabian",
-        &super::script::Old_North_Arabian_table), ("Old_Permic", &super::script::Old_Permic_table),
-        ("Old_Persian", &super::script::Old_Persian_table), ("Old_South_Arabian",
-        &super::script::Old_South_Arabian_table), ("Old_Turkic", &super::script::Old_Turkic_table),
-        ("Oriya", &super::script::Oriya_table), ("Osmanya", &super::script::Osmanya_table), ("P",
-        &super::general_category::P_table), ("Pahawh_Hmong", &super::script::Pahawh_Hmong_table),
-        ("Palmyrene", &super::script::Palmyrene_table), ("Pau_Cin_Hau",
-        &super::script::Pau_Cin_Hau_table), ("Pc", &super::general_category::Pc_table), ("Pd",
-        &super::general_category::Pd_table), ("Pe", &super::general_category::Pe_table), ("Pf",
-        &super::general_category::Pf_table), ("Phags_Pa", &super::script::Phags_Pa_table),
-        ("Phoenician", &super::script::Phoenician_table), ("Pi",
-        &super::general_category::Pi_table), ("Po", &super::general_category::Po_table), ("Ps",
-        &super::general_category::Ps_table), ("Psalter_Pahlavi",
-        &super::script::Psalter_Pahlavi_table), ("Rejang", &super::script::Rejang_table), ("Runic",
-        &super::script::Runic_table), ("S", &super::general_category::S_table), ("Samaritan",
-        &super::script::Samaritan_table), ("Saurashtra", &super::script::Saurashtra_table), ("Sc",
-        &super::general_category::Sc_table), ("Sharada", &super::script::Sharada_table), ("Shavian",
-        &super::script::Shavian_table), ("Siddham", &super::script::Siddham_table), ("Sinhala",
-        &super::script::Sinhala_table), ("Sk", &super::general_category::Sk_table), ("Sm",
-        &super::general_category::Sm_table), ("So", &super::general_category::So_table),
-        ("Sora_Sompeng", &super::script::Sora_Sompeng_table), ("Sundanese",
-        &super::script::Sundanese_table), ("Syloti_Nagri", &super::script::Syloti_Nagri_table),
-        ("Syriac", &super::script::Syriac_table), ("Tagalog", &super::script::Tagalog_table),
-        ("Tagbanwa", &super::script::Tagbanwa_table), ("Tai_Le", &super::script::Tai_Le_table),
-        ("Tai_Tham", &super::script::Tai_Tham_table), ("Tai_Viet", &super::script::Tai_Viet_table),
-        ("Takri", &super::script::Takri_table), ("Tamil", &super::script::Tamil_table), ("Telugu",
-        &super::script::Telugu_table), ("Thaana", &super::script::Thaana_table), ("Thai",
-        &super::script::Thai_table), ("Tibetan", &super::script::Tibetan_table), ("Tifinagh",
-        &super::script::Tifinagh_table), ("Tirhuta", &super::script::Tirhuta_table), ("Ugaritic",
-        &super::script::Ugaritic_table), ("Uppercase", &super::derived_property::Uppercase_table),
-        ("Vai", &super::script::Vai_table), ("Warang_Citi", &super::script::Warang_Citi_table),
-        ("White_Space", &super::property::White_Space_table), ("XID_Continue",
-        &super::derived_property::XID_Continue_table), ("XID_Start",
-        &super::derived_property::XID_Start_table), ("Yi", &super::script::Yi_table), ("Z",
-        &super::general_category::Z_table), ("Zl", &super::general_category::Zl_table), ("Zp",
-        &super::general_category::Zp_table), ("Zs", &super::general_category::Zs_table)
-    ];
-
-    pub static PERLD: &'static &'static [(char, char)] = &super::general_category::Nd_table;
-
-    pub static PERLS: &'static &'static [(char, char)] = &super::property::White_Space_table;
-
-    pub static PERLW: &'static [(char, char)] = &[
+    pub const UNICODE_CLASSES: &'static [(&'static str, &'static [(char, char)])] = &[
+        ("Alphabetic", super::derived_property::Alphabetic_table), ("Arabic",
+        super::script::Arabic_table), ("Armenian", super::script::Armenian_table), ("Avestan",
+        super::script::Avestan_table), ("Balinese", super::script::Balinese_table), ("Bamum",
+        super::script::Bamum_table), ("Bassa_Vah", super::script::Bassa_Vah_table), ("Batak",
+        super::script::Batak_table), ("Bengali", super::script::Bengali_table), ("Bopomofo",
+        super::script::Bopomofo_table), ("Brahmi", super::script::Brahmi_table), ("Braille",
+        super::script::Braille_table), ("Buginese", super::script::Buginese_table), ("Buhid",
+        super::script::Buhid_table), ("C", super::general_category::C_table),
+        ("Canadian_Aboriginal", super::script::Canadian_Aboriginal_table), ("Carian",
+        super::script::Carian_table), ("Caucasian_Albanian",
+        super::script::Caucasian_Albanian_table), ("Cc", super::general_category::Cc_table), ("Cf",
+        super::general_category::Cf_table), ("Chakma", super::script::Chakma_table), ("Cham",
+        super::script::Cham_table), ("Cherokee", super::script::Cherokee_table), ("Cn",
+        super::general_category::Cn_table), ("Co", super::general_category::Co_table), ("Common",
+        super::script::Common_table), ("Coptic", super::script::Coptic_table), ("Cuneiform",
+        super::script::Cuneiform_table), ("Cypriot", super::script::Cypriot_table), ("Cyrillic",
+        super::script::Cyrillic_table), ("Default_Ignorable_Code_Point",
+        super::derived_property::Default_Ignorable_Code_Point_table), ("Deseret",
+        super::script::Deseret_table), ("Devanagari", super::script::Devanagari_table), ("Duployan",
+        super::script::Duployan_table), ("Egyptian_Hieroglyphs",
+        super::script::Egyptian_Hieroglyphs_table), ("Elbasan", super::script::Elbasan_table),
+        ("Ethiopic", super::script::Ethiopic_table), ("Georgian", super::script::Georgian_table),
+        ("Glagolitic", super::script::Glagolitic_table), ("Gothic", super::script::Gothic_table),
+        ("Grantha", super::script::Grantha_table), ("Greek", super::script::Greek_table),
+        ("Gujarati", super::script::Gujarati_table), ("Gurmukhi", super::script::Gurmukhi_table),
+        ("Han", super::script::Han_table), ("Hangul", super::script::Hangul_table), ("Hanunoo",
+        super::script::Hanunoo_table), ("Hebrew", super::script::Hebrew_table), ("Hiragana",
+        super::script::Hiragana_table), ("Imperial_Aramaic", super::script::Imperial_Aramaic_table),
+        ("Inherited", super::script::Inherited_table), ("Inscriptional_Pahlavi",
+        super::script::Inscriptional_Pahlavi_table), ("Inscriptional_Parthian",
+        super::script::Inscriptional_Parthian_table), ("Javanese", super::script::Javanese_table),
+        ("Join_Control", super::property::Join_Control_table), ("Kaithi",
+        super::script::Kaithi_table), ("Kannada", super::script::Kannada_table), ("Katakana",
+        super::script::Katakana_table), ("Kayah_Li", super::script::Kayah_Li_table), ("Kharoshthi",
+        super::script::Kharoshthi_table), ("Khmer", super::script::Khmer_table), ("Khojki",
+        super::script::Khojki_table), ("Khudawadi", super::script::Khudawadi_table), ("L",
+        super::general_category::L_table), ("LC", super::general_category::LC_table), ("Lao",
+        super::script::Lao_table), ("Latin", super::script::Latin_table), ("Lepcha",
+        super::script::Lepcha_table), ("Limbu", super::script::Limbu_table), ("Linear_A",
+        super::script::Linear_A_table), ("Linear_B", super::script::Linear_B_table), ("Lisu",
+        super::script::Lisu_table), ("Ll", super::general_category::Ll_table), ("Lm",
+        super::general_category::Lm_table), ("Lo", super::general_category::Lo_table), ("Lowercase",
+        super::derived_property::Lowercase_table), ("Lt", super::general_category::Lt_table), ("Lu",
+        super::general_category::Lu_table), ("Lycian", super::script::Lycian_table), ("Lydian",
+        super::script::Lydian_table), ("M", super::general_category::M_table), ("Mahajani",
+        super::script::Mahajani_table), ("Malayalam", super::script::Malayalam_table), ("Mandaic",
+        super::script::Mandaic_table), ("Manichaean", super::script::Manichaean_table), ("Mc",
+        super::general_category::Mc_table), ("Me", super::general_category::Me_table),
+        ("Meetei_Mayek", super::script::Meetei_Mayek_table), ("Mende_Kikakui",
+        super::script::Mende_Kikakui_table), ("Meroitic_Cursive",
+        super::script::Meroitic_Cursive_table), ("Meroitic_Hieroglyphs",
+        super::script::Meroitic_Hieroglyphs_table), ("Miao", super::script::Miao_table), ("Mn",
+        super::general_category::Mn_table), ("Modi", super::script::Modi_table), ("Mongolian",
+        super::script::Mongolian_table), ("Mro", super::script::Mro_table), ("Myanmar",
+        super::script::Myanmar_table), ("N", super::general_category::N_table), ("Nabataean",
+        super::script::Nabataean_table), ("Nd", super::general_category::Nd_table), ("New_Tai_Lue",
+        super::script::New_Tai_Lue_table), ("Nko", super::script::Nko_table), ("Nl",
+        super::general_category::Nl_table), ("No", super::general_category::No_table),
+        ("Noncharacter_Code_Point", super::property::Noncharacter_Code_Point_table), ("Ogham",
+        super::script::Ogham_table), ("Ol_Chiki", super::script::Ol_Chiki_table), ("Old_Italic",
+        super::script::Old_Italic_table), ("Old_North_Arabian",
+        super::script::Old_North_Arabian_table), ("Old_Permic", super::script::Old_Permic_table),
+        ("Old_Persian", super::script::Old_Persian_table), ("Old_South_Arabian",
+        super::script::Old_South_Arabian_table), ("Old_Turkic", super::script::Old_Turkic_table),
+        ("Oriya", super::script::Oriya_table), ("Osmanya", super::script::Osmanya_table), ("P",
+        super::general_category::P_table), ("Pahawh_Hmong", super::script::Pahawh_Hmong_table),
+        ("Palmyrene", super::script::Palmyrene_table), ("Pau_Cin_Hau",
+        super::script::Pau_Cin_Hau_table), ("Pc", super::general_category::Pc_table), ("Pd",
+        super::general_category::Pd_table), ("Pe", super::general_category::Pe_table), ("Pf",
+        super::general_category::Pf_table), ("Phags_Pa", super::script::Phags_Pa_table),
+        ("Phoenician", super::script::Phoenician_table), ("Pi", super::general_category::Pi_table),
+        ("Po", super::general_category::Po_table), ("Ps", super::general_category::Ps_table),
+        ("Psalter_Pahlavi", super::script::Psalter_Pahlavi_table), ("Rejang",
+        super::script::Rejang_table), ("Runic", super::script::Runic_table), ("S",
+        super::general_category::S_table), ("Samaritan", super::script::Samaritan_table),
+        ("Saurashtra", super::script::Saurashtra_table), ("Sc", super::general_category::Sc_table),
+        ("Sharada", super::script::Sharada_table), ("Shavian", super::script::Shavian_table),
+        ("Siddham", super::script::Siddham_table), ("Sinhala", super::script::Sinhala_table), ("Sk",
+        super::general_category::Sk_table), ("Sm", super::general_category::Sm_table), ("So",
+        super::general_category::So_table), ("Sora_Sompeng", super::script::Sora_Sompeng_table),
+        ("Sundanese", super::script::Sundanese_table), ("Syloti_Nagri",
+        super::script::Syloti_Nagri_table), ("Syriac", super::script::Syriac_table), ("Tagalog",
+        super::script::Tagalog_table), ("Tagbanwa", super::script::Tagbanwa_table), ("Tai_Le",
+        super::script::Tai_Le_table), ("Tai_Tham", super::script::Tai_Tham_table), ("Tai_Viet",
+        super::script::Tai_Viet_table), ("Takri", super::script::Takri_table), ("Tamil",
+        super::script::Tamil_table), ("Telugu", super::script::Telugu_table), ("Thaana",
+        super::script::Thaana_table), ("Thai", super::script::Thai_table), ("Tibetan",
+        super::script::Tibetan_table), ("Tifinagh", super::script::Tifinagh_table), ("Tirhuta",
+        super::script::Tirhuta_table), ("Ugaritic", super::script::Ugaritic_table), ("Uppercase",
+        super::derived_property::Uppercase_table), ("Vai", super::script::Vai_table),
+        ("Warang_Citi", super::script::Warang_Citi_table), ("White_Space",
+        super::property::White_Space_table), ("XID_Continue",
+        super::derived_property::XID_Continue_table), ("XID_Start",
+        super::derived_property::XID_Start_table), ("Yi", super::script::Yi_table), ("Z",
+        super::general_category::Z_table), ("Zl", super::general_category::Zl_table), ("Zp",
+        super::general_category::Zp_table), ("Zs", super::general_category::Zs_table)
+    ];
+
+    pub const PERLD: &'static [(char, char)] = super::general_category::Nd_table;
+
+    pub const PERLS: &'static [(char, char)] = super::property::White_Space_table;
+
+    pub const PERLW: &'static [(char, char)] = &[
         ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'),
         ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'),
         ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'),
@@ -4254,7 +4253,7 @@ pub mod regex {
 
 pub mod normalization {
     // Canonical decompositions
-    pub static canonical_table: &'static [(char, &'static [char])] = &[
+    pub const canonical_table: &'static [(char, &'static [char])] = &[
         ('\u{c0}', &['\u{41}', '\u{300}']), ('\u{c1}', &['\u{41}', '\u{301}']), ('\u{c2}',
         &['\u{41}', '\u{302}']), ('\u{c3}', &['\u{41}', '\u{303}']), ('\u{c4}', &['\u{41}',
         '\u{308}']), ('\u{c5}', &['\u{41}', '\u{30a}']), ('\u{c7}', &['\u{43}', '\u{327}']),
@@ -5056,7 +5055,7 @@ pub mod normalization {
     ];
 
     // Compatibility decompositions
-    pub static compatibility_table: &'static [(char, &'static [char])] = &[
+    pub const compatibility_table: &'static [(char, &'static [char])] = &[
         ('\u{a0}', &['\u{20}']), ('\u{a8}', &['\u{20}', '\u{308}']), ('\u{aa}', &['\u{61}']),
         ('\u{af}', &['\u{20}', '\u{304}']), ('\u{b2}', &['\u{32}']), ('\u{b3}', &['\u{33}']),
         ('\u{b4}', &['\u{20}', '\u{301}']), ('\u{b5}', &['\u{3bc}']), ('\u{b8}', &['\u{20}',
@@ -6480,7 +6479,7 @@ pub mod normalization {
     ];
 
     // Canonical compositions
-    pub static composition_table: &'static [(char, &'static [(char, char)])] = &[
+    pub const composition_table: &'static [(char, &'static [(char, char)])] = &[
         ('\u{3c}', &[('\u{338}', '\u{226e}')]), ('\u{3d}', &[('\u{338}', '\u{2260}')]), ('\u{3e}',
         &[('\u{338}', '\u{226f}')]), ('\u{41}', &[('\u{300}', '\u{c0}'), ('\u{301}', '\u{c1}'),
         ('\u{302}', '\u{c2}'), ('\u{303}', '\u{c3}'), ('\u{304}', '\u{100}'), ('\u{306}',
@@ -6840,7 +6839,7 @@ fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
         }
     }
 
-    static combining_class_table: &'static [(char, char, u8)] = &[
+    const combining_class_table: &'static [(char, char, u8)] = &[
         ('\u{300}', '\u{314}', 230), ('\u{315}', '\u{315}', 232), ('\u{316}', '\u{319}', 220),
         ('\u{31a}', '\u{31a}', 232), ('\u{31b}', '\u{31b}', 216), ('\u{31c}', '\u{320}', 220),
         ('\u{321}', '\u{322}', 202), ('\u{323}', '\u{326}', 220), ('\u{327}', '\u{328}', 202),
@@ -6988,7 +6987,7 @@ fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<usize>
         }
     }
 
-    static LuLl_table: &'static [(char, char)] = &[
+    const LuLl_table: &'static [(char, char)] = &[
         ('\u{41}', '\u{61}'), ('\u{42}', '\u{62}'), ('\u{43}', '\u{63}'), ('\u{44}', '\u{64}'),
         ('\u{45}', '\u{65}'), ('\u{46}', '\u{66}'), ('\u{47}', '\u{67}'), ('\u{48}', '\u{68}'),
         ('\u{49}', '\u{69}'), ('\u{4a}', '\u{6a}'), ('\u{4b}', '\u{6b}'), ('\u{4c}', '\u{6c}'),
@@ -7284,7 +7283,7 @@ fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<usize>
         ('\u{118be}', '\u{118de}'), ('\u{118bf}', '\u{118df}')
     ];
 
-    static LlLu_table: &'static [(char, char)] = &[
+    const LlLu_table: &'static [(char, char)] = &[
         ('\u{61}', '\u{41}'), ('\u{62}', '\u{42}'), ('\u{63}', '\u{43}'), ('\u{64}', '\u{44}'),
         ('\u{65}', '\u{45}'), ('\u{66}', '\u{46}'), ('\u{67}', '\u{47}'), ('\u{68}', '\u{48}'),
         ('\u{69}', '\u{49}'), ('\u{6a}', '\u{4a}'), ('\u{6b}', '\u{4b}'), ('\u{6c}', '\u{4c}'),
@@ -7625,7 +7624,7 @@ pub fn width(c: char, is_cjk: bool) -> Option<usize> {
 
     // character width table. Based on Markus Kuhn's free wcwidth() implementation,
     //     http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
-    static charwidth_table: &'static [(char, char, u8, u8)] = &[
+    const charwidth_table: &'static [(char, char, u8, u8)] = &[
         ('\u{a1}', '\u{a1}', 1, 2), ('\u{a4}', '\u{a4}', 1, 2), ('\u{a7}', '\u{a8}', 1, 2),
         ('\u{aa}', '\u{aa}', 1, 2), ('\u{ae}', '\u{ae}', 1, 2), ('\u{b0}', '\u{b4}', 1, 2),
         ('\u{b6}', '\u{ba}', 1, 2), ('\u{bc}', '\u{bf}', 1, 2), ('\u{c6}', '\u{c6}', 1, 2),
@@ -7839,7 +7838,7 @@ pub fn grapheme_category(c: char) -> GraphemeCat {
         bsearch_range_value_table(c, grapheme_cat_table)
     }
 
-    static grapheme_cat_table: &'static [(char, char, GraphemeCat)] = &[
+    const grapheme_cat_table: &'static [(char, char, GraphemeCat)] = &[
         ('\u{0}', '\u{1f}', GC_Control), ('\u{7f}', '\u{9f}', GC_Control), ('\u{ad}', '\u{ad}',
         GC_Control), ('\u{300}', '\u{36f}', GC_Extend), ('\u{483}', '\u{487}', GC_Extend),
         ('\u{488}', '\u{489}', GC_Extend), ('\u{591}', '\u{5bd}', GC_Extend), ('\u{5bf}', '\u{5bf}',
index fb75c67253c6d057d37e962e80d9e5fe7ad03910..f239a0d78d1ddd9875bb6c873d5f5f07e0aeb6b4 100644 (file)
 #![feature(box_syntax)]
 
 use std::ascii::OwnedAsciiExt;
+use std::env;
+use std::fs::File;
+use std::io::prelude::*;
+use std::io;
 use std::slice;
 use std::sync::Arc;
 use std::thread;
 
 static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
-static TABLE_SIZE: uint = 2 << 16;
+static TABLE_SIZE: usize = 2 << 16;
 
 static OCCURRENCES: [&'static str;5] = [
     "GGT",
@@ -73,7 +77,7 @@ fn push_char(&self, c: u8) -> Code {
         Code((self.hash() << 2) + (pack_symbol(c) as u64))
     }
 
-    fn rotate(&self, c: u8, frame: uint) -> Code {
+    fn rotate(&self, c: u8, frame: usize) -> Code {
         Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
     }
 
@@ -81,7 +85,7 @@ fn pack(string: &str) -> Code {
         string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
     }
 
-    fn unpack(&self, frame: uint) -> String {
+    fn unpack(&self, frame: usize) -> String {
         let mut key = self.hash();
         let mut result = Vec::new();
         for _ in 0..frame {
@@ -113,13 +117,13 @@ fn f(&self, entry: &mut Entry) {
 impl TableCallback for PrintCallback {
     fn f(&self, entry: &mut Entry) {
         let PrintCallback(s) = *self;
-        println!("{}\t{}", entry.count as int, s);
+        println!("{}\t{}", entry.count, s);
     }
 }
 
 struct Entry {
     code: Code,
-    count: uint,
+    count: usize,
     next: Option<Box<Entry>>,
 }
 
@@ -165,20 +169,20 @@ fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
         let index = key.hash() % (TABLE_SIZE as u64);
 
         {
-            if self.items[index as uint].is_none() {
+            if self.items[index as usize].is_none() {
                 let mut entry = box Entry {
                     code: key,
                     count: 0,
                     next: None,
                 };
                 c.f(&mut *entry);
-                self.items[index as uint] = Some(entry);
+                self.items[index as usize] = Some(entry);
                 return;
             }
         }
 
         {
-            let entry = self.items[index as uint].as_mut().unwrap();
+            let entry = self.items[index as usize].as_mut().unwrap();
             if entry.code == key {
                 c.f(&mut **entry);
                 return;
@@ -233,10 +237,10 @@ fn pack_symbol(c: u8) -> u8 {
 }
 
 fn unpack_symbol(c: u8) -> u8 {
-    TABLE[c as uint]
+    TABLE[c as usize]
 }
 
-fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
+fn generate_frequencies(mut input: &[u8], frame: usize) -> Table {
     let mut frequencies = Table::new();
     if input.len() < frame { return frequencies; }
     let mut code = Code(0);
@@ -256,7 +260,7 @@ fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
     frequencies
 }
 
-fn print_frequencies(frequencies: &Table, frame: uint) {
+fn print_frequencies(frequencies: &Table, frame: usize) {
     let mut vector = Vec::new();
     for entry in frequencies.iter() {
         vector.push((entry.count, entry.code));
@@ -280,9 +284,9 @@ fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
     frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
 }
 
-fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
+fn get_sequence<R: BufRead>(r: &mut R, key: &str) -> Vec<u8> {
     let mut res = Vec::new();
-    for l in r.lines().map(|l| l.ok().unwrap())
+    for l in r.lines().map(|l| l.unwrap())
         .skip_while(|l| key != &l[..key.len()]).skip(1)
     {
         res.push_all(l.trim().as_bytes());
@@ -291,13 +295,13 @@ fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
 }
 
 fn main() {
-    let input = if std::env::var_os("RUST_BENCH").is_some() {
-        let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data"));
-        get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE")
+    let input = if env::var_os("RUST_BENCH").is_some() {
+        let f = File::open("shootout-k-nucleotide.data").unwrap();
+        get_sequence(&mut io::BufReader::new(f), ">THREE")
     } else {
-        let mut stdin = std::old_io::stdin();
+        let stdin = io::stdin();
         let mut stdin = stdin.lock();
-        get_sequence(&mut *stdin, ">THREE")
+        get_sequence(&mut stdin, ">THREE")
     };
     let input = Arc::new(input);
 
index b45f241e8e5d4291a7d72df40faf1535ac2d3090..40e1e7d2b76b02614a211db532013b8a9a0b1452 100644 (file)
@@ -13,9 +13,8 @@
 #![feature(box_syntax)]
 #![allow(non_snake_case)]
 
-use std::old_io::BufferedReader;
-use std::old_io::stdio::StdReader;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
 use std::iter::repeat;
 use std::num::Int;
 use std::env;
@@ -37,7 +36,7 @@
 //
 
 // internal type of sudoku grids
-type grid = Vec<Vec<u8> > ;
+type grid = Vec<Vec<u8>>;
 
 struct Sudoku {
     grid: grid
@@ -55,9 +54,11 @@ pub fn new(g: grid) -> Sudoku {
         return Sudoku::new(g)
     }
 
-    pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
+    pub fn read(reader: &mut BufRead) -> Sudoku {
         /* assert first line is exactly "9,9" */
-        assert!(reader.read_line().unwrap() == "9,9".to_string());
+        let mut s = String::new();
+        reader.read_line(&mut s).unwrap();
+        assert_eq!(s, "9,9\n");
 
         let mut g = repeat(vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8])
                           .take(10).collect::<Vec<_>>();
@@ -71,7 +72,7 @@ pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
             if comps.len() == 3 {
                 let row = comps[0].parse::<u8>().unwrap();
                 let col = comps[1].parse::<u8>().unwrap();
-                g[row as uint][col as uint] = comps[2].parse().unwrap();
+                g[row as usize][col as usize] = comps[2].parse().unwrap();
             }
             else {
                 panic!("Invalid sudoku file");
@@ -80,11 +81,11 @@ pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
         return Sudoku::new(g)
     }
 
-    pub fn write(&self, writer: &mut old_io::Writer) {
+    pub fn write(&self, writer: &mut Write) {
         for row in 0u8..9u8 {
-            write!(writer, "{}", self.grid[row as uint][0]);
+            write!(writer, "{}", self.grid[row as usize][0]);
             for col in 1u8..9u8 {
-                write!(writer, " {}", self.grid[row as uint][col as uint]);
+                write!(writer, " {}", self.grid[row as usize][col as usize]);
             }
             write!(writer, "\n");
          }
@@ -95,7 +96,7 @@ pub fn solve(&mut self) {
         let mut work: Vec<(u8, u8)> = Vec::new(); /* queue of uncolored fields */
         for row in 0u8..9u8 {
             for col in 0u8..9u8 {
-                let color = self.grid[row as uint][col as uint];
+                let color = self.grid[row as usize][col as usize];
                 if color == 0u8 {
                     work.push((row, col));
                 }
@@ -107,7 +108,7 @@ pub fn solve(&mut self) {
         while ptr < end {
             let (row, col) = work[ptr];
             // is there another color to try?
-            let the_color = self.grid[row as uint][col as uint] +
+            let the_color = self.grid[row as usize][col as usize] +
                                 (1 as u8);
             if self.next_color(row, col, the_color) {
                 //  yes: advance work list
@@ -130,10 +131,10 @@ fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
 
             // find first remaining color that is available
             let next = avail.next();
-            self.grid[row as uint][col as uint] = next;
+            self.grid[row as usize][col as usize] = next;
             return 0u8 != next;
         }
-        self.grid[row as uint][col as uint] = 0u8;
+        self.grid[row as usize][col as usize] = 0u8;
         return false;
     }
 
@@ -141,9 +142,9 @@ fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
     fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) {
         for idx in 0u8..9u8 {
             /* check same column fields */
-            avail.remove(self.grid[idx as uint][col as uint]);
+            avail.remove(self.grid[idx as usize][col as usize]);
             /* check same row fields */
-            avail.remove(self.grid[row as uint][idx as uint]);
+            avail.remove(self.grid[row as usize][idx as usize]);
         }
 
         // check same block fields
@@ -151,7 +152,7 @@ fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) {
         let col0 = (col / 3u8) * 3u8;
         for alt_row in row0..row0 + 3u8 {
             for alt_col in col0..col0 + 3u8 {
-                avail.remove(self.grid[alt_row as uint][alt_col as uint]);
+                avail.remove(self.grid[alt_row as usize][alt_col as usize]);
             }
         }
     }
@@ -165,7 +166,7 @@ fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) {
 impl Colors {
     fn new(start_color: u8) -> Colors {
         // Sets bits 9..start_color
-        let tails = !0u16 << start_color as uint;
+        let tails = !0u16 << start_color as usize;
         return Colors(HEADS & tails);
     }
 
@@ -182,7 +183,7 @@ fn next(&self) -> u8 {
     fn remove(&mut self, color: u8) {
         if color != 0u8 {
             let Colors(val) = *self;
-            let mask = !(1u16 << color as uint);
+            let mask = !(1u16 << color as usize);
             *self    = Colors(val & mask);
         }
     }
@@ -269,15 +270,16 @@ fn check_DEFAULT_SUDOKU_solution() {
 }
 
 fn main() {
-    let args        = env::args();
+    let args = env::args();
     let use_default = args.len() == 1;
     let mut sudoku = if use_default {
         Sudoku::from_vec(&DEFAULT_SUDOKU)
     } else {
-        let mut stdin = old_io::stdin();
-        let mut stdin = stdin.lock();
-        Sudoku::read(&mut *stdin)
+        let stdin = io::stdin();
+        let mut locked = stdin.lock();
+        Sudoku::read(&mut locked)
     };
     sudoku.solve();
-    sudoku.write(&mut old_io::stdout());
+    let out = io::stdout();
+    sudoku.write(&mut out.lock());
 }
index 02d06c4e1bf806adc18ac37dee7f3a2a10192405..43a0ad6b5f6bf71ea08efb88f8439b31972a0d64 100644 (file)
 
 // ignore-android
 
-#![feature(asm)]
+#![feature(asm, rustc_attrs)]
 
 #![allow(dead_code, non_upper_case_globals)]
 
 #[cfg(any(target_arch = "x86",
           target_arch = "x86_64"))]
-pub fn main() {
+#[rustc_error]
+pub fn main() { //~ ERROR compilation successful
     // assignment not dead
     let mut x: isize = 0;
     unsafe {
@@ -33,7 +34,3 @@ pub fn main() {
     }
     assert_eq!(x, 13);
 }
-
-// At least one error is needed so that compilation fails
-#[static_assert]
-static b: bool = false; //~ ERROR static assertion failed
diff --git a/src/test/compile-fail/dropck_no_diverge_on_nonregular_1.rs b/src/test/compile-fail/dropck_no_diverge_on_nonregular_1.rs
new file mode 100644 (file)
index 0000000..f096885
--- /dev/null
@@ -0,0 +1,37 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+    elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+
+enum FingerTree<T:'static> {
+    Single(T),
+    // Bug report said Digit after Box would stack overflow (versus
+    // Digit before Box; see dropck_no_diverge_on_nonregular_2).
+    Deep(
+        Box<FingerTree<Node<T>>>,
+        Digit<T>,
+        )
+}
+
+fn main() {
+    let ft = //~ ERROR overflow while adding drop-check rules for FingerTree
+        FingerTree::Single(1);
+    //~^ ERROR overflow while adding drop-check rules for FingerTree
+}
diff --git a/src/test/compile-fail/dropck_no_diverge_on_nonregular_2.rs b/src/test/compile-fail/dropck_no_diverge_on_nonregular_2.rs
new file mode 100644 (file)
index 0000000..886bd6b
--- /dev/null
@@ -0,0 +1,36 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+    elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+enum FingerTree<T:'static> {
+    Single(T),
+    // Bug report said Digit before Box would infinite loop (versus
+    // Digit after Box; see dropck_no_diverge_on_nonregular_1).
+    Deep(
+        Digit<T>,
+        Box<FingerTree<Node<T>>>,
+        )
+}
+
+fn main() {
+    let ft = //~ ERROR overflow while adding drop-check rules for FingerTree
+        FingerTree::Single(1);
+    //~^ ERROR overflow while adding drop-check rules for FingerTree
+}
diff --git a/src/test/compile-fail/dropck_no_diverge_on_nonregular_3.rs b/src/test/compile-fail/dropck_no_diverge_on_nonregular_3.rs
new file mode 100644 (file)
index 0000000..f7eb6e1
--- /dev/null
@@ -0,0 +1,46 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Issue 22443: Reject code using non-regular types that would
+// otherwise cause dropck to loop infinitely.
+//
+// This version is just checking that we still sanely handle a trivial
+// wrapper around the non-regular type. (It also demonstrates how the
+// error messages will report different types depending on which type
+// dropck is analyzing.)
+
+use std::marker::PhantomData;
+
+struct Digit<T> {
+    elem: T
+}
+
+struct Node<T:'static> { m: PhantomData<&'static T> }
+
+enum FingerTree<T:'static> {
+    Single(T),
+    // According to the bug report, Digit before Box would infinite loop.
+    Deep(
+        Digit<T>,
+        Box<FingerTree<Node<T>>>,
+        )
+}
+
+enum Wrapper<T:'static> {
+    Simple,
+    Other(FingerTree<T>),
+}
+
+fn main() {
+    let w = //~ ERROR overflow while adding drop-check rules for core::option
+        Some(Wrapper::Simple::<u32>);
+    //~^ ERROR overflow while adding drop-check rules for core::option::Option
+    //~| ERROR overflow while adding drop-check rules for Wrapper
+}
diff --git a/src/test/compile-fail/feature-gate-static-assert.rs b/src/test/compile-fail/feature-gate-static-assert.rs
new file mode 100644 (file)
index 0000000..2574039
--- /dev/null
@@ -0,0 +1,14 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#[static_assert] //~ ERROR `#[static_assert]` is an experimental feature
+static X: bool = true;
+
+fn main() {}
index 1e04e685e41b8b3434ca2b62dfd92671eea445eb..105f885f2875f4934aa01ecddc3c5bb66d5c0231 100644 (file)
@@ -9,6 +9,7 @@
 // except according to those terms.
 
 // error-pattern: too big for the current
+#![allow(exceeding_bitshifts)]
 
 fn main() {
    let fat : [u8; (1<<61)+(1<<31)] = [0; (1u64<<61) as usize +(1u64<<31) as usize];
diff --git a/src/test/compile-fail/issue-22912.rs b/src/test/compile-fail/issue-22912.rs
new file mode 100644 (file)
index 0000000..f4536ce
--- /dev/null
@@ -0,0 +1,41 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub struct PublicType;
+struct PrivateType;
+
+pub trait PublicTrait {
+    type Item;
+}
+
+trait PrivateTrait {
+    type Item;
+}
+
+impl PublicTrait for PublicType {
+    type Item = PrivateType;  //~ ERROR private type in exported type signature
+}
+
+// OK
+impl PublicTrait for PrivateType {
+    type Item = PrivateType;
+}
+
+// OK
+impl PrivateTrait for PublicType {
+    type Item = PrivateType;
+}
+
+// OK
+impl PrivateTrait for PrivateType {
+    type Item = PrivateType;
+}
+
+fn main() {}
index d0da51373d926fe599ee84da402673be3913f5d9..85298e4c6e096e3a4e19c576a9ff448fb3685aed 100644 (file)
@@ -14,7 +14,9 @@
 fn id<T>(t: T) -> T { t }
 
 fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> {
-    id(box || *v) //~ ERROR cannot infer
+    id(box || *v)
+        //~^ ERROR `v` does not live long enough
+        //~| ERROR cannot move out of borrowed content
 }
 
 fn main() {
index 30d3ab17a463e6622480b0e22fbf7478b7b225a1..08c5cae9f5f79b1ece1168829e748fa7ac4a551c 100644 (file)
@@ -8,13 +8,15 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(rustc_attrs)]
 #![allow(dead_code)]
 
 // Matching against NaN should result in a warning
 
 use std::f64::NAN;
 
-fn main() {
+#[rustc_error]
+fn main() { //~ ERROR compilation successful
     let x = NAN;
     match x {
         NAN => {},
@@ -27,7 +29,3 @@ fn main() {
     };
     //~^^^ WARNING unmatchable NaN in pattern, use the is_nan method in a guard instead
 }
-
-// At least one error is needed so that compilation fails
-#[static_assert]
-static B: bool = false; //~ ERROR static assertion failed
index 954ae8ebc48dd87df4dff656dee302492a309e1c..9c2e8d278ab0b8310db1190bd21c2ee27c824730 100644 (file)
@@ -8,11 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::{int, i8, i16, i32, i64};
+use std::{isize, i8, i16, i32, i64};
 use std::thread;
 
 fn main() {
-    assert!(thread::spawn(move|| { int::MIN / -1; }).join().is_err());
+    assert!(thread::spawn(move|| { isize::MIN / -1; }).join().is_err());
     //~^ ERROR attempted to divide with overflow in a constant expression
     assert!(thread::spawn(move|| { i8::MIN / -1; }).join().is_err());
     //~^ ERROR attempted to divide with overflow in a constant expression
@@ -32,7 +32,7 @@ fn main() {
     //~^ ERROR attempted to divide by zero in a constant expression
     assert!(thread::spawn(move|| { 1i64 / 0; }).join().is_err());
     //~^ ERROR attempted to divide by zero in a constant expression
-    assert!(thread::spawn(move|| { int::MIN % -1; }).join().is_err());
+    assert!(thread::spawn(move|| { isize::MIN % -1; }).join().is_err());
     //~^ ERROR attempted remainder with overflow in a constant expression
     assert!(thread::spawn(move|| { i8::MIN % -1; }).join().is_err());
     //~^ ERROR attempted remainder with overflow in a constant expression
index d85f58edc90d451d7f913936d2bbf8bd9e0b73f2..7a7912b06f88715ac012be4a7536dffef15bd6e6 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(static_assert)]
 #![allow(dead_code)]
 
 #[static_assert]
index 7ea4d1c7507afc5ae434ac63d07a753f10d489ba..cc33d11241757923acc065286c5de077204ca6e9 100644 (file)
@@ -18,7 +18,7 @@ fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> {
 
 fn static_proc(x: &isize) -> Box<FnMut()->(isize) + 'static> {
     // This is illegal, because the region bound on `proc` is 'static.
-    box move|| { *x } //~ ERROR cannot infer
+    box move|| { *x } //~ ERROR captured variable `x` does not outlive the enclosing closure
 }
 
 fn main() { }
index 97b51fdb3250800ce687bac0731d5f1088e76424..c9b378d1df26d433eaaffb4dbfed0f8a381d768c 100644 (file)
@@ -20,9 +20,9 @@ fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> {
 }
 
 fn main() {
-    let cl_box = {
+    let mut cl_box = {
         let mut i = 3;
-        box_it(box || i += 1) //~ ERROR cannot infer
+        box_it(box || i += 1) //~ ERROR `i` does not live long enough
     };
     cl_box.cl.call_mut(());
 }
index abbcd7e45904f1b1170d897654462056bd8d6fc7..fe03ca8353d293d80ad34a538945db97b6e4bbc5 100755 (executable)
 fn main() {
     let bad = {
         let x = 1;
-        let y = &x;
+        let y = &x; //~ ERROR `x` does not live long enough
 
-        thread::scoped(|| { //~ ERROR cannot infer an appropriate lifetime
+        thread::scoped(|| {
+            //~^ ERROR `y` does not live long enough
             let _z = y;
         })
     };
index 349e5f4cb5105c433ab38fb9e4fd52c2bf7c933e..d0cfbfbbcccc21adaea08611ed774546c0eba768 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(static_assert)]
 #![allow(dead_code)]
 
 #[static_assert]
index d5e70205e9536f5ffa22f71232c8f5d0fc8b256c..35f840dab0c0cb6a0d7aa7446def00b272269145 100644 (file)
@@ -8,6 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(static_assert)]
 #![allow(dead_code)]
 
 #[static_assert]
index 59c8495371852c809d39db541b7d4a5f5ede996e..5f4bf0d33be67c0ccbbeaa2bc6c8ab8adf2237eb 100644 (file)
@@ -15,6 +15,6 @@
 fn main() {
     let _f = {
         let x = 0_usize;
-        || x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements
+        || x //~ ERROR `x` does not live long enough
     };
 }
index 964db6e9a4546bfb8b8ad18cfd80dc5af26110eb..5f3744712ccb4c2b5b2049b70533ec4bdfe8e9c7 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn main() {
-    pub use std::uint; //~ ERROR: visibility has no effect
+    pub use std::usize; //~ ERROR: visibility has no effect
     pub struct A; //~ ERROR: visibility has no effect
     pub enum B {} //~ ERROR: visibility has no effect
     pub trait C { //~ ERROR: visibility has no effect
index be4ad0781f272f9ee40110772d5b1b79000ca3e9..c15c4b83828a34bff88dde7f2c43eea5a36535b8 100644 (file)
 
 // error-pattern:index out of bounds: the len is 3 but the index is
 
-use std::uint;
+use std::usize;
 use std::mem::size_of;
 
 fn main() {
     let xs = [1, 2, 3];
-    xs[uint::MAX / size_of::<int>() + 1];
+    xs[usize::MAX / size_of::<isize>() + 1];
 }
index c86f8a38f63c409f32eeb4885a17da54050f398e..2c7c0875227d9baeddb83028f6bf45cf2c6290d8 100644 (file)
 // error-pattern:capacity overflow
 
 use std::collections::hash_map::HashMap;
-use std::uint;
+use std::usize;
 use std::mem::size_of;
 
 fn main() {
-    let threshold = uint::MAX / size_of::<(u64, u64, u64)>();
+    let threshold = usize::MAX / size_of::<(u64, u64, u64)>();
     let mut h = HashMap::<u64, u64>::with_capacity(threshold + 100);
     h.insert(0, 0);
 }
index c16f1f4c842ac1d1afacc0205d28635c7b224d9a..127be1f90d5ff08fc5ed5a5ffa7d625fd0dca84f 100644 (file)
@@ -10,4 +10,5 @@
 
 fn main() {
     let _ = std::old_io::stdin();
+    let _ = std::io::stdin();
 }
index 2f9a0b328b5d492146d76adb077dd3e8585d97db..c6c66f1c75c5432d477fdf980389b348a4bf38e4 100644 (file)
@@ -16,7 +16,7 @@ pub trait Foo {
 }
 
 #[derive(PartialEq)]
-struct Bar;
+pub struct Bar;
 
 impl Foo for int {
     type A = uint;
index 0ec8a3661906f7aaee7806a151ba4718339eb7da..901b3c0d96b010c78b50cd1c8f6ddfc797968722 100644 (file)
@@ -15,7 +15,7 @@ pub trait Foo {
     fn boo(&self) -> <Self as Foo>::A;
 }
 
-struct Bar;
+pub struct Bar;
 
 impl Foo for char {
     type A = Bar;
index fe24ab6bbeb1b453a21c8ac791820c2f10aeac7f..8ae550be3fc6672dfe1ee51acc5df4a7cd33d733 100644 (file)
@@ -16,7 +16,7 @@ pub trait Foo {
 }
 
 #[derive(PartialEq)]
-struct Bar;
+pub struct Bar;
 
 impl Foo for int {
     type A = uint;
index 4a7d6be55a1625fa4730c38d3d43a8feaaf8e83b..f1c747eca68406c82bcb7b97738feeabf9c9dde8 100644 (file)
@@ -8,10 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// ignore-fast
-
 use std::env;
-use std::old_io;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
 use std::str;
 
 fn main() {
@@ -25,17 +25,19 @@ fn main() {
 
 fn parent() {
     let args: Vec<String> = env::args().collect();
-    let mut p = old_io::process::Command::new(&args[0])
-                                     .arg("child").spawn().unwrap();
-    p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap();
+    let mut p = Command::new(&args[0]).arg("child")
+                        .stdout(Stdio::capture())
+                        .stdin(Stdio::capture())
+                        .spawn().unwrap();
+    p.stdin.as_mut().unwrap().write_all(b"test1\ntest2\ntest3").unwrap();
     let out = p.wait_with_output().unwrap();
     assert!(out.status.success());
-    let s = str::from_utf8(&out.output).unwrap();
-    assert_eq!(s, "test1\n\ntest2\n\ntest3\n");
+    let s = str::from_utf8(&out.stdout).unwrap();
+    assert_eq!(s, "test1\ntest2\ntest3\n");
 }
 
 fn child() {
-    let mut stdin = old_io::stdin();
+    let mut stdin = io::stdin();
     for line in stdin.lock().lines() {
         println!("{}", line.unwrap());
     }
index 723db9485ca6ee110b2ced81aad5f69b60f193ae..7e4c464d9aaba7f37c5b650fe07725be6ca85505 100644 (file)
@@ -8,11 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-
-use std::old_io::process;
-use std::old_io::Command;
-use std::old_io;
 use std::env;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
 
 fn main() {
     let args: Vec<String> = env::args().collect();
@@ -21,22 +20,23 @@ fn main() {
     }
 
     test();
-
 }
 
 fn child() {
-    old_io::stdout().write_line("foo").unwrap();
-    old_io::stderr().write_line("bar").unwrap();
-    let mut stdin = old_io::stdin();
-    assert_eq!(stdin.lock().read_line().err().unwrap().kind, old_io::EndOfFile);
+    writeln!(&mut io::stdout(), "foo").unwrap();
+    writeln!(&mut io::stderr(), "bar").unwrap();
+    let mut stdin = io::stdin();
+    let mut s = String::new();
+    stdin.lock().read_line(&mut s).unwrap();
+    assert_eq!(s.len(), 0);
 }
 
 fn test() {
     let args: Vec<String> = env::args().collect();
     let mut p = Command::new(&args[0]).arg("child")
-                                     .stdin(process::Ignored)
-                                     .stdout(process::Ignored)
-                                     .stderr(process::Ignored)
+                                     .stdin(Stdio::capture())
+                                     .stdout(Stdio::capture())
+                                     .stderr(Stdio::capture())
                                      .spawn().unwrap();
     assert!(p.wait().unwrap().success());
 }
index b06c4923c16c1af370ea3f443e1932d4a3a7d475..1ebe3a7f068acc7184c3e334e70876dc919dcaf8 100644 (file)
@@ -8,6 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// DON'T REENABLE THIS UNLESS YOU'VE ACTUALLY FIXED THE UNDERLYING ISSUE
+// ignore-android seems to block forever
 
 #![forbid(warnings)]
 
 // A var moved into a proc, that has a mutable loan path should
 // not trigger a misleading unused_mut warning.
 
+use std::io::prelude::*;
 use std::thread;
 
 pub fn main() {
-    let mut stdin = std::old_io::stdin();
+    let mut stdin = std::io::stdin();
     thread::spawn(move|| {
-        let _ = stdin.read_to_end();
-    });
+        let mut v = Vec::new();
+        let _ = stdin.read_to_end(&mut v);
+    }).join().ok().unwrap();
 }
index dd1cfb5e342832e9b50f87bae8687cfd0aaeae18..d4c32f42188bb0b4934f073c2c21955d3ecb4c7a 100644 (file)
 #![allow(unknown_features)]
 #![feature(box_syntax)]
 
-use std::old_io;
+use std::io::{self, Write};
 
-fn f(wr: &mut Writer) {
-    wr.write_str("hello").ok().expect("failed");
+fn f(wr: &mut Write) {
+    wr.write_all(b"hello").ok().expect("failed");
 }
 
 fn main() {
-    let mut wr = box old_io::stdout() as Box<Writer + 'static>;
+    let mut wr = box io::stdout() as Box<Write>;
     f(&mut wr);
 }
diff --git a/src/test/run-pass/issue-22777.rs b/src/test/run-pass/issue-22777.rs
new file mode 100644 (file)
index 0000000..cab33be
--- /dev/null
@@ -0,0 +1,55 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This test is reduced from libsyntax.  It is just checking that we
+// can successfully deal with a "deep" structure, which the drop-check
+// was hitting a recursion limit on at one point.
+
+#![allow(non_camel_case_types)]
+
+pub fn noop_fold_impl_item() -> SmallVector<ImplItem> {
+    loop  { }
+}
+
+pub struct SmallVector<T>(P<T>);
+pub struct ImplItem(P<S01_Method>);
+
+struct P<T>(Box<T>);
+
+struct S01_Method(P<S02_Generics>);
+struct S02_Generics(P<S03_TyParam>);
+struct S03_TyParam(P<S04_TyParamBound>);
+struct S04_TyParamBound(S05_PolyTraitRef);
+struct S05_PolyTraitRef(S06_TraitRef);
+struct S06_TraitRef(S07_Path);
+struct S07_Path(Vec<S08_PathSegment>);
+struct S08_PathSegment(S09_PathParameters);
+struct S09_PathParameters(P<S10_ParenthesizedParameterData>);
+struct S10_ParenthesizedParameterData(Option<P<S11_Ty>>);
+struct S11_Ty(P<S12_Expr>);
+struct S12_Expr(P<S13_Block>);
+struct S13_Block(Vec<P<S14_Stmt>>);
+struct S14_Stmt(P<S15_Decl>);
+struct S15_Decl(P<S16_Local>);
+struct S16_Local(P<S17_Pat>);
+struct S17_Pat(P<S18_Mac>);
+struct S18_Mac(Vec<P<S19_TokenTree>>);
+struct S19_TokenTree(P<S20_Token>);
+struct S20_Token(P<S21_Nonterminal>);
+struct S21_Nonterminal(P<S22_Item>);
+struct S22_Item(P<S23_EnumDef>);
+struct S23_EnumDef(Vec<P<S24_Variant>>);
+struct S24_Variant(P<S25_VariantKind>);
+struct S25_VariantKind(P<S26_StructDef>);
+struct S26_StructDef(Vec<P<S27_StructField>>);
+struct S27_StructField(P<S28_StructFieldKind>);
+struct S28_StructFieldKind;
+
+pub fn main() {}
index 28ab3c3ef12537956feed46fcdfdc587f12bde1b..074bbf270fd7e26f87342ceca320fd7ae71ed3e7 100644 (file)
@@ -8,9 +8,9 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use std::old_io;
+use std::io;
 
 pub fn main() {
-    let stdout = &mut old_io::stdout() as &mut old_io::Writer;
+    let stdout = &mut io::stdout() as &mut io::Write;
     stdout.write(b"Hello!");
 }
index 521aef4b5ba5b0b02bebe2e30381d75fc3d8c512..2752fc88b456b2b45c171d1a19bdf4d27d4f768d 100644 (file)
@@ -10,6 +10,8 @@
 
 // ignore-pretty - token trees can't pretty print
 
+#![feature(custom_attribute)]
+
 macro_rules! compiles_fine {
     (#[$at:meta]) => {
         // test that the different types of attributes work
index 017784990f4178ece9fcc4dff70c6cbca120b35e..3e5f84fa26fe075769334e213e478b5acf3234e5 100644 (file)
 // non-ASCII characters.  The child process ensures all the strings are
 // intact.
 
-use std::old_io;
-use std::old_io::fs;
-use std::old_io::Command;
+use std::io::prelude::*;
+use std::io;
+use std::fs;
+use std::process::Command;
 use std::os;
 use std::env;
-use std::old_path::Path;
+use std::path::{Path, PathBuf};
 
 fn main() {
     let my_args = env::args().collect::<Vec<_>>();
-    let my_cwd  = os::getcwd().unwrap();
+    let my_cwd  = PathBuf::new(os::getcwd().unwrap().as_str().unwrap());
     let my_env  = env::vars().collect::<Vec<_>>();
-    let my_path = Path::new(os::self_exe_name().unwrap());
-    let my_dir  = my_path.dir_path();
-    let my_ext  = my_path.extension_str().unwrap_or("");
+    let my_path = PathBuf::new(os::self_exe_name().unwrap().as_str().unwrap());
+    let my_dir  = my_path.parent().unwrap();
+    let my_ext  = my_path.extension().and_then(|s| s.to_str()).unwrap_or("");
 
     // some non-ASCII characters
-    let blah       = "\u03c0\u042f\u97f3\u00e6\u221e";
+    let blah       = "\u{3c0}\u{42f}\u{97f3}\u{e6}\u{221e}";
 
     let child_name = "child";
     let child_dir  = format!("process-spawn-with-unicode-params-{}", blah);
 
     // parameters sent to child / expected to be received from parent
     let arg = blah;
-    let cwd = my_dir.join(Path::new(child_dir.clone()));
+    let cwd = my_dir.join(&child_dir);
     let env = ("RUST_TEST_PROC_SPAWN_UNICODE".to_string(), blah.to_string());
 
     // am I the parent or the child?
@@ -47,24 +48,22 @@ fn main() {
 
         let child_filestem = Path::new(child_name);
         let child_filename = child_filestem.with_extension(my_ext);
-        let child_path     = cwd.join(child_filename);
+        let child_path     = cwd.join(&child_filename);
 
         // make a separate directory for the child
-        drop(fs::mkdir(&cwd, old_io::USER_RWX).is_ok());
-        assert!(fs::copy(&my_path, &child_path).is_ok());
-        let mut my_env = my_env;
-        my_env.push(env);
+        let _ = fs::create_dir(&cwd);
+        fs::copy(&my_path, &child_path).unwrap();
 
         // run child
         let p = Command::new(&child_path)
                         .arg(arg)
-                        .cwd(&cwd)
-                        .env_set_all(&my_env)
+                        .current_dir(&cwd)
+                        .env(&env.0, &env.1)
                         .spawn().unwrap().wait_with_output().unwrap();
 
         // display the output
-        assert!(old_io::stdout().write(&p.output).is_ok());
-        assert!(old_io::stderr().write(&p.error).is_ok());
+        io::stdout().write_all(&p.stdout).unwrap();
+        io::stderr().write_all(&p.stderr).unwrap();
 
         // make sure the child succeeded
         assert!(p.status.success());
@@ -72,7 +71,7 @@ fn main() {
     } else {                            // child
 
         // check working directory (don't try to compare with `cwd` here!)
-        assert!(my_cwd.ends_with_path(&Path::new(child_dir)));
+        assert!(my_cwd.ends_with(&child_dir));
 
         // check arguments
         assert_eq!(&*my_args[1], arg);
index f8fd81b9365159f6bcc21f72e46515172385720f..f650e56bb6b772ccf34ea72cff50b1ce21dbec86 100644 (file)
@@ -8,6 +8,8 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+#![feature(static_assert)]
+
 #[static_assert]
 static b: bool = true;
 
index 08d39e58b7ce292c2b849b8c809a226a470dfc00..a6f4b8299cb6898284ffa9e784b610173aad9cb7 100644 (file)
@@ -53,7 +53,7 @@ fn drop(&mut self) {
 }
 
 pub fn main() {
-    assert!(MAX_LEN <= std::usize::BITS);
+    assert!(MAX_LEN <= std::usize::BITS as usize);
     // len can't go above 64.
     for len in 2..MAX_LEN {
         for _ in 0..REPEATS {