diff options
1614 files changed, 15765 insertions, 14407 deletions
diff --git a/README.md b/README.md index f60629faef1..e858e91773b 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,14 @@ documentation. ## Quick Start 1. Download a [binary installer][installer] for your platform. -2. Read the [guide]. +2. Read [The Rust Programming Language][trpl]. 3. Enjoy! > ***Note:*** Windows users can read the detailed > [using Rust on Windows][win-wiki] notes on the wiki. [installer]: http://www.rust-lang.org/install.html -[guide]: http://doc.rust-lang.org/guide.html +[trpl]: http://doc.rust-lang.org/book/index.html [win-wiki]: https://github.com/rust-lang/rust/wiki/Using-Rust-on-Windows ## Building from Source @@ -53,7 +53,7 @@ documentation. When complete, `make install` will place several programs into `/usr/local/bin`: `rustc`, the Rust compiler, and `rustdoc`, the API-documentation tool. -3. Read the [guide]. +3. Read [The Rust Programming Language][trpl]. 4. Enjoy! ### Building on Windows @@ -75,7 +75,7 @@ To easily build on windows we can use [MSYS2](http://sourceforge.net/projects/ms [repo]: https://github.com/rust-lang/rust [tarball]: https://static.rust-lang.org/dist/rust-nightly.tar.gz -[guide]: http://doc.rust-lang.org/guide.html +[trpl]: http://doc.rust-lang.org/book/index.html ## Notes diff --git a/RELEASES.md b/RELEASES.md index f7c385cbe7c..b75fde6fd32 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -19,8 +19,10 @@ Version 1.0.0-alpha (January 2015) distribution into the Cargo ecosystem so they can evolve separately and don't need to be stabilized as quickly, including 'time', 'getopts', 'num', 'regex', and 'term'. - * Documentation continues to be expanded with more guides, more - API coverage and more examples. + * Documentation continues to be expanded with more API coverage, more + examples, and more in-depth explanations. The guides have been + consolidated into [The Rust Programming Language][trpl]. + * "Rust By Example" is now maintained by the Rust team. * All official Rust binary installers now come with [Cargo], the Rust package manager. @@ -179,6 +181,7 @@ Version 1.0.0-alpha (January 2015) [objsafe]: https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md [assoc]: https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md [ints]: https://github.com/rust-lang/rfcs/pull/544#issuecomment-68760871 +[trpl]: http://doc.rust-lang.org/book/index.html Version 0.12.0 (October 2014) ----------------------------- diff --git a/configure b/configure index ea9320c901b..d0b99b12fd9 100755 --- a/configure +++ b/configure @@ -599,6 +599,18 @@ then fi putvar CFG_RELEASE_CHANNEL +# A magic value that allows the compiler to use unstable features +# during the bootstrap even when doing so would normally be an error +# because of feature staging or because the build turns on +# warnings-as-errors and unstable features default to warnings. The +# build has to match this key in an env var. Meant to be a mild +# deterrent from users just turning on unstable features on the stable +# channel. +# Basing CFG_BOOTSTRAP_KEY on CFG_BOOTSTRAP_KEY lets it get picked up +# during a Makefile reconfig. +CFG_BOOTSTRAP_KEY="${CFG_BOOTSTRAP_KEY-`date +%N`}" +putvar CFG_BOOTSTRAP_KEY + step_msg "looking for build programs" probe_need CFG_PERL perl @@ -1043,18 +1055,6 @@ do make_dir $h/test/debuginfo-gdb make_dir $h/test/debuginfo-lldb make_dir $h/test/codegen - make_dir $h/test/doc-guide - make_dir $h/test/doc-guide-ffi - make_dir $h/test/doc-guide-runtime - make_dir $h/test/doc-guide-macros - make_dir $h/test/doc-guide-ownership - make_dir $h/test/doc-guide-pointers - make_dir $h/test/doc-guide-container - make_dir $h/test/doc-guide-tasks - make_dir $h/test/doc-guide-plugin - make_dir $h/test/doc-guide-crates - make_dir $h/test/doc-guide-error-handling - make_dir $h/test/doc-reference done # Configure submodules diff --git a/mk/crates.mk b/mk/crates.mk index cea92e19a26..5b8772c4e0a 100644 --- a/mk/crates.mk +++ b/mk/crates.mk @@ -57,7 +57,7 @@ RUSTC_CRATES := rustc rustc_typeck rustc_borrowck rustc_resolve rustc_driver \ rustc_trans rustc_back rustc_llvm HOST_CRATES := syntax $(RUSTC_CRATES) rustdoc fmt_macros CRATES := $(TARGET_CRATES) $(HOST_CRATES) -TOOLS := compiletest rustdoc rustc +TOOLS := compiletest rustdoc rustc rustbook DEPS_core := DEPS_libc := core @@ -99,9 +99,11 @@ DEPS_fmt_macros = std TOOL_DEPS_compiletest := test getopts TOOL_DEPS_rustdoc := rustdoc TOOL_DEPS_rustc := rustc_driver +TOOL_DEPS_rustbook := std regex rustdoc TOOL_SOURCE_compiletest := $(S)src/compiletest/compiletest.rs TOOL_SOURCE_rustdoc := $(S)src/driver/driver.rs TOOL_SOURCE_rustc := $(S)src/driver/driver.rs +TOOL_SOURCE_rustbook := $(S)src/rustbook/main.rs ONLY_RLIB_core := 1 ONLY_RLIB_libc := 1 diff --git a/mk/dist.mk b/mk/dist.mk index 8347238cf20..05af3f21232 100644 --- a/mk/dist.mk +++ b/mk/dist.mk @@ -59,6 +59,7 @@ PKG_FILES := \ rustllvm \ snapshots.txt \ rust-installer \ + rustbook \ test) \ $(PKG_GITMODULES) \ $(filter-out config.stamp, \ diff --git a/mk/docs.mk b/mk/docs.mk index 274598feada..1104c3eb6db 100644 --- a/mk/docs.mk +++ b/mk/docs.mk @@ -9,7 +9,7 @@ # except according to those terms. ###################################################################### -# The various pieces of standalone documentation: guides, manual, etc +# The various pieces of standalone documentation. # # The DOCS variable is their names (with no file extension). # @@ -25,13 +25,11 @@ # L10N_LANGS are the languages for which the docs have been # translated. ###################################################################### -DOCS := index intro tutorial guide guide-ffi guide-macros guide-ownership \ - guide-tasks guide-container guide-pointers guide-testing \ - guide-plugin guide-crates complement-bugreport guide-error-handling \ - complement-lang-faq complement-design-faq complement-project-faq \ - rustdoc guide-unsafe guide-strings reference +DOCS := index intro tutorial complement-bugreport \ + complement-lang-faq complement-design-faq complement-project-faq \ + rustdoc reference -PDF_DOCS := guide reference +PDF_DOCS := reference RUSTDOC_DEPS_reference := doc/full-toc.inc RUSTDOC_FLAGS_reference := --html-in-header=doc/full-toc.inc @@ -61,9 +59,15 @@ RUSTDOC_EXE = $(HBIN2_H_$(CFG_BUILD))/rustdoc$(X_$(CFG_BUILD)) # ./configure RUSTDOC = $(RPATH_VAR2_T_$(CFG_BUILD)_H_$(CFG_BUILD)) $(RUSTDOC_EXE) +# The rustbook executable... +RUSTBOOK_EXE = $(HBIN2_H_$(CFG_BUILD))/rustbook$(X_$(CFG_BUILD)) +# ...with rpath included in case --disable-rpath was provided to +# ./configure +RUSTBOOK = $(RPATH_VAR2_T_$(CFG_BUILD)_H_$(CFG_BUILD)) $(RUSTBOOK_EXE) + D := $(S)src/doc -DOC_TARGETS := +DOC_TARGETS := trpl COMPILER_DOC_TARGETS := DOC_L10N_TARGETS := @@ -270,3 +274,9 @@ endif docs: $(DOC_TARGETS) compiler-docs: $(COMPILER_DOC_TARGETS) + +trpl: doc/book/index.html + +doc/book/index.html: $(RUSTBOOK_EXE) $(wildcard $(S)/src/doc/trpl/*.md) + $(Q)rm -rf doc/book + $(Q)$(RUSTBOOK) build $(S)src/doc/trpl doc/book diff --git a/mk/main.mk b/mk/main.mk index a97e68af59b..99aecc34be9 100644 --- a/mk/main.mk +++ b/mk/main.mk @@ -25,11 +25,13 @@ ifeq ($(CFG_RELEASE_CHANNEL),stable) CFG_RELEASE=$(CFG_RELEASE_NUM) # This is the string used in dist artifact file names, e.g. "0.12.0", "nightly" CFG_PACKAGE_VERS=$(CFG_RELEASE_NUM) +CFG_DISABLE_UNSTABLE_FEATURES=1 endif ifeq ($(CFG_RELEASE_CHANNEL),beta) # The beta channel is temporarily called 'alpha' CFG_RELEASE=$(CFG_RELEASE_NUM)-alpha$(CFG_BETA_CYCLE) CFG_PACKAGE_VERS=$(CFG_RELEASE_NUM)-alpha$(CFG_BETA_CYCLE) +CFG_DISABLE_UNSTABLE_FEATURES=1 endif ifeq ($(CFG_RELEASE_CHANNEL),nightly) CFG_RELEASE=$(CFG_RELEASE_NUM)-nightly @@ -121,11 +123,9 @@ CFG_JEMALLOC_FLAGS += $(JEMALLOC_FLAGS) ifdef CFG_DISABLE_DEBUG CFG_RUSTC_FLAGS += --cfg ndebug - CFG_GCCISH_CFLAGS += -DRUST_NDEBUG else $(info cfg: enabling more debugging (CFG_ENABLE_DEBUG)) CFG_RUSTC_FLAGS += --cfg debug - CFG_GCCISH_CFLAGS += -DRUST_DEBUG endif ifdef SAVE_TEMPS @@ -319,11 +319,20 @@ export CFG_VERSION_WIN export CFG_RELEASE export CFG_PACKAGE_NAME export CFG_BUILD +export CFG_RELEASE_CHANNEL export CFG_LLVM_ROOT export CFG_PREFIX export CFG_LIBDIR export CFG_LIBDIR_RELATIVE export CFG_DISABLE_INJECT_STD_VERSION +ifdef CFG_DISABLE_UNSTABLE_FEATURES +CFG_INFO := $(info cfg: disabling unstable features (CFG_DISABLE_UNSTABLE_FEATURES)) +# Turn on feature-staging +export CFG_DISABLE_UNSTABLE_FEATURES +endif +# Subvert unstable feature lints to do the self-build +export CFG_BOOTSTRAP_KEY +export RUSTC_BOOTSTRAP_KEY:=$(CFG_BOOTSTRAP_KEY) ###################################################################### # Per-stage targets and runner diff --git a/mk/prepare.mk b/mk/prepare.mk index 52fbbef81bd..6a5daeb6909 100644 --- a/mk/prepare.mk +++ b/mk/prepare.mk @@ -70,7 +70,7 @@ define PREPARE_MAN $(Q)$(PREPARE_MAN_CMD) $(PREPARE_SOURCE_MAN_DIR)/$(1) $(PREPARE_DEST_MAN_DIR)/$(1) endef -PREPARE_TOOLS = $(filter-out compiletest, $(TOOLS)) +PREPARE_TOOLS = $(filter-out compiletest rustbook, $(TOOLS)) # $(1) is tool diff --git a/mk/tests.mk b/mk/tests.mk index 714a9f89005..c8c4beb1153 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -147,6 +147,17 @@ else CFG_ADB_TEST_DIR= endif +# $(1) - name of doc test +# $(2) - file of the test +define DOCTEST +DOC_NAMES := $$(DOC_NAMES) $(1) +DOCFILE_$(1) := $(2) +endef + +$(foreach doc,$(DOCS), \ + $(eval $(call DOCTEST,md-$(doc),$(S)src/doc/$(doc).md))) +$(foreach file,$(wildcard $(S)src/doc/trpl/*.md), \ + $(eval $(call DOCTEST,$(file:$(S)src/doc/trpl/%.md=trpl-%),$(file)))) ###################################################################### # Main test targets @@ -292,6 +303,7 @@ tidy: | grep '^$(S)src/rust-installer' -v \ | xargs $(CFG_PYTHON) $(S)src/etc/check-binaries.py + endif @@ -339,8 +351,8 @@ check-stage$(1)-T-$(2)-H-$(3)-doc-crates-exec: \ check-stage$(1)-T-$(2)-H-$(3)-doc-crate-$$(crate)-exec) check-stage$(1)-T-$(2)-H-$(3)-doc-exec: \ - $$(foreach docname,$$(DOCS), \ - check-stage$(1)-T-$(2)-H-$(3)-doc-$$(docname)-exec) + $$(foreach docname,$$(DOC_NAMES), \ + check-stage$(1)-T-$(2)-H-$(3)-doc-$$(docname)-exec) \ check-stage$(1)-T-$(2)-H-$(3)-pretty-exec: \ check-stage$(1)-T-$(2)-H-$(3)-pretty-rpass-exec \ @@ -795,17 +807,18 @@ check-stage$(1)-T-$(2)-H-$(3)-doc-$(4)-exec: $$(call TEST_OK_FILE,$(1),$(2),$(3) # rustdoc etc. ifeq ($(NO_REBUILD),) DOCTESTDEP_$(1)_$(2)_$(3)_$(4) = \ - $$(D)/$(4).md \ + $$(DOCFILE_$(4)) \ $$(TEST_SREQ$(1)_T_$(2)_H_$(3)) \ $$(RUSTDOC_EXE_$(1)_T_$(2)_H_$(3)) else -DOCTESTDEP_$(1)_$(2)_$(3)_$(4) = $$(D)/$(4).md +DOCTESTDEP_$(1)_$(2)_$(3)_$(4) = $$(DOCFILE_$(4)) endif ifeq ($(2),$$(CFG_BUILD)) $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)): $$(DOCTESTDEP_$(1)_$(2)_$(3)_$(4)) @$$(call E, run doc-$(4) [$(2)]) - $$(Q)$$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --cfg dox --test $$< --test-args "$$(TESTARGS)" && touch $$@ + $$(Q)$$(RUSTDOC_$(1)_T_$(2)_H_$(3)) --cfg dox --test $$< \ + --test-args "$$(TESTARGS)" && touch $$@ else $$(call TEST_OK_FILE,$(1),$(2),$(3),doc-$(4)): touch $$@ @@ -815,7 +828,7 @@ endef $(foreach host,$(CFG_HOST), \ $(foreach target,$(CFG_TARGET), \ $(foreach stage,$(STAGES), \ - $(foreach docname,$(DOCS), \ + $(foreach docname,$(DOC_NAMES), \ $(eval $(call DEF_DOC_TEST,$(stage),$(target),$(host),$(docname))))))) # Crates @@ -877,7 +890,7 @@ TEST_GROUPS = \ debuginfo-lldb \ codegen \ doc \ - $(foreach docname,$(DOCS),doc-$(docname)) \ + $(foreach docname,$(DOC_NAMES),doc-$(docname)) \ pretty \ pretty-rpass \ pretty-rpass-valgrind \ @@ -946,7 +959,7 @@ $(foreach stage,$(STAGES), \ $(eval $(call DEF_CHECK_FOR_STAGE_AND_HOSTS_AND_GROUP,$(stage),$(host),$(group)))))) define DEF_CHECK_DOC_FOR_STAGE -check-stage$(1)-docs: $$(foreach docname,$$(DOCS), \ +check-stage$(1)-docs: $$(foreach docname,$$(DOC_NAMES), \ check-stage$(1)-T-$$(CFG_BUILD)-H-$$(CFG_BUILD)-doc-$$(docname)) \ $$(foreach crate,$$(TEST_DOC_CRATES), \ check-stage$(1)-T-$$(CFG_BUILD)-H-$$(CFG_BUILD)-doc-crate-$$(crate)) diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index e2420b0a220..802fb05796d 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -9,7 +9,10 @@ // except according to those terms. #![crate_type = "bin"] +#![allow(unknown_features)] #![feature(slicing_syntax, unboxed_closures)] +#![feature(box_syntax)] +#![feature(int_uint)] #![deny(warnings)] diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index 2413a001ee8..374fd2e3ef0 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -42,6 +42,8 @@ pub struct TestProps { pub pretty_compare_only: bool, // Patterns which must not appear in the output of a cfail test. pub forbid_output: Vec<String>, + // Ignore errors which originate from a command line span + pub ignore_command_line: bool, } // Load any test directives embedded in the file @@ -60,6 +62,8 @@ pub fn load_props(testfile: &Path) -> TestProps { let mut pretty_mode = None; let mut pretty_compare_only = false; let mut forbid_output = Vec::new(); + let mut ignore_command_line = false; + iter_header(testfile, |ln| { match parse_error_pattern(ln) { Some(ep) => error_patterns.push(ep), @@ -102,6 +106,10 @@ pub fn load_props(testfile: &Path) -> TestProps { pretty_compare_only = parse_pretty_compare_only(ln); } + if !ignore_command_line { + ignore_command_line = parse_ignore_command_line(ln); + } + match parse_aux_build(ln) { Some(ab) => { aux_builds.push(ab); } None => {} @@ -140,6 +148,7 @@ pub fn load_props(testfile: &Path) -> TestProps { pretty_mode: pretty_mode.unwrap_or("normal".to_string()), pretty_compare_only: pretty_compare_only, forbid_output: forbid_output, + ignore_command_line: ignore_command_line, } } @@ -291,6 +300,10 @@ fn parse_pretty_compare_only(line: &str) -> bool { parse_name_directive(line, "pretty-compare-only") } +fn parse_ignore_command_line(line: &str) -> bool { + parse_name_directive(line, "ignore-command-line") +} + fn parse_exec_env(line: &str) -> Option<(String, String)> { parse_name_value_directive(line, "exec-env").map(|nv| { // nv is either FOO or FOO=BAR diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index f8e2ba4828f..a97d4913440 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -104,7 +104,7 @@ fn run_cfail_test(config: &Config, props: &TestProps, testfile: &Path) { if !props.error_patterns.is_empty() { fatal("both error pattern and expected errors specified"); } - check_expected_errors(expected_errors, testfile, &proc_res); + check_expected_errors(props, expected_errors, testfile, &proc_res); } else { check_error_patterns(props, testfile, output_to_check.as_slice(), &proc_res); } @@ -908,8 +908,7 @@ fn check_error_patterns(props: &TestProps, } if done { return; } - let missing_patterns = - props.error_patterns.index(&(next_err_idx..)); + let missing_patterns = &props.error_patterns[next_err_idx..]; if missing_patterns.len() == 1u { fatal_proc_rec(format!("error pattern '{}' not found!", missing_patterns[0]).as_slice(), @@ -942,7 +941,8 @@ fn check_forbid_output(props: &TestProps, } } -fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> , +fn check_expected_errors(props: &TestProps, + expected_errors: Vec<errors::ExpectedError> , testfile: &Path, proc_res: &ProcRes) { @@ -997,6 +997,11 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> , was_expected = true; } + if line.starts_with("<command line option>") && + props.ignore_command_line { + was_expected = true; + } + if !was_expected && is_compiler_error_or_warning(line) { fatal_proc_rec(format!("unexpected compiler error or warning: '{}'", line).as_slice(), diff --git a/src/doc/footer.inc b/src/doc/footer.inc index 4e7d60586f2..f32f2fd443f 100644 --- a/src/doc/footer.inc +++ b/src/doc/footer.inc @@ -1,5 +1,5 @@ <footer><p> -Copyright © 2011-2014 The Rust Project Developers. Licensed under the +Copyright © 2011-2015 The Rust Project Developers. Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a> or the <a href="http://opensource.org/licenses/MIT">MIT license</a>, at your option. </p><p> diff --git a/src/doc/guide-container.md b/src/doc/guide-container.md deleted file mode 100644 index e9bda17f4bc..00000000000 --- a/src/doc/guide-container.md +++ /dev/null @@ -1,6 +0,0 @@ -% The Rust Containers and Iterators Guide - -This guide has been removed, with no direct replacement. - -You may enjoy reading the [iterator](std/iter/index.html) and -[collections](std/collections/index.html) documentation. diff --git a/src/doc/guide-strings.md b/src/doc/guide-strings.md deleted file mode 100644 index 43cc8483bce..00000000000 --- a/src/doc/guide-strings.md +++ /dev/null @@ -1,308 +0,0 @@ -% The Guide to Rust Strings - -Strings are an important concept to master in any programming language. If you -come from a managed language background, you may be surprised at the complexity -of string handling in a systems programming language. Efficient access and -allocation of memory for a dynamically sized structure involves a lot of -details. Luckily, Rust has lots of tools to help us here. - -A **string** is a sequence of unicode scalar values encoded as a stream of -UTF-8 bytes. All strings are guaranteed to be validly-encoded UTF-8 sequences. -Additionally, strings are not null-terminated and can contain null bytes. - -Rust has two main types of strings: `&str` and `String`. - -# &str - -The first kind is a `&str`. This is pronounced a 'string slice'. -String literals are of the type `&str`: - -```{rust} -let string = "Hello there."; -``` - -Like any Rust type, string slices have an associated lifetime. A string literal -is a `&'static str`. A string slice can be written without an explicit -lifetime in many cases, such as in function arguments. In these cases the -lifetime will be inferred: - -```{rust} -fn takes_slice(slice: &str) { - println!("Got: {}", slice); -} -``` - -Like vector slices, string slices are simply a pointer plus a length. This -means that they're a 'view' into an already-allocated string, such as a -`&'static str` or a `String`. - -# String - -A `String` is a heap-allocated string. This string is growable, and is also -guaranteed to be UTF-8. - -```{rust} -let mut s = "Hello".to_string(); -println!("{}", s); - -s.push_str(", world."); -println!("{}", s); -``` - -You can coerce a `String` into a `&str` with the `as_slice()` method: - -```{rust} -fn takes_slice(slice: &str) { - println!("Got: {}", slice); -} - -fn main() { - let s = "Hello".to_string(); - takes_slice(s.as_slice()); -} -``` - -You can also get a `&str` from a stack-allocated array of bytes: - -```{rust} -use std::str; - -let x: &[u8] = &[b'a', b'b']; -let stack_str: &str = str::from_utf8(x).unwrap(); -``` - -# Best Practices - -## `String` vs. `&str` - -In general, you should prefer `String` when you need ownership, and `&str` when -you just need to borrow a string. This is very similar to using `Vec<T>` vs. `&[T]`, -and `T` vs `&T` in general. - -This means starting off with this: - -```{rust,ignore} -fn foo(s: &str) { -``` - -and only moving to this: - -```{rust,ignore} -fn foo(s: String) { -``` - -If you have good reason. It's not polite to hold on to ownership you don't -need, and it can make your lifetimes more complex. - -## Generic functions - -To write a function that's generic over types of strings, use `&str`. - -```{rust} -fn some_string_length(x: &str) -> uint { - x.len() -} - -fn main() { - let s = "Hello, world"; - - println!("{}", some_string_length(s)); - - let s = "Hello, world".to_string(); - - println!("{}", some_string_length(s.as_slice())); -} -``` - -Both of these lines will print `12`. - -## Comparisons - -To compare a String to a constant string, prefer `as_slice()`... - -```{rust} -fn compare(x: String) { - if x.as_slice() == "Hello" { - println!("yes"); - } -} -``` - -... over `to_string()`: - -```{rust} -fn compare(x: String) { - if x == "Hello".to_string() { - println!("yes"); - } -} -``` - -Converting a `String` to a `&str` is cheap, but converting the `&str` to a -`String` involves an allocation. - -## Indexing strings - -You may be tempted to try to access a certain character of a `String`, like -this: - -```{rust,ignore} -let s = "hello".to_string(); - -println!("{}", s[0]); -``` - -This does not compile. This is on purpose. In the world of UTF-8, direct -indexing is basically never what you want to do. The reason is that each -character can be a variable number of bytes. This means that you have to iterate -through the characters anyway, which is an O(n) operation. - -There's 3 basic levels of unicode (and its encodings): - -- code units, the underlying data type used to store everything -- code points/unicode scalar values (char) -- graphemes (visible characters) - -Rust provides iterators for each of these situations: - -- `.bytes()` will iterate over the underlying bytes -- `.chars()` will iterate over the code points -- `.graphemes()` will iterate over each grapheme - -Usually, the `graphemes()` method on `&str` is what you want: - -```{rust} -let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé"; - -for l in s.graphemes(true) { - println!("{}", l); -} -``` - -This prints: - -```{text} -u͔ -n͈̰̎ -i̙̮͚̦ -c͚̉ -o̼̩̰͗ -d͔̆̓ͥ -é -``` - -Note that `l` has the type `&str` here, since a single grapheme can consist of -multiple codepoints, so a `char` wouldn't be appropriate. - -This will print out each visible character in turn, as you'd expect: first "u͔", then -"n͈̰̎", etc. If you wanted each individual codepoint of each grapheme, you can use `.chars()`: - -```{rust} -let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé"; - -for l in s.chars() { - println!("{}", l); -} -``` - -This prints: - -```{text} -u -͔ -n -̎ -͈ -̰ -i -̙ -̮ -͚ -̦ -c -̉ -͚ -o -͗ -̼ -̩ -̰ -d -̆ -̓ -ͥ -͔ -e -́ -``` - -You can see how some of them are combining characters, and therefore the output -looks a bit odd. - -If you want the individual byte representation of each codepoint, you can use -`.bytes()`: - -```{rust} -let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé"; - -for l in s.bytes() { - println!("{}", l); -} -``` - -This will print: - -```{text} -117 -205 -148 -110 -204 -142 -205 -136 -204 -176 -105 -204 -153 -204 -174 -205 -154 -204 -166 -99 -204 -137 -205 -154 -111 -205 -151 -204 -188 -204 -169 -204 -176 -100 -204 -134 -205 -131 -205 -165 -205 -148 -101 -204 -129 -``` - -Many more bytes than graphemes! - -# Other Documentation - -* [the `&str` API documentation](std/str/index.html) -* [the `String` API documentation](std/string/index.html) diff --git a/src/doc/guide.md b/src/doc/guide.md deleted file mode 100644 index f736ef821fa..00000000000 --- a/src/doc/guide.md +++ /dev/null @@ -1,5516 +0,0 @@ -% The Rust Guide - -Hey there! Welcome to the Rust guide. This is the place to be if you'd like to -learn how to program in Rust. Rust is a systems programming language with a -focus on "high-level, bare-metal programming": the lowest level control a -programming language can give you, but with zero-cost, higher level -abstractions, because people aren't computers. We really think Rust is -something special, and we hope you do too. - -To show you how to get going with Rust, we're going to write the traditional -"Hello, World!" program. Next, we'll introduce you to a tool that's useful for -writing real-world Rust programs and libraries: "Cargo." After that, we'll talk -about the basics of Rust, write a little program to try them out, and then learn -more advanced things. - -Sound good? Let's go! - -# Installing Rust - -The first step to using Rust is to install it! There are a number of ways to -install Rust, but the easiest is to use the `rustup` script. If you're on -Linux or a Mac, all you need to do is this (note that you don't need to type -in the `$`s, they just indicate the start of each command): - -```bash -$ curl -L https://static.rust-lang.org/rustup.sh | sudo sh -``` - -If you're concerned about the [potential insecurity](http://curlpipesh.tumblr.com/) of using `curl | sudo sh`, -please keep reading and see our disclaimer below. And feel free to use a two-step version of the installation and examine our installation script: - -```bash -$ curl -L https://static.rust-lang.org/rustup.sh -O -$ sudo sh rustup.sh -``` - -If you're on Windows, please download either the [32-bit -installer](https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.exe) -or the [64-bit -installer](https://static.rust-lang.org/dist/rust-nightly-x86_64-pc-windows-gnu.exe) -and run it. - -If you decide you don't want Rust anymore, we'll be a bit sad, but that's okay. -Not every programming language is great for everyone. Just pass an argument to -the script: - -```bash -$ curl -s https://static.rust-lang.org/rustup.sh | sudo sh -s -- --uninstall -``` - -If you used the Windows installer, just re-run the `.exe` and it will give you -an uninstall option. - -You can re-run this script any time you want to update Rust. Which, at this -point, is often. Rust is still pre-1.0, and so people assume that you're using -a very recent Rust. - -This brings me to one other point: some people, and somewhat rightfully so, get -very upset when we tell you to `curl | sudo sh`. And they should be! Basically, -when you do this, you are trusting that the good people who maintain Rust -aren't going to hack your computer and do bad things. That's a good instinct! -If you're one of those people, please check out the documentation on [building -Rust from Source](https://github.com/rust-lang/rust#building-from-source), or -[the official binary downloads](http://www.rust-lang.org/install.html). And we -promise that this method will not be the way to install Rust forever: it's just -the easiest way to keep people updated while Rust is in its alpha state. - -Oh, we should also mention the officially supported platforms: - -* Windows (7, 8, Server 2008 R2) -* Linux (2.6.18 or later, various distributions), x86 and x86-64 -* OSX 10.7 (Lion) or greater, x86 and x86-64 - -We extensively test Rust on these platforms, and a few others, too, like -Android. But these are the ones most likely to work, as they have the most -testing. - -Finally, a comment about Windows. Rust considers Windows to be a first-class -platform upon release, but if we're honest, the Windows experience isn't as -integrated as the Linux/OS X experience is. We're working on it! If anything -does not work, it is a bug. Please let us know if that happens. Each and every -commit is tested against Windows just like any other platform. - -If you've got Rust installed, you can open up a shell, and type this: - -```bash -$ rustc --version -``` - -You should see some output that looks something like this: - -```bash -rustc 1.0.0-nightly (f11f3e7ba 2015-01-04 20:02:14 +0000) -``` - -If you did, Rust has been installed successfully! Congrats! - -If not, there are a number of places where you can get help. The easiest is -[the #rust IRC channel on irc.mozilla.org](irc://irc.mozilla.org/#rust), which -you can access through -[Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click -that link, and you'll be chatting with other Rustaceans (a silly nickname we -call ourselves), and we can help you out. Other great resources include [our -forum](http://discuss.rust-lang.org/), [the /r/rust -subreddit](http://www.reddit.com/r/rust), and [Stack -Overflow](http://stackoverflow.com/questions/tagged/rust). - -# Hello, world! - -Now that you have Rust installed, let's write your first Rust program. It's -traditional to make your first program in any new language one that prints the -text "Hello, world!" to the screen. The nice thing about starting with such a -simple program is that you can verify that your compiler isn't just installed, -but also working properly. And printing information to the screen is a pretty -common thing to do. - -The first thing that we need to do is make a file to put our code in. I like -to make a `projects` directory in my home directory, and keep all my projects -there. Rust does not care where your code lives. - -This actually leads to one other concern we should address: this guide will -assume that you have basic familiarity with the command line. Rust does not -require that you know a whole ton about the command line, but until the -language is in a more finished state, IDE support is spotty. Rust makes no -specific demands on your editing tooling, or where your code lives. - -With that said, let's make a directory in our projects directory. - -```{bash} -$ mkdir ~/projects -$ cd ~/projects -$ mkdir hello_world -$ cd hello_world -``` - -If you're on Windows and not using PowerShell, the `~` may not work. Consult -the documentation for your shell for more details. - -Let's make a new source file next. I'm going to use the syntax `editor -filename` to represent editing a file in these examples, but you should use -whatever method you want. We'll call our file `main.rs`: - -```{bash} -$ editor main.rs -``` - -Rust files always end in a `.rs` extension. If you're using more than one word -in your filename, use an underscore. `hello_world.rs` rather than -`helloworld.rs`. - -Now that you've got your file open, type this in: - -```{rust} -fn main() { - println!("Hello, world!"); -} -``` - -Save the file, and then type this into your terminal window: - -```{bash} -$ rustc main.rs -$ ./main # or main.exe on Windows -Hello, world! -``` - -You can also run these examples on [play.rust-lang.org](http://play.rust-lang.org/) by clicking on the arrow that appears in the upper right of the example when you mouse over the code. - -Success! Let's go over what just happened in detail. - -```{rust} -fn main() { - -} -``` - -These lines define a **function** in Rust. The `main` function is special: -it's the beginning of every Rust program. The first line says "I'm declaring a -function named `main`, which takes no arguments and returns nothing." If there -were arguments, they would go inside the parentheses (`(` and `)`), and because -we aren't returning anything from this function, we've dropped that notation -entirely. We'll get to it later. - -You'll also note that the function is wrapped in curly braces (`{` and `}`). -Rust requires these around all function bodies. It is also considered good -style to put the opening curly brace on the same line as the function -declaration, with one space in between. - -Next up is this line: - -```{rust} - println!("Hello, world!"); -``` - -This line does all of the work in our little program. There are a number of -details that are important here. The first is that it's indented with four -spaces, not tabs. Please configure your editor of choice to insert four spaces -with the tab key. We provide some [sample configurations for various -editors](https://github.com/rust-lang/rust/tree/master/src/etc). - -The second point is the `println!()` part. This is calling a Rust **macro**, -which is how metaprogramming is done in Rust. If it were a function instead, it -would look like this: `println()`. For our purposes, we don't need to worry -about this difference. Just know that sometimes, you'll see a `!`, and that -means that you're calling a macro instead of a normal function. Rust implements -`println!` as a macro rather than a function for good reasons, but that's a -very advanced topic. You'll learn more when we talk about macros later. One -last thing to mention: Rust's macros are significantly different from C macros, -if you've used those. Don't be scared of using macros. We'll get to the details -eventually, you'll just have to trust us for now. - -Next, `"Hello, world!"` is a **string**. Strings are a surprisingly complicated -topic in a systems programming language, and this is a **statically allocated** -string. We will talk more about different kinds of allocation later. We pass -this string as an argument to `println!`, which prints the string to the -screen. Easy enough! - -Finally, the line ends with a semicolon (`;`). Rust is an **expression -oriented** language, which means that most things are expressions. The `;` is -used to indicate that this expression is over, and the next one is ready to -begin. Most lines of Rust code end with a `;`. We will cover this in-depth -later in the guide. - -Finally, actually **compiling** and **running** our program. We can compile -with our compiler, `rustc`, by passing it the name of our source file: - -```{bash} -$ rustc main.rs -``` - -This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust -will output a binary executable. You can see it with `ls`: - -```{bash} -$ ls -main main.rs -``` - -Or on Windows: - -```{bash} -$ dir -main.exe main.rs -``` - -There are now two files: our source code, with the `.rs` extension, and the -executable (`main.exe` on Windows, `main` everywhere else) - -```{bash} -$ ./main # or main.exe on Windows -``` - -This prints out our `Hello, world!` text to our terminal. - -If you come from a dynamically typed language like Ruby, Python, or JavaScript, -you may not be used to these two steps being separate. Rust is an -**ahead-of-time compiled language**, which means that you can compile a -program, give it to someone else, and they don't need to have Rust installed. -If you give someone a `.rb` or `.py` or `.js` file, they need to have -Ruby/Python/JavaScript installed, but you just need one command to both compile -and run your program. Everything is a tradeoff in language design, and Rust has -made its choice. - -Congratulations! You have officially written a Rust program. That makes you a -Rust programmer! Welcome. - -Next, I'd like to introduce you to another tool, Cargo, which is used to write -real-world Rust programs. Just using `rustc` is nice for simple things, but as -your project grows, you'll want something to help you manage all of the options -that it has, and to make it easy to share your code with other people and -projects. - -# Hello, Cargo! - -[Cargo](http://crates.io) is a tool that Rustaceans use to help manage their -Rust projects. Cargo is currently in an alpha state, just like Rust, and so it -is still a work in progress. However, it is already good enough to use for many -Rust projects, and so it is assumed that Rust projects will use Cargo from the -beginning. - -Cargo manages three things: building your code, downloading the dependencies -your code needs, and building the dependencies your code needs. At first, your -program doesn't have any dependencies, so we'll only be using the first part of -its functionality. Eventually, we'll add more. Since we started off by using -Cargo, it'll be easy to add later. - -If you installed Rust via the official installers you will also have -Cargo. If you installed Rust some other way, you may want to [check -the Cargo -README](https://github.com/rust-lang/cargo#installing-cargo-from-nightlies) -for specific instructions about installing it. - -Let's convert Hello World to Cargo. - -To Cargo-ify our project, we need to do two things: Make a `Cargo.toml` -configuration file, and put our source file in the right place. Let's -do that part first: - -```{bash} -$ mkdir src -$ mv main.rs src/main.rs -``` - -Cargo expects your source files to live inside a `src` directory. That leaves -the top level for other things, like READMEs, license information, and anything -not related to your code. Cargo helps us keep our projects nice and tidy. A -place for everything, and everything in its place. - -Next, our configuration file: - -```{bash} -$ editor Cargo.toml -``` - -Make sure to get this name right: you need the capital `C`! - -Put this inside: - -```toml -[package] - -name = "hello_world" -version = "0.0.1" -authors = [ "Your name <you@example.com>" ] - -[[bin]] - -name = "hello_world" -``` - -This file is in the [TOML](https://github.com/toml-lang/toml) format. Let's let -it explain itself to you: - -> TOML aims to be a minimal configuration file format that's easy to read due -> to obvious semantics. TOML is designed to map unambiguously to a hash table. -> TOML should be easy to parse into data structures in a wide variety of -> languages. - -TOML is very similar to INI, but with some extra goodies. - -Anyway, there are two **table**s in this file: `package` and `bin`. The first -tells Cargo metadata about your package. The second tells Cargo that we're -interested in building a binary, not a library (though we could do both!), as -well as what it is named. - -Once you have this file in place, we should be ready to build! Try this: - -```{bash} -$ cargo build - Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world) -$ ./target/hello_world -Hello, world! -``` - -Bam! We build our project with `cargo build`, and run it with -`./target/hello_world`. This hasn't bought us a whole lot over our simple use -of `rustc`, but think about the future: when our project has more than one -file, we would need to call `rustc` more than once, and pass it a bunch of options to -tell it to build everything together. With Cargo, as our project grows, we can -just `cargo build` and it'll work the right way. - -You'll also notice that Cargo has created a new file: `Cargo.lock`. - -```toml -[root] -name = "hello_world" -version = "0.0.1" -``` - -This file is used by Cargo to keep track of dependencies in your application. -Right now, we don't have any, so it's a bit sparse. You won't ever need -to touch this file yourself, just let Cargo handle it. - -That's it! We've successfully built `hello_world` with Cargo. Even though our -program is simple, it's using much of the real tooling that you'll use for the -rest of your Rust career. - -Now that you've got the tools down, let's actually learn more about the Rust -language itself. These are the basics that will serve you well through the rest -of your time with Rust. - -# Variable bindings - -The first thing we'll learn about are 'variable bindings.' They look like this: - -```{rust} -fn main() { - let x = 5; -} -``` - -Putting `fn main() {` in each example is a bit tedious, so we'll leave that out -in the future. If you're following along, make sure to edit your `main()` -function, rather than leaving it off. Otherwise, you'll get an error. - -In many languages, this is called a 'variable.' But Rust's variable bindings -have a few tricks up their sleeves. Rust has a very powerful feature called -'pattern matching' that we'll get into detail with later, but the left -hand side of a `let` expression is a full pattern, not just a variable name. -This means we can do things like: - -```{rust} -let (x, y) = (1, 2); -``` - -After this expression is evaluated, `x` will be one, and `y` will be two. -Patterns are really powerful, but this is about all we can do with them so far. -So let's just keep this in the back of our minds as we go forward. - -Rust is a statically typed language, which means that we specify our types up -front. So why does our first example compile? Well, Rust has this thing called -"type inference." If it can figure out what the type of something is, Rust -doesn't require you to actually type it out. - -We can add the type if we want to, though. Types come after a colon (`:`): - -```{rust} -let x: i32 = 5; -``` - -If I asked you to read this out loud to the rest of the class, you'd say "`x` -is a binding with the type `i32` and the value `five`." - -In future examples, we may annotate the type in a comment. The examples will -look like this: - -```{rust} -fn main() { - let x = 5; // x: i32 -} -``` - -Note the similarities between this annotation and the syntax you use with `let`. -Including these kinds of comments is not idiomatic Rust, but we'll occasionally -include them to help you understand what the types that Rust infers are. - -By default, bindings are **immutable**. This code will not compile: - -```{ignore} -let x = 5; -x = 10; -``` - -It will give you this error: - -```text -error: re-assignment of immutable variable `x` - x = 10; - ^~~~~~~ -``` - -If you want a binding to be mutable, you can use `mut`: - -```{rust} -let mut x = 5; // mut x: i32 -x = 10; -``` - -There is no single reason that bindings are immutable by default, but we can -think about it through one of Rust's primary focuses: safety. If you forget to -say `mut`, the compiler will catch it, and let you know that you have mutated -something you may not have intended to mutate. If bindings were mutable by -default, the compiler would not be able to tell you this. If you _did_ intend -mutation, then the solution is quite easy: add `mut`. - -There are other good reasons to avoid mutable state when possible, but they're -out of the scope of this guide. In general, you can often avoid explicit -mutation, and so it is preferable in Rust. That said, sometimes, mutation is -what you need, so it's not verboten. - -Let's get back to bindings. Rust variable bindings have one more aspect that -differs from other languages: bindings are required to be initialized with a -value before you're allowed to use them. If we try... - -```{ignore} -let x; -``` - -...we'll get an error: - -```text -src/main.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type -src/main.rs:2 let x; - ^ -``` - -Giving it a type will compile, though: - -```{rust} -let x: i32; -``` - -Let's try it out. Change your `src/main.rs` file to look like this: - -```{rust} -fn main() { - let x: i32; - - println!("Hello world!"); -} -``` - -You can use `cargo build` on the command line to build it. You'll get a warning, -but it will still print "Hello, world!": - -```text - Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) -src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default -src/main.rs:2 let x: i32; - ^ -``` - -Rust warns us that we never use the variable binding, but since we never use it, -no harm, no foul. Things change if we try to actually use this `x`, however. Let's -do that. Change your program to look like this: - -```{rust,ignore} -fn main() { - let x: i32; - - println!("The value of x is: {}", x); -} -``` - -And try to build it. You'll get an error: - -```{bash} -$ cargo build - Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) -src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` -src/main.rs:4 println!("The value of x is: {}", x); - ^ -note: in expansion of format_args! -<std macros>:2:23: 2:77 note: expansion site -<std macros>:1:1: 3:2 note: in expansion of println! -src/main.rs:4:5: 4:42 note: expansion site -error: aborting due to previous error -Could not compile `hello_world`. -``` - -Rust will not let us use a value that has not been initialized. Next, let's -talk about this stuff we've added to `println!`. - -If you include two curly braces (`{}`, some call them moustaches...) in your -string to print, Rust will interpret this as a request to interpolate some sort -of value. **String interpolation** is a computer science term that means "stick -in the middle of a string." We add a comma, and then `x`, to indicate that we -want `x` to be the value we're interpolating. The comma is used to separate -arguments we pass to functions and macros, if you're passing more than one. - -When you just use the curly braces, Rust will attempt to display the -value in a meaningful way by checking out its type. If you want to specify the -format in a more detailed manner, there are a [wide number of options -available](std/fmt/index.html). For now, we'll just stick to the default: -integers aren't very complicated to print. - -# `if` - -Rust's take on `if` is not particularly complex, but it's much more like the -`if` you'll find in a dynamically typed language than in a more traditional -systems language. So let's talk about it, to make sure you grasp the nuances. - -`if` is a specific form of a more general concept, the 'branch.' The name comes -from a branch in a tree: a decision point, where depending on a choice, -multiple paths can be taken. - -In the case of `if`, there is one choice that leads down two paths: - -```rust -let x = 5; - -if x == 5 { - println!("x is five!"); -} -``` - -If we changed the value of `x` to something else, this line would not print. -More specifically, if the expression after the `if` evaluates to `true`, then -the block is executed. If it's `false`, then it is not. - -If you want something to happen in the `false` case, use an `else`: - -```{rust} -let x = 5; - -if x == 5 { - println!("x is five!"); -} else { - println!("x is not five :("); -} -``` - -This is all pretty standard. However, you can also do this: - - -```{rust} -let x = 5; - -let y = if x == 5 { - 10 -} else { - 15 -}; // y: i32 -``` - -Which we can (and probably should) write like this: - -```{rust} -let x = 5; - -let y = if x == 5 { 10 } else { 15 }; // y: i32 -``` - -This reveals two interesting things about Rust: it is an expression-based -language, and semicolons are different from semicolons in other 'curly brace -and semicolon'-based languages. These two things are related. - -## Expressions vs. Statements - -Rust is primarily an expression based language. There are only two kinds of -statements, and everything else is an expression. - -So what's the difference? Expressions return a value, and statements do not. -In many languages, `if` is a statement, and therefore, `let x = if ...` would -make no sense. But in Rust, `if` is an expression, which means that it returns -a value. We can then use this value to initialize the binding. - -Speaking of which, bindings are a kind of the first of Rust's two statements. -The proper name is a **declaration statement**. So far, `let` is the only kind -of declaration statement we've seen. Let's talk about that some more. - -In some languages, variable bindings can be written as expressions, not just -statements. Like Ruby: - -```{ruby} -x = y = 5 -``` - -In Rust, however, using `let` to introduce a binding is _not_ an expression. The -following will produce a compile-time error: - -```{ignore} -let x = (let y = 5); // expected identifier, found keyword `let` -``` - -The compiler is telling us here that it was expecting to see the beginning of -an expression, and a `let` can only begin a statement, not an expression. - -Note that assigning to an already-bound variable (e.g. `y = 5`) is still an -expression, although its value is not particularly useful. Unlike C, where an -assignment evaluates to the assigned value (e.g. `5` in the previous example), -in Rust the value of an assignment is the unit type `()` (which we'll cover later). - -The second kind of statement in Rust is the **expression statement**. Its -purpose is to turn any expression into a statement. In practical terms, Rust's -grammar expects statements to follow other statements. This means that you use -semicolons to separate expressions from each other. This means that Rust -looks a lot like most other languages that require you to use semicolons -at the end of every line, and you will see semicolons at the end of almost -every line of Rust code you see. - -What is this exception that makes us say 'almost?' You saw it already, in this -code: - -```{rust} -let x = 5; - -let y: i32 = if x == 5 { 10 } else { 15 }; -``` - -Note that I've added the type annotation to `y`, to specify explicitly that I -want `y` to be an integer. - -This is not the same as this, which won't compile: - -```{ignore} -let x = 5; - -let y: i32 = if x == 5 { 10; } else { 15; }; -``` - -Note the semicolons after the 10 and 15. Rust will give us the following error: - -```text -error: mismatched types: expected `i32` but found `()` (expected i32 but found ()) -``` - -We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a -special type in Rust's type system. In Rust, `()` is _not_ a valid value for a -variable of type `i32`. It's only a valid value for variables of the type `()`, -which aren't very useful. Remember how we said statements don't return a value? -Well, that's the purpose of unit in this case. The semicolon turns any -expression into a statement by throwing away its value and returning unit -instead. - -There's one more time in which you won't see a semicolon at the end of a line -of Rust code. For that, we'll need our next concept: functions. - -# Functions - -You've already seen one function so far, the `main` function: - -```{rust} -fn main() { -} -``` - -This is the simplest possible function declaration. As we mentioned before, -`fn` says 'this is a function,' followed by the name, some parentheses because -this function takes no arguments, and then some curly braces to indicate the -body. Here's a function named `foo`: - -```{rust} -fn foo() { -} -``` - -So, what about taking arguments? Here's a function that prints a number: - -```{rust} -fn print_number(x: i32) { - println!("x is: {}", x); -} -``` - -Here's a complete program that uses `print_number`: - -```{rust} -fn main() { - print_number(5); -} - -fn print_number(x: i32) { - println!("x is: {}", x); -} -``` - -As you can see, function arguments work very similar to `let` declarations: -you add a type to the argument name, after a colon. - -Here's a complete program that adds two numbers together and prints them: - -```{rust} -fn main() { - print_sum(5, 6); -} - -fn print_sum(x: i32, y: i32) { - println!("sum is: {}", x + y); -} -``` - -You separate arguments with a comma, both when you call the function, as well -as when you declare it. - -Unlike `let`, you _must_ declare the types of function arguments. This does -not work: - -```{ignore} -fn print_number(x, y) { - println!("x is: {}", x + y); -} -``` - -You get this error: - -```text -hello.rs:5:18: 5:19 error: expected `:` but found `,` -hello.rs:5 fn print_number(x, y) { -``` - -This is a deliberate design decision. While full-program inference is possible, -languages which have it, like Haskell, often suggest that documenting your -types explicitly is a best-practice. We agree that forcing functions to declare -types while allowing for inference inside of function bodies is a wonderful -sweet spot between full inference and no inference. - -What about returning a value? Here's a function that adds one to an integer: - -```{rust} -fn add_one(x: i32) -> i32 { - x + 1 -} -``` - -Rust functions return exactly one value, and you declare the type after an -'arrow', which is a dash (`-`) followed by a greater-than sign (`>`). - -You'll note the lack of a semicolon here. If we added it in: - -```{ignore} -fn add_one(x: i32) -> i32 { - x + 1; -} -``` - -We would get an error: - -```text -error: not all control paths return a value -fn add_one(x: i32) -> i32 { - x + 1; -} - -help: consider removing this semicolon: - x + 1; - ^ -``` - -Remember our earlier discussions about semicolons and `()`? Our function claims -to return an `i32`, but with a semicolon, it would return `()` instead. Rust -realizes this probably isn't what we want, and suggests removing the semicolon. - -This is very much like our `if` statement before: the result of the block -(`{}`) is the value of the expression. Other expression-oriented languages, -such as Ruby, work like this, but it's a bit unusual in the systems programming -world. When people first learn about this, they usually assume that it -introduces bugs. But because Rust's type system is so strong, and because unit -is its own unique type, we have never seen an issue where adding or removing a -semicolon in a return position would cause a bug. - -But what about early returns? Rust does have a keyword for that, `return`: - -```{rust} -fn foo(x: i32) -> i32 { - if x < 5 { return x; } - - x + 1 -} -``` - -Using a `return` as the last line of a function works, but is considered poor -style: - -```{rust} -fn foo(x: i32) -> i32 { - if x < 5 { return x; } - - return x + 1; -} -``` - -There are some additional ways to define functions, but they involve features -that we haven't learned about yet, so let's just leave it at that for now. - - -# Comments - -Now that we have some functions, it's a good idea to learn about comments. -Comments are notes that you leave to other programmers to help explain things -about your code. The compiler mostly ignores them. - -Rust has two kinds of comments that you should care about: **line comment**s -and **doc comment**s. - -```{rust} -// Line comments are anything after '//' and extend to the end of the line. - -let x = 5; // this is also a line comment. - -// If you have a long explanation for something, you can put line comments next -// to each other. Put a space between the // and your comment so that it's -// more readable. -``` - -The other kind of comment is a doc comment. Doc comments use `///` instead of -`//`, and support Markdown notation inside: - -```{rust} -/// `hello` is a function that prints a greeting that is personalized based on -/// the name given. -/// -/// # Arguments -/// -/// * `name` - The name of the person you'd like to greet. -/// -/// # Example -/// -/// ```rust -/// let name = "Steve"; -/// hello(name); // prints "Hello, Steve!" -/// ``` -fn hello(name: &str) { - println!("Hello, {}!", name); -} -``` - -When writing doc comments, adding sections for any arguments, return values, -and providing some examples of usage is very, very helpful. - -You can use the [`rustdoc`](rustdoc.html) tool to generate HTML documentation -from these doc comments. - -# Compound Data Types - -Rust, like many programming languages, has a number of different data types -that are built-in. You've already done some simple work with integers and -strings, but next, let's talk about some more complicated ways of storing data. - -## Tuples - -The first compound data type we're going to talk about are called **tuple**s. -Tuples are an ordered list of a fixed size. Like this: - -```rust -let x = (1, "hello"); -``` - -The parentheses and commas form this two-length tuple. Here's the same code, but -with the type annotated: - -```rust -let x: (i32, &str) = (1, "hello"); -``` - -As you can see, the type of a tuple looks just like the tuple, but with each -position having a type name rather than the value. Careful readers will also -note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple. -You haven't seen `&str` as a type before, and we'll discuss the details of -strings later. In systems programming languages, strings are a bit more complex -than in other languages. For now, just read `&str` as "a string slice," and -we'll learn more soon. - -You can access the fields in a tuple through a **destructuring let**. Here's -an example: - -```rust -let (x, y, z) = (1, 2, 3); - -println!("x is {}", x); -``` - -Remember before when I said the left-hand side of a `let` statement was more -powerful than just assigning a binding? Here we are. We can put a pattern on -the left-hand side of the `let`, and if it matches up to the right-hand side, -we can assign multiple bindings at once. In this case, `let` 'destructures,' -or 'breaks up,' the tuple, and assigns the bits to three bindings. - -This pattern is very powerful, and we'll see it repeated more later. - -There are also a few things you can do with a tuple as a whole, without -destructuring. You can assign one tuple into another, if they have the same -arity and contained types. - -```rust -let mut x = (1, 2); // x: (i32, i32) -let y = (2, 3); // y: (i32, i32) - -x = y; -``` - -You can also check for equality with `==`. Again, this will only compile if the -tuples have the same type. - -```rust -let x = (1, 2, 3); -let y = (2, 2, 4); - -if x == y { - println!("yes"); -} else { - println!("no"); -} -``` - -This will print `no`, because some of the values aren't equal. - -One other use of tuples is to return multiple values from a function: - -```rust -fn next_two(x: i32) -> (i32, i32) { (x + 1, x + 2) } - -fn main() { - let (x, y) = next_two(5); - println!("x, y = {}, {}", x, y); -} -``` - -Even though Rust functions can only return one value, a tuple _is_ one value, -that happens to be made up of more than one value. You can also see in this example how you -can destructure a pattern returned by a function, as well. - -Tuples are a very simple data structure, and so are not often what you want. -Let's move on to their bigger sibling, structs. - -## Structs - -A struct is another form of a 'record type,' just like a tuple. There's a -difference: structs give each element that they contain a name, called a -'field' or a 'member.' Check it out: - -```rust -struct Point { - x: i32, - y: i32, -} - -fn main() { - let origin = Point { x: 0, y: 0 }; // origin: Point - - println!("The origin is at ({}, {})", origin.x, origin.y); -} -``` - -There's a lot going on here, so let's break it down. We declare a struct with -the `struct` keyword, and then with a name. By convention, structs begin with a -capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`. - -We can create an instance of our struct via `let`, as usual, but we use a `key: -value` style syntax to set each field. The order doesn't need to be the same as -in the original declaration. - -Finally, because fields have names, we can access the field through dot -notation: `origin.x`. - -The values in structs are immutable by default, like other bindings in Rust. -Use `mut` to make them mutable: - -```{rust} -struct Point { - x: i32, - y: i32, -} - -fn main() { - let mut point = Point { x: 0, y: 0 }; - - point.x = 5; - - println!("The point is at ({}, {})", point.x, point.y); -} -``` - -This will print `The point is at (5, 0)`. - -## Tuple Structs and Newtypes - -Rust has another data type that's like a hybrid between a tuple and a struct, -called a **tuple struct**. Tuple structs do have a name, but their fields -don't: - - -```{rust} -struct Color(i32, i32, i32); -struct Point(i32, i32, i32); -``` - -These two will not be equal, even if they have the same values: - -```{rust} -# struct Color(i32, i32, i32); -# struct Point(i32, i32, i32); -let black = Color(0, 0, 0); -let origin = Point(0, 0, 0); -``` - -It is almost always better to use a struct than a tuple struct. We would write -`Color` and `Point` like this instead: - -```{rust} -struct Color { - red: i32, - blue: i32, - green: i32, -} - -struct Point { - x: i32, - y: i32, - z: i32, -} -``` - -Now, we have actual names, rather than positions. Good names are important, -and with a struct, we have actual names. - -There _is_ one case when a tuple struct is very useful, though, and that's a -tuple struct with only one element. We call this a 'newtype,' because it lets -you create a new type that's a synonym for another one: - -```{rust} -struct Inches(i32); - -let length = Inches(10); - -let Inches(integer_length) = length; -println!("length is {} inches", integer_length); -``` - -As you can see here, you can extract the inner integer type through a -destructuring `let`. - -## Enums - -Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful -feature of Rust, and are used throughout the standard library. This is an enum -that is provided by the Rust standard library: - -```{rust} -enum Ordering { - Less, - Equal, - Greater, -} -``` - -An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given -time. - -Because `Ordering` is provided by the standard library, we can use the `use` -keyword to use it in our code. We'll learn more about `use` later, but it's -used to bring names into scope. - -Here's an example of how to use `Ordering`: - -```{rust} -use std::cmp::Ordering; - -fn cmp(a: i32, b: i32) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} - -fn main() { - let x = 5; - let y = 10; - - let ordering = cmp(x, y); // ordering: Ordering - - if ordering == Ordering::Less { - println!("less"); - } else if ordering == Ordering::Greater { - println!("greater"); - } else if ordering == Ordering::Equal { - println!("equal"); - } -} -``` - -There's a symbol here we haven't seen before: the double colon (`::`). -This is used to indicate a namespace. In this case, `Ordering` lives in -the `cmp` submodule of the `std` module. We'll talk more about modules -later in the guide. For now, all you need to know is that you can `use` -things from the standard library if you need them. - -Okay, let's talk about the actual code in the example. `cmp` is a function that -compares two things, and returns an `Ordering`. We return either -`Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on if -the two values are greater, less, or equal. Note that each variant of the -`enum` is namespaced under the `enum` itself: it's `Ordering::Greater` not -`Greater`. - -The `ordering` variable has the type `Ordering`, and so contains one of the -three values. We can then do a bunch of `if`/`else` comparisons to check which -one it is. However, repeated `if`/`else` comparisons get quite tedious. Rust -has a feature that not only makes them nicer to read, but also makes sure that -you never miss a case. Before we get to that, though, let's talk about another -kind of enum: one with values. - -This enum has two variants, one of which has a value: - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} -``` - -This enum represents an `i32` that we may or may not have. In the `Missing` -case, we have no value, but in the `Value` case, we do. This enum is specific -to `i32`s, though. We can make it usable by any type, but we haven't quite -gotten there yet! - -You can also have any number of values in an enum: - -```{rust} -enum OptionalColor { - Color(i32, i32, i32), - Missing, -} -``` - -And you can also have something like this: - -```{rust} -enum StringResult { - StringOK(String), - ErrorReason(String), -} -``` -Where a `StringResult` is either a `StringResult::StringOK`, with the result of -a computation, or an `StringResult::ErrorReason` with a `String` explaining -what caused the computation to fail. These kinds of `enum`s are actually very -useful and are even part of the standard library. - -Here is an example of using our `StringResult`: - -```rust -enum StringResult { - StringOK(String), - ErrorReason(String), -} - -fn respond(greeting: &str) -> StringResult { - if greeting == "Hello" { - StringResult::StringOK("Good morning!".to_string()) - } else { - StringResult::ErrorReason("I didn't understand you!".to_string()) - } -} -``` - -That's a lot of typing! We can use the `use` keyword to make it shorter: - -```rust -use StringResult::StringOK; -use StringResult::ErrorReason; - -enum StringResult { - StringOK(String), - ErrorReason(String), -} - -# fn main() {} - -fn respond(greeting: &str) -> StringResult { - if greeting == "Hello" { - StringOK("Good morning!".to_string()) - } else { - ErrorReason("I didn't understand you!".to_string()) - } -} -``` - -`use` declarations must come before anything else, which looks a little strange in this example, -since we `use` the variants before we define them. Anyway, in the body of `respond`, we can just -say `StringOK` now, rather than the full `StringResult::StringOK`. Importing variants can be -convenient, but can also cause name conflicts, so do this with caution. It's considered good style -to rarely import variants for this reason. - -As you can see, `enum`s with values are quite a powerful tool for data representation, -and can be even more useful when they're generic across types. Before we get to generics, -though, let's talk about how to use them with pattern matching, a tool that will -let us deconstruct this sum type (the type theory term for enums) in a very elegant -way and avoid all these messy `if`/`else`s. - -# Match - -Often, a simple `if`/`else` isn't enough, because you have more than two -possible options. Also, `else` conditions can get incredibly complicated, so -what's the solution? - -Rust has a keyword, `match`, that allows you to replace complicated `if`/`else` -groupings with something more powerful. Check it out: - -```{rust} -let x = 5; - -match x { - 1 => println!("one"), - 2 => println!("two"), - 3 => println!("three"), - 4 => println!("four"), - 5 => println!("five"), - _ => println!("something else"), -} -``` - -`match` takes an expression and then branches based on its value. Each 'arm' of -the branch is of the form `val => expression`. When the value matches, that arm's -expression will be evaluated. It's called `match` because of the term 'pattern -matching', which `match` is an implementation of. - -So what's the big advantage here? Well, there are a few. First of all, `match` -enforces 'exhaustiveness checking'. Do you see that last arm, the one with the -underscore (`_`)? If we remove that arm, Rust will give us an error: - -```text -error: non-exhaustive patterns: `_` not covered -``` - -In other words, Rust is trying to tell us we forgot a value. Because `x` is an -integer, Rust knows that it can have a number of different values – for example, -`6`. Without the `_`, however, there is no arm that could match, and so Rust refuses -to compile. `_` acts like a 'catch-all arm'. If none of the other arms match, -the arm with `_` will, and since we have this catch-all arm, we now have an arm -for every possible value of `x`, and so our program will compile successfully. - -`match` statements also destructure enums, as well. Remember this code from the -section on enums? - -```{rust} -use std::cmp::Ordering; - -fn cmp(a: i32, b: i32) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} - -fn main() { - let x = 5; - let y = 10; - - let ordering = cmp(x, y); - - if ordering == Ordering::Less { - println!("less"); - } else if ordering == Ordering::Greater { - println!("greater"); - } else if ordering == Ordering::Equal { - println!("equal"); - } -} -``` - -We can re-write this as a `match`: - -```{rust} -use std::cmp::Ordering; - -fn cmp(a: i32, b: i32) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} - -fn main() { - let x = 5; - let y = 10; - - match cmp(x, y) { - Ordering::Less => println!("less"), - Ordering::Greater => println!("greater"), - Ordering::Equal => println!("equal"), - } -} -``` - -This version has way less noise, and it also checks exhaustively to make sure -that we have covered all possible variants of `Ordering`. With our `if`/`else` -version, if we had forgotten the `Greater` case, for example, our program would -have happily compiled. If we forget in the `match`, it will not. Rust helps us -make sure to cover all of our bases. - -`match` expressions also allow us to get the values contained in an `enum` -(also known as destructuring) as follows: - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} - -fn main() { - let x = OptionalInt::Value(5); - let y = OptionalInt::Missing; - - match x { - OptionalInt::Value(n) => println!("x is {}", n), - OptionalInt::Missing => println!("x is missing!"), - } - - match y { - OptionalInt::Value(n) => println!("y is {}", n), - OptionalInt::Missing => println!("y is missing!"), - } -} -``` - -That is how you can get and use the values contained in `enum`s. -It can also allow us to handle errors or unexpected computations; for example, a -function that is not guaranteed to be able to compute a result (an `i32` here) -could return an `OptionalInt`, and we would handle that value with a `match`. -As you can see, `enum` and `match` used together are quite useful! - -`match` is also an expression, which means we can use it on the right-hand -side of a `let` binding or directly where an expression is used. We could -also implement the previous example like this: - -```{rust} -use std::cmp::Ordering; - -fn cmp(a: i32, b: i32) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} - -fn main() { - let x = 5; - let y = 10; - - println!("{}", match cmp(x, y) { - Ordering::Less => "less", - Ordering::Greater => "greater", - Ordering::Equal => "equal", - }); -} -``` - -Sometimes, it's a nice pattern. - -# Looping - -Looping is the last basic construct that we haven't learned yet in Rust. Rust has -two main looping constructs: `for` and `while`. - -## `for` - -The `for` loop is used to loop a particular number of times. Rust's `for` loops -work a bit differently than in other systems languages, however. Rust's `for` -loop doesn't look like this "C-style" `for` loop: - -```{c} -for (x = 0; x < 10; x++) { - printf( "%d\n", x ); -} -``` - -Instead, it looks like this: - -```{rust} -for x in range(0, 10) { - println!("{}", x); // x: i32 -} -``` - -In slightly more abstract terms, - -```{ignore} -for var in expression { - code -} -``` - -The expression is an iterator, which we will discuss in more depth later in the -guide. The iterator gives back a series of elements. Each element is one -iteration of the loop. That value is then bound to the name `var`, which is -valid for the loop body. Once the body is over, the next value is fetched from -the iterator, and we loop another time. When there are no more values, the -`for` loop is over. - -In our example, `range` is a function that takes a start and an end position, -and gives an iterator over those values. The upper bound is exclusive, though, -so our loop will print `0` through `9`, not `10`. - -Rust does not have the "C-style" `for` loop on purpose. Manually controlling -each element of the loop is complicated and error prone, even for experienced C -developers. - -We'll talk more about `for` when we cover **iterator**s, later in the Guide. - -## `while` - -The other kind of looping construct in Rust is the `while` loop. It looks like -this: - -```{rust} -let mut x = 5u; // mut x: uint -let mut done = false; // mut done: bool - -while !done { - x += x - 3; - println!("{}", x); - if x % 5 == 0 { done = true; } -} -``` - -`while` loops are the correct choice when you're not sure how many times -you need to loop. - -If you need an infinite loop, you may be tempted to write this: - -```{rust,ignore} -while true { -``` - -However, Rust has a dedicated keyword, `loop`, to handle this case: - -```{rust,ignore} -loop { -``` - -Rust's control-flow analysis treats this construct differently than a -`while true`, since we know that it will always loop. The details of what -that _means_ aren't super important to understand at this stage, but in -general, the more information we can give to the compiler, the better it -can do with safety and code generation, so you should always prefer -`loop` when you plan to loop infinitely. - -## Ending iteration early - -Let's take a look at that `while` loop we had earlier: - -```{rust} -let mut x = 5u; -let mut done = false; - -while !done { - x += x - 3; - println!("{}", x); - if x % 5 == 0 { done = true; } -} -``` - -We had to keep a dedicated `mut` boolean variable binding, `done`, to know -when we should exit out of the loop. Rust has two keywords to help us with -modifying iteration: `break` and `continue`. - -In this case, we can write the loop in a better way with `break`: - -```{rust} -let mut x = 5u; - -loop { - x += x - 3; - println!("{}", x); - if x % 5 == 0 { break; } -} -``` - -We now loop forever with `loop` and use `break` to break out early. - -`continue` is similar, but instead of ending the loop, goes to the next -iteration. This will only print the odd numbers: - -```{rust} -for x in range(0, 10) { - if x % 2 == 0 { continue; } - - println!("{}", x); -} -``` - -Both `continue` and `break` are valid in both kinds of loops. - -# Strings - -Strings are an important concept for any programmer to master. Rust's string -handling system is a bit different from other languages, due to its systems -focus. Any time you have a data structure of variable size, things can get -tricky, and strings are a re-sizable data structure. That being said, Rust's -strings also work differently than in some other systems languages, such as C. - -Let's dig into the details. A **string** is a sequence of Unicode scalar values -encoded as a stream of UTF-8 bytes. All strings are guaranteed to be -validly encoded UTF-8 sequences. Additionally, strings are not null-terminated -and can contain null bytes. - -Rust has two main types of strings: `&str` and `String`. - -The first kind is a `&str`. This is pronounced a 'string slice.' String literals -are of the type `&str`: - -```{rust} -let string = "Hello there."; // string: &str -``` - -This string is statically allocated, meaning that it's saved inside our -compiled program, and exists for the entire duration it runs. The `string` -binding is a reference to this statically allocated string. String slices -have a fixed size, and cannot be mutated. - -A `String`, on the other hand, is an in-memory string. This string is -growable, and is also guaranteed to be UTF-8. - -```{rust} -let mut s = "Hello".to_string(); // mut s: String -println!("{}", s); - -s.push_str(", world."); -println!("{}", s); -``` - -You can get a `&str` view into a `String` with the `as_slice()` method: - -```{rust} -fn takes_slice(slice: &str) { - println!("Got: {}", slice); -} - -fn main() { - let s = "Hello".to_string(); - takes_slice(s.as_slice()); -} -``` - -To compare a String to a constant string, prefer `as_slice()`... - -```{rust} -fn compare(string: String) { - if string.as_slice() == "Hello" { - println!("yes"); - } -} -``` - -... over `to_string()`: - -```{rust} -fn compare(string: String) { - if string == "Hello".to_string() { - println!("yes"); - } -} -``` - -Viewing a `String` as a `&str` is cheap, but converting the `&str` to a -`String` involves allocating memory. No reason to do that unless you have to! - -That's the basics of strings in Rust! They're probably a bit more complicated -than you are used to, if you come from a scripting language, but when the -low-level details matter, they really matter. Just remember that `String`s -allocate memory and control their data, while `&str`s are a reference to -another string, and you'll be all set. - -# Arrays, Vectors, and Slices - -Like many programming languages, Rust has list types to represent a sequence of -things. The most basic is the **array**, a fixed-size list of elements of the -same type. By default, arrays are immutable. - -```{rust} -let a = [1, 2, 3]; // a: [i32; 3] -let mut m = [1, 2, 3]; // mut m: [i32; 3] -``` - -There's a shorthand for initializing each element of an array to the same -value. In this example, each element of `a` will be initialized to `0`: - -```{rust} -let a = [0; 20]; // a: [i32; 20] -``` - -Arrays have type `[T; N]`. We'll talk about this `T` notation later, when we -cover generics. - -You can get the number of elements in an array `a` with `a.len()`, and use -`a.iter()` to iterate over them with a for loop. This code will print each -number in order: - -```{rust} -let a = [1, 2, 3]; - -println!("a has {} elements", a.len()); -for e in a.iter() { - println!("{}", e); -} -``` - -You can access a particular element of an array with **subscript notation**: - -```{rust} -let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3] - -println!("The second name is: {}", names[1]); -``` - -Subscripts start at zero, like in most programming languages, so the first name -is `names[0]` and the second name is `names[1]`. The above example prints -`The second name is: Brian`. If you try to use a subscript that is not in the -array, you will get an error: array access is bounds-checked at run-time. Such -errant access is the source of many bugs in other systems programming -languages. - -A **vector** is a dynamic or "growable" array, implemented as the standard -library type [`Vec<T>`](std/vec/) (we'll talk about what the `<T>` means -later). Vectors are to arrays what `String` is to `&str`. You can create them -with the `vec!` macro: - -```{rust} -let v = vec![1, 2, 3]; // v: Vec<i32> -``` - -(Notice that unlike the `println!` macro we've used in the past, we use square -brackets `[]` with `vec!`. Rust allows you to use either in either situation, -this is just convention.) - -You can get the length of, iterate over, and subscript vectors just like -arrays. In addition, (mutable) vectors can grow automatically: - -```{rust} -let mut nums = vec![1, 2, 3]; // mut nums: Vec<i32> - -nums.push(4); - -println!("The length of nums is now {}", nums.len()); // Prints 4 -``` - -Vectors have many more useful methods. - -A **slice** is a reference to (or "view" into) an array. They are useful for -allowing safe, efficient access to a portion of an array without copying. For -example, you might want to reference just one line of a file read into memory. -By nature, a slice is not created directly, but from an existing variable. -Slices have a length, can be mutable or not, and in many ways behave like -arrays: - -```{rust} -let a = [0, 1, 2, 3, 4]; -let middle = a.slice(1, 4); // A slice of a: just the elements [1,2,3] - -for e in middle.iter() { - println!("{}", e); // Prints 1, 2, 3 -} -``` - -You can also take a slice of a vector, `String`, or `&str`, because they are -backed by arrays. Slices have type `&[T]`, which we'll talk about when we cover -generics. - -We have now learned all of the most basic Rust concepts. We're ready to start -building our guessing game, we just need to know one last thing: how to get -input from the keyboard. You can't have a guessing game without the ability to -guess! - -# Standard Input - -Getting input from the keyboard is pretty easy, but uses some things -we haven't seen before. Here's a simple program that reads some input, -and then prints it back out: - -```{rust,ignore} -fn main() { - println!("Type something!"); - - let input = std::io::stdin().read_line().ok().expect("Failed to read line"); - - println!("{}", input); -} -``` - -Let's go over these chunks, one by one: - -```{rust,ignore} -std::io::stdin(); -``` - -This calls a function, `stdin()`, that lives inside the `std::io` module. As -you can imagine, everything in `std` is provided by Rust, the 'standard -library.' We'll talk more about the module system later. - -Since writing the fully qualified name all the time is annoying, we can use -the `use` statement to import it in: - -```{rust} -use std::io::stdin; - -stdin(); -``` - -However, it's considered better practice to not import individual functions, but -to import the module, and only use one level of qualification: - -```{rust} -use std::io; - -io::stdin(); -``` - -Let's update our example to use this style: - -```{rust,ignore} -use std::io; - -fn main() { - println!("Type something!"); - - let input = io::stdin().read_line().ok().expect("Failed to read line"); - - println!("{}", input); -} -``` - -Next up: - -```{rust,ignore} -.read_line() -``` - -The `read_line()` method can be called on the result of `stdin()` to return -a full line of input. Nice and easy. - -```{rust,ignore} -.ok().expect("Failed to read line"); -``` - -Do you remember this code? - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} - -fn main() { - let x = OptionalInt::Value(5); - let y = OptionalInt::Missing; - - match x { - OptionalInt::Value(n) => println!("x is {}", n), - OptionalInt::Missing => println!("x is missing!"), - } - - match y { - OptionalInt::Value(n) => println!("y is {}", n), - OptionalInt::Missing => println!("y is missing!"), - } -} -``` - -We had to match each time to see if we had a value or not. In this case, -though, we _know_ that `x` has a `Value`, but `match` forces us to handle -the `missing` case. This is what we want 99% of the time, but sometimes, we -know better than the compiler. - -Likewise, `read_line()` does not return a line of input. It _might_ return a -line of input, though it might also fail to do so. This could happen if our program -isn't running in a terminal, but as part of a cron job, or some other context -where there's no standard input. Because of this, `read_line` returns a type -very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about -`IoResult<T>` yet because it is the **generic** form of our `OptionalInt`. -Until then, you can think of it as being the same thing, just for any type – -not just `i32`s. - -Rust provides a method on these `IoResult<T>`s called `ok()`, which does the -same thing as our `match` statement but assumes that we have a valid value. -We then call `expect()` on the result, which will terminate our program if we -don't have a valid value. In this case, if we can't get input, our program -doesn't work, so we're okay with that. In most cases, we would want to handle -the error case explicitly. `expect()` allows us to give an error message if -this crash happens. - -We will cover the exact details of how all of this works later in the Guide. -For now, this gives you enough of a basic understanding to work with. - -Back to the code we were working on! Here's a refresher: - -```{rust,ignore} -use std::io; - -fn main() { - println!("Type something!"); - - let input = io::stdin().read_line().ok().expect("Failed to read line"); - - println!("{}", input); -} -``` - -With long lines like this, Rust gives you some flexibility with the whitespace. -We _could_ write the example like this: - -```{rust,ignore} -use std::io; - -fn main() { - println!("Type something!"); - - // here, we'll show the types at each step - - let input = io::stdin() // std::io::stdio::StdinReader - .read_line() // IoResult<String> - .ok() // Option<String> - .expect("Failed to read line"); // String - - println!("{}", input); -} -``` - -Sometimes, this makes things more readable – sometimes, less. Use your judgement -here. - -That's all you need to get basic input from the standard input! It's not too -complicated, but there are a number of small parts. - -# Guessing Game - -Okay! We've got the basics of Rust down. Let's write a bigger program. - -For our first project, we'll implement a classic beginner programming problem: -the guessing game. Here's how it works: Our program will generate a random -integer between one and a hundred. It will then prompt us to enter a guess. -Upon entering our guess, it will tell us if we're too low or too high. Once we -guess correctly, it will congratulate us. Sound good? - -## Set up - -Let's set up a new project. Go to your projects directory. Remember how we -had to create our directory structure and a `Cargo.toml` for `hello_world`? Cargo -has a command that does that for us. Let's give it a shot: - -```{bash} -$ cd ~/projects -$ cargo new guessing_game --bin -$ cd guessing_game -``` - -We pass the name of our project to `cargo new`, and then the `--bin` flag, -since we're making a binary, rather than a library. - -Check out the generated `Cargo.toml`: - -```toml -[package] - -name = "guessing_game" -version = "0.0.1" -authors = ["Your Name <you@example.com>"] -``` - -Cargo gets this information from your environment. If it's not correct, go ahead -and fix that. - -Finally, Cargo generated a "Hello, world!" for us. Check out `src/main.rs`: - -```{rust} -fn main() { - println!("Hello, world!") -} -``` - -Let's try compiling what Cargo gave us: - -```{bash} -$ cargo build - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) -``` - -Excellent! Open up your `src/main.rs` again. We'll be writing all of -our code in this file. We'll talk about multiple-file projects later on in the -guide. - -Before we move on, let me show you one more Cargo command: `run`. `cargo run` -is kind of like `cargo build`, but it also then runs the produced executable. -Try it out: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Hello, world! -``` - -Great! The `run` command comes in handy when you need to rapidly iterate on a project. -Our game is just such a project, we need to quickly test each iteration before moving on to the next one. - -## Processing a Guess - -Let's get to it! The first thing we need to do for our guessing game is -allow our player to input a guess. Put this in your `src/main.rs`: - -```{rust,no_run} -use std::io; - -fn main() { - println!("Guess the number!"); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - println!("You guessed: {}", input); -} -``` - -You've seen this code before, when we talked about standard input. We -import the `std::io` module with `use`, and then our `main` function contains -our program's logic. We print a little message announcing the game, ask the -user to input a guess, get their input, and then print it out. - -Because we talked about this in the section on standard I/O, I won't go into -more details here. If you need a refresher, go re-read that section. - -## Generating a secret number - -Next, we need to generate a secret number. To do that, we need to use Rust's -random number generation, which we haven't talked about yet. Rust includes a -bunch of interesting functions in its standard library. If you need a bit of -code, it's possible that it's already been written for you! In this case, -we do know that Rust has random number generation, but we don't know how to -use it. - -Enter the docs. Rust has a page specifically to document the standard library. -You can find that page [here](std/index.html). There's a lot of information on -that page, but the best part is the search bar. Right up at the top, there's -a box that you can enter in a search term. The search is pretty primitive -right now, but is getting better all the time. If you type 'random' in that -box, the page will update to [this one](std/index.html?search=random). The very -first result is a link to [`std::rand::random`](std/rand/fn.random.html). If we -click on that result, we'll be taken to its documentation page. - -This page shows us a few things: the type signature of the function, some -explanatory text, and then an example. Let's try to modify our code to add in the -`random` function and see what happens: - -```{rust,ignore} -use std::io; -use std::rand; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random() % 100) + 1; // secret_number: i32 - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - - println!("You guessed: {}", input); -} -``` - -The first thing we changed was to `use std::rand`, as the docs -explained. We then added in a `let` expression to create a variable binding -named `secret_number`, and we printed out its result. - -Also, you may wonder why we are using `%` on the result of `rand::random()`. -This operator is called 'modulo', and it returns the remainder of a division. -By taking the modulo of the result of `rand::random()`, we're limiting the -values to be between 0 and 99. Then, we add one to the result, making it from 1 -to 100. Using modulo can give you a very, very small bias in the result, but -for this example, it is not important. - -Let's try to compile this using `cargo build`: - -```bash -$ cargo build - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) -src/main.rs:7:26: 7:34 error: the type of this value must be known in this context -src/main.rs:7 let secret_number = (rand::random() % 100) + 1; - ^~~~~~~~ -error: aborting due to previous error -``` - -It didn't work! Rust says "the type of this value must be known in this -context." What's up with that? Well, as it turns out, `rand::random()` can -generate many kinds of random values, not just integers. And in this case, Rust -isn't sure what kind of value `random()` should generate. So we have to help -it. With number literals, we can just add an `i32` onto the end to tell Rust they're -integers, but that does not work with functions. There's a different syntax, -and it looks like this: - -```{rust,ignore} -rand::random::<i32>(); -``` - -This says "please give me a random `i32` value." We can change our code to use -this hint: - -```{rust,no_run} -use std::io; -use std::rand; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<i32>() % 100) + 1; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - - println!("You guessed: {}", input); -} -``` - -Try running our new program a few times: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 7 -Please input your guess. -4 -You guessed: 4 -$ ./target/guessing_game -Guess the number! -The secret number is: 83 -Please input your guess. -5 -You guessed: 5 -$ ./target/guessing_game -Guess the number! -The secret number is: -29 -Please input your guess. -42 -You guessed: 42 -``` - -Wait. Negative 29? We wanted a number between one and a hundred! We have two -options here: we can either ask `random()` to generate an unsigned integer, which -can only be positive, or we can use the `abs()` function. Let's go with the -unsigned integer approach. If we want a random positive number, we should ask for -a random positive number. Our code looks like this now: - -```{rust,no_run} -use std::io; -use std::rand; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - - println!("You guessed: {}", input); -} -``` - -And trying it out: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 57 -Please input your guess. -3 -You guessed: 3 -``` - -Great! Next up: let's compare our guess to the secret guess. - -## Comparing guesses - -If you remember, earlier in the guide, we made a `cmp` function that compared -two numbers. Let's add that in, along with a `match` statement to compare our -guess to the secret number: - -```{rust,ignore} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - - println!("You guessed: {}", input); - - match cmp(input, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} - -fn cmp(a: i32, b: i32) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -If we try to compile, we'll get some errors: - -```bash -$ cargo build - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) -src/main.rs:20:15: 20:20 error: mismatched types: expected `i32` but found `collections::string::String` (expected i32 but found struct collections::string::String) -src/main.rs:20 match cmp(input, secret_number) { - ^~~~~ -src/main.rs:20:22: 20:35 error: mismatched types: expected `i32` but found `uint` (expected i32 but found uint) -src/main.rs:20 match cmp(input, secret_number) { - ^~~~~~~~~~~~~ -error: aborting due to 2 previous errors -``` - -This often happens when writing Rust programs, and is one of Rust's greatest -strengths. You try out some code, see if it compiles, and Rust tells you that -you've done something wrong. In this case, our `cmp` function works on integers, -but we've given it unsigned integers. In this case, the fix is easy, because -we wrote the `cmp` function! Let's change it to take `uint`s: - -```{rust,ignore} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - - - println!("You guessed: {}", input); - - match cmp(input, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -And try compiling again: - -```bash -$ cargo build - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) -src/main.rs:20:15: 20:20 error: mismatched types: expected `uint` but found `collections::string::String` (expected uint but found struct collections::string::String) -src/main.rs:20 match cmp(input, secret_number) { - ^~~~~ -error: aborting due to previous error -``` - -This error is similar to the last one: we expected to get a `uint`, but we got -a `String` instead! That's because our `input` variable is coming from the -standard input, and you can guess anything. Try it: - -```bash -$ ./target/guessing_game -Guess the number! -The secret number is: 73 -Please input your guess. -hello -You guessed: hello -``` - -Oops! Also, you'll note that we just ran our program even though it didn't compile. -This works because the older version we did successfully compile was still lying -around. Gotta be careful! - -Anyway, we have a `String`, but we need a `uint`. What to do? Well, there's -a function for that: - -```{rust,ignore} -let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); -let input_num: Option<uint> = input.parse(); -``` - -The `parse` function takes in a `&str` value and converts it into something. -We tell it what kind of something with a type hint. Remember our type hint with -`random()`? It looked like this: - -```{rust,ignore} -rand::random::<uint>(); -``` - -There's an alternate way of providing a hint too, and that's declaring the type -in a `let`: - -```{rust,ignore} -let x: uint = rand::random(); -``` - -In this case, we say `x` is a `uint` 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::<uint>(); // input_num: Option<uint> -let input_num: Option<uint> = "5".parse(); // input_num: Option<uint> -``` - -Anyway, with us now converting our input to a number, our code looks like this: - -```{rust,ignore} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.parse(); - - println!("You guessed: {}", input_num); - - match cmp(input_num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -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 `uint` but found `core::option::Option<uint>` (expected uint but found enum core::option::Option) -src/main.rs:22 match cmp(input_num, secret_number) { - ^~~~~~~~~ -error: aborting due to previous error -``` - -Oh yeah! Our `input_num` has the type `Option<uint>`, rather than `uint`. We -need to unwrap the Option. If you remember from before, `match` is a great way -to do that. Try this code: - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - return; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -We use a `match` to either give us the `uint` inside of the `Option`, or else -print an error message and return. Let's give this a shot: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 17 -Please input your guess. -5 -Please input a number! -``` - -Uh, what? But we did! - -... actually, we didn't. See, when you get a line of input from `stdin()`, -you get all the input. Including the `\n` character from you pressing Enter. -Therefore, `parse()` sees the string `"5\n"` and says "nope, that's not a -number; there's non-number stuff in there!" Luckily for us, `&str`s have an easy -method we can use defined on them: `trim()`. One small modification, and our -code looks like this: - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.trim().parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - return; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -Let's try it! - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 58 -Please input your guess. - 76 -You guessed: 76 -Too big! -``` - -Nice! You can see I even added spaces before my guess, and it still figured -out that I guessed 76. Run the program a few times, and verify that guessing -the number works, as well as guessing a number too small. - -The Rust compiler helped us out quite a bit there! This technique is called -"lean on the compiler", and it's often useful when working on some code. Let -the error messages help guide you towards the correct types. - -Now we've got most of the game working, but we can only make one guess. Let's -change that by adding loops! - -## Looping - -As we already discussed, the `loop` keyword gives us an infinite loop. -Let's add that in: - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - loop { - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.trim().parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - return; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), - } - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -And try it out. But wait, didn't we just add an infinite loop? Yup. Remember -that `return`? If we give a non-number answer, we'll `return` and quit. Observe: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 59 -Please input your guess. -45 -You guessed: 45 -Too small! -Please input your guess. -60 -You guessed: 60 -Too big! -Please input your guess. -59 -You guessed: 59 -You win! -Please input your guess. -quit -Please input a number! -``` - -Ha! `quit` actually quits. As does any other non-number input. Well, this is -suboptimal to say the least. First, let's actually quit when you win the game: - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - loop { - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.trim().parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - return; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - return; - }, - } - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -By adding the `return` line after the `You win!`, we'll exit the program when -we win. We have just one more tweak to make: when someone inputs a non-number, -we don't want to quit, we just want to ignore it. Change that `return` to -`continue`: - - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - println!("The secret number is: {}", secret_number); - - loop { - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.trim().parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - continue; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - return; - }, - } - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -Now we should be good! Let's try: - -```bash -$ cargo run - Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) - Running `target/guessing_game` -Guess the number! -The secret number is: 61 -Please input your guess. -10 -You guessed: 10 -Too small! -Please input your guess. -99 -You guessed: 99 -Too big! -Please input your guess. -foo -Please input a number! -Please input your guess. -61 -You guessed: 61 -You win! -``` - -Awesome! With one tiny last tweak, we have finished the guessing game. Can you -think of what it is? That's right, we don't want to print out the secret number. -It was good for testing, but it kind of ruins the game. Here's our final source: - -```{rust,no_run} -use std::io; -use std::rand; -use std::cmp::Ordering; - -fn main() { - println!("Guess the number!"); - - let secret_number = (rand::random::<uint>() % 100u) + 1u; - - loop { - - println!("Please input your guess."); - - let input = io::stdin().read_line() - .ok() - .expect("Failed to read line"); - let input_num: Option<uint> = input.trim().parse(); - - let num = match input_num { - Some(num) => num, - None => { - println!("Please input a number!"); - continue; - } - }; - - - println!("You guessed: {}", num); - - match cmp(num, secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => { - println!("You win!"); - return; - }, - } - } -} - -fn cmp(a: uint, b: uint) -> Ordering { - if a < b { Ordering::Less } - else if a > b { Ordering::Greater } - else { Ordering::Equal } -} -``` - -## Complete! - -At this point, you have successfully built the Guessing Game! Congratulations! - -You've now learned the basic syntax of Rust. All of this is relatively close to -various other programming languages you have used in the past. These -fundamental syntactical and semantic elements will form the foundation for the -rest of your Rust education. - -Now that you're an expert at the basics, it's time to learn about some of -Rust's more unique features. - -# Crates and Modules - -Rust features a strong module system, but it works a bit differently than in -other programming languages. Rust's module system has two main components: -**crate**s and **module**s. - -A crate is Rust's unit of independent compilation. Rust always compiles one -crate at a time, producing either a library or an executable. However, executables -usually depend on libraries, and many libraries depend on other libraries as well. -To support this, crates can depend on other crates. - -Each crate contains a hierarchy of modules. This tree starts off with a single -module, called the **crate root**. Within the crate root, we can declare other -modules, which can contain other modules, as deeply as you'd like. - -Note that we haven't mentioned anything about files yet. Rust does not impose a -particular relationship between your filesystem structure and your module -structure. That said, there is a conventional approach to how Rust looks for -modules on the file system, but it's also overridable. - -Enough talk, let's build something! Let's make a new project called `modules`. - -```{bash,ignore} -$ cd ~/projects -$ cargo new modules --bin -$ cd modules -``` - -Let's double check our work by compiling: - -```{bash} -$ cargo run - Compiling modules v0.0.1 (file:///home/you/projects/modules) - Running `target/modules` -Hello, world! -``` - -Excellent! We already have a single crate here: our `src/main.rs` is a crate. -Everything in that file is in the crate root. A crate that generates an executable -defines a `main` function inside its root, as we've done here. - -Let's define a new module inside our crate. Edit `src/main.rs` to look like this: - -``` -fn main() { - println!("Hello, world!") -} - -mod hello { - fn print_hello() { - println!("Hello, world!") - } -} -``` - -We now have a module named `hello` inside of our crate root. Modules use -`snake_case` naming, like functions and variable bindings. - -Inside the `hello` module, we've defined a `print_hello` function. This will -also print out our "hello world" message. Modules allow you to split up your -program into nice neat boxes of functionality, grouping common things together, -and keeping different things apart. It's kinda like having a set of shelves: -a place for everything and everything in its place. - -To call our `print_hello` function, we use the double colon (`::`): - -```{rust,ignore} -hello::print_hello(); -``` - -You've seen this before, with `io::stdin()` and `rand::random()`. Now you know -how to make your own. However, crates and modules have rules about -**visibility**, which controls who exactly may use the functions defined in a -given module. By default, everything in a module is private, which means that -it can only be used by other functions in the same module. This will not -compile: - -```{rust,ignore} -fn main() { - hello::print_hello(); -} - -mod hello { - fn print_hello() { - println!("Hello, world!") - } -} -``` - -It gives an error: - -```bash - Compiling modules v0.0.1 (file:///home/you/projects/modules) -src/main.rs:2:5: 2:23 error: function `print_hello` is private -src/main.rs:2 hello::print_hello(); - ^~~~~~~~~~~~~~~~~~ -``` - -To make it public, we use the `pub` keyword: - -```{rust} -fn main() { - hello::print_hello(); -} - -mod hello { - pub fn print_hello() { - println!("Hello, world!") - } -} -``` - -Usage of the `pub` keyword is sometimes called 'exporting', because -we're making the function available for other modules. This will work: - -```bash -$ cargo run - Compiling modules v0.0.1 (file:///home/you/projects/modules) - Running `target/modules` -Hello, world! -``` - -Nice! There are more things we can do with modules, including moving them into -their own files. This is enough detail for now. - -# Testing - -Traditionally, testing has not been a strong suit of most systems programming -languages. Rust, however, has very basic testing built into the language -itself. While automated testing cannot prove that your code is bug-free, it is -useful for verifying that certain behaviors work as intended. - -Here's a very basic test: - -```{rust} -#[test] -fn is_one_equal_to_one() { - assert_eq!(1, 1); -} -``` - -You may notice something new: that `#[test]`. Before we get into the mechanics -of testing, let's talk about attributes. - -## Attributes - -Rust's testing system uses **attribute**s to mark which functions are tests. -Attributes can be placed on any Rust **item**. Remember how most things in -Rust are an expression, but `let` is not? Item declarations are also not -expressions. Here's a list of things that qualify as an item: - -* functions -* modules -* type definitions -* structures -* enumerations -* static items -* traits -* implementations - -You haven't learned about all of these things yet, but that's the list. As -you can see, functions are at the top of it. - -Attributes can appear in three ways: - -1. A single identifier, the attribute name. `#[test]` is an example of this. -2. An identifier followed by an equals sign (`=`) and a literal. `#[cfg=test]` - is an example of this. -3. An identifier followed by a parenthesized list of sub-attribute arguments. - `#[cfg(unix, target_word_size = "32")]` is an example of this, where one of - the sub-arguments is of the second kind. - -There are a number of different kinds of attributes, enough that we won't go -over them all here. Before we talk about the testing-specific attributes, I -want to call out one of the most important kinds of attributes: stability -markers. - -## Stability attributes - -Rust provides six attributes to indicate the stability level of various -parts of your library. The six levels are: - -* deprecated: This item should no longer be used. No guarantee of backwards - compatibility. -* experimental: This item was only recently introduced or is otherwise in a - state of flux. It may change significantly, or even be removed. No guarantee - of backwards-compatibility. -* unstable: This item is still under development and requires more testing to - be considered stable. No guarantee of backwards-compatibility. -* stable: This item is considered stable, and will not change significantly. - Guarantee of backwards-compatibility. -* frozen: This item is very stable, and is unlikely to change. Guarantee of - backwards-compatibility. -* locked: This item will never change unless a serious bug is found. Guarantee - of backwards-compatibility. - -All of Rust's standard library uses these attribute markers to communicate -their relative stability, and you should use them in your code, as well. -There's an associated attribute, `warn`, that allows you to warn when you -import an item marked with certain levels: deprecated, experimental and -unstable. For now, only deprecated warns by default, but this will change once -the standard library has been stabilized. - -You can use the `warn` attribute like this: - -```{rust,ignore} -#![warn(unstable)] -``` - -And later, when you import a crate: - -```{rust,ignore} -extern crate some_crate; -``` - -You'll get a warning if you use something marked unstable. - -You may have noticed an exclamation point in the `warn` attribute declaration. -The `!` in this attribute means that this attribute applies to the enclosing -item, rather than to the item that follows the attribute. This `warn` -attribute declaration applies to the enclosing crate itself, rather than -to whatever item statement follows it: - -```{rust,ignore} -// applies to the crate we're in -#![warn(unstable)] - -extern crate some_crate; - -// applies to the following `fn`. -#[test] -fn a_test() { - // ... -} -``` - -## Writing tests - -Let's write a very simple crate in a test-driven manner. You know the drill by -now: make a new project: - -```{bash,ignore} -$ cd ~/projects -$ cargo new testing --bin -$ cd testing -``` - -And try it out: - -```bash -$ cargo run - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running `target/testing` -Hello, world! -``` - -Great. Rust's infrastructure supports tests in two sorts of places, and they're -for two kinds of tests: you include **unit test**s inside of the crate itself, -and you place **integration test**s inside a `tests` directory. "Unit tests" -are small tests that test one focused unit; "integration tests" test multiple -units in integration. That being said, this is a social convention – they're no -different in syntax. Let's make a `tests` directory: - -```{bash,ignore} -$ mkdir tests -``` - -Next, let's create an integration test in `tests/lib.rs`: - -```{rust,no_run} -#[test] -fn foo() { - assert!(false); -} -``` - -It doesn't matter what you name your test functions, though it's nice if -you give them descriptive names. You'll see why in a moment. We then use a -macro, `assert!`, to assert that something is true. In this case, we're giving -it `false`, so this test should fail. Let's try it! - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) -/home/you/projects/testing/src/main.rs:1:1: 3:2 warning: function is never used: `main`, #[warn(dead_code)] on by default -/home/you/projects/testing/src/main.rs:1 fn main() { -/home/you/projects/testing/src/main.rs:2 println!("Hello, world!") -/home/you/projects/testing/src/main.rs:3 } - Running target/lib-654ce120f310a3a5 - -running 1 test -test foo ... FAILED - -failures: - ----- foo stdout ---- - thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3 - - - -failures: - foo - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured - -thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243 -``` - -Lots of output! Let's break this down: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) -``` - -You can run all of your tests with `cargo test`. This runs both your tests in -`tests`, as well as the tests you put inside of your crate. - -```text -/home/you/projects/testing/src/main.rs:1:1: 3:2 warning: function is never used: `main`, #[warn(dead_code)] on by default -/home/you/projects/testing/src/main.rs:1 fn main() { -/home/you/projects/testing/src/main.rs:2 println!("Hello, world!") -/home/you/projects/testing/src/main.rs:3 } -``` - -Rust has a **lint** called 'warn on dead code' used by default. A lint is a -bit of code that checks your code, and can tell you things about it. In this -case, Rust is warning us that we've written some code that's never used: our -`main` function. Of course, since we're running tests, we don't use `main`. -We'll turn this lint off for just this function soon. For now, just ignore this -output. - -```text - Running target/lib-654ce120f310a3a5 - -running 1 test -test foo ... FAILED -``` - -Now we're getting somewhere. Remember when we talked about naming our tests -with good names? This is why. Here, it says 'test foo' because we called our -test 'foo'. If we had given it a good name, it'd be more clear which test -failed, especially as we accumulate more tests. - -```text -failures: - ----- foo stdout ---- - thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3 - - - -failures: - foo - -test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured - -thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243 -``` - -After all the tests run, Rust will show us any output from our failed tests. -In this instance, Rust tells us that our assertion failed, with false. This was -what we expected. - -Whew! Let's fix our test: - -```{rust} -#[test] -fn foo() { - assert!(true); -} -``` - -And then try to run our tests again: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running target/lib-654ce120f310a3a5 - -running 1 test -test foo ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-6d7518593c7c3ee5 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Nice! Our test passes, as we expected. Note how we didn't get the -`main` warning this time? This is because `src/main.rs` didn't -need recompiling, but we'll get that warning again if we -change (and recompile) that file. Let's get rid of that -warning; change your `src/main.rs` to look like this: - -```{rust} -#[cfg(not(test))] -fn main() { - println!("Hello, world!") -} -``` - -This attribute combines two things: `cfg` and `not`. The `cfg` attribute allows -you to conditionally compile code based on something. The following item will -only be compiled if the configuration says it's true. And when Cargo compiles -our tests, it sets things up so that `cfg(test)` is true. But we want to only -include `main` when it's _not_ true. So we use `not` to negate things: -`cfg(not(test))` will only compile our code when the `cfg(test)` is false. - -With this attribute, we won't get the warning (even -though `src/main.rs` gets recompiled this time): - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running target/lib-654ce120f310a3a5 - -running 1 test -test foo ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-6d7518593c7c3ee5 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Nice. Okay, let's write a real test now. Change your `tests/lib.rs` -to look like this: - -```{rust,ignore} -#[test] -fn math_checks_out() { - let result = add_three_times_four(5); - - assert_eq!(32, result); -} -``` - -And try to run the test: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) -/home/you/projects/testing/tests/lib.rs:3:18: 3:38 error: unresolved name `add_three_times_four`. -/home/you/projects/testing/tests/lib.rs:3 let result = add_three_times_four(5); - ^~~~~~~~~~~~~~~~~~~~ -error: aborting due to previous error -Build failed, waiting for other jobs to finish... -Could not compile `testing`. - -To learn more, run the command again with `--verbose`. -``` - -Rust can't find this function. That makes sense, as we didn't write it yet! - -In order to share this code with our tests, we'll need to make a library crate. -This is also just good software design: as we mentioned before, it's a good idea -to put most of your functionality into a library crate, and have your executable -crate use that library. This allows for code reuse. - -To do that, we'll need to make a new module. Make a new file, `src/lib.rs`, -and put this in it: - -```{rust} -# fn main() {} -pub fn add_three_times_four(x: i32) -> i32 { - (x + 3) * 4 -} -``` - -We're calling this file `lib.rs`, because Cargo uses that filename as the crate -root by convention. - -We'll then need to use this crate in our `src/main.rs`: - -```{rust,ignore} -extern crate testing; - -#[cfg(not(test))] -fn main() { - println!("Hello, world!") -} -``` - -Finally, let's import this function in our `tests/lib.rs`: - -```{rust,ignore} -extern crate testing; -use testing::add_three_times_four; - -#[test] -fn math_checks_out() { - let result = add_three_times_four(5); - - assert_eq!(32, result); -} -``` - -Let's give it a run: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running target/lib-654ce120f310a3a5 - -running 1 test -test math_checks_out ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-6d7518593c7c3ee5 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-8a94b31f7fd2e8fe - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests testing - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Great! One test passed. We've got an integration test showing that our public -method works, but maybe we want to test some of the internal logic as well. -While this function is simple, if it were more complicated, you can imagine -we'd need more tests. Let's break it up into two helper functions and write -some unit tests to test those. - -Change your `src/lib.rs` to look like this: - -```{rust,ignore} -pub fn add_three_times_four(x: i32) -> i32 { - times_four(add_three(x)) -} - -fn add_three(x: i32) -> i32 { x + 3 } - -fn times_four(x: i32) -> i32 { x * 4 } -``` - -If you run `cargo test`, you should get the same output: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running target/lib-654ce120f310a3a5 - -running 1 test -test math_checks_out ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-6d7518593c7c3ee5 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-8a94b31f7fd2e8fe - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests testing - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -If we tried to write a test for these two new functions, it wouldn't -work. For example: - -```{rust,ignore} -extern crate testing; -use testing::add_three_times_four; -use testing::add_three; - -#[test] -fn math_checks_out() { - let result = add_three_times_four(5); - - assert_eq!(32, result); -} - -#[test] -fn test_add_three() { - let result = add_three(5); - - assert_eq!(8, result); -} -``` - -We'd get this error: - -```text - Compiling testing v0.0.1 (file:///home/you/projects/testing) -/home/you/projects/testing/tests/lib.rs:3:5: 3:24 error: function `add_three` is private -/home/you/projects/testing/tests/lib.rs:3 use testing::add_three; - ^~~~~~~~~~~~~~~~~~~ -``` - -Right. It's private. So external, integration tests won't work. We need a -unit test. Open up your `src/lib.rs` and add this: - -```{rust,ignore} -pub fn add_three_times_four(x: i32) -> i32 { - times_four(add_three(x)) -} - -fn add_three(x: i32) -> i32 { x + 3 } - -fn times_four(x: i32) -> i32 { x * 4 } - -#[cfg(test)] -mod test { - use super::add_three; - use super::times_four; - - #[test] - fn test_add_three() { - let result = add_three(5); - - assert_eq!(8, result); - } - - #[test] - fn test_times_four() { - let result = times_four(5); - - assert_eq!(20, result); - } -} -``` - -Let's give it a shot: - -```bash -$ cargo test - Compiling testing v0.0.1 (file:///home/you/projects/testing) - Running target/lib-654ce120f310a3a5 - -running 1 test -test math_checks_out ... ok - -test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-6d7518593c7c3ee5 - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured - - Running target/testing-8a94b31f7fd2e8fe - -running 2 tests -test test::test_times_four ... ok -test test::test_add_three ... ok - -test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured - - Doc-tests testing - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured -``` - -Cool! We now have two tests of our internal functions. You'll note that there -are three sets of output now: one for `src/main.rs`, one for `src/lib.rs`, and -one for `tests/lib.rs`. There's one interesting thing that we haven't talked -about yet, and that's these lines: - -```{rust,ignore} -use super::add_three; -use super::times_four; -``` - -Because we've made a nested module, we can import functions from the parent -module by using `super`. Sub-modules are allowed to 'see' private functions in -the parent. - -We've now covered the basics of testing. Rust's tools are primitive, but they -work well in the simple cases. There are some Rustaceans working on building -more complicated frameworks on top of all of this, but they're just starting -out. - -# Pointers - -In systems programming, pointers are an incredibly important topic. Rust has a -very rich set of pointers, and they operate differently than in many other -languages. They are important enough that we have a specific [Pointer -Guide](guide-pointers.html) that goes into pointers in much detail. In fact, -while you're currently reading this guide, which covers the language in broad -overview, there are a number of other guides that put a specific topic under a -microscope. You can find the list of guides on the [documentation index -page](index.html#guides). - -In this section, we'll assume that you're familiar with pointers as a general -concept. If you aren't, please read the [introduction to -pointers](guide-pointers.html#an-introduction) section of the Pointer Guide, -and then come back here. We'll wait. - -Got the gist? Great. Let's talk about pointers in Rust. - -## References - -The most primitive form of pointer in Rust is called a **reference**. -References are created using the ampersand (`&`). Here's a simple -reference: - -```{rust} -let x = 5; -let y = &x; -``` - -`y` is a reference to `x`. To dereference (get the value being referred to -rather than the reference itself) `y`, we use the asterisk (`*`): - -```{rust} -let x = 5; -let y = &x; - -assert_eq!(5, *y); -``` - -Like any `let` binding, references are immutable by default. - -You can declare that functions take a reference: - -```{rust} -fn add_one(x: &i32) -> i32 { *x + 1 } - -fn main() { - assert_eq!(6, add_one(&5)); -} -``` - -As you can see, we can make a reference from a literal by applying `&` as well. -Of course, in this simple function, there's not a lot of reason to take `x` by -reference. It's just an example of the syntax. - -Because references are immutable, you can have multiple references that -**alias** (point to the same place): - -```{rust} -let x = 5; -let y = &x; -let z = &x; -``` - -We can make a mutable reference by using `&mut` instead of `&`: - -```{rust} -let mut x = 5; -let y = &mut x; -``` - -Note that `x` must also be mutable. If it isn't, like this: - -```{rust,ignore} -let x = 5; -let y = &mut x; -``` - -Rust will complain: - -```text -error: cannot borrow immutable local variable `x` as mutable - let y = &mut x; - ^ -``` - -We don't want a mutable reference to immutable data! This error message uses a -term we haven't talked about yet, 'borrow'. We'll get to that in just a moment. - -This simple example actually illustrates a lot of Rust's power: Rust has -prevented us, at compile time, from breaking our own rules. Because Rust's -references check these kinds of rules entirely at compile time, there's no -runtime overhead for this safety. At runtime, these are the same as a raw -machine pointer, like in C or C++. We've just double-checked ahead of time -that we haven't done anything dangerous. - -Rust will also prevent us from creating two mutable references that alias. -This won't work: - -```{rust,ignore} -let mut x = 5; -let y = &mut x; -let z = &mut x; -``` - -It gives us this error: - -```text -error: cannot borrow `x` as mutable more than once at a time - let z = &mut x; - ^ -note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends - let y = &mut x; - ^ -note: previous borrow ends here - fn main() { - let mut x = 5; - let y = &mut x; - let z = &mut x; - } - ^ -``` - -This is a big error message. Let's dig into it for a moment. There are three -parts: the error and two notes. The error says what we expected, we cannot have -two mutable pointers that point to the same memory. - -The two notes give some extra context. Rust's error messages often contain this -kind of extra information when the error is complex. Rust is telling us two -things: first, that the reason we cannot **borrow** `x` as `z` is that we -previously borrowed `x` as `y`. The second note shows where `y`'s borrowing -ends. - -Wait, borrowing? - -In order to truly understand this error, we have to learn a few new concepts: -**ownership**, **borrowing**, and **lifetimes**. - -## Ownership, borrowing, and lifetimes - -Whenever a resource of some kind is created, something must be responsible -for destroying that resource as well. Given that we're discussing pointers -right now, let's discuss this in the context of memory allocation, though -it applies to other resources as well. - -When you allocate heap memory, you need a mechanism to free that memory. Many -languages use a garbage collector to handle deallocation. This is a valid, -time-tested strategy, but it's not without its drawbacks: it adds overhead, and -can lead to unpredictable pauses in execution. Because the programmer does not -have to think as much about deallocation, allocation becomes something -commonplace, leading to more memory usage. And if you need precise control -over when something is deallocated, leaving it up to your runtime can make this -difficult. - -Rust chooses a different path, and that path is called **ownership**. Any -binding that creates a resource is the **owner** of that resource. - -Being an owner affords you some privileges: - -1. You control when that resource is deallocated. -2. You may lend that resource, immutably, to as many borrowers as you'd like. -3. You may lend that resource, mutably, to a single borrower. - -But it also comes with some restrictions: - -1. If someone is borrowing your resource (either mutably or immutably), you may - not mutate the resource or mutably lend it to someone. -2. If someone is mutably borrowing your resource, you may not lend it out at - all (mutably or immutably) or access it in any way. - -What's up with all this 'lending' and 'borrowing'? When you allocate memory, -you get a pointer to that memory. This pointer allows you to manipulate said -memory. If you are the owner of a pointer, then you may allow another -binding to temporarily borrow that pointer, and then they can manipulate the -memory. The length of time that the borrower is borrowing the pointer -from you is called a **lifetime**. - -If two distinct bindings share a pointer, and the memory that pointer points to -is immutable, then there are no problems. But if it's mutable, the result of -changing it can vary unpredictably depending on who happens to access it first, -which is called a **race condition**. To avoid this, if someone wants to mutate -something that they've borrowed from you, you must not have lent out that -pointer to anyone else. - -Rust has a sophisticated system called the **borrow checker** to make sure that -everyone plays by these rules. At compile time, it verifies that none of these -rules are broken. If our program compiles successfully, Rust can guarantee it -is free of data races and other memory errors, and there is no runtime overhead -for any of this. The borrow checker works only at compile time. If the borrow -checker did find a problem, it will report an error and your program will -refuse to compile. - -That's a lot to take in. It's also one of the _most_ important concepts in -all of Rust. Let's see this syntax in action: - -```{rust} -{ - let x = 5; // x is the owner of this integer, which is memory on the stack. - - // other code here... - -} // privilege 1: when x goes out of scope, this memory is deallocated - -/// this function borrows an integer. It's given back automatically when the -/// function returns. -fn foo(x: &i32) -> &i32 { x } - -{ - // x is the owner of the integer, which is memory on the stack. - let x = 5; - - // privilege 2: you may lend that resource to as many borrowers as you like - let y = &x; - let z = &x; - - foo(&x); // functions can borrow too! - - let a = &x; // we can do this alllllll day! -} - -{ - // x is the owner of this integer, which is memory on the stack. - let mut x = 5; - - // privilege 3: you may lend that resource to a single borrower, mutably - let y = &mut x; -} -``` - -If you are a borrower, you get a few privileges as well, but must also obey a -restriction: - -1. If the borrow is immutable, you may read the data the pointer points to. -2. If the borrow is mutable, you may read and write the data the pointer points to. -3. You may lend the pointer to someone else, **BUT** -4. When you do so, they must return it before you can give your own borrow back. - -This last requirement can seem odd, but it also makes sense. If you have to -return something, and you've lent it to someone, they need to give it back to -you for you to give it back! If we didn't, then the owner could deallocate -the memory, and the person we've loaned it out to would have a pointer to -invalid memory. This is called a 'dangling pointer'. - -Let's re-examine the error that led us to talk about all of this, which was a -violation of the restrictions placed on owners who lend something out mutably. -The code: - -```{rust,ignore} -let mut x = 5; -let y = &mut x; -let z = &mut x; -``` - -The error: - -```text -error: cannot borrow `x` as mutable more than once at a time - let z = &mut x; - ^ -note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends - let y = &mut x; - ^ -note: previous borrow ends here - fn main() { - let mut x = 5; - let y = &mut x; - let z = &mut x; - } - ^ -``` - -This error comes in three parts. Let's go over each in turn. - -```text -error: cannot borrow `x` as mutable more than once at a time - let z = &mut x; - ^ -``` - -This error states the restriction: you cannot lend out something mutable more -than once at the same time. The borrow checker knows the rules! - -```text -note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends - let y = &mut x; - ^ -``` - -Some compiler errors come with notes to help you fix the error. This error comes -with two notes, and this is the first. This note informs us of exactly where -the first mutable borrow occurred. The error showed us the second. So now we -see both parts of the problem. It also alludes to rule #3, by reminding us that -we can't change `x` until the borrow is over. - -```text -note: previous borrow ends here - fn main() { - let mut x = 5; - let y = &mut x; - let z = &mut x; - } - ^ -``` - -Here's the second note, which lets us know where the first borrow would be over. -This is useful, because if we wait to try to borrow `x` after this borrow is -over, then everything will work. - -For more advanced patterns, please consult the [Ownership -Guide](guide-ownership.html). You'll also learn what this type signature with -the `'a` syntax is: - -```{rust,ignore} -pub fn as_maybe_owned(&self) -> MaybeOwned<'a> { ... } -``` - -## Boxes - -Most of the types we've seen so far have a fixed size or number of components. -The compiler needs this fact to lay out values in memory. However, some data -structures, such as a linked list, do not have a fixed size. You might think to -implement a linked list with an enum that's either a `Node` or the end of the -list (`Nil`), like this: - -```{rust,ignore} -enum List { // error: illegal recursive enum type - Node(u32, List), - Nil -} -``` - -But the compiler complains that the type is recursive, that is, it could be -arbitrarily large. To remedy this, Rust provides a fixed-size container called -a **box** that can hold any type. You can box up any value with the `box` -keyword. Our boxed List gets the type `Box<List>` (more on the notation when we -get to generics): - -```{rust} -enum List { - Node(u32, Box<List>), - Nil -} - -fn main() { - let list = List::Node(0, box List::Node(1, box List::Nil)); -} -``` - -A box dynamically allocates memory to hold its contents. The great thing about -Rust is that that memory is *automatically*, *efficiently*, and *predictably* -deallocated when you're done with the box. - -A box is a pointer type, and you access what's inside using the `*` operator, -just like regular references. This (rather silly) example dynamically allocates -an integer `5` and makes `x` a pointer to it: - -```{rust} -{ - let x = box 5; - println!("{}", *x); // Prints 5 -} -``` - -The great thing about boxes is that we don't have to manually free this -allocation! Instead, when `x` reaches the end of its lifetime – in this case, -when it goes out of scope at the end of the block – Rust `free`s `x`. This -isn't because Rust has a garbage collector (it doesn't). Instead, by tracking -the ownership and lifetime of a variable (with a little help from you, the -programmer), the compiler knows precisely when it is no longer used. - -The Rust code above will do the same thing as the following C code: - -```{c,ignore} -{ - i32 *x = (i32 *)malloc(sizeof(i32)); - if (!x) abort(); - *x = 5; - printf("%d\n", *x); - free(x); -} -``` - -We get the benefits of manual memory management, while ensuring we don't -introduce any bugs. We can't forget to `free` our memory. - -Boxes are the sole owner of their contents, so you cannot take a mutable -reference to them and then use the original box: - -```{rust,ignore} -let mut x = box 5; -let y = &mut x; - -*x; // you might expect 5, but this is actually an error -``` - -This gives us this error: - -```text -error: cannot use `*x` because it was mutably borrowed - *x; - ^~ -note: borrow of `x` occurs here - let y = &mut x; - ^ -``` - -As long as `y` is borrowing the contents, we cannot use `x`. After `y` is -done borrowing the value, we can use it again. This works fine: - -```{rust} -let mut x = box 5; - -{ - let y = &mut x; -} // y goes out of scope at the end of the block - -*x; -``` - -Boxes are simple and efficient pointers to dynamically allocated values with a -single owner. They are useful for tree-like structures where the lifetime of a -child depends solely on the lifetime of its (single) parent. If you need a -value that must persist as long as any of several referrers, read on. - -## Rc and Arc - -Sometimes you need a variable that is referenced from multiple places -(immutably!), lasting as long as any of those places, and disappearing when it -is no longer referenced. For instance, in a graph-like data structure, a node -might be referenced from all of its neighbors. In this case, it is not possible -for the compiler to determine ahead of time when the value can be freed – it -needs a little run-time support. - -Rust's **Rc** type provides shared ownership of a dynamically allocated value -that is automatically freed at the end of its last owner's lifetime. (`Rc` -stands for 'reference counted', referring to the way these library types are -implemented.) This provides more flexibility than single-owner boxes, but has -some runtime overhead. - -To create an `Rc` value, use `Rc::new()`. To create a second owner, use the -`.clone()` method: - -```{rust} -use std::rc::Rc; - -let x = Rc::new(5); -let y = x.clone(); - -println!("{} {}", *x, *y); // Prints 5 5 -``` - -The `Rc` will live as long as any of its owners are alive. After that, the -memory will be `free`d. - -**Arc** is an 'atomically reference counted' value, identical to `Rc` except -that ownership can be safely shared among multiple threads. Why two types? -`Arc` has more overhead, so if you're not in a multi-threaded scenario, you -don't have to pay the price. - -If you use `Rc` or `Arc`, you have to be careful about introducing cycles. If -you have two `Rc`s that point to each other, they will happily keep each other -alive forever, creating a memory leak. To learn more, check out [the section on -`Rc` and `Arc` in the pointers guide](guide-pointers.html#rc-and-arc). - -# Patterns - -We've made use of patterns a few times in the guide: first with `let` bindings, -then with `match` statements. Let's go on a whirlwind tour of all of the things -patterns can do! - -A quick refresher: you can match against literals directly, and `_` acts as an -'any' case: - -```{rust} -let x = 1; - -match x { - 1 => println!("one"), - 2 => println!("two"), - 3 => println!("three"), - _ => println!("anything"), -} -``` - -You can match multiple patterns with `|`: - -```{rust} -let x = 1; - -match x { - 1 | 2 => println!("one or two"), - 3 => println!("three"), - _ => println!("anything"), -} -``` - -You can match a range of values with `...`: - -```{rust} -let x = 1; - -match x { - 1 ... 5 => println!("one through five"), - _ => println!("anything"), -} -``` - -Ranges are mostly used with integers and single characters. - -If you're matching multiple things, via a `|` or a `...`, you can bind -the value to a name with `@`: - -```{rust} -let x = 1; - -match x { - e @ 1 ... 5 => println!("got a range element {}", e), - _ => println!("anything"), -} -``` - -If you're matching on an enum which has variants, you can use `..` to -ignore the value and type in the variant: - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} - -let x = OptionalInt::Value(5); - -match x { - OptionalInt::Value(..) => println!("Got an i32!"), - OptionalInt::Missing => println!("No such luck."), -} -``` - -You can introduce **match guards** with `if`: - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} - -let x = OptionalInt::Value(5); - -match x { - OptionalInt::Value(i) if i > 5 => println!("Got an i32 bigger than five!"), - OptionalInt::Value(..) => println!("Got an i32!"), - OptionalInt::Missing => println!("No such luck."), -} -``` - -If you're matching on a pointer, you can use the same syntax as you declared it -with. First, `&`: - -```{rust} -let x = &5; - -match x { - &val => println!("Got a value: {}", val), -} -``` - -Here, the `val` inside the `match` has type `i32`. In other words, the left-hand -side of the pattern destructures the value. If we have `&5`, then in `&val`, `val` -would be `5`. - -If you want to get a reference, use the `ref` keyword: - -```{rust} -let x = 5; - -match x { - ref r => println!("Got a reference to {}", r), -} -``` - -Here, the `r` inside the `match` has the type `&i32`. In other words, the `ref` -keyword _creates_ a reference, for use in the pattern. If you need a mutable -reference, `ref mut` will work in the same way: - -```{rust} -let mut x = 5; - -match x { - ref mut mr => println!("Got a mutable reference to {}", mr), -} -``` - -If you have a struct, you can destructure it inside of a pattern: - -```{rust} -# #![allow(non_shorthand_field_patterns)] -struct Point { - x: i32, - y: i32, -} - -let origin = Point { x: 0, y: 0 }; - -match origin { - Point { x: x, y: y } => println!("({},{})", x, y), -} -``` - -If we only care about some of the values, we don't have to give them all names: - -```{rust} -# #![allow(non_shorthand_field_patterns)] -struct Point { - x: i32, - y: i32, -} - -let origin = Point { x: 0, y: 0 }; - -match origin { - Point { x: x, .. } => println!("x is {}", x), -} -``` - -You can do this kind of match on any member, not just the first: - -```{rust} -# #![allow(non_shorthand_field_patterns)] -struct Point { - x: i32, - y: i32, -} - -let origin = Point { x: 0, y: 0 }; - -match origin { - Point { y: y, .. } => println!("y is {}", y), -} -``` - -If you want to match against a slice or array, you can use `[]`: - -```{rust} -fn main() { - let v = vec!["match_this", "1"]; - - match v.as_slice() { - ["match_this", second] => println!("The second element is {}", second), - _ => {}, - } -} -``` - -Whew! That's a lot of different ways to match things, and they can all be -mixed and matched, depending on what you're doing: - -```{rust,ignore} -match x { - Foo { x: Some(ref name), y: None } => ... -} -``` - -Patterns are very powerful. Make good use of them. - -# Method Syntax - -Functions are great, but if you want to call a bunch of them on some data, it -can be awkward. Consider this code: - -```{rust,ignore} -baz(bar(foo(x))); -``` - -We would read this left-to right, and so we see 'baz bar foo.' But this isn't the -order that the functions would get called in, that's inside-out: 'foo bar baz.' -Wouldn't it be nice if we could do this instead? - -```{rust,ignore} -x.foo().bar().baz(); -``` - -Luckily, as you may have guessed with the leading question, you can! Rust provides -the ability to use this **method call syntax** via the `impl` keyword. - -Here's how it works: - -```{rust} -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -fn main() { - let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; - println!("{}", c.area()); -} -``` - -This will print `12.566371`. - -We've made a struct that represents a circle. We then write an `impl` block, -and inside it, define a method, `area`. Methods take a special first -parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`. -You can think of this first parameter as being the `x` in `x.foo()`. The three -variants correspond to the three kinds of things `x` could be: `self` if it's -just a value on the stack, `&self` if it's a reference, and `&mut self` if it's -a mutable reference. We should default to using `&self`, as it's the most -common. - -Finally, as you may remember, the value of the area of a circle is `π*r²`. -Because we took the `&self` parameter to `area`, we can use it just like any -other parameter. Because we know it's a `Circle`, we can access the `radius` -just like we would with any other struct. An import of π and some -multiplications later, and we have our area. - -You can also define methods that do not take a `self` parameter. Here's a -pattern that's very common in Rust code: - -```{rust} -# #![allow(non_shorthand_field_patterns)] -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn new(x: f64, y: f64, radius: f64) -> Circle { - Circle { - x: x, - y: y, - radius: radius, - } - } -} - -fn main() { - let c = Circle::new(0.0, 0.0, 2.0); -} -``` - -This **static method** builds a new `Circle` for us. Note that static methods -are called with the `Struct::method()` syntax, rather than the `ref.method()` -syntax. - -# Closures - -So far, we've made lots of functions in Rust, but we've given them all names. -Rust also allows us to create anonymous functions. Rust's anonymous -functions are called **closure**s. By themselves, closures aren't all that -interesting, but when you combine them with functions that take closures as -arguments, really powerful things are possible. - -Let's make a closure: - -```{rust} -let add_one = |&: x| { 1 + x }; - -println!("The sum of 5 plus 1 is {}.", add_one(5)); -``` - -We create a closure using the `|...| { ... }` syntax, and then we create a -binding so we can use it later. Note that we call the function using the -binding name and two parentheses, just like we would for a named function. - -Let's compare syntax. The two are pretty close: - -```{rust} -let add_one = |&: x: i32| -> i32 { 1 + x }; -fn add_one (x: i32) -> i32 { 1 + x } -``` - -As you may have noticed, closures infer their argument and return types, so you -don't need to declare one. This is different from named functions, which -default to returning unit (`()`). - -There's one big difference between a closure and named functions, and it's in -the name: a closure "closes over its environment." What does that mean? It means -this: - -```{rust} -fn main() { - let x: i32 = 5; - - let printer = |&:| { println!("x is: {}", x); }; - - printer(); // prints "x is: 5" -} -``` - -The `||` syntax means this is an anonymous closure that takes no arguments. -Without it, we'd just have a block of code in `{}`s. - -In other words, a closure has access to variables in the scope where it's -defined. The closure borrows any variables it uses, so this will error: - -```{rust,ignore} -fn main() { - let mut x = 5; - - let printer = |&:| { println!("x is: {}", x); }; - - x = 6; // error: cannot assign to `x` because it is borrowed -} -``` - -## Moving closures - -Rust has a second type of closure, called a **moving closure**. Moving -closures are indicated using the `move` keyword (e.g., `move || x * -x`). The difference between a moving closure and an ordinary closure -is that a moving closure always takes ownership of all variables that -it uses. Ordinary closures, in contrast, just create a reference into -the enclosing stack frame. Moving closures are most useful with Rust's -concurrency features, and so we'll just leave it at this for -now. We'll talk about them more in the "Threads" section of the guide. - -## Accepting closures as arguments - -Closures are most useful as an argument to another function. Here's an example: - -```{rust} -fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { - f(x) + f(x) -} - -fn main() { - let square = |&: x: i32| { x * x }; - - twice(5, square); // evaluates to 50 -} -``` - -Let's break the example down, starting with `main`: - -```{rust} -let square = |&: x: i32| { x * x }; -``` - -We've seen this before. We make a closure that takes an integer, and returns -its square. - -```{rust} -# fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { f(x) + f(x) } -# let square = |&: x: i32| { x * x }; -twice(5, square); // evaluates to 50 -``` - -This line is more interesting. Here, we call our function, `twice`, and we pass -it two arguments: an integer, `5`, and our closure, `square`. This is just like -passing any other two variable bindings to a function, but if you've never -worked with closures before, it can seem a little complex. Just think: "I'm -passing two variables: one is an i32, and one is a function." - -Next, let's look at how `twice` is defined: - -```{rust,ignore} -fn twice(x: i32, f: |i32| -> i32) -> i32 { -``` - -`twice` takes two arguments, `x` and `f`. That's why we called it with two -arguments. `x` is an `i32`, we've done that a ton of times. `f` is a function, -though, and that function takes an `i32` and returns an `i32`. Notice -how the `|i32| -> i32` syntax looks a lot like our definition of `square` -above, if we added the return type in: - -```{rust} -let square = |&: x: i32| -> i32 { x * x }; -// |i32| -> i32 -``` - -This function takes an `i32` and returns an `i32`. - -This is the most complicated function signature we've seen yet! Give it a read -a few times until you can see how it works. It takes a teeny bit of practice, and -then it's easy. - -Finally, `twice` returns an `i32` as well. - -Okay, let's look at the body of `twice`: - -```{rust} -fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { - f(x) + f(x) -} -``` - -Since our closure is named `f`, we can call it just like we called our closures -before, and we pass in our `x` argument to each one, hence the name `twice`. - -If you do the math, `(5 * 5) + (5 * 5) == 50`, so that's the output we get. - -Play around with this concept until you're comfortable with it. Rust's standard -library uses lots of closures where appropriate, so you'll be using -this technique a lot. - -If we didn't want to give `square` a name, we could just define it inline. -This example is the same as the previous one: - -```{rust} -fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { - f(x) + f(x) -} - -fn main() { - twice(5, |x: i32| { x * x }); // evaluates to 50 -} -``` - -A named function's name can be used wherever you'd use a closure. Another -way of writing the previous example: - -```{rust} -fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { - f(x) + f(x) -} - -fn square(x: i32) -> i32 { x * x } - -fn main() { - twice(5, square); // evaluates to 50 -} -``` - -Doing this is not particularly common, but it's useful every once in a while. - -That's all you need to get the hang of closures! Closures are a little bit -strange at first, but once you're used to them, you'll miss them -in other languages. Passing functions to other functions is -incredibly powerful, as you will see in the following chapter about iterators. - -# Iterators - -Let's talk about loops. - -Remember Rust's `for` loop? Here's an example: - -```{rust} -for x in range(0, 10) { - println!("{}", x); -} -``` - -Now that you know more Rust, we can talk in detail about how this works. The -`range` function returns an **iterator**. An iterator is something that we can -call the `.next()` method on repeatedly, and it gives us a sequence of things. - -Like this: - -```{rust} -let mut range = range(0, 10); - -loop { - match range.next() { - Some(x) => { - println!("{}", x); - }, - None => { break } - } -} -``` - -We make a mutable binding to the return value of `range`, which is our iterator. -We then `loop`, with an inner `match`. This `match` is used on the result of -`range.next()`, which gives us a reference to the next value of the iterator. -`next` returns an `Option<i32>`, in this case, which will be `Some(i32)` when -we have a value and `None` once we run out. If we get `Some(i32)`, we print it -out, and if we get `None`, we `break` out of the loop. - -This code sample is basically the same as our `for` loop version. The `for` -loop is just a handy way to write this `loop`/`match`/`break` construct. - -`for` loops aren't the only thing that uses iterators, however. Writing your -own iterator involves implementing the `Iterator` trait. While doing that is -outside of the scope of this guide, Rust provides a number of useful iterators -to accomplish various tasks. Before we talk about those, we should talk about a -Rust anti-pattern. And that's `range`. - -Yes, we just talked about how `range` is cool. But `range` is also very -primitive. For example, if you needed to iterate over the contents of -a vector, you may be tempted to write this: - -```{rust} -let nums = vec![1, 2, 3]; - -for i in range(0u, nums.len()) { - println!("{}", nums[i]); -} -``` - -This is strictly worse than using an actual iterator. The `.iter()` method on -vectors returns an iterator that iterates through a reference to each element -of the vector in turn. So write this: - -```{rust} -let nums = vec![1, 2, 3]; - -for num in nums.iter() { - println!("{}", num); -} -``` - -There are two reasons for this. First, this more directly expresses what we -mean. We iterate through the entire vector, rather than iterating through -indexes, and then indexing the vector. Second, this version is more efficient: -the first version will have extra bounds checking because it used indexing, -`nums[i]`. But since we yield a reference to each element of the vector in turn -with the iterator, there's no bounds checking in the second example. This is -very common with iterators: we can ignore unnecessary bounds checks, but still -know that we're safe. - -There's another detail here that's not 100% clear because of how `println!` -works. `num` is actually of type `&i32`. That is, it's a reference to an `i32`, -not an `i32` itself. `println!` handles the dereferencing for us, so we don't -see it. This code works fine too: - -```{rust} -let nums = vec![1, 2, 3]; - -for num in nums.iter() { - println!("{}", *num); -} -``` - -Now we're explicitly dereferencing `num`. Why does `iter()` give us references? -Well, if it gave us the data itself, we would have to be its owner, which would -involve making a copy of the data and giving us the copy. With references, -we're just borrowing a reference to the data, and so it's just passing -a reference, without needing to do the copy. - -So, now that we've established that `range` is often not what you want, let's -talk about what you do want instead. - -There are three broad classes of things that are relevant here: iterators, -**iterator adapters**, and **consumers**. Here's some definitions: - -* 'iterators' give you a sequence of values. -* 'iterator adapters' operate on an iterator, producing a new iterator with a - different output sequence. -* 'consumers' operate on an iterator, producing some final set of values. - -Let's talk about consumers first, since you've already seen an iterator, -`range`. - -## Consumers - -A 'consumer' operates on an iterator, returning some kind of value or values. -The most common consumer is `collect()`. This code doesn't quite compile, -but it shows the intention: - -```{rust,ignore} -let one_to_one_hundred = range(1, 101).collect(); -``` - -As you can see, we call `collect()` on our iterator. `collect()` takes -as many values as the iterator will give it, and returns a collection -of the results. So why won't this compile? Rust can't determine what -type of things you want to collect, and so you need to let it know. -Here's the version that does compile: - -```{rust} -let one_to_one_hundred = range(1, 101).collect::<Vec<i32>>(); -``` - -If you remember, the `::<>` syntax allows us to give a type hint, -and so we tell it that we want a vector of integers. - -`collect()` is the most common consumer, but there are others too. `find()` -is one: - -```{rust} -let greater_than_forty_two = range(0, 100) - .find(|x| *x > 42); - -match greater_than_forty_two { - Some(_) => println!("We got some numbers!"), - None => println!("No numbers found :("), -} -``` - -`find` takes a closure, and works on a reference to each element of an -iterator. This closure returns `true` if the element is the element we're -looking for, and `false` otherwise. Because we might not find a matching -element, `find` returns an `Option` rather than the element itself. - -Another important consumer is `fold`. Here's what it looks like: - -```{rust} -let sum = range(1, 4) - .fold(0, |sum, x| sum + x); -``` - -`fold()` is a consumer that looks like this: -`fold(base, |accumulator, element| ...)`. It takes two arguments: the first -is an element called the "base". The second is a closure that itself takes two -arguments: the first is called the "accumulator," and the second is an -"element." Upon each iteration, the closure is called, and the result is the -value of the accumulator on the next iteration. On the first iteration, the -base is the value of the accumulator. - -Okay, that's a bit confusing. Let's examine the values of all of these things -in this iterator: - -| base | accumulator | element | closure result | -|------|-------------|---------|----------------| -| 0 | 0 | 1 | 1 | -| 0 | 1 | 2 | 3 | -| 0 | 3 | 3 | 6 | - -We called `fold()` with these arguments: - -```{rust} -# range(1, 4) -.fold(0, |sum, x| sum + x); -``` - -So, `0` is our base, `sum` is our accumulator, and `x` is our element. On the -first iteration, we set `sum` to `0`, and `x` is the first element of `nums`, -`1`. We then add `sum` and `x`, which gives us `0 + 1 = 1`. On the second -iteration, that value becomes our accumulator, `sum`, and the element is -the second element of the array, `2`. `1 + 2 = 3`, and so that becomes -the value of the accumulator for the last iteration. On that iteration, -`x` is the last element, `3`, and `3 + 3 = 6`, which is our final -result for our sum. `1 + 2 + 3 = 6`, and that's the result we got. - -Whew. `fold` can be a bit strange the first few times you see it, but once it -clicks, you can use it all over the place. Any time you have a list of things, -and you want a single result, `fold` is appropriate. - -Consumers are important due to one additional property of iterators we haven't -talked about yet: laziness. Let's talk some more about iterators, and you'll -see why consumers matter. - -## Iterators - -As we've said before, an iterator is something that we can call the -`.next()` method on repeatedly, and it gives us a sequence of things. -Because you need to call the method, this means that iterators -are **lazy** and don't need to generate all of the values upfront. -This code, for example, does not actually generate the numbers -`1-100`, and just creates a value that represents the sequence: - -```{rust} -let nums = range(1, 100); -``` - -Since we didn't do anything with the range, it didn't generate the sequence. -Let's add the consumer: - -```{rust} -let nums = range(1, 100).collect::<Vec<i32>>(); -``` - -Now, `collect()` will require that `range()` give it some numbers, and so -it will do the work of generating the sequence. - -`range` is one of two basic iterators that you'll see. The other is `iter()`, -which you've used before. `iter()` can turn a vector into a simple iterator -that gives you each element in turn: - -```{rust} -let nums = [1, 2, 3]; - -for num in nums.iter() { - println!("{}", num); -} -``` - -These two basic iterators should serve you well. There are some more -advanced iterators, including ones that are infinite. Like `count`: - -```{rust} -std::iter::count(1, 5); -``` - -This iterator counts up from one, adding five each time. It will give -you a new integer every time, forever (well, technically, until it reaches the -maximum number representable by an `i32`). But since iterators are lazy, -that's okay! You probably don't want to use `collect()` on it, though... - -That's enough about iterators. Iterator adapters are the last concept -we need to talk about with regards to iterators. Let's get to it! - -## Iterator adapters - -"Iterator adapters" take an iterator and modify it somehow, producing -a new iterator. The simplest one is called `map`: - -```{rust,ignore} -range(1, 100).map(|x| x + 1); -``` - -`map` is called upon another iterator, and produces a new iterator where each -element reference has the closure it's been given as an argument called on it. -So this would give us the numbers from `2-100`. Well, almost! If you -compile the example, you'll get a warning: - -```text -warning: unused result which must be used: iterator adaptors are lazy and - do nothing unless consumed, #[warn(unused_must_use)] on by default - range(1, 100).map(|x| x + 1); - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -``` - -Laziness strikes again! That closure will never execute. This example -doesn't print any numbers: - -```{rust,ignore} -range(1, 100).map(|x| println!("{}", x)); -``` - -If you are trying to execute a closure on an iterator for its side effects, -just use `for` instead. - -There are tons of interesting iterator adapters. `take(n)` will return an -iterator over the next `n` elements of the original iterator, note that this -has no side effect on the original iterator. Let's try it out with our infinite -iterator from before, `count()`: - -```{rust} -for i in std::iter::count(1, 5).take(5) { - println!("{}", i); -} -``` - -This will print - -```text -1 -6 -11 -16 -21 -``` - -`filter()` is an adapter that takes a closure as an argument. This closure -returns `true` or `false`. The new iterator `filter()` produces -only the elements that that closure returns `true` for: - -```{rust} -for i in range(1, 100).filter(|&x| x % 2 == 0) { - println!("{}", i); -} -``` - -This will print all of the even numbers between one and a hundred. -(Note that because `filter` doesn't consume the elements that are -being iterated over, it is passed a reference to each element, and -thus the filter predicate uses the `&x` pattern to extract the integer -itself.) - -You can chain all three things together: start with an iterator, adapt it -a few times, and then consume the result. Check it out: - -```{rust} -range(1, 1000) - .filter(|&x| x % 2 == 0) - .filter(|&x| x % 3 == 0) - .take(5) - .collect::<Vec<i32>>(); -``` - -This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. - -This is just a small taste of what iterators, iterator adapters, and consumers -can help you with. There are a number of really useful iterators, and you can -write your own as well. Iterators provide a safe, efficient way to manipulate -all kinds of lists. They're a little unusual at first, but if you play with -them, you'll get hooked. For a full list of the different iterators and -consumers, check out the [iterator module documentation](std/iter/index.html). - -# Generics - -Sometimes, when writing a function or data type, we may want it to work for -multiple types of arguments. For example, remember our `OptionalInt` type? - -```{rust} -enum OptionalInt { - Value(i32), - Missing, -} -``` - -If we wanted to also have an `OptionalFloat64`, we would need a new enum: - -```{rust} -enum OptionalFloat64 { - Valuef64(f64), - Missingf64, -} -``` - -Such repetition is unfortunate. Luckily, Rust has a feature that gives us a -better way: **generics**. Generics are called **parametric polymorphism** in -type theory, which means that they are types or functions that have multiple -forms over a given parameter ("parametric"). - -Let's see how generics help us escape `OptionalInt`. `Option` is already -provided in Rust's standard library and looks like this: - -```rust -enum Option<T> { - Some(T), - None, -} -``` - -The `<T>` part, which you've seen a few times before, indicates that this is a -generic data type. `T` is called a **type parameter**. When we create instances -of `Option`, we need to provide a concrete type in place of the type -parameter. For example, if we wanted something like our `OptionalInt`, we would -need to instantiate an `Option<i32>`. Inside the declaration of our enum, -wherever we see a `T`, we replace it with the type specified (or inferred by the -compiler). - -```{rust} -let x: Option<i32> = Some(5); -``` - -In this particular `Option`, `T` has the value of `i32`. On the right-hand side -of the binding, we do make a `Some(T)`, where `T` is `5`. Since that's an -`i32`, the two sides match, and Rust is happy. If they didn't match, we'd get an -error: - -```{rust,ignore} -let x: Option<f64> = Some(5); -// error: mismatched types: expected `core::option::Option<f64>`, -// found `core::option::Option<i32>` (expected f64, found i32) -``` - -That doesn't mean we can't make `Option<T>`s that hold an `f64`! They just have to -match up: - -```{rust} -let x: Option<i32> = Some(5); -let y: Option<f64> = Some(5.0f64); -``` - -Generics don't have to only be generic over one type. Consider Rust's built-in -`Result<T, E>` type: - -```{rust} -enum Result<T, E> { - Ok(T), - Err(E), -} -``` - -This type is generic over _two_ types: `T` and `E`. By the way, the capital letters -can be any letter you'd like. We could define `Result<T, E>` as: - -```{rust} -enum Result<H, N> { - Ok(H), - Err(N), -} -``` - -Convention says that the first generic parameter should be `T`, for "type," and -that we use `E` for "error." - -The `Result<T, E>` type is intended to be used to return the result of a -computation and to have the ability to return an error if it didn't work -out. Here's an example: - -```{rust} -let x: Result<f64, String> = Ok(2.3f64); -let y: Result<f64, String> = Err("There was an error.".to_string()); -``` - -This particular `Result` will return an `f64` upon success and a `String` if -there's a failure. Let's write a function that uses `Result<T, E>`: - -```{rust} -fn inverse(x: f64) -> Result<f64, String> { - if x == 0.0f64 { return Err("x cannot be zero!".to_string()); } - - Ok(1.0f64 / x) -} -``` - -We want to indicate that `inverse(0.0f64)` is undefined or is an erroneous usage -of the function, so we check to make sure that we weren't passed zero. If we -were, we return an `Err` with a message. If it's okay, we return an `Ok` with -the answer. - -Why does this matter? Well, remember how `match` does exhaustive matches? -Here's how this function gets used: - -```{rust} -# fn inverse(x: f64) -> Result<f64, String> { -# if x == 0.0f64 { return Err("x cannot be zero!".to_string()); } -# Ok(1.0f64 / x) -# } -let x = inverse(25.0f64); - -match x { - Ok(x) => println!("The inverse of 25 is {}", x), - Err(msg) => println!("Error: {}", msg), -} -``` - -The `match` enforces that we handle the `Err` case. In addition, because the -answer is wrapped up in an `Ok`, we can't just use the result without doing -the match: - -```{rust,ignore} -let x = inverse(25.0f64); -println!("{}", x + 2.0f64); // error: binary operation `+` cannot be applied - // to type `core::result::Result<f64,collections::string::String>` -``` - -This function is great, but there's one other problem: it only works for 64 bit -floating point values. If we wanted to handle 32 bit floating point values we'd -have to write this: - -```{rust} -fn inverse32(x: f32) -> Result<f32, String> { - if x == 0.0f32 { return Err("x cannot be zero!".to_string()); } - - Ok(1.0f32 / x) -} -``` - -What we need is a **generic function**. We can do that with Rust! However, it -won't _quite_ work yet. We need to talk about syntax. A first attempt at a -generic version of `inverse` might look something like this: - -```{rust,ignore} -fn inverse<T>(x: T) -> Result<T, String> { - if x == 0.0 { return Err("x cannot be zero!".to_string()); } - - Ok(1.0 / x) -} -``` - -Just like how we had `Option<T>`, we use a similar syntax for `inverse<T>`. We -can then use `T` inside the rest of the signature: `x` has type `T`, and half of -the `Result` has type `T`. However, if we try to compile that example, we'll get -some errors: - -```text -error: binary operation `==` cannot be applied to type `T` - if x == 0.0 { return Err("x cannot be zero!".to_string()); } - ^~~~~~~~ -error: mismatched types: expected `_`, found `T` (expected floating-point variable, found type parameter) - Ok(1.0 / x) - ^ -error: mismatched types: expected `core::result::Result<T, collections::string::String>`, found `core::result::Result<_, _>` (expected type parameter, found floating-point variable) - Ok(1.0 / x) - ^~~~~~~~~~~ -``` - -The problem is that `T` is unconstrained: it can be _any_ type. It could be a -`String`, and the expression `1.0 / x` has no meaning if `x` is a `String`. It -may be a type that doesn't implement `==`, and the first line would be -wrong. What do we do? - -To fix this example, we need to learn about another Rust feature: **traits**. - -# Traits - -Our discussion of **traits** begins with the `impl` keyword. We used it before -to specify methods. - -```{rust} -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -We define a trait in terms of its methods. We then `impl` a trait `for` a type -(or many types). - -```{rust} -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} -``` - -The `trait` block defines only type signatures. When we `impl` a trait, we use -`impl Trait for Item`, rather than just `impl Item`. - -The first of the three errors we got with our generic `inverse` function was -this: - -```text -error: binary operation `==` cannot be applied to type `T` -``` - -We can use traits to constrain generic type parameters. Consider this function, -which does not compile, and gives us a similar error: - -```{rust,ignore} -fn print_area<T>(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -Rust complains: - -```text -error: type `T` does not implement any method in scope named `area` -``` - -Because `T` can be any type, we can't be sure that it implements the `area` -method. But we can add a **trait constraint** to our generic `T`, ensuring that -we can only compile the function if it's called with types which `impl` the -`HasArea` trait: - -```{rust} -# trait HasArea { -# fn area(&self) -> f64; -# } -fn print_area<T: HasArea>(shape: T) { - println!("This shape has an area of {}", shape.area()); -} -``` - -The syntax `<T: HasArea>` means "any type that implements the HasArea trait." -Because traits define method signatures, we can be sure that any type which -implements `HasArea` will have an `area` method. - -Here's an extended example of how this works: - -```{rust} -trait HasArea { - fn area(&self) -> f64; -} - -struct Circle { - x: f64, - y: f64, - radius: f64, -} - -impl HasArea for Circle { - fn area(&self) -> f64 { - std::f64::consts::PI * (self.radius * self.radius) - } -} - -struct Square { - x: f64, - y: f64, - side: f64, -} - -impl HasArea for Square { - fn area(&self) -> f64 { - self.side * self.side - } -} - -fn print_area<T: HasArea>(shape: T) { - println!("This shape has an area of {}", shape.area()); -} - -fn main() { - let c = Circle { - x: 0.0f64, - y: 0.0f64, - radius: 1.0f64, - }; - - let s = Square { - x: 0.0f64, - y: 0.0f64, - side: 1.0f64, - }; - - print_area(c); - print_area(s); -} -``` - -This program outputs: - -```text -This shape has an area of 3.141593 -This shape has an area of 1 -``` - -As you can see, `print_area` is now generic, but also ensures that we -have passed in the correct types. If we pass in an incorrect type: - -```{rust,ignore} -print_area(5); -``` - -We get a compile-time error: - -```text -error: failed to find an implementation of trait main::HasArea for i32 -``` - -So far, we've only added trait implementations to structs, but you can -implement a trait for any type. So technically, we _could_ implement -`HasArea` for `i32`: - -```{rust} -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for i32 { - fn area(&self) -> f64 { - println!("this is silly"); - - *self as f64 - } -} - -5.area(); -``` - -It is considered poor style to implement methods on such primitive types, even -though it is possible. - -## Scoped Method Resolution and Orphan `impl`s - -There are two restrictions for implementing traits that prevent this from -getting out of hand. - -1. **Scope-based Method Resolution**: Traits must be `use`d in any scope where - you wish to use the trait's methods -2. **No Orphan `impl`s**: Either the trait or the type you're writing the `impl` - for must be inside your crate. - -If we organize our crate differently by using modules, we'll need to ensure both -of the conditions are satisfied. Don't worry, you can lean on the compiler since -it won't let you get away with violating them. - -```{rust} -use shapes::HasArea; // satisfies #1 - -mod shapes { - use std::f64::consts; - - pub trait HasArea { - fn area(&self) -> f64; - } - - pub struct Circle { - pub x: f64, - pub y: f64, - pub radius: f64, - } - - impl HasArea for Circle { - fn area(&self) -> f64 { - consts::PI * (self.radius * self.radius) - } - } -} - -fn main() { - // use shapes::HasArea; // This would satisfy #1, too - let c = shapes::Circle { - x: 0.0f64, - y: 0.0f64, - radius: 1.0f64, - }; - - println!("{}", c.area()); -} -``` - -Requiring us to `use` traits whose methods we want means that even if someone -does something bad like add methods to `i32`, it won't affect us, unless you -`use` that trait. - -The second condition allows us to `impl` built-in `trait`s for types we define, -or allows us to `impl` our own `trait`s for built-in types, but restricts us -from mixing and matching third party or built-in `impl`s with third party or -built-in types. - -We could `impl` the `HasArea` trait for `i32`, because `HasArea` is in our -crate. But if we tried to implement `Float`, a standard library `trait`, for -`i32`, we could not, because neither the `trait` nor the `type` are in our -crate. - -## Monomorphization - -One last thing about generics and traits: the compiler performs -**monomorphization** on generic functions so they are statically dispatched. To -see what that means, let's take a look at `print_area` again: - -```{rust,ignore} -fn print_area<T: HasArea>(shape: T) { - println!("This shape has an area of {}", shape.area()); -} - -fn main() { - let c = Circle { ... }; - - let s = Square { ... }; - - print_area(c); - print_area(s); -} -``` - -Because we have called `print_area` with two different types in place of its -type paramater `T`, Rust will generate two versions of the function with the -appropriate concrete types, replacing the call sites with calls to the concrete -implementations. In other words, the compiler will actually compile something -more like this: - -```{rust,ignore} -fn __print_area_circle(shape: Circle) { - println!("This shape has an area of {}", shape.area()); -} - -fn __print_area_square(shape: Square) { - println!("This shape has an area of {}", shape.area()); -} - -fn main() { - let c = Circle { ... }; - - let s = Square { ... }; - - __print_area_circle(c); - __print_area_square(s); -} -``` - -These names are for illustration; the compiler will generate its own cryptic -names for internal uses. The point is that there is no runtime overhead of -deciding which version to call. The function to be called is determined -statically, at compile time. Thus, generic functions are **statically -dispatched**. The downside is that we have two similar functions, so our binary -is larger. - -# Threads - -Concurrency and parallelism are topics that are of increasing interest to a -broad subsection of software developers. Modern computers are often multi-core, -to the point that even embedded devices like cell phones have more than one -processor. Rust's semantics lend themselves very nicely to solving a number of -issues that programmers have with concurrency. Many concurrency errors that are -runtime errors in other languages are compile-time errors in Rust. - -Rust's concurrency primitive is called a **thread**. It's worth noting that -threads are implemented as a library, and not part of the language. This means -that in the future, other concurrency libraries can be written for Rust to help -in specific scenarios. Here's an example of creating a thread: - -```{rust,ignore} -spawn(move || { - println!("Hello from a thread!"); -}); -``` - -The `spawn` function takes a closure as an argument, and runs that -closure in a new thread. Typically, you will want to use a moving -closure, so that the closure takes ownership of any variables that it -touches. This implies that those variables are not usable from the -parent thread after the child thread is spawned: - -```{rust,ignore} -let mut x = vec![1, 2, 3]; - -spawn(move || { - println!("The value of x[0] is: {}", x[0]); -}); - -println!("The value of x[0] is: {}", x[0]); // error: use of moved value: `x` -``` - -`x` is now owned by the closure, and so we can't use it anymore. Many -other languages would let us do this, but it's not safe to do -so. Rust's borrow checker catches the error. - -If threads were only able to capture these values, they wouldn't be very useful. -Luckily, threads can communicate with each other through **channel**s. Channels -work like this: - -```{rust,ignore} -let (tx, rx) = channel(); - -spawn(move || { - tx.send("Hello from a thread!".to_string()); -}); - -let message = rx.recv(); -println!("{}", message); -``` - -The `channel()` function returns two endpoints: a `Receiver<T>` and a -`Sender<T>`. You can use the `.send()` method on the `Sender<T>` end, and -receive the message on the `Receiver<T>` side with the `recv()` method. This -method blocks until it gets a message. There's a similar method, `.try_recv()`, -which returns an `Result<T, TryRecvError>` and does not block. - -If you want to send messages to the thread as well, create two channels! - -```{rust,ignore} -let (tx1, rx1) = channel(); -let (tx2, rx2) = channel(); - -spawn(move || { - tx1.send("Hello from a thread!".to_string()); - let message = rx2.recv(); - println!("{}", message); -}); - -let message = rx1.recv(); -println!("{}", message); - -tx2.send("Goodbye from main!".to_string()); -``` - -The closure has one sending end and one receiving end, and the main thread has -one of each as well. Now they can talk back and forth in whatever way they -wish. - -Notice as well that because `Sender` and `Receiver` are generic, while you can -pass any kind of information through the channel, the ends are strongly typed. -If you try to pass a string, and then an integer, Rust will complain. - -## Futures - -With these basic primitives, many different concurrency patterns can be -developed. Rust includes some of these types in its standard library. For -example, if you wish to compute some value in the background, `Future` is -a useful thing to use: - -```{rust} -# #![allow(deprecated)] -use std::sync::Future; - -let mut delayed_value = Future::spawn(move || { - // just return anything for examples' sake - - 12345 -}); -println!("value = {}", delayed_value.get()); -``` - -Calling `Future::spawn` works just like `spawn()`: it takes a -closure. In this case, though, you don't need to mess with the -channel: just have the closure return the value. - -`Future::spawn` will return a value which we can bind with `let`. It needs -to be mutable, because once the value is computed, it saves a copy of the -value, and if it were immutable, it couldn't update itself. - -The future will go on processing in the background, and when we need -the final value, we can call `get()` on it. This will block until the -result is done, but if it's finished computing in the background, -we'll just get the value immediately. - -## Success and failure - -Threads don't always succeed, they can also panic. A thread that wishes to panic -can call the `panic!` macro, passing a message: - -```{rust,ignore} -spawn(move || { - panic!("Nope."); -}); -``` - -If a thread panics, it is not possible for it to recover. However, it can -notify other thread that it has panicked. We can do this with `thread::try`: - -```{rust,ignore} -use std::thread; -use std::rand; - -let result = thread::try(move || { - if rand::random() { - println!("OK"); - } else { - panic!("oops!"); - } -}); -``` - -This thread will randomly panic or succeed. `thread::try` returns a `Result` -type, so we can handle the response like any other computation that may -fail. - -# Macros - -One of Rust's most advanced features is its system of **macro**s. While -functions allow you to provide abstractions over values and operations, macros -allow you to provide abstractions over syntax. Do you wish Rust had the ability -to do something that it can't currently do? You may be able to write a macro -to extend Rust's capabilities. - -You've already used one macro extensively: `println!`. When we invoke -a Rust macro, we need to use the exclamation mark (`!`). There are two reasons -why this is so: the first is that it makes it clear when you're using a -macro. The second is that macros allow for flexible syntax, and so Rust must -be able to tell where a macro starts and ends. The `!(...)` helps with this. - -Let's talk some more about `println!`. We could have implemented `println!` as -a function, but it would be worse. Why? Well, what macros allow you to do -is write code that generates more code. So when we call `println!` like this: - -```{rust} -let x = 5; -println!("x is: {}", x); -``` - -The `println!` macro does a few things: - -1. It parses the string to find any `{}`s. -2. It checks that the number of `{}`s matches the number of other arguments. -3. It generates a bunch of Rust code, taking this in mind. - -What this means is that you get type checking at compile time, because -Rust will generate code that takes all of the types into account. If -`println!` was a function, it could still do this type checking, but it -would happen at run time rather than compile time. - -We can check this out using a special flag to `rustc`. Put this code in a file -called `print.rs`: - -```{rust} -fn main() { - let x = 5; - println!("x is: {}", x); -} -``` - -You can have the macros expanded like this: `rustc --pretty=expanded print.rs`, which will -give us this huge result: - -```{rust,ignore} -#![feature(phase)] -#![no_std] -#![feature(globs)] -#[phase(plugin, link)] -extern crate "std" as std; -extern crate "native" as rt; -#[prelude_import] -use std::prelude::*; -fn main() { - let x = 5; - match (&x,) { - (__arg0,) => { - #[inline] - #[allow(dead_code)] - static __STATIC_FMTSTR: [&'static str, ..1u] = ["x is: "]; - let __args_vec = - &[::std::fmt::argument(::std::fmt::secret_show, __arg0)]; - let __args = - unsafe { - ::std::fmt::Arguments::new(__STATIC_FMTSTR, __args_vec) - }; - ::std::io::stdio::println_args(&__args) - } - }; -} -``` - -Whew! This isn't too terrible. You can see that we still `let x = 5`, -but then things get a little bit hairy. Three more bindings get set: a -static format string, an argument vector, and the arguments. We then -invoke the `println_args` function with the generated arguments. - -This is the code that Rust actually compiles. You can see all of the extra -information that's here. We get all of the type safety and options that it -provides, but at compile time, and without needing to type all of this out. -This is how macros are powerful: without them you would need to type all of -this by hand to get a type-checked `println`. - -For more on macros, please consult [the Macros Guide](guide-macros.html). -Macros are a very advanced and still slightly experimental feature, but they don't -require a deep understanding to be called, since they look just like functions. The -Guide can help you if you want to write your own. - -# Unsafe - -Finally, there's one more Rust concept that you should be aware of: `unsafe`. -There are two circumstances where Rust's safety provisions don't work well. -The first is when interfacing with C code, and the second is when building -certain kinds of abstractions. - -Rust has support for [FFI](http://en.wikipedia.org/wiki/Foreign_function_interface) -(which you can read about in the [FFI Guide](guide-ffi.html)), but can't guarantee -that the C code will be safe. Therefore, Rust marks such functions with the `unsafe` -keyword, which indicates that the function may not behave properly. - -Second, if you'd like to create some sort of shared-memory data structure, Rust -won't allow it, because memory must be owned by a single owner. However, if -you're planning on making access to that shared memory safe – such as with a -mutex – _you_ know that it's safe, but Rust can't know. Writing an `unsafe` -block allows you to ask the compiler to trust you. In this case, the _internal_ -implementation of the mutex is considered unsafe, but the _external_ interface -we present is safe. This allows it to be effectively used in normal Rust, while -being able to implement functionality that the compiler can't double check for -us. - -Doesn't an escape hatch undermine the safety of the entire system? Well, if -Rust code segfaults, it _must_ be because of unsafe code somewhere. By -annotating exactly where that is, you have a significantly smaller area to -search. - -We haven't even talked about any examples here, and that's because I want to -emphasize that you should not be writing unsafe code unless you know exactly -what you're doing. The vast majority of Rust developers will only interact with -it when doing FFI, and advanced library authors may use it to build certain -kinds of abstraction. - -# Conclusion - -We covered a lot of ground here. When you've mastered everything in this Guide, -you will have a firm grasp of basic Rust development. There's a whole lot more -out there, we've just covered the surface. There's tons of topics that you can -dig deeper into, and we've built specialized guides for many of them. To learn -more, dig into the [full documentation index](index.html). - -Happy hacking! diff --git a/src/doc/index.md b/src/doc/index.md index 7f22c1eeb85..25dcc10d893 100644 --- a/src/doc/index.md +++ b/src/doc/index.md @@ -9,10 +9,11 @@ If you haven't seen Rust at all yet, the first thing you should read is the [30 minute intro](intro.html). It will give you an overview of the basic ideas of Rust at a high level. -Once you know you really want to learn Rust, the next step is reading [the -guide](guide.html). It is a lengthy explanation of Rust, its syntax, and its -concepts. Upon completing the guide, you'll be an intermediate Rust developer, -and will have a good grasp of the fundamental ideas behind Rust. +Once you know you really want to learn Rust, the next step is reading [The +Rust Programming Language](book/index.html). It is a lengthy explanation of +Rust, its syntax, and its concepts. Upon completing the book, you'll be an +intermediate Rust developer, and will have a good grasp of the fundamental +ideas behind Rust. # Community & Getting Help @@ -48,24 +49,6 @@ development of Rust itself is discussed. Rust does not have an exact specification, but an effort to describe as much of the language in as much detail as possible is in [the reference](reference.html). -# Guides - -Rust Guides are in-depth looks at a particular topic that's relevant to Rust -development. If you're trying to figure out how to do something, there may be -a guide that can help you out: - -* [Ownership](guide-ownership.html) -* [Strings](guide-strings.html) -* [Pointers](guide-pointers.html) -* [Crates and modules](guide-crates.html) -* [Threads and Communication](guide-tasks.html) -* [Error Handling](guide-error-handling.html) -* [Foreign Function Interface](guide-ffi.html) -* [Writing Unsafe and Low-Level Code](guide-unsafe.html) -* [Macros](guide-macros.html) -* [Testing](guide-testing.html) -* [Compiler Plugins](guide-plugin.html) - # Tools Rust's still a young language, so there isn't a ton of tooling yet, but the diff --git a/src/doc/intro.md b/src/doc/intro.md index fbc96a577a4..cb28586d103 100644 --- a/src/doc/intro.md +++ b/src/doc/intro.md @@ -7,8 +7,8 @@ This introduction will give you a rough idea of what Rust is like, eliding many details. It does not require prior experience with systems programming, but you may find the syntax easier if you've used a 'curly brace' programming language before, like C or JavaScript. The concepts are more important than the syntax, -so don't worry if you don't get every last detail: you can read [the -Guide](guide.html) to get a more complete explanation. +so don't worry if you don't get every last detail: you can read [The +Rust Programming Language](book/index.html) to get a more complete explanation. Because this is about high-level concepts, you don't need to actually install Rust to follow along. If you'd like to anyway, check out [the @@ -542,7 +542,7 @@ use std::thread::Thread; fn main() { let vec = vec![1i, 2, 3]; - for i in range(1u, 3) { + for i in range(0u, 3) { Thread::spawn(move || { println!("{}", vec[i]); }).detach(); @@ -558,7 +558,7 @@ a vector: ```{rust} let vec = vec![1i, 2, 3]; -for i in range(1u, vec.len()) { +for i in range(0u, vec.len()) { println!("{}", vec[i]); } ``` @@ -587,5 +587,6 @@ the type system helps you find bugs, how Rust can help you write correct concurrent code, and how you don't have to pay a speed cost for much of this safety. -To continue your Rustic education, read [the guide](guide.html) for a more -in-depth exploration of Rust's syntax and concepts. +To continue your Rustic education, read [The Rust Programming +Language](book/index.html) for a more in-depth exploration of Rust's syntax and +concepts. diff --git a/src/doc/reference.md b/src/doc/reference.md index febd5f883d1..2486466c869 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -14,7 +14,7 @@ provides three kinds of material: influenced the design. This document does not serve as an introduction to the language. Background -familiarity with the language is assumed. A separate [guide] is available to +familiarity with the language is assumed. A separate [book] is available to help acquire such background familiarity. This document also does not serve as a reference to the [standard] library @@ -23,7 +23,7 @@ separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you're looking for may be there, not here. -[guide]: guide.html +[book]: book/index.html [standard]: std/index.html # Notation @@ -647,10 +647,10 @@ All of the above extensions are expressions with values. Users of `rustc` can define new syntax extensions in two ways: -* [Compiler plugins](guide-plugin.html#syntax-extensions) can include arbitrary +* [Compiler plugins](book/syntax-extensions.html) can include arbitrary Rust code that manipulates syntax trees at compile time. -* [Macros](guide-macros.html) define new syntax in a higher-level, +* [Macros](book/macros.html) define new syntax in a higher-level, declarative way. ## Macros @@ -1588,10 +1588,11 @@ pointer values (pointing to a type for which an implementation of the given trait is in scope) to pointers to the trait name, used as a type. ``` +# use std::boxed::Box; # trait Shape { } # impl Shape for int { } # let mycircle = 0i; -let myshape: Box<Shape> = box mycircle as Box<Shape>; +let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>; ``` The resulting value is a box containing the value that was cast, along with @@ -1646,12 +1647,13 @@ fn radius_times_area<T: Circle>(c: T) -> f64 { Likewise, supertrait methods may also be called on trait objects. ```{.ignore} +# use std::boxed::Box; # trait Shape { fn area(&self) -> f64; } # trait Circle : Shape { fn radius(&self) -> f64; } # impl Shape for int { fn area(&self) -> f64 { 0.0 } } # impl Circle for int { fn radius(&self) -> f64 { 0.0 } } # let mycircle = 0; -let mycircle = box mycircle as Box<Circle>; +let mycircle = Box::new(mycircle) as Box<Circle>; let nonsense = mycircle.radius() * mycircle.area(); ``` @@ -2074,7 +2076,7 @@ On `struct`s: list of names `#[macro_use(foo, bar)]` restricts the import to just those macros named. The `extern crate` must appear at the crate root, not inside `mod`, which ensures proper function of the [`$crate` macro - variable](guide-macros.html#the-variable-$crate). + variable](book/macros.html#the-variable-$crate). - `macro_reexport` on an `extern crate` — re-export the named macros. @@ -2088,8 +2090,9 @@ On `struct`s: - `no_link` on an `extern crate` — even if we load this crate for macros or compiler plugins, don't link it into the output. -See the [macros guide](guide-macros.html#scoping-and-macro-import/export) for -more information on macro scope. +See the [macros section of the +book](book/macros.html#scoping-and-macro-import/export) for more information on +macro scope. ### Miscellaneous attributes @@ -2191,7 +2194,7 @@ For any lint check `C`: The lint checks supported by the compiler can be found via `rustc -W help`, along with their default settings. [Compiler -plugins](guide-plugin.html#lint-plugins) can provide additional lint checks. +plugins](book/plugin.html#lint-plugins) can provide additional lint checks. ```{.ignore} mod m1 { @@ -3376,14 +3379,17 @@ stands for a *single* data field, whereas a wildcard `..` stands for *all* the fields of a particular variant. For example: ``` +#![feature(box_syntax)] enum List<X> { Nil, Cons(X, Box<List<X>>) } -let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil)); +fn main() { + let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil)); -match x { - List::Cons(_, box List::Nil) => panic!("singleton list"), - List::Cons(..) => return, - List::Nil => panic!("empty list") + match x { + List::Cons(_, box List::Nil) => panic!("singleton list"), + List::Cons(..) => return, + List::Nil => panic!("empty list") + } } ``` @@ -3436,25 +3442,28 @@ the inside of the match. An example of a `match` expression: ``` +#![feature(box_syntax)] # fn process_pair(a: int, b: int) { } # fn process_ten() { } enum List<X> { Nil, Cons(X, Box<List<X>>) } -let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil)); +fn main() { + let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil)); -match x { - List::Cons(a, box List::Cons(b, _)) => { - process_pair(a, b); - } - List::Cons(10, _) => { - process_ten(); - } - List::Nil => { - return; - } - _ => { - panic!(); + match x { + List::Cons(a, box List::Cons(b, _)) => { + process_pair(a, b); + } + List::Cons(10, _) => { + process_ten(); + } + List::Nil => { + return; + } + _ => { + panic!(); + } } } ``` @@ -3468,6 +3477,8 @@ Subpatterns can also be bound to variables by the use of the syntax `variable @ subpattern`. For example: ``` +#![feature(box_syntax)] + enum List { Nil, Cons(uint, Box<List>) } fn is_sorted(list: &List) -> bool { @@ -3781,12 +3792,13 @@ enclosing `enum` or `struct` type itself. Such recursion has restrictions: An example of a *recursive* type and its use: ``` +# use std::boxed::Box; enum List<T> { - Nil, - Cons(T, Box<List<T>>) + Nil, + Cons(T, Box<List<T>>) } -let a: List<int> = List::Cons(7, box List::Cons(13, box List::Nil)); +let a: List<int> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil)))); ``` ### Pointer types @@ -3893,6 +3905,7 @@ implementation of `R`, and the pointer value of `E`. An example of an object type: ``` +# use std::boxed::Box; trait Printable { fn stringify(&self) -> String; } @@ -3906,7 +3919,7 @@ fn print(a: Box<Printable>) { } fn main() { - print(box 10i as Box<Printable>); + print(Box::new(10i) as Box<Printable>); } ``` @@ -4100,7 +4113,8 @@ the type of a box is `std::owned::Box<T>`. An example of a box type and value: ``` -let x: Box<int> = box 10; +# use std::boxed::Box; +let x: Box<int> = Box::new(10); ``` Box values exist in 1:1 correspondence with their heap allocation, copying a @@ -4109,7 +4123,8 @@ copy of a box to move ownership of the value. After a value has been moved, the source location cannot be used unless it is reinitialized. ``` -let x: Box<int> = box 10; +# use std::boxed::Box; +let x: Box<int> = Box::new(10); let y = x; // attempting to use `x` will result in an error here ``` @@ -4213,7 +4228,7 @@ communication facilities. The Rust compiler supports various methods to link crates together both statically and dynamically. This section will explore the various methods to link Rust crates together, and more information about native libraries can be -found in the [ffi guide][ffi]. +found in the [ffi section of the book][ffi]. In one session of compilation, the compiler can generate multiple artifacts through the usage of either command line flags or the `crate_type` attribute. @@ -4345,5 +4360,5 @@ that have since been removed): * [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and pattern syntax -[ffi]: guide-ffi.html -[plugin]: guide-plugin.html +[ffi]: book/ffi.html +[plugin]: book/plugin.html diff --git a/src/doc/trpl/README.md b/src/doc/trpl/README.md new file mode 100644 index 00000000000..0202e873b36 --- /dev/null +++ b/src/doc/trpl/README.md @@ -0,0 +1,35 @@ +% The Rust Programming Language + +Welcome! This book will teach you about [the Rust Programming +Language](http://www.rust-lang.org/). Rust is a modern systems programming +language focusing on safety and speed. It accomplishes these goals by being +memory safe without using garbage collection. + +"The Rust Programming Language" is split into three sections, which you can +navigate through the menu on the left. + +## Basics + +This section is a linear introduction to the basic syntax and semantics of +Rust. It has individual sections on each part of Rust's syntax, and cumulates +in a small project: a guessing game. + +After reading "Basics," you will have a good foundation to learn more about +Rust, and can write very simple programs. + +## Intermediate + +This section contains individual chapters, which are self-contained. They focus +on specific topics, and can be read in any order. + +After reading "Intermediate," you will have a solid understanding of Rust, +and will be able to understand most Rust code and write more complex programs. + +## Advanced + +In a similar fashion to "Intermediate," this setion is full of individual, +deep-dive chapters, which stand alone and can be read in any order. These +chapters focus on the most complex features, as well as some things that +are only available in upcoming versions of Rust. + +After reading "Advanced," you'll be a Rust expert! diff --git a/src/doc/trpl/SUMMARY.md b/src/doc/trpl/SUMMARY.md new file mode 100644 index 00000000000..1a61c6d216b --- /dev/null +++ b/src/doc/trpl/SUMMARY.md @@ -0,0 +1,36 @@ +# Summary + +* [I: The Basics](basic.md) + * [Installing Rust](installing-rust.md) + * [Hello, world!](hello-world.md) + * [Hello, Cargo!](hello-cargo.md) + * [Variable Bindings](variable-bindings.md) + * [If](if.md) + * [Functions](functions.md) + * [Comments](comments.md) + * [Compound Data Types](compound-data-types.md) + * [Match](match.md) + * [Looping](looping.md) + * [Strings](strings.md) + * [Arrays, Vectors, and Slices](arrays-vectors-and-slices.md) + * [Standard Input](standard-input.md) + * [Guessing Game](guessing-game.md) +* [II: Intermediate Rust](intermediate.md) + * [Crates and Modules](crates-and-modules.md) + * [Testing](testing.md) + * [Pointers](pointers.md) + * [Ownership](ownership.md) + * [Patterns](patterns.md) + * [Method Syntax](method-syntax.md) + * [Closures](closures.md) + * [Iterators](iterators.md) + * [Generics](generics.md) + * [Traits](traits.md) + * [Tasks](tasks.md) + * [Error Handling](error-handling.md) +* [III: Advanced Topics](advanced.md) + * [FFI](ffi.md) + * [Unsafe Code](unsafe.md) + * [Macros](macros.md) + * [Compiler Plugins](plugins.md) +* [Conclusion](conclusion.md) diff --git a/src/doc/trpl/advanced.md b/src/doc/trpl/advanced.md new file mode 100644 index 00000000000..138db523b9a --- /dev/null +++ b/src/doc/trpl/advanced.md @@ -0,0 +1,8 @@ +% Advanced + +In a similar fashion to "Intermediate," this setion is full of individual, +deep-dive chapters, which stand alone and can be read in any order. These +chapters focus on the most complex features, as well as some things that +are only available in upcoming versions of Rust. + +After reading "Advanced," you'll be a Rust expert! diff --git a/src/doc/trpl/arrays-vectors-and-slices.md b/src/doc/trpl/arrays-vectors-and-slices.md new file mode 100644 index 00000000000..24d60dd2e4e --- /dev/null +++ b/src/doc/trpl/arrays-vectors-and-slices.md @@ -0,0 +1,99 @@ +% Arrays, Vectors, and Slices + +Like many programming languages, Rust has list types to represent a sequence of +things. The most basic is the **array**, a fixed-size list of elements of the +same type. By default, arrays are immutable. + +```{rust} +let a = [1, 2, 3]; // a: [i32; 3] +let mut m = [1, 2, 3]; // mut m: [i32; 3] +``` + +There's a shorthand for initializing each element of an array to the same +value. In this example, each element of `a` will be initialized to `0`: + +```{rust} +let a = [0; 20]; // a: [i32; 20] +``` + +Arrays have type `[T; N]`. We'll talk about this `T` notation later, when we +cover generics. + +You can get the number of elements in an array `a` with `a.len()`, and use +`a.iter()` to iterate over them with a for loop. This code will print each +number in order: + +```{rust} +let a = [1, 2, 3]; + +println!("a has {} elements", a.len()); +for e in a.iter() { + println!("{}", e); +} +``` + +You can access a particular element of an array with **subscript notation**: + +```{rust} +let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3] + +println!("The second name is: {}", names[1]); +``` + +Subscripts start at zero, like in most programming languages, so the first name +is `names[0]` and the second name is `names[1]`. The above example prints +`The second name is: Brian`. If you try to use a subscript that is not in the +array, you will get an error: array access is bounds-checked at run-time. Such +errant access is the source of many bugs in other systems programming +languages. + +A **vector** is a dynamic or "growable" array, implemented as the standard +library type [`Vec<T>`](../std/vec/) (we'll talk about what the `<T>` means +later). Vectors are to arrays what `String` is to `&str`. You can create them +with the `vec!` macro: + +```{rust} +let v = vec![1, 2, 3]; // v: Vec<i32> +``` + +(Notice that unlike the `println!` macro we've used in the past, we use square +brackets `[]` with `vec!`. Rust allows you to use either in either situation, +this is just convention.) + +You can get the length of, iterate over, and subscript vectors just like +arrays. In addition, (mutable) vectors can grow automatically: + +```{rust} +let mut nums = vec![1, 2, 3]; // mut nums: Vec<i32> + +nums.push(4); + +println!("The length of nums is now {}", nums.len()); // Prints 4 +``` + +Vectors have many more useful methods. + +A **slice** is a reference to (or "view" into) an array. They are useful for +allowing safe, efficient access to a portion of an array without copying. For +example, you might want to reference just one line of a file read into memory. +By nature, a slice is not created directly, but from an existing variable. +Slices have a length, can be mutable or not, and in many ways behave like +arrays: + +```{rust} +let a = [0, 1, 2, 3, 4]; +let middle = a.slice(1, 4); // A slice of a: just the elements [1,2,3] + +for e in middle.iter() { + println!("{}", e); // Prints 1, 2, 3 +} +``` + +You can also take a slice of a vector, `String`, or `&str`, because they are +backed by arrays. Slices have type `&[T]`, which we'll talk about when we cover +generics. + +We have now learned all of the most basic Rust concepts. We're ready to start +building our guessing game, we just need to know one last thing: how to get +input from the keyboard. You can't have a guessing game without the ability to +guess! diff --git a/src/doc/trpl/basic.md b/src/doc/trpl/basic.md new file mode 100644 index 00000000000..087121d0e7d --- /dev/null +++ b/src/doc/trpl/basic.md @@ -0,0 +1,8 @@ +% Basics + +This section is a linear introduction to the basic syntax and semantics of +Rust. It has individual sections on each part of Rust's syntax, and cumulates +in a small project: a guessing game. + +After reading "Basics," you will have a good foundation to learn more about +Rust, and can write very simple programs. diff --git a/src/doc/trpl/closures.md b/src/doc/trpl/closures.md new file mode 100644 index 00000000000..6413b90ee71 --- /dev/null +++ b/src/doc/trpl/closures.md @@ -0,0 +1,185 @@ +% Closures + +So far, we've made lots of functions in Rust, but we've given them all names. +Rust also allows us to create anonymous functions. Rust's anonymous +functions are called **closure**s. By themselves, closures aren't all that +interesting, but when you combine them with functions that take closures as +arguments, really powerful things are possible. + +Let's make a closure: + +```{rust} +let add_one = |&: x| { 1 + x }; + +println!("The sum of 5 plus 1 is {}.", add_one(5)); +``` + +We create a closure using the `|...| { ... }` syntax, and then we create a +binding so we can use it later. Note that we call the function using the +binding name and two parentheses, just like we would for a named function. + +Let's compare syntax. The two are pretty close: + +```{rust} +let add_one = |&: x: i32| -> i32 { 1 + x }; +fn add_one (x: i32) -> i32 { 1 + x } +``` + +As you may have noticed, closures infer their argument and return types, so you +don't need to declare one. This is different from named functions, which +default to returning unit (`()`). + +There's one big difference between a closure and named functions, and it's in +the name: a closure "closes over its environment." What does that mean? It means +this: + +```{rust} +fn main() { + let x: i32 = 5; + + let printer = |&:| { println!("x is: {}", x); }; + + printer(); // prints "x is: 5" +} +``` + +The `||` syntax means this is an anonymous closure that takes no arguments. +Without it, we'd just have a block of code in `{}`s. + +In other words, a closure has access to variables in the scope where it's +defined. The closure borrows any variables it uses, so this will error: + +```{rust,ignore} +fn main() { + let mut x = 5; + + let printer = |&:| { println!("x is: {}", x); }; + + x = 6; // error: cannot assign to `x` because it is borrowed +} +``` + +## Moving closures + +Rust has a second type of closure, called a **moving closure**. Moving +closures are indicated using the `move` keyword (e.g., `move || x * +x`). The difference between a moving closure and an ordinary closure +is that a moving closure always takes ownership of all variables that +it uses. Ordinary closures, in contrast, just create a reference into +the enclosing stack frame. Moving closures are most useful with Rust's +concurrency features, and so we'll just leave it at this for +now. We'll talk about them more in the "Threads" section of the guide. + +## Accepting closures as arguments + +Closures are most useful as an argument to another function. Here's an example: + +```{rust} +fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { + f(x) + f(x) +} + +fn main() { + let square = |&: x: i32| { x * x }; + + twice(5, square); // evaluates to 50 +} +``` + +Let's break the example down, starting with `main`: + +```{rust} +let square = |&: x: i32| { x * x }; +``` + +We've seen this before. We make a closure that takes an integer, and returns +its square. + +```{rust} +# fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { f(x) + f(x) } +# let square = |&: x: i32| { x * x }; +twice(5, square); // evaluates to 50 +``` + +This line is more interesting. Here, we call our function, `twice`, and we pass +it two arguments: an integer, `5`, and our closure, `square`. This is just like +passing any other two variable bindings to a function, but if you've never +worked with closures before, it can seem a little complex. Just think: "I'm +passing two variables: one is an i32, and one is a function." + +Next, let's look at how `twice` is defined: + +```{rust,ignore} +fn twice(x: i32, f: |i32| -> i32) -> i32 { +``` + +`twice` takes two arguments, `x` and `f`. That's why we called it with two +arguments. `x` is an `i32`, we've done that a ton of times. `f` is a function, +though, and that function takes an `i32` and returns an `i32`. Notice +how the `|i32| -> i32` syntax looks a lot like our definition of `square` +above, if we added the return type in: + +```{rust} +let square = |&: x: i32| -> i32 { x * x }; +// |i32| -> i32 +``` + +This function takes an `i32` and returns an `i32`. + +This is the most complicated function signature we've seen yet! Give it a read +a few times until you can see how it works. It takes a teeny bit of practice, and +then it's easy. + +Finally, `twice` returns an `i32` as well. + +Okay, let's look at the body of `twice`: + +```{rust} +fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { + f(x) + f(x) +} +``` + +Since our closure is named `f`, we can call it just like we called our closures +before, and we pass in our `x` argument to each one, hence the name `twice`. + +If you do the math, `(5 * 5) + (5 * 5) == 50`, so that's the output we get. + +Play around with this concept until you're comfortable with it. Rust's standard +library uses lots of closures where appropriate, so you'll be using +this technique a lot. + +If we didn't want to give `square` a name, we could just define it inline. +This example is the same as the previous one: + +```{rust} +fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { + f(x) + f(x) +} + +fn main() { + twice(5, |x: i32| { x * x }); // evaluates to 50 +} +``` + +A named function's name can be used wherever you'd use a closure. Another +way of writing the previous example: + +```{rust} +fn twice<F: Fn(i32) -> i32>(x: i32, f: F) -> i32 { + f(x) + f(x) +} + +fn square(x: i32) -> i32 { x * x } + +fn main() { + twice(5, square); // evaluates to 50 +} +``` + +Doing this is not particularly common, but it's useful every once in a while. + +That's all you need to get the hang of closures! Closures are a little bit +strange at first, but once you're used to them, you'll miss them +in other languages. Passing functions to other functions is +incredibly powerful, as you will see in the following chapter about iterators. diff --git a/src/doc/trpl/comments.md b/src/doc/trpl/comments.md new file mode 100644 index 00000000000..f02c1ad9a18 --- /dev/null +++ b/src/doc/trpl/comments.md @@ -0,0 +1,46 @@ +% Comments + +Now that we have some functions, it's a good idea to learn about comments. +Comments are notes that you leave to other programmers to help explain things +about your code. The compiler mostly ignores them. + +Rust has two kinds of comments that you should care about: **line comment**s +and **doc comment**s. + +```{rust} +// Line comments are anything after '//' and extend to the end of the line. + +let x = 5; // this is also a line comment. + +// If you have a long explanation for something, you can put line comments next +// to each other. Put a space between the // and your comment so that it's +// more readable. +``` + +The other kind of comment is a doc comment. Doc comments use `///` instead of +`//`, and support Markdown notation inside: + +```{rust} +/// `hello` is a function that prints a greeting that is personalized based on +/// the name given. +/// +/// # Arguments +/// +/// * `name` - The name of the person you'd like to greet. +/// +/// # Example +/// +/// ```rust +/// let name = "Steve"; +/// hello(name); // prints "Hello, Steve!" +/// ``` +fn hello(name: &str) { + println!("Hello, {}!", name); +} +``` + +When writing doc comments, adding sections for any arguments, return values, +and providing some examples of usage is very, very helpful. + +You can use the [`rustdoc`](../rustdoc.html) tool to generate HTML documentation +from these doc comments. diff --git a/src/doc/trpl/compound-data-types.md b/src/doc/trpl/compound-data-types.md new file mode 100644 index 00000000000..b80d248bc41 --- /dev/null +++ b/src/doc/trpl/compound-data-types.md @@ -0,0 +1,353 @@ +% Compound Data Types + +Rust, like many programming languages, has a number of different data types +that are built-in. You've already done some simple work with integers and +strings, but next, let's talk about some more complicated ways of storing data. + +## Tuples + +The first compound data type we're going to talk about are called **tuple**s. +Tuples are an ordered list of a fixed size. Like this: + +```rust +let x = (1, "hello"); +``` + +The parentheses and commas form this two-length tuple. Here's the same code, but +with the type annotated: + +```rust +let x: (i32, &str) = (1, "hello"); +``` + +As you can see, the type of a tuple looks just like the tuple, but with each +position having a type name rather than the value. Careful readers will also +note that tuples are heterogeneous: we have an `i32` and a `&str` in this tuple. +You haven't seen `&str` as a type before, and we'll discuss the details of +strings later. In systems programming languages, strings are a bit more complex +than in other languages. For now, just read `&str` as "a string slice," and +we'll learn more soon. + +You can access the fields in a tuple through a **destructuring let**. Here's +an example: + +```rust +let (x, y, z) = (1, 2, 3); + +println!("x is {}", x); +``` + +Remember before when I said the left-hand side of a `let` statement was more +powerful than just assigning a binding? Here we are. We can put a pattern on +the left-hand side of the `let`, and if it matches up to the right-hand side, +we can assign multiple bindings at once. In this case, `let` 'destructures,' +or 'breaks up,' the tuple, and assigns the bits to three bindings. + +This pattern is very powerful, and we'll see it repeated more later. + +There are also a few things you can do with a tuple as a whole, without +destructuring. You can assign one tuple into another, if they have the same +arity and contained types. + +```rust +let mut x = (1, 2); // x: (i32, i32) +let y = (2, 3); // y: (i32, i32) + +x = y; +``` + +You can also check for equality with `==`. Again, this will only compile if the +tuples have the same type. + +```rust +let x = (1, 2, 3); +let y = (2, 2, 4); + +if x == y { + println!("yes"); +} else { + println!("no"); +} +``` + +This will print `no`, because some of the values aren't equal. + +One other use of tuples is to return multiple values from a function: + +```rust +fn next_two(x: i32) -> (i32, i32) { (x + 1, x + 2) } + +fn main() { + let (x, y) = next_two(5); + println!("x, y = {}, {}", x, y); +} +``` + +Even though Rust functions can only return one value, a tuple _is_ one value, +that happens to be made up of more than one value. You can also see in this example how you +can destructure a pattern returned by a function, as well. + +Tuples are a very simple data structure, and so are not often what you want. +Let's move on to their bigger sibling, structs. + +## Structs + +A struct is another form of a 'record type,' just like a tuple. There's a +difference: structs give each element that they contain a name, called a +'field' or a 'member.' Check it out: + +```rust +struct Point { + x: i32, + y: i32, +} + +fn main() { + let origin = Point { x: 0, y: 0 }; // origin: Point + + println!("The origin is at ({}, {})", origin.x, origin.y); +} +``` + +There's a lot going on here, so let's break it down. We declare a struct with +the `struct` keyword, and then with a name. By convention, structs begin with a +capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`. + +We can create an instance of our struct via `let`, as usual, but we use a `key: +value` style syntax to set each field. The order doesn't need to be the same as +in the original declaration. + +Finally, because fields have names, we can access the field through dot +notation: `origin.x`. + +The values in structs are immutable by default, like other bindings in Rust. +Use `mut` to make them mutable: + +```{rust} +struct Point { + x: i32, + y: i32, +} + +fn main() { + let mut point = Point { x: 0, y: 0 }; + + point.x = 5; + + println!("The point is at ({}, {})", point.x, point.y); +} +``` + +This will print `The point is at (5, 0)`. + +## Tuple Structs and Newtypes + +Rust has another data type that's like a hybrid between a tuple and a struct, +called a **tuple struct**. Tuple structs do have a name, but their fields +don't: + + +```{rust} +struct Color(i32, i32, i32); +struct Point(i32, i32, i32); +``` + +These two will not be equal, even if they have the same values: + +```{rust} +# struct Color(i32, i32, i32); +# struct Point(i32, i32, i32); +let black = Color(0, 0, 0); +let origin = Point(0, 0, 0); +``` + +It is almost always better to use a struct than a tuple struct. We would write +`Color` and `Point` like this instead: + +```{rust} +struct Color { + red: i32, + blue: i32, + green: i32, +} + +struct Point { + x: i32, + y: i32, + z: i32, +} +``` + +Now, we have actual names, rather than positions. Good names are important, +and with a struct, we have actual names. + +There _is_ one case when a tuple struct is very useful, though, and that's a +tuple struct with only one element. We call this a 'newtype,' because it lets +you create a new type that's a synonym for another one: + +```{rust} +struct Inches(i32); + +let length = Inches(10); + +let Inches(integer_length) = length; +println!("length is {} inches", integer_length); +``` + +As you can see here, you can extract the inner integer type through a +destructuring `let`. + +## Enums + +Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful +feature of Rust, and are used throughout the standard library. This is an enum +that is provided by the Rust standard library: + +```{rust} +enum Ordering { + Less, + Equal, + Greater, +} +``` + +An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given +time. + +Because `Ordering` is provided by the standard library, we can use the `use` +keyword to use it in our code. We'll learn more about `use` later, but it's +used to bring names into scope. + +Here's an example of how to use `Ordering`: + +```{rust} +use std::cmp::Ordering; + +fn cmp(a: i32, b: i32) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} + +fn main() { + let x = 5; + let y = 10; + + let ordering = cmp(x, y); // ordering: Ordering + + if ordering == Ordering::Less { + println!("less"); + } else if ordering == Ordering::Greater { + println!("greater"); + } else if ordering == Ordering::Equal { + println!("equal"); + } +} +``` + +There's a symbol here we haven't seen before: the double colon (`::`). +This is used to indicate a namespace. In this case, `Ordering` lives in +the `cmp` submodule of the `std` module. We'll talk more about modules +later in the guide. For now, all you need to know is that you can `use` +things from the standard library if you need them. + +Okay, let's talk about the actual code in the example. `cmp` is a function that +compares two things, and returns an `Ordering`. We return either +`Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on if +the two values are greater, less, or equal. Note that each variant of the +`enum` is namespaced under the `enum` itself: it's `Ordering::Greater` not +`Greater`. + +The `ordering` variable has the type `Ordering`, and so contains one of the +three values. We can then do a bunch of `if`/`else` comparisons to check which +one it is. However, repeated `if`/`else` comparisons get quite tedious. Rust +has a feature that not only makes them nicer to read, but also makes sure that +you never miss a case. Before we get to that, though, let's talk about another +kind of enum: one with values. + +This enum has two variants, one of which has a value: + +```{rust} +enum OptionalInt { + Value(i32), + Missing, +} +``` + +This enum represents an `i32` that we may or may not have. In the `Missing` +case, we have no value, but in the `Value` case, we do. This enum is specific +to `i32`s, though. We can make it usable by any type, but we haven't quite +gotten there yet! + +You can also have any number of values in an enum: + +```{rust} +enum OptionalColor { + Color(i32, i32, i32), + Missing, +} +``` + +And you can also have something like this: + +```{rust} +enum StringResult { + StringOK(String), + ErrorReason(String), +} +``` +Where a `StringResult` is either a `StringResult::StringOK`, with the result of +a computation, or an `StringResult::ErrorReason` with a `String` explaining +what caused the computation to fail. These kinds of `enum`s are actually very +useful and are even part of the standard library. + +Here is an example of using our `StringResult`: + +```rust +enum StringResult { + StringOK(String), + ErrorReason(String), +} + +fn respond(greeting: &str) -> StringResult { + if greeting == "Hello" { + StringResult::StringOK("Good morning!".to_string()) + } else { + StringResult::ErrorReason("I didn't understand you!".to_string()) + } +} +``` + +That's a lot of typing! We can use the `use` keyword to make it shorter: + +```rust +use StringResult::StringOK; +use StringResult::ErrorReason; + +enum StringResult { + StringOK(String), + ErrorReason(String), +} + +# fn main() {} + +fn respond(greeting: &str) -> StringResult { + if greeting == "Hello" { + StringOK("Good morning!".to_string()) + } else { + ErrorReason("I didn't understand you!".to_string()) + } +} +``` + +`use` declarations must come before anything else, which looks a little strange in this example, +since we `use` the variants before we define them. Anyway, in the body of `respond`, we can just +say `StringOK` now, rather than the full `StringResult::StringOK`. Importing variants can be +convenient, but can also cause name conflicts, so do this with caution. It's considered good style +to rarely import variants for this reason. + +As you can see, `enum`s with values are quite a powerful tool for data representation, +and can be even more useful when they're generic across types. Before we get to generics, +though, let's talk about how to use them with pattern matching, a tool that will +let us deconstruct this sum type (the type theory term for enums) in a very elegant +way and avoid all these messy `if`/`else`s. diff --git a/src/doc/trpl/conclusion.md b/src/doc/trpl/conclusion.md new file mode 100644 index 00000000000..0472787e948 --- /dev/null +++ b/src/doc/trpl/conclusion.md @@ -0,0 +1,10 @@ +% Conclusion + +We covered a lot of ground here. When you've mastered everything in this Guide, +you will have a firm grasp of basic Rust development. There's a whole lot more +out there, we've just covered the surface. There's tons of topics that you can +dig deeper into, and we've built specialized guides for many of them. To learn +more, dig into the [full documentation +index](index.html). + +Happy hacking! diff --git a/src/doc/guide-crates.md b/src/doc/trpl/crates-and-modules.md index ba825c2c9a8..ba825c2c9a8 100644 --- a/src/doc/guide-crates.md +++ b/src/doc/trpl/crates-and-modules.md diff --git a/src/doc/guide-error-handling.md b/src/doc/trpl/error-handling.md index d241e77f810..98b46511f04 100644 --- a/src/doc/guide-error-handling.md +++ b/src/doc/trpl/error-handling.md @@ -147,10 +147,10 @@ for all but the most trivial of situations. Here's an example of using `Result`: ```rust -#[deriving(Show)] +#[derive(Show)] enum Version { Version1, Version2 } -#[deriving(Show)] +#[derive(Show)] enum ParseError { InvalidHeaderLength, InvalidVersion } fn parse_version(header: &[u8]) -> Result<Version, ParseError> { diff --git a/src/doc/guide-ffi.md b/src/doc/trpl/ffi.md index 7ee1c1a7032..1f12c05f37e 100644 --- a/src/doc/guide-ffi.md +++ b/src/doc/trpl/ffi.md @@ -262,6 +262,7 @@ referenced Rust object. Rust code: ~~~~no_run +# use std::boxed::Box; #[repr(C)] struct RustObject { @@ -286,7 +287,7 @@ extern { fn main() { // Create the object that will be referenced in the callback - let mut rust_object = box RustObject { a: 5 }; + let mut rust_object = Box::new(RustObject { a: 5 }); unsafe { register_callback(&mut *rust_object, callback); diff --git a/src/doc/trpl/functions.md b/src/doc/trpl/functions.md new file mode 100644 index 00000000000..e3827d962c3 --- /dev/null +++ b/src/doc/trpl/functions.md @@ -0,0 +1,146 @@ +% Functions + +You've already seen one function so far, the `main` function: + +```{rust} +fn main() { +} +``` + +This is the simplest possible function declaration. As we mentioned before, +`fn` says 'this is a function,' followed by the name, some parentheses because +this function takes no arguments, and then some curly braces to indicate the +body. Here's a function named `foo`: + +```{rust} +fn foo() { +} +``` + +So, what about taking arguments? Here's a function that prints a number: + +```{rust} +fn print_number(x: i32) { + println!("x is: {}", x); +} +``` + +Here's a complete program that uses `print_number`: + +```{rust} +fn main() { + print_number(5); +} + +fn print_number(x: i32) { + println!("x is: {}", x); +} +``` + +As you can see, function arguments work very similar to `let` declarations: +you add a type to the argument name, after a colon. + +Here's a complete program that adds two numbers together and prints them: + +```{rust} +fn main() { + print_sum(5, 6); +} + +fn print_sum(x: i32, y: i32) { + println!("sum is: {}", x + y); +} +``` + +You separate arguments with a comma, both when you call the function, as well +as when you declare it. + +Unlike `let`, you _must_ declare the types of function arguments. This does +not work: + +```{ignore} +fn print_number(x, y) { + println!("x is: {}", x + y); +} +``` + +You get this error: + +```text +hello.rs:5:18: 5:19 error: expected `:` but found `,` +hello.rs:5 fn print_number(x, y) { +``` + +This is a deliberate design decision. While full-program inference is possible, +languages which have it, like Haskell, often suggest that documenting your +types explicitly is a best-practice. We agree that forcing functions to declare +types while allowing for inference inside of function bodies is a wonderful +sweet spot between full inference and no inference. + +What about returning a value? Here's a function that adds one to an integer: + +```{rust} +fn add_one(x: i32) -> i32 { + x + 1 +} +``` + +Rust functions return exactly one value, and you declare the type after an +'arrow', which is a dash (`-`) followed by a greater-than sign (`>`). + +You'll note the lack of a semicolon here. If we added it in: + +```{ignore} +fn add_one(x: i32) -> i32 { + x + 1; +} +``` + +We would get an error: + +```text +error: not all control paths return a value +fn add_one(x: i32) -> i32 { + x + 1; +} + +help: consider removing this semicolon: + x + 1; + ^ +``` + +Remember our earlier discussions about semicolons and `()`? Our function claims +to return an `i32`, but with a semicolon, it would return `()` instead. Rust +realizes this probably isn't what we want, and suggests removing the semicolon. + +This is very much like our `if` statement before: the result of the block +(`{}`) is the value of the expression. Other expression-oriented languages, +such as Ruby, work like this, but it's a bit unusual in the systems programming +world. When people first learn about this, they usually assume that it +introduces bugs. But because Rust's type system is so strong, and because unit +is its own unique type, we have never seen an issue where adding or removing a +semicolon in a return position would cause a bug. + +But what about early returns? Rust does have a keyword for that, `return`: + +```{rust} +fn foo(x: i32) -> i32 { + if x < 5 { return x; } + + x + 1 +} +``` + +Using a `return` as the last line of a function works, but is considered poor +style: + +```{rust} +fn foo(x: i32) -> i32 { + if x < 5 { return x; } + + return x + 1; +} +``` + +There are some additional ways to define functions, but they involve features +that we haven't learned about yet, so let's just leave it at that for now. diff --git a/src/doc/trpl/generics.md b/src/doc/trpl/generics.md new file mode 100644 index 00000000000..137b66ea15a --- /dev/null +++ b/src/doc/trpl/generics.md @@ -0,0 +1,177 @@ +% Generics + +Sometimes, when writing a function or data type, we may want it to work for +multiple types of arguments. For example, remember our `OptionalInt` type? + +```{rust} +enum OptionalInt { + Value(int), + Missing, +} +``` + +If we wanted to also have an `OptionalFloat64`, we would need a new enum: + +```{rust} +enum OptionalFloat64 { + Valuef64(f64), + Missingf64, +} +``` + +This is really unfortunate. Luckily, Rust has a feature that gives us a better +way: generics. Generics are called **parametric polymorphism** in type theory, +which means that they are types or functions that have multiple forms ("poly" +is multiple, "morph" is form) over a given parameter ("parametric"). + +Anyway, enough with type theory declarations, let's check out the generic form +of `OptionalInt`. It is actually provided by Rust itself, and looks like this: + +```rust +enum Option<T> { + Some(T), + None, +} +``` + +The `<T>` part, which you've seen a few times before, indicates that this is +a generic data type. Inside the declaration of our enum, wherever we see a `T`, +we substitute that type for the same type used in the generic. Here's an +example of using `Option<T>`, with some extra type annotations: + +```{rust} +let x: Option<int> = Some(5i); +``` + +In the type declaration, we say `Option<int>`. Note how similar this looks to +`Option<T>`. So, in this particular `Option`, `T` has the value of `int`. On +the right-hand side of the binding, we do make a `Some(T)`, where `T` is `5i`. +Since that's an `int`, the two sides match, and Rust is happy. If they didn't +match, we'd get an error: + +```{rust,ignore} +let x: Option<f64> = Some(5i); +// error: mismatched types: expected `core::option::Option<f64>` +// but found `core::option::Option<int>` (expected f64 but found int) +``` + +That doesn't mean we can't make `Option<T>`s that hold an `f64`! They just have to +match up: + +```{rust} +let x: Option<int> = Some(5i); +let y: Option<f64> = Some(5.0f64); +``` + +This is just fine. One definition, multiple uses. + +Generics don't have to only be generic over one type. Consider Rust's built-in +`Result<T, E>` type: + +```{rust} +enum Result<T, E> { + Ok(T), + Err(E), +} +``` + +This type is generic over _two_ types: `T` and `E`. By the way, the capital letters +can be any letter you'd like. We could define `Result<T, E>` as: + +```{rust} +enum Result<H, N> { + Ok(H), + Err(N), +} +``` + +if we wanted to. Convention says that the first generic parameter should be +`T`, for 'type,' and that we use `E` for 'error.' Rust doesn't care, however. + +The `Result<T, E>` type is intended to +be used to return the result of a computation, and to have the ability to +return an error if it didn't work out. Here's an example: + +```{rust} +let x: Result<f64, String> = Ok(2.3f64); +let y: Result<f64, String> = Err("There was an error.".to_string()); +``` + +This particular Result will return an `f64` if there's a success, and a +`String` if there's a failure. Let's write a function that uses `Result<T, E>`: + +```{rust} +fn inverse(x: f64) -> Result<f64, String> { + if x == 0.0f64 { return Err("x cannot be zero!".to_string()); } + + Ok(1.0f64 / x) +} +``` + +We don't want to take the inverse of zero, so we check to make sure that we +weren't passed zero. If we were, then we return an `Err`, with a message. If +it's okay, we return an `Ok`, with the answer. + +Why does this matter? Well, remember how `match` does exhaustive matches? +Here's how this function gets used: + +```{rust} +# fn inverse(x: f64) -> Result<f64, String> { +# if x == 0.0f64 { return Err("x cannot be zero!".to_string()); } +# Ok(1.0f64 / x) +# } +let x = inverse(25.0f64); + +match x { + Ok(x) => println!("The inverse of 25 is {}", x), + Err(msg) => println!("Error: {}", msg), +} +``` + +The `match` enforces that we handle the `Err` case. In addition, because the +answer is wrapped up in an `Ok`, we can't just use the result without doing +the match: + +```{rust,ignore} +let x = inverse(25.0f64); +println!("{}", x + 2.0f64); // error: binary operation `+` cannot be applied + // to type `core::result::Result<f64,collections::string::String>` +``` + +This function is great, but there's one other problem: it only works for 64 bit +floating point values. What if we wanted to handle 32 bit floating point as +well? We'd have to write this: + +```{rust} +fn inverse32(x: f32) -> Result<f32, String> { + if x == 0.0f32 { return Err("x cannot be zero!".to_string()); } + + Ok(1.0f32 / x) +} +``` + +Bummer. What we need is a **generic function**. Luckily, we can write one! +However, it won't _quite_ work yet. Before we get into that, let's talk syntax. +A generic version of `inverse` would look something like this: + +```{rust,ignore} +fn inverse<T>(x: T) -> Result<T, String> { + if x == 0.0 { return Err("x cannot be zero!".to_string()); } + + Ok(1.0 / x) +} +``` + +Just like how we had `Option<T>`, we use a similar syntax for `inverse<T>`. +We can then use `T` inside the rest of the signature: `x` has type `T`, and half +of the `Result` has type `T`. However, if we try to compile that example, we'll get +an error: + +```text +error: binary operation `==` cannot be applied to type `T` +``` + +Because `T` can be _any_ type, it may be a type that doesn't implement `==`, +and therefore, the first line would be wrong. What do we do? + +To fix this example, we need to learn about another Rust feature: traits. diff --git a/src/doc/trpl/guessing-game.md b/src/doc/trpl/guessing-game.md new file mode 100644 index 00000000000..2847964f15f --- /dev/null +++ b/src/doc/trpl/guessing-game.md @@ -0,0 +1,891 @@ +% Guessing Game + +Okay! We've got the basics of Rust down. Let's write a bigger program. + +For our first project, we'll implement a classic beginner programming problem: +the guessing game. Here's how it works: Our program will generate a random +integer between one and a hundred. It will then prompt us to enter a guess. +Upon entering our guess, it will tell us if we're too low or too high. Once we +guess correctly, it will congratulate us. Sound good? + +## Set up + +Let's set up a new project. Go to your projects directory. Remember how we +had to create our directory structure and a `Cargo.toml` for `hello_world`? Cargo +has a command that does that for us. Let's give it a shot: + +```{bash} +$ cd ~/projects +$ cargo new guessing_game --bin +$ cd guessing_game +``` + +We pass the name of our project to `cargo new`, and then the `--bin` flag, +since we're making a binary, rather than a library. + +Check out the generated `Cargo.toml`: + +```toml +[package] + +name = "guessing_game" +version = "0.0.1" +authors = ["Your Name <you@example.com>"] +``` + +Cargo gets this information from your environment. If it's not correct, go ahead +and fix that. + +Finally, Cargo generated a "Hello, world!" for us. Check out `src/main.rs`: + +```{rust} +fn main() { + println!("Hello, world!") +} +``` + +Let's try compiling what Cargo gave us: + +```{bash} +$ cargo build + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) +``` + +Excellent! Open up your `src/main.rs` again. We'll be writing all of +our code in this file. We'll talk about multiple-file projects later on in the +guide. + +Before we move on, let me show you one more Cargo command: `run`. `cargo run` +is kind of like `cargo build`, but it also then runs the produced executable. +Try it out: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Hello, world! +``` + +Great! The `run` command comes in handy when you need to rapidly iterate on a project. +Our game is just such a project, we need to quickly test each iteration before moving on to the next one. + +## Processing a Guess + +Let's get to it! The first thing we need to do for our guessing game is +allow our player to input a guess. Put this in your `src/main.rs`: + +```{rust,no_run} +use std::io; + +fn main() { + println!("Guess the number!"); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + println!("You guessed: {}", input); +} +``` + +You've seen this code before, when we talked about standard input. We +import the `std::io` module with `use`, and then our `main` function contains +our program's logic. We print a little message announcing the game, ask the +user to input a guess, get their input, and then print it out. + +Because we talked about this in the section on standard I/O, I won't go into +more details here. If you need a refresher, go re-read that section. + +## Generating a secret number + +Next, we need to generate a secret number. To do that, we need to use Rust's +random number generation, which we haven't talked about yet. Rust includes a +bunch of interesting functions in its standard library. If you need a bit of +code, it's possible that it's already been written for you! In this case, +we do know that Rust has random number generation, but we don't know how to +use it. + +Enter the docs. Rust has a page specifically to document the standard library. +You can find that page [here](../std/index.html). There's a lot of information on +that page, but the best part is the search bar. Right up at the top, there's +a box that you can enter in a search term. The search is pretty primitive +right now, but is getting better all the time. If you type 'random' in that +box, the page will update to [this one](../std/index.html?search=random). The very +first result is a link to [`std::rand::random`](../std/rand/fn.random.html). If we +click on that result, we'll be taken to its documentation page. + +This page shows us a few things: the type signature of the function, some +explanatory text, and then an example. Let's try to modify our code to add in the +`random` function and see what happens: + +```{rust,ignore} +use std::io; +use std::rand; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random() % 100) + 1; // secret_number: i32 + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + + println!("You guessed: {}", input); +} +``` + +The first thing we changed was to `use std::rand`, as the docs +explained. We then added in a `let` expression to create a variable binding +named `secret_number`, and we printed out its result. + +Also, you may wonder why we are using `%` on the result of `rand::random()`. +This operator is called 'modulo', and it returns the remainder of a division. +By taking the modulo of the result of `rand::random()`, we're limiting the +values to be between 0 and 99. Then, we add one to the result, making it from 1 +to 100. Using modulo can give you a very, very small bias in the result, but +for this example, it is not important. + +Let's try to compile this using `cargo build`: + +```bash +$ cargo build + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) +src/main.rs:7:26: 7:34 error: the type of this value must be known in this context +src/main.rs:7 let secret_number = (rand::random() % 100) + 1; + ^~~~~~~~ +error: aborting due to previous error +``` + +It didn't work! Rust says "the type of this value must be known in this +context." What's up with that? Well, as it turns out, `rand::random()` can +generate many kinds of random values, not just integers. And in this case, Rust +isn't sure what kind of value `random()` should generate. So we have to help +it. With number literals, we can just add an `i32` onto the end to tell Rust they're +integers, but that does not work with functions. There's a different syntax, +and it looks like this: + +```{rust,ignore} +rand::random::<i32>(); +``` + +This says "please give me a random `i32` value." We can change our code to use +this hint: + +```{rust,no_run} +use std::io; +use std::rand; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<i32>() % 100) + 1; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + + println!("You guessed: {}", input); +} +``` + +Try running our new program a few times: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 7 +Please input your guess. +4 +You guessed: 4 +$ ./target/guessing_game +Guess the number! +The secret number is: 83 +Please input your guess. +5 +You guessed: 5 +$ ./target/guessing_game +Guess the number! +The secret number is: -29 +Please input your guess. +42 +You guessed: 42 +``` + +Wait. Negative 29? We wanted a number between one and a hundred! We have two +options here: we can either ask `random()` to generate an unsigned integer, which +can only be positive, or we can use the `abs()` function. Let's go with the +unsigned integer approach. If we want a random positive number, we should ask for +a random positive number. Our code looks like this now: + +```{rust,no_run} +use std::io; +use std::rand; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + + println!("You guessed: {}", input); +} +``` + +And trying it out: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 57 +Please input your guess. +3 +You guessed: 3 +``` + +Great! Next up: let's compare our guess to the secret guess. + +## Comparing guesses + +If you remember, earlier in the guide, we made a `cmp` function that compared +two numbers. Let's add that in, along with a `match` statement to compare our +guess to the secret number: + +```{rust,ignore} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + + println!("You guessed: {}", input); + + match cmp(input, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} + +fn cmp(a: i32, b: i32) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +If we try to compile, we'll get some errors: + +```bash +$ cargo build + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) +src/main.rs:20:15: 20:20 error: mismatched types: expected `i32` but found `collections::string::String` (expected i32 but found struct collections::string::String) +src/main.rs:20 match cmp(input, secret_number) { + ^~~~~ +src/main.rs:20:22: 20:35 error: mismatched types: expected `i32` but found `uint` (expected i32 but found uint) +src/main.rs:20 match cmp(input, secret_number) { + ^~~~~~~~~~~~~ +error: aborting due to 2 previous errors +``` + +This often happens when writing Rust programs, and is one of Rust's greatest +strengths. You try out some code, see if it compiles, and Rust tells you that +you've done something wrong. In this case, our `cmp` function works on integers, +but we've given it unsigned integers. In this case, the fix is easy, because +we wrote the `cmp` function! Let's change it to take `uint`s: + +```{rust,ignore} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + + + println!("You guessed: {}", input); + + match cmp(input, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +And try compiling again: + +```bash +$ cargo build + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) +src/main.rs:20:15: 20:20 error: mismatched types: expected `uint` but found `collections::string::String` (expected uint but found struct collections::string::String) +src/main.rs:20 match cmp(input, secret_number) { + ^~~~~ +error: aborting due to previous error +``` + +This error is similar to the last one: we expected to get a `uint`, but we got +a `String` instead! That's because our `input` variable is coming from the +standard input, and you can guess anything. Try it: + +```bash +$ ./target/guessing_game +Guess the number! +The secret number is: 73 +Please input your guess. +hello +You guessed: hello +``` + +Oops! Also, you'll note that we just ran our program even though it didn't compile. +This works because the older version we did successfully compile was still lying +around. Gotta be careful! + +Anyway, we have a `String`, but we need a `uint`. What to do? Well, there's +a function for that: + +```{rust,ignore} +let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); +let input_num: Option<uint> = input.parse(); +``` + +The `parse` function takes in a `&str` value and converts it into something. +We tell it what kind of something with a type hint. Remember our type hint with +`random()`? It looked like this: + +```{rust,ignore} +rand::random::<uint>(); +``` + +There's an alternate way of providing a hint too, and that's declaring the type +in a `let`: + +```{rust,ignore} +let x: uint = rand::random(); +``` + +In this case, we say `x` is a `uint` 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::<uint>(); // input_num: Option<uint> +let input_num: Option<uint> = "5".parse(); // input_num: Option<uint> +``` + +Anyway, with us now converting our input to a number, our code looks like this: + +```{rust,ignore} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.parse(); + + println!("You guessed: {}", input_num); + + match cmp(input_num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +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 `uint` but found `core::option::Option<uint>` (expected uint but found enum core::option::Option) +src/main.rs:22 match cmp(input_num, secret_number) { + ^~~~~~~~~ +error: aborting due to previous error +``` + +Oh yeah! Our `input_num` has the type `Option<uint>`, rather than `uint`. We +need to unwrap the Option. If you remember from before, `match` is a great way +to do that. Try this code: + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + return; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +We use a `match` to either give us the `uint` inside of the `Option`, or else +print an error message and return. Let's give this a shot: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 17 +Please input your guess. +5 +Please input a number! +``` + +Uh, what? But we did! + +... actually, we didn't. See, when you get a line of input from `stdin()`, +you get all the input. Including the `\n` character from you pressing Enter. +Therefore, `parse()` sees the string `"5\n"` and says "nope, that's not a +number; there's non-number stuff in there!" Luckily for us, `&str`s have an easy +method we can use defined on them: `trim()`. One small modification, and our +code looks like this: + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.trim().parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + return; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +Let's try it! + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 58 +Please input your guess. + 76 +You guessed: 76 +Too big! +``` + +Nice! You can see I even added spaces before my guess, and it still figured +out that I guessed 76. Run the program a few times, and verify that guessing +the number works, as well as guessing a number too small. + +The Rust compiler helped us out quite a bit there! This technique is called +"lean on the compiler", and it's often useful when working on some code. Let +the error messages help guide you towards the correct types. + +Now we've got most of the game working, but we can only make one guess. Let's +change that by adding loops! + +## Looping + +As we already discussed, the `loop` keyword gives us an infinite loop. +Let's add that in: + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + loop { + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.trim().parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + return; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => println!("You win!"), + } + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +And try it out. But wait, didn't we just add an infinite loop? Yup. Remember +that `return`? If we give a non-number answer, we'll `return` and quit. Observe: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 59 +Please input your guess. +45 +You guessed: 45 +Too small! +Please input your guess. +60 +You guessed: 60 +Too big! +Please input your guess. +59 +You guessed: 59 +You win! +Please input your guess. +quit +Please input a number! +``` + +Ha! `quit` actually quits. As does any other non-number input. Well, this is +suboptimal to say the least. First, let's actually quit when you win the game: + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + loop { + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.trim().parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + return; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + return; + }, + } + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +By adding the `return` line after the `You win!`, we'll exit the program when +we win. We have just one more tweak to make: when someone inputs a non-number, +we don't want to quit, we just want to ignore it. Change that `return` to +`continue`: + + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + println!("The secret number is: {}", secret_number); + + loop { + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.trim().parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + continue; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + return; + }, + } + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +Now we should be good! Let's try: + +```bash +$ cargo run + Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game) + Running `target/guessing_game` +Guess the number! +The secret number is: 61 +Please input your guess. +10 +You guessed: 10 +Too small! +Please input your guess. +99 +You guessed: 99 +Too big! +Please input your guess. +foo +Please input a number! +Please input your guess. +61 +You guessed: 61 +You win! +``` + +Awesome! With one tiny last tweak, we have finished the guessing game. Can you +think of what it is? That's right, we don't want to print out the secret number. +It was good for testing, but it kind of ruins the game. Here's our final source: + +```{rust,no_run} +use std::io; +use std::rand; +use std::cmp::Ordering; + +fn main() { + println!("Guess the number!"); + + let secret_number = (rand::random::<uint>() % 100u) + 1u; + + loop { + + println!("Please input your guess."); + + let input = io::stdin().read_line() + .ok() + .expect("Failed to read line"); + let input_num: Option<uint> = input.trim().parse(); + + let num = match input_num { + Some(num) => num, + None => { + println!("Please input a number!"); + continue; + } + }; + + + println!("You guessed: {}", num); + + match cmp(num, secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + return; + }, + } + } +} + +fn cmp(a: uint, b: uint) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} +``` + +## Complete! + +At this point, you have successfully built the Guessing Game! Congratulations! + +You've now learned the basic syntax of Rust. All of this is relatively close to +various other programming languages you have used in the past. These +fundamental syntactical and semantic elements will form the foundation for the +rest of your Rust education. + +Now that you're an expert at the basics, it's time to learn about some of +Rust's more unique features. diff --git a/src/doc/trpl/hello-cargo.md b/src/doc/trpl/hello-cargo.md new file mode 100644 index 00000000000..d8acd95b59d --- /dev/null +++ b/src/doc/trpl/hello-cargo.md @@ -0,0 +1,108 @@ +% Hello, Cargo! + +[Cargo](http://crates.io) is a tool that Rustaceans use to help manage their +Rust projects. Cargo is currently in an alpha state, just like Rust, and so it +is still a work in progress. However, it is already good enough to use for many +Rust projects, and so it is assumed that Rust projects will use Cargo from the +beginning. + +Cargo manages three things: building your code, downloading the dependencies +your code needs, and building the dependencies your code needs. At first, your +program doesn't have any dependencies, so we'll only be using the first part of +its functionality. Eventually, we'll add more. Since we started off by using +Cargo, it'll be easy to add later. + +If you installed Rust via the official installers you will also have +Cargo. If you installed Rust some other way, you may want to [check +the Cargo +README](https://github.com/rust-lang/cargo#installing-cargo-from-nightlies) +for specific instructions about installing it. + +Let's convert Hello World to Cargo. + +To Cargo-ify our project, we need to do two things: Make a `Cargo.toml` +configuration file, and put our source file in the right place. Let's +do that part first: + +```{bash} +$ mkdir src +$ mv main.rs src/main.rs +``` + +Cargo expects your source files to live inside a `src` directory. That leaves +the top level for other things, like READMEs, license information, and anything +not related to your code. Cargo helps us keep our projects nice and tidy. A +place for everything, and everything in its place. + +Next, our configuration file: + +```{bash} +$ editor Cargo.toml +``` + +Make sure to get this name right: you need the capital `C`! + +Put this inside: + +```toml +[package] + +name = "hello_world" +version = "0.0.1" +authors = [ "Your name <you@example.com>" ] + +[[bin]] + +name = "hello_world" +``` + +This file is in the [TOML](https://github.com/toml-lang/toml) format. Let's let +it explain itself to you: + +> TOML aims to be a minimal configuration file format that's easy to read due +> to obvious semantics. TOML is designed to map unambiguously to a hash table. +> TOML should be easy to parse into data structures in a wide variety of +> languages. + +TOML is very similar to INI, but with some extra goodies. + +Anyway, there are two **table**s in this file: `package` and `bin`. The first +tells Cargo metadata about your package. The second tells Cargo that we're +interested in building a binary, not a library (though we could do both!), as +well as what it is named. + +Once you have this file in place, we should be ready to build! Try this: + +```{bash} +$ cargo build + Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world) +$ ./target/hello_world +Hello, world! +``` + +Bam! We build our project with `cargo build`, and run it with +`./target/hello_world`. This hasn't bought us a whole lot over our simple use +of `rustc`, but think about the future: when our project has more than one +file, we would need to call `rustc` more than once, and pass it a bunch of options to +tell it to build everything together. With Cargo, as our project grows, we can +just `cargo build` and it'll work the right way. + +You'll also notice that Cargo has created a new file: `Cargo.lock`. + +```toml +[root] +name = "hello_world" +version = "0.0.1" +``` + +This file is used by Cargo to keep track of dependencies in your application. +Right now, we don't have any, so it's a bit sparse. You won't ever need +to touch this file yourself, just let Cargo handle it. + +That's it! We've successfully built `hello_world` with Cargo. Even though our +program is simple, it's using much of the real tooling that you'll use for the +rest of your Rust career. + +Now that you've got the tools down, let's actually learn more about the Rust +language itself. These are the basics that will serve you well through the rest +of your time with Rust. diff --git a/src/doc/trpl/hello-world.md b/src/doc/trpl/hello-world.md new file mode 100644 index 00000000000..f9cc1ebf0bf --- /dev/null +++ b/src/doc/trpl/hello-world.md @@ -0,0 +1,164 @@ +% Hello, world! + +Now that you have Rust installed, let's write your first Rust program. It's +traditional to make your first program in any new language one that prints the +text "Hello, world!" to the screen. The nice thing about starting with such a +simple program is that you can verify that your compiler isn't just installed, +but also working properly. And printing information to the screen is a pretty +common thing to do. + +The first thing that we need to do is make a file to put our code in. I like +to make a `projects` directory in my home directory, and keep all my projects +there. Rust does not care where your code lives. + +This actually leads to one other concern we should address: this guide will +assume that you have basic familiarity with the command line. Rust does not +require that you know a whole ton about the command line, but until the +language is in a more finished state, IDE support is spotty. Rust makes no +specific demands on your editing tooling, or where your code lives. + +With that said, let's make a directory in our projects directory. + +```{bash} +$ mkdir ~/projects +$ cd ~/projects +$ mkdir hello_world +$ cd hello_world +``` + +If you're on Windows and not using PowerShell, the `~` may not work. Consult +the documentation for your shell for more details. + +Let's make a new source file next. I'm going to use the syntax `editor +filename` to represent editing a file in these examples, but you should use +whatever method you want. We'll call our file `main.rs`: + +```{bash} +$ editor main.rs +``` + +Rust files always end in a `.rs` extension. If you're using more than one word +in your filename, use an underscore. `hello_world.rs` rather than +`helloworld.rs`. + +Now that you've got your file open, type this in: + +```{rust} +fn main() { + println!("Hello, world!"); +} +``` + +Save the file, and then type this into your terminal window: + +```{bash} +$ rustc main.rs +$ ./main # or main.exe on Windows +Hello, world! +``` + +You can also run these examples on [play.rust-lang.org](http://play.rust-lang.org/) by clicking on the arrow that appears in the upper right of the example when you mouse over the code. + +Success! Let's go over what just happened in detail. + +```{rust} +fn main() { + +} +``` + +These lines define a **function** in Rust. The `main` function is special: +it's the beginning of every Rust program. The first line says "I'm declaring a +function named `main`, which takes no arguments and returns nothing." If there +were arguments, they would go inside the parentheses (`(` and `)`), and because +we aren't returning anything from this function, we've dropped that notation +entirely. We'll get to it later. + +You'll also note that the function is wrapped in curly braces (`{` and `}`). +Rust requires these around all function bodies. It is also considered good +style to put the opening curly brace on the same line as the function +declaration, with one space in between. + +Next up is this line: + +```{rust} + println!("Hello, world!"); +``` + +This line does all of the work in our little program. There are a number of +details that are important here. The first is that it's indented with four +spaces, not tabs. Please configure your editor of choice to insert four spaces +with the tab key. We provide some [sample configurations for various +editors](https://github.com/rust-lang/rust/tree/master/src/etc). + +The second point is the `println!()` part. This is calling a Rust **macro**, +which is how metaprogramming is done in Rust. If it were a function instead, it +would look like this: `println()`. For our purposes, we don't need to worry +about this difference. Just know that sometimes, you'll see a `!`, and that +means that you're calling a macro instead of a normal function. Rust implements +`println!` as a macro rather than a function for good reasons, but that's a +very advanced topic. You'll learn more when we talk about macros later. One +last thing to mention: Rust's macros are significantly different from C macros, +if you've used those. Don't be scared of using macros. We'll get to the details +eventually, you'll just have to trust us for now. + +Next, `"Hello, world!"` is a **string**. Strings are a surprisingly complicated +topic in a systems programming language, and this is a **statically allocated** +string. We will talk more about different kinds of allocation later. We pass +this string as an argument to `println!`, which prints the string to the +screen. Easy enough! + +Finally, the line ends with a semicolon (`;`). Rust is an **expression +oriented** language, which means that most things are expressions. The `;` is +used to indicate that this expression is over, and the next one is ready to +begin. Most lines of Rust code end with a `;`. We will cover this in-depth +later in the guide. + +Finally, actually **compiling** and **running** our program. We can compile +with our compiler, `rustc`, by passing it the name of our source file: + +```{bash} +$ rustc main.rs +``` + +This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust +will output a binary executable. You can see it with `ls`: + +```{bash} +$ ls +main main.rs +``` + +Or on Windows: + +```{bash} +$ dir +main.exe main.rs +``` + +There are now two files: our source code, with the `.rs` extension, and the +executable (`main.exe` on Windows, `main` everywhere else) + +```{bash} +$ ./main # or main.exe on Windows +``` + +This prints out our `Hello, world!` text to our terminal. + +If you come from a dynamically typed language like Ruby, Python, or JavaScript, +you may not be used to these two steps being separate. Rust is an +**ahead-of-time compiled language**, which means that you can compile a +program, give it to someone else, and they don't need to have Rust installed. +If you give someone a `.rb` or `.py` or `.js` file, they need to have +Ruby/Python/JavaScript installed, but you just need one command to both compile +and run your program. Everything is a tradeoff in language design, and Rust has +made its choice. + +Congratulations! You have officially written a Rust program. That makes you a +Rust programmer! Welcome. + +Next, I'd like to introduce you to another tool, Cargo, which is used to write +real-world Rust programs. Just using `rustc` is nice for simple things, but as +your project grows, you'll want something to help you manage all of the options +that it has, and to make it easy to share your code with other people and +projects. diff --git a/src/doc/trpl/if.md b/src/doc/trpl/if.md new file mode 100644 index 00000000000..6f81a27b2b7 --- /dev/null +++ b/src/doc/trpl/if.md @@ -0,0 +1,141 @@ +% `if` + +Rust's take on `if` is not particularly complex, but it's much more like the +`if` you'll find in a dynamically typed language than in a more traditional +systems language. So let's talk about it, to make sure you grasp the nuances. + +`if` is a specific form of a more general concept, the 'branch.' The name comes +from a branch in a tree: a decision point, where depending on a choice, +multiple paths can be taken. + +In the case of `if`, there is one choice that leads down two paths: + +```rust +let x = 5; + +if x == 5 { + println!("x is five!"); +} +``` + +If we changed the value of `x` to something else, this line would not print. +More specifically, if the expression after the `if` evaluates to `true`, then +the block is executed. If it's `false`, then it is not. + +If you want something to happen in the `false` case, use an `else`: + +```{rust} +let x = 5; + +if x == 5 { + println!("x is five!"); +} else { + println!("x is not five :("); +} +``` + +This is all pretty standard. However, you can also do this: + + +```{rust} +let x = 5; + +let y = if x == 5 { + 10 +} else { + 15 +}; // y: i32 +``` + +Which we can (and probably should) write like this: + +```{rust} +let x = 5; + +let y = if x == 5 { 10 } else { 15 }; // y: i32 +``` + +This reveals two interesting things about Rust: it is an expression-based +language, and semicolons are different from semicolons in other 'curly brace +and semicolon'-based languages. These two things are related. + +## Expressions vs. Statements + +Rust is primarily an expression based language. There are only two kinds of +statements, and everything else is an expression. + +So what's the difference? Expressions return a value, and statements do not. +In many languages, `if` is a statement, and therefore, `let x = if ...` would +make no sense. But in Rust, `if` is an expression, which means that it returns +a value. We can then use this value to initialize the binding. + +Speaking of which, bindings are a kind of the first of Rust's two statements. +The proper name is a **declaration statement**. So far, `let` is the only kind +of declaration statement we've seen. Let's talk about that some more. + +In some languages, variable bindings can be written as expressions, not just +statements. Like Ruby: + +```{ruby} +x = y = 5 +``` + +In Rust, however, using `let` to introduce a binding is _not_ an expression. The +following will produce a compile-time error: + +```{ignore} +let x = (let y = 5); // expected identifier, found keyword `let` +``` + +The compiler is telling us here that it was expecting to see the beginning of +an expression, and a `let` can only begin a statement, not an expression. + +Note that assigning to an already-bound variable (e.g. `y = 5`) is still an +expression, although its value is not particularly useful. Unlike C, where an +assignment evaluates to the assigned value (e.g. `5` in the previous example), +in Rust the value of an assignment is the unit type `()` (which we'll cover later). + +The second kind of statement in Rust is the **expression statement**. Its +purpose is to turn any expression into a statement. In practical terms, Rust's +grammar expects statements to follow other statements. This means that you use +semicolons to separate expressions from each other. This means that Rust +looks a lot like most other languages that require you to use semicolons +at the end of every line, and you will see semicolons at the end of almost +every line of Rust code you see. + +What is this exception that makes us say 'almost?' You saw it already, in this +code: + +```{rust} +let x = 5; + +let y: i32 = if x == 5 { 10 } else { 15 }; +``` + +Note that I've added the type annotation to `y`, to specify explicitly that I +want `y` to be an integer. + +This is not the same as this, which won't compile: + +```{ignore} +let x = 5; + +let y: i32 = if x == 5 { 10; } else { 15; }; +``` + +Note the semicolons after the 10 and 15. Rust will give us the following error: + +```text +error: mismatched types: expected `i32` but found `()` (expected i32 but found ()) +``` + +We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a +special type in Rust's type system. In Rust, `()` is _not_ a valid value for a +variable of type `i32`. It's only a valid value for variables of the type `()`, +which aren't very useful. Remember how we said statements don't return a value? +Well, that's the purpose of unit in this case. The semicolon turns any +expression into a statement by throwing away its value and returning unit +instead. + +There's one more time in which you won't see a semicolon at the end of a line +of Rust code. For that, we'll need our next concept: functions. diff --git a/src/doc/trpl/installing-rust.md b/src/doc/trpl/installing-rust.md new file mode 100644 index 00000000000..5893b51a420 --- /dev/null +++ b/src/doc/trpl/installing-rust.md @@ -0,0 +1,89 @@ +% Installing Rust + +The first step to using Rust is to install it! There are a number of ways to +install Rust, but the easiest is to use the `rustup` script. If you're on +Linux or a Mac, all you need to do is this (note that you don't need to type +in the `$`s, they just indicate the start of each command): + +```bash +$ curl -L https://static.rust-lang.org/rustup.sh | sudo sh +``` + +If you're concerned about the [potential insecurity](http://curlpipesh.tumblr.com/) of using `curl | sudo sh`, +please keep reading and see our disclaimer below. And feel free to use a two-step version of the installation and examine our installation script: + +```bash +$ curl -L https://static.rust-lang.org/rustup.sh -O +$ sudo sh rustup.sh +``` + +If you're on Windows, please download either the [32-bit +installer](https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.exe) +or the [64-bit +installer](https://static.rust-lang.org/dist/rust-nightly-x86_64-pc-windows-gnu.exe) +and run it. + +If you decide you don't want Rust anymore, we'll be a bit sad, but that's okay. +Not every programming language is great for everyone. Just pass an argument to +the script: + +```bash +$ curl -s https://static.rust-lang.org/rustup.sh | sudo sh -s -- --uninstall +``` + +If you used the Windows installer, just re-run the `.exe` and it will give you +an uninstall option. + +You can re-run this script any time you want to update Rust. Which, at this +point, is often. Rust is still pre-1.0, and so people assume that you're using +a very recent Rust. + +This brings me to one other point: some people, and somewhat rightfully so, get +very upset when we tell you to `curl | sudo sh`. And they should be! Basically, +when you do this, you are trusting that the good people who maintain Rust +aren't going to hack your computer and do bad things. That's a good instinct! +If you're one of those people, please check out the documentation on [building +Rust from Source](https://github.com/rust-lang/rust#building-from-source), or +[the official binary downloads](http://www.rust-lang.org/install.html). And we +promise that this method will not be the way to install Rust forever: it's just +the easiest way to keep people updated while Rust is in its alpha state. + +Oh, we should also mention the officially supported platforms: + +* Windows (7, 8, Server 2008 R2) +* Linux (2.6.18 or later, various distributions), x86 and x86-64 +* OSX 10.7 (Lion) or greater, x86 and x86-64 + +We extensively test Rust on these platforms, and a few others, too, like +Android. But these are the ones most likely to work, as they have the most +testing. + +Finally, a comment about Windows. Rust considers Windows to be a first-class +platform upon release, but if we're honest, the Windows experience isn't as +integrated as the Linux/OS X experience is. We're working on it! If anything +does not work, it is a bug. Please let us know if that happens. Each and every +commit is tested against Windows just like any other platform. + +If you've got Rust installed, you can open up a shell, and type this: + +```bash +$ rustc --version +``` + +You should see some output that looks something like this: + +```bash +rustc 1.0.0-nightly (f11f3e7ba 2015-01-04 20:02:14 +0000) +``` + +If you did, Rust has been installed successfully! Congrats! + +If not, there are a number of places where you can get help. The easiest is +[the #rust IRC channel on irc.mozilla.org](irc://irc.mozilla.org/#rust), which +you can access through +[Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click +that link, and you'll be chatting with other Rustaceans (a silly nickname we +call ourselves), and we can help you out. Other great resources include [our +forum](http://discuss.rust-lang.org/), [the /r/rust +subreddit](http://www.reddit.com/r/rust), and [Stack +Overflow](http://stackoverflow.com/questions/tagged/rust). diff --git a/src/doc/trpl/intermediate.md b/src/doc/trpl/intermediate.md new file mode 100644 index 00000000000..73370a32231 --- /dev/null +++ b/src/doc/trpl/intermediate.md @@ -0,0 +1,7 @@ +% Intermediate + +This section contains individual chapters, which are self-contained. They focus +on specific topics, and can be read in any order. + +After reading "Intermediate," you will have a solid understanding of Rust, +and will be able to understand most Rust code and write more complex programs. diff --git a/src/doc/trpl/iterators.md b/src/doc/trpl/iterators.md new file mode 100644 index 00000000000..a773b7329db --- /dev/null +++ b/src/doc/trpl/iterators.md @@ -0,0 +1,339 @@ +% Iterators + +Let's talk about loops. + +Remember Rust's `for` loop? Here's an example: + +```{rust} +for x in range(0i, 10i) { + println!("{}", x); +} +``` + +Now that you know more Rust, we can talk in detail about how this works. The +`range` function returns an **iterator**. An iterator is something that we can +call the `.next()` method on repeatedly, and it gives us a sequence of things. + +Like this: + +```{rust} +let mut range = range(0i, 10i); + +loop { + match range.next() { + Some(x) => { + println!("{}", x); + }, + None => { break } + } +} +``` + +We make a mutable binding to the return value of `range`, which is our iterator. +We then `loop`, with an inner `match`. This `match` is used on the result of +`range.next()`, which gives us a reference to the next value of the iterator. +`next` returns an `Option<int>`, in this case, which will be `Some(int)` when +we have a value and `None` once we run out. If we get `Some(int)`, we print it +out, and if we get `None`, we `break` out of the loop. + +This code sample is basically the same as our `for` loop version. The `for` +loop is just a handy way to write this `loop`/`match`/`break` construct. + +`for` loops aren't the only thing that uses iterators, however. Writing your +own iterator involves implementing the `Iterator` trait. While doing that is +outside of the scope of this guide, Rust provides a number of useful iterators +to accomplish various tasks. Before we talk about those, we should talk about a +Rust anti-pattern. And that's `range`. + +Yes, we just talked about how `range` is cool. But `range` is also very +primitive. For example, if you needed to iterate over the contents of +a vector, you may be tempted to write this: + +```{rust} +let nums = vec![1i, 2i, 3i]; + +for i in range(0u, nums.len()) { + println!("{}", nums[i]); +} +``` + +This is strictly worse than using an actual iterator. The `.iter()` method on +vectors returns an iterator which iterates through a reference to each element +of the vector in turn. So write this: + +```{rust} +let nums = vec![1i, 2i, 3i]; + +for num in nums.iter() { + println!("{}", num); +} +``` + +There are two reasons for this. First, this more directly expresses what we +mean. We iterate through the entire vector, rather than iterating through +indexes, and then indexing the vector. Second, this version is more efficient: +the first version will have extra bounds checking because it used indexing, +`nums[i]`. But since we yield a reference to each element of the vector in turn +with the iterator, there's no bounds checking in the second example. This is +very common with iterators: we can ignore unnecessary bounds checks, but still +know that we're safe. + +There's another detail here that's not 100% clear because of how `println!` +works. `num` is actually of type `&int`. That is, it's a reference to an `int`, +not an `int` itself. `println!` handles the dereferencing for us, so we don't +see it. This code works fine too: + +```{rust} +let nums = vec![1i, 2i, 3i]; + +for num in nums.iter() { + println!("{}", *num); +} +``` + +Now we're explicitly dereferencing `num`. Why does `iter()` give us references? +Well, if it gave us the data itself, we would have to be its owner, which would +involve making a copy of the data and giving us the copy. With references, +we're just borrowing a reference to the data, and so it's just passing +a reference, without needing to do the copy. + +So, now that we've established that `range` is often not what you want, let's +talk about what you do want instead. + +There are three broad classes of things that are relevant here: iterators, +**iterator adapters**, and **consumers**. Here's some definitions: + +* 'iterators' give you a sequence of values. +* 'iterator adapters' operate on an iterator, producing a new iterator with a + different output sequence. +* 'consumers' operate on an iterator, producing some final set of values. + +Let's talk about consumers first, since you've already seen an iterator, +`range`. + +## Consumers + +A 'consumer' operates on an iterator, returning some kind of value or values. +The most common consumer is `collect()`. This code doesn't quite compile, +but it shows the intention: + +```{rust,ignore} +let one_to_one_hundred = range(1i, 101i).collect(); +``` + +As you can see, we call `collect()` on our iterator. `collect()` takes +as many values as the iterator will give it, and returns a collection +of the results. So why won't this compile? Rust can't determine what +type of things you want to collect, and so you need to let it know. +Here's the version that does compile: + +```{rust} +let one_to_one_hundred = range(1i, 101i).collect::<Vec<int>>(); +``` + +If you remember, the `::<>` syntax allows us to give a type hint, +and so we tell it that we want a vector of integers. + +`collect()` is the most common consumer, but there are others too. `find()` +is one: + +```{rust} +let greater_than_forty_two = range(0i, 100i) + .find(|x| *x > 42); + +match greater_than_forty_two { + Some(_) => println!("We got some numbers!"), + None => println!("No numbers found :("), +} +``` + +`find` takes a closure, and works on a reference to each element of an +iterator. This closure returns `true` if the element is the element we're +looking for, and `false` otherwise. Because we might not find a matching +element, `find` returns an `Option` rather than the element itself. + +Another important consumer is `fold`. Here's what it looks like: + +```{rust} +let sum = range(1i, 4i) + .fold(0i, |sum, x| sum + x); +``` + +`fold()` is a consumer that looks like this: +`fold(base, |accumulator, element| ...)`. It takes two arguments: the first +is an element called the "base". The second is a closure that itself takes two +arguments: the first is called the "accumulator," and the second is an +"element." Upon each iteration, the closure is called, and the result is the +value of the accumulator on the next iteration. On the first iteration, the +base is the value of the accumulator. + +Okay, that's a bit confusing. Let's examine the values of all of these things +in this iterator: + +| base | accumulator | element | closure result | +|------|-------------|---------|----------------| +| 0i | 0i | 1i | 1i | +| 0i | 1i | 2i | 3i | +| 0i | 3i | 3i | 6i | + +We called `fold()` with these arguments: + +```{rust} +# range(1i, 4i) +.fold(0i, |sum, x| sum + x); +``` + +So, `0i` is our base, `sum` is our accumulator, and `x` is our element. On the +first iteration, we set `sum` to `0i`, and `x` is the first element of `nums`, +`1i`. We then add `sum` and `x`, which gives us `0i + 1i = 1i`. On the second +iteration, that value becomes our accumulator, `sum`, and the element is +the second element of the array, `2i`. `1i + 2i = 3i`, and so that becomes +the value of the accumulator for the last iteration. On that iteration, +`x` is the last element, `3i`, and `3i + 3i = 6i`, which is our final +result for our sum. `1 + 2 + 3 = 6`, and that's the result we got. + +Whew. `fold` can be a bit strange the first few times you see it, but once it +clicks, you can use it all over the place. Any time you have a list of things, +and you want a single result, `fold` is appropriate. + +Consumers are important due to one additional property of iterators we haven't +talked about yet: laziness. Let's talk some more about iterators, and you'll +see why consumers matter. + +## Iterators + +As we've said before, an iterator is something that we can call the +`.next()` method on repeatedly, and it gives us a sequence of things. +Because you need to call the method, this means that iterators +are **lazy** and don't need to generate all of the values upfront. +This code, for example, does not actually generate the numbers +`1-100`, and just creates a value that represents the sequence: + +```{rust} +let nums = range(1i, 100i); +``` + +Since we didn't do anything with the range, it didn't generate the sequence. +Let's add the consumer: + +```{rust} +let nums = range(1i, 100i).collect::<Vec<int>>(); +``` + +Now, `collect()` will require that `range()` give it some numbers, and so +it will do the work of generating the sequence. + +`range` is one of two basic iterators that you'll see. The other is `iter()`, +which you've used before. `iter()` can turn a vector into a simple iterator +that gives you each element in turn: + +```{rust} +let nums = [1i, 2i, 3i]; + +for num in nums.iter() { + println!("{}", num); +} +``` + +These two basic iterators should serve you well. There are some more +advanced iterators, including ones that are infinite. Like `count`: + +```{rust} +std::iter::count(1i, 5i); +``` + +This iterator counts up from one, adding five each time. It will give +you a new integer every time, forever (well, technically, until it reaches the +maximum number representable by an `int`). But since iterators are lazy, +that's okay! You probably don't want to use `collect()` on it, though... + +That's enough about iterators. Iterator adapters are the last concept +we need to talk about with regards to iterators. Let's get to it! + +## Iterator adapters + +"Iterator adapters" take an iterator and modify it somehow, producing +a new iterator. The simplest one is called `map`: + +```{rust,ignore} +range(1i, 100i).map(|x| x + 1i); +``` + +`map` is called upon another iterator, and produces a new iterator where each +element reference has the closure it's been given as an argument called on it. +So this would give us the numbers from `2-100`. Well, almost! If you +compile the example, you'll get a warning: + +```{notrust,ignore} +warning: unused result which must be used: iterator adaptors are lazy and + do nothing unless consumed, #[warn(unused_must_use)] on by default + range(1i, 100i).map(|x| x + 1i); + ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``` + +Laziness strikes again! That closure will never execute. This example +doesn't print any numbers: + +```{rust,ignore} +range(1i, 100i).map(|x| println!("{}", x)); +``` + +If you are trying to execute a closure on an iterator for its side effects, +just use `for` instead. + +There are tons of interesting iterator adapters. `take(n)` will return an +iterator over the next `n` elements of the original iterator, note that this +has no side effect on the original iterator. Let's try it out with our infinite +iterator from before, `count()`: + +```{rust} +for i in std::iter::count(1i, 5i).take(5) { + println!("{}", i); +} +``` + +This will print + +```{notrust,ignore} +1 +6 +11 +16 +21 +``` + +`filter()` is an adapter that takes a closure as an argument. This closure +returns `true` or `false`. The new iterator `filter()` produces +only the elements that that closure returns `true` for: + +```{rust} +for i in range(1i, 100i).filter(|&x| x % 2 == 0) { + println!("{}", i); +} +``` + +This will print all of the even numbers between one and a hundred. +(Note that because `filter` doesn't consume the elements that are +being iterated over, it is passed a reference to each element, and +thus the filter predicate uses the `&x` pattern to extract the integer +itself.) + +You can chain all three things together: start with an iterator, adapt it +a few times, and then consume the result. Check it out: + +```{rust} +range(1i, 1000i) + .filter(|&x| x % 2 == 0) + .filter(|&x| x % 3 == 0) + .take(5) + .collect::<Vec<int>>(); +``` + +This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. + +This is just a small taste of what iterators, iterator adapters, and consumers +can help you with. There are a number of really useful iterators, and you can +write your own as well. Iterators provide a safe, efficient way to manipulate +all kinds of lists. They're a little unusual at first, but if you play with +them, you'll get hooked. For a full list of the different iterators and +consumers, check out the [iterator module documentation](../std/iter/index.html). diff --git a/src/doc/trpl/looping.md b/src/doc/trpl/looping.md new file mode 100644 index 00000000000..80926c99e87 --- /dev/null +++ b/src/doc/trpl/looping.md @@ -0,0 +1,133 @@ +% Looping + +Looping is the last basic construct that we haven't learned yet in Rust. Rust has +two main looping constructs: `for` and `while`. + +## `for` + +The `for` loop is used to loop a particular number of times. Rust's `for` loops +work a bit differently than in other systems languages, however. Rust's `for` +loop doesn't look like this "C-style" `for` loop: + +```{c} +for (x = 0; x < 10; x++) { + printf( "%d\n", x ); +} +``` + +Instead, it looks like this: + +```{rust} +for x in range(0, 10) { + println!("{}", x); // x: i32 +} +``` + +In slightly more abstract terms, + +```{ignore} +for var in expression { + code +} +``` + +The expression is an iterator, which we will discuss in more depth later in the +guide. The iterator gives back a series of elements. Each element is one +iteration of the loop. That value is then bound to the name `var`, which is +valid for the loop body. Once the body is over, the next value is fetched from +the iterator, and we loop another time. When there are no more values, the +`for` loop is over. + +In our example, `range` is a function that takes a start and an end position, +and gives an iterator over those values. The upper bound is exclusive, though, +so our loop will print `0` through `9`, not `10`. + +Rust does not have the "C-style" `for` loop on purpose. Manually controlling +each element of the loop is complicated and error prone, even for experienced C +developers. + +We'll talk more about `for` when we cover **iterator**s, later in the Guide. + +## `while` + +The other kind of looping construct in Rust is the `while` loop. It looks like +this: + +```{rust} +let mut x = 5u; // mut x: uint +let mut done = false; // mut done: bool + +while !done { + x += x - 3; + println!("{}", x); + if x % 5 == 0 { done = true; } +} +``` + +`while` loops are the correct choice when you're not sure how many times +you need to loop. + +If you need an infinite loop, you may be tempted to write this: + +```{rust,ignore} +while true { +``` + +However, Rust has a dedicated keyword, `loop`, to handle this case: + +```{rust,ignore} +loop { +``` + +Rust's control-flow analysis treats this construct differently than a +`while true`, since we know that it will always loop. The details of what +that _means_ aren't super important to understand at this stage, but in +general, the more information we can give to the compiler, the better it +can do with safety and code generation, so you should always prefer +`loop` when you plan to loop infinitely. + +## Ending iteration early + +Let's take a look at that `while` loop we had earlier: + +```{rust} +let mut x = 5u; +let mut done = false; + +while !done { + x += x - 3; + println!("{}", x); + if x % 5 == 0 { done = true; } +} +``` + +We had to keep a dedicated `mut` boolean variable binding, `done`, to know +when we should exit out of the loop. Rust has two keywords to help us with +modifying iteration: `break` and `continue`. + +In this case, we can write the loop in a better way with `break`: + +```{rust} +let mut x = 5u; + +loop { + x += x - 3; + println!("{}", x); + if x % 5 == 0 { break; } +} +``` + +We now loop forever with `loop` and use `break` to break out early. + +`continue` is similar, but instead of ending the loop, goes to the next +iteration. This will only print the odd numbers: + +```{rust} +for x in range(0, 10) { + if x % 2 == 0 { continue; } + + println!("{}", x); +} +``` + +Both `continue` and `break` are valid in both kinds of loops. diff --git a/src/doc/guide-macros.md b/src/doc/trpl/macros.md index 95f5305775e..c694806b4ba 100644 --- a/src/doc/guide-macros.md +++ b/src/doc/trpl/macros.md @@ -507,7 +507,7 @@ When this library is loaded with `#[use_macros] extern crate`, only `m2` will be imported. The Rust Reference has a [listing of macro-related -attributes](reference.html#macro--and-plugin-related-attributes). +attributes](../reference.html#macro--and-plugin-related-attributes). # The variable `$crate` @@ -567,7 +567,7 @@ intermediate states out, and passing the flag `--pretty expanded` as a command-line argument to the compiler will show the result of expansion. If Rust's macro system can't do what you need, you may want to write a -[compiler plugin](guide-plugin.html) instead. Compared to `macro_rules!` +[compiler plugin](plugin.html) instead. Compared to `macro_rules!` macros, this is significantly more work, the interfaces are much less stable, and the warnings about debugging apply ten-fold. In exchange you get the flexibility of running arbitrary Rust code within the compiler. Syntax diff --git a/src/doc/trpl/match.md b/src/doc/trpl/match.md new file mode 100644 index 00000000000..c120142cf5c --- /dev/null +++ b/src/doc/trpl/match.md @@ -0,0 +1,156 @@ +% Match + +Often, a simple `if`/`else` isn't enough, because you have more than two +possible options. Also, `else` conditions can get incredibly complicated, so +what's the solution? + +Rust has a keyword, `match`, that allows you to replace complicated `if`/`else` +groupings with something more powerful. Check it out: + +```{rust} +let x = 5; + +match x { + 1 => println!("one"), + 2 => println!("two"), + 3 => println!("three"), + 4 => println!("four"), + 5 => println!("five"), + _ => println!("something else"), +} +``` + +`match` takes an expression and then branches based on its value. Each 'arm' of +the branch is of the form `val => expression`. When the value matches, that arm's +expression will be evaluated. It's called `match` because of the term 'pattern +matching', which `match` is an implementation of. + +So what's the big advantage here? Well, there are a few. First of all, `match` +enforces 'exhaustiveness checking'. Do you see that last arm, the one with the +underscore (`_`)? If we remove that arm, Rust will give us an error: + +```text +error: non-exhaustive patterns: `_` not covered +``` + +In other words, Rust is trying to tell us we forgot a value. Because `x` is an +integer, Rust knows that it can have a number of different values – for example, +`6`. Without the `_`, however, there is no arm that could match, and so Rust refuses +to compile. `_` acts like a 'catch-all arm'. If none of the other arms match, +the arm with `_` will, and since we have this catch-all arm, we now have an arm +for every possible value of `x`, and so our program will compile successfully. + +`match` statements also destructure enums, as well. Remember this code from the +section on enums? + +```{rust} +use std::cmp::Ordering; + +fn cmp(a: i32, b: i32) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} + +fn main() { + let x = 5; + let y = 10; + + let ordering = cmp(x, y); + + if ordering == Ordering::Less { + println!("less"); + } else if ordering == Ordering::Greater { + println!("greater"); + } else if ordering == Ordering::Equal { + println!("equal"); + } +} +``` + +We can re-write this as a `match`: + +```{rust} +use std::cmp::Ordering; + +fn cmp(a: i32, b: i32) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} + +fn main() { + let x = 5; + let y = 10; + + match cmp(x, y) { + Ordering::Less => println!("less"), + Ordering::Greater => println!("greater"), + Ordering::Equal => println!("equal"), + } +} +``` + +This version has way less noise, and it also checks exhaustively to make sure +that we have covered all possible variants of `Ordering`. With our `if`/`else` +version, if we had forgotten the `Greater` case, for example, our program would +have happily compiled. If we forget in the `match`, it will not. Rust helps us +make sure to cover all of our bases. + +`match` expressions also allow us to get the values contained in an `enum` +(also known as destructuring) as follows: + +```{rust} +enum OptionalInt { + Value(i32), + Missing, +} + +fn main() { + let x = OptionalInt::Value(5); + let y = OptionalInt::Missing; + + match x { + OptionalInt::Value(n) => println!("x is {}", n), + OptionalInt::Missing => println!("x is missing!"), + } + + match y { + OptionalInt::Value(n) => println!("y is {}", n), + OptionalInt::Missing => println!("y is missing!"), + } +} +``` + +That is how you can get and use the values contained in `enum`s. +It can also allow us to handle errors or unexpected computations; for example, a +function that is not guaranteed to be able to compute a result (an `i32` here) +could return an `OptionalInt`, and we would handle that value with a `match`. +As you can see, `enum` and `match` used together are quite useful! + +`match` is also an expression, which means we can use it on the right-hand +side of a `let` binding or directly where an expression is used. We could +also implement the previous example like this: + +```{rust} +use std::cmp::Ordering; + +fn cmp(a: i32, b: i32) -> Ordering { + if a < b { Ordering::Less } + else if a > b { Ordering::Greater } + else { Ordering::Equal } +} + +fn main() { + let x = 5; + let y = 10; + + println!("{}", match cmp(x, y) { + Ordering::Less => "less", + Ordering::Greater => "greater", + Ordering::Equal => "equal", + }); +} +``` + +Sometimes, it's a nice pattern. diff --git a/src/doc/trpl/method-syntax.md b/src/doc/trpl/method-syntax.md new file mode 100644 index 00000000000..54e9cdf5191 --- /dev/null +++ b/src/doc/trpl/method-syntax.md @@ -0,0 +1,88 @@ +% Method Syntax + +Functions are great, but if you want to call a bunch of them on some data, it +can be awkward. Consider this code: + +```{rust,ignore} +baz(bar(foo(x))); +``` + +We would read this left-to right, and so we see 'baz bar foo.' But this isn't the +order that the functions would get called in, that's inside-out: 'foo bar baz.' +Wouldn't it be nice if we could do this instead? + +```{rust,ignore} +x.foo().bar().baz(); +``` + +Luckily, as you may have guessed with the leading question, you can! Rust provides +the ability to use this **method call syntax** via the `impl` keyword. + +Here's how it works: + +```{rust} +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } +} + +fn main() { + let c = Circle { x: 0.0, y: 0.0, radius: 2.0 }; + println!("{}", c.area()); +} +``` + +This will print `12.566371`. + +We've made a struct that represents a circle. We then write an `impl` block, +and inside it, define a method, `area`. Methods take a special first +parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`. +You can think of this first parameter as being the `x` in `x.foo()`. The three +variants correspond to the three kinds of thing `x` could be: `self` if it's +just a value on the stack, `&self` if it's a reference, and `&mut self` if it's +a mutable reference. We should default to using `&self`, as it's the most +common. + +Finally, as you may remember, the value of the area of a circle is `π*r²`. +Because we took the `&self` parameter to `area`, we can use it just like any +other parameter. Because we know it's a `Circle`, we can access the `radius` +just like we would with any other struct. An import of π and some +multiplications later, and we have our area. + +You can also define methods that do not take a `self` parameter. Here's a +pattern that's very common in Rust code: + +```{rust} +# #![allow(non_shorthand_field_patterns)] +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl Circle { + fn new(x: f64, y: f64, radius: f64) -> Circle { + Circle { + x: x, + y: y, + radius: radius, + } + } +} + +fn main() { + let c = Circle::new(0.0, 0.0, 2.0); +} +``` + +This **static method** builds a new `Circle` for us. Note that static methods +are called with the `Struct::method()` syntax, rather than the `ref.method()` +syntax. + diff --git a/src/doc/guide-ownership.md b/src/doc/trpl/ownership.md index 414a874082e..3db4da73f93 100644 --- a/src/doc/guide-ownership.md +++ b/src/doc/trpl/ownership.md @@ -81,27 +81,29 @@ therefore deallocates the memory for you. Here's the equivalent example in Rust: ```rust +# use std::boxed::Box; { - let x = box 5i; + let x = Box::new(5i); } ``` -The `box` keyword creates a `Box<T>` (specifically `Box<int>` in this case) by -allocating a small segment of memory on the heap with enough space to fit an -`int`. But where in the code is the box deallocated? We said before that we -must have a deallocation for each allocation. Rust handles this for you. It +The `Box::new` function creates a `Box<T>` (specifically `Box<int>` in this +case) by allocating a small segment of memory on the heap with enough space to +fit an `int`. But where in the code is the box deallocated? We said before that +we must have a deallocation for each allocation. Rust handles this for you. It knows that our handle, `x`, is the owning reference to our box. Rust knows that `x` will go out of scope at the end of the block, and so it inserts a call to deallocate the memory at the end of the scope. Because the compiler does this -for us, it's impossible to forget. We always have exactly one deallocation paired -with each of our allocations. +for us, it's impossible to forget. We always have exactly one deallocation + paired with each of our allocations. This is pretty straightforward, but what happens when we want to pass our box to a function? Let's look at some code: ```rust +# use std::boxed::Box; fn main() { - let x = box 5i; + let x = Box::new(5i); add_one(x); } @@ -115,8 +117,9 @@ This code works, but it's not ideal. For example, let's add one more line of code, where we print out the value of `x`: ```{rust,ignore} +# use std::boxed::Box; fn main() { - let x = box 5i; + let x = Box::new(5i); add_one(x); @@ -148,8 +151,9 @@ To fix this, we can have `add_one` give ownership back when it's done with the box: ```rust +# use std::boxed::Box; fn main() { - let x = box 5i; + let x = Box::new(5i); let y = add_one(x); @@ -458,7 +462,7 @@ lifetime, and so if you elide a lifetime (like `&T` instead of `&'a T`), Rust will do three things to determine what those lifetimes should be. When talking about lifetime elision, we use the term 'input lifetime' and -'output lifetime'. An 'input liftime' is a lifetime associated with a parameter +'output lifetime'. An 'input lifetime' is a lifetime associated with a parameter of a function, and an 'output lifetime' is a lifetime associated with the return value of a function. For example, this function has an input lifetime: diff --git a/src/doc/trpl/patterns.md b/src/doc/trpl/patterns.md new file mode 100644 index 00000000000..282703c4387 --- /dev/null +++ b/src/doc/trpl/patterns.md @@ -0,0 +1,199 @@ +% Patterns + +We've made use of patterns a few times in the guide: first with `let` bindings, +then with `match` statements. Let's go on a whirlwind tour of all of the things +patterns can do! + +A quick refresher: you can match against literals directly, and `_` acts as an +'any' case: + +```{rust} +let x = 1i; + +match x { + 1 => println!("one"), + 2 => println!("two"), + 3 => println!("three"), + _ => println!("anything"), +} +``` + +You can match multiple patterns with `|`: + +```{rust} +let x = 1i; + +match x { + 1 | 2 => println!("one or two"), + 3 => println!("three"), + _ => println!("anything"), +} +``` + +You can match a range of values with `...`: + +```{rust} +let x = 1i; + +match x { + 1 ... 5 => println!("one through five"), + _ => println!("anything"), +} +``` + +Ranges are mostly used with integers and single characters. + +If you're matching multiple things, via a `|` or a `...`, you can bind +the value to a name with `@`: + +```{rust} +let x = 1i; + +match x { + e @ 1 ... 5 => println!("got a range element {}", e), + _ => println!("anything"), +} +``` + +If you're matching on an enum which has variants, you can use `..` to +ignore the value and type in the variant: + +```{rust} +enum OptionalInt { + Value(int), + Missing, +} + +let x = OptionalInt::Value(5i); + +match x { + OptionalInt::Value(..) => println!("Got an int!"), + OptionalInt::Missing => println!("No such luck."), +} +``` + +You can introduce **match guards** with `if`: + +```{rust} +enum OptionalInt { + Value(int), + Missing, +} + +let x = OptionalInt::Value(5i); + +match x { + OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), + OptionalInt::Value(..) => println!("Got an int!"), + OptionalInt::Missing => println!("No such luck."), +} +``` + +If you're matching on a pointer, you can use the same syntax as you declared it +with. First, `&`: + +```{rust} +let x = &5i; + +match x { + &val => println!("Got a value: {}", val), +} +``` + +Here, the `val` inside the `match` has type `int`. In other words, the left-hand +side of the pattern destructures the value. If we have `&5i`, then in `&val`, `val` +would be `5i`. + +If you want to get a reference, use the `ref` keyword: + +```{rust} +let x = 5i; + +match x { + ref r => println!("Got a reference to {}", r), +} +``` + +Here, the `r` inside the `match` has the type `&int`. In other words, the `ref` +keyword _creates_ a reference, for use in the pattern. If you need a mutable +reference, `ref mut` will work in the same way: + +```{rust} +let mut x = 5i; + +match x { + ref mut mr => println!("Got a mutable reference to {}", mr), +} +``` + +If you have a struct, you can destructure it inside of a pattern: + +```{rust} +# #![allow(non_shorthand_field_patterns)] +struct Point { + x: int, + y: int, +} + +let origin = Point { x: 0i, y: 0i }; + +match origin { + Point { x: x, y: y } => println!("({},{})", x, y), +} +``` + +If we only care about some of the values, we don't have to give them all names: + +```{rust} +# #![allow(non_shorthand_field_patterns)] +struct Point { + x: int, + y: int, +} + +let origin = Point { x: 0i, y: 0i }; + +match origin { + Point { x: x, .. } => println!("x is {}", x), +} +``` + +You can do this kind of match on any member, not just the first: + +```{rust} +# #![allow(non_shorthand_field_patterns)] +struct Point { + x: int, + y: int, +} + +let origin = Point { x: 0i, y: 0i }; + +match origin { + Point { y: y, .. } => println!("y is {}", y), +} +``` + +If you want to match against a slice or array, you can use `[]`: + +```{rust} +fn main() { + let v = vec!["match_this", "1"]; + + match v.as_slice() { + ["match_this", second] => println!("The second element is {}", second), + _ => {}, + } +} +``` + +Whew! That's a lot of different ways to match things, and they can all be +mixed and matched, depending on what you're doing: + +```{rust,ignore} +match x { + Foo { x: Some(ref name), y: None } => ... +} +``` + +Patterns are very powerful. Make good use of them. diff --git a/src/doc/guide-plugin.md b/src/doc/trpl/plugins.md index 025f0cced63..2a0710d018c 100644 --- a/src/doc/guide-plugin.md +++ b/src/doc/trpl/plugins.md @@ -5,20 +5,20 @@ <p> <b>Warning:</b> Plugins are an advanced, unstable feature! For many details, the only available documentation is the <a -href="syntax/index.html"><code>libsyntax</code></a> and <a -href="rustc/index.html"><code>librustc</code></a> API docs, or even the source +href="../syntax/index.html"><code>libsyntax</code></a> and <a +href="../rustc/index.html"><code>librustc</code></a> API docs, or even the source code itself. These internal compiler APIs are also subject to change at any time. </p> <p> For defining new syntax it is often much easier to use Rust's <a -href="guide-macros.html">built-in macro system</a>. +href="macros.html">built-in macro system</a>. </p> <p style="margin-bottom: 0"> The code in this document uses language features not covered in the Rust -Guide. See the <a href="reference.html">Reference Manual</a> for more +Guide. See the <a href="../reference.html">Reference Manual</a> for more information. </p> @@ -32,19 +32,19 @@ extend the compiler's behavior with new syntax extensions, lint checks, etc. A plugin is a dynamic library crate with a designated "registrar" function that registers extensions with `rustc`. Other crates can use these extensions by loading the plugin crate with `#[plugin] extern crate`. See the -[`rustc::plugin`](rustc/plugin/index.html) documentation for more about the +[`rustc::plugin`](../rustc/plugin/index.html) documentation for more about the mechanics of defining and loading a plugin. Arguments passed as `#[plugin=...]` or `#[plugin(...)]` are not interpreted by rustc itself. They are provided to the plugin through the `Registry`'s [`args` -method](rustc/plugin/registry/struct.Registry.html#method.args). +method](../rustc/plugin/registry/struct.Registry.html#method.args). # Syntax extensions Plugins can extend Rust's syntax in various ways. One kind of syntax extension is the procedural macro. These are invoked the same way as [ordinary -macros](guide-macros.html), but the expansion is performed by arbitrary Rust -code that manipulates [syntax trees](syntax/ast/index.html) at +macros](macros.html), but the expansion is performed by arbitrary Rust +code that manipulates [syntax trees](../syntax/ast/index.html) at compile time. Let's write a plugin @@ -126,14 +126,13 @@ The advantages over a simple `fn(&str) -> uint` are: a way to define new literal syntax for any data type. In addition to procedural macros, you can define new -[`deriving`](reference.html#deriving)-like attributes and other kinds of +[`deriving`](../reference.html#deriving)-like attributes and other kinds of extensions. See -[`Registry::register_syntax_extension`](rustc/plugin/registry/struct.Registry.html#method.register_syntax_extension) +[`Registry::register_syntax_extension`](../rustc/plugin/registry/struct.Registry.html#method.register_syntax_extension) and the [`SyntaxExtension` enum](http://doc.rust-lang.org/syntax/ext/base/enum.SyntaxExtension.html). For a more involved macro example, see -[`src/libregex_macros/lib.rs`](https://github.com/rust-lang/rust/blob/master/src/libregex_macros/lib.rs) -in the Rust distribution. +[`regex_macros`](https://github.com/rust-lang/regex/blob/master/regex_macros/src/lib.rs). ## Tips and tricks @@ -147,7 +146,7 @@ variables of the same name (but different syntax contexts) are in play in the same scope. In this case `--pretty expanded,hygiene` will tell you about the syntax contexts. -You can use [`syntax::parse`](syntax/parse/index.html) to turn token trees into +You can use [`syntax::parse`](../syntax/parse/index.html) to turn token trees into higher-level syntax elements like expressions: ```ignore @@ -163,23 +162,23 @@ Looking through [`libsyntax` parser code](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs) will give you a feel for how the parsing infrastructure works. -Keep the [`Span`s](syntax/codemap/struct.Span.html) of +Keep the [`Span`s](../syntax/codemap/struct.Span.html) of everything you parse, for better error reporting. You can wrap -[`Spanned`](syntax/codemap/struct.Spanned.html) around +[`Spanned`](../syntax/codemap/struct.Spanned.html) around your custom data structures. Calling -[`ExtCtxt::span_fatal`](syntax/ext/base/struct.ExtCtxt.html#method.span_fatal) +[`ExtCtxt::span_fatal`](../syntax/ext/base/struct.ExtCtxt.html#method.span_fatal) will immediately abort compilation. It's better to instead call -[`ExtCtxt::span_err`](syntax/ext/base/struct.ExtCtxt.html#method.span_err) +[`ExtCtxt::span_err`](../syntax/ext/base/struct.ExtCtxt.html#method.span_err) and return -[`DummyResult`](syntax/ext/base/struct.DummyResult.html), +[`DummyResult`](../syntax/ext/base/struct.DummyResult.html), so that the compiler can continue and find further errors. The example above produced an integer literal using -[`AstBuilder::expr_uint`](syntax/ext/build/trait.AstBuilder.html#tymethod.expr_uint). +[`AstBuilder::expr_uint`](../syntax/ext/build/trait.AstBuilder.html#tymethod.expr_uint). As an alternative to the `AstBuilder` trait, `libsyntax` provides a set of -[quasiquote macros](syntax/ext/quote/index.html). They are undocumented and +[quasiquote macros](../syntax/ext/quote/index.html). They are undocumented and very rough around the edges. However, the implementation may be a good starting point for an improved quasiquote as an ordinary plugin library. @@ -187,7 +186,7 @@ starting point for an improved quasiquote as an ordinary plugin library. # Lint plugins Plugins can extend [Rust's lint -infrastructure](reference.html#lint-check-attributes) with additional checks for +infrastructure](../reference.html#lint-check-attributes) with additional checks for code style, safety, etc. You can see [`src/test/auxiliary/lint_plugin_test.rs`](https://github.com/rust-lang/rust/blob/master/src/test/auxiliary/lint_plugin_test.rs) for a full example, the core of which is reproduced here: @@ -236,11 +235,11 @@ foo.rs:4 fn lintme() { } The components of a lint plugin are: * one or more `declare_lint!` invocations, which define static - [`Lint`](rustc/lint/struct.Lint.html) structs; + [`Lint`](../rustc/lint/struct.Lint.html) structs; * a struct holding any state needed by the lint pass (here, none); -* a [`LintPass`](rustc/lint/trait.LintPass.html) +* a [`LintPass`](../rustc/lint/trait.LintPass.html) implementation defining how to check each syntax element. A single `LintPass` may call `span_lint` for several different `Lint`s, but should register them all through the `get_lints` method. @@ -252,7 +251,7 @@ mostly use the same infrastructure as lint plugins, and provide examples of how to access type information. Lints defined by plugins are controlled by the usual [attributes and compiler -flags](reference.html#lint-check-attributes), e.g. `#[allow(test_lint)]` or +flags](../reference.html#lint-check-attributes), e.g. `#[allow(test_lint)]` or `-A test-lint`. These identifiers are derived from the first argument to `declare_lint!`, with appropriate case and punctuation conversion. diff --git a/src/doc/guide-pointers.md b/src/doc/trpl/pointers.md index 14e33ab0f74..ad80d2812d0 100644 --- a/src/doc/guide-pointers.md +++ b/src/doc/trpl/pointers.md @@ -409,7 +409,7 @@ test.rs:4 let y = &x; As you might guess, this kind of analysis is complex for a human, and therefore hard for a computer, too! There is an entire [guide devoted to references, ownership, -and lifetimes](guide-ownership.html) that goes into this topic in +and lifetimes](ownership.html) that goes into this topic in great detail, so if you want the full details, check that out. ## Best practices @@ -455,12 +455,13 @@ fn rc_succ(x: Rc<int>) -> int { *x + 1 } Note that the caller of your function will have to modify their calls slightly: ```{rust} +# use std::boxed::Box; use std::rc::Rc; fn succ(x: &int) -> int { *x + 1 } let ref_x = &5i; -let box_x = box 5i; +let box_x = Box::new(5i); let rc_x = Rc::new(5i); succ(ref_x); @@ -477,24 +478,17 @@ those contents. heap allocation in Rust. Creating a box looks like this: ```{rust} -let x = box(std::boxed::HEAP) 5i; +# use std::boxed::Box; +let x = Box::new(5i); ``` -`box` is a keyword that does 'placement new,' which we'll talk about in a bit. -`box` will be useful for creating a number of heap-allocated types, but is not -quite finished yet. In the meantime, `box`'s type defaults to -`std::boxed::HEAP`, and so you can leave it off: - -```{rust} -let x = box 5i; -``` - -As you might assume from the `HEAP`, boxes are heap allocated. They are -deallocated automatically by Rust when they go out of scope: +Boxes are heap allocated and they are deallocated automatically by Rust when +they go out of scope: ```{rust} +# use std::boxed::Box; { - let x = box 5i; + let x = Box::new(5i); // stuff happens @@ -513,8 +507,9 @@ You don't need to fully grok the theory of affine types or regions to grok boxes, though. As a rough approximation, you can treat this Rust code: ```{rust} +# use std::boxed::Box; { - let x = box 5i; + let x = Box::new(5i); // stuff happens } @@ -547,18 +542,19 @@ with some improvements: 4. Rust enforces that no other writeable pointers alias to this heap memory, which means writing to an invalid pointer is not possible. -See the section on references or the [ownership guide](guide-ownership.html) +See the section on references or the [ownership guide](ownership.html) for more detail on how lifetimes work. Using boxes and references together is very common. For example: ```{rust} +# use std::boxed::Box; fn add_one(x: &int) -> int { *x + 1 } fn main() { - let x = box 5i; + let x = Box::new(5i); println!("{}", add_one(&*x)); } @@ -570,12 +566,13 @@ function, and since it's only reading the value, allows it. We can borrow `x` multiple times, as long as it's not simultaneous: ```{rust} +# use std::boxed::Box; fn add_one(x: &int) -> int { *x + 1 } fn main() { - let x = box 5i; + let x = Box::new(5i); println!("{}", add_one(&*x)); println!("{}", add_one(&*x)); @@ -586,12 +583,13 @@ fn main() { Or as long as it's not a mutable borrow. This will error: ```{rust,ignore} +# use std::boxed::Box; fn add_one(x: &mut int) -> int { *x + 1 } fn main() { - let x = box 5i; + let x = Box::new(5i); println!("{}", add_one(&*x)); // error: cannot borrow immutable dereference // of `&`-pointer as mutable @@ -612,14 +610,15 @@ Sometimes, you need a recursive data structure. The simplest is known as a ```{rust} -#[deriving(Show)] +# use std::boxed::Box; +#[derive(Show)] enum List<T> { Cons(T, Box<List<T>>), Nil, } fn main() { - let list: List<int> = List::Cons(1, box List::Cons(2, box List::Cons(3, box List::Nil))); + let list: List<int> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Cons(3, Box::new(List::Nil)))))); println!("{:?}", list); } ``` @@ -627,7 +626,7 @@ fn main() { This prints: ```text -Cons(1, box Cons(2, box Cons(3, box Nil))) +Cons(1, Box(Cons(2, Box(Cons(3, Box(Nil)))))) ``` The reference to another `List` inside of the `Cons` enum variant must be a box, @@ -667,6 +666,7 @@ In many languages with pointers, you'd return a pointer from a function so as to avoid copying a large data structure. For example: ```{rust} +# use std::boxed::Box; struct BigStruct { one: int, two: int, @@ -675,15 +675,15 @@ struct BigStruct { } fn foo(x: Box<BigStruct>) -> Box<BigStruct> { - return box *x; + return Box::new(*x); } fn main() { - let x = box BigStruct { + let x = Box::new(BigStruct { one: 1, two: 2, one_hundred: 100, - }; + }); let y = foo(x); } @@ -695,6 +695,7 @@ than the hundred `int`s that make up the `BigStruct`. This is an antipattern in Rust. Instead, write this: ```{rust} +# use std::boxed::Box; struct BigStruct { one: int, two: int, @@ -707,13 +708,13 @@ fn foo(x: Box<BigStruct>) -> BigStruct { } fn main() { - let x = box BigStruct { + let x = Box::new(BigStruct { one: 1, two: 2, one_hundred: 100, - }; + }); - let y = box foo(x); + let y = Box::new(foo(x)); } ``` @@ -779,6 +780,6 @@ Here's a quick rundown of Rust's pointer types: # Related resources -* [API documentation for Box](std/boxed/index.html) -* [Ownership guide](guide-ownership.html) +* [API documentation for Box](../std/boxed/index.html) +* [Ownership guide](ownership.html) * [Cyclone paper on regions](http://www.cs.umd.edu/projects/cyclone/papers/cyclone-regions.pdf), which inspired Rust's lifetime system diff --git a/src/doc/trpl/rust-book.css b/src/doc/trpl/rust-book.css new file mode 100644 index 00000000000..3d08de40f55 --- /dev/null +++ b/src/doc/trpl/rust-book.css @@ -0,0 +1,59 @@ + +@import url("//static.rust-lang.org/doc/master/rust.css"); + +body { + max-width:none; +} + +#toc { + position: absolute; + left: 0px; + top: 0px; + bottom: 0px; + width: 250px; + overflow-y: auto; + border-right: 1px solid rgba(0, 0, 0, 0.07); + padding: 10px 10px; + font-size: 16px; + background: none repeat scroll 0% 0% #FFF; + box-sizing: border-box; +} + +#page-wrapper { + position: absolute; + overflow-y: auto; + left: 260px; + right: 0px; + top: 0px; + bottom: 0px; + box-sizing: border-box; + background: none repeat scroll 0% 0% #FFF; +} + +#page { + margin-left: auto; + margin-right:auto; + width: 750px; +} + +.chapter { + list-style: none outside none; + padding-left: 0px; + line-height: 30px; +} + +.section { + list-style: none outside none; + padding-left: 20px; + line-height: 30px; +} + +.section li { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.chapter li a { + color: #000000; +} diff --git a/src/doc/trpl/standard-input.md b/src/doc/trpl/standard-input.md new file mode 100644 index 00000000000..2d31f06ebaa --- /dev/null +++ b/src/doc/trpl/standard-input.md @@ -0,0 +1,159 @@ +% Standard Input + +Getting input from the keyboard is pretty easy, but uses some things +we haven't seen before. Here's a simple program that reads some input, +and then prints it back out: + +```{rust,ignore} +fn main() { + println!("Type something!"); + + let input = std::io::stdin().read_line().ok().expect("Failed to read line"); + + println!("{}", input); +} +``` + +Let's go over these chunks, one by one: + +```{rust,ignore} +std::io::stdin(); +``` + +This calls a function, `stdin()`, that lives inside the `std::io` module. As +you can imagine, everything in `std` is provided by Rust, the 'standard +library.' We'll talk more about the module system later. + +Since writing the fully qualified name all the time is annoying, we can use +the `use` statement to import it in: + +```{rust} +use std::io::stdin; + +stdin(); +``` + +However, it's considered better practice to not import individual functions, but +to import the module, and only use one level of qualification: + +```{rust} +use std::io; + +io::stdin(); +``` + +Let's update our example to use this style: + +```{rust,ignore} +use std::io; + +fn main() { + println!("Type something!"); + + let input = io::stdin().read_line().ok().expect("Failed to read line"); + + println!("{}", input); +} +``` + +Next up: + +```{rust,ignore} +.read_line() +``` + +The `read_line()` method can be called on the result of `stdin()` to return +a full line of input. Nice and easy. + +```{rust,ignore} +.ok().expect("Failed to read line"); +``` + +Do you remember this code? + +```{rust} +enum OptionalInt { + Value(i32), + Missing, +} + +fn main() { + let x = OptionalInt::Value(5); + let y = OptionalInt::Missing; + + match x { + OptionalInt::Value(n) => println!("x is {}", n), + OptionalInt::Missing => println!("x is missing!"), + } + + match y { + OptionalInt::Value(n) => println!("y is {}", n), + OptionalInt::Missing => println!("y is missing!"), + } +} +``` + +We had to match each time to see if we had a value or not. In this case, +though, we _know_ that `x` has a `Value`, but `match` forces us to handle +the `missing` case. This is what we want 99% of the time, but sometimes, we +know better than the compiler. + +Likewise, `read_line()` does not return a line of input. It _might_ return a +line of input, though it might also fail to do so. This could happen if our program +isn't running in a terminal, but as part of a cron job, or some other context +where there's no standard input. Because of this, `read_line` returns a type +very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about +`IoResult<T>` yet because it is the **generic** form of our `OptionalInt`. +Until then, you can think of it as being the same thing, just for any type – +not just `i32`s. + +Rust provides a method on these `IoResult<T>`s called `ok()`, which does the +same thing as our `match` statement but assumes that we have a valid value. +We then call `expect()` on the result, which will terminate our program if we +don't have a valid value. In this case, if we can't get input, our program +doesn't work, so we're okay with that. In most cases, we would want to handle +the error case explicitly. `expect()` allows us to give an error message if +this crash happens. + +We will cover the exact details of how all of this works later in the Guide. +For now, this gives you enough of a basic understanding to work with. + +Back to the code we were working on! Here's a refresher: + +```{rust,ignore} +use std::io; + +fn main() { + println!("Type something!"); + + let input = io::stdin().read_line().ok().expect("Failed to read line"); + + println!("{}", input); +} +``` + +With long lines like this, Rust gives you some flexibility with the whitespace. +We _could_ write the example like this: + +```{rust,ignore} +use std::io; + +fn main() { + println!("Type something!"); + + // here, we'll show the types at each step + + let input = io::stdin() // std::io::stdio::StdinReader + .read_line() // IoResult<String> + .ok() // Option<String> + .expect("Failed to read line"); // String + + println!("{}", input); +} +``` + +Sometimes, this makes things more readable – sometimes, less. Use your judgement +here. + +That's all you need to get basic input from the standard input! It's not too +complicated, but there are a number of small parts. diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md new file mode 100644 index 00000000000..a40e748dae7 --- /dev/null +++ b/src/doc/trpl/strings.md @@ -0,0 +1,79 @@ +% Strings + +Strings are an important concept for any programmer to master. Rust's string +handling system is a bit different from other languages, due to its systems +focus. Any time you have a data structure of variable size, things can get +tricky, and strings are a re-sizable data structure. That being said, Rust's +strings also work differently than in some other systems languages, such as C. + +Let's dig into the details. A **string** is a sequence of Unicode scalar values +encoded as a stream of UTF-8 bytes. All strings are guaranteed to be +validly encoded UTF-8 sequences. Additionally, strings are not null-terminated +and can contain null bytes. + +Rust has two main types of strings: `&str` and `String`. + +The first kind is a `&str`. This is pronounced a 'string slice.' String literals +are of the type `&str`: + +```{rust} +let string = "Hello there."; // string: &str +``` + +This string is statically allocated, meaning that it's saved inside our +compiled program, and exists for the entire duration it runs. The `string` +binding is a reference to this statically allocated string. String slices +have a fixed size, and cannot be mutated. + +A `String`, on the other hand, is an in-memory string. This string is +growable, and is also guaranteed to be UTF-8. + +```{rust} +let mut s = "Hello".to_string(); // mut s: String +println!("{}", s); + +s.push_str(", world."); +println!("{}", s); +``` + +You can get a `&str` view into a `String` with the `as_slice()` method: + +```{rust} +fn takes_slice(slice: &str) { + println!("Got: {}", slice); +} + +fn main() { + let s = "Hello".to_string(); + takes_slice(s.as_slice()); +} +``` + +To compare a String to a constant string, prefer `as_slice()`... + +```{rust} +fn compare(string: String) { + if string.as_slice() == "Hello" { + println!("yes"); + } +} +``` + +... over `to_string()`: + +```{rust} +fn compare(string: String) { + if string == "Hello".to_string() { + println!("yes"); + } +} +``` + +Viewing a `String` as a `&str` is cheap, but converting the `&str` to a +`String` involves allocating memory. No reason to do that unless you have to! + +That's the basics of strings in Rust! They're probably a bit more complicated +than you are used to, if you come from a scripting language, but when the +low-level details matter, they really matter. Just remember that `String`s +allocate memory and control their data, while `&str`s are a reference to +another string, and you'll be all set. diff --git a/src/doc/guide-tasks.md b/src/doc/trpl/tasks.md index 8eb13187e58..8e9f40b0f4e 100644 --- a/src/doc/guide-tasks.md +++ b/src/doc/trpl/tasks.md @@ -369,7 +369,7 @@ Unlike `spawn`, the function spawned using `try` may return a value, which child thread terminates successfully, `try` will return an `Ok` result; if the child thread panics, `try` will return an `Error` result. -[`Result`]: std/result/index.html +[`Result`]: ../std/result/index.html > *Note:* A panicked thread does not currently produce a useful error > value (`try` always returns `Err(())`). In the diff --git a/src/doc/guide-testing.md b/src/doc/trpl/testing.md index 4c3d93bdfbe..4c3d93bdfbe 100644 --- a/src/doc/guide-testing.md +++ b/src/doc/trpl/testing.md diff --git a/src/doc/trpl/traits.md b/src/doc/trpl/traits.md new file mode 100644 index 00000000000..04c644da2ab --- /dev/null +++ b/src/doc/trpl/traits.md @@ -0,0 +1,317 @@ +% Traits + +Do you remember the `impl` keyword, used to call a function with method +syntax? + +```{rust} +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } +} +``` + +Traits are similar, except that we define a trait with just the method +signature, then implement the trait for that struct. Like this: + +```{rust} +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } +} +``` + +As you can see, the `trait` block looks very similar to the `impl` block, +but we don't define a body, just a type signature. When we `impl` a trait, +we use `impl Trait for Item`, rather than just `impl Item`. + +So what's the big deal? Remember the error we were getting with our generic +`inverse` function? + +```text +error: binary operation `==` cannot be applied to type `T` +``` + +We can use traits to constrain our generics. Consider this function, which +does not compile, and gives us a similar error: + +```{rust,ignore} +fn print_area<T>(shape: T) { + println!("This shape has an area of {}", shape.area()); +} +``` + +Rust complains: + +```text +error: type `T` does not implement any method in scope named `area` +``` + +Because `T` can be any type, we can't be sure that it implements the `area` +method. But we can add a **trait constraint** to our generic `T`, ensuring +that it does: + +```{rust} +# trait HasArea { +# fn area(&self) -> f64; +# } +fn print_area<T: HasArea>(shape: T) { + println!("This shape has an area of {}", shape.area()); +} +``` + +The syntax `<T: HasArea>` means `any type that implements the HasArea trait`. +Because traits define function type signatures, we can be sure that any type +which implements `HasArea` will have an `.area()` method. + +Here's an extended example of how this works: + +```{rust} +trait HasArea { + fn area(&self) -> f64; +} + +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } +} + +struct Square { + x: f64, + y: f64, + side: f64, +} + +impl HasArea for Square { + fn area(&self) -> f64 { + self.side * self.side + } +} + +fn print_area<T: HasArea>(shape: T) { + println!("This shape has an area of {}", shape.area()); +} + +fn main() { + let c = Circle { + x: 0.0f64, + y: 0.0f64, + radius: 1.0f64, + }; + + let s = Square { + x: 0.0f64, + y: 0.0f64, + side: 1.0f64, + }; + + print_area(c); + print_area(s); +} +``` + +This program outputs: + +```text +This shape has an area of 3.141593 +This shape has an area of 1 +``` + +As you can see, `print_area` is now generic, but also ensures that we +have passed in the correct types. If we pass in an incorrect type: + +```{rust,ignore} +print_area(5i); +``` + +We get a compile-time error: + +```text +error: failed to find an implementation of trait main::HasArea for int +``` + +So far, we've only added trait implementations to structs, but you can +implement a trait for any type. So technically, we _could_ implement +`HasArea` for `int`: + +```{rust} +trait HasArea { + fn area(&self) -> f64; +} + +impl HasArea for int { + fn area(&self) -> f64 { + println!("this is silly"); + + *self as f64 + } +} + +5i.area(); +``` + +It is considered poor style to implement methods on such primitive types, even +though it is possible. + +This may seem like the Wild West, but there are two other restrictions around +implementing traits that prevent this from getting out of hand. First, traits +must be `use`d in any scope where you wish to use the trait's method. So for +example, this does not work: + +```{rust,ignore} +mod shapes { + use std::f64::consts; + + trait HasArea { + fn area(&self) -> f64; + } + + struct Circle { + x: f64, + y: f64, + radius: f64, + } + + impl HasArea for Circle { + fn area(&self) -> f64 { + consts::PI * (self.radius * self.radius) + } + } +} + +fn main() { + let c = shapes::Circle { + x: 0.0f64, + y: 0.0f64, + radius: 1.0f64, + }; + + println!("{}", c.area()); +} +``` + +Now that we've moved the structs and traits into their own module, we get an +error: + +```text +error: type `shapes::Circle` does not implement any method in scope named `area` +``` + +If we add a `use` line right above `main` and make the right things public, +everything is fine: + +```{rust} +use shapes::HasArea; + +mod shapes { + use std::f64::consts; + + pub trait HasArea { + fn area(&self) -> f64; + } + + pub struct Circle { + pub x: f64, + pub y: f64, + pub radius: f64, + } + + impl HasArea for Circle { + fn area(&self) -> f64 { + consts::PI * (self.radius * self.radius) + } + } +} + + +fn main() { + let c = shapes::Circle { + x: 0.0f64, + y: 0.0f64, + radius: 1.0f64, + }; + + println!("{}", c.area()); +} +``` + +This means that even if someone does something bad like add methods to `int`, +it won't affect you, unless you `use` that trait. + +There's one more restriction on implementing traits. Either the trait or the +type you're writing the `impl` for must be inside your crate. So, we could +implement the `HasArea` type for `int`, because `HasArea` is in our crate. But +if we tried to implement `Float`, a trait provided by Rust, for `int`, we could +not, because both the trait and the type aren't in our crate. + +One last thing about traits: generic functions with a trait bound use +**monomorphization** ("mono": one, "morph": form), so they are statically +dispatched. What's that mean? Well, let's take a look at `print_area` again: + +```{rust,ignore} +fn print_area<T: HasArea>(shape: T) { + println!("This shape has an area of {}", shape.area()); +} + +fn main() { + let c = Circle { ... }; + + let s = Square { ... }; + + print_area(c); + print_area(s); +} +``` + +When we use this trait with `Circle` and `Square`, Rust ends up generating +two different functions with the concrete type, and replacing the call sites with +calls to the concrete implementations. In other words, you get something like +this: + +```{rust,ignore} +fn __print_area_circle(shape: Circle) { + println!("This shape has an area of {}", shape.area()); +} + +fn __print_area_square(shape: Square) { + println!("This shape has an area of {}", shape.area()); +} + +fn main() { + let c = Circle { ... }; + + let s = Square { ... }; + + __print_area_circle(c); + __print_area_square(s); +} +``` + +The names don't actually change to this, it's just for illustration. But +as you can see, there's no overhead of deciding which version to call here, +hence 'statically dispatched.' The downside is that we have two copies of +the same function, so our binary is a little bit larger. diff --git a/src/doc/guide-unsafe.md b/src/doc/trpl/unsafe.md index 11bc0bc30f2..3e0a1ef1345 100644 --- a/src/doc/guide-unsafe.md +++ b/src/doc/trpl/unsafe.md @@ -12,7 +12,7 @@ block which allows the programmer to dodge some of the compiler's checks and do a wide range of operations, such as: - dereferencing [raw pointers](#raw-pointers) -- calling a function via FFI ([covered by the FFI guide](guide-ffi.html)) +- calling a function via FFI ([covered by the FFI guide](ffi.html)) - casting between types bitwise (`transmute`, aka "reinterpret cast") - [inline assembly](#inline-assembly) @@ -37,7 +37,7 @@ build safe interfaces. ## References One of Rust's biggest features is memory safety. This is achieved in -part via [the ownership system](guide-ownership.html), which is how the +part via [the ownership system](ownership.html), which is how the compiler can guarantee that every `&` reference is always valid, and, for example, never pointing to freed memory. @@ -197,6 +197,7 @@ extern crate libc; use libc::{c_void, size_t, malloc, free}; use std::mem; use std::ptr; +# use std::boxed::Box; // Define a wrapper around the handle returned by the foreign code. // Unique<T> has the same semantics as Box<T> @@ -265,7 +266,7 @@ impl<T: Send> Drop for Unique<T> { // A comparison between the built-in `Box` and this reimplementation fn main() { { - let mut x = box 5i; + let mut x = Box::new(5i); *x = 10; } // `x` is freed here @@ -503,7 +504,7 @@ shouldn't get triggered. The second of these three functions, `eh_personality`, is used by the failure mechanisms of the compiler. This is often mapped to GCC's personality function (see the -[libstd implementation](std/rt/unwind/index.html) for more +[libstd implementation](../std/rt/unwind/index.html) for more information), but crates which do not trigger a panic can be assured that this function is never called. The final function, `panic_fmt`, is also used by the failure mechanisms of the compiler. @@ -516,7 +517,7 @@ also used by the failure mechanisms of the compiler. With the above techniques, we've got a bare-metal executable running some Rust code. There is a good deal of functionality provided by the standard library, however, that is necessary to be productive in Rust. If the standard library is -not sufficient, then [libcore](core/index.html) is designed to be used +not sufficient, then [libcore](../core/index.html) is designed to be used instead. The core library has very few dependencies and is much more portable than the @@ -653,7 +654,7 @@ sugar for dynamic allocations via `malloc` and `free`: ``` #![no_std] -#![feature(lang_items)] +#![feature(lang_items, box_syntax)] extern crate libc; diff --git a/src/doc/trpl/variable-bindings.md b/src/doc/trpl/variable-bindings.md new file mode 100644 index 00000000000..4e2e7bd2fe2 --- /dev/null +++ b/src/doc/trpl/variable-bindings.md @@ -0,0 +1,174 @@ +% Variable bindings + +The first thing we'll learn about are 'variable bindings.' They look like this: + +```{rust} +fn main() { + let x = 5; +} +``` + +Putting `fn main() {` in each example is a bit tedious, so we'll leave that out +in the future. If you're following along, make sure to edit your `main()` +function, rather than leaving it off. Otherwise, you'll get an error. + +In many languages, this is called a 'variable.' But Rust's variable bindings +have a few tricks up their sleeves. Rust has a very powerful feature called +'pattern matching' that we'll get into detail with later, but the left +hand side of a `let` expression is a full pattern, not just a variable name. +This means we can do things like: + +```{rust} +let (x, y) = (1, 2); +``` + +After this expression is evaluated, `x` will be one, and `y` will be two. +Patterns are really powerful, but this is about all we can do with them so far. +So let's just keep this in the back of our minds as we go forward. + +Rust is a statically typed language, which means that we specify our types up +front. So why does our first example compile? Well, Rust has this thing called +"type inference." If it can figure out what the type of something is, Rust +doesn't require you to actually type it out. + +We can add the type if we want to, though. Types come after a colon (`:`): + +```{rust} +let x: i32 = 5; +``` + +If I asked you to read this out loud to the rest of the class, you'd say "`x` +is a binding with the type `i32` and the value `five`." + +In future examples, we may annotate the type in a comment. The examples will +look like this: + +```{rust} +fn main() { + let x = 5; // x: i32 +} +``` + +Note the similarities between this annotation and the syntax you use with `let`. +Including these kinds of comments is not idiomatic Rust, but we'll occasionally +include them to help you understand what the types that Rust infers are. + +By default, bindings are **immutable**. This code will not compile: + +```{ignore} +let x = 5; +x = 10; +``` + +It will give you this error: + +```text +error: re-assignment of immutable variable `x` + x = 10; + ^~~~~~~ +``` + +If you want a binding to be mutable, you can use `mut`: + +```{rust} +let mut x = 5; // mut x: i32 +x = 10; +``` + +There is no single reason that bindings are immutable by default, but we can +think about it through one of Rust's primary focuses: safety. If you forget to +say `mut`, the compiler will catch it, and let you know that you have mutated +something you may not have intended to mutate. If bindings were mutable by +default, the compiler would not be able to tell you this. If you _did_ intend +mutation, then the solution is quite easy: add `mut`. + +There are other good reasons to avoid mutable state when possible, but they're +out of the scope of this guide. In general, you can often avoid explicit +mutation, and so it is preferable in Rust. That said, sometimes, mutation is +what you need, so it's not verboten. + +Let's get back to bindings. Rust variable bindings have one more aspect that +differs from other languages: bindings are required to be initialized with a +value before you're allowed to use them. If we try... + +```{ignore} +let x; +``` + +...we'll get an error: + +```text +src/main.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type +src/main.rs:2 let x; + ^ +``` + +Giving it a type will compile, though: + +```{rust} +let x: i32; +``` + +Let's try it out. Change your `src/main.rs` file to look like this: + +```{rust} +fn main() { + let x: i32; + + println!("Hello world!"); +} +``` + +You can use `cargo build` on the command line to build it. You'll get a warning, +but it will still print "Hello, world!": + +```text + Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) +src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default +src/main.rs:2 let x: i32; + ^ +``` + +Rust warns us that we never use the variable binding, but since we never use it, +no harm, no foul. Things change if we try to actually use this `x`, however. Let's +do that. Change your program to look like this: + +```{rust,ignore} +fn main() { + let x: i32; + + println!("The value of x is: {}", x); +} +``` + +And try to build it. You'll get an error: + +```{bash} +$ cargo build + Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world) +src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` +src/main.rs:4 println!("The value of x is: {}", x); + ^ +note: in expansion of format_args! +<std macros>:2:23: 2:77 note: expansion site +<std macros>:1:1: 3:2 note: in expansion of println! +src/main.rs:4:5: 4:42 note: expansion site +error: aborting due to previous error +Could not compile `hello_world`. +``` + +Rust will not let us use a value that has not been initialized. Next, let's +talk about this stuff we've added to `println!`. + +If you include two curly braces (`{}`, some call them moustaches...) in your +string to print, Rust will interpret this as a request to interpolate some sort +of value. **String interpolation** is a computer science term that means "stick +in the middle of a string." We add a comma, and then `x`, to indicate that we +want `x` to be the value we're interpolating. The comma is used to separate +arguments we pass to functions and macros, if you're passing more than one. + +When you just use the curly braces, Rust will attempt to display the +value in a meaningful way by checking out its type. If you want to specify the +format in a more detailed manner, there are a [wide number of options +available](../std/fmt/index.html). For now, we'll just stick to the default: +integers aren't very complicated to print. diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 5d47602b5e1..290dd21d666 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -67,21 +67,20 @@ //! } //! ``` +use core::prelude::*; + use core::atomic; use core::atomic::Ordering::{Relaxed, Release, Acquire, SeqCst}; use core::borrow::BorrowFrom; -use core::clone::Clone; use core::fmt::{self, Show}; -use core::cmp::{Eq, Ord, PartialEq, PartialOrd, Ordering}; +use core::cmp::{Ordering}; use core::default::Default; -use core::marker::{Sync, Send}; -use core::mem::{min_align_of, size_of, drop}; +use core::mem::{min_align_of, size_of}; use core::mem; use core::nonzero::NonZero; -use core::ops::{Drop, Deref}; -use core::option::Option; -use core::option::Option::{Some, None}; -use core::ptr::{self, PtrExt}; +use core::ops::Deref; +use core::ptr; +use core::hash::{Hash, Hasher}; use heap::deallocate; /// An atomically reference counted wrapper for shared state. @@ -127,7 +126,7 @@ unsafe impl<T: Sync + Send> Sync for Arc<T> { } /// Weak pointers will not keep the data inside of the `Arc` alive, and can be used to break cycles /// between `Arc` pointers. #[unsafe_no_drop_flag] -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] pub struct Weak<T> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref @@ -180,7 +179,7 @@ impl<T> Arc<T> { /// /// let weak_five = five.downgrade(); /// ``` - #[experimental = "Weak pointers may not belong in this module."] + #[unstable = "Weak pointers may not belong in this module."] pub fn downgrade(&self) -> Weak<T> { // See the clone() impl for why this is relaxed self.inner().weak.fetch_add(1, Relaxed); @@ -201,12 +200,12 @@ impl<T> Arc<T> { /// Get the number of weak references to this value. #[inline] -#[experimental] +#[unstable] pub fn weak_count<T>(this: &Arc<T>) -> uint { this.inner().weak.load(SeqCst) - 1 } /// Get the number of strong references to this value. #[inline] -#[experimental] +#[unstable] pub fn strong_count<T>(this: &Arc<T>) -> uint { this.inner().strong.load(SeqCst) } #[stable] @@ -272,7 +271,7 @@ impl<T: Send + Sync + Clone> Arc<T> { /// let mut_five = five.make_unique(); /// ``` #[inline] - #[experimental] + #[unstable] pub fn make_unique(&mut self) -> &mut T { // Note that we hold a strong reference, which also counts as a weak reference, so we only // clone if there is an additional reference of either kind. @@ -356,7 +355,7 @@ impl<T: Sync + Send> Drop for Arc<T> { } } -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] impl<T: Sync + Send> Weak<T> { /// Upgrades a weak reference to a strong reference. /// @@ -394,7 +393,7 @@ impl<T: Sync + Send> Weak<T> { } } -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] impl<T: Sync + Send> Clone for Weak<T> { /// Makes a clone of the `Weak<T>`. /// @@ -586,13 +585,26 @@ impl<T: fmt::Show> fmt::Show for Arc<T> { } #[stable] +impl<T: fmt::String> fmt::String for Arc<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&**self, f) + } +} + +#[stable] impl<T: Default + Sync + Send> Default for Arc<T> { #[stable] fn default() -> Arc<T> { Arc::new(Default::default()) } } +impl<H: Hasher, T: Hash<H>> Hash<H> for Arc<T> { + fn hash(&self, state: &mut H) { + (**self).hash(state) + } +} + #[cfg(test)] -#[allow(experimental)] +#[allow(unstable)] mod tests { use std::clone::Clone; use std::sync::mpsc::channel; diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index d46f18abf97..458eb3dce57 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -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. // @@ -33,15 +33,18 @@ use core::ops::{Deref, DerefMut}; /// The following two examples are equivalent: /// /// ```rust +/// #![feature(box_syntax)] /// use std::boxed::HEAP; /// +/// fn main() { /// # struct Bar; /// # impl Bar { fn new(_a: int) { } } -/// let foo = box(HEAP) Bar::new(2); -/// let foo = box Bar::new(2); +/// let foo = box(HEAP) Bar::new(2); +/// let foo = box Bar::new(2); +/// } /// ``` #[lang = "exchange_heap"] -#[experimental = "may be renamed; uncertain about custom allocator design"] +#[unstable = "may be renamed; uncertain about custom allocator design"] pub static HEAP: () = (); /// A type that represents a uniquely-owned value. @@ -49,6 +52,14 @@ pub static HEAP: () = (); #[stable] pub struct Box<T>(Unique<T>); +impl<T> Box<T> { + /// Moves `x` into a freshly allocated box on the global exchange heap. + #[stable] + pub fn new(x: T) -> Box<T> { + box x + } +} + #[stable] impl<T: Default> Default for Box<T> { #[stable] @@ -102,16 +113,24 @@ impl<T: ?Sized + Ord> Ord for Box<T> { fn cmp(&self, other: &Box<T>) -> Ordering { Ord::cmp(&**self, &**other) } - -#[stable]} +} +#[stable] impl<T: ?Sized + Eq> Eq for Box<T> {} +#[cfg(stage0)] impl<S: hash::Writer, T: ?Sized + Hash<S>> Hash<S> for Box<T> { #[inline] fn hash(&self, state: &mut S) { (**self).hash(state); } } +#[cfg(not(stage0))] +impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); + } +} /// Extension methods for an owning `Any` trait object. #[unstable = "post-DST and coherence changes, this will not be a trait but \ @@ -149,6 +168,7 @@ impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> { } } +#[stable] impl<T: ?Sized + fmt::String> fmt::String for Box<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(&**self, f) @@ -177,27 +197,27 @@ impl<T: ?Sized> DerefMut for Box<T> { mod test { #[test] fn test_owned_clone() { - let a = box 5i; + let a = Box::new(5i); let b: Box<int> = a.clone(); assert!(a == b); } #[test] fn any_move() { - let a = box 8u as Box<Any>; - let b = box Test as Box<Any>; + let a = Box::new(8u) as Box<Any>; + let b = Box::new(Test) as Box<Any>; match a.downcast::<uint>() { - Ok(a) => { assert!(a == box 8u); } + Ok(a) => { assert!(a == Box::new(8u)); } Err(..) => panic!() } match b.downcast::<Test>() { - Ok(a) => { assert!(a == box Test); } + Ok(a) => { assert!(a == Box::new(Test)); } Err(..) => panic!() } - let a = box 8u as Box<Any>; - let b = box Test as Box<Any>; + let a = Box::new(8u) as Box<Any>; + let b = Box::new(Test) as Box<Any>; assert!(a.downcast::<Box<Test>>().is_err()); assert!(b.downcast::<Box<uint>>().is_err()); @@ -205,8 +225,8 @@ mod test { #[test] fn test_show() { - let a = box 8u as Box<Any>; - let b = box Test as Box<Any>; + let a = Box::new(8u) as Box<Any>; + let b = Box::new(Test) as Box<Any>; let a_str = a.to_str(); let b_str = b.to_str(); assert_eq!(a_str, "Box<Any>"); @@ -223,6 +243,6 @@ mod test { #[test] fn deref() { fn homura<T: Deref<Target=i32>>(_: T) { } - homura(box 765i32); + homura(Box::new(765i32)); } } diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index c57435cdc8c..02933c763ef 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -115,16 +115,20 @@ unsafe fn exchange_free(ptr: *mut u8, old_size: uint, align: uint) { // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. In practice, the alignment is a // constant at the call site and the branch will be optimized out. -#[cfg(any(target_arch = "arm", - target_arch = "mips", - target_arch = "mipsel"))] +#[cfg(all(not(feature = "external_funcs"), + not(feature = "external_crate"), + any(target_arch = "arm", + target_arch = "mips", + target_arch = "mipsel")))] const MIN_ALIGN: uint = 8; -#[cfg(any(target_arch = "x86", - target_arch = "x86_64", - target_arch = "aarch64"))] +#[cfg(all(not(feature = "external_funcs"), + not(feature = "external_crate"), + any(target_arch = "x86", + target_arch = "x86_64", + target_arch = "aarch64")))] const MIN_ALIGN: uint = 16; -#[cfg(external_funcs)] +#[cfg(feature = "external_funcs")] mod imp { extern { fn rust_allocate(size: uint, align: uint) -> *mut u8; @@ -142,14 +146,13 @@ mod imp { } #[inline] - pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: uint, size: uint, - align: uint) -> uint { - rust_reallocate_inplace(ptr, old_size, size, align) + pub unsafe fn deallocate(ptr: *mut u8, old_size: uint, align: uint) { + rust_deallocate(ptr, old_size, align) } #[inline] - pub unsafe fn deallocate(ptr: *mut u8, old_size: uint, align: uint) { - rust_deallocate(ptr, old_size, align) + pub unsafe fn reallocate(ptr: *mut u8, old_size: uint, size: uint, align: uint) -> *mut u8 { + rust_reallocate(ptr, old_size, size, align) } #[inline] @@ -169,14 +172,16 @@ mod imp { } } -#[cfg(external_crate)] +#[cfg(feature = "external_crate")] mod imp { extern crate external; pub use self::external::{allocate, deallocate, reallocate_inplace, reallocate}; pub use self::external::{usable_size, stats_print}; } -#[cfg(all(not(external_funcs), not(external_crate), jemalloc))] +#[cfg(all(not(feature = "external_funcs"), + not(feature = "external_crate"), + jemalloc))] mod imp { use core::option::Option; use core::option::Option::None; @@ -253,7 +258,10 @@ mod imp { } } -#[cfg(all(not(external_funcs), not(external_crate), not(jemalloc), unix))] +#[cfg(all(not(feature = "external_funcs"), + not(feature = "external_crate"), + not(jemalloc), + unix))] mod imp { use core::cmp; use core::ptr; @@ -314,7 +322,10 @@ mod imp { pub fn stats_print() {} } -#[cfg(all(not(external_funcs), not(external_crate), not(jemalloc), windows))] +#[cfg(all(not(feature = "external_funcs"), + not(feature = "external_crate"), + not(jemalloc), + windows))] mod imp { use libc::{c_void, size_t}; use libc; diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index ba6e89cdd76..4a85637625a 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -57,7 +57,8 @@ //! default global allocator. It is not compatible with the libc allocator API. #![crate_name = "alloc"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", @@ -66,9 +67,13 @@ #![no_std] #![allow(unknown_features)] #![feature(lang_items, unsafe_destructor)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #[macro_use] extern crate core; + +#[cfg(all(not(feature = "external_funcs"), not(feature = "external_crate")))] extern crate libc; // Allow testing this library diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 67b25427710..f42c6dbdc15 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -10,23 +10,26 @@ //! Thread-local reference-counted boxes (the `Rc<T>` type). //! -//! The `Rc<T>` type provides shared ownership of an immutable value. Destruction is deterministic, -//! and will occur as soon as the last owner is gone. It is marked as non-sendable because it -//! avoids the overhead of atomic reference counting. +//! The `Rc<T>` type provides shared ownership of an immutable value. +//! Destruction is deterministic, and will occur as soon as the last owner is +//! gone. It is marked as non-sendable because it avoids the overhead of atomic +//! reference counting. //! -//! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer to the box. A -//! `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but will return `None` if the value -//! has already been dropped. +//! The `downgrade` method can be used to create a non-owning `Weak<T>` pointer +//! to the box. A `Weak<T>` pointer can be upgraded to an `Rc<T>` pointer, but +//! will return `None` if the value has already been dropped. //! -//! For example, a tree with parent pointers can be represented by putting the nodes behind strong -//! `Rc<T>` pointers, and then storing the parent pointers as `Weak<T>` pointers. +//! For example, a tree with parent pointers can be represented by putting the +//! nodes behind strong `Rc<T>` pointers, and then storing the parent pointers +//! as `Weak<T>` pointers. //! //! # Examples //! -//! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. We want to have our -//! `Gadget`s point to their `Owner`. We can't do this with unique ownership, because more than one -//! gadget may belong to the same `Owner`. `Rc<T>` allows us to share an `Owner` between multiple -//! `Gadget`s, and have the `Owner` remain allocated as long as any `Gadget` points at it. +//! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`. +//! We want to have our `Gadget`s point to their `Owner`. We can't do this with +//! unique ownership, because more than one gadget may belong to the same +//! `Owner`. `Rc<T>` allows us to share an `Owner` between multiple `Gadget`s, +//! and have the `Owner` remain allocated as long as any `Gadget` points at it. //! //! ```rust //! use std::rc::Rc; @@ -218,7 +221,7 @@ impl<T> Rc<T> { /// /// let weak_five = five.downgrade(); /// ``` - #[experimental = "Weak pointers may not belong in this module"] + #[unstable = "Weak pointers may not belong in this module"] pub fn downgrade(&self) -> Weak<T> { self.inc_weak(); Weak { @@ -231,12 +234,12 @@ impl<T> Rc<T> { /// Get the number of weak references to this value. #[inline] -#[experimental] +#[unstable] pub fn weak_count<T>(this: &Rc<T>) -> uint { this.weak() - 1 } /// Get the number of strong references to this value. #[inline] -#[experimental] +#[unstable] pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() } /// Returns true if there are no other `Rc` or `Weak<T>` values that share the same inner value. @@ -252,7 +255,7 @@ pub fn strong_count<T>(this: &Rc<T>) -> uint { this.strong() } /// rc::is_unique(&five); /// ``` #[inline] -#[experimental] +#[unstable] pub fn is_unique<T>(rc: &Rc<T>) -> bool { weak_count(rc) == 0 && strong_count(rc) == 1 } @@ -274,7 +277,7 @@ pub fn is_unique<T>(rc: &Rc<T>) -> bool { /// assert_eq!(rc::try_unwrap(x), Err(Rc::new(4u))); /// ``` #[inline] -#[experimental] +#[unstable] pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> { if is_unique(&rc) { unsafe { @@ -308,7 +311,7 @@ pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> { /// assert!(rc::get_mut(&mut x).is_none()); /// ``` #[inline] -#[experimental] +#[unstable] pub fn get_mut<'a, T>(rc: &'a mut Rc<T>) -> Option<&'a mut T> { if is_unique(rc) { let inner = unsafe { &mut **rc._ptr }; @@ -334,7 +337,7 @@ impl<T: Clone> Rc<T> { /// let mut_five = five.make_unique(); /// ``` #[inline] - #[experimental] + #[unstable] pub fn make_unique(&mut self) -> &mut T { if !is_unique(self) { *self = Rc::new((**self).clone()) @@ -597,27 +600,42 @@ impl<T: Ord> Ord for Rc<T> { } // FIXME (#18248) Make `T` `Sized?` +#[cfg(stage0)] impl<S: hash::Writer, T: Hash<S>> Hash<S> for Rc<T> { #[inline] fn hash(&self, state: &mut S) { (**self).hash(state); } } +#[cfg(not(stage0))] +impl<S: hash::Hasher, T: Hash<S>> Hash<S> for Rc<T> { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); + } +} -#[experimental = "Show is experimental."] +#[unstable = "Show is experimental."] impl<T: fmt::Show> fmt::Show for Rc<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Rc({:?})", **self) } } +#[stable] +impl<T: fmt::String> fmt::String for Rc<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&**self, f) + } +} + /// A weak version of `Rc<T>`. /// /// Weak references do not count when determining if the inner value should be dropped. /// /// See the [module level documentation](../index.html) for more. #[unsafe_no_drop_flag] -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] pub struct Weak<T> { // FIXME #12808: strange names to try to avoid interfering with // field accesses of the contained type via Deref @@ -626,7 +644,7 @@ pub struct Weak<T> { _noshare: marker::NoSync } -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] impl<T> Weak<T> { /// Upgrades a weak reference to a strong reference. /// @@ -699,7 +717,7 @@ impl<T> Drop for Weak<T> { } } -#[experimental = "Weak pointers may not belong in this module."] +#[unstable = "Weak pointers may not belong in this module."] impl<T> Clone for Weak<T> { /// Makes a clone of the `Weak<T>`. /// @@ -721,7 +739,7 @@ impl<T> Clone for Weak<T> { } } -#[experimental = "Show is experimental."] +#[unstable = "Show is experimental."] impl<T: fmt::Show> fmt::Show for Weak<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(Weak)") @@ -762,7 +780,7 @@ impl<T> RcBoxPtr<T> for Weak<T> { } #[cfg(test)] -#[allow(experimental)] +#[allow(unstable)] mod tests { use super::{Rc, Weak, weak_count, strong_count}; use std::cell::RefCell; diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 423c16bfee8..e3d075c0f39 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -20,15 +20,19 @@ //! more complex, slower arena which can hold objects of any type. #![crate_name = "arena"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(unsafe_destructor)] #![feature(unboxed_closures)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![allow(missing_docs)] extern crate alloc; diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index 2154d06377a..c1b34c52fcc 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -134,7 +134,7 @@ static FALSE: bool = false; /// # Examples /// /// ```rust -/// use collections::Bitv; +/// use std::collections::Bitv; /// /// let mut bv = Bitv::from_elem(10, false); /// @@ -330,7 +330,7 @@ impl Bitv { if extra_bytes > 0 { let mut last_word = 0u32; - for (i, &byte) in bytes.index(&((complete_words*4)..)).iter().enumerate() { + for (i, &byte) in bytes[(complete_words*4)..].iter().enumerate() { last_word |= (reverse_bits(byte) as u32) << (i * 8); } bitv.storage.push(last_word); @@ -982,7 +982,7 @@ impl fmt::Show for Bitv { } #[stable] -impl<S: hash::Writer> hash::Hash<S> for Bitv { +impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Bitv { fn hash(&self, state: &mut S) { self.nbits.hash(state); for elem in self.blocks() { @@ -1742,7 +1742,7 @@ impl fmt::Show for BitvSet { } } -impl<S: hash::Writer> hash::Hash<S> for BitvSet { +impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for BitvSet { fn hash(&self, state: &mut S) { for pos in self.iter() { pos.hash(state); diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 4e44779810b..3e1533dd35f 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -23,7 +23,9 @@ use core::borrow::BorrowFrom; use core::cmp::Ordering; use core::default::Default; use core::fmt::Show; -use core::hash::{Writer, Hash}; +use core::hash::{Hash, Hasher}; +#[cfg(stage0)] +use core::hash::Writer; use core::iter::{Map, FromIterator}; use core::ops::{Index, IndexMut}; use core::{iter, fmt, mem}; @@ -820,6 +822,7 @@ impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> { } #[stable] +#[cfg(stage0)] impl<S: Writer, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> { fn hash(&self, state: &mut S) { for elt in self.iter() { @@ -827,6 +830,15 @@ impl<S: Writer, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> { } } } +#[stable] +#[cfg(not(stage0))] +impl<S: Hasher, K: Hash<S>, V: Hash<S>> Hash<S> for BTreeMap<K, V> { + fn hash(&self, state: &mut S) { + for elt in self.iter() { + elt.hash(state); + } + } +} #[stable] impl<K: Ord, V> Default for BTreeMap<K, V> { diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 25df4a3cc2a..812cff6fab7 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -678,7 +678,7 @@ mod test { use prelude::*; use super::BTreeSet; - use std::hash; + use std::hash::{self, SipHasher}; #[test] fn test_clone_eq() { @@ -703,7 +703,7 @@ mod test { y.insert(2); y.insert(1); - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y)); } struct Counter<'a, 'b> { diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 63ea9f7cb43..0b426f6016c 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -27,7 +27,7 @@ use alloc::boxed::Box; use core::cmp::Ordering; use core::default::Default; use core::fmt; -use core::hash::{Writer, Hash}; +use core::hash::{Writer, Hasher, Hash}; use core::iter::{self, FromIterator}; use core::mem; use core::ptr; @@ -675,7 +675,7 @@ impl<A: fmt::Show> fmt::Show for DList<A> { } #[stable] -impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> { +impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for DList<A> { fn hash(&self, state: &mut S) { self.len().hash(state); for elt in self.iter() { @@ -688,7 +688,7 @@ impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> { mod tests { use prelude::*; use std::rand; - use std::hash; + use std::hash::{self, SipHasher}; use std::thread::Thread; use test::Bencher; use test; @@ -951,7 +951,7 @@ mod tests { let mut x = DList::new(); let mut y = DList::new(); - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y)); x.push_back(1i); x.push_back(2); @@ -961,7 +961,7 @@ mod tests { y.push_front(2); y.push_front(1); - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y)); } #[test] diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 6eab36d8844..54ab26c4f77 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -14,7 +14,8 @@ #![crate_name = "collections"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", @@ -23,8 +24,10 @@ #![allow(unknown_features)] #![feature(unsafe_destructor, slicing_syntax)] -#![feature(old_impl_check)] +#![feature(box_syntax)] #![feature(unboxed_closures)] +#![feature(old_impl_check)] +#![allow(unknown_features)] #![feature(int_uint)] #![no_std] #[macro_use] @@ -101,8 +104,6 @@ mod std { pub use core::option; // necessary for panic!() pub use core::clone; // deriving(Clone) pub use core::cmp; // deriving(Eq, Ord, etc.) - #[cfg(stage0)] - pub use core::marker as kinds; pub use core::marker; // deriving(Copy) pub use core::hash; // deriving(Hash) } diff --git a/src/libcollections/macros.rs b/src/libcollections/macros.rs index 68e2482964d..0ff869d6183 100644 --- a/src/libcollections/macros.rs +++ b/src/libcollections/macros.rs @@ -10,9 +10,10 @@ /// Creates a `Vec` containing the arguments. #[macro_export] +#[stable] macro_rules! vec { ($($x:expr),*) => ({ - let xs: $crate::boxed::Box<[_]> = box [$($x),*]; + let xs: $crate::boxed::Box<[_]> = $crate::boxed::Box::new([$($x),*]); $crate::slice::SliceExt::into_vec(xs) }); ($($x:expr,)*) => (vec![$($x),*]) diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 42c17136a08..c3d22675868 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -27,7 +27,7 @@ use core::ops::{Index, IndexMut}; use core::ptr; use core::raw::Slice as RawSlice; -use std::hash::{Writer, Hash}; +use std::hash::{Writer, Hash, Hasher}; use std::cmp; use alloc::heap; @@ -556,7 +556,7 @@ impl<T> RingBuf<T> { let buf = self.buffer_as_slice(); if contiguous { let (empty, buf) = buf.split_at(0); - (buf.index(&(self.tail..self.head)), empty) + (&buf[self.tail..self.head], empty) } else { let (mid, right) = buf.split_at(self.tail); let (left, _) = mid.split_at(self.head); @@ -1562,7 +1562,7 @@ impl<A: Ord> Ord for RingBuf<A> { } #[stable] -impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> { +impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for RingBuf<A> { fn hash(&self, state: &mut S) { self.len().hash(state); for elt in self.iter() { @@ -1631,7 +1631,7 @@ mod tests { use prelude::*; use core::iter; use std::fmt::Show; - use std::hash; + use std::hash::{self, SipHasher}; use test::Bencher; use test; @@ -2283,7 +2283,7 @@ mod tests { y.push_back(2); y.push_back(3); - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y)); } #[test] diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 61309f0cc0f..9a1f22ef7a6 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -55,7 +55,7 @@ //! #![feature(slicing_syntax)] //! fn main() { //! let numbers = [0i, 1i, 2i]; -//! let last_numbers = numbers.index(&(1..3)); +//! let last_numbers = &numbers[1..3]; //! // last_numbers is now &[1i, 2i] //! } //! ``` @@ -98,7 +98,7 @@ use core::iter::{range, range_step, MultiplicativeIterator}; use core::marker::Sized; use core::mem::size_of; use core::mem; -use core::ops::{FnMut, FullRange, Index, IndexMut}; +use core::ops::{FnMut, FullRange}; use core::option::Option::{self, Some, None}; use core::ptr::PtrExt; use core::ptr; @@ -166,7 +166,7 @@ pub trait SliceExt { /// assert_eq!(num_moved, 3); /// assert!(a == [6i, 7, 8, 4, 5]); /// ``` - #[experimental = "uncertain about this API approach"] + #[unstable = "uncertain about this API approach"] fn move_from(&mut self, src: Vec<Self::Item>, start: uint, end: uint) -> uint; /// Returns a subslice spanning the interval [`start`, `end`). @@ -175,7 +175,7 @@ pub trait SliceExt { /// original slice (i.e. when `end > self.len()`) or when `start > end`. /// /// Slicing with `start` equal to `end` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice(&self, start: uint, end: uint) -> &[Self::Item]; /// Returns a subslice from `start` to the end of the slice. @@ -183,7 +183,7 @@ pub trait SliceExt { /// Panics when `start` is strictly greater than the length of the original slice. /// /// Slicing from `self.len()` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice_from(&self, start: uint) -> &[Self::Item]; /// Returns a subslice from the start of the slice to `end`. @@ -191,7 +191,7 @@ pub trait SliceExt { /// Panics when `end` is strictly greater than the length of the original slice. /// /// Slicing to `0` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice_to(&self, end: uint) -> &[Self::Item]; /// Divides one slice into two at an index. @@ -245,7 +245,7 @@ pub trait SliceExt { /// ```rust /// let v = &[1i, 2, 3, 4]; /// for win in v.windows(2) { - /// println!("{}", win); + /// println!("{:?}", win); /// } /// ``` #[stable] @@ -268,7 +268,7 @@ pub trait SliceExt { /// ```rust /// let v = &[1i, 2, 3, 4, 5]; /// for win in v.chunks(2) { - /// println!("{}", win); + /// println!("{:?}", win); /// } /// ``` #[stable] @@ -284,11 +284,11 @@ pub trait SliceExt { fn first(&self) -> Option<&Self::Item>; /// Returns all but the first element of a slice. - #[experimental = "likely to be renamed"] + #[unstable = "likely to be renamed"] fn tail(&self) -> &[Self::Item]; /// Returns all but the last element of a slice. - #[experimental = "likely to be renamed"] + #[unstable = "likely to be renamed"] fn init(&self) -> &[Self::Item]; /// Returns the last element of a slice, or `None` if it is empty. @@ -384,7 +384,7 @@ pub trait SliceExt { /// original slice (i.e. when `end > self.len()`) or when `start > end`. /// /// Slicing with `start` equal to `end` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice_mut(&mut self, start: uint, end: uint) -> &mut [Self::Item]; /// Returns a mutable subslice from `start` to the end of the slice. @@ -392,7 +392,7 @@ pub trait SliceExt { /// Panics when `start` is strictly greater than the length of the original slice. /// /// Slicing from `self.len()` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice_from_mut(&mut self, start: uint) -> &mut [Self::Item]; /// Returns a mutable subslice from the start of the slice to `end`. @@ -400,7 +400,7 @@ pub trait SliceExt { /// Panics when `end` is strictly greater than the length of the original slice. /// /// Slicing to `0` yields an empty slice. - #[experimental = "will be replaced by slice syntax"] + #[unstable = "will be replaced by slice syntax"] fn slice_to_mut(&mut self, end: uint) -> &mut [Self::Item]; /// Returns an iterator that allows modifying each value @@ -412,11 +412,11 @@ pub trait SliceExt { fn first_mut(&mut self) -> Option<&mut Self::Item>; /// Returns all but the first element of a mutable slice - #[experimental = "likely to be renamed or removed"] + #[unstable = "likely to be renamed or removed"] fn tail_mut(&mut self) -> &mut [Self::Item]; /// Returns all but the last element of a mutable slice - #[experimental = "likely to be renamed or removed"] + #[unstable = "likely to be renamed or removed"] fn init_mut(&mut self) -> &mut [Self::Item]; /// Returns a mutable pointer to the last item in the slice. @@ -554,7 +554,7 @@ pub trait SliceExt { /// let mut perms = v.permutations(); /// /// for p in perms { - /// println!("{}", p); + /// println!("{:?}", p); /// } /// ``` /// @@ -588,7 +588,7 @@ pub trait SliceExt { /// assert!(dst.clone_from_slice(&src2) == 3); /// assert!(dst == [3i, 4, 5]); /// ``` - #[experimental] + #[unstable] fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone; /// Sorts the slice, in place. @@ -677,11 +677,11 @@ pub trait SliceExt { fn prev_permutation(&mut self) -> bool where Self::Item: Ord; /// Find the first index containing a matching value. - #[experimental] + #[unstable] fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq; /// Find the last index containing a matching value. - #[experimental] + #[unstable] fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq; /// Return true if the slice contains an element with the given value. @@ -697,7 +697,7 @@ pub trait SliceExt { fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq; /// Convert `self` into a vector without clones or allocation. - #[experimental] + #[unstable] fn into_vec(self: Box<Self>) -> Vec<Self::Item>; } @@ -1034,7 +1034,7 @@ impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] { /// /// The last generated swap is always (0, 1), and it returns the /// sequence to its initial order. -#[experimental] +#[unstable] #[derive(Clone)] pub struct ElementSwaps { sdir: Vec<SizeDirection>, @@ -1046,7 +1046,7 @@ pub struct ElementSwaps { impl ElementSwaps { /// Creates an `ElementSwaps` iterator for a sequence of `length` elements. - #[experimental] + #[unstable] pub fn new(length: uint) -> ElementSwaps { // Initialize `sdir` with a direction that position should move in // (all negative at the beginning) and the `size` of the @@ -1065,12 +1065,12 @@ impl ElementSwaps { #[unstable = "trait is unstable"] impl<T> BorrowFrom<Vec<T>> for [T] { - fn borrow_from(owned: &Vec<T>) -> &[T] { owned.index(&FullRange) } + fn borrow_from(owned: &Vec<T>) -> &[T] { &owned[] } } #[unstable = "trait is unstable"] impl<T> BorrowFromMut<Vec<T>> for [T] { - fn borrow_from_mut(owned: &mut Vec<T>) -> &mut [T] { owned.index_mut(&FullRange) } + fn borrow_from_mut(owned: &mut Vec<T>) -> &mut [T] { &mut owned[] } } #[unstable = "trait is unstable"] @@ -1400,7 +1400,6 @@ mod tests { use core::prelude::{Ord, FullRange}; use core::default::Default; use core::mem; - use core::ops::Index; use std::iter::RandomAccessIterator; use std::rand::{Rng, thread_rng}; use std::rc::Rc; @@ -1611,7 +1610,7 @@ mod tests { // Test on stack. let vec_stack: &[_] = &[1i, 2, 3]; - let v_b = vec_stack.index(&(1u..3u)).to_vec(); + let v_b = vec_stack[1u..3u].to_vec(); assert_eq!(v_b.len(), 2u); let v_b = v_b.as_slice(); assert_eq!(v_b[0], 2); @@ -1619,7 +1618,7 @@ mod tests { // Test `Box<[T]>` let vec_unique = vec![1i, 2, 3, 4, 5, 6]; - let v_d = vec_unique.index(&(1u..6u)).to_vec(); + let v_d = vec_unique[1u..6u].to_vec(); assert_eq!(v_d.len(), 5u); let v_d = v_d.as_slice(); assert_eq!(v_d[0], 2); @@ -1632,21 +1631,21 @@ mod tests { #[test] fn test_slice_from() { let vec: &[int] = &[1, 2, 3, 4]; - assert_eq!(vec.index(&(0..)), vec); + assert_eq!(&vec[0..], vec); let b: &[int] = &[3, 4]; - assert_eq!(vec.index(&(2..)), b); + assert_eq!(&vec[2..], b); let b: &[int] = &[]; - assert_eq!(vec.index(&(4..)), b); + assert_eq!(&vec[4..], b); } #[test] fn test_slice_to() { let vec: &[int] = &[1, 2, 3, 4]; - assert_eq!(vec.index(&(0..4)), vec); + assert_eq!(&vec[0..4], vec); let b: &[int] = &[1, 2]; - assert_eq!(vec.index(&(0..2)), b); + assert_eq!(&vec[0..2], b); let b: &[int] = &[]; - assert_eq!(vec.index(&(0..0)), b); + assert_eq!(&vec[0..0], b); } @@ -2572,7 +2571,7 @@ mod tests { } assert_eq!(cnt, 3); - for f in v.index(&(1..3)).iter() { + for f in v[1..3].iter() { assert!(*f == Foo); cnt += 1; } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 09d140067f4..ccf654ac0a0 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -386,7 +386,7 @@ macro_rules! utf8_acc_cont_byte { #[unstable = "trait is unstable"] impl BorrowFrom<String> for str { - fn borrow_from(owned: &String) -> &str { owned.index(&FullRange) } + fn borrow_from(owned: &String) -> &str { &owned[] } } #[unstable = "trait is unstable"] @@ -464,7 +464,7 @@ pub trait StrExt: Index<FullRange, Output = str> { #[unstable = "this functionality may be moved to libunicode"] fn nfd_chars<'a>(&'a self) -> Decompositions<'a> { Decompositions { - iter: self.index(&FullRange).chars(), + iter: self[].chars(), buffer: Vec::new(), sorted: false, kind: Canonical @@ -477,7 +477,7 @@ pub trait StrExt: Index<FullRange, Output = str> { #[unstable = "this functionality may be moved to libunicode"] fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> { Decompositions { - iter: self.index(&FullRange).chars(), + iter: self[].chars(), buffer: Vec::new(), sorted: false, kind: Compatible @@ -525,7 +525,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn contains(&self, pat: &str) -> bool { - core_str::StrExt::contains(self.index(&FullRange), pat) + core_str::StrExt::contains(&self[], pat) } /// Returns true if a string contains a char pattern. @@ -541,7 +541,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "might get removed in favour of a more generic contains()"] fn contains_char<P: CharEq>(&self, pat: P) -> bool { - core_str::StrExt::contains_char(self.index(&FullRange), pat) + core_str::StrExt::contains_char(&self[], pat) } /// An iterator over the characters of `self`. Note, this iterates @@ -555,7 +555,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn chars(&self) -> Chars { - core_str::StrExt::chars(self.index(&FullRange)) + core_str::StrExt::chars(&self[]) } /// An iterator over the bytes of `self` @@ -568,13 +568,13 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn bytes(&self) -> Bytes { - core_str::StrExt::bytes(self.index(&FullRange)) + core_str::StrExt::bytes(&self[]) } /// An iterator over the characters of `self` and their byte offsets. #[stable] fn char_indices(&self) -> CharIndices { - core_str::StrExt::char_indices(self.index(&FullRange)) + core_str::StrExt::char_indices(&self[]) } /// An iterator over substrings of `self`, separated by characters @@ -597,7 +597,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn split<P: CharEq>(&self, pat: P) -> Split<P> { - core_str::StrExt::split(self.index(&FullRange), pat) + core_str::StrExt::split(&self[], pat) } /// An iterator over substrings of `self`, separated by characters @@ -624,7 +624,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn splitn<P: CharEq>(&self, count: uint, pat: P) -> SplitN<P> { - core_str::StrExt::splitn(self.index(&FullRange), count, pat) + core_str::StrExt::splitn(&self[], count, pat) } /// An iterator over substrings of `self`, separated by characters @@ -653,7 +653,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "might get removed"] fn split_terminator<P: CharEq>(&self, pat: P) -> SplitTerminator<P> { - core_str::StrExt::split_terminator(self.index(&FullRange), pat) + core_str::StrExt::split_terminator(&self[], pat) } /// An iterator over substrings of `self`, separated by characters @@ -674,7 +674,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn rsplitn<P: CharEq>(&self, count: uint, pat: P) -> RSplitN<P> { - core_str::StrExt::rsplitn(self.index(&FullRange), count, pat) + core_str::StrExt::rsplitn(&self[], count, pat) } /// An iterator over the start and end indices of the disjoint @@ -699,7 +699,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "might have its iterator type changed"] fn match_indices<'a>(&'a self, pat: &'a str) -> MatchIndices<'a> { - core_str::StrExt::match_indices(self.index(&FullRange), pat) + core_str::StrExt::match_indices(&self[], pat) } /// An iterator over the substrings of `self` separated by the pattern `sep`. @@ -715,7 +715,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "might get removed in the future in favor of a more generic split()"] fn split_str<'a>(&'a self, pat: &'a str) -> SplitStr<'a> { - core_str::StrExt::split_str(self.index(&FullRange), pat) + core_str::StrExt::split_str(&self[], pat) } /// An iterator over the lines of a string (subsequences separated @@ -731,7 +731,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn lines(&self) -> Lines { - core_str::StrExt::lines(self.index(&FullRange)) + core_str::StrExt::lines(&self[]) } /// An iterator over the lines of a string, separated by either @@ -747,7 +747,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn lines_any(&self) -> LinesAny { - core_str::StrExt::lines_any(self.index(&FullRange)) + core_str::StrExt::lines_any(&self[]) } /// Returns a slice of the given string from the byte range @@ -782,7 +782,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "use slice notation [a..b] instead"] fn slice(&self, begin: uint, end: uint) -> &str { - core_str::StrExt::slice(self.index(&FullRange), begin, end) + core_str::StrExt::slice(&self[], begin, end) } /// Returns a slice of the string from `begin` to its end. @@ -795,7 +795,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// See also `slice`, `slice_to` and `slice_chars`. #[unstable = "use slice notation [a..] instead"] fn slice_from(&self, begin: uint) -> &str { - core_str::StrExt::slice_from(self.index(&FullRange), begin) + core_str::StrExt::slice_from(&self[], begin) } /// Returns a slice of the string from the beginning to byte @@ -809,7 +809,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// See also `slice`, `slice_from` and `slice_chars`. #[unstable = "use slice notation [0..a] instead"] fn slice_to(&self, end: uint) -> &str { - core_str::StrExt::slice_to(self.index(&FullRange), end) + core_str::StrExt::slice_to(&self[], end) } /// Returns a slice of the string from the character range @@ -837,7 +837,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "may have yet to prove its worth"] fn slice_chars(&self, begin: uint, end: uint) -> &str { - core_str::StrExt::slice_chars(self.index(&FullRange), begin, end) + core_str::StrExt::slice_chars(&self[], begin, end) } /// Takes a bytewise (not UTF-8) slice from a string. @@ -848,7 +848,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// the entire slice as well. #[stable] unsafe fn slice_unchecked(&self, begin: uint, end: uint) -> &str { - core_str::StrExt::slice_unchecked(self.index(&FullRange), begin, end) + core_str::StrExt::slice_unchecked(&self[], begin, end) } /// Returns true if the pattern `pat` is a prefix of the string. @@ -860,7 +860,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn starts_with(&self, pat: &str) -> bool { - core_str::StrExt::starts_with(self.index(&FullRange), pat) + core_str::StrExt::starts_with(&self[], pat) } /// Returns true if the pattern `pat` is a suffix of the string. @@ -872,7 +872,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn ends_with(&self, pat: &str) -> bool { - core_str::StrExt::ends_with(self.index(&FullRange), pat) + core_str::StrExt::ends_with(&self[], pat) } /// Returns a string with all pre- and suffixes that match @@ -892,7 +892,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn trim_matches<P: CharEq>(&self, pat: P) -> &str { - core_str::StrExt::trim_matches(self.index(&FullRange), pat) + core_str::StrExt::trim_matches(&self[], pat) } /// Returns a string with all prefixes that match @@ -912,7 +912,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn trim_left_matches<P: CharEq>(&self, pat: P) -> &str { - core_str::StrExt::trim_left_matches(self.index(&FullRange), pat) + core_str::StrExt::trim_left_matches(&self[], pat) } /// Returns a string with all suffixes that match @@ -932,7 +932,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn trim_right_matches<P: CharEq>(&self, pat: P) -> &str { - core_str::StrExt::trim_right_matches(self.index(&FullRange), pat) + core_str::StrExt::trim_right_matches(&self[], pat) } /// Check that `index`-th byte lies at the start and/or end of a @@ -960,7 +960,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "naming is uncertain with container conventions"] fn is_char_boundary(&self, index: uint) -> bool { - core_str::StrExt::is_char_boundary(self.index(&FullRange), index) + core_str::StrExt::is_char_boundary(&self[], index) } /// Pluck a character out of a string and return the index of the next @@ -1018,7 +1018,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// If `i` is not the index of the beginning of a valid UTF-8 character. #[unstable = "naming is uncertain with container conventions"] fn char_range_at(&self, start: uint) -> CharRange { - core_str::StrExt::char_range_at(self.index(&FullRange), start) + core_str::StrExt::char_range_at(&self[], start) } /// Given a byte position and a str, return the previous char and its position. @@ -1033,7 +1033,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// If `i` is not an index following a valid UTF-8 character. #[unstable = "naming is uncertain with container conventions"] fn char_range_at_reverse(&self, start: uint) -> CharRange { - core_str::StrExt::char_range_at_reverse(self.index(&FullRange), start) + core_str::StrExt::char_range_at_reverse(&self[], start) } /// Plucks the character starting at the `i`th byte of a string. @@ -1053,7 +1053,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// If `i` is not the index of the beginning of a valid UTF-8 character. #[unstable = "naming is uncertain with container conventions"] fn char_at(&self, i: uint) -> char { - core_str::StrExt::char_at(self.index(&FullRange), i) + core_str::StrExt::char_at(&self[], i) } /// Plucks the character ending at the `i`th byte of a string. @@ -1064,7 +1064,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// If `i` is not an index following a valid UTF-8 character. #[unstable = "naming is uncertain with container conventions"] fn char_at_reverse(&self, i: uint) -> char { - core_str::StrExt::char_at_reverse(self.index(&FullRange), i) + core_str::StrExt::char_at_reverse(&self[], i) } /// Work with the byte buffer of a string as a byte slice. @@ -1076,7 +1076,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn as_bytes(&self) -> &[u8] { - core_str::StrExt::as_bytes(self.index(&FullRange)) + core_str::StrExt::as_bytes(&self[]) } /// Returns the byte index of the first character of `self` that @@ -1104,7 +1104,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn find<P: CharEq>(&self, pat: P) -> Option<uint> { - core_str::StrExt::find(self.index(&FullRange), pat) + core_str::StrExt::find(&self[], pat) } /// Returns the byte index of the last character of `self` that @@ -1132,7 +1132,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn rfind<P: CharEq>(&self, pat: P) -> Option<uint> { - core_str::StrExt::rfind(self.index(&FullRange), pat) + core_str::StrExt::rfind(&self[], pat) } /// Returns the byte index of the first matching substring @@ -1156,7 +1156,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "might get removed in favor of a more generic find in the future"] fn find_str(&self, needle: &str) -> Option<uint> { - core_str::StrExt::find_str(self.index(&FullRange), needle) + core_str::StrExt::find_str(&self[], needle) } /// Retrieves the first character from a string slice and returns @@ -1179,7 +1179,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "awaiting conventions about shifting and slices"] fn slice_shift_char(&self) -> Option<(char, &str)> { - core_str::StrExt::slice_shift_char(self.index(&FullRange)) + core_str::StrExt::slice_shift_char(&self[]) } /// Returns the byte offset of an inner slice relative to an enclosing outer slice. @@ -1198,7 +1198,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "awaiting convention about comparability of arbitrary slices"] fn subslice_offset(&self, inner: &str) -> uint { - core_str::StrExt::subslice_offset(self.index(&FullRange), inner) + core_str::StrExt::subslice_offset(&self[], inner) } /// Return an unsafe pointer to the strings buffer. @@ -1209,13 +1209,13 @@ pub trait StrExt: Index<FullRange, Output = str> { #[stable] #[inline] fn as_ptr(&self) -> *const u8 { - core_str::StrExt::as_ptr(self.index(&FullRange)) + core_str::StrExt::as_ptr(&self[]) } /// Return an iterator of `u16` over the string encoded as UTF-16. #[unstable = "this functionality may only be provided by libunicode"] fn utf16_units(&self) -> Utf16Units { - Utf16Units { encoder: Utf16Encoder::new(self.index(&FullRange).chars()) } + Utf16Units { encoder: Utf16Encoder::new(self[].chars()) } } /// Return the number of bytes in this string @@ -1229,7 +1229,7 @@ pub trait StrExt: Index<FullRange, Output = str> { #[stable] #[inline] fn len(&self) -> uint { - core_str::StrExt::len(self.index(&FullRange)) + core_str::StrExt::len(&self[]) } /// Returns true if this slice contains no bytes @@ -1242,7 +1242,7 @@ pub trait StrExt: Index<FullRange, Output = str> { #[inline] #[stable] fn is_empty(&self) -> bool { - core_str::StrExt::is_empty(self.index(&FullRange)) + core_str::StrExt::is_empty(&self[]) } /// Parse this string into the specified type. @@ -1256,7 +1256,7 @@ pub trait StrExt: Index<FullRange, Output = str> { #[inline] #[unstable = "this method was just created"] fn parse<F: FromStr>(&self) -> Option<F> { - core_str::StrExt::parse(self.index(&FullRange)) + core_str::StrExt::parse(&self[]) } /// Returns an iterator over the @@ -1280,7 +1280,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "this functionality may only be provided by libunicode"] fn graphemes(&self, is_extended: bool) -> Graphemes { - UnicodeStr::graphemes(self.index(&FullRange), is_extended) + UnicodeStr::graphemes(&self[], is_extended) } /// Returns an iterator over the grapheme clusters of self and their byte offsets. @@ -1295,7 +1295,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[unstable = "this functionality may only be provided by libunicode"] fn grapheme_indices(&self, is_extended: bool) -> GraphemeIndices { - UnicodeStr::grapheme_indices(self.index(&FullRange), is_extended) + UnicodeStr::grapheme_indices(&self[], is_extended) } /// An iterator over the words of a string (subsequences separated @@ -1311,7 +1311,7 @@ pub trait StrExt: Index<FullRange, Output = str> { /// ``` #[stable] fn words(&self) -> Words { - UnicodeStr::words(self.index(&FullRange)) + UnicodeStr::words(&self[]) } /// Returns a string's displayed width in columns, treating control @@ -1325,25 +1325,25 @@ pub trait StrExt: Index<FullRange, Output = str> { /// `is_cjk` = `false`) if the locale is unknown. #[unstable = "this functionality may only be provided by libunicode"] fn width(&self, is_cjk: bool) -> uint { - UnicodeStr::width(self.index(&FullRange), is_cjk) + UnicodeStr::width(&self[], is_cjk) } /// Returns a string with leading and trailing whitespace removed. #[stable] fn trim(&self) -> &str { - UnicodeStr::trim(self.index(&FullRange)) + UnicodeStr::trim(&self[]) } /// Returns a string with leading whitespace removed. #[stable] fn trim_left(&self) -> &str { - UnicodeStr::trim_left(self.index(&FullRange)) + UnicodeStr::trim_left(&self[]) } /// Returns a string with trailing whitespace removed. #[stable] fn trim_right(&self) -> &str { - UnicodeStr::trim_right(self.index(&FullRange)) + UnicodeStr::trim_right(&self[]) } } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 59418f50e3c..5991fc832e9 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -92,7 +92,7 @@ impl String { /// assert_eq!(s.as_slice(), "hello"); /// ``` #[inline] - #[experimental = "needs investigation to see if to_string() can match perf"] + #[unstable = "needs investigation to see if to_string() can match perf"] pub fn from_str(string: &str) -> String { String { vec: ::slice::SliceExt::to_vec(string.as_bytes()) } } @@ -168,7 +168,7 @@ impl String { if i > 0 { unsafe { - res.as_mut_vec().push_all(v.index(&(0..i))) + res.as_mut_vec().push_all(&v[0..i]) }; } @@ -185,7 +185,7 @@ impl String { macro_rules! error { () => ({ unsafe { if subseqidx != i_ { - res.as_mut_vec().push_all(v.index(&(subseqidx..i_))); + res.as_mut_vec().push_all(&v[subseqidx..i_]); } subseqidx = i; res.as_mut_vec().push_all(REPLACEMENT); @@ -254,7 +254,7 @@ impl String { } if subseqidx < total { unsafe { - res.as_mut_vec().push_all(v.index(&(subseqidx..total))) + res.as_mut_vec().push_all(&v[subseqidx..total]) }; } Cow::Owned(res) @@ -681,6 +681,7 @@ impl fmt::Show for FromUtf8Error { } } +#[stable] impl fmt::String for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(&self.error, f) @@ -693,6 +694,7 @@ impl fmt::Show for FromUtf16Error { } } +#[stable] impl fmt::String for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt("invalid utf-16: lone surrogate found", f) @@ -717,7 +719,7 @@ impl<'a> FromIterator<&'a str> for String { } } -#[experimental = "waiting on Extend stabilization"] +#[unstable = "waiting on Extend stabilization"] impl Extend<char> for String { fn extend<I:Iterator<Item=char>>(&mut self, mut iterator: I) { let (lower_bound, _) = iterator.size_hint(); @@ -728,7 +730,7 @@ impl Extend<char> for String { } } -#[experimental = "waiting on Extend stabilization"] +#[unstable = "waiting on Extend stabilization"] impl<'a> Extend<&'a str> for String { fn extend<I: Iterator<Item=&'a str>>(&mut self, mut iterator: I) { // A guess that at least one byte per iterator element will be needed. @@ -788,7 +790,7 @@ impl<'a, 'b> PartialEq<CowString<'a>> for &'b str { fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) } } -#[experimental = "waiting on Str stabilization"] +#[unstable = "waiting on Str stabilization"] impl Str for String { #[inline] #[stable] @@ -805,27 +807,36 @@ impl Default for String { } } -#[experimental = "waiting on fmt stabilization"] +#[stable] impl fmt::String for String { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(&**self, f) } } -#[experimental = "waiting on fmt stabilization"] +#[unstable = "waiting on fmt stabilization"] impl fmt::Show for String { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Show::fmt(&**self, f) } } -#[experimental = "waiting on Hash stabilization"] +#[unstable = "waiting on Hash stabilization"] +#[cfg(stage0)] impl<H: hash::Writer> hash::Hash<H> for String { #[inline] fn hash(&self, hasher: &mut H) { (**self).hash(hasher) } } +#[unstable = "waiting on Hash stabilization"] +#[cfg(not(stage0))] +impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for String { + #[inline] + fn hash(&self, hasher: &mut H) { + (**self).hash(hasher) + } +} #[unstable = "recent addition, needs more experience"] impl<'a> Add<&'a str> for String { @@ -841,21 +852,21 @@ impl ops::Index<ops::Range<uint>> for String { type Output = str; #[inline] fn index(&self, index: &ops::Range<uint>) -> &str { - &self.index(&FullRange)[*index] + &self[][*index] } } impl ops::Index<ops::RangeTo<uint>> for String { type Output = str; #[inline] fn index(&self, index: &ops::RangeTo<uint>) -> &str { - &self.index(&FullRange)[*index] + &self[][*index] } } impl ops::Index<ops::RangeFrom<uint>> for String { type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom<uint>) -> &str { - &self.index(&FullRange)[*index] + &self[][*index] } } impl ops::Index<ops::FullRange> for String { @@ -871,12 +882,12 @@ impl ops::Deref for String { type Target = str; fn deref<'a>(&'a self) -> &'a str { - unsafe { mem::transmute(self.vec.index(&FullRange)) } + unsafe { mem::transmute(&self.vec[]) } } } /// Wrapper type providing a `&String` reference via `Deref`. -#[experimental] +#[unstable] pub struct DerefString<'a> { x: DerefVec<'a, u8> } @@ -903,7 +914,7 @@ impl<'a> Deref for DerefString<'a> { /// let string = as_string("foo").clone(); /// string_consumer(string); /// ``` -#[experimental] +#[unstable] pub fn as_string<'a>(x: &'a str) -> DerefString<'a> { DerefString { x: as_vec(x.as_bytes()) } } @@ -921,19 +932,7 @@ pub trait ToString { fn to_string(&self) -> String; } -#[cfg(stage0)] -impl<T: fmt::Show> ToString for T { - fn to_string(&self) -> String { - use core::fmt::Writer; - let mut buf = String::new(); - let _ = buf.write_fmt(format_args!("{}", self)); - buf.shrink_to_fit(); - buf - } -} - -#[cfg(not(stage0))] -impl<T: fmt::String> ToString for T { +impl<T: fmt::String + ?Sized> ToString for T { fn to_string(&self) -> String { use core::fmt::Writer; let mut buf = String::new(); @@ -996,6 +995,12 @@ mod tests { } #[test] + fn test_unsized_to_string() { + let s: &str = "abc"; + let _: String = (*s).to_string(); + } + + #[test] fn test_from_utf8() { let xs = b"hello".to_vec(); assert_eq!(String::from_utf8(xs).unwrap(), @@ -1277,18 +1282,17 @@ mod tests { assert_eq!(2u8.to_string(), "2"); assert_eq!(true.to_string(), "true"); assert_eq!(false.to_string(), "false"); - assert_eq!(().to_string(), "()"); assert_eq!(("hi".to_string()).to_string(), "hi"); } #[test] fn test_vectors() { let x: Vec<int> = vec![]; - assert_eq!(x.to_string(), "[]"); - assert_eq!((vec![1i]).to_string(), "[1]"); - assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]"); - assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() == - "[[], [1], [1, 1]]"); + assert_eq!(format!("{:?}", x), "[]"); + assert_eq!(format!("{:?}", vec![1i]), "[1i]"); + assert_eq!(format!("{:?}", vec![1i, 2, 3]), "[1i, 2i, 3i]"); + assert!(format!("{:?}", vec![vec![], vec![1i], vec![1i, 1]]) == + "[[], [1i], [1i, 1i]]"); } #[test] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 5fc3fafac9e..47afc78bc12 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -44,6 +44,8 @@ //! let two = xs.pop(); //! ``` +#![stable] + use core::prelude::*; use alloc::boxed::Box; @@ -374,7 +376,7 @@ impl<T> Vec<T> { /// Note that this will drop any excess capacity. Calling this and /// converting back to a vector with `into_vec()` is equivalent to calling /// `shrink_to_fit()`. - #[experimental] + #[unstable] pub fn into_boxed_slice(mut self) -> Box<[T]> { self.shrink_to_fit(); unsafe { @@ -775,7 +777,7 @@ impl<T> Vec<T> { /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x)); /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice()); /// ``` - #[experimental = "API may change to provide stronger guarantees"] + #[unstable = "API may change to provide stronger guarantees"] pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U { // FIXME: Assert statically that the types `T` and `U` have the same // size. @@ -993,7 +995,7 @@ impl<T: Clone> Vec<T> { /// assert_eq!(vec, vec![1, 2, 3, 4]); /// ``` #[inline] - #[experimental = "likely to be replaced by a more optimized extend"] + #[unstable = "likely to be replaced by a more optimized extend"] pub fn push_all(&mut self, other: &[T]) { self.reserve(other.len()); @@ -1178,19 +1180,27 @@ impl<T:Clone> Clone for Vec<T> { // self.len <= other.len due to the truncate above, so the // slice here is always in-bounds. - let slice = other.index(&(self.len()..)); + let slice = &other[self.len()..]; self.push_all(slice); } } +#[cfg(stage0)] impl<S: hash::Writer, T: Hash<S>> Hash<S> for Vec<T> { #[inline] fn hash(&self, state: &mut S) { self.as_slice().hash(state); } } +#[cfg(not(stage0))] +impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> { + #[inline] + fn hash(&self, state: &mut S) { + self.as_slice().hash(state); + } +} -#[experimental = "waiting on Index stability"] +#[unstable = "waiting on Index stability"] impl<T> Index<uint> for Vec<T> { type Output = T; @@ -1294,7 +1304,7 @@ impl<T> FromIterator<T> for Vec<T> { } } -#[experimental = "waiting on Extend stability"] +#[unstable = "waiting on Extend stability"] impl<T> Extend<T> for Vec<T> { #[inline] fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) { @@ -1447,29 +1457,13 @@ impl<T> Default for Vec<T> { } } -#[experimental = "waiting on Show stability"] +#[unstable = "waiting on Show stability"] impl<T: fmt::Show> fmt::Show for Vec<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Show::fmt(self.as_slice(), f) } } -#[cfg(stage0)] -#[experimental = "waiting on Show stability"] -impl<T: fmt::Show> fmt::String for Vec<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_slice(), f) - } -} - -#[cfg(not(stage0))] -#[experimental = "waiting on Show stability"] -impl<T: fmt::String> fmt::String for Vec<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_slice(), f) - } -} - impl<'a> fmt::Writer for Vec<u8> { fn write_str(&mut self, s: &str) -> fmt::Result { self.push_all(s.as_bytes()); @@ -1481,7 +1475,7 @@ impl<'a> fmt::Writer for Vec<u8> { // Clone-on-write //////////////////////////////////////////////////////////////////////////////// -#[experimental = "unclear how valuable this alias is"] +#[unstable = "unclear how valuable this alias is"] /// A clone-on-write vector pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>; @@ -1699,13 +1693,13 @@ impl<'a, T> Drop for Drain<'a, T> { //////////////////////////////////////////////////////////////////////////////// /// Wrapper type providing a `&Vec<T>` reference via `Deref`. -#[experimental] +#[unstable] pub struct DerefVec<'a, T> { x: Vec<T>, l: ContravariantLifetime<'a> } -#[experimental] +#[unstable] impl<'a, T> Deref for DerefVec<'a, T> { type Target = Vec<T>; @@ -1725,7 +1719,7 @@ impl<'a, T> Drop for DerefVec<'a, T> { } /// Convert a slice to a wrapper type providing a `&Vec<T>` reference. -#[experimental] +#[unstable] pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> { unsafe { DerefVec { @@ -2039,7 +2033,7 @@ mod tests { v.push(()); assert_eq!(v.iter_mut().count(), 4); - for &() in v.iter_mut() {} + for &mut () in v.iter_mut() {} unsafe { v.set_len(0); } assert_eq!(v.iter_mut().count(), 0); } diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 4399a6fec22..d4ce266d3e2 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -18,7 +18,7 @@ use core::prelude::*; use core::cmp::Ordering; use core::default::Default; use core::fmt; -use core::hash::{Hash, Writer}; +use core::hash::{Hash, Writer, Hasher}; use core::iter::{Enumerate, FilterMap, Map, FromIterator}; use core::iter; use core::mem::replace; @@ -85,7 +85,7 @@ impl<V:Clone> Clone for VecMap<V> { } } -impl<S: Writer, V: Hash<S>> Hash<S> for VecMap<V> { +impl<S: Writer + Hasher, V: Hash<S>> Hash<S> for VecMap<V> { fn hash(&self, state: &mut S) { // In order to not traverse the `VecMap` twice, count the elements // during iteration. @@ -712,7 +712,7 @@ impl<V> DoubleEndedIterator for IntoIter<V> { #[cfg(test)] mod test_map { use prelude::*; - use core::hash::hash; + use core::hash::{hash, SipHasher}; use super::VecMap; @@ -1004,7 +1004,7 @@ mod test_map { let mut x = VecMap::new(); let mut y = VecMap::new(); - assert!(hash(&x) == hash(&y)); + assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y)); x.insert(1, 'a'); x.insert(2, 'b'); x.insert(3, 'c'); @@ -1013,12 +1013,12 @@ mod test_map { y.insert(2, 'b'); y.insert(1, 'a'); - assert!(hash(&x) == hash(&y)); + assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y)); x.insert(1000, 'd'); x.remove(&1000); - assert!(hash(&x) == hash(&y)); + assert!(hash::<_, SipHasher>(&x) == hash::<_, SipHasher>(&y)); } #[test] diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 25007bfde93..797687a9ad9 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -89,7 +89,7 @@ use intrinsics::TypeId; #[stable] pub trait Any: 'static { /// Get the `TypeId` of `self` - #[experimental = "this method will likely be replaced by an associated static"] + #[unstable = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 05db9e11760..c07fac108d6 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -12,13 +12,13 @@ //! up to a certain length. Eventually we should able to generalize //! to all lengths. -#![experimental] // not yet reviewed +#![unstable] // not yet reviewed use clone::Clone; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use fmt; use marker::Copy; -use ops::{Deref, FullRange, Index}; +use ops::{Deref, FullRange}; use option::Option; // macro for implementing n-ary tuple functions and operations @@ -35,7 +35,7 @@ macro_rules! array_impls { #[unstable = "waiting for Show to stabilize"] impl<T:fmt::Show> fmt::Show for [T; $N] { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Show::fmt(&self.index(&FullRange), f) + fmt::Show::fmt(&&self[], f) } } @@ -43,11 +43,11 @@ macro_rules! array_impls { impl<A, B> PartialEq<[B; $N]> for [A; $N] where A: PartialEq<B> { #[inline] fn eq(&self, other: &[B; $N]) -> bool { - self.index(&FullRange) == other.index(&FullRange) + &self[] == &other[] } #[inline] fn ne(&self, other: &[B; $N]) -> bool { - self.index(&FullRange) != other.index(&FullRange) + &self[] != &other[] } } @@ -58,11 +58,11 @@ macro_rules! array_impls { { #[inline(always)] fn eq(&self, other: &Rhs) -> bool { - PartialEq::eq(self.index(&FullRange), &**other) + PartialEq::eq(&self[], &**other) } #[inline(always)] fn ne(&self, other: &Rhs) -> bool { - PartialEq::ne(self.index(&FullRange), &**other) + PartialEq::ne(&self[], &**other) } } @@ -73,11 +73,11 @@ macro_rules! array_impls { { #[inline(always)] fn eq(&self, other: &[B; $N]) -> bool { - PartialEq::eq(&**self, other.index(&FullRange)) + PartialEq::eq(&**self, &other[]) } #[inline(always)] fn ne(&self, other: &[B; $N]) -> bool { - PartialEq::ne(&**self, other.index(&FullRange)) + PartialEq::ne(&**self, &other[]) } } @@ -88,23 +88,23 @@ macro_rules! array_impls { impl<T:PartialOrd> PartialOrd for [T; $N] { #[inline] fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> { - PartialOrd::partial_cmp(&self.index(&FullRange), &other.index(&FullRange)) + PartialOrd::partial_cmp(&&self[], &&other[]) } #[inline] fn lt(&self, other: &[T; $N]) -> bool { - PartialOrd::lt(&self.index(&FullRange), &other.index(&FullRange)) + PartialOrd::lt(&&self[], &&other[]) } #[inline] fn le(&self, other: &[T; $N]) -> bool { - PartialOrd::le(&self.index(&FullRange), &other.index(&FullRange)) + PartialOrd::le(&&self[], &&other[]) } #[inline] fn ge(&self, other: &[T; $N]) -> bool { - PartialOrd::ge(&self.index(&FullRange), &other.index(&FullRange)) + PartialOrd::ge(&&self[], &&other[]) } #[inline] fn gt(&self, other: &[T; $N]) -> bool { - PartialOrd::gt(&self.index(&FullRange), &other.index(&FullRange)) + PartialOrd::gt(&&self[], &&other[]) } } @@ -112,7 +112,7 @@ macro_rules! array_impls { impl<T:Ord> Ord for [T; $N] { #[inline] fn cmp(&self, other: &[T; $N]) -> Ordering { - Ord::cmp(&self.index(&FullRange), &other.index(&FullRange)) + Ord::cmp(&&self[], &&other[]) } } )+ diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index 31631355422..4363a0a4441 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -133,7 +133,7 @@ impl<T> ToOwned<T> for T where T: Clone { /// } /// } /// ``` -//#[deriving(Show)] NOTE(stage0): uncomment after snapshot +#[derive(Show)] pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> { /// Borrowed data. Borrowed(&'a B), @@ -142,16 +142,6 @@ pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> { Owned(T) } -//NOTE(stage0): replace with deriving(Show) after snapshot -impl<'a, T, B: ?Sized> fmt::Show for Cow<'a, T, B> where - B: fmt::String + ToOwned<T>, - T: fmt::String -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - #[stable] impl<'a, T, B: ?Sized> Clone for Cow<'a, T, B> where B: ToOwned<T> { fn clone(&self) -> Cow<'a, T, B> { @@ -248,6 +238,7 @@ impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwne } } +#[stable] impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where B: fmt::String + ToOwned<T>, T: fmt::String, diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 674364269f1..6db01b7cb7a 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -202,7 +202,7 @@ impl<T:Copy> Cell<T> { /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] - #[experimental] + #[unstable] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } @@ -332,7 +332,7 @@ impl<T> RefCell<T> { /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] - #[experimental] + #[unstable] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } @@ -424,7 +424,7 @@ impl<'b, T> Deref for Ref<'b, T> { /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. -#[experimental = "likely to be moved to a method, pending language changes"] +#[unstable = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> { Ref { _value: orig._value, diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 3149247a83a..ffa6d085543 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -81,7 +81,7 @@ clone_impl! { char } macro_rules! extern_fn_clone { ($($A:ident),*) => ( - #[experimental = "this may not be sufficient for fns with region parameters"] + #[unstable = "this may not be sufficient for fns with region parameters"] impl<$($A,)* ReturnType> Clone for extern "Rust" fn($($A),*) -> ReturnType { /// Return a copy of a function pointer #[inline] diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index c3dfd5f5159..c1f1997df74 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -290,7 +290,7 @@ pub fn max<T: Ord>(v1: T, v2: T) -> T { /// /// Returns the first argument if the comparison determines them to be equal. #[inline] -#[experimental] +#[unstable] pub fn partial_min<T: PartialOrd>(v1: T, v2: T) -> Option<T> { match v1.partial_cmp(&v2) { Some(Less) | Some(Equal) => Some(v1), @@ -303,7 +303,7 @@ pub fn partial_min<T: PartialOrd>(v1: T, v2: T) -> Option<T> { /// /// Returns the first argument if the comparison determines them to be equal. #[inline] -#[experimental] +#[unstable] pub fn partial_max<T: PartialOrd>(v1: T, v2: T) -> Option<T> { match v1.partial_cmp(&v2) { Some(Less) => Some(v2), diff --git a/src/libcore/finally.rs b/src/libcore/finally.rs index 2b48b2bf81a..a21ec892dd7 100644 --- a/src/libcore/finally.rs +++ b/src/libcore/finally.rs @@ -32,7 +32,7 @@ //! # } //! ``` -#![experimental] +#![unstable] use ops::{Drop, FnMut, FnOnce}; diff --git a/src/libcore/fmt/float.rs b/src/libcore/fmt/float.rs index d833b8fed77..0ffcb014c28 100644 --- a/src/libcore/fmt/float.rs +++ b/src/libcore/fmt/float.rs @@ -20,7 +20,7 @@ use fmt; use iter::{IteratorExt, range}; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; -use ops::{FnOnce, Index}; +use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; @@ -332,5 +332,5 @@ pub fn float_to_str_bytes_common<T: Float, U, F>( } } - f(unsafe { str::from_utf8_unchecked(buf.index(&(0..end))) }) + f(unsafe { str::from_utf8_unchecked(&buf[0..end]) }) } diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index f9027f19068..67d5482898e 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -11,6 +11,7 @@ //! Utilities for formatting and printing strings #![allow(unused_variables)] +#![stable] use any; use cell::{Cell, RefCell, Ref, RefMut}; @@ -21,7 +22,7 @@ use mem; use option::Option; use option::Option::{Some, None}; use result::Result::Ok; -use ops::{Deref, FnOnce, Index}; +use ops::{Deref, FnOnce}; use result; use slice::SliceExt; use slice; @@ -35,7 +36,7 @@ mod num; mod float; pub mod rt; -#[experimental = "core and I/O reconciliation may alter this definition"] +#[unstable = "core and I/O reconciliation may alter this definition"] /// The type returned by formatter methods. pub type Result = result::Result<(), Error>; @@ -44,7 +45,7 @@ pub type Result = result::Result<(), Error>; /// This type does not support transmission of an error other than that an error /// occurred. Any extra information must be arranged to be transmitted through /// some other means. -#[experimental = "core and I/O reconciliation may alter this definition"] +#[unstable = "core and I/O reconciliation may alter this definition"] #[derive(Copy)] pub struct Error; @@ -57,7 +58,7 @@ pub struct Error; /// This trait should generally not be implemented by consumers of the standard /// library. The `write!` macro accepts an instance of `io::Writer`, and the /// `io::Writer` trait is favored over implementing this trait. -#[experimental = "waiting for core and I/O reconciliation"] +#[unstable = "waiting for core and I/O reconciliation"] pub trait Writer { /// Writes a slice of bytes into this writer, returning whether the write /// succeeded. @@ -122,7 +123,7 @@ enum Void {} /// family of functions. It contains a function to format the given value. At /// compile time it is ensured that the function and the value have the correct /// types, and then this struct is used to canonicalize arguments to one type. -#[experimental = "implementation detail of the `format_args!` macro"] +#[unstable = "implementation detail of the `format_args!` macro"] #[derive(Copy)] pub struct Argument<'a> { value: &'a Void, @@ -161,7 +162,7 @@ impl<'a> Arguments<'a> { /// When using the format_args!() macro, this function is used to generate the /// Arguments structure. #[doc(hidden)] #[inline] - #[experimental = "implementation detail of the `format_args!` macro"] + #[unstable = "implementation detail of the `format_args!` macro"] pub fn new(pieces: &'a [&'a str], args: &'a [Argument<'a>]) -> Arguments<'a> { Arguments { @@ -178,7 +179,7 @@ impl<'a> Arguments<'a> { /// created with `argumentuint`. However, failing to do so doesn't cause /// unsafety, but will ignore invalid . #[doc(hidden)] #[inline] - #[experimental = "implementation detail of the `format_args!` macro"] + #[unstable = "implementation detail of the `format_args!` macro"] pub fn with_placeholders(pieces: &'a [&'a str], fmt: &'a [rt::Argument<'a>], args: &'a [Argument<'a>]) -> Arguments<'a> { @@ -219,6 +220,7 @@ impl<'a> Show for Arguments<'a> { } } +#[stable] impl<'a> String for Arguments<'a> { fn fmt(&self, fmt: &mut Formatter) -> Result { write(fmt.buf, *self) @@ -299,7 +301,7 @@ pub trait UpperExp { /// /// * output - the buffer to write output to /// * args - the precompiled arguments generated by `format_args!` -#[experimental = "libcore and I/O have yet to be reconciled, and this is an \ +#[unstable = "libcore and I/O have yet to be reconciled, and this is an \ implementation detail which should not otherwise be exported"] pub fn write(output: &mut Writer, args: Arguments) -> Result { let mut formatter = Formatter { @@ -424,7 +426,7 @@ impl<'a> Formatter<'a> { for c in sign.into_iter() { let mut b = [0; 4]; let n = c.encode_utf8(&mut b).unwrap_or(0); - let b = unsafe { str::from_utf8_unchecked(b.index(&(0..n))) }; + let b = unsafe { str::from_utf8_unchecked(&b[0..n]) }; try!(f.buf.write_str(b)); } if prefixed { f.buf.write_str(prefix) } @@ -532,7 +534,7 @@ impl<'a> Formatter<'a> { let mut fill = [0u8; 4]; let len = self.fill.encode_utf8(&mut fill).unwrap_or(0); - let fill = unsafe { str::from_utf8_unchecked(fill.index(&(..len))) }; + let fill = unsafe { str::from_utf8_unchecked(&fill[..len]) }; for _ in range(0, pre_pad) { try!(self.buf.write_str(fill)); @@ -561,7 +563,7 @@ impl<'a> Formatter<'a> { } /// Flags for formatting (packed version of rt::Flag) - #[experimental = "return type may change and method was just created"] + #[unstable = "return type may change and method was just created"] pub fn flags(&self) -> uint { self.flags } /// Character used as 'fill' whenever there is alignment @@ -590,7 +592,7 @@ impl Show for Error { /// This is a function which calls are emitted to by the compiler itself to /// create the Argument structures that are passed into the `format` function. #[doc(hidden)] #[inline] -#[experimental = "implementation detail of the `format_args!` macro"] +#[unstable = "implementation detail of the `format_args!` macro"] pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result, t: &'a T) -> Argument<'a> { Argument::new(t, f) @@ -599,7 +601,7 @@ pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result, /// When the compiler determines that the type of an argument *must* be a uint /// (such as for width and precision), then it invokes this method. #[doc(hidden)] #[inline] -#[experimental = "implementation detail of the `format_args!` macro"] +#[unstable = "implementation detail of the `format_args!` macro"] pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { Argument::from_uint(s) } @@ -627,22 +629,13 @@ impl Show for bool { } } +#[stable] impl String for bool { fn fmt(&self, f: &mut Formatter) -> Result { String::fmt(if *self { "true" } else { "false" }, f) } } -#[cfg(stage0)] -//NOTE(stage0): remove impl after snapshot -impl Show for str { - fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(self, f) - } -} - -#[cfg(not(stage0))] -//NOTE(stage0): remove cfg after snapshot impl Show for str { fn fmt(&self, f: &mut Formatter) -> Result { try!(write!(f, "\"")); @@ -653,22 +646,13 @@ impl Show for str { } } +#[stable] impl String for str { fn fmt(&self, f: &mut Formatter) -> Result { f.pad(self) } } -#[cfg(stage0)] -//NOTE(stage0): remove impl after snapshot -impl Show for char { - fn fmt(&self, f: &mut Formatter) -> Result { - String::fmt(self, f) - } -} - -#[cfg(not(stage0))] -//NOTE(stage0): remove cfg after snapshot impl Show for char { fn fmt(&self, f: &mut Formatter) -> Result { use char::CharExt; @@ -680,11 +664,12 @@ impl Show for char { } } +#[stable] impl String for char { fn fmt(&self, f: &mut Formatter) -> Result { let mut utf8 = [0u8; 4]; let amt = self.encode_utf8(&mut utf8).unwrap_or(0); - let s: &str = unsafe { mem::transmute(utf8.index(&(0..amt))) }; + let s: &str = unsafe { mem::transmute(&utf8[0..amt]) }; String::fmt(s, f) } } @@ -725,6 +710,7 @@ macro_rules! floating { ($ty:ident) => { } } + #[stable] impl String for $ty { fn fmt(&self, fmt: &mut Formatter) -> Result { use num::Float; @@ -796,15 +782,9 @@ floating! { f64 } impl<T> Show for *const T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } -impl<T> String for *const T { - fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } -} impl<T> Show for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } -impl<T> String for *mut T { - fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } -} macro_rules! peel { ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) @@ -863,61 +843,12 @@ impl<T: Show> Show for [T] { } } -#[cfg(stage0)] -impl<T: Show> String for [T] { - fn fmt(&self, f: &mut Formatter) -> Result { - if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { - try!(write!(f, "[")); - } - let mut is_first = true; - for x in self.iter() { - if is_first { - is_first = false; - } else { - try!(write!(f, ", ")); - } - try!(write!(f, "{}", *x)) - } - if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { - try!(write!(f, "]")); - } - Ok(()) - } -} -#[cfg(not(stage0))] -impl<T: String> String for [T] { - fn fmt(&self, f: &mut Formatter) -> Result { - if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { - try!(write!(f, "[")); - } - let mut is_first = true; - for x in self.iter() { - if is_first { - is_first = false; - } else { - try!(write!(f, ", ")); - } - try!(write!(f, "{}", *x)) - } - if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 { - try!(write!(f, "]")); - } - Ok(()) - } -} - impl Show for () { fn fmt(&self, f: &mut Formatter) -> Result { f.pad("()") } } -impl String for () { - fn fmt(&self, f: &mut Formatter) -> Result { - f.pad("()") - } -} - impl<T: Copy + Show> Show for Cell<T> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "Cell {{ value: {:?} }}", self.get()) @@ -946,6 +877,7 @@ impl<'b, T: Show> Show for RefMut<'b, T> { } } +#[stable] impl String for Utf8Error { fn fmt(&self, f: &mut Formatter) -> Result { match *self { diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 17149aed3db..1df6f845225 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -16,7 +16,6 @@ use fmt; use iter::IteratorExt; -use ops::Index; use num::{Int, cast}; use slice::SliceExt; use str; @@ -62,7 +61,7 @@ trait GenericRadix { if x == zero { break }; // No more digits left to accumulate. } } - let buf = unsafe { str::from_utf8_unchecked(buf.index(&(curr..))) }; + let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) }; f.pad_integral(is_positive, self.prefix(), buf) } } @@ -155,14 +154,6 @@ pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> { macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident, $S:expr) => { - #[cfg(stage0)] - impl fmt::Show for RadixFmt<$T, Radix> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } - } - - #[cfg(not(stage0))] impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(fmt::String::fmt(self, f)); @@ -188,14 +179,6 @@ macro_rules! int_base { macro_rules! show { ($T:ident with $S:expr) => { - #[cfg(stage0)] - impl fmt::Show for $T { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } - } - - #[cfg(not(stage0))] impl fmt::Show for $T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(fmt::String::fmt(self, f)); diff --git a/src/libcore/fmt/rt.rs b/src/libcore/fmt/rt.rs index 6dbda3d8445..8d8e8c4b703 100644 --- a/src/libcore/fmt/rt.rs +++ b/src/libcore/fmt/rt.rs @@ -14,7 +14,7 @@ //! These definitions are similar to their `ct` equivalents, but differ in that //! these can be statically allocated and are slightly optimized for the runtime -#![experimental = "implementation detail of the `format_args!` macro"] +#![unstable = "implementation detail of the `format_args!` macro"] pub use self::Alignment::*; pub use self::Count::*; diff --git a/src/libcore/hash/mod.rs b/src/libcore/hash/mod.rs index d8b9cf9594d..a82ea009e13 100644 --- a/src/libcore/hash/mod.rs +++ b/src/libcore/hash/mod.rs @@ -16,8 +16,7 @@ //! # Examples //! //! ```rust -//! use std::hash; -//! use std::hash::Hash; +//! use std::hash::{hash, Hash, SipHasher}; //! //! #[derive(Hash)] //! struct Person { @@ -29,16 +28,14 @@ //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; //! -//! assert!(hash::hash(&person1) != hash::hash(&person2)); +//! assert!(hash::<_, SipHasher>(&person1) != hash::<_, SipHasher>(&person2)); //! ``` //! //! If you need more control over how a value is hashed, you need to implement //! the trait `Hash`: //! //! ```rust -//! use std::hash; -//! use std::hash::Hash; -//! use std::hash::sip::SipState; +//! use std::hash::{hash, Hash, Hasher, Writer, SipHasher}; //! //! struct Person { //! id: uint, @@ -46,8 +43,8 @@ //! phone: u64, //! } //! -//! impl Hash for Person { -//! fn hash(&self, state: &mut SipState) { +//! impl<H: Hasher + Writer> Hash<H> for Person { +//! fn hash(&self, state: &mut H) { //! self.id.hash(state); //! self.phone.hash(state); //! } @@ -56,186 +53,382 @@ //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; //! -//! assert!(hash::hash(&person1) == hash::hash(&person2)); +//! assert_eq!(hash::<_, SipHasher>(&person1), hash::<_, SipHasher>(&person2)); //! ``` -#![allow(unused_must_use)] +#![unstable = "module was recently redesigned"] -use prelude::*; +use default::Default; -use borrow::{Cow, ToOwned}; -use intrinsics::TypeId; -use mem; -use num::Int; +pub use self::sip::SipHasher; -/// Reexport the `sip::hash` function as our default hasher. -pub use self::sip::hash as hash; +mod sip; -pub mod sip; +/// A hashable type. +/// +/// The `H` type parameter is an abstract hash state that is used by the `Hash` +/// to compute the hash. Specific implementations of this trait may specialize +/// for particular instances of `H` in order to be able to optimize the hashing +/// behavior. +#[cfg(stage0)] +pub trait Hash<H> { + /// Feeds this value into the state given, updating the hasher as necessary. + fn hash(&self, state: &mut H); +} -/// A hashable type. The `S` type parameter is an abstract hash state that is -/// used by the `Hash` to compute the hash. It defaults to -/// `std::hash::sip::SipState`. -pub trait Hash<S = sip::SipState> { - /// Computes the hash of a value. - fn hash(&self, state: &mut S); +/// A hashable type. +/// +/// The `H` type parameter is an abstract hash state that is used by the `Hash` +/// to compute the hash. Specific implementations of this trait may specialize +/// for particular instances of `H` in order to be able to optimize the hashing +/// behavior. +#[cfg(not(stage0))] +pub trait Hash<H: Hasher> { + /// Feeds this value into the state given, updating the hasher as necessary. + fn hash(&self, state: &mut H); } -/// A trait that computes a hash for a value. The main users of this trait are -/// containers like `HashMap`, which need a generic way hash multiple types. -pub trait Hasher<S> { - /// Compute the hash of a value. - fn hash<T: ?Sized + Hash<S>>(&self, value: &T) -> u64; +/// A trait which represents the ability to hash an arbitrary stream of bytes. +pub trait Hasher { + /// Result type of one run of hashing generated by this hasher. + type Output; + + /// Resets this hasher back to its initial state (as if it were just + /// created). + fn reset(&mut self); + + /// Completes a round of hashing, producing the output hash generated. + fn finish(&self) -> Self::Output; } +/// A common bound on the `Hasher` parameter to `Hash` implementations in order +/// to generically hash an aggregate. +#[experimental = "this trait will likely be replaced by io::Writer"] #[allow(missing_docs)] pub trait Writer { fn write(&mut self, bytes: &[u8]); } +/// Hash a value with the default SipHasher algorithm (two initial keys of 0). +/// +/// The specified value will be hashed with this hasher and then the resulting +/// hash will be returned. +pub fn hash<T: Hash<H>, H: Hasher + Default>(value: &T) -> H::Output { + let mut h: H = Default::default(); + value.hash(&mut h); + h.finish() +} + ////////////////////////////////////////////////////////////////////////////// -macro_rules! impl_hash { - ($ty:ident, $uty:ident) => { - impl<S: Writer> Hash<S> for $ty { - #[inline] - fn hash(&self, state: &mut S) { - let a: [u8; ::$ty::BYTES] = unsafe { - mem::transmute((*self as $uty).to_le() as $ty) - }; - state.write(a.as_slice()) +#[cfg(stage0)] +mod impls { + use prelude::*; + + use borrow::{Cow, ToOwned}; + use intrinsics::TypeId; + use mem; + use super::{Hash, Writer}; + use num::Int; + + macro_rules! impl_hash { + ($ty:ident, $uty:ident) => { + impl<S: Writer> Hash<S> for $ty { + #[inline] + fn hash(&self, state: &mut S) { + let a: [u8; ::$ty::BYTES] = unsafe { + mem::transmute((*self as $uty).to_le() as $ty) + }; + state.write(a.as_slice()) + } } } } -} -impl_hash! { u8, u8 } -impl_hash! { u16, u16 } -impl_hash! { u32, u32 } -impl_hash! { u64, u64 } -impl_hash! { uint, uint } -impl_hash! { i8, u8 } -impl_hash! { i16, u16 } -impl_hash! { i32, u32 } -impl_hash! { i64, u64 } -impl_hash! { int, uint } - -impl<S: Writer> Hash<S> for bool { - #[inline] - fn hash(&self, state: &mut S) { - (*self as u8).hash(state); + impl_hash! { u8, u8 } + impl_hash! { u16, u16 } + impl_hash! { u32, u32 } + impl_hash! { u64, u64 } + impl_hash! { uint, uint } + impl_hash! { i8, u8 } + impl_hash! { i16, u16 } + impl_hash! { i32, u32 } + impl_hash! { i64, u64 } + impl_hash! { int, uint } + + impl<S: Writer> Hash<S> for bool { + #[inline] + fn hash(&self, state: &mut S) { + (*self as u8).hash(state); + } } -} -impl<S: Writer> Hash<S> for char { - #[inline] - fn hash(&self, state: &mut S) { - (*self as u32).hash(state); + impl<S: Writer> Hash<S> for char { + #[inline] + fn hash(&self, state: &mut S) { + (*self as u32).hash(state); + } } -} -impl<S: Writer> Hash<S> for str { - #[inline] - fn hash(&self, state: &mut S) { - state.write(self.as_bytes()); - 0xffu8.hash(state) + impl<S: Writer> Hash<S> for str { + #[inline] + fn hash(&self, state: &mut S) { + state.write(self.as_bytes()); + 0xffu8.hash(state) + } } -} -macro_rules! impl_hash_tuple { - () => ( - impl<S: Writer> Hash<S> for () { - #[inline] - fn hash(&self, state: &mut S) { - state.write(&[]); + macro_rules! impl_hash_tuple { + () => ( + impl<S> Hash<S> for () { + #[inline] + fn hash(&self, _state: &mut S) {} } - } - ); - - ( $($name:ident)+) => ( - impl<S: Writer, $($name: Hash<S>),*> Hash<S> for ($($name,)*) { - #[inline] - #[allow(non_snake_case)] - fn hash(&self, state: &mut S) { - match *self { - ($(ref $name,)*) => { - $( - $name.hash(state); - )* + ); + + ( $($name:ident)+) => ( + impl<S, $($name: Hash<S>),*> Hash<S> for ($($name,)*) { + #[inline] + #[allow(non_snake_case)] + fn hash(&self, state: &mut S) { + match *self { + ($(ref $name,)*) => { + $( + $name.hash(state); + )* + } } } } + ); + } + + impl_hash_tuple! {} + impl_hash_tuple! { A } + impl_hash_tuple! { A B } + impl_hash_tuple! { A B C } + impl_hash_tuple! { A B C D } + impl_hash_tuple! { A B C D E } + impl_hash_tuple! { A B C D E F } + impl_hash_tuple! { A B C D E F G } + impl_hash_tuple! { A B C D E F G H } + impl_hash_tuple! { A B C D E F G H I } + impl_hash_tuple! { A B C D E F G H I J } + impl_hash_tuple! { A B C D E F G H I J K } + impl_hash_tuple! { A B C D E F G H I J K L } + + impl<S: Writer, T: Hash<S>> Hash<S> for [T] { + #[inline] + fn hash(&self, state: &mut S) { + self.len().hash(state); + for elt in self.iter() { + elt.hash(state); + } } - ); -} + } + -impl_hash_tuple! {} -impl_hash_tuple! { A } -impl_hash_tuple! { A B } -impl_hash_tuple! { A B C } -impl_hash_tuple! { A B C D } -impl_hash_tuple! { A B C D E } -impl_hash_tuple! { A B C D E F } -impl_hash_tuple! { A B C D E F G } -impl_hash_tuple! { A B C D E F G H } -impl_hash_tuple! { A B C D E F G H I } -impl_hash_tuple! { A B C D E F G H I J } -impl_hash_tuple! { A B C D E F G H I J K } -impl_hash_tuple! { A B C D E F G H I J K L } - -impl<S: Writer, T: Hash<S>> Hash<S> for [T] { - #[inline] - fn hash(&self, state: &mut S) { - self.len().hash(state); - for elt in self.iter() { - elt.hash(state); + impl<'a, S, T: ?Sized + Hash<S>> Hash<S> for &'a T { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); } } -} + impl<'a, S, T: ?Sized + Hash<S>> Hash<S> for &'a mut T { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); + } + } -impl<'a, S: Writer, T: ?Sized + Hash<S>> Hash<S> for &'a T { - #[inline] - fn hash(&self, state: &mut S) { - (**self).hash(state); + impl<S: Writer, T> Hash<S> for *const T { + #[inline] + fn hash(&self, state: &mut S) { + // NB: raw-pointer Hash does _not_ dereference + // to the target; it just gives you the pointer-bytes. + (*self as uint).hash(state); + } } -} -impl<'a, S: Writer, T: ?Sized + Hash<S>> Hash<S> for &'a mut T { - #[inline] - fn hash(&self, state: &mut S) { - (**self).hash(state); + impl<S: Writer, T> Hash<S> for *mut T { + #[inline] + fn hash(&self, state: &mut S) { + // NB: raw-pointer Hash does _not_ dereference + // to the target; it just gives you the pointer-bytes. + (*self as uint).hash(state); + } } -} -impl<S: Writer, T> Hash<S> for *const T { - #[inline] - fn hash(&self, state: &mut S) { - // NB: raw-pointer Hash does _not_ dereference - // to the target; it just gives you the pointer-bytes. - (*self as uint).hash(state); + impl<S: Writer> Hash<S> for TypeId { + #[inline] + fn hash(&self, state: &mut S) { + self.hash().hash(state) + } } -} -impl<S: Writer, T> Hash<S> for *mut T { - #[inline] - fn hash(&self, state: &mut S) { - // NB: raw-pointer Hash does _not_ dereference - // to the target; it just gives you the pointer-bytes. - (*self as uint).hash(state); + impl<'a, T, B: ?Sized, S> Hash<S> for Cow<'a, T, B> + where B: Hash<S> + ToOwned<T> + { + #[inline] + fn hash(&self, state: &mut S) { + Hash::hash(&**self, state) + } } } -impl<S: Writer> Hash<S> for TypeId { - #[inline] - fn hash(&self, state: &mut S) { - self.hash().hash(state) +#[cfg(not(stage0))] +mod impls { + use prelude::*; + + use borrow::{Cow, ToOwned}; + use intrinsics::TypeId; + use mem; + use super::{Hash, Writer, Hasher}; + use num::Int; + + macro_rules! impl_hash { + ($ty:ident, $uty:ident) => { + impl<S: Writer + Hasher> Hash<S> for $ty { + #[inline] + fn hash(&self, state: &mut S) { + let a: [u8; ::$ty::BYTES] = unsafe { + mem::transmute((*self as $uty).to_le() as $ty) + }; + state.write(a.as_slice()) + } + } + } + } + + impl_hash! { u8, u8 } + impl_hash! { u16, u16 } + impl_hash! { u32, u32 } + impl_hash! { u64, u64 } + impl_hash! { uint, uint } + impl_hash! { i8, u8 } + impl_hash! { i16, u16 } + impl_hash! { i32, u32 } + impl_hash! { i64, u64 } + impl_hash! { int, uint } + + impl<S: Writer + Hasher> Hash<S> for bool { + #[inline] + fn hash(&self, state: &mut S) { + (*self as u8).hash(state); + } + } + + impl<S: Writer + Hasher> Hash<S> for char { + #[inline] + fn hash(&self, state: &mut S) { + (*self as u32).hash(state); + } + } + + impl<S: Writer + Hasher> Hash<S> for str { + #[inline] + fn hash(&self, state: &mut S) { + state.write(self.as_bytes()); + 0xffu8.hash(state) + } + } + + macro_rules! impl_hash_tuple { + () => ( + impl<S: Hasher> Hash<S> for () { + #[inline] + fn hash(&self, _state: &mut S) {} + } + ); + + ( $($name:ident)+) => ( + impl<S: Hasher, $($name: Hash<S>),*> Hash<S> for ($($name,)*) { + #[inline] + #[allow(non_snake_case)] + fn hash(&self, state: &mut S) { + match *self { + ($(ref $name,)*) => { + $( + $name.hash(state); + )* + } + } + } + } + ); + } + + impl_hash_tuple! {} + impl_hash_tuple! { A } + impl_hash_tuple! { A B } + impl_hash_tuple! { A B C } + impl_hash_tuple! { A B C D } + impl_hash_tuple! { A B C D E } + impl_hash_tuple! { A B C D E F } + impl_hash_tuple! { A B C D E F G } + impl_hash_tuple! { A B C D E F G H } + impl_hash_tuple! { A B C D E F G H I } + impl_hash_tuple! { A B C D E F G H I J } + impl_hash_tuple! { A B C D E F G H I J K } + impl_hash_tuple! { A B C D E F G H I J K L } + + impl<S: Writer + Hasher, T: Hash<S>> Hash<S> for [T] { + #[inline] + fn hash(&self, state: &mut S) { + self.len().hash(state); + for elt in self.iter() { + elt.hash(state); + } + } + } + + + impl<'a, S: Hasher, T: ?Sized + Hash<S>> Hash<S> for &'a T { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); + } + } + + impl<'a, S: Hasher, T: ?Sized + Hash<S>> Hash<S> for &'a mut T { + #[inline] + fn hash(&self, state: &mut S) { + (**self).hash(state); + } } -} -impl<'a, T, B: ?Sized, S> Hash<S> for Cow<'a, T, B> where B: Hash<S> + ToOwned<T> { - #[inline] - fn hash(&self, state: &mut S) { - Hash::hash(&**self, state) + impl<S: Writer + Hasher, T> Hash<S> for *const T { + #[inline] + fn hash(&self, state: &mut S) { + // NB: raw-pointer Hash does _not_ dereference + // to the target; it just gives you the pointer-bytes. + (*self as uint).hash(state); + } + } + + impl<S: Writer + Hasher, T> Hash<S> for *mut T { + #[inline] + fn hash(&self, state: &mut S) { + // NB: raw-pointer Hash does _not_ dereference + // to the target; it just gives you the pointer-bytes. + (*self as uint).hash(state); + } + } + + impl<S: Writer + Hasher> Hash<S> for TypeId { + #[inline] + fn hash(&self, state: &mut S) { + self.hash().hash(state) + } + } + + impl<'a, T, B: ?Sized, S: Hasher> Hash<S> for Cow<'a, T, B> + where B: Hash<S> + ToOwned<T> + { + #[inline] + fn hash(&self, state: &mut S) { + Hash::hash(&**self, state) + } } } diff --git a/src/libcore/hash/sip.rs b/src/libcore/hash/sip.rs index c4d45e9c2c8..c20fb8457d2 100644 --- a/src/libcore/hash/sip.rs +++ b/src/libcore/hash/sip.rs @@ -11,27 +11,27 @@ // ignore-lexer-test FIXME #15883 //! An implementation of SipHash 2-4. -//! -//! See: http://131002.net/siphash/ -//! -//! Consider this as a main "general-purpose" hash for all hashtables: it -//! runs at good speed (competitive with spooky and city) and permits -//! strong _keyed_ hashing. Key your hashtables from a strong RNG, -//! such as `rand::Rng`. -//! -//! Although the SipHash algorithm is considered to be cryptographically -//! strong, this implementation has not been reviewed for such purposes. -//! As such, all cryptographic uses of this implementation are strongly -//! discouraged. use prelude::*; use default::Default; -use super::{Hash, Hasher, Writer}; - -/// `SipState` computes a SipHash 2-4 hash over a stream of bytes. -#[derive(Copy)] -pub struct SipState { +use super::{Hasher, Writer}; + +/// An implementation of SipHash 2-4. +/// +/// See: http://131002.net/siphash/ +/// +/// Consider this as a main "general-purpose" hash for all hashtables: it +/// runs at good speed (competitive with spooky and city) and permits +/// strong _keyed_ hashing. Key your hashtables from a strong RNG, +/// such as `rand::Rng`. +/// +/// Although the SipHash algorithm is considered to be cryptographically +/// strong, this implementation has not been reviewed for such purposes. +/// As such, all cryptographic uses of this implementation are strongly +/// discouraged. +#[allow(missing_copy_implementations)] +pub struct SipHasher { k0: u64, k1: u64, length: uint, // how many bytes we've processed @@ -86,17 +86,17 @@ macro_rules! compress { }) } -impl SipState { - /// Creates a `SipState` that is keyed off the provided keys. +impl SipHasher { + /// Creates a new `SipHasher` with the two initial keys set to 0. #[inline] - pub fn new() -> SipState { - SipState::new_with_keys(0, 0) + pub fn new() -> SipHasher { + SipHasher::new_with_keys(0, 0) } - /// Creates a `SipState` that is keyed off the provided keys. + /// Creates a `SipHasher` that is keyed off the provided keys. #[inline] - pub fn new_with_keys(key0: u64, key1: u64) -> SipState { - let mut state = SipState { + pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher { + let mut state = SipHasher { k0: key0, k1: key1, length: 0, @@ -111,43 +111,12 @@ impl SipState { state } - /// Resets the state to its initial state. - #[inline] - pub fn reset(&mut self) { - self.length = 0; - self.v0 = self.k0 ^ 0x736f6d6570736575; - self.v1 = self.k1 ^ 0x646f72616e646f6d; - self.v2 = self.k0 ^ 0x6c7967656e657261; - self.v3 = self.k1 ^ 0x7465646279746573; - self.ntail = 0; - } - /// Returns the computed hash. - #[inline] - pub fn result(&self) -> u64 { - let mut v0 = self.v0; - let mut v1 = self.v1; - let mut v2 = self.v2; - let mut v3 = self.v3; - - let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; - - v3 ^= b; - compress!(v0, v1, v2, v3); - compress!(v0, v1, v2, v3); - v0 ^= b; - - v2 ^= 0xff; - compress!(v0, v1, v2, v3); - compress!(v0, v1, v2, v3); - compress!(v0, v1, v2, v3); - compress!(v0, v1, v2, v3); - - v0 ^ v1 ^ v2 ^ v3 - } + #[deprecated = "renamed to finish"] + pub fn result(&self) -> u64 { self.finish() } } -impl Writer for SipState { +impl Writer for SipHasher { #[inline] fn write(&mut self, msg: &[u8]) { let length = msg.len(); @@ -195,355 +164,60 @@ impl Writer for SipState { } } -#[stable] -impl Clone for SipState { - #[inline] - fn clone(&self) -> SipState { - *self - } -} +impl Hasher for SipHasher { + type Output = u64; -#[stable] -impl Default for SipState { - #[inline] - #[stable] - fn default() -> SipState { - SipState::new() + fn reset(&mut self) { + self.length = 0; + self.v0 = self.k0 ^ 0x736f6d6570736575; + self.v1 = self.k1 ^ 0x646f72616e646f6d; + self.v2 = self.k0 ^ 0x6c7967656e657261; + self.v3 = self.k1 ^ 0x7465646279746573; + self.ntail = 0; } -} -/// `SipHasher` computes the SipHash algorithm from a stream of bytes. -#[derive(Clone)] -#[allow(missing_copy_implementations)] -pub struct SipHasher { - k0: u64, - k1: u64, -} + fn finish(&self) -> u64 { + let mut v0 = self.v0; + let mut v1 = self.v1; + let mut v2 = self.v2; + let mut v3 = self.v3; -impl SipHasher { - /// Creates a `Sip`. - #[inline] - pub fn new() -> SipHasher { - SipHasher::new_with_keys(0, 0) - } + let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; - /// Creates a `Sip` that is keyed off the provided keys. - #[inline] - pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher { - SipHasher { - k0: key0, - k1: key1, - } + v3 ^= b; + compress!(v0, v1, v2, v3); + compress!(v0, v1, v2, v3); + v0 ^= b; + + v2 ^= 0xff; + compress!(v0, v1, v2, v3); + compress!(v0, v1, v2, v3); + compress!(v0, v1, v2, v3); + compress!(v0, v1, v2, v3); + + v0 ^ v1 ^ v2 ^ v3 } } -impl Hasher<SipState> for SipHasher { +impl Clone for SipHasher { #[inline] - fn hash<T: ?Sized + Hash<SipState>>(&self, value: &T) -> u64 { - let mut state = SipState::new_with_keys(self.k0, self.k1); - value.hash(&mut state); - state.result() + fn clone(&self) -> SipHasher { + SipHasher { + k0: self.k0, + k1: self.k1, + length: self.length, + v0: self.v0, + v1: self.v1, + v2: self.v2, + v3: self.v3, + tail: self.tail, + ntail: self.ntail, + } } } impl Default for SipHasher { - #[inline] fn default() -> SipHasher { SipHasher::new() } } - -/// Hashes a value using the SipHash algorithm. -#[inline] -pub fn hash<T: ?Sized + Hash<SipState>>(value: &T) -> u64 { - let mut state = SipState::new(); - value.hash(&mut state); - state.result() -} - -/// Hashes a value with the SipHash algorithm with the provided keys. -#[inline] -pub fn hash_with_keys<T: ?Sized + Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 { - let mut state = SipState::new_with_keys(k0, k1); - value.hash(&mut state); - state.result() -} - -#[cfg(test)] -mod tests { - use test::Bencher; - use prelude::*; - use std::fmt; - - use super::super::{Hash, Writer}; - use super::{SipState, hash, hash_with_keys}; - - // Hash just the bytes of the slice, without length prefix - struct Bytes<'a>(&'a [u8]); - - impl<'a, S: Writer> Hash<S> for Bytes<'a> { - #[allow(unused_must_use)] - fn hash(&self, state: &mut S) { - let Bytes(v) = *self; - state.write(v); - } - } - - #[test] - #[allow(unused_must_use)] - fn test_siphash() { - let vecs : [[u8; 8]; 64] = [ - [ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ], - [ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ], - [ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ], - [ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ], - [ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ], - [ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ], - [ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ], - [ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ], - [ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ], - [ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ], - [ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ], - [ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ], - [ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ], - [ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ], - [ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ], - [ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ], - [ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ], - [ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ], - [ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ], - [ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ], - [ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ], - [ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ], - [ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ], - [ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ], - [ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ], - [ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ], - [ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ], - [ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ], - [ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ], - [ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ], - [ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ], - [ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ], - [ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ], - [ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ], - [ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ], - [ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ], - [ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ], - [ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ], - [ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ], - [ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ], - [ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ], - [ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ], - [ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ], - [ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ], - [ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ], - [ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ], - [ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ], - [ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ], - [ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ], - [ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ], - [ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ], - [ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ], - [ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ], - [ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ], - [ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ], - [ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ], - [ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ], - [ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ], - [ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ], - [ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ], - [ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ], - [ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ], - [ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ], - [ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ] - ]; - - let k0 = 0x_07_06_05_04_03_02_01_00_u64; - let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64; - let mut buf = Vec::new(); - let mut t = 0; - let mut state_inc = SipState::new_with_keys(k0, k1); - let mut state_full = SipState::new_with_keys(k0, k1); - - fn to_hex_str(r: &[u8; 8]) -> String { - let mut s = String::new(); - for b in r.iter() { - s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice()); - } - s - } - - fn result_bytes(h: u64) -> Vec<u8> { - vec![(h >> 0) as u8, - (h >> 8) as u8, - (h >> 16) as u8, - (h >> 24) as u8, - (h >> 32) as u8, - (h >> 40) as u8, - (h >> 48) as u8, - (h >> 56) as u8, - ] - } - - fn result_str(h: u64) -> String { - let r = result_bytes(h); - let mut s = String::new(); - for b in r.iter() { - s.push_str(format!("{}", fmt::radix(*b, 16)).as_slice()); - } - s - } - - while t < 64 { - debug!("siphash test {}: {}", t, buf); - let vec = u8to64_le!(vecs[t], 0); - let out = hash_with_keys(k0, k1, &Bytes(buf.as_slice())); - debug!("got {}, expected {}", out, vec); - assert_eq!(vec, out); - - state_full.reset(); - state_full.write(buf.as_slice()); - let f = result_str(state_full.result()); - let i = result_str(state_inc.result()); - let v = to_hex_str(&vecs[t]); - debug!("{}: ({}) => inc={} full={}", t, v, i, f); - - assert_eq!(f, i); - assert_eq!(f, v); - - buf.push(t as u8); - state_inc.write(&[t as u8]); - - t += 1; - } - } - - #[test] #[cfg(target_arch = "aarch64")] - fn test_hash_uint() { - let val = 0xdeadbeef_deadbeef_u64; - assert_eq!(hash(&(val as u64)), hash(&(val as uint))); - assert!(hash(&(val as u32)) != hash(&(val as uint))); - } - #[test] #[cfg(target_arch = "arm")] - fn test_hash_uint() { - let val = 0xdeadbeef_deadbeef_u64; - assert!(hash(&(val as u64)) != hash(&(val as uint))); - assert_eq!(hash(&(val as u32)), hash(&(val as uint))); - } - #[test] #[cfg(target_arch = "x86_64")] - fn test_hash_uint() { - let val = 0xdeadbeef_deadbeef_u64; - assert_eq!(hash(&(val as u64)), hash(&(val as uint))); - assert!(hash(&(val as u32)) != hash(&(val as uint))); - } - #[test] #[cfg(target_arch = "x86")] - fn test_hash_uint() { - let val = 0xdeadbeef_deadbeef_u64; - assert!(hash(&(val as u64)) != hash(&(val as uint))); - assert_eq!(hash(&(val as u32)), hash(&(val as uint))); - } - - #[test] - fn test_hash_idempotent() { - let val64 = 0xdeadbeef_deadbeef_u64; - assert_eq!(hash(&val64), hash(&val64)); - let val32 = 0xdeadbeef_u32; - assert_eq!(hash(&val32), hash(&val32)); - } - - #[test] - fn test_hash_no_bytes_dropped_64() { - let val = 0xdeadbeef_deadbeef_u64; - - assert!(hash(&val) != hash(&zero_byte(val, 0))); - assert!(hash(&val) != hash(&zero_byte(val, 1))); - assert!(hash(&val) != hash(&zero_byte(val, 2))); - assert!(hash(&val) != hash(&zero_byte(val, 3))); - assert!(hash(&val) != hash(&zero_byte(val, 4))); - assert!(hash(&val) != hash(&zero_byte(val, 5))); - assert!(hash(&val) != hash(&zero_byte(val, 6))); - assert!(hash(&val) != hash(&zero_byte(val, 7))); - - fn zero_byte(val: u64, byte: uint) -> u64 { - assert!(byte < 8); - val & !(0xff << (byte * 8)) - } - } - - #[test] - fn test_hash_no_bytes_dropped_32() { - let val = 0xdeadbeef_u32; - - assert!(hash(&val) != hash(&zero_byte(val, 0))); - assert!(hash(&val) != hash(&zero_byte(val, 1))); - assert!(hash(&val) != hash(&zero_byte(val, 2))); - assert!(hash(&val) != hash(&zero_byte(val, 3))); - - fn zero_byte(val: u32, byte: uint) -> u32 { - assert!(byte < 4); - val & !(0xff << (byte * 8)) - } - } - - #[test] - fn test_hash_no_concat_alias() { - let s = ("aa", "bb"); - let t = ("aabb", ""); - let u = ("a", "abb"); - - assert!(s != t && t != u); - assert!(hash(&s) != hash(&t) && hash(&s) != hash(&u)); - - let v: (&[u8], &[u8], &[u8]) = (&[1u8], &[0u8, 0], &[0u8]); - let w: (&[u8], &[u8], &[u8]) = (&[1u8, 0, 0, 0], &[], &[]); - - assert!(v != w); - assert!(hash(&v) != hash(&w)); - } - - #[bench] - fn bench_str_under_8_bytes(b: &mut Bencher) { - let s = "foo"; - b.iter(|| { - assert_eq!(hash(&s), 16262950014981195938); - }) - } - - #[bench] - fn bench_str_of_8_bytes(b: &mut Bencher) { - let s = "foobar78"; - b.iter(|| { - assert_eq!(hash(&s), 4898293253460910787); - }) - } - - #[bench] - fn bench_str_over_8_bytes(b: &mut Bencher) { - let s = "foobarbaz0"; - b.iter(|| { - assert_eq!(hash(&s), 10581415515220175264); - }) - } - - #[bench] - fn bench_long_str(b: &mut Bencher) { - let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor \ -incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \ -exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute \ -irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla \ -pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui \ -officia deserunt mollit anim id est laborum."; - b.iter(|| { - assert_eq!(hash(&s), 17717065544121360093); - }) - } - - #[bench] - fn bench_u64(b: &mut Bencher) { - let u = 16262950014981195938u64; - b.iter(|| { - assert_eq!(hash(&u), 5254097107239593357); - }) - } -} diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 822416a387e..5924d515dda 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -39,9 +39,12 @@ //! guaranteed to happen in order. This is the standard mode for working //! with atomic types and is equivalent to Java's `volatile`. -#![experimental] +#![unstable] #![allow(missing_docs)] +#[cfg(not(stage0))] +use marker::Sized; + pub type GlueFn = extern "Rust" fn(*const i8); #[lang="ty_desc"] @@ -200,6 +203,10 @@ extern "rust-intrinsic" { /// Gets an identifier which is globally unique to the specified type. This /// function will return the same value for a type regardless of whichever /// crate it is invoked in. + #[cfg(not(stage0))] + pub fn type_id<T: ?Sized + 'static>() -> TypeId; + + #[cfg(stage0)] pub fn type_id<T: 'static>() -> TypeId; /// Create a value initialized to zero. @@ -326,7 +333,7 @@ extern "rust-intrinsic" { /// Invokes memset on the specified pointer, setting `count * size_of::<T>()` /// bytes of memory starting at `dst` to `c`. - #[experimental = "uncertain about naming and semantics"] + #[unstable = "uncertain about naming and semantics"] pub fn set_memory<T>(dst: *mut T, val: u8, count: uint); /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with @@ -551,8 +558,15 @@ pub struct TypeId { impl TypeId { /// Returns the `TypeId` of the type this generic function has been instantiated with + #[cfg(not(stage0))] + pub fn of<T: ?Sized + 'static>() -> TypeId { + unsafe { type_id::<T>() } + } + + #[cfg(stage0)] pub fn of<T: 'static>() -> TypeId { unsafe { type_id::<T>() } } + pub fn hash(&self) -> u64 { self.t } } diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index d30cfc405a1..d4aa4c99a76 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -942,7 +942,7 @@ pub trait IteratorExt: Iterator + Sized { } /// Use an iterator to reverse a container in place. - #[experimental = "uncertain about placement or widespread use"] + #[unstable = "uncertain about placement or widespread use"] fn reverse_in_place<'a, T: 'a>(&mut self) where Self: Iterator<Item=&'a mut T> + DoubleEndedIterator { @@ -974,7 +974,7 @@ pub trait DoubleEndedIterator: Iterator { /// Calling `next()` or `next_back()` on a `RandomAccessIterator` /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)` /// after `it.next()` is called. -#[experimental = "not widely used, may be better decomposed into Index and ExactSizeIterator"] +#[unstable = "not widely used, may be better decomposed into Index and ExactSizeIterator"] pub trait RandomAccessIterator: Iterator { /// Return the number of indexable elements. At most `std::uint::MAX` /// elements are indexable, even if the iterator represents a longer range. @@ -1049,7 +1049,7 @@ impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator { fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Rev<I> where I: DoubleEndedIterator + RandomAccessIterator { #[inline] fn indexable(&self) -> uint { self.iter.indexable() } @@ -1084,7 +1084,7 @@ impl<'a, I> DoubleEndedIterator for ByRef<'a, I> where I: 'a + DoubleEndedIterat } /// A trait for iterators over elements which can be added together -#[experimental = "needs to be re-evaluated as part of numerics reform"] +#[unstable = "needs to be re-evaluated as part of numerics reform"] pub trait AdditiveIterator<A> { /// Iterates over the entire iterator, summing up all the elements /// @@ -1102,7 +1102,7 @@ pub trait AdditiveIterator<A> { macro_rules! impl_additive { ($A:ty, $init:expr) => { - #[experimental = "trait is experimental"] + #[unstable = "trait is experimental"] impl<T: Iterator<Item=$A>> AdditiveIterator<$A> for T { #[inline] fn sum(self) -> $A { @@ -1125,7 +1125,7 @@ impl_additive! { f32, 0.0 } impl_additive! { f64, 0.0 } /// A trait for iterators over elements which can be multiplied together. -#[experimental = "needs to be re-evaluated as part of numerics reform"] +#[unstable = "needs to be re-evaluated as part of numerics reform"] pub trait MultiplicativeIterator<A> { /// Iterates over the entire iterator, multiplying all the elements /// @@ -1146,7 +1146,7 @@ pub trait MultiplicativeIterator<A> { macro_rules! impl_multiplicative { ($A:ty, $init:expr) => { - #[experimental = "trait is experimental"] + #[unstable = "trait is experimental"] impl<T: Iterator<Item=$A>> MultiplicativeIterator<$A> for T { #[inline] fn product(self) -> $A { @@ -1287,7 +1287,7 @@ impl<I> Iterator for Cycle<I> where I: Clone + Iterator { } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Cycle<I> where I: Clone + RandomAccessIterator, { @@ -1372,7 +1372,7 @@ impl<T, A, B> DoubleEndedIterator for Chain<A, B> where } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<T, A, B> RandomAccessIterator for Chain<A, B> where A: RandomAccessIterator<Item=T>, B: RandomAccessIterator<Item=T>, @@ -1464,7 +1464,7 @@ impl<T, U, A, B> DoubleEndedIterator for Zip<A, B> where } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<T, U, A, B> RandomAccessIterator for Zip<A, B> where A: RandomAccessIterator<Item=T>, B: RandomAccessIterator<Item=U>, @@ -1546,7 +1546,7 @@ impl<A, B, I, F> DoubleEndedIterator for Map<A, B, I, F> where } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<A, B, I, F> RandomAccessIterator for Map<A, B, I, F> where I: RandomAccessIterator<Item=A>, F: FnMut(A) -> B, @@ -1735,7 +1735,7 @@ impl<I> DoubleEndedIterator for Enumerate<I> where } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Enumerate<I> where I: RandomAccessIterator { #[inline] fn indexable(&self) -> uint { @@ -1961,7 +1961,7 @@ impl<I> Iterator for Skip<I> where I: Iterator { } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Skip<I> where I: RandomAccessIterator{ #[inline] fn indexable(&self) -> uint { @@ -2016,7 +2016,7 @@ impl<I> Iterator for Take<I> where I: Iterator{ } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Take<I> where I: RandomAccessIterator{ #[inline] fn indexable(&self) -> uint { @@ -2229,7 +2229,7 @@ impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator { } // Allow RandomAccessIterators to be fused without affecting random-access behavior -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<I> RandomAccessIterator for Fuse<I> where I: RandomAccessIterator { #[inline] fn indexable(&self) -> uint { @@ -2246,7 +2246,7 @@ impl<I> Fuse<I> { /// Resets the fuse such that the next call to .next() or .next_back() will /// call the underlying iterator again even if it previously returned None. #[inline] - #[experimental = "seems marginal"] + #[unstable = "seems marginal"] pub fn reset_fuse(&mut self) { self.done = false } @@ -2315,7 +2315,7 @@ impl<A, I, F> DoubleEndedIterator for Inspect<A, I, F> where } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where I: RandomAccessIterator<Item=A>, F: FnMut(&A), @@ -2344,7 +2344,7 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where /// /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`. /// // You can simply change `u32` to `u64` in this line if you want higher values than that. -/// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&(ref mut x2, ref mut x1)| { +/// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&mut (ref mut x2, ref mut x1)| { /// // Attempt to get the next Fibonacci number /// // `x1` will be `None` if previously overflowed. /// let next = match (*x2, *x1) { @@ -2364,7 +2364,7 @@ impl<A, I, F> RandomAccessIterator for Inspect<A, I, F> where /// println!("{}", i); /// } /// ``` -#[experimental] +#[unstable] pub struct Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { f: F, /// Internal state that will be passed to the closure on the next iteration @@ -2385,7 +2385,7 @@ impl<A, St, F> Clone for Unfold<A, St, F> where } } -#[experimental] +#[unstable] impl<A, St, F> Unfold<A, St, F> where F: FnMut(&mut St) -> Option<A> { /// Creates a new iterator with the specified closure as the "iterator /// function" and an initial state to eventually pass to the closure @@ -2749,9 +2749,9 @@ macro_rules! step_impl_no_between { } step_impl!(uint u8 u16 u32 int i8 i16 i32); -#[cfg(target_word_size = "64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] step_impl!(u64 i64); -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] step_impl_no_between!(u64 i64); @@ -2778,7 +2778,7 @@ impl<A: Clone> DoubleEndedIterator for Repeat<A> { fn next_back(&mut self) -> Option<A> { self.idx(0) } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<A: Clone> RandomAccessIterator for Repeat<A> { #[inline] fn indexable(&self) -> uint { uint::MAX } @@ -2790,12 +2790,12 @@ type IterateState<T, F> = (F, Option<T>, bool); /// An iterator that repeatedly applies a given function, starting /// from a given seed value. -#[experimental] +#[unstable] pub type Iterate<T, F> = Unfold<T, IterateState<T, F>, fn(&mut IterateState<T, F>) -> Option<T>>; /// Create a new iterator that produces an infinite sequence of /// repeated applications of the given function `f`. -#[experimental] +#[unstable] pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where T: Clone, F: FnMut(T) -> T, @@ -2804,7 +2804,7 @@ pub fn iterate<T, F>(seed: T, f: F) -> Iterate<T, F> where T: Clone, F: FnMut(T) -> T, { - let &(ref mut f, ref mut val, ref mut first) = st; + let &mut (ref mut f, ref mut val, ref mut first) = st; if *first { *first = false; } else { diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index a7e3b61b0d4..28f8cf588be 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -48,7 +48,8 @@ // separate crate, libcoretest, to avoid bizarre issues. #![crate_name = "core"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", @@ -57,9 +58,11 @@ #![no_std] #![allow(unknown_features, raw_pointer_derive)] -#![feature(intrinsics, lang_items)] +#![cfg_attr(stage0, allow(unused_attributes))] +#![allow(unknown_features)] #![feature(intrinsics, lang_items)] #![feature(simd, unsafe_destructor, slicing_syntax)] #![feature(unboxed_closures)] +#![allow(unknown_features)] #![feature(int_uint)] #![deny(missing_docs)] #[macro_use] @@ -78,12 +81,14 @@ mod int_macros; 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; #[path = "num/u32.rs"] pub mod u32; @@ -146,8 +151,6 @@ mod core { mod std { pub use clone; pub use cmp; - #[cfg(stage0)] - pub use marker as kinds; pub use marker; pub use option; pub use fmt; diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index bfe88fff22f..f6415518864 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -15,7 +15,7 @@ macro_rules! panic { panic!("explicit panic") ); ($msg:expr) => ({ - static _MSG_FILE_LINE: (&'static str, &'static str, uint) = ($msg, file!(), line!()); + static _MSG_FILE_LINE: (&'static str, &'static str, usize) = ($msg, file!(), line!()); ::core::panicking::panic(&_MSG_FILE_LINE) }); ($fmt:expr, $($arg:tt)*) => ({ @@ -23,7 +23,7 @@ macro_rules! panic { // used inside a dead function. Just `#[allow(dead_code)]` is // insufficient, since the user may have // `#[forbid(dead_code)]` and which cannot be overridden. - static _FILE_LINE: (&'static str, uint) = (file!(), line!()); + static _FILE_LINE: (&'static str, usize) = (file!(), line!()); ::core::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE) }); } diff --git a/src/libcore/nonzero.rs b/src/libcore/nonzero.rs index 087404da624..abaf2529323 100644 --- a/src/libcore/nonzero.rs +++ b/src/libcore/nonzero.rs @@ -32,7 +32,7 @@ unsafe impl Zeroable for u64 {} /// NULL or 0 that might allow certain optimizations. #[lang="non_zero"] #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Show)] -#[experimental] +#[unstable] pub struct NonZero<T: Zeroable>(T); impl<T: Zeroable> NonZero<T> { diff --git a/src/libcore/num/int.rs b/src/libcore/num/int.rs index 91c5e4163f9..065763a0d8e 100644 --- a/src/libcore/num/int.rs +++ b/src/libcore/num/int.rs @@ -8,10 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Operations and constants for architecture-sized signed integers (`int` type) +//! 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. -#![stable] -#![doc(primitive = "int")] +#![deprecated = "replaced by isize"] -#[cfg(target_word_size = "32")] int_module! { int, 32 } -#[cfg(target_word_size = "64")] int_module! { int, 64 } +#[cfg(stage0)] #[cfg(target_word_size = "32")] int_module! { int, 32 } +#[cfg(stage0)] #[cfg(target_word_size = "64")] int_module! { int, 64 } + +#[cfg(not(stage0))] #[cfg(target_pointer_width = "32")] int_module! { int, 32 } +#[cfg(not(stage0))] #[cfg(target_pointer_width = "64")] int_module! { int, 64 } diff --git a/src/libcore/num/isize.rs b/src/libcore/num/isize.rs new file mode 100644 index 00000000000..c1cf3c62131 --- /dev/null +++ b/src/libcore/num/isize.rs @@ -0,0 +1,25 @@ +// 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. +// +// 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. + +//! Operations and constants for pointer-sized signed integers (`isize` type) +//! +//! This type was recently added to replace `int`. The rollout of the +//! new type will gradually take place over the alpha cycle along with +//! the development of clearer conventions around integer types. + +#![stable] +#![doc(primitive = "isize")] + +#[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] +int_module! { isize, 32 } +#[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] +int_module! { isize, 64 } diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 490d8111f46..57415f4331d 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -24,7 +24,7 @@ use iter::IteratorExt; use marker::Copy; use mem::size_of; use ops::{Add, Sub, Mul, Div, Rem, Neg}; -use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr, Index}; +use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; use option::Option; use option::Option::{Some, None}; use str::{FromStr, StrExt}; @@ -496,7 +496,7 @@ uint_impl! { u64 = u64, 64, intrinsics::u64_sub_with_overflow, intrinsics::u64_mul_with_overflow } -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] uint_impl! { uint = u32, 32, intrinsics::ctpop32, intrinsics::ctlz32, @@ -506,7 +506,7 @@ uint_impl! { uint = u32, 32, intrinsics::u32_sub_with_overflow, intrinsics::u32_mul_with_overflow } -#[cfg(target_word_size = "64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] uint_impl! { uint = u64, 64, intrinsics::ctpop64, intrinsics::ctlz64, @@ -601,13 +601,13 @@ int_impl! { i64 = i64, u64, 64, intrinsics::i64_sub_with_overflow, intrinsics::i64_mul_with_overflow } -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] int_impl! { int = i32, u32, 32, intrinsics::i32_add_with_overflow, intrinsics::i32_sub_with_overflow, intrinsics::i32_mul_with_overflow } -#[cfg(target_word_size = "64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] int_impl! { int = i64, u64, 64, intrinsics::i64_add_with_overflow, intrinsics::i64_sub_with_overflow, @@ -726,7 +726,7 @@ impl UnsignedInt for u32 {} impl UnsignedInt for u64 {} /// A generic trait for converting a value to a number. -#[experimental = "trait is likely to be removed"] +#[unstable = "trait is likely to be removed"] pub trait ToPrimitive { /// Converts the value of `self` to an `int`. #[inline] @@ -991,7 +991,7 @@ impl_to_primitive_float! { f32 } impl_to_primitive_float! { f64 } /// A generic trait for converting a number to a value. -#[experimental = "trait is likely to be removed"] +#[unstable = "trait is likely to be removed"] 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. @@ -1073,73 +1073,73 @@ pub trait FromPrimitive : ::marker::Sized { } /// A utility function that just calls `FromPrimitive::from_int`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_int<A: FromPrimitive>(n: int) -> Option<A> { FromPrimitive::from_int(n) } /// A utility function that just calls `FromPrimitive::from_i8`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_i8<A: FromPrimitive>(n: i8) -> Option<A> { FromPrimitive::from_i8(n) } /// A utility function that just calls `FromPrimitive::from_i16`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_i16<A: FromPrimitive>(n: i16) -> Option<A> { FromPrimitive::from_i16(n) } /// A utility function that just calls `FromPrimitive::from_i32`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_i32<A: FromPrimitive>(n: i32) -> Option<A> { FromPrimitive::from_i32(n) } /// A utility function that just calls `FromPrimitive::from_i64`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_i64<A: FromPrimitive>(n: i64) -> Option<A> { FromPrimitive::from_i64(n) } /// A utility function that just calls `FromPrimitive::from_uint`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_uint<A: FromPrimitive>(n: uint) -> Option<A> { FromPrimitive::from_uint(n) } /// A utility function that just calls `FromPrimitive::from_u8`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_u8<A: FromPrimitive>(n: u8) -> Option<A> { FromPrimitive::from_u8(n) } /// A utility function that just calls `FromPrimitive::from_u16`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_u16<A: FromPrimitive>(n: u16) -> Option<A> { FromPrimitive::from_u16(n) } /// A utility function that just calls `FromPrimitive::from_u32`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_u32<A: FromPrimitive>(n: u32) -> Option<A> { FromPrimitive::from_u32(n) } /// A utility function that just calls `FromPrimitive::from_u64`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_u64<A: FromPrimitive>(n: u64) -> Option<A> { FromPrimitive::from_u64(n) } /// A utility function that just calls `FromPrimitive::from_f32`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_f32<A: FromPrimitive>(n: f32) -> Option<A> { FromPrimitive::from_f32(n) } /// A utility function that just calls `FromPrimitive::from_f64`. -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn from_f64<A: FromPrimitive>(n: f64) -> Option<A> { FromPrimitive::from_f64(n) } @@ -1190,13 +1190,13 @@ impl_from_primitive! { f64, to_f64 } /// ``` /// #[inline] -#[experimental = "likely to be removed"] +#[unstable = "likely to be removed"] pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> { NumCast::from(n) } /// An interface for casting between machine scalars. -#[experimental = "trait is likely to be removed"] +#[unstable = "trait is likely to be removed"] pub trait NumCast: ToPrimitive { /// Creates a number from another value that can be converted into a primitive via the /// `ToPrimitive` trait. @@ -1394,20 +1394,20 @@ pub trait Float } /// A generic trait for converting a string with a radix (base) to a value -#[experimental = "might need to return Result"] +#[unstable = "might need to return Result"] pub trait FromStrRadix { fn from_str_radix(str: &str, radix: uint) -> Option<Self>; } /// A utility function that just calls FromStrRadix::from_str_radix. -#[experimental = "might need to return Result"] +#[unstable = "might need to return Result"] pub fn from_str_radix<T: FromStrRadix>(str: &str, radix: uint) -> Option<T> { FromStrRadix::from_str_radix(str, radix) } macro_rules! from_str_radix_float_impl { ($T:ty) => { - #[experimental = "might need to return Result"] + #[unstable = "might need to return Result"] impl FromStr for $T { /// Convert a string in base 10 to a float. /// Accepts an optional decimal exponent. @@ -1440,7 +1440,7 @@ macro_rules! from_str_radix_float_impl { } } - #[experimental = "might need to return Result"] + #[unstable = "might need to return Result"] impl FromStrRadix for $T { /// Convert a string in a given base to a float. /// @@ -1577,7 +1577,7 @@ macro_rules! from_str_radix_float_impl { }; // Parse the exponent as decimal integer - let src = src.index(&(offset..)); + let src = &src[offset..]; let (is_positive, exp) = match src.slice_shift_char() { Some(('-', src)) => (false, src.parse::<uint>()), Some(('+', src)) => (true, src.parse::<uint>()), @@ -1604,7 +1604,7 @@ from_str_radix_float_impl! { f64 } macro_rules! from_str_radix_int_impl { ($T:ty) => { - #[experimental = "might need to return Result"] + #[unstable = "might need to return Result"] impl FromStr for $T { #[inline] fn from_str(src: &str) -> Option<$T> { @@ -1612,7 +1612,7 @@ macro_rules! from_str_radix_int_impl { } } - #[experimental = "might need to return Result"] + #[unstable = "might need to return Result"] impl FromStrRadix for $T { fn from_str_radix(src: &str, radix: uint) -> Option<$T> { assert!(radix >= 2 && radix <= 36, diff --git a/src/libcore/num/uint.rs b/src/libcore/num/uint.rs index 35739f68da9..7931890ca5e 100644 --- a/src/libcore/num/uint.rs +++ b/src/libcore/num/uint.rs @@ -8,9 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Operations and constants for architecture-sized unsigned integers (`uint` type) +//! 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. -#![stable] -#![doc(primitive = "uint")] +#![deprecated = "replaced by usize"] uint_module! { uint, int, ::int::BITS } diff --git a/src/libcore/num/usize.rs b/src/libcore/num/usize.rs new file mode 100644 index 00000000000..5eebcd51a77 --- /dev/null +++ b/src/libcore/num/usize.rs @@ -0,0 +1,20 @@ +// 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. +// +// 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. + +//! Operations and constants for pointer-sized unsigned integers (`usize` type) +//! +//! This type was recently added to replace `uint`. The rollout of the +//! new type will gradually take place over the alpha cycle along with +//! the development of clearer conventions around integer types. + +#![stable] +#![doc(primitive = "usize")] + +uint_module! { usize, isize, ::isize::BITS } diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 4debab91739..ab956587d82 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -65,6 +65,7 @@ use clone::Clone; use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator}; use marker::Sized; use option::Option::{self, Some, None}; +use fmt; /// The `Drop` trait is used to run some code when a value goes out of scope. This /// is sometimes called a 'destructor'. @@ -847,13 +848,20 @@ pub trait IndexMut<Index: ?Sized> { } /// An unbounded range. -#[derive(Copy)] +#[derive(Copy, PartialEq, Eq)] #[lang="full_range"] #[unstable = "API still in development"] pub struct FullRange; +#[unstable = "API still in development"] +impl fmt::Show for FullRange { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt::Show::fmt("..", fmt) + } +} + /// A (half-open) range which is bounded at both ends. -#[derive(Copy)] +#[derive(Copy, PartialEq, Eq)] #[lang="range"] #[unstable = "API still in development"] pub struct Range<Idx> { @@ -904,8 +912,15 @@ impl<Idx: Clone + Step> DoubleEndedIterator for Range<Idx> { #[unstable = "API still in development"] impl<Idx: Clone + Step> ExactSizeIterator for Range<Idx> {} +#[unstable = "API still in development"] +impl<Idx: fmt::Show> fmt::Show for Range<Idx> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{:?}..{:?}", self.start, self.end) + } +} + /// A range which is only bounded below. -#[derive(Copy)] +#[derive(Copy, PartialEq, Eq)] #[lang="range_from"] #[unstable = "API still in development"] pub struct RangeFrom<Idx> { @@ -926,8 +941,15 @@ impl<Idx: Clone + Step> Iterator for RangeFrom<Idx> { } } +#[unstable = "API still in development"] +impl<Idx: fmt::Show> fmt::Show for RangeFrom<Idx> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{:?}..", self.start) + } +} + /// A range which is only bounded above. -#[derive(Copy)] +#[derive(Copy, PartialEq, Eq)] #[lang="range_to"] #[unstable = "API still in development"] pub struct RangeTo<Idx> { @@ -935,6 +957,13 @@ pub struct RangeTo<Idx> { pub end: Idx, } +#[unstable = "API still in development"] +impl<Idx: fmt::Show> fmt::Show for RangeTo<Idx> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "..{:?}", self.end) + } +} + /// The `Deref` trait is used to specify the functionality of dereferencing /// operations like `*v`. diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 272570a0d5b..41eecb4649d 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -66,10 +66,11 @@ //! not (`None`). //! //! ``` +//! # use std::boxed::Box; //! let optional: Option<Box<int>> = None; //! check_optional(&optional); //! -//! let optional: Option<Box<int>> = Some(box 9000); +//! let optional: Option<Box<int>> = Some(Box::new(9000)); //! check_optional(&optional); //! //! fn check_optional(optional: &Option<Box<int>>) { @@ -145,17 +146,17 @@ use self::Option::*; +use clone::Clone; use cmp::{Eq, Ord}; use default::Default; -use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator}; use iter::{ExactSizeIterator}; +use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator}; use mem; -use result::Result; +use ops::{Deref, FnOnce}; use result::Result::{Ok, Err}; -use slice; +use result::Result; use slice::AsSlice; -use clone::Clone; -use ops::{Deref, FnOnce}; +use slice; // Note that this is not a lang item per se, but it has a hidden dependency on // `Iterator`, which is one. The compiler assumes that the `next` method of @@ -476,7 +477,7 @@ impl<T> Option<T> { /// assert_eq!(x.ok_or(0i), Err(0i)); /// ``` #[inline] - #[experimental] + #[unstable] pub fn ok_or<E>(self, err: E) -> Result<T, E> { match self { Some(v) => Ok(v), @@ -497,7 +498,7 @@ impl<T> Option<T> { /// assert_eq!(x.ok_or_else(|| 0i), Err(0i)); /// ``` #[inline] - #[experimental] + #[unstable] pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> { match self { Some(v) => Ok(v), @@ -533,7 +534,7 @@ impl<T> Option<T> { /// ``` /// let mut x = Some(4u); /// match x.iter_mut().next() { - /// Some(&ref mut v) => *v = 42u, + /// Some(&mut ref mut v) => *v = 42u, /// None => {}, /// } /// assert_eq!(x, Some(42)); @@ -762,7 +763,6 @@ impl<T> AsSlice<T> for Option<T> { #[stable] impl<T> Default for Option<T> { - #[stable] #[inline] #[stable] fn default() -> Option<T> { None } diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 20305c3191a..ab1e69f0060 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -46,12 +46,13 @@ //! though unsafely, transformed from one type to the other. //! //! ``` +//! # use std::boxed::Box; //! use std::mem; //! //! unsafe { -//! let my_num: Box<int> = box 10; +//! let my_num: Box<int> = Box::new(10); //! let my_num: *const int = mem::transmute(my_num); -//! let my_speed: Box<int> = box 88; +//! let my_speed: Box<int> = Box::new(88); //! let my_speed: *mut int = mem::transmute(my_speed); //! //! // By taking ownership of the original `Box<T>` though @@ -105,7 +106,7 @@ pub use intrinsics::copy_nonoverlapping_memory; #[unstable] pub use intrinsics::copy_memory; -#[experimental = "uncertain about naming and semantics"] +#[unstable = "uncertain about naming and semantics"] pub use intrinsics::set_memory; diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index 1ad6d43f76f..13a387c7cb0 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -9,7 +9,7 @@ // except according to those terms. #![allow(missing_docs)] -#![experimental] +#![unstable] //! Contains struct definitions for the layout of compiler built-in types. //! diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 95ae6ebfb68..f7421203336 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -383,8 +383,8 @@ impl<T, E> Result<T, E> { /// ``` /// fn mutate(r: &mut Result<int, int>) { /// match r.as_mut() { - /// Ok(&ref mut v) => *v = 42, - /// Err(&ref mut e) => *e = 0, + /// Ok(&mut ref mut v) => *v = 42, + /// Err(&mut ref mut e) => *e = 0, /// } /// } /// @@ -529,7 +529,7 @@ impl<T, E> Result<T, E> { /// ``` /// let mut x: Result<uint, &str> = Ok(7); /// match x.iter_mut().next() { - /// Some(&ref mut x) => *x = 40, + /// Some(&mut ref mut x) => *x = 40, /// None => {}, /// } /// assert_eq!(x, Ok(40)); @@ -953,7 +953,7 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { /// If an `Err` is encountered, it is immediately returned. /// Otherwise, the folded value is returned. #[inline] -#[experimental] +#[unstable] pub fn fold<T, V, E, diff --git a/src/libcore/simd.rs b/src/libcore/simd.rs index 1f9aebb91be..b73910d7c06 100644 --- a/src/libcore/simd.rs +++ b/src/libcore/simd.rs @@ -19,7 +19,7 @@ //! provided beyond this module. //! //! ```rust -//! #[allow(experimental)]; +//! #[allow(unstable)]; //! //! fn main() { //! use std::simd::f32x4; @@ -37,7 +37,7 @@ #![allow(non_camel_case_types)] #![allow(missing_docs)] -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] @@ -46,26 +46,26 @@ pub struct i8x16(pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8, pub i8); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct i16x8(pub i16, pub i16, pub i16, pub i16, pub i16, pub i16, pub i16, pub i16); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct i32x4(pub i32, pub i32, pub i32, pub i32); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct i64x2(pub i64, pub i64); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] @@ -74,32 +74,32 @@ pub struct u8x16(pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8, pub u8); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct u16x8(pub u16, pub u16, pub u16, pub u16, pub u16, pub u16, pub u16, pub u16); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct u32x4(pub u32, pub u32, pub u32, pub u32); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct u64x2(pub u64, pub u64); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] pub struct f32x4(pub f32, pub f32, pub f32, pub f32); -#[experimental] +#[unstable] #[simd] #[derive(Copy, Show)] #[repr(C)] diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index bf2df465370..7e47c5257a3 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -159,7 +159,7 @@ impl<T> SliceExt for [T] { #[inline] fn split_at(&self, mid: uint) -> (&[T], &[T]) { - (self.index(&(0..mid)), self.index(&(mid..))) + (&self[0..mid], &self[mid..]) } #[inline] @@ -236,11 +236,11 @@ impl<T> SliceExt for [T] { } #[inline] - fn tail(&self) -> &[T] { self.index(&(1..)) } + fn tail(&self) -> &[T] { &self[1..] } #[inline] fn init(&self) -> &[T] { - self.index(&(0..(self.len() - 1))) + &self[0..(self.len() - 1)] } #[inline] @@ -443,13 +443,13 @@ impl<T> SliceExt for [T] { #[inline] fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq { let n = needle.len(); - self.len() >= n && needle == self.index(&(0..n)) + self.len() >= n && needle == &self[0..n] } #[inline] fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { let (m, n) = (self.len(), needle.len()); - m >= n && needle == self.index(&((m-n)..)) + m >= n && needle == &self[(m-n)..] } #[unstable] @@ -457,7 +457,7 @@ impl<T> SliceExt for [T] { self.binary_search_by(|p| p.cmp(x)) } - #[experimental] + #[unstable] fn next_permutation(&mut self) -> bool where T: Ord { // These cases only have 1 permutation each, so we can't do anything. if self.len() < 2 { return false; } @@ -488,7 +488,7 @@ impl<T> SliceExt for [T] { true } - #[experimental] + #[unstable] fn prev_permutation(&mut self) -> bool where T: Ord { // These cases only have 1 permutation each, so we can't do anything. if self.len() < 2 { return false; } @@ -630,25 +630,25 @@ impl<T> ops::IndexMut<ops::FullRange> for [T] { //////////////////////////////////////////////////////////////////////////////// /// Data that is viewable as a slice. -#[experimental = "will be replaced by slice syntax"] +#[unstable = "will be replaced by slice syntax"] pub trait AsSlice<T> { /// Work with `self` as a slice. fn as_slice<'a>(&'a self) -> &'a [T]; } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<T> AsSlice<T> for [T] { #[inline(always)] fn as_slice<'a>(&'a self) -> &'a [T] { self } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U { #[inline(always)] fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U { #[inline(always)] fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) } @@ -754,7 +754,7 @@ pub struct Iter<'a, T: 'a> { marker: marker::ContravariantLifetime<'a> } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> { type Output = [T]; #[inline] @@ -763,7 +763,7 @@ impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> { } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> { type Output = [T]; #[inline] @@ -772,7 +772,7 @@ impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> { } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> { type Output = [T]; #[inline] @@ -781,7 +781,7 @@ impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> { } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> { type Output = [T]; #[inline] @@ -795,7 +795,7 @@ impl<'a, T> Iter<'a, T> { /// /// This has the same lifetime as the original slice, and so the /// iterator can continue to be used while this exists. - #[experimental] + #[unstable] pub fn as_slice(&self) -> &'a [T] { make_slice!(T => &'a [T]: self.ptr, self.end) } @@ -813,7 +813,7 @@ impl<'a, T> Clone for Iter<'a, T> { fn clone(&self) -> Iter<'a, T> { *self } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<'a, T> RandomAccessIterator for Iter<'a, T> { #[inline] fn indexable(&self) -> uint { @@ -847,7 +847,7 @@ pub struct IterMut<'a, T: 'a> { } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -855,7 +855,7 @@ impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> { self.index(&ops::FullRange).index(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -863,7 +863,7 @@ impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> { self.index(&ops::FullRange).index(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -871,7 +871,7 @@ impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> { self.index(&ops::FullRange).index(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -880,7 +880,7 @@ impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> { } } -#[experimental] +#[unstable] impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -888,7 +888,7 @@ impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> { self.index_mut(&ops::FullRange).index_mut(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -896,7 +896,7 @@ impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> { self.index_mut(&ops::FullRange).index_mut(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -904,7 +904,7 @@ impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> { self.index_mut(&ops::FullRange).index_mut(index) } } -#[experimental] +#[unstable] impl<'a, T> ops::IndexMut<ops::FullRange> for IterMut<'a, T> { type Output = [T]; #[inline] @@ -921,7 +921,7 @@ impl<'a, T> IterMut<'a, T> { /// to consume the iterator. Consider using the `Slice` and /// `SliceMut` implementations for obtaining slices with more /// restricted lifetimes that do not consume the iterator. - #[experimental] + #[unstable] pub fn into_slice(self) -> &'a mut [T] { make_slice!(T => &'a mut [T]: self.ptr, self.end) } @@ -972,8 +972,8 @@ impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool { match self.v.iter().position(|x| (self.pred)(x)) { None => self.finish(), Some(idx) => { - let ret = Some(self.v.index(&(0..idx))); - self.v = self.v.index(&((idx + 1)..)); + let ret = Some(&self.v[0..idx]); + self.v = &self.v[(idx + 1)..]; ret } } @@ -998,8 +998,8 @@ impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> boo match self.v.iter().rposition(|x| (self.pred)(x)) { None => self.finish(), Some(idx) => { - let ret = Some(self.v.index(&((idx + 1)..))); - self.v = self.v.index(&(0..idx)); + let ret = Some(&self.v[(idx + 1)..]); + self.v = &self.v[0..idx]; ret } } @@ -1195,8 +1195,8 @@ impl<'a, T> Iterator for Windows<'a, T> { if self.size > self.v.len() { None } else { - let ret = Some(self.v.index(&(0..self.size))); - self.v = self.v.index(&(1..)); + let ret = Some(&self.v[0..self.size]); + self.v = &self.v[1..]; ret } } @@ -1269,7 +1269,7 @@ impl<'a, T> DoubleEndedIterator for Chunks<'a, T> { } } -#[experimental = "trait is experimental"] +#[unstable = "trait is experimental"] impl<'a, T> RandomAccessIterator for Chunks<'a, T> { #[inline] fn indexable(&self) -> uint { @@ -1283,7 +1283,7 @@ impl<'a, T> RandomAccessIterator for Chunks<'a, T> { let mut hi = lo + self.size; if hi < lo || hi > self.v.len() { hi = self.v.len(); } - Some(self.v.index(&(lo..hi))) + Some(&self.v[lo..hi]) } else { None } @@ -1417,7 +1417,7 @@ pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] { // /// Operations on `[u8]`. -#[experimental = "needs review"] +#[unstable = "needs review"] pub mod bytes { use ptr; use slice::SliceExt; @@ -1430,7 +1430,7 @@ pub mod bytes { impl MutableByteVector for [u8] { #[inline] - #[allow(experimental)] + #[allow(unstable)] fn set_memory(&mut self, value: u8) { unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) }; } @@ -1506,7 +1506,7 @@ impl<T: PartialOrd> PartialOrd for [T] { } /// Extension methods for slices containing integers. -#[experimental] +#[unstable] pub trait IntSliceExt<U, S> { /// Converts the slice to an immutable slice of unsigned integers with the same width. fn as_unsigned<'a>(&'a self) -> &'a [U]; @@ -1521,7 +1521,7 @@ pub trait IntSliceExt<U, S> { macro_rules! impl_int_slice { ($u:ty, $s:ty, $t:ty) => { - #[experimental] + #[unstable] impl IntSliceExt<$u, $s> for [$t] { #[inline] fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 3f8ce000e21..6051c68b116 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -26,7 +26,7 @@ use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator}; use marker::Sized; use mem; use num::Int; -use ops::{Fn, FnMut, Index}; +use ops::{Fn, FnMut}; use option::Option::{self, None, Some}; use ptr::PtrExt; use raw::{Repr, Slice}; @@ -580,7 +580,7 @@ impl NaiveSearcher { fn next(&mut self, haystack: &[u8], needle: &[u8]) -> Option<(uint, uint)> { while self.position + needle.len() <= haystack.len() { - if haystack.index(&(self.position .. self.position + needle.len())) == needle { + if &haystack[self.position .. self.position + needle.len()] == needle { let match_pos = self.position; self.position += needle.len(); // add 1 for all matches return Some((match_pos, match_pos + needle.len())); @@ -701,10 +701,10 @@ impl TwoWaySearcher { // // What's going on is we have some critical factorization (u, v) of the // needle, and we want to determine whether u is a suffix of - // v.index(&(0..period)). If it is, we use "Algorithm CP1". Otherwise we use + // &v[0..period]. If it is, we use "Algorithm CP1". Otherwise we use // "Algorithm CP2", which is optimized for when the period of the needle // is large. - if needle.index(&(0..crit_pos)) == needle.index(&(period.. period + crit_pos)) { + if &needle[0..crit_pos] == &needle[period.. period + crit_pos] { TwoWaySearcher { crit_pos: crit_pos, period: period, @@ -1412,13 +1412,13 @@ impl StrExt for str { #[inline] fn starts_with(&self, needle: &str) -> bool { let n = needle.len(); - self.len() >= n && needle.as_bytes() == self.as_bytes().index(&(0..n)) + self.len() >= n && needle.as_bytes() == &self.as_bytes()[0..n] } #[inline] fn ends_with(&self, needle: &str) -> bool { let (m, n) = (self.len(), needle.len()); - m >= n && needle.as_bytes() == self.as_bytes().index(&((m-n)..)) + m >= n && needle.as_bytes() == &self.as_bytes()[(m-n)..] } #[inline] diff --git a/src/libcoretest/any.rs b/src/libcoretest/any.rs index c0be3a28794..e6a7170acea 100644 --- a/src/libcoretest/any.rs +++ b/src/libcoretest/any.rs @@ -101,12 +101,12 @@ fn any_downcast_mut() { } match a_r.downcast_mut::<uint>() { - Some(&612) => {} + Some(&mut 612) => {} x => panic!("Unexpected value {:?}", x) } match b_r.downcast_mut::<uint>() { - Some(&413) => {} + Some(&mut 413) => {} x => panic!("Unexpected value {:?}", x) } } diff --git a/src/libcoretest/cell.rs b/src/libcoretest/cell.rs index 86f34ecd15e..a808593ffbd 100644 --- a/src/libcoretest/cell.rs +++ b/src/libcoretest/cell.rs @@ -114,7 +114,7 @@ fn discard_doesnt_unborrow() { } #[test] -#[allow(experimental)] +#[allow(unstable)] fn clone_ref_updates_flag() { let x = RefCell::new(0i); { diff --git a/src/libcoretest/char.rs b/src/libcoretest/char.rs index f901e800176..7b6b4f84808 100644 --- a/src/libcoretest/char.rs +++ b/src/libcoretest/char.rs @@ -167,7 +167,7 @@ fn test_encode_utf8() { fn check(input: char, expect: &[u8]) { let mut buf = [0u8; 4]; let n = input.encode_utf8(buf.as_mut_slice()).unwrap_or(0); - assert_eq!(buf.index(&(0..n)), expect); + assert_eq!(&buf[0..n], expect); } check('x', &[0x78]); @@ -181,7 +181,7 @@ fn test_encode_utf16() { fn check(input: char, expect: &[u16]) { let mut buf = [0u16; 2]; let n = input.encode_utf16(buf.as_mut_slice()).unwrap_or(0); - assert_eq!(buf.index(&(0..n)), expect); + assert_eq!(&buf[0..n], expect); } check('x', &[0x0078]); diff --git a/src/libcoretest/hash/mod.rs b/src/libcoretest/hash/mod.rs index 63bf9ec3314..d48820aee06 100644 --- a/src/libcoretest/hash/mod.rs +++ b/src/libcoretest/hash/mod.rs @@ -7,27 +7,22 @@ // <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 core::marker::Sized; -use std::mem; - -use core::slice::SliceExt; -use core::hash::{Hash, Hasher, Writer}; -struct MyWriterHasher; +use std::mem; +use std::hash::{Hash, Hasher, Writer}; +use std::default::Default; -impl Hasher<MyWriter> for MyWriterHasher { - fn hash<T: ?Sized + Hash<MyWriter>>(&self, value: &T) -> u64 { - let mut state = MyWriter { hash: 0 }; - value.hash(&mut state); - state.hash - } +struct MyHasher { + hash: u64, } -struct MyWriter { - hash: u64, +impl Default for MyHasher { + fn default() -> MyHasher { + MyHasher { hash: 0 } + } } -impl Writer for MyWriter { +impl Writer for MyHasher { // Most things we'll just add up the bytes. fn write(&mut self, buf: &[u8]) { for byte in buf.iter() { @@ -36,66 +31,87 @@ impl Writer for MyWriter { } } +impl Hasher for MyHasher { + type Output = u64; + fn reset(&mut self) { self.hash = 0; } + fn finish(&self) -> u64 { self.hash } +} + + #[test] fn test_writer_hasher() { - let hasher = MyWriterHasher; + fn hash<T: Hash<MyHasher>>(t: &T) -> u64 { + ::std::hash::hash::<_, MyHasher>(t) + } - assert_eq!(hasher.hash(&()), 0); + assert_eq!(hash(&()), 0); - assert_eq!(hasher.hash(&5u8), 5); - assert_eq!(hasher.hash(&5u16), 5); - assert_eq!(hasher.hash(&5u32), 5); - assert_eq!(hasher.hash(&5u64), 5); - assert_eq!(hasher.hash(&5u), 5); + assert_eq!(hash(&5u8), 5); + assert_eq!(hash(&5u16), 5); + assert_eq!(hash(&5u32), 5); + assert_eq!(hash(&5u64), 5); + assert_eq!(hash(&5u), 5); - assert_eq!(hasher.hash(&5i8), 5); - assert_eq!(hasher.hash(&5i16), 5); - assert_eq!(hasher.hash(&5i32), 5); - assert_eq!(hasher.hash(&5i64), 5); - assert_eq!(hasher.hash(&5i), 5); + assert_eq!(hash(&5i8), 5); + assert_eq!(hash(&5i16), 5); + assert_eq!(hash(&5i32), 5); + assert_eq!(hash(&5i64), 5); + assert_eq!(hash(&5i), 5); - assert_eq!(hasher.hash(&false), 0); - assert_eq!(hasher.hash(&true), 1); + assert_eq!(hash(&false), 0); + assert_eq!(hash(&true), 1); - assert_eq!(hasher.hash(&'a'), 97); + assert_eq!(hash(&'a'), 97); let s: &str = "a"; - assert_eq!(hasher.hash(& s), 97 + 0xFF); + assert_eq!(hash(& s), 97 + 0xFF); // FIXME (#18283) Enable test //let s: Box<str> = box "a"; //assert_eq!(hasher.hash(& s), 97 + 0xFF); let cs: &[u8] = &[1u8, 2u8, 3u8]; - assert_eq!(hasher.hash(& cs), 9); + assert_eq!(hash(& cs), 9); let cs: Box<[u8]> = box [1u8, 2u8, 3u8]; - assert_eq!(hasher.hash(& cs), 9); + assert_eq!(hash(& cs), 9); // FIXME (#18248) Add tests for hashing Rc<str> and Rc<[T]> unsafe { let ptr: *const int = mem::transmute(5i); - assert_eq!(hasher.hash(&ptr), 5); + assert_eq!(hash(&ptr), 5); } unsafe { let ptr: *mut int = mem::transmute(5i); - assert_eq!(hasher.hash(&ptr), 5); + assert_eq!(hash(&ptr), 5); } } -struct Custom { - hash: u64 +struct Custom { hash: u64 } +struct CustomHasher { output: u64 } + +impl Hasher for CustomHasher { + type Output = u64; + fn reset(&mut self) { self.output = 0; } + fn finish(&self) -> u64 { self.output } +} + +impl Default for CustomHasher { + fn default() -> CustomHasher { + CustomHasher { output: 0 } + } } -impl Hash<u64> for Custom { - fn hash(&self, state: &mut u64) { - *state = self.hash; +impl Hash<CustomHasher> for Custom { + fn hash(&self, state: &mut CustomHasher) { + state.output = self.hash; } } #[test] fn test_custom_state() { - let custom = Custom { hash: 5 }; - let mut state = 0; - custom.hash(&mut state); - assert_eq!(state, 5); + fn hash<T: Hash<CustomHasher>>(t: &T) -> u64 { + ::std::hash::hash::<_, CustomHasher>(t) + } + + assert_eq!(hash(&Custom { hash: 5 }), 5); } diff --git a/src/libcoretest/intrinsics.rs b/src/libcoretest/intrinsics.rs new file mode 100644 index 00000000000..bcf8a6a433b --- /dev/null +++ b/src/libcoretest/intrinsics.rs @@ -0,0 +1,31 @@ +// 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 core::intrinsics::TypeId; + +#[test] +fn test_typeid_sized_types() { + struct X; struct Y(uint); + + assert_eq!(TypeId::of::<X>(), TypeId::of::<X>()); + assert_eq!(TypeId::of::<Y>(), TypeId::of::<Y>()); + assert!(TypeId::of::<X>() != TypeId::of::<Y>()); +} + +#[test] +fn test_typeid_unsized_types() { + trait Z {} + struct X(str); struct Y(Z + 'static); + + assert_eq!(TypeId::of::<X>(), TypeId::of::<X>()); + assert_eq!(TypeId::of::<Y>(), TypeId::of::<Y>()); + assert!(TypeId::of::<X>() != TypeId::of::<Y>()); +} + diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs index 50ae59e70dc..0d371dbe153 100644 --- a/src/libcoretest/lib.rs +++ b/src/libcoretest/lib.rs @@ -7,8 +7,11 @@ // <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. -#![feature(globs, unsafe_destructor, slicing_syntax, default_type_params)] + +#![feature(unsafe_destructor, slicing_syntax)] #![feature(unboxed_closures)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate core; extern crate test; diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index b9403598ec2..485549cc552 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::iter::range; - pub fn op1() -> Result<int, &'static str> { Ok(666) } pub fn op2() -> Result<int, &'static str> { Err("sadface") } diff --git a/src/libcoretest/slice.rs b/src/libcoretest/slice.rs index b714b6a4e41..6fae384763f 100644 --- a/src/libcoretest/slice.rs +++ b/src/libcoretest/slice.rs @@ -57,17 +57,17 @@ fn iterator_to_slice() { } { let mut iter = data.iter_mut(); - assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); + assert_eq!(&iter[], &other_data[]); // mutability: assert!(&mut iter[] == other_data); iter.next(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); + assert_eq!(&iter[], &other_data[1..]); assert!(&mut iter[] == &mut other_data[1..]); iter.next_back(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); + assert_eq!(&iter[], &other_data[1..2]); assert!(&mut iter[] == &mut other_data[1..2]); let s = iter.into_slice(); diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index f38440d86c6..fb6c98515f7 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -15,7 +15,9 @@ //! [mz]: https://code.google.com/p/miniz/ #![crate_name = "flate"] -#![experimental] +#![unstable] +#![staged_api] +#![allow(unknown_features)] #![feature(int_uint)] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 47cc072a636..70ad8d28d27 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -15,7 +15,8 @@ //! generated instead. #![crate_name = "fmt_macros"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -24,6 +25,7 @@ html_playground_url = "http://play.rust-lang.org/")] #![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] pub use self::Piece::*; pub use self::Position::*; @@ -211,12 +213,12 @@ impl<'a> Parser<'a> { self.cur.next(); } Some((_, other)) => { - self.err(format!("expected `{:?}`, found `{:?}`", c, - other).index(&FullRange)); + self.err(&format!("expected `{:?}`, found `{:?}`", c, + other)[]); } None => { - self.err(format!("expected `{:?}` but string was terminated", - c).index(&FullRange)); + self.err(&format!("expected `{:?}` but string was terminated", + c)[]); } } } @@ -239,12 +241,12 @@ impl<'a> Parser<'a> { // we may not consume the character, so clone the iterator match self.cur.clone().next() { Some((pos, '}')) | Some((pos, '{')) => { - return self.input.index(&(start..pos)); + return &self.input[start..pos]; } Some(..) => { self.cur.next(); } None => { self.cur.next(); - return self.input.index(&(start..self.input.len())); + return &self.input[start..self.input.len()]; } } } @@ -284,7 +286,7 @@ impl<'a> Parser<'a> { flags: 0, precision: CountImplied, width: CountImplied, - ty: self.input.index(&(0..0)), + ty: &self.input[0..0], }; if !self.consume(':') { return spec } @@ -393,7 +395,7 @@ impl<'a> Parser<'a> { self.cur.next(); pos } - Some(..) | None => { return self.input.index(&(0..0)); } + Some(..) | None => { return &self.input[0..0]; } }; let mut end; loop { @@ -405,7 +407,7 @@ impl<'a> Parser<'a> { None => { end = self.input.len(); break } } } - self.input.index(&(start..end)) + &self.input[start..end] } /// Optionally parses an integer at the current position. This doesn't deal diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index f50e24c6354..470ef6e7e57 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -78,7 +78,8 @@ //! ``` #![crate_name = "getopts"] -#![experimental = "use the crates.io `getopts` library instead"] +#![unstable = "use the crates.io `getopts` library instead"] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -86,6 +87,7 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![deny(missing_docs)] #[cfg(test)] #[macro_use] extern crate log; @@ -280,7 +282,7 @@ impl OptGroup { impl Matches { fn opt_vals(&self, nm: &str) -> Vec<Optval> { - match find_opt(self.opts.index(&FullRange), Name::from_str(nm)) { + match find_opt(&self.opts[], Name::from_str(nm)) { Some(id) => self.vals[id].clone(), None => panic!("No option '{}' defined", nm) } @@ -308,7 +310,7 @@ impl Matches { /// Returns true if any of several options were matched. pub fn opts_present(&self, names: &[String]) -> bool { for nm in names.iter() { - match find_opt(self.opts.as_slice(), Name::from_str(nm.index(&FullRange))) { + match find_opt(self.opts.as_slice(), Name::from_str(&nm[])) { Some(id) if !self.vals[id].is_empty() => return true, _ => (), }; @@ -319,7 +321,7 @@ impl Matches { /// Returns the string argument supplied to one of several matching options or `None`. pub fn opts_str(&self, names: &[String]) -> Option<String> { for nm in names.iter() { - match self.opt_val(nm.index(&FullRange)) { + match self.opt_val(&nm[]) { Some(Val(ref s)) => return Some(s.clone()), _ => () } @@ -584,7 +586,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { while i < l { let cur = args[i].clone(); let curlen = cur.len(); - if !is_arg(cur.index(&FullRange)) { + if !is_arg(&cur[]) { free.push(cur); } else if cur == "--" { let mut j = i + 1; @@ -594,7 +596,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let mut names; let mut i_arg = None; if cur.as_bytes()[1] == b'-' { - let tail = cur.index(&(2..curlen)); + let tail = &cur[2..curlen]; let tail_eq: Vec<&str> = tail.split('=').collect(); if tail_eq.len() <= 1 { names = vec!(Long(tail.to_string())); @@ -630,7 +632,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { }; if arg_follows && range.next < curlen { - i_arg = Some(cur.index(&(range.next..curlen)).to_string()); + i_arg = Some((&cur[range.next..curlen]).to_string()); break; } @@ -658,7 +660,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { v.push(Val((i_arg.clone()) .unwrap())); } else if name_pos < names.len() || i + 1 == l || - is_arg(args[i + 1].index(&FullRange)) { + is_arg(&args[i + 1][]) { let v = &mut vals[optid]; v.push(Given); } else { @@ -721,7 +723,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { 0 => {} 1 => { row.push('-'); - row.push_str(short_name.index(&FullRange)); + row.push_str(&short_name[]); row.push(' '); } _ => panic!("the short name should only be 1 ascii char long"), @@ -732,7 +734,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { 0 => {} _ => { row.push_str("--"); - row.push_str(long_name.index(&FullRange)); + row.push_str(&long_name[]); row.push(' '); } } @@ -740,10 +742,10 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { // arg match hasarg { No => {} - Yes => row.push_str(hint.index(&FullRange)), + Yes => row.push_str(&hint[]), Maybe => { row.push('['); - row.push_str(hint.index(&FullRange)); + row.push_str(&hint[]); row.push(']'); } } @@ -756,7 +758,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { row.push(' '); } } else { - row.push_str(desc_sep.index(&FullRange)); + row.push_str(&desc_sep[]); } // Normalize desc to contain words separated by one space character @@ -768,14 +770,14 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { // FIXME: #5516 should be graphemes not codepoints let mut desc_rows = Vec::new(); - each_split_within(desc_normalized_whitespace.index(&FullRange), 54, |substr| { + each_split_within(&desc_normalized_whitespace[], 54, |substr| { desc_rows.push(substr.to_string()); true }); // FIXME: #5516 should be graphemes not codepoints // wrapped description - row.push_str(desc_rows.connect(desc_sep.index(&FullRange)).index(&FullRange)); + row.push_str(&desc_rows.connect(&desc_sep[])[]); row }); @@ -794,10 +796,10 @@ fn format_option(opt: &OptGroup) -> String { // Use short_name is possible, but fallback to long_name. if opt.short_name.len() > 0 { line.push('-'); - line.push_str(opt.short_name.index(&FullRange)); + line.push_str(&opt.short_name[]); } else { line.push_str("--"); - line.push_str(opt.long_name.index(&FullRange)); + line.push_str(&opt.long_name[]); } if opt.hasarg != No { @@ -805,7 +807,7 @@ fn format_option(opt: &OptGroup) -> String { if opt.hasarg == Maybe { line.push('['); } - line.push_str(opt.hint.index(&FullRange)); + line.push_str(&opt.hint[]); if opt.hasarg == Maybe { line.push(']'); } @@ -824,10 +826,10 @@ fn format_option(opt: &OptGroup) -> String { /// Derive a short one-line usage summary from a set of long options. pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String { let mut line = format!("Usage: {} ", program_name); - line.push_str(opts.iter() - .map(format_option) - .collect::<Vec<String>>() - .connect(" ").index(&FullRange)); + line.push_str(&opts.iter() + .map(format_option) + .collect::<Vec<String>>() + .connect(" ")[]); line } @@ -890,9 +892,9 @@ fn each_split_within<F>(ss: &str, lim: uint, mut it: F) -> bool where (B, Cr, UnderLim) => { B } (B, Cr, OverLim) if (i - last_start + 1) > lim => panic!("word starting with {} longer than limit!", - ss.index(&(last_start..(i + 1)))), + &ss[last_start..(i + 1)]), (B, Cr, OverLim) => { - *cont = it(ss.index(&(slice_start..last_end))); + *cont = it(&ss[slice_start..last_end]); slice_start = last_start; B } @@ -902,7 +904,7 @@ fn each_split_within<F>(ss: &str, lim: uint, mut it: F) -> bool where } (B, Ws, OverLim) => { last_end = i; - *cont = it(ss.index(&(slice_start..last_end))); + *cont = it(&ss[slice_start..last_end]); A } @@ -911,14 +913,14 @@ fn each_split_within<F>(ss: &str, lim: uint, mut it: F) -> bool where B } (C, Cr, OverLim) => { - *cont = it(ss.index(&(slice_start..last_end))); + *cont = it(&ss[slice_start..last_end]); slice_start = i; last_start = i; last_end = i; B } (C, Ws, OverLim) => { - *cont = it(ss.index(&(slice_start..last_end))); + *cont = it(&ss[slice_start..last_end]); A } (C, Ws, UnderLim) => { diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 83bad70e7b1..b48fe2e4278 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -265,13 +265,15 @@ //! * [DOT language](http://www.graphviz.org/doc/info/lang.html) #![crate_name = "graphviz"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] #![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] use self::LabelText::*; @@ -452,7 +454,7 @@ impl<'a> LabelText<'a> { pub fn escape(&self) -> String { match self { &LabelStr(ref s) => s.escape_default(), - &EscStr(ref s) => LabelText::escape_str(s.index(&FullRange)), + &EscStr(ref s) => LabelText::escape_str(&s[]), } } @@ -481,7 +483,7 @@ impl<'a> LabelText<'a> { let mut prefix = self.pre_escaped_content().into_owned(); let suffix = suffix.pre_escaped_content(); prefix.push_str(r"\n\n"); - prefix.push_str(suffix.index(&FullRange)); + prefix.push_str(&suffix[]); EscStr(prefix.into_cow()) } } @@ -675,7 +677,7 @@ mod tests { impl<'a> Labeller<'a, Node, &'a Edge> for LabelledGraph { fn graph_id(&'a self) -> Id<'a> { - Id::new(self.name.index(&FullRange)).unwrap() + Id::new(&self.name[]).unwrap() } fn node_id(&'a self, n: &Node) -> Id<'a> { id_name(n) diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index 347a958076d..34964bbae51 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -10,7 +10,9 @@ #![crate_name = "libc"] #![crate_type = "rlib"] -#![cfg_attr(not(feature = "cargo-build"), experimental)] +#![cfg_attr(not(feature = "cargo-build"), unstable)] +#![cfg_attr(not(feature = "cargo-build"), staged_api)] +#![allow(unknown_features)] #![feature(int_uint)] #![no_std] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", @@ -5065,7 +5067,5 @@ pub fn issue_14344_workaround() {} // FIXME #14344 force linkage to happen corre #[doc(hidden)] #[cfg(not(test))] mod std { - #[cfg(stage0)] - pub use core::marker as kinds; pub use core::marker; } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 08b01e956e1..a166dc369cb 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -156,14 +156,19 @@ //! if logging is disabled, none of the components of the log will be executed. #![crate_name = "log"] -#![experimental = "use the crates.io `log` library instead"] +#![unstable = "use the crates.io `log` library instead"] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] + +#![allow(unknown_features)] #![feature(slicing_syntax)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![deny(missing_docs)] extern crate regex; @@ -287,7 +292,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { // Test the literal string from args against the current filter, if there // is one. match unsafe { FILTER.as_ref() } { - Some(filter) if !filter.is_match(args.to_string().index(&FullRange)) => return, + Some(filter) if !filter.is_match(&args.to_string()[]) => return, _ => {} } @@ -382,7 +387,7 @@ fn enabled(level: u32, // Search for the longest match, the vector is assumed to be pre-sorted. for directive in iter.rev() { match directive.name { - Some(ref name) if !module.starts_with(name.index(&FullRange)) => {}, + Some(ref name) if !module.starts_with(&name[]) => {}, Some(..) | None => { return level <= directive.level } @@ -397,7 +402,7 @@ fn enabled(level: u32, /// `Once` primitive (and this function is called from that primitive). fn init() { let (mut directives, filter) = match os::getenv("RUST_LOG") { - Some(spec) => directive::parse_logging_spec(spec.index(&FullRange)), + Some(spec) => directive::parse_logging_spec(&spec[]), None => (Vec::new(), None), }; diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 2fdba8a6c4f..e248de10df4 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -17,7 +17,7 @@ //! internally. The `IndependentSample` trait is for generating values //! that do not need to record state. -#![experimental] +#![unstable] use core::prelude::*; use core::num::{Float, Int}; diff --git a/src/librand/lib.rs b/src/librand/lib.rs index ad2a4dbec4e..4d605253ab0 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -22,9 +22,10 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] - +#![allow(unknown_features)] #![feature(int_uint)] #![no_std] -#![experimental] +#![unstable] +#![staged_api] #[macro_use] extern crate core; @@ -193,7 +194,7 @@ pub trait Rng : Sized { /// /// let mut rng = thread_rng(); /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>(); - /// println!("{}", x); + /// println!("{:?}", x); /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5) /// .collect::<Vec<(f64, bool)>>()); /// ``` @@ -270,7 +271,7 @@ pub trait Rng : Sized { /// let mut rng = thread_rng(); /// println!("{:?}", rng.choose(&choices)); /// # // uncomment when slicing syntax is stable - /// //assert_eq!(rng.choose(choices.index(&(0..0))), None); + /// //assert_eq!(rng.choose(&choices[0..0]), None); /// ``` fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { if values.is_empty() { @@ -290,9 +291,9 @@ pub trait Rng : Sized { /// let mut rng = thread_rng(); /// let mut y = [1i, 2, 3]; /// rng.shuffle(&mut y); - /// println!("{}", y.as_slice()); + /// println!("{:?}", y.as_slice()); /// rng.shuffle(&mut y); - /// println!("{}", y.as_slice()); + /// println!("{:?}", y.as_slice()); /// ``` fn shuffle<T>(&mut self, values: &mut [T]) { let mut i = values.len(); @@ -495,8 +496,6 @@ pub struct Closed01<F>(pub F); mod std { pub use core::{option, fmt}; // panic!() pub use core::clone; // derive Clone - #[cfg(stage0)] - pub use core::marker as kinds; pub use core::marker; } diff --git a/src/librbml/io.rs b/src/librbml/io.rs index 5ebec32d733..bdc00d7db97 100644 --- a/src/librbml/io.rs +++ b/src/librbml/io.rs @@ -95,7 +95,7 @@ impl Writer for SeekableMemWriter { // there (left), and what will be appended on the end (right) let cap = self.buf.len() - self.pos; let (left, right) = if cap <= buf.len() { - (buf.index(&(0..cap)), buf.index(&(cap..))) + (&buf[0..cap], &buf[cap..]) } else { let result: (_, &[_]) = (buf, &[]); result diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index a66d1dd08c1..6a7062a419e 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -16,7 +16,8 @@ //! http://www.matroska.org/technical/specs/rfc/index.html #![crate_name = "rbml"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -25,6 +26,7 @@ html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] #![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate serialize; #[macro_use] extern crate log; @@ -56,7 +58,7 @@ impl<'doc> Doc<'doc> { } pub fn as_str_slice<'a>(&'a self) -> &'a str { - str::from_utf8(self.data.index(&(self.start..self.end))).unwrap() + str::from_utf8(&self.data[self.start..self.end]).unwrap() } pub fn as_str(&self) -> String { @@ -291,7 +293,7 @@ pub mod reader { pub fn with_doc_data<T, F>(d: Doc, f: F) -> T where F: FnOnce(&[u8]) -> T, { - f(d.data.index(&(d.start..d.end))) + f(&d.data[d.start..d.end]) } diff --git a/src/libregex/compile.rs b/src/libregex/compile.rs index 5803da1d335..d29a7a425c1 100644 --- a/src/libregex/compile.rs +++ b/src/libregex/compile.rs @@ -105,7 +105,7 @@ impl Program { // This is a bit hacky since we have to skip over the initial // 'Save' instruction. let mut pre = String::with_capacity(5); - for inst in c.insts.index(&(1..)).iter() { + for inst in c.insts[1..].iter() { match *inst { OneChar(c, FLAG_EMPTY) => pre.push(c), _ => break diff --git a/src/libregex/lib.rs b/src/libregex/lib.rs index c039abc9aff..45f42336ceb 100644 --- a/src/libregex/lib.rs +++ b/src/libregex/lib.rs @@ -16,7 +16,8 @@ #![crate_name = "regex"] #![crate_type = "rlib"] #![crate_type = "dylib"] -#![experimental = "use the crates.io `regex` library instead"] +#![unstable = "use the crates.io `regex` library instead"] +#![staged_api] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", @@ -24,6 +25,8 @@ #![allow(unknown_features)] #![feature(slicing_syntax)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![deny(missing_docs)] #[cfg(test)] diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index dd11d42b8aa..1cc2b271e9c 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -18,7 +18,6 @@ use std::cmp; use std::fmt; use std::iter; use std::num; -use std::ops::Index; /// Static data containing Unicode ranges for general categories and scripts. use unicode::regex::{UNICODE_CLASSES, PERLD, PERLS, PERLW}; @@ -285,8 +284,8 @@ impl<'a> Parser<'a> { match self.next_char() { true => Ok(()), false => { - self.err(format!("Expected {:?} but got EOF.", - expected).index(&FullRange)) + self.err(&format!("Expected {:?} but got EOF.", + expected)[]) } } } @@ -294,11 +293,11 @@ impl<'a> Parser<'a> { fn expect(&mut self, expected: char) -> Result<(), Error> { match self.next_char() { true if self.cur() == expected => Ok(()), - true => self.err(format!("Expected '{:?}' but got '{:?}'.", - expected, self.cur()).index(&FullRange)), + true => self.err(&format!("Expected '{:?}' but got '{:?}'.", + expected, self.cur())[]), false => { - self.err(format!("Expected '{:?}' but got EOF.", - expected).index(&FullRange)) + self.err(&format!("Expected '{:?}' but got EOF.", + expected)[]) } } } @@ -443,15 +442,15 @@ impl<'a> Parser<'a> { match try!(self.parse_escape()) { Literal(c3, _) => c2 = c3, // allow literal escapes below ast => - return self.err(format!("Expected a literal, but got {:?}.", - ast).index(&FullRange)), + return self.err(&format!("Expected a literal, but got {:?}.", + ast)[]), } } if c2 < c { - return self.err(format!("Invalid character class \ - range '{}-{}'", - c, - c2).index(&FullRange)) + return self.err(&format!("Invalid character class \ + range '{}-{}'", + c, + c2)[]) } ranges.push((c, self.cur())) } else { @@ -489,7 +488,7 @@ impl<'a> Parser<'a> { FLAG_EMPTY }; let name = self.slice(name_start, closer - 1); - match find_class(ASCII_CLASSES, name.index(&FullRange)) { + match find_class(ASCII_CLASSES, &name[]) { None => None, Some(ranges) => { self.chari = closer; @@ -511,21 +510,21 @@ impl<'a> Parser<'a> { match self.pos('}') { Some(i) => i, None => { - return self.err(format!("No closing brace for counted \ - repetition starting at position \ - {:?}.", - start).index(&FullRange)) + return self.err(&format!("No closing brace for counted \ + repetition starting at position \ + {:?}.", + start)[]) } }; self.chari = closer; let greed = try!(self.get_next_greedy()); - let inner = self.chars.index(&((start+1)..closer)).iter().cloned() + let inner = self.chars[(start+1)..closer].iter().cloned() .collect::<String>(); // Parse the min and max values from the regex. let (mut min, mut max): (uint, Option<uint>); if !inner.contains(",") { - min = try!(self.parse_uint(inner.index(&FullRange))); + min = try!(self.parse_uint(&inner[])); max = Some(min); } else { let pieces: Vec<&str> = inner.splitn(1, ',').collect(); @@ -545,21 +544,21 @@ impl<'a> Parser<'a> { // Do some bounds checking and make sure max >= min. if min > MAX_REPEAT { - return self.err(format!( + return self.err(&format!( "{} exceeds maximum allowed repetitions ({})", - min, MAX_REPEAT).index(&FullRange)); + min, MAX_REPEAT)[]); } if max.is_some() { let m = max.unwrap(); if m > MAX_REPEAT { - return self.err(format!( + return self.err(&format!( "{} exceeds maximum allowed repetitions ({})", - m, MAX_REPEAT).index(&FullRange)); + m, MAX_REPEAT)[]); } if m < min { - return self.err(format!( + return self.err(&format!( "Max repetitions ({}) cannot be smaller than min \ - repetitions ({}).", m, min).index(&FullRange)); + repetitions ({}).", m, min)[]); } } @@ -623,7 +622,7 @@ impl<'a> Parser<'a> { Ok(AstClass(ranges, flags)) } _ => { - self.err(format!("Invalid escape sequence '\\\\{}'", c).index(&FullRange)) + self.err(&format!("Invalid escape sequence '\\\\{}'", c)[]) } } } @@ -641,9 +640,9 @@ impl<'a> Parser<'a> { let closer = match self.pos('}') { Some(i) => i, - None => return self.err(format!( + None => return self.err(&format!( "Missing '}}' for unclosed '{{' at position {}", - self.chari).index(&FullRange)), + self.chari)[]), }; if closer - self.chari + 1 == 0 { return self.err("No Unicode class name found.") @@ -657,10 +656,10 @@ impl<'a> Parser<'a> { name = self.slice(self.chari + 1, self.chari + 2); self.chari += 1; } - match find_class(UNICODE_CLASSES, name.index(&FullRange)) { + match find_class(UNICODE_CLASSES, &name[]) { None => { - return self.err(format!("Could not find Unicode class '{}'", - name).index(&FullRange)) + return self.err(&format!("Could not find Unicode class '{}'", + name)[]) } Some(ranges) => { Ok(AstClass(ranges, negated | (self.flags & FLAG_NOCASE))) @@ -683,11 +682,11 @@ impl<'a> Parser<'a> { } } let s = self.slice(start, end); - match num::from_str_radix::<u32>(s.index(&FullRange), 8) { + match num::from_str_radix::<u32>(&s[], 8) { Some(n) => Ok(Literal(try!(self.char_from_u32(n)), FLAG_EMPTY)), None => { - self.err(format!("Could not parse '{:?}' as octal number.", - s).index(&FullRange)) + self.err(&format!("Could not parse '{:?}' as octal number.", + s)[]) } } } @@ -703,14 +702,14 @@ impl<'a> Parser<'a> { let closer = match self.pos('}') { None => { - return self.err(format!("Missing '}}' for unclosed \ + return self.err(&format!("Missing '}}' for unclosed \ '{{' at position {}", - start).index(&FullRange)) + start)[]) } Some(i) => i, }; self.chari = closer; - self.parse_hex_digits(self.slice(start, closer).index(&FullRange)) + self.parse_hex_digits(&self.slice(start, closer)[]) } // Parses a two-digit hex number. @@ -730,7 +729,7 @@ impl<'a> Parser<'a> { match num::from_str_radix::<u32>(s, 16) { Some(n) => Ok(Literal(try!(self.char_from_u32(n)), FLAG_EMPTY)), None => { - self.err(format!("Could not parse '{}' as hex number.", s).index(&FullRange)) + self.err(&format!("Could not parse '{}' as hex number.", s)[]) } } } @@ -755,8 +754,8 @@ impl<'a> Parser<'a> { "Capture names can only have underscores, letters and digits.") } if self.names.contains(&name) { - return self.err(format!("Duplicate capture group name '{}'.", - name).index(&FullRange)) + return self.err(&format!("Duplicate capture group name '{}'.", + name)[]) } self.names.push(name.clone()); self.chari = closer; @@ -788,9 +787,9 @@ impl<'a> Parser<'a> { 'U' => { flags = flags | FLAG_SWAP_GREED; saw_flag = true}, '-' => { if sign < 0 { - return self.err(format!( + return self.err(&format!( "Cannot negate flags twice in '{}'.", - self.slice(start, self.chari + 1)).index(&FullRange)) + self.slice(start, self.chari + 1))[]) } sign = -1; saw_flag = false; @@ -799,9 +798,9 @@ impl<'a> Parser<'a> { ':' | ')' => { if sign < 0 { if !saw_flag { - return self.err(format!( + return self.err(&format!( "A valid flag does not follow negation in '{}'", - self.slice(start, self.chari + 1)).index(&FullRange)) + self.slice(start, self.chari + 1))[]) } flags = flags ^ flags; } @@ -812,8 +811,8 @@ impl<'a> Parser<'a> { self.flags = flags; return Ok(()) } - _ => return self.err(format!( - "Unrecognized flag '{}'.", self.cur()).index(&FullRange)), + _ => return self.err(&format!( + "Unrecognized flag '{}'.", self.cur())[]), } } } @@ -910,8 +909,8 @@ impl<'a> Parser<'a> { match s.parse::<uint>() { Some(i) => Ok(i), None => { - self.err(format!("Expected an unsigned integer but got '{}'.", - s).index(&FullRange)) + self.err(&format!("Expected an unsigned integer but got '{}'.", + s)[]) } } } @@ -920,8 +919,8 @@ impl<'a> Parser<'a> { match char::from_u32(n) { Some(c) => Ok(c), None => { - self.err(format!("Could not decode '{}' to unicode \ - character.", n).index(&FullRange)) + self.err(&format!("Could not decode '{}' to unicode \ + character.", n)[]) } } } @@ -954,7 +953,7 @@ impl<'a> Parser<'a> { } fn slice(&self, start: uint, end: uint) -> String { - self.chars.index(&(start..end)).iter().cloned().collect() + self.chars[start..end].iter().cloned().collect() } } diff --git a/src/libregex/re.rs b/src/libregex/re.rs index 37f9869f3bf..abc51d62404 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -90,15 +90,6 @@ impl Clone for ExNative { } } -#[cfg(stage0)] -//FIXME: remove after stage0 snapshot -impl fmt::Show for Regex { - /// Shows the original regular expression. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self.as_str(), f) - } -} - impl fmt::String for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -247,24 +238,24 @@ impl Regex { } let (s, e) = cap.pos(0).unwrap(); // captures only reports matches - new.push_str(text.index(&(last_match..s))); - new.push_str(rep.reg_replace(&cap).index(&FullRange)); + new.push_str(&text[last_match..s]); + new.push_str(&rep.reg_replace(&cap)[]); last_match = e; } - new.push_str(text.index(&(last_match..text.len()))); + new.push_str(&text[last_match..text.len()]); return new; } /// Returns the original string of this regex. pub fn as_str<'a>(&'a self) -> &'a str { match *self { - Dynamic(ExDynamic { ref original, .. }) => original.index(&FullRange), - Native(ExNative { ref original, .. }) => original.index(&FullRange), + Dynamic(ExDynamic { ref original, .. }) => &original[], + Native(ExNative { ref original, .. }) => &original[], } } #[doc(hidden)] - #[experimental] + #[unstable] pub fn names_iter<'a>(&'a self) -> NamesIter<'a> { match *self { Native(ref n) => NamesIterNative(n.names.iter()), @@ -356,13 +347,13 @@ impl<'r, 't> Iterator for RegexSplits<'r, 't> { if self.last >= text.len() { None } else { - let s = text.index(&(self.last..text.len())); + let s = &text[self.last..text.len()]; self.last = text.len(); Some(s) } } Some((s, e)) => { - let matched = text.index(&(self.last..s)); + let matched = &text[self.last..s]; self.last = e; Some(matched) } @@ -393,7 +384,7 @@ impl<'r, 't> Iterator for RegexSplitsN<'r, 't> { } else { self.cur += 1; if self.cur >= self.limit { - Some(text.index(&(self.splits.last..text.len()))) + Some(&text[self.splits.last..text.len()]) } else { self.splits.next() } @@ -419,7 +410,7 @@ pub struct Captures<'t> { } impl<'t> Captures<'t> { - #[allow(experimental)] + #[allow(unstable)] fn new(re: &Regex, search: &'t str, locs: CaptureLocs) -> Option<Captures<'t>> { if !has_match(&locs) { @@ -526,7 +517,7 @@ impl<'t> Captures<'t> { }) }); let re = Regex::new(r"\$\$").unwrap(); - re.replace_all(text.index(&FullRange), NoExpand("$")) + re.replace_all(&text[], NoExpand("$")) } /// Returns the number of captured groups. diff --git a/src/libregex/vm.rs b/src/libregex/vm.rs index 04c430da4d2..9605536a052 100644 --- a/src/libregex/vm.rs +++ b/src/libregex/vm.rs @@ -152,7 +152,7 @@ impl<'r, 't> Nfa<'r, 't> { // out early. if self.prog.prefix.len() > 0 && clist.size == 0 { let needle = self.prog.prefix.as_bytes(); - let haystack = self.input.as_bytes().index(&(self.ic..)); + let haystack = &self.input.as_bytes()[self.ic..]; match find_prefix(needle, haystack) { None => break, Some(i) => { diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index a3a041c2497..fb7c5296d02 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -15,7 +15,8 @@ //! This API is completely unstable and subject to change. #![crate_name = "rustc"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -25,8 +26,9 @@ #![allow(unknown_features)] #![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![feature(rustc_diagnostic_macros)] -#![feature(old_impl_check)] extern crate arena; extern crate flate; diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 1af8e2f29eb..620b8f277dd 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -34,7 +34,7 @@ use middle::{def, pat_util, stability}; use middle::const_eval::{eval_const_expr_partial, const_int, const_uint}; use util::ppaux::{ty_to_string}; use util::nodemap::{FnvHashMap, NodeSet}; -use lint::{Context, LintPass, LintArray}; +use lint::{Context, LintPass, LintArray, Lint}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::num::SignedInt; @@ -216,7 +216,7 @@ impl LintPass for TypeLimits { match lit.node { ast::LitInt(v, ast::SignedIntLit(_, ast::Plus)) | ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => { - let int_type = if t == ast::TyIs { + let int_type = if let ast::TyIs(_) = t { cx.sess().target.int_type } else { t }; let (min, max) = int_ty_range(int_type); @@ -233,7 +233,7 @@ impl LintPass for TypeLimits { }; }, ty::ty_uint(t) => { - let uint_type = if t == ast::TyUs { + let uint_type = if let ast::TyUs(_) = t { cx.sess().target.uint_type } else { t }; let (min, max) = uint_ty_range(uint_type); @@ -296,7 +296,7 @@ impl LintPass for TypeLimits { // 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::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), @@ -306,7 +306,7 @@ impl LintPass for TypeLimits { fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) { match uint_ty { - ast::TyUs=> (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), @@ -323,7 +323,7 @@ impl LintPass for TypeLimits { 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::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, @@ -333,7 +333,7 @@ impl LintPass for TypeLimits { 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::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, @@ -404,12 +404,12 @@ struct ImproperCTypesVisitor<'a, 'tcx: 'a> { impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_def(&mut self, sp: Span, ty_id: ast::NodeId, path_id: ast::NodeId) { match self.cx.tcx.def_map.borrow()[path_id].clone() { - def::DefPrimTy(ast::TyInt(ast::TyIs)) => { + def::DefPrimTy(ast::TyInt(ast::TyIs(_))) => { self.cx.span_lint(IMPROPER_CTYPES, sp, "found rust type `isize` in foreign module, while \ libc::c_int or libc::c_long should be used"); } - def::DefPrimTy(ast::TyUint(ast::TyUs)) => { + def::DefPrimTy(ast::TyUint(ast::TyUs(_))) => { self.cx.span_lint(IMPROPER_CTYPES, sp, "found rust type `usize` in foreign module, while \ libc::c_uint or libc::c_ulong should be used"); @@ -506,7 +506,7 @@ impl BoxPointers { if n_uniq > 0 { let s = ty_to_string(cx.tcx, ty); let m = format!("type uses owned (Box type) pointers: {}", s); - cx.span_lint(BOX_POINTERS, span, m.index(&FullRange)); + cx.span_lint(BOX_POINTERS, span, &m[]); } } } @@ -586,7 +586,7 @@ impl LintPass for RawPointerDerive { } fn check_item(&mut self, cx: &Context, item: &ast::Item) { - if !attr::contains_name(item.attrs.index(&FullRange), "automatically_derived") { + if !attr::contains_name(&item.attrs[], "automatically_derived") { return } let did = match item.node { @@ -770,11 +770,11 @@ impl LintPass for UnusedResults { 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.index(&FullRange), s.span); + warned |= check_must_use(cx, &it.attrs[], s.span); } } else { csearch::get_item_attrs(&cx.sess().cstore, did, |attrs| { - warned |= check_must_use(cx, attrs.index(&FullRange), s.span); + warned |= check_must_use(cx, &attrs[], s.span); }); } } @@ -796,7 +796,7 @@ impl LintPass for UnusedResults { msg.push_str(s.get()); } } - cx.span_lint(UNUSED_MUST_USE, sp, msg.index(&FullRange)); + cx.span_lint(UNUSED_MUST_USE, sp, &msg[]); return true; } } @@ -842,7 +842,7 @@ impl NonCamelCaseTypes { } else { format!("{} `{}` should have a camel case name such as `{}`", sort, s, c) }; - cx.span_lint(NON_CAMEL_CASE_TYPES, span, m.index(&FullRange)); + cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[]); } } } @@ -981,8 +981,8 @@ impl NonSnakeCase { if !is_snake_case(ident) { cx.span_lint(NON_SNAKE_CASE, span, - format!("{} `{}` should have a snake case name such as `{}`", - sort, s, to_snake_case(s.get())).index(&FullRange)); + &format!("{} `{}` should have a snake case name such as `{}`", + sort, s, to_snake_case(s.get()))[]); } } } @@ -1066,10 +1066,10 @@ impl LintPass for NonUpperCaseGlobals { // upper/lowercase) if s.get().chars().any(|c| c.is_lowercase()) { cx.span_lint(NON_UPPER_CASE_GLOBALS, it.span, - format!("static constant `{}` should have an uppercase name \ + &format!("static constant `{}` should have an uppercase name \ such as `{}`", - s.get(), s.get().chars().map(|c| c.to_uppercase()) - .collect::<String>().index(&FullRange)).index(&FullRange)); + s.get(), &s.get().chars().map(|c| c.to_uppercase()) + .collect::<String>()[])[]); } } _ => {} @@ -1083,10 +1083,10 @@ impl LintPass for NonUpperCaseGlobals { let s = token::get_ident(path1.node); if s.get().chars().any(|c| c.is_lowercase()) { cx.span_lint(NON_UPPER_CASE_GLOBALS, path1.span, - format!("static constant in pattern `{}` should have an uppercase \ + &format!("static constant in pattern `{}` should have an uppercase \ name such as `{}`", - s.get(), s.get().chars().map(|c| c.to_uppercase()) - .collect::<String>().index(&FullRange)).index(&FullRange)); + s.get(), &s.get().chars().map(|c| c.to_uppercase()) + .collect::<String>()[])[]); } } _ => {} @@ -1110,8 +1110,8 @@ impl UnusedParens { 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).index(&FullRange)) + &format!("unnecessary parentheses around {}", + msg)[]) } } @@ -1213,7 +1213,7 @@ impl LintPass for UnusedImportBraces { let m = format!("braces around {} is unnecessary", token::get_ident(*name).get()); cx.span_lint(UNUSED_IMPORT_BRACES, view_item.span, - m.index(&FullRange)); + &m[]); }, _ => () } @@ -1251,8 +1251,8 @@ impl LintPass for NonShorthandFieldPatterns { if let ast::PatIdent(_, ident, None) = fieldpat.node.pat.node { if ident.node.as_str() == fieldpat.node.ident.as_str() { cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, - format!("the `{}:` in this pattern is redundant and can \ - be removed", ident.node.as_str()).index(&FullRange)) + &format!("the `{}:` in this pattern is redundant and can \ + be removed", ident.node.as_str())[]) } } } @@ -1356,7 +1356,7 @@ impl LintPass for UnusedMut { fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { if let ast::ExprMatch(_, ref arms, _) = e.node { for a in arms.iter() { - self.check_unused_mut_pat(cx, a.pats.index(&FullRange)) + self.check_unused_mut_pat(cx, &a.pats[]) } } } @@ -1477,7 +1477,7 @@ impl MissingDoc { }); if !has_doc { cx.span_lint(MISSING_DOCS, sp, - format!("missing documentation for {}", desc).index(&FullRange)); + &format!("missing documentation for {}", desc)[]); } } } @@ -1491,7 +1491,7 @@ impl LintPass for MissingDoc { let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| { attr.check_name("doc") && match attr.meta_item_list() { None => false, - Some(l) => attr::contains_name(l.index(&FullRange), "hidden"), + Some(l) => attr::contains_name(&l[], "hidden"), } }); self.doc_hidden_stack.push(doc_hidden); @@ -1513,7 +1513,7 @@ impl LintPass for MissingDoc { } fn check_crate(&mut self, cx: &Context, krate: &ast::Crate) { - self.check_missing_docs_attrs(cx, None, krate.attrs.index(&FullRange), + self.check_missing_docs_attrs(cx, None, &krate.attrs[], krate.span, "crate"); } @@ -1527,7 +1527,7 @@ impl LintPass for MissingDoc { ast::ItemTy(..) => "a type alias", _ => return }; - self.check_missing_docs_attrs(cx, Some(it.id), it.attrs.index(&FullRange), + self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs[], it.span, desc); } @@ -1540,13 +1540,13 @@ impl LintPass for MissingDoc { // 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.index(&FullRange), + 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.index(&FullRange), + self.check_missing_docs_attrs(cx, Some(tm.id), &tm.attrs[], tm.span, "a type method"); } @@ -1556,14 +1556,14 @@ impl LintPass for MissingDoc { let cur_struct_def = *self.struct_def_stack.last() .expect("empty struct_def_stack"); self.check_missing_docs_attrs(cx, Some(cur_struct_def), - sf.node.attrs.index(&FullRange), sf.span, + &sf.node.attrs[], sf.span, "a struct field") } } } 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.index(&FullRange), + 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; @@ -1630,61 +1630,83 @@ declare_lint! { Warn, "detects use of #[deprecated] items" } -// FIXME #6875: Change to Warn after std library stabilization is complete -declare_lint! { - EXPERIMENTAL, - Allow, - "detects use of #[experimental] items" -} declare_lint! { UNSTABLE, - Allow, + Warn, "detects use of #[unstable] items (incl. items with no stability attribute)" } -/// Checks for use of items with `#[deprecated]`, `#[experimental]` and +/// Checks for use of items with `#[deprecated]`, `#[unstable]` and /// `#[unstable]` attributes, or no stability attribute. #[derive(Copy)] -pub struct Stability; +pub struct Stability { this_crate_staged: bool } impl Stability { + pub fn new() -> Stability { Stability { this_crate_staged: false } } + fn lint(&self, cx: &Context, id: ast::DefId, span: Span) { - let stability = stability::lookup(cx.tcx, id); + + let ref stability = stability::lookup(cx.tcx, id); let cross_crate = !ast_util::is_local(id); + let staged = (!cross_crate && self.this_crate_staged) + || (cross_crate && stability::is_staged_api(cx.tcx, id)); + + if !staged { return } // stability attributes are promises made across crates; only // check DEPRECATED for crate-local usage. - let (lint, label) = match stability { + let (lint, label) = match *stability { // no stability attributes == Unstable None if cross_crate => (UNSTABLE, "unmarked"), Some(attr::Stability { level: attr::Unstable, .. }) if cross_crate => (UNSTABLE, "unstable"), - Some(attr::Stability { level: attr::Experimental, .. }) if cross_crate => - (EXPERIMENTAL, "experimental"), Some(attr::Stability { level: attr::Deprecated, .. }) => (DEPRECATED, "deprecated"), _ => return }; - let msg = match stability { - Some(attr::Stability { text: Some(ref s), .. }) => { - format!("use of {} item: {}", label, *s) - } - _ => format!("use of {} item", label) - }; + output(cx, span, stability, lint, label); - cx.span_lint(lint, span, msg.index(&FullRange)); + fn output(cx: &Context, span: Span, stability: &Option<attr::Stability>, + lint: &'static Lint, label: &'static str) { + let msg = match *stability { + Some(attr::Stability { text: Some(ref s), .. }) => { + format!("use of {} item: {}", label, *s) + } + _ => format!("use of {} item", label) + }; + + cx.span_lint(lint, span, &msg[]); + } } + fn is_internal(&self, cx: &Context, span: Span) -> bool { cx.tcx.sess.codemap().span_is_internal(span) } + } impl LintPass for Stability { fn get_lints(&self) -> LintArray { - lint_array!(DEPRECATED, EXPERIMENTAL, UNSTABLE) + lint_array!(DEPRECATED, UNSTABLE) + } + + fn check_crate(&mut self, _: &Context, c: &ast::Crate) { + // Just mark the #[staged_api] attribute used, though nothing else is done + // with it during this pass over the source. + for attr in c.attrs.iter() { + if attr.name().get() == "staged_api" { + match attr.node.value.node { + ast::MetaWord(_) => { + attr::mark_used(attr); + self.this_crate_staged = true; + } + _ => (/*pass*/) + } + } + } } fn check_view_item(&mut self, cx: &Context, item: &ast::ViewItem) { @@ -1746,6 +1768,7 @@ impl LintPass for Stability { } _ => return }; + self.lint(cx, id, span); } @@ -1878,3 +1901,22 @@ impl LintPass for HardwiredLints { ) } } + +/// Forbids using the `#[feature(...)]` attribute +#[derive(Copy)] +pub struct UnstableFeatures; + +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"); + } + } +} diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 51998bdbcf2..95e1e8d44bf 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -28,8 +28,9 @@ use self::TargetLint::*; use middle::privacy::ExportedItems; use middle::ty::{self, Ty}; use session::{early_error, Session}; +use session::config::UnstableFeatures; use lint::{Level, LevelSource, Lint, LintId, LintArray, LintPass, LintPassObject}; -use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid}; +use lint::{Default, CommandLine, Node, Allow, Warn, Deny, Forbid, ReleaseChannel}; use lint::builtin; use util::nodemap::FnvHashMap; @@ -104,7 +105,7 @@ impl LintStore { } pub fn get_lints<'t>(&'t self) -> &'t [(&'static Lint, bool)] { - self.lints.index(&FullRange) + &self.lints[] } pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> { @@ -124,11 +125,11 @@ impl LintStore { match (sess, from_plugin) { // We load builtin lints first, so a duplicate is a compiler bug. // Use early_error when handling -W help with no crate. - (None, _) => early_error(msg.index(&FullRange)), - (Some(sess), false) => sess.bug(msg.index(&FullRange)), + (None, _) => early_error(&msg[]), + (Some(sess), false) => sess.bug(&msg[]), // A duplicate name from a plugin is a user error. - (Some(sess), true) => sess.err(msg.index(&FullRange)), + (Some(sess), true) => sess.err(&msg[]), } } @@ -149,11 +150,11 @@ impl LintStore { match (sess, from_plugin) { // We load builtin lints first, so a duplicate is a compiler bug. // Use early_error when handling -W help with no crate. - (None, _) => early_error(msg.index(&FullRange)), - (Some(sess), false) => sess.bug(msg.index(&FullRange)), + (None, _) => early_error(&msg[]), + (Some(sess), false) => sess.bug(&msg[]), // A duplicate name from a plugin is a user error. - (Some(sess), true) => sess.err(msg.index(&FullRange)), + (Some(sess), true) => sess.err(&msg[]), } } } @@ -208,14 +209,15 @@ impl LintStore { UnsafeBlocks, UnusedMut, UnusedAllocation, - Stability, MissingCopyImplementations, + UnstableFeatures, ); add_builtin_with_new!(sess, TypeLimits, RawPointerDerive, MissingDoc, + Stability, ); add_lint_group!(sess, "bad_style", @@ -267,8 +269,8 @@ impl LintStore { let warning = format!("lint {} has been renamed to {}", lint_name, new_name); match span { - Some(span) => sess.span_warn(span, warning.index(&FullRange)), - None => sess.warn(warning.index(&FullRange)), + Some(span) => sess.span_warn(span, &warning[]), + None => sess.warn(&warning[]), }; Some(lint_id) } @@ -278,26 +280,52 @@ impl LintStore { pub fn process_command_line(&mut self, sess: &Session) { for &(ref lint_name, level) in sess.opts.lint_opts.iter() { - match self.find_lint(lint_name.index(&FullRange), sess, None) { + match self.find_lint(&lint_name[], sess, None) { Some(lint_id) => self.set_level(lint_id, (level, CommandLine)), None => { match self.lint_groups.iter().map(|(&x, pair)| (x, pair.0.clone())) .collect::<FnvHashMap<&'static str, Vec<LintId>>>() - .get(lint_name.index(&FullRange)) { + .get(&lint_name[]) { Some(v) => { v.iter() .map(|lint_id: &LintId| self.set_level(*lint_id, (level, CommandLine))) .collect::<Vec<()>>(); } - None => sess.err(format!("unknown {} flag: {}", - level.as_str(), lint_name).index(&FullRange)), + None => sess.err(&format!("unknown {} flag: {}", + level.as_str(), lint_name)[]), } } } } } + + fn maybe_stage_features(&mut self, sess: &Session) { + let lvl = match sess.opts.unstable_features { + UnstableFeatures::Default => return, + UnstableFeatures::Disallow => Warn, + UnstableFeatures::Cheat => Allow + }; + match self.by_name.get("unstable_features") { + Some(&Id(lint_id)) => if self.get_level_source(lint_id).0 != Forbid { + self.set_level(lint_id, (lvl, ReleaseChannel)) + }, + Some(&Renamed(_, lint_id)) => if self.get_level_source(lint_id).0 != Forbid { + self.set_level(lint_id, (lvl, ReleaseChannel)) + }, + None => unreachable!() + } + match self.by_name.get("unstable") { + Some(&Id(lint_id)) => if self.get_level_source(lint_id).0 != Forbid { + self.set_level(lint_id, (lvl, ReleaseChannel)) + }, + Some(&Renamed(_, lint_id)) => if self.get_level_source(lint_id).0 != Forbid { + self.set_level(lint_id, (lvl, ReleaseChannel)) + }, + None => unreachable!() + } + } } /// Context for lint checking. @@ -380,6 +408,7 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, if level == Allow { return } let name = lint.name_lower(); + let mut def = None; let mut note = None; let msg = match source { Default => { @@ -394,7 +423,13 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, }, name.replace("_", "-")) }, Node(src) => { - note = Some(src); + def = Some(src); + msg.to_string() + } + ReleaseChannel => { + let release_channel = option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"); + note = Some(format!("this feature may not be used in the {} release channel", + release_channel)); msg.to_string() } }; @@ -403,14 +438,18 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint, if level == Forbid { level = Deny; } match (level, span) { - (Warn, Some(sp)) => sess.span_warn(sp, msg.index(&FullRange)), - (Warn, None) => sess.warn(msg.index(&FullRange)), - (Deny, Some(sp)) => sess.span_err(sp, msg.index(&FullRange)), - (Deny, None) => sess.err(msg.index(&FullRange)), + (Warn, Some(sp)) => sess.span_warn(sp, &msg[]), + (Warn, None) => sess.warn(&msg[]), + (Deny, Some(sp)) => sess.span_err(sp, &msg[]), + (Deny, None) => sess.err(&msg[]), _ => sess.bug("impossible level in raw_emit_lint"), } - for span in note.into_iter() { + for note in note.into_iter() { + sess.note(¬e[]); + } + + for span in def.into_iter() { sess.span_note(span, "lint level defined here"); } } @@ -513,9 +552,9 @@ impl<'a, 'tcx> Context<'a, 'tcx> { if now == Forbid && level != Forbid { let lint_name = lint_id.as_str(); self.tcx.sess.span_err(span, - format!("{}({}) overruled by outer forbid({})", + &format!("{}({}) overruled by outer forbid({})", level.as_str(), lint_name, - lint_name).index(&FullRange)); + lint_name)[]); } else if now != level { let src = self.lints.get_level_source(lint_id).1; self.level_stack.push((lint_id, (now, src))); @@ -550,7 +589,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { fn visit_item(&mut self, it: &ast::Item) { - self.with_lint_attrs(it.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&it.attrs[], |cx| { run_lints!(cx, check_item, it); cx.visit_ids(|v| v.visit_item(it)); visit::walk_item(cx, it); @@ -558,14 +597,14 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { } fn visit_foreign_item(&mut self, it: &ast::ForeignItem) { - self.with_lint_attrs(it.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&it.attrs[], |cx| { run_lints!(cx, check_foreign_item, it); visit::walk_foreign_item(cx, it); }) } fn visit_view_item(&mut self, i: &ast::ViewItem) { - self.with_lint_attrs(i.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&i.attrs[], |cx| { run_lints!(cx, check_view_item, i); cx.visit_ids(|v| v.visit_view_item(i)); visit::walk_view_item(cx, i); @@ -591,7 +630,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { body: &'v ast::Block, span: Span, id: ast::NodeId) { match fk { visit::FkMethod(_, _, m) => { - self.with_lint_attrs(m.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&m.attrs[], |cx| { run_lints!(cx, check_fn, fk, decl, body, span, id); cx.visit_ids(|v| { v.visit_fn(fk, decl, body, span, id); @@ -607,7 +646,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { } fn visit_ty_method(&mut self, t: &ast::TypeMethod) { - self.with_lint_attrs(t.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&t.attrs[], |cx| { run_lints!(cx, check_ty_method, t); visit::walk_ty_method(cx, t); }) @@ -624,14 +663,14 @@ impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> { } fn visit_struct_field(&mut self, s: &ast::StructField) { - self.with_lint_attrs(s.node.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&s.node.attrs[], |cx| { run_lints!(cx, check_struct_field, s); visit::walk_struct_field(cx, s); }) } fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics) { - self.with_lint_attrs(v.node.attrs.index(&FullRange), |cx| { + self.with_lint_attrs(&v.node.attrs[], |cx| { run_lints!(cx, check_variant, v, g); visit::walk_variant(cx, v, g); run_lints!(cx, check_variant_post, v, g); @@ -725,7 +764,7 @@ impl<'a, 'tcx> IdVisitingOperation for Context<'a, 'tcx> { None => {} Some(lints) => { for (lint_id, span, msg) in lints.into_iter() { - self.span_lint(lint_id.lint, span, msg.index(&FullRange)) + self.span_lint(lint_id.lint, span, &msg[]) } } } @@ -767,11 +806,15 @@ impl LintPass for GatherNodeLevels { /// Consumes the `lint_store` field of the `Session`. pub fn check_crate(tcx: &ty::ctxt, exported_items: &ExportedItems) { + + // If this is a feature-staged build of rustc then flip several lints to 'forbid' + tcx.sess.lint_store.borrow_mut().maybe_stage_features(&tcx.sess); + let krate = tcx.map.krate(); let mut cx = Context::new(tcx, krate, exported_items); // Visit the whole crate. - cx.with_lint_attrs(krate.attrs.index(&FullRange), |cx| { + cx.with_lint_attrs(&krate.attrs[], |cx| { cx.visit_id(ast::CRATE_NODE_ID); cx.visit_ids(|v| { v.visited_outermost = true; diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index e9778fa05ff..826a35e3bb5 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -40,7 +40,7 @@ use syntax::ast; pub use lint::context::{Context, LintStore, raw_emit_lint, check_crate, gather_attrs}; /// Specification of a single lint. -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Lint { /// A string identifier for the lint. /// @@ -186,7 +186,7 @@ impl PartialEq for LintId { impl Eq for LintId { } -impl<S: hash::Writer> hash::Hash<S> for LintId { +impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for LintId { fn hash(&self, state: &mut S) { let ptr = self.lint as *const Lint; ptr.hash(state); @@ -208,7 +208,7 @@ impl LintId { } /// Setting for how to handle a lint. -#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)] +#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show)] pub enum Level { Allow, Warn, Deny, Forbid } @@ -248,6 +248,9 @@ pub enum LintSource { /// Lint level was set by a command-line flag. CommandLine, + + /// Lint level was set by the release channel. + ReleaseChannel } pub type LevelSource = (Level, LintSource); diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 66967a73546..4a2981b8cdf 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -26,7 +26,7 @@ use syntax::ast; use syntax::abi; use syntax::attr; use syntax::attr::AttrMetaMethods; -use syntax::codemap::{Span, mk_sp}; +use syntax::codemap::{COMMAND_LINE_SP, Span, mk_sp}; use syntax::parse; use syntax::parse::token::InternedString; use syntax::parse::token; @@ -65,7 +65,7 @@ fn dump_crates(cstore: &CStore) { } fn should_link(i: &ast::ViewItem) -> bool { - !attr::contains_name(i.attrs.index(&FullRange), "no_link") + !attr::contains_name(&i.attrs[], "no_link") } @@ -90,7 +90,7 @@ pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) { for c in s.chars() { if c.is_alphanumeric() { continue } if c == '_' || c == '-' { continue } - err(format!("invalid character `{}` in crate name: `{}`", c, s).index(&FullRange)); + err(&format!("invalid character `{}` in crate name: `{}`", c, s)[]); } match sess { Some(sess) => sess.abort_if_errors(), @@ -189,8 +189,8 @@ impl<'a> CrateReader<'a> { match self.extract_crate_info(i) { Some(info) => { let (cnum, _, _) = self.resolve_crate(&None, - info.ident.index(&FullRange), - info.name.index(&FullRange), + &info.ident[], + &info.name[], None, i.span, PathKind::Crate); @@ -209,7 +209,7 @@ impl<'a> CrateReader<'a> { let name = match *path_opt { Some((ref path_str, _)) => { let name = path_str.get().to_string(); - validate_crate_name(Some(self.sess), name.index(&FullRange), + validate_crate_name(Some(self.sess), &name[], Some(i.span)); name } @@ -275,8 +275,8 @@ impl<'a> CrateReader<'a> { cstore::NativeUnknown } else { self.sess.span_err(m.span, - format!("unknown kind: `{}`", - k).index(&FullRange)); + &format!("unknown kind: `{}`", + k)[]); cstore::NativeUnknown } } @@ -330,7 +330,7 @@ impl<'a> CrateReader<'a> { match self.sess.opts.externs.get(name) { Some(locs) => { let found = locs.iter().any(|l| { - let l = fs::realpath(&Path::new(l.index(&FullRange))).ok(); + let l = fs::realpath(&Path::new(&l[])).ok(); l == source.dylib || l == source.rlib }); if found { @@ -409,7 +409,7 @@ impl<'a> CrateReader<'a> { crate_name: name, hash: hash.map(|a| &*a), filesearch: self.sess.target_filesearch(kind), - triple: self.sess.opts.target_triple.index(&FullRange), + triple: &self.sess.opts.target_triple[], root: root, rejected_via_hash: vec!(), rejected_via_triple: vec!(), @@ -435,8 +435,8 @@ impl<'a> CrateReader<'a> { decoder::get_crate_deps(cdata).iter().map(|dep| { debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash); let (local_cnum, _, _) = self.resolve_crate(root, - dep.name.index(&FullRange), - dep.name.index(&FullRange), + &dep.name[], + &dep.name[], Some(&dep.hash), span, PathKind::Dependency); @@ -445,9 +445,21 @@ impl<'a> CrateReader<'a> { } pub fn read_plugin_metadata<'b>(&'b mut self, - vi: &'b ast::ViewItem) -> PluginMetadata<'b> { - let info = self.extract_crate_info(vi).unwrap(); - let target_triple = self.sess.opts.target_triple.index(&FullRange); + krate: CrateOrString<'b>) -> PluginMetadata<'b> { + let (info, span) = match krate { + CrateOrString::Krate(c) => { + (self.extract_crate_info(c).unwrap(), c.span) + } + CrateOrString::Str(s) => { + (CrateInfo { + name: s.to_string(), + ident: s.to_string(), + id: ast::DUMMY_NODE_ID, + should_link: true, + }, COMMAND_LINE_SP) + } + }; + let target_triple = &self.sess.opts.target_triple[]; let is_cross = target_triple != config::host_triple(); let mut should_link = info.should_link && !is_cross; let mut target_only = false; @@ -455,9 +467,9 @@ impl<'a> CrateReader<'a> { let name = info.name.clone(); let mut load_ctxt = loader::Context { sess: self.sess, - span: vi.span, - ident: ident.index(&FullRange), - crate_name: name.index(&FullRange), + span: span, + ident: &ident[], + crate_name: &name[], hash: None, filesearch: self.sess.host_filesearch(PathKind::Crate), triple: config::host_triple(), @@ -485,8 +497,8 @@ impl<'a> CrateReader<'a> { let register = should_link && self.existing_match(info.name.as_slice(), None).is_none(); let metadata = if register { // Register crate now to avoid double-reading metadata - let (_, cmd, _) = self.register_crate(&None, info.ident.index(&FullRange), - info.name.index(&FullRange), vi.span, library); + let (_, cmd, _) = self.register_crate(&None, &info.ident[], + &info.name[], span, library); PMDSource::Registered(cmd) } else { // Not registering the crate; just hold on to the metadata @@ -498,17 +510,23 @@ impl<'a> CrateReader<'a> { metadata: metadata, dylib: dylib, info: info, - vi_span: vi.span, + vi_span: span, target_only: target_only, } } } +#[derive(Copy)] +pub enum CrateOrString<'a> { + Krate(&'a ast::ViewItem), + Str(&'a str) +} + impl<'a> PluginMetadata<'a> { /// Read exported macros pub fn exported_macros(&self) -> Vec<ast::MacroDef> { - let imported_from = Some(token::intern(self.info.ident.index(&FullRange)).ident()); - let source_name = format!("<{} macros>", self.info.ident.index(&FullRange)); + let imported_from = Some(token::intern(&self.info.ident[]).ident()); + let source_name = format!("<{} macros>", &self.info.ident[]); let mut macros = vec![]; decoder::each_exported_macro(self.metadata.as_slice(), &*self.sess.cstore.intr, @@ -550,7 +568,7 @@ impl<'a> PluginMetadata<'a> { self.info.ident, config::host_triple(), self.sess.opts.target_triple); - self.sess.span_err(self.vi_span, message.index(&FullRange)); + self.sess.span_err(self.vi_span, &message[]); self.sess.abort_if_errors(); } @@ -563,7 +581,7 @@ impl<'a> PluginMetadata<'a> { let message = format!("plugin crate `{}` only found in rlib format, \ but must be available in dylib format", self.info.ident); - self.sess.span_err(self.vi_span, message.index(&FullRange)); + self.sess.span_err(self.vi_span, &message[]); // No need to abort because the loading code will just ignore this // empty dylib. None diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 72ce61b133a..cfff7c9935b 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -27,6 +27,7 @@ use std::rc::Rc; use syntax::ast; use syntax::ast_map; use syntax::attr; +use syntax::attr::AttrMetaMethods; use syntax::diagnostic::expect; use syntax::parse::token; @@ -95,7 +96,7 @@ pub fn get_item_path(tcx: &ty::ctxt, def: ast::DefId) -> Vec<ast_map::PathElem> // FIXME #1920: This path is not always correct if the crate is not linked // into the root namespace. - let mut r = vec![ast_map::PathMod(token::intern(cdata.name.index(&FullRange)))]; + let mut r = vec![ast_map::PathMod(token::intern(&cdata.name[]))]; r.push_all(path.as_slice()); r } @@ -375,6 +376,18 @@ pub fn get_stability(cstore: &cstore::CStore, decoder::get_stability(&*cdata, def.node) } +pub fn is_staged_api(cstore: &cstore::CStore, def: ast::DefId) -> bool { + let cdata = cstore.get_crate_data(def.krate); + let attrs = decoder::get_crate_attributes(cdata.data()); + for attr in attrs.iter() { + if attr.name().get() == "staged_api" { + match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) } + } + } + + return false; +} + pub fn get_repr_attrs(cstore: &cstore::CStore, def: ast::DefId) -> Vec<attr::ReprAttr> { let cdata = cstore.get_crate_data(def.krate); diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 9e71c867efa..5ac8f908bf1 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -33,8 +33,7 @@ use middle::ty::{self, Ty}; use middle::astencode::vtable_decoder_helpers; use std::collections::HashMap; -use std::hash::Hash; -use std::hash; +use std::hash::{self, Hash, SipHasher}; use std::io::extensions::u64_from_be_bytes; use std::io; use std::num::FromPrimitive; @@ -75,7 +74,7 @@ fn lookup_hash<'a, F>(d: rbml::Doc<'a>, mut eq_fn: F, hash: u64) -> Option<rbml: let mut ret = None; reader::tagged_docs(tagged_doc.doc, belt, |elt| { let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint; - if eq_fn(elt.data.index(&((elt.start + 4) .. elt.end))) { + if eq_fn(&elt.data[(elt.start + 4) .. elt.end]) { ret = Some(reader::doc_at(d.data, pos).unwrap().doc); false } else { @@ -89,12 +88,12 @@ pub fn maybe_find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> { fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool { return u64_from_be_bytes( - bytes.index(&(0u..4u)), 0u, 4u) as ast::NodeId + &bytes[0u..4u], 0u, 4u) as ast::NodeId == item_id; } lookup_hash(items, |a| eq_item(a, item_id), - hash::hash(&(item_id as i64))) + hash::hash::<i64, SipHasher>(&(item_id as i64))) } fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> { @@ -1191,7 +1190,7 @@ pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> { } reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| { let name = docstr(depdoc, tag_crate_dep_crate_name); - let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash).index(&FullRange)); + let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash)[]); deps.push(CrateDep { cnum: crate_num, name: name, diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 83038df338b..c8921f1b2fb 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -29,8 +29,7 @@ use util::nodemap::{FnvHashMap, NodeMap, NodeSet}; use serialize::Encodable; use std::cell::RefCell; -use std::hash::Hash; -use std::hash; +use std::hash::{Hash, Hasher, SipHasher}; use syntax::abi; use syntax::ast::{self, DefId, NodeId}; use syntax::ast_map::{PathElem, PathElems}; @@ -95,7 +94,7 @@ fn encode_impl_type_basename(rbml_w: &mut Encoder, name: ast::Ident) { } pub fn encode_def_id(rbml_w: &mut Encoder, id: DefId) { - rbml_w.wr_tagged_str(tag_def_id, def_to_string(id).index(&FullRange)); + rbml_w.wr_tagged_str(tag_def_id, &def_to_string(id)[]); } #[derive(Clone)] @@ -154,7 +153,7 @@ fn encode_variant_id(rbml_w: &mut Encoder, vid: DefId) { rbml_w.end_tag(); rbml_w.start_tag(tag_mod_child); - rbml_w.wr_str(s.index(&FullRange)); + rbml_w.wr_str(&s[]); rbml_w.end_tag(); } @@ -264,7 +263,7 @@ fn encode_symbol(ecx: &EncodeContext, } None => { ecx.diag.handler().bug( - format!("encode_symbol: id not found {}", id).index(&FullRange)); + &format!("encode_symbol: id not found {}", id)[]); } } rbml_w.end_tag(); @@ -332,8 +331,8 @@ fn encode_enum_variant_info(ecx: &EncodeContext, encode_name(rbml_w, variant.node.name.name); encode_parent_item(rbml_w, local_def(id)); encode_visibility(rbml_w, variant.node.vis); - encode_attributes(rbml_w, variant.node.attrs.index(&FullRange)); - encode_repr_attrs(rbml_w, ecx, variant.node.attrs.index(&FullRange)); + encode_attributes(rbml_w, &variant.node.attrs[]); + encode_repr_attrs(rbml_w, ecx, &variant.node.attrs[]); let stab = stability::lookup(ecx.tcx, ast_util::local_def(variant.node.id)); encode_stability(rbml_w, stab); @@ -344,9 +343,9 @@ fn encode_enum_variant_info(ecx: &EncodeContext, let fields = ty::lookup_struct_fields(ecx.tcx, def_id); let idx = encode_info_for_struct(ecx, rbml_w, - fields.index(&FullRange), + &fields[], index); - encode_struct_fields(rbml_w, fields.index(&FullRange), def_id); + encode_struct_fields(rbml_w, &fields[], def_id); encode_index(rbml_w, idx, write_i64); } } @@ -386,12 +385,12 @@ fn encode_reexported_static_method(rbml_w: &mut Encoder, 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).index(&FullRange)); + 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!("{}::{}", + rbml_w.wr_str(&format!("{}::{}", exp.name, - token::get_name(method_name)).index(&FullRange)); + token::get_name(method_name))[]); rbml_w.end_tag(); rbml_w.end_tag(); } @@ -529,7 +528,7 @@ fn encode_reexports(ecx: &EncodeContext, 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).index(&FullRange)); + 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()); @@ -562,13 +561,13 @@ fn encode_info_for_mod(ecx: &EncodeContext, // Encode info about all the module children. for item in md.items.iter() { rbml_w.start_tag(tag_mod_child); - rbml_w.wr_str(def_to_string(local_def(item.id)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def(item.id))[]); rbml_w.end_tag(); 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)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def( + auxiliary_node_id))[]); rbml_w.end_tag(); true }); @@ -580,7 +579,7 @@ fn encode_info_for_mod(ecx: &EncodeContext, 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)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def(did))[]); rbml_w.end_tag(); } } @@ -615,7 +614,7 @@ fn encode_visibility(rbml_w: &mut Encoder, visibility: ast::Visibility) { ast::Public => 'y', ast::Inherited => 'i', }; - rbml_w.wr_str(ch.to_string().index(&FullRange)); + rbml_w.wr_str(&ch.to_string()[]); rbml_w.end_tag(); } @@ -627,7 +626,7 @@ fn encode_unboxed_closure_kind(rbml_w: &mut Encoder, ty::FnMutUnboxedClosureKind => 'm', ty::FnOnceUnboxedClosureKind => 'o', }; - rbml_w.wr_str(ch.to_string().index(&FullRange)); + rbml_w.wr_str(&ch.to_string()[]); rbml_w.end_tag(); } @@ -788,7 +787,7 @@ fn encode_generics<'a, 'tcx>(rbml_w: &mut Encoder, rbml_w.end_tag(); rbml_w.wr_tagged_str(tag_region_param_def_def_id, - def_to_string(param.def_id).index(&FullRange)); + &def_to_string(param.def_id)[]); rbml_w.wr_tagged_u64(tag_region_param_def_space, param.space.to_uint() as u64); @@ -864,9 +863,9 @@ fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, encode_path(rbml_w, impl_path.chain(Some(elem).into_iter())); match ast_item_opt { Some(&ast::MethodImplItem(ref ast_method)) => { - encode_attributes(rbml_w, ast_method.attrs.index(&FullRange)); + encode_attributes(rbml_w, &ast_method.attrs[]); let any_types = !pty.generics.types.is_empty(); - if any_types || is_default_impl || should_inline(ast_method.attrs.index(&FullRange)) { + if any_types || is_default_impl || should_inline(&ast_method.attrs[]) { encode_inlined_item(ecx, rbml_w, IIImplItemRef(local_def(parent_id), ast_item_opt.unwrap())); } @@ -912,7 +911,7 @@ fn encode_info_for_associated_type(ecx: &EncodeContext, match typedef_opt { None => {} Some(typedef) => { - encode_attributes(rbml_w, typedef.attrs.index(&FullRange)); + encode_attributes(rbml_w, &typedef.attrs[]); encode_type(ecx, rbml_w, ty::node_id_to_type(ecx.tcx, typedef.id)); } @@ -1046,7 +1045,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_path(rbml_w, path); encode_visibility(rbml_w, vis); encode_stability(rbml_w, stab); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); + encode_attributes(rbml_w, &item.attrs[]); rbml_w.end_tag(); } ast::ItemConst(_, _) => { @@ -1072,8 +1071,8 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_bounds_and_type(rbml_w, ecx, &lookup_item_type(tcx, def_id)); encode_name(rbml_w, item.ident.name); encode_path(rbml_w, path); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); - if tps_len > 0u || should_inline(item.attrs.index(&FullRange)) { + encode_attributes(rbml_w, &item.attrs[]); + if tps_len > 0u || should_inline(&item.attrs[]) { encode_inlined_item(ecx, rbml_w, IIItemRef(item)); } if tps_len == 0 { @@ -1089,7 +1088,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_info_for_mod(ecx, rbml_w, m, - item.attrs.index(&FullRange), + &item.attrs[], item.id, path, item.ident, @@ -1106,7 +1105,7 @@ fn encode_info_for_item(ecx: &EncodeContext, // Encode all the items in this module. for foreign_item in fm.items.iter() { rbml_w.start_tag(tag_mod_child); - rbml_w.wr_str(def_to_string(local_def(foreign_item.id)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def(foreign_item.id))[]); rbml_w.end_tag(); } encode_visibility(rbml_w, vis); @@ -1134,8 +1133,8 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_item_variances(rbml_w, ecx, item.id); encode_bounds_and_type(rbml_w, ecx, &lookup_item_type(tcx, def_id)); encode_name(rbml_w, item.ident.name); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); - encode_repr_attrs(rbml_w, ecx, item.attrs.index(&FullRange)); + encode_attributes(rbml_w, &item.attrs[]); + encode_repr_attrs(rbml_w, ecx, &item.attrs[]); for v in (*enum_definition).variants.iter() { encode_variant_id(rbml_w, local_def(v.node.id)); } @@ -1152,7 +1151,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_enum_variant_info(ecx, rbml_w, item.id, - (*enum_definition).variants.index(&FullRange), + &(*enum_definition).variants[], index); } ast::ItemStruct(ref struct_def, _) => { @@ -1164,7 +1163,7 @@ fn encode_info_for_item(ecx: &EncodeContext, class itself */ let idx = encode_info_for_struct(ecx, rbml_w, - fields.index(&FullRange), + &fields[], index); /* Index the class*/ @@ -1178,16 +1177,16 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_item_variances(rbml_w, ecx, item.id); encode_name(rbml_w, item.ident.name); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); + encode_attributes(rbml_w, &item.attrs[]); encode_path(rbml_w, path.clone()); encode_stability(rbml_w, stab); encode_visibility(rbml_w, vis); - encode_repr_attrs(rbml_w, ecx, item.attrs.index(&FullRange)); + encode_repr_attrs(rbml_w, ecx, &item.attrs[]); /* Encode def_ids for each field and method for methods, write all the stuff get_trait_method needs to know*/ - encode_struct_fields(rbml_w, fields.index(&FullRange), def_id); + encode_struct_fields(rbml_w, &fields[], def_id); encode_inlined_item(ecx, rbml_w, IIItemRef(item)); @@ -1219,7 +1218,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_family(rbml_w, 'i'); encode_bounds_and_type(rbml_w, ecx, &lookup_item_type(tcx, def_id)); encode_name(rbml_w, item.ident.name); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); + encode_attributes(rbml_w, &item.attrs[]); encode_unsafety(rbml_w, unsafety); encode_polarity(rbml_w, polarity); match ty.node { @@ -1323,7 +1322,7 @@ fn encode_info_for_item(ecx: &EncodeContext, encode_generics(rbml_w, ecx, &trait_def.generics, tag_item_generics); encode_trait_ref(rbml_w, ecx, &*trait_def.trait_ref, tag_item_trait_ref); encode_name(rbml_w, item.ident.name); - encode_attributes(rbml_w, item.attrs.index(&FullRange)); + encode_attributes(rbml_w, &item.attrs[]); encode_visibility(rbml_w, vis); encode_stability(rbml_w, stab); for &method_def_id in ty::trait_item_def_ids(tcx, def_id).iter() { @@ -1341,7 +1340,7 @@ fn encode_info_for_item(ecx: &EncodeContext, rbml_w.end_tag(); rbml_w.start_tag(tag_mod_child); - rbml_w.wr_str(def_to_string(method_def_id.def_id()).index(&FullRange)); + rbml_w.wr_str(&def_to_string(method_def_id.def_id())[]); rbml_w.end_tag(); } encode_path(rbml_w, path.clone()); @@ -1433,14 +1432,14 @@ fn encode_info_for_item(ecx: &EncodeContext, }; match trait_item { &ast::RequiredMethod(ref m) => { - encode_attributes(rbml_w, m.attrs.index(&FullRange)); + encode_attributes(rbml_w, &m.attrs[]); encode_trait_item(rbml_w); encode_item_sort(rbml_w, 'r'); encode_method_argument_names(rbml_w, &*m.decl); } &ast::ProvidedMethod(ref m) => { - encode_attributes(rbml_w, m.attrs.index(&FullRange)); + encode_attributes(rbml_w, &m.attrs[]); encode_trait_item(rbml_w); encode_item_sort(rbml_w, 'p'); encode_inlined_item(ecx, rbml_w, IITraitItemRef(def_id, trait_item)); @@ -1449,7 +1448,7 @@ fn encode_info_for_item(ecx: &EncodeContext, &ast::TypeTraitItem(ref associated_type) => { encode_attributes(rbml_w, - associated_type.attrs.index(&FullRange)); + &associated_type.attrs[]); encode_item_sort(rbml_w, 't'); } } @@ -1598,11 +1597,13 @@ fn encode_info_for_items(ecx: &EncodeContext, fn encode_index<T, F>(rbml_w: &mut Encoder, index: Vec<entry<T>>, mut write_fn: F) where F: FnMut(&mut SeekableMemWriter, &T), - T: Hash, + T: Hash<SipHasher>, { let mut buckets: Vec<Vec<entry<T>>> = range(0, 256u16).map(|_| Vec::new()).collect(); for elt in index.into_iter() { - let h = hash::hash(&elt.val) as uint; + let mut s = SipHasher::new(); + elt.val.hash(&mut s); + let h = s.finish() as uint; (&mut buckets[h % 256]).push(elt); } @@ -1826,10 +1827,10 @@ fn encode_macro_defs(rbml_w: &mut Encoder, rbml_w.start_tag(tag_macro_def); encode_name(rbml_w, def.ident.name); - encode_attributes(rbml_w, def.attrs.index(&FullRange)); + encode_attributes(rbml_w, &def.attrs[]); rbml_w.start_tag(tag_macro_def_body); - rbml_w.wr_str(pprust::tts_to_string(def.body.index(&FullRange)).index(&FullRange)); + rbml_w.wr_str(&pprust::tts_to_string(&def.body[])[]); rbml_w.end_tag(); rbml_w.end_tag(); @@ -1869,7 +1870,7 @@ fn encode_struct_field_attrs(rbml_w: &mut Encoder, krate: &ast::Crate) { fn visit_struct_field(&mut self, field: &ast::StructField) { self.rbml_w.start_tag(tag_struct_field); self.rbml_w.wr_tagged_u32(tag_struct_field_id, field.node.id); - encode_attributes(self.rbml_w, field.node.attrs.index(&FullRange)); + encode_attributes(self.rbml_w, &field.node.attrs[]); self.rbml_w.end_tag(); } } @@ -1941,13 +1942,13 @@ fn encode_misc_info(ecx: &EncodeContext, rbml_w.start_tag(tag_misc_info_crate_items); for item in krate.module.items.iter() { rbml_w.start_tag(tag_mod_child); - rbml_w.wr_str(def_to_string(local_def(item.id)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def(item.id))[]); rbml_w.end_tag(); 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)).index(&FullRange)); + rbml_w.wr_str(&def_to_string(local_def( + auxiliary_node_id))[]); rbml_w.end_tag(); true }); @@ -2116,17 +2117,17 @@ fn encode_metadata_inner(wr: &mut SeekableMemWriter, let mut rbml_w = writer::Encoder::new(wr); - encode_crate_name(&mut rbml_w, ecx.link_meta.crate_name.index(&FullRange)); + encode_crate_name(&mut rbml_w, &ecx.link_meta.crate_name[]); encode_crate_triple(&mut rbml_w, - tcx.sess + &tcx.sess .opts .target_triple - .index(&FullRange)); + []); encode_hash(&mut rbml_w, &ecx.link_meta.crate_hash); encode_dylib_dependency_formats(&mut rbml_w, &ecx); let mut i = rbml_w.writer.tell().unwrap(); - encode_attributes(&mut rbml_w, krate.attrs.index(&FullRange)); + encode_attributes(&mut rbml_w, &krate.attrs[]); stats.attr_bytes = rbml_w.writer.tell().unwrap() - i; i = rbml_w.writer.tell().unwrap(); diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 29625d0a6af..e8160487e16 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -272,12 +272,12 @@ fn find_libdir(sysroot: &Path) -> String { } } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] fn primary_libdir_name() -> String { "lib64".to_string() } - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] fn primary_libdir_name() -> String { "lib32".to_string() } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 0fa9472287c..3a925aba0b7 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -315,14 +315,14 @@ impl<'a> Context<'a> { &Some(ref r) => format!("{} which `{}` depends on", message, r.ident) }; - self.sess.span_err(self.span, message.index(&FullRange)); + self.sess.span_err(self.span, &message[]); if self.rejected_via_triple.len() > 0 { let mismatches = self.rejected_via_triple.iter(); for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() { self.sess.fileline_note(self.span, - format!("crate `{}`, path #{}, triple {}: {}", - self.ident, i+1, got, path.display()).index(&FullRange)); + &format!("crate `{}`, path #{}, triple {}: {}", + self.ident, i+1, got, path.display())[]); } } if self.rejected_via_hash.len() > 0 { @@ -331,16 +331,16 @@ impl<'a> Context<'a> { let mismatches = self.rejected_via_hash.iter(); for (i, &CrateMismatch{ ref path, .. }) in mismatches.enumerate() { self.sess.fileline_note(self.span, - format!("crate `{}` path {}{}: {}", - self.ident, "#", i+1, path.display()).index(&FullRange)); + &format!("crate `{}` path {}{}: {}", + self.ident, "#", i+1, path.display())[]); } match self.root { &None => {} &Some(ref r) => { for (i, path) in r.paths().iter().enumerate() { self.sess.fileline_note(self.span, - format!("crate `{}` path #{}: {}", - r.ident, i+1, path.display()).index(&FullRange)); + &format!("crate `{}` path #{}: {}", + r.ident, i+1, path.display())[]); } } } @@ -386,7 +386,7 @@ impl<'a> Context<'a> { None => return FileDoesntMatch, Some(file) => file, }; - let (hash, rlib) = if file.starts_with(rlib_prefix.index(&FullRange)) && + let (hash, rlib) = if file.starts_with(&rlib_prefix[]) && file.ends_with(".rlib") { (file.slice(rlib_prefix.len(), file.len() - ".rlib".len()), true) @@ -445,27 +445,27 @@ impl<'a> Context<'a> { 1 => Some(libraries.into_iter().next().unwrap()), _ => { self.sess.span_err(self.span, - format!("multiple matching crates for `{}`", - self.crate_name).index(&FullRange)); + &format!("multiple matching crates for `{}`", + self.crate_name)[]); self.sess.note("candidates:"); for lib in libraries.iter() { match lib.dylib { Some(ref p) => { - self.sess.note(format!("path: {}", - p.display()).index(&FullRange)); + self.sess.note(&format!("path: {}", + p.display())[]); } None => {} } match lib.rlib { Some(ref p) => { - self.sess.note(format!("path: {}", - p.display()).index(&FullRange)); + self.sess.note(&format!("path: {}", + p.display())[]); } None => {} } let data = lib.metadata.as_slice(); let name = decoder::get_crate_name(data); - note_crate_name(self.sess.diagnostic(), name.index(&FullRange)); + note_crate_name(self.sess.diagnostic(), &name[]); } None } @@ -516,22 +516,22 @@ impl<'a> Context<'a> { }; if ret.is_some() { self.sess.span_err(self.span, - format!("multiple {} candidates for `{}` \ + &format!("multiple {} candidates for `{}` \ found", flavor, - self.crate_name).index(&FullRange)); + self.crate_name)[]); self.sess.span_note(self.span, - format!(r"candidate #1: {}", + &format!(r"candidate #1: {}", ret.as_ref().unwrap() - .display()).index(&FullRange)); + .display())[]); error = 1; ret = None; } if error > 0 { error += 1; self.sess.span_note(self.span, - format!(r"candidate #{}: {}", error, - lib.display()).index(&FullRange)); + &format!(r"candidate #{}: {}", error, + lib.display())[]); continue } *slot = Some(metadata); @@ -606,17 +606,17 @@ impl<'a> Context<'a> { let mut rlibs = HashSet::new(); let mut dylibs = HashSet::new(); { - let mut locs = locs.iter().map(|l| Path::new(l.index(&FullRange))).filter(|loc| { + let mut locs = locs.iter().map(|l| Path::new(&l[])).filter(|loc| { if !loc.exists() { - sess.err(format!("extern location for {} does not exist: {}", - self.crate_name, loc.display()).index(&FullRange)); + sess.err(&format!("extern location for {} does not exist: {}", + self.crate_name, loc.display())[]); return false; } let file = match loc.filename_str() { Some(file) => file, None => { - sess.err(format!("extern location for {} is not a file: {}", - self.crate_name, loc.display()).index(&FullRange)); + sess.err(&format!("extern location for {} is not a file: {}", + self.crate_name, loc.display())[]); return false; } }; @@ -624,13 +624,13 @@ impl<'a> Context<'a> { return true } else { let (ref prefix, ref suffix) = dylibname; - if file.starts_with(prefix.index(&FullRange)) && - file.ends_with(suffix.index(&FullRange)) { + if file.starts_with(&prefix[]) && + file.ends_with(&suffix[]) { return true } } - sess.err(format!("extern location for {} is of an unknown type: {}", - self.crate_name, loc.display()).index(&FullRange)); + sess.err(&format!("extern location for {} is of an unknown type: {}", + self.crate_name, loc.display())[]); false }); @@ -663,7 +663,7 @@ impl<'a> Context<'a> { } pub fn note_crate_name(diag: &SpanHandler, name: &str) { - diag.handler().note(format!("crate name: {}", name).index(&FullRange)); + diag.handler().note(&format!("crate name: {}", name)[]); } impl ArchiveMetadata { diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index a4304bf1e2d..5aacaa04e46 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -98,7 +98,7 @@ fn scan<R, F, G>(st: &mut PState, mut is_last: F, op: G) -> R where } let end_pos = st.pos; st.pos += 1; - return op(st.data.index(&(start_pos..end_pos))); + return op(&st.data[start_pos..end_pos]); } pub fn parse_ident(st: &mut PState, last: char) -> ast::Ident { @@ -250,8 +250,8 @@ fn parse_trait_store_<F>(st: &mut PState, conv: &mut F) -> ty::TraitStore where '~' => ty::UniqTraitStore, '&' => ty::RegionTraitStore(parse_region_(st, conv), parse_mutability(st)), c => { - st.tcx.sess.bug(format!("parse_trait_store(): bad input '{}'", - c).index(&FullRange)) + st.tcx.sess.bug(&format!("parse_trait_store(): bad input '{}'", + c)[]) } } } @@ -318,7 +318,7 @@ fn parse_bound_region_<F>(st: &mut PState, conv: &mut F) -> ty::BoundRegion wher } '[' => { let def = parse_def_(st, RegionParameter, conv); - let ident = token::str_to_ident(parse_str(st, ']').index(&FullRange)); + let ident = token::str_to_ident(&parse_str(st, ']')[]); ty::BrNamed(def, ident.name) } 'f' => { @@ -357,7 +357,7 @@ fn parse_region_<F>(st: &mut PState, conv: &mut F) -> ty::Region where assert_eq!(next(st), '|'); let index = parse_u32(st); assert_eq!(next(st), '|'); - let nm = token::str_to_ident(parse_str(st, ']').index(&FullRange)); + let nm = token::str_to_ident(&parse_str(st, ']')[]); ty::ReEarlyBound(node_id, space, index, nm.name) } 'f' => { @@ -481,7 +481,7 @@ fn parse_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> Ty<'tcx> w assert_eq!(next(st), '|'); let space = parse_param_space(st); assert_eq!(next(st), '|'); - let name = token::intern(parse_str(st, ']').index(&FullRange)); + let name = token::intern(&parse_str(st, ']')[]); return ty::mk_param(tcx, space, index, name); } '~' => return ty::mk_uniq(tcx, parse_ty_(st, conv)), @@ -637,7 +637,7 @@ fn parse_abi_set(st: &mut PState) -> abi::Abi { assert_eq!(next(st), '['); scan(st, |c| c == ']', |bytes| { let abi_str = str::from_utf8(bytes).unwrap(); - abi::lookup(abi_str.index(&FullRange)).expect(abi_str) + abi::lookup(&abi_str[]).expect(abi_str) }) } @@ -733,8 +733,8 @@ pub fn parse_def_id(buf: &[u8]) -> ast::DefId { panic!(); } - let crate_part = buf.index(&(0u..colon_idx)); - let def_part = buf.index(&((colon_idx + 1u)..len)); + let crate_part = &buf[0u..colon_idx]; + let def_part = &buf[(colon_idx + 1u)..len]; let crate_num = match str::from_utf8(crate_part).ok().and_then(|s| s.parse::<uint>()) { Some(cn) => cn as ast::CrateNum, diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index c019d129218..bdd08ad6c49 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -61,7 +61,7 @@ pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'t ty::ty_char => mywrite!(w, "c"), ty::ty_int(t) => { match t { - ast::TyIs => mywrite!(w, "is"), + ast::TyIs(_) => mywrite!(w, "is"), ast::TyI8 => mywrite!(w, "MB"), ast::TyI16 => mywrite!(w, "MW"), ast::TyI32 => mywrite!(w, "ML"), @@ -70,7 +70,7 @@ pub fn enc_ty<'a, 'tcx>(w: &mut SeekableMemWriter, cx: &ctxt<'a, 'tcx>, t: Ty<'t } ty::ty_uint(t) => { match t { - ast::TyUs => mywrite!(w, "us"), + ast::TyUs(_) => mywrite!(w, "us"), ast::TyU8 => mywrite!(w, "Mb"), ast::TyU16 => mywrite!(w, "Mw"), ast::TyU32 => mywrite!(w, "Ml"), diff --git a/src/librustc/middle/astconv_util.rs b/src/librustc/middle/astconv_util.rs index 955f522b804..8cd3795580e 100644 --- a/src/librustc/middle/astconv_util.rs +++ b/src/librustc/middle/astconv_util.rs @@ -47,8 +47,8 @@ pub fn ast_ty_to_prim_ty<'tcx>(tcx: &ty::ctxt<'tcx>, ast_ty: &ast::Ty) let a_def = match tcx.def_map.borrow().get(&id) { None => { tcx.sess.span_bug(ast_ty.span, - format!("unbound path {}", - path.repr(tcx)).index(&FullRange)) + &format!("unbound path {}", + path.repr(tcx))[]) } Some(&d) => d }; diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 32ce131c57a..550c0f34caf 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -132,7 +132,7 @@ pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata, // Do an Option dance to use the path after it is moved below. let s = ast_map::path_to_string(ast_map::Values(path.iter())); path_as_str = Some(s); - path_as_str.as_ref().map(|x| x.index(&FullRange)) + path_as_str.as_ref().map(|x| &x[]) }); let mut ast_dsr = reader::Decoder::new(ast_doc); let from_id_range = Decodable::decode(&mut ast_dsr).unwrap(); @@ -1876,8 +1876,8 @@ fn decode_side_tables(dcx: &DecodeContext, match c::astencode_tag::from_uint(tag) { None => { dcx.tcx.sess.bug( - format!("unknown tag found in side tables: {:x}", - tag).index(&FullRange)); + &format!("unknown tag found in side tables: {:x}", + tag)[]); } Some(value) => { let val_doc = entry_doc.get(c::tag_table_val as uint); @@ -1961,8 +1961,8 @@ fn decode_side_tables(dcx: &DecodeContext, } _ => { dcx.tcx.sess.bug( - format!("unknown tag found in side tables: {:x}", - tag).index(&FullRange)); + &format!("unknown tag found in side tables: {:x}", + tag)[]); } } } diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index f7fc90bcef6..b601ea59486 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -362,7 +362,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { let mut cond_exit = discr_exit; for arm in arms.iter() { cond_exit = self.add_dummy_node(&[cond_exit]); // 2 - let pats_exit = self.pats_any(arm.pats.index(&FullRange), + let pats_exit = self.pats_any(&arm.pats[], cond_exit); // 3 let guard_exit = self.opt_expr(&arm.guard, pats_exit); // 4 @@ -615,15 +615,15 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } self.tcx.sess.span_bug( expr.span, - format!("no loop scope for id {}", - loop_id).index(&FullRange)); + &format!("no loop scope for id {}", + loop_id)[]); } r => { self.tcx.sess.span_bug( expr.span, - format!("bad entry `{:?}` in def_map for label", - r).index(&FullRange)); + &format!("bad entry `{:?}` in def_map for label", + r)[]); } } } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 8b9a0d89b38..f4db2b6e61d 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -52,7 +52,7 @@ fn replace_newline_with_backslash_l(s: String) -> String { } impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { - fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(self.name.index(&FullRange)).unwrap() } + fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[]).unwrap() } fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { dot::Id::new(format!("N{}", i.node_id())).unwrap() @@ -85,9 +85,9 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); - label.push_str(format!("exiting scope_{} {}", + label.push_str(&format!("exiting scope_{} {}", i, - s.index(&FullRange)).index(&FullRange)); + &s[])[]); } dot::LabelText::EscStr(label.into_cow()) } diff --git a/src/librustc/middle/check_loop.rs b/src/librustc/middle/check_loop.rs index 5024e5c4f77..1f779acac25 100644 --- a/src/librustc/middle/check_loop.rs +++ b/src/librustc/middle/check_loop.rs @@ -74,11 +74,11 @@ impl<'a> CheckLoopVisitor<'a> { Loop => {} Closure => { self.sess.span_err(span, - format!("`{}` inside of a closure", name).index(&FullRange)); + &format!("`{}` inside of a closure", name)[]); } Normal => { self.sess.span_err(span, - format!("`{}` outside of loop", name).index(&FullRange)); + &format!("`{}` outside of loop", name)[]); } } } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index f1edfb37273..43f39a67f5c 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -47,7 +47,7 @@ struct Matrix<'a>(Vec<Vec<&'a Pat>>); /// Pretty-printer for matrices of patterns, example: /// ++++++++++++++++++++++++++ -/// + _ + .index(&FullRange) + +/// + _ + [] + /// ++++++++++++++++++++++++++ /// + true + [First] + /// ++++++++++++++++++++++++++ @@ -161,7 +161,7 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) { // First, check legality of move bindings. check_legality_of_move_bindings(cx, arm.guard.is_some(), - arm.pats.index(&FullRange)); + &arm.pats[]); // Second, if there is a guard on each arm, make sure it isn't // assigning or borrowing anything mutably. @@ -198,7 +198,7 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) { } // Fourth, check for unreachable arms. - check_arms(cx, inlined_arms.index(&FullRange), source); + check_arms(cx, &inlined_arms[], source); // Finally, check if the whole match expression is exhaustive. // Check for empty enum, because is_useful only works on inhabited types. @@ -228,9 +228,9 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) { is_refutable(cx, &*static_inliner.fold_pat((*pat).clone()), |uncovered_pat| { cx.tcx.sess.span_err( pat.span, - format!("refutable pattern in `for` loop binding: \ + &format!("refutable pattern in `for` loop binding: \ `{}` not covered", - pat_to_string(uncovered_pat)).index(&FullRange)); + pat_to_string(uncovered_pat))[]); }); // Check legality of move bindings. @@ -303,7 +303,7 @@ fn check_arms(cx: &MatchCheckCtxt, for pat in pats.iter() { let v = vec![&**pat]; - match is_useful(cx, &seen, v.index(&FullRange), LeaveOutWitness) { + match is_useful(cx, &seen, &v[], LeaveOutWitness) { NotUseful => { match source { ast::MatchSource::IfLetDesugar { .. } => { @@ -355,7 +355,7 @@ fn raw_pat<'a>(p: &'a Pat) -> &'a Pat { fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix) { match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) { UsefulWithWitness(pats) => { - let witness = match pats.index(&FullRange) { + let witness = match &pats[] { [ref witness] => &**witness, [] => DUMMY_WILD_PAT, _ => unreachable!() @@ -609,7 +609,7 @@ fn is_useful(cx: &MatchCheckCtxt, UsefulWithWitness(pats) => UsefulWithWitness({ let arity = constructor_arity(cx, &c, left_ty); let mut result = { - let pat_slice = pats.index(&FullRange); + let pat_slice = &pats[]; let subpats: Vec<_> = range(0, arity).map(|i| { pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p) }).collect(); @@ -656,10 +656,10 @@ fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix, witness: WitnessPreference) -> Usefulness { let arity = constructor_arity(cx, &ctor, lty); let matrix = Matrix(m.iter().filter_map(|r| { - specialize(cx, r.index(&FullRange), &ctor, 0u, arity) + specialize(cx, &r[], &ctor, 0u, arity) }).collect()); match specialize(cx, v, &ctor, 0u, arity) { - Some(v) => is_useful(cx, &matrix, v.index(&FullRange), witness), + Some(v) => is_useful(cx, &matrix, &v[], witness), None => NotUseful } } @@ -729,7 +729,7 @@ fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat, /// This computes the arity of a constructor. The arity of a constructor /// is how many subpattern patterns of that constructor should be expanded to. /// -/// For instance, a tuple pattern (_, 42u, Some(.index(&FullRange))) has the arity of 3. +/// For instance, a tuple pattern (_, 42u, Some([])) has the arity of 3. /// A struct pattern's arity is the number of fields it contains, etc. pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> uint { match ty.sty { @@ -926,8 +926,8 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], } }; head.map(|mut head| { - head.push_all(r.index(&(0..col))); - head.push_all(r.index(&((col + 1)..))); + head.push_all(&r[0..col]); + head.push_all(&r[(col + 1)..]); head }) } @@ -1041,10 +1041,10 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt, _ => { cx.tcx.sess.span_bug( p.span, - format!("binding pattern {} is not an \ + &format!("binding pattern {} is not an \ identifier: {:?}", p.id, - p.node).index(&FullRange)); + p.node)[]); } } } diff --git a/src/librustc/middle/check_static.rs b/src/librustc/middle/check_static.rs index 994a2b0dc8a..154272d2deb 100644 --- a/src/librustc/middle/check_static.rs +++ b/src/librustc/middle/check_static.rs @@ -111,8 +111,8 @@ impl<'a, 'tcx> CheckStaticVisitor<'a, 'tcx> { return }; - self.tcx.sess.span_err(e.span, format!("mutable statics are not allowed \ - to have {}", suffix).index(&FullRange)); + self.tcx.sess.span_err(e.span, &format!("mutable statics are not allowed \ + to have {}", suffix)[]); } fn check_static_type(&self, e: &ast::Expr) { @@ -169,8 +169,8 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckStaticVisitor<'a, 'tcx> { ty::ty_struct(did, _) | ty::ty_enum(did, _) if ty::has_dtor(self.tcx, did) => { self.tcx.sess.span_err(e.span, - format!("{} are not allowed to have \ - destructors", self.msg()).index(&FullRange)) + &format!("{} are not allowed to have \ + destructors", self.msg())[]) } _ => {} } @@ -234,7 +234,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for CheckStaticVisitor<'a, 'tcx> { let msg = "constants cannot refer to other statics, \ insert an intermediate constant \ instead"; - self.tcx.sess.span_err(e.span, msg.index(&FullRange)); + self.tcx.sess.span_err(e.span, &msg[]); } _ => {} } diff --git a/src/librustc/middle/check_static_recursion.rs b/src/librustc/middle/check_static_recursion.rs index 75851f0a853..e2a0738def1 100644 --- a/src/librustc/middle/check_static_recursion.rs +++ b/src/librustc/middle/check_static_recursion.rs @@ -104,8 +104,8 @@ impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> { ast_map::NodeForeignItem(_) => {}, _ => { self.sess.span_err(e.span, - format!("expected item, found {}", - self.ast_map.node_to_string(def_id.node)).index(&FullRange)); + &format!("expected item, found {}", + self.ast_map.node_to_string(def_id.node))[]); return; }, } diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index e726993bd48..52352e920ce 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -48,7 +48,7 @@ use std::rc::Rc; // target uses". This _includes_ integer-constants, plus the following // constructors: // -// fixed-size vectors and strings: .index(&FullRange) and ""/_ +// fixed-size vectors and strings: [] and ""/_ // vector and string slices: &[] and &"" // tuples: (,) // enums: foo(...) @@ -117,7 +117,7 @@ fn lookup_variant_by_id<'a>(tcx: &'a ty::ctxt, None => None, Some(ast_map::NodeItem(it)) => match it.node { ast::ItemEnum(ast::EnumDef { ref variants }, _) => { - variant_expr(variants.index(&FullRange), variant_def.node) + variant_expr(&variants[], variant_def.node) } _ => None }, @@ -138,7 +138,7 @@ fn lookup_variant_by_id<'a>(tcx: &'a ty::ctxt, // NOTE this doesn't do the right thing, it compares inlined // NodeId's to the original variant_def's NodeId, but they // come from different crates, so they will likely never match. - variant_expr(variants.index(&FullRange), variant_def.node).map(|e| e.id) + variant_expr(&variants[], variant_def.node).map(|e| e.id) } _ => None }, @@ -364,7 +364,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr) -> P<ast::Pat> { pub fn eval_const_expr(tcx: &ty::ctxt, e: &Expr) -> const_val { match eval_const_expr_partial(tcx, e) { Ok(r) => r, - Err(s) => tcx.sess.span_fatal(e.span, s.index(&FullRange)) + Err(s) => tcx.sess.span_fatal(e.span, &s[]) } } @@ -528,12 +528,12 @@ pub fn eval_const_expr_partial(tcx: &ty::ctxt, e: &Expr) -> Result<const_val, St eval_const_expr_partial(tcx, &**base) .and_then(|val| define_casts!(val, { - ty::ty_int(ast::TyIs) => (int, const_int, i64), + ty::ty_int(ast::TyIs(_)) => (int, const_int, i64), ty::ty_int(ast::TyI8) => (i8, const_int, i64), ty::ty_int(ast::TyI16) => (i16, const_int, i64), ty::ty_int(ast::TyI32) => (i32, const_int, i64), ty::ty_int(ast::TyI64) => (i64, const_int, i64), - ty::ty_uint(ast::TyUs) => (uint, const_uint, u64), + ty::ty_uint(ast::TyUs(_)) => (uint, const_uint, u64), ty::ty_uint(ast::TyU8) => (u8, const_uint, u64), ty::ty_uint(ast::TyU16) => (u16, const_uint, u64), ty::ty_uint(ast::TyU32) => (u32, const_uint, u64), diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index bdd98a94fc3..4ae0aa43406 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -312,7 +312,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let mut t = on_entry.to_vec(); self.apply_gen_kill(cfgidx, t.as_mut_slice()); temp_bits = t; - temp_bits.index(&FullRange) + &temp_bits[] } }; debug!("{} each_bit_for_node({:?}, cfgidx={:?}) bits={}", @@ -421,7 +421,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let bits = self.kills.slice_mut(start, end); debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [before]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); - bits.clone_from_slice(orig_kills.index(&FullRange)); + bits.clone_from_slice(&orig_kills[]); debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [after]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); } @@ -554,7 +554,7 @@ fn bits_to_string(words: &[uint]) -> String { let mut v = word; for _ in range(0u, uint::BYTES) { result.push(sep); - result.push_str(format!("{:02x}", v & 0xFF).index(&FullRange)); + result.push_str(&format!("{:02x}", v & 0xFF)[]); v >>= 8; sep = '-'; } diff --git a/src/librustc/middle/dependency_format.rs b/src/librustc/middle/dependency_format.rs index 0bc899a8a62..cca0b7d9ad0 100644 --- a/src/librustc/middle/dependency_format.rs +++ b/src/librustc/middle/dependency_format.rs @@ -117,8 +117,8 @@ fn calculate_type(sess: &session::Session, sess.cstore.iter_crate_data(|cnum, data| { let src = sess.cstore.get_used_crate_source(cnum).unwrap(); if src.rlib.is_some() { return } - sess.err(format!("dependency `{}` not found in rlib format", - data.name).index(&FullRange)); + sess.err(&format!("dependency `{}` not found in rlib format", + data.name)[]); }); return Vec::new(); } @@ -191,13 +191,13 @@ fn calculate_type(sess: &session::Session, Some(cstore::RequireDynamic) if src.dylib.is_some() => continue, Some(kind) => { let data = sess.cstore.get_crate_data(cnum + 1); - sess.err(format!("crate `{}` required to be available in {}, \ + sess.err(&format!("crate `{}` required to be available in {}, \ but it was not available in this form", data.name, match kind { cstore::RequireStatic => "rlib", cstore::RequireDynamic => "dylib", - }).index(&FullRange)); + })[]); } } } @@ -220,9 +220,9 @@ fn add_library(sess: &session::Session, // can be refined over time. if link2 != link || link == cstore::RequireStatic { let data = sess.cstore.get_crate_data(cnum); - sess.err(format!("cannot satisfy dependencies so `{}` only \ + sess.err(&format!("cannot satisfy dependencies so `{}` only \ shows up once", - data.name).index(&FullRange)); + data.name)[]); sess.help("having upstream crates all available in one format \ will likely make this go away"); } diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 45838436e60..e5eb439d42c 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -857,8 +857,8 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { let (m, r) = match self_ty.sty { ty::ty_rptr(r, ref m) => (m.mutbl, r), _ => self.tcx().sess.span_bug(expr.span, - format!("bad overloaded deref type {}", - method_ty.repr(self.tcx())).index(&FullRange)) + &format!("bad overloaded deref type {}", + method_ty.repr(self.tcx()))[]) }; let bk = ty::BorrowKind::from_mutbl(m); self.delegate.borrow(expr.id, expr.span, cmt, @@ -1180,7 +1180,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { let msg = format!("Pattern has unexpected def: {:?} and type {}", def, cmt_pat.ty.repr(tcx)); - tcx.sess.span_bug(pat.span, msg.index(&FullRange)) + tcx.sess.span_bug(pat.span, &msg[]) } } } diff --git a/src/librustc/middle/infer/combine.rs b/src/librustc/middle/infer/combine.rs index 22975f54a9f..4a4328fa98b 100644 --- a/src/librustc/middle/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -142,7 +142,7 @@ pub trait Combine<'tcx> : Sized { for _ in a_regions.iter() { invariance.push(ty::Invariant); } - invariance.index(&FullRange) + &invariance[] } }; @@ -427,6 +427,16 @@ impl<'tcx> Combineable<'tcx> for ty::TraitRef<'tcx> { } } +impl<'tcx> Combineable<'tcx> for Ty<'tcx> { + fn combine<C:Combine<'tcx>>(combiner: &C, + a: &Ty<'tcx>, + b: &Ty<'tcx>) + -> cres<'tcx, Ty<'tcx>> + { + combiner.tys(*a, *b) + } +} + impl<'tcx> Combineable<'tcx> for ty::ProjectionPredicate<'tcx> { fn combine<C:Combine<'tcx>>(combiner: &C, a: &ty::ProjectionPredicate<'tcx>, @@ -477,10 +487,10 @@ pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C, (&ty::ty_infer(TyVar(_)), _) | (_, &ty::ty_infer(TyVar(_))) => { tcx.sess.bug( - format!("{}: bot and var types should have been handled ({},{})", + &format!("{}: bot and var types should have been handled ({},{})", this.tag(), a.repr(this.infcx().tcx), - b.repr(this.infcx().tcx)).index(&FullRange)); + b.repr(this.infcx().tcx))[]); } (&ty::ty_err, _) | (_, &ty::ty_err) => { @@ -855,8 +865,8 @@ impl<'cx, 'tcx> ty_fold::TypeFolder<'tcx> for Generalizer<'cx, 'tcx> { ty::ReEarlyBound(..) => { self.tcx().sess.span_bug( self.span, - format!("Encountered early bound region when generalizing: {}", - r.repr(self.tcx())).index(&FullRange)); + &format!("Encountered early bound region when generalizing: {}", + r.repr(self.tcx()))[]); } // Always make a fresh region variable for skolemized regions; diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index 762617fb49b..bbd12c9671d 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -200,9 +200,9 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { ref trace_origins, ref same_regions) => { if !same_regions.is_empty() { - self.report_processed_errors(var_origins.index(&FullRange), - trace_origins.index(&FullRange), - same_regions.index(&FullRange)); + self.report_processed_errors(&var_origins[], + &trace_origins[], + &same_regions[]); } } } @@ -373,10 +373,10 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { self.tcx.sess.span_err( trace.origin.span(), - format!("{}: {} ({})", + &format!("{}: {} ({})", message_root_str, expected_found_str, - ty::type_err_to_str(self.tcx, terr)).index(&FullRange)); + ty::type_err_to_str(self.tcx, terr))[]); match trace.origin { infer::MatchExpressionArm(_, arm_span) => @@ -445,42 +445,42 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { // Does the required lifetime have a nice name we can print? self.tcx.sess.span_err( origin.span(), - format!("{} may not live long enough", labeled_user_string).index(&FullRange)); + &format!("{} may not live long enough", labeled_user_string)[]); self.tcx.sess.span_help( origin.span(), - format!( + &format!( "consider adding an explicit lifetime bound `{}: {}`...", bound_kind.user_string(self.tcx), - sub.user_string(self.tcx)).index(&FullRange)); + sub.user_string(self.tcx))[]); } ty::ReStatic => { // Does the required lifetime have a nice name we can print? self.tcx.sess.span_err( origin.span(), - format!("{} may not live long enough", labeled_user_string).index(&FullRange)); + &format!("{} may not live long enough", labeled_user_string)[]); self.tcx.sess.span_help( origin.span(), - format!( + &format!( "consider adding an explicit lifetime bound `{}: 'static`...", - bound_kind.user_string(self.tcx)).index(&FullRange)); + bound_kind.user_string(self.tcx))[]); } _ => { // If not, be less specific. self.tcx.sess.span_err( origin.span(), - format!( + &format!( "{} may not live long enough", - labeled_user_string).index(&FullRange)); + labeled_user_string)[]); self.tcx.sess.span_help( origin.span(), - format!( + &format!( "consider adding an explicit lifetime bound for `{}`", - bound_kind.user_string(self.tcx)).index(&FullRange)); + bound_kind.user_string(self.tcx))[]); note_and_explain_region( self.tcx, - format!("{} must be valid for ", labeled_user_string).index(&FullRange), + &format!("{} must be valid for ", labeled_user_string)[], sub, "..."); } @@ -517,12 +517,12 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::ReborrowUpvar(span, ref upvar_id) => { self.tcx.sess.span_err( span, - format!("lifetime of borrowed pointer outlives \ + &format!("lifetime of borrowed pointer outlives \ lifetime of captured variable `{}`...", ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_string()).index(&FullRange)); + .to_string())[]); note_and_explain_region( self.tcx, "...the borrowed pointer is valid for ", @@ -530,11 +530,11 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { "..."); note_and_explain_region( self.tcx, - format!("...but `{}` is only valid for ", + &format!("...but `{}` is only valid for ", ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_string()).index(&FullRange), + .to_string())[], sup, ""); } @@ -576,11 +576,11 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::FreeVariable(span, id) => { self.tcx.sess.span_err( span, - format!("captured variable `{}` does not \ + &format!("captured variable `{}` does not \ outlive the enclosing closure", ty::local_var_name_str(self.tcx, id).get() - .to_string()).index(&FullRange)); + .to_string())[]); note_and_explain_region( self.tcx, "captured variable is valid for ", @@ -620,9 +620,9 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::RelateParamBound(span, ty) => { self.tcx.sess.span_err( span, - format!("the type `{}` does not fulfill the \ + &format!("the type `{}` does not fulfill the \ required lifetime", - self.ty_to_string(ty)).index(&FullRange)); + self.ty_to_string(ty))[]); note_and_explain_region(self.tcx, "type must outlive ", sub, @@ -646,9 +646,9 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::RelateDefaultParamBound(span, ty) => { self.tcx.sess.span_err( span, - format!("the type `{}` (provided as the value of \ + &format!("the type `{}` (provided as the value of \ a type parameter) is not valid at this point", - self.ty_to_string(ty)).index(&FullRange)); + self.ty_to_string(ty))[]); note_and_explain_region(self.tcx, "type must outlive ", sub, @@ -712,9 +712,9 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::ExprTypeIsNotInScope(t, span) => { self.tcx.sess.span_err( span, - format!("type of expression contains references \ + &format!("type of expression contains references \ that are not valid during the expression: `{}`", - self.ty_to_string(t)).index(&FullRange)); + self.ty_to_string(t))[]); note_and_explain_region( self.tcx, "type is only valid for ", @@ -734,9 +734,9 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { infer::ReferenceOutlivesReferent(ty, span) => { self.tcx.sess.span_err( span, - format!("in type `{}`, reference has a longer lifetime \ + &format!("in type `{}`, reference has a longer lifetime \ than the data it references", - self.ty_to_string(ty)).index(&FullRange)); + self.ty_to_string(ty))[]); note_and_explain_region( self.tcx, "the pointer is valid for ", @@ -861,7 +861,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { let (fn_decl, generics, unsafety, ident, expl_self, span) = node_inner.expect("expect item fn"); let taken = lifetimes_in_scope(self.tcx, scope_id); - let life_giver = LifeGiver::with_taken(taken.index(&FullRange)); + let life_giver = LifeGiver::with_taken(&taken[]); let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self, generics, same_regions, &life_giver); let (fn_decl, expl_self, generics) = rebuilder.rebuild(); @@ -937,7 +937,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { } expl_self_opt = self.rebuild_expl_self(expl_self_opt, lifetime, &anon_nums, ®ion_names); - inputs = self.rebuild_args_ty(inputs.index(&FullRange), lifetime, + inputs = self.rebuild_args_ty(&inputs[], lifetime, &anon_nums, ®ion_names); output = self.rebuild_output(&output, lifetime, &anon_nums, ®ion_names); ty_params = self.rebuild_ty_params(ty_params, lifetime, @@ -972,7 +972,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { names.push(lt_name); } names.sort(); - let name = token::str_to_ident(names[0].index(&FullRange)).name; + let name = token::str_to_ident(&names[0][]).name; return (name_to_dummy_lifetime(name), Kept); } return (self.life_giver.give_lifetime(), Fresh); @@ -1220,9 +1220,9 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { None => { self.tcx .sess - .fatal(format!( + .fatal(&format!( "unbound path {}", - pprust::path_to_string(path)).index(&FullRange)) + pprust::path_to_string(path))[]) } Some(&d) => d }; @@ -1420,7 +1420,7 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { opt_explicit_self, generics); let msg = format!("consider using an explicit lifetime \ parameter as shown: {}", suggested_fn); - self.tcx.sess.span_help(span, msg.index(&FullRange)); + self.tcx.sess.span_help(span, &msg[]); } fn report_inference_failure(&self, @@ -1461,9 +1461,9 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { self.tcx.sess.span_err( var_origin.span(), - format!("cannot infer an appropriate lifetime{} \ + &format!("cannot infer an appropriate lifetime{} \ due to conflicting requirements", - var_description).index(&FullRange)); + var_description)[]); } fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) { @@ -1510,8 +1510,8 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { Some(values_str) => { self.tcx.sess.span_note( trace.origin.span(), - format!("...so that {} ({})", - desc, values_str).index(&FullRange)); + &format!("...so that {} ({})", + desc, values_str)[]); } None => { // Really should avoid printing this error at @@ -1520,7 +1520,7 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { // doing right now. - nmatsakis self.tcx.sess.span_note( trace.origin.span(), - format!("...so that {}", desc).index(&FullRange)); + &format!("...so that {}", desc)[]); } } } @@ -1533,11 +1533,11 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { infer::ReborrowUpvar(span, ref upvar_id) => { self.tcx.sess.span_note( span, - format!( + &format!( "...so that closure can access `{}`", ty::local_var_name_str(self.tcx, upvar_id.var_id) .get() - .to_string()).index(&FullRange)) + .to_string())[]) } infer::InfStackClosure(span) => { self.tcx.sess.span_note( @@ -1558,11 +1558,11 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { infer::FreeVariable(span, id) => { self.tcx.sess.span_note( span, - format!("...so that captured variable `{}` \ + &format!("...so that captured variable `{}` \ does not outlive the enclosing closure", ty::local_var_name_str( self.tcx, - id).get().to_string()).index(&FullRange)); + id).get().to_string())[]); } infer::IndexSlice(span) => { self.tcx.sess.span_note( @@ -1604,9 +1604,9 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { infer::ExprTypeIsNotInScope(t, span) => { self.tcx.sess.span_note( span, - format!("...so type `{}` of expression is valid during the \ + &format!("...so type `{}` of expression is valid during the \ expression", - self.ty_to_string(t)).index(&FullRange)); + self.ty_to_string(t))[]); } infer::BindingTypeIsNotValidAtDecl(span) => { self.tcx.sess.span_note( @@ -1616,30 +1616,30 @@ impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> { infer::ReferenceOutlivesReferent(ty, span) => { self.tcx.sess.span_note( span, - format!("...so that the reference type `{}` \ + &format!("...so that the reference type `{}` \ does not outlive the data it points at", - self.ty_to_string(ty)).index(&FullRange)); + self.ty_to_string(ty))[]); } infer::RelateParamBound(span, t) => { self.tcx.sess.span_note( span, - format!("...so that the type `{}` \ + &format!("...so that the type `{}` \ will meet the declared lifetime bounds", - self.ty_to_string(t)).index(&FullRange)); + self.ty_to_string(t))[]); } infer::RelateDefaultParamBound(span, t) => { self.tcx.sess.span_note( span, - format!("...so that type parameter \ + &format!("...so that type parameter \ instantiated with `{}`, \ will meet its declared lifetime bounds", - self.ty_to_string(t)).index(&FullRange)); + self.ty_to_string(t))[]); } infer::RelateRegionParamBound(span) => { self.tcx.sess.span_note( span, - format!("...so that the declared lifetime parameter bounds \ - are satisfied").index(&FullRange)); + &format!("...so that the declared lifetime parameter bounds \ + are satisfied")[]); } } } @@ -1691,7 +1691,7 @@ fn lifetimes_in_scope(tcx: &ty::ctxt, Some(node) => match node { ast_map::NodeItem(item) => match item.node { ast::ItemFn(_, _, _, ref gen, _) => { - taken.push_all(gen.lifetimes.index(&FullRange)); + taken.push_all(&gen.lifetimes[]); None }, _ => None @@ -1699,7 +1699,7 @@ fn lifetimes_in_scope(tcx: &ty::ctxt, ast_map::NodeImplItem(ii) => { match *ii { ast::MethodImplItem(ref m) => { - taken.push_all(m.pe_generics().lifetimes.index(&FullRange)); + taken.push_all(&m.pe_generics().lifetimes[]); Some(m.id) } ast::TypeImplItem(_) => None, @@ -1758,10 +1758,10 @@ impl LifeGiver { let mut lifetime; loop { let mut s = String::from_str("'"); - s.push_str(num_to_string(self.counter.get()).index(&FullRange)); + s.push_str(&num_to_string(self.counter.get())[]); if !self.taken.contains(&s) { lifetime = name_to_dummy_lifetime( - token::str_to_ident(s.index(&FullRange)).name); + token::str_to_ident(&s[]).name); self.generated.borrow_mut().push(lifetime); break; } diff --git a/src/librustc/middle/infer/freshen.rs b/src/librustc/middle/infer/freshen.rs index 02c52f82967..6bc424fdf95 100644 --- a/src/librustc/middle/infer/freshen.rs +++ b/src/librustc/middle/infer/freshen.rs @@ -135,10 +135,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> { t } - ty::ty_open(..) => { - self.tcx().sess.bug("Cannot freshen an open existential type"); - } - + ty::ty_open(..) | ty::ty_bool | ty::ty_char | ty::ty_int(..) | diff --git a/src/librustc/middle/infer/higher_ranked/mod.rs b/src/librustc/middle/infer/higher_ranked/mod.rs index 073052dd368..0df84323ae5 100644 --- a/src/librustc/middle/infer/higher_ranked/mod.rs +++ b/src/librustc/middle/infer/higher_ranked/mod.rs @@ -187,9 +187,9 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C infcx.tcx.sess.span_bug( span, - format!("region {:?} is not associated with \ + &format!("region {:?} is not associated with \ any bound region from A!", - r0).index(&FullRange)) + r0)[]) } } @@ -322,7 +322,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C } infcx.tcx.sess.span_bug( span, - format!("could not find original bound region for {:?}", r).index(&FullRange)); + &format!("could not find original bound region for {:?}", r)[]); } fn fresh_bound_variable(infcx: &InferCtxt, debruijn: ty::DebruijnIndex) -> ty::Region { @@ -339,7 +339,7 @@ fn var_ids<'tcx, T: Combine<'tcx>>(combiner: &T, r => { combiner.infcx().tcx.sess.span_bug( combiner.trace().origin.span(), - format!("found non-region-vid: {:?}", r).index(&FullRange)); + &format!("found non-region-vid: {:?}", r)[]); } }).collect() } @@ -468,7 +468,7 @@ pub fn skolemize_late_bound_regions<'a,'tcx,T>(infcx: &InferCtxt<'a,'tcx>, * when higher-ranked things are involved. See `doc.rs` for more details. */ - let (result, map) = ty::replace_late_bound_regions(infcx.tcx, binder, |br, _| { + let (result, map) = ty::replace_late_bound_regions(infcx.tcx, binder, |br| { infcx.region_vars.new_skolemized(br, &snapshot.region_vars_snapshot) }); diff --git a/src/librustc/middle/infer/mod.rs b/src/librustc/middle/infer/mod.rs index 3f18af3d768..ab1c41f6968 100644 --- a/src/librustc/middle/infer/mod.rs +++ b/src/librustc/middle/infer/mod.rs @@ -39,7 +39,7 @@ use util::ppaux::{ty_to_string}; use util::ppaux::{Repr, UserString}; use self::coercion::Coerce; -use self::combine::{Combine, CombineFields}; +use self::combine::{Combine, Combineable, CombineFields}; use self::region_inference::{RegionVarBindings, RegionSnapshot}; use self::equate::Equate; use self::sub::Sub; @@ -360,17 +360,9 @@ pub fn can_mk_subty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, }) } -pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, - a: Ty<'tcx>, b: Ty<'tcx>) - -> ures<'tcx> { - debug!("can_mk_subty({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); - cx.probe(|_| { - let trace = TypeTrace { - origin: Misc(codemap::DUMMY_SP), - values: Types(expected_found(true, a, b)) - }; - cx.equate(true, trace).tys(a, b) - }).to_ures() +pub fn can_mk_eqty<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> ures<'tcx> +{ + cx.can_equate(&a, &b) } pub fn mk_subr<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>, @@ -1000,9 +992,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { format!(" ({})", ty::type_err_to_str(self.tcx, t_err)) }); - self.tcx.sess.span_err(sp, format!("{}{}", + self.tcx.sess.span_err(sp, &format!("{}{}", mk_msg(resolved_expected.map(|t| self.ty_to_string(t)), actual_ty), - error_str).index(&FullRange)); + error_str)[]); for err in err.iter() { ty::note_and_explain_type_err(self.tcx, *err) @@ -1056,7 +1048,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { ty::replace_late_bound_regions( self.tcx, value, - |br, _| self.next_region_var(LateBoundRegion(span, br, lbrct))) + |br| self.next_region_var(LateBoundRegion(span, br, lbrct))) } /// See `verify_generic_bound` method in `region_inference` @@ -1072,6 +1064,23 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { self.region_vars.verify_generic_bound(origin, kind, a, bs); } + + pub fn can_equate<T>(&self, a: &T, b: &T) -> ures<'tcx> + where T : Combineable<'tcx> + Repr<'tcx> + { + debug!("can_equate({}, {})", a.repr(self.tcx), b.repr(self.tcx)); + self.probe(|_| { + // Gin up a dummy trace, since this won't be committed + // anyhow. We should make this typetrace stuff more + // generic so we don't have to do anything quite this + // terrible. + let e = self.tcx.types.err; + let trace = TypeTrace { origin: Misc(codemap::DUMMY_SP), + values: Types(expected_found(true, e, e)) }; + let eq = self.equate(true, trace); + Combineable::combine(&eq, a, b) + }).to_ures() + } } impl<'tcx> TypeTrace<'tcx> { diff --git a/src/librustc/middle/infer/region_inference/graphviz.rs b/src/librustc/middle/infer/region_inference/graphviz.rs index 29feaf358e2..0d6ab9c273b 100644 --- a/src/librustc/middle/infer/region_inference/graphviz.rs +++ b/src/librustc/middle/infer/region_inference/graphviz.rs @@ -22,7 +22,6 @@ use middle::ty; use super::Constraint; use middle::infer::SubregionOrigin; use middle::infer::region_inference::RegionVarBindings; -use session::config; use util::nodemap::{FnvHashMap, FnvHashSet}; use util::ppaux::Repr; @@ -55,7 +54,7 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, subject_node: ast::NodeId) { let tcx = region_vars.tcx; - if !region_vars.tcx.sess.debugging_opt(config::PRINT_REGION_GRAPH) { + if !region_vars.tcx.sess.opts.debugging_opts.print_region_graph { return; } diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 5c5c08b53a2..d54d0ae87ae 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -473,9 +473,9 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (_, ReLateBound(..)) => { self.tcx.sess.span_bug( origin.span(), - format!("cannot relate bound region: {} <= {}", + &format!("cannot relate bound region: {} <= {}", sub.repr(self.tcx), - sup.repr(self.tcx)).index(&FullRange)); + sup.repr(self.tcx))[]); } (_, ReStatic) => { // all regions are subregions of static, so we can ignore this @@ -734,9 +734,9 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (ReEarlyBound(..), _) | (_, ReEarlyBound(..)) => { self.tcx.sess.bug( - format!("cannot relate bound region: LUB({}, {})", + &format!("cannot relate bound region: LUB({}, {})", a.repr(self.tcx), - b.repr(self.tcx)).index(&FullRange)); + b.repr(self.tcx))[]); } (ReStatic, _) | (_, ReStatic) => { @@ -750,10 +750,10 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => { self.tcx.sess.span_bug( (*self.var_origins.borrow())[v_id.index as uint].span(), - format!("lub_concrete_regions invoked with \ + &format!("lub_concrete_regions invoked with \ non-concrete regions: {:?}, {:?}", a, - b).index(&FullRange)); + b)[]); } (ReFree(ref fr), ReScope(s_id)) | @@ -834,9 +834,9 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (ReEarlyBound(..), _) | (_, ReEarlyBound(..)) => { self.tcx.sess.bug( - format!("cannot relate bound region: GLB({}, {})", + &format!("cannot relate bound region: GLB({}, {})", a.repr(self.tcx), - b.repr(self.tcx)).index(&FullRange)); + b.repr(self.tcx))[]); } (ReStatic, r) | (r, ReStatic) => { @@ -853,10 +853,10 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (_, ReInfer(ReVar(v_id))) => { self.tcx.sess.span_bug( (*self.var_origins.borrow())[v_id.index as uint].span(), - format!("glb_concrete_regions invoked with \ + &format!("glb_concrete_regions invoked with \ non-concrete regions: {:?}, {:?}", a, - b).index(&FullRange)); + b)[]); } (ReFree(ref fr), ReScope(s_id)) | @@ -977,7 +977,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.expansion(var_data.as_mut_slice()); self.contraction(var_data.as_mut_slice()); let values = - self.extract_values_and_collect_conflicts(var_data.index(&FullRange), + self.extract_values_and_collect_conflicts(&var_data[], errors); self.collect_concrete_region_errors(&values, errors); values @@ -1411,11 +1411,11 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[node_idx.index as uint].span(), - format!("collect_error_for_expanding_node() could not find error \ + &format!("collect_error_for_expanding_node() could not find error \ for var {:?}, lower_bounds={}, upper_bounds={}", node_idx, lower_bounds.repr(self.tcx), - upper_bounds.repr(self.tcx)).index(&FullRange)); + upper_bounds.repr(self.tcx))[]); } fn collect_error_for_contracting_node( @@ -1456,10 +1456,10 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[node_idx.index as uint].span(), - format!("collect_error_for_contracting_node() could not find error \ + &format!("collect_error_for_contracting_node() could not find error \ for var {:?}, upper_bounds={}", node_idx, - upper_bounds.repr(self.tcx)).index(&FullRange)); + upper_bounds.repr(self.tcx))[]); } fn collect_concrete_regions(&self, diff --git a/src/librustc/middle/infer/resolve.rs b/src/librustc/middle/infer/resolve.rs index 9035d72e9a2..7bb3106b0ba 100644 --- a/src/librustc/middle/infer/resolve.rs +++ b/src/librustc/middle/infer/resolve.rs @@ -95,8 +95,8 @@ impl<'a, 'tcx> ty_fold::TypeFolder<'tcx> for FullTypeResolver<'a, 'tcx> { } ty::ty_infer(_) => { self.infcx.tcx.sess.bug( - format!("Unexpected type in full type resolver: {}", - t.repr(self.infcx.tcx)).index(&FullRange)); + &format!("Unexpected type in full type resolver: {}", + t.repr(self.infcx.tcx))[]); } _ => { ty_fold::super_fold_ty(self, t) diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 850033b3ed1..1b1dca00422 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -326,8 +326,8 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> { None => { self.tcx .sess - .span_bug(span, format!("no variable registered for id {}", - node_id).index(&FullRange)); + .span_bug(span, &format!("no variable registered for id {}", + node_id)[]); } } } @@ -597,8 +597,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // creating liveness nodes for. self.ir.tcx.sess.span_bug( span, - format!("no live node registered for node {}", - node_id).index(&FullRange)); + &format!("no live node registered for node {}", + node_id)[]); } } } @@ -1133,7 +1133,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // Uninteresting cases: just propagate in rev exec order ast::ExprVec(ref exprs) => { - self.propagate_through_exprs(exprs.index(&FullRange), succ) + self.propagate_through_exprs(&exprs[], succ) } ast::ExprRepeat(ref element, ref count) => { @@ -1157,7 +1157,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } else { succ }; - let succ = self.propagate_through_exprs(args.index(&FullRange), succ); + let succ = self.propagate_through_exprs(&args[], succ); self.propagate_through_expr(&**f, succ) } @@ -1170,11 +1170,11 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } else { succ }; - self.propagate_through_exprs(args.index(&FullRange), succ) + self.propagate_through_exprs(&args[], succ) } ast::ExprTup(ref exprs) => { - self.propagate_through_exprs(exprs.index(&FullRange), succ) + self.propagate_through_exprs(&exprs[], succ) } ast::ExprBinary(op, ref l, ref r) if ast_util::lazy_binop(op) => { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index b29c24c5861..51ec7528432 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -75,7 +75,7 @@ use middle::def; use middle::region; use middle::ty::{self, Ty}; use util::nodemap::{NodeMap}; -use util::ppaux::{Repr}; +use util::ppaux::{Repr, UserString}; use syntax::ast::{MutImmutable, MutMutable}; use syntax::ast; @@ -113,10 +113,17 @@ pub struct Upvar { // different kinds of pointers: #[derive(Clone, Copy, PartialEq, Eq, Hash, Show)] pub enum PointerKind { + /// `Box<T>` Unique, + + /// `&T` BorrowedPtr(ty::BorrowKind, ty::Region), - Implicit(ty::BorrowKind, ty::Region), // Implicit deref of a borrowed ptr. - UnsafePtr(ast::Mutability) + + /// `*T` + UnsafePtr(ast::Mutability), + + /// Implicit deref of the `&T` that results from an overloaded index `[]`. + Implicit(ty::BorrowKind, ty::Region), } // We use the term "interior" to mean "something reachable from the @@ -453,7 +460,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { autoderefs, cmt.repr(self.tcx())); for deref in range(1u, autoderefs + 1) { - cmt = try!(self.cat_deref(expr, cmt, deref, false)); + cmt = try!(self.cat_deref(expr, cmt, deref)); } return Ok(cmt); } @@ -465,7 +472,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { match expr.node { ast::ExprUnary(ast::UnDeref, ref e_base) => { let base_cmt = try!(self.cat_expr(&**e_base)); - self.cat_deref(expr, base_cmt, 0, false) + self.cat_deref(expr, base_cmt, 0) } ast::ExprField(ref base, f_name) => { @@ -489,10 +496,23 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { // If this is an index implemented by a method call, then it // will include an implicit deref of the result. let ret_ty = self.overloaded_method_return_ty(method_ty); - self.cat_deref(expr, - self.cat_rvalue_node(expr.id(), - expr.span(), - ret_ty), 1, true) + + // The index method always returns an `&T`, so + // dereference it to find the result type. + let elem_ty = match ret_ty.sty { + ty::ty_rptr(_, mt) => mt.ty, + _ => { + debug!("cat_expr_unadjusted: return type of overloaded index is {}?", + ret_ty.repr(self.tcx())); + return Err(()); + } + }; + + // The call to index() returns a `&T` value, which + // is an rvalue. That is what we will be + // dereferencing. + let base_cmt = self.cat_rvalue_node(expr.id(), expr.span(), ret_ty); + self.cat_deref_common(expr, base_cmt, 1, elem_ty, true) } None => { self.cat_index(expr, try!(self.cat_expr(&**base))) @@ -584,9 +604,9 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { _ => { self.tcx().sess.span_bug( span, - format!("Upvar of non-closure {} - {}", + &format!("Upvar of non-closure {} - {}", fn_node_id, - ty.repr(self.tcx())).index(&FullRange)); + ty.repr(self.tcx()))[]); } } } @@ -837,8 +857,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { fn cat_deref<N:ast_node>(&self, node: &N, base_cmt: cmt<'tcx>, - deref_cnt: uint, - implicit: bool) + deref_cnt: uint) -> McResult<cmt<'tcx>> { let adjustment = match self.typer.adjustments().borrow().get(&node.id()) { Some(adj) if ty::adjust_is_object(adj) => ty::AutoObject, @@ -866,7 +885,8 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { }; let base_cmt_ty = base_cmt.ty; match ty::deref(base_cmt_ty, true) { - Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, implicit), + Some(mt) => self.cat_deref_common(node, base_cmt, deref_cnt, mt.ty, + /* implicit: */ false), None => { debug!("Explicit deref of non-derefable type: {}", base_cmt_ty.repr(self.tcx())); @@ -1236,7 +1256,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { // box p1, &p1, &mut p1. we can ignore the mutability of // PatRegion since that information is already contained // in the type. - let subcmt = try!(self.cat_deref(pat, cmt, 0, false)); + let subcmt = try!(self.cat_deref(pat, cmt, 0)); try!(self.cat_pattern_(subcmt, &**subpat, op)); } @@ -1392,22 +1412,6 @@ impl<'tcx> cmt_<'tcx> { pub fn descriptive_string(&self, tcx: &ty::ctxt) -> String { - fn upvar_to_string(upvar: &Upvar, is_copy: bool) -> String { - if upvar.is_unboxed { - let kind = match upvar.kind { - ty::FnUnboxedClosureKind => "Fn", - ty::FnMutUnboxedClosureKind => "FnMut", - ty::FnOnceUnboxedClosureKind => "FnOnce" - }; - format!("captured outer variable in an `{}` closure", kind) - } else { - (match (upvar.kind, is_copy) { - (ty::FnOnceUnboxedClosureKind, true) => "captured outer variable in a proc", - _ => "captured outer variable" - }).to_string() - } - } - match self.cat { cat_static_item => { "static item".to_string() @@ -1427,16 +1431,23 @@ impl<'tcx> cmt_<'tcx> { let upvar = self.upvar(); match upvar.as_ref().map(|i| &i.cat) { Some(&cat_upvar(ref var)) => { - upvar_to_string(var, false) + var.user_string(tcx) } Some(_) => unreachable!(), None => { match pk { Implicit(..) => { - "dereference (dereference is implicit, due to indexing)".to_string() + format!("indexed content") + } + Unique => { + format!("`Box` content") + } + UnsafePtr(..) => { + format!("dereference of unsafe pointer") + } + BorrowedPtr(..) => { + format!("borrowed content") } - Unique => format!("dereference of `{}`", ptr_sigil(pk)), - _ => format!("dereference of `{}`-pointer", ptr_sigil(pk)) } } } @@ -1447,14 +1458,12 @@ impl<'tcx> cmt_<'tcx> { cat_interior(_, InteriorField(PositionalField(_))) => { "anonymous field".to_string() } - cat_interior(_, InteriorElement(VecElement)) => { - "vec content".to_string() - } + cat_interior(_, InteriorElement(VecElement)) | cat_interior(_, InteriorElement(OtherElement)) => { "indexed content".to_string() } cat_upvar(ref var) => { - upvar_to_string(var, true) + var.user_string(tcx) } cat_downcast(ref cmt, _) => { cmt.descriptive_string(tcx) @@ -1483,7 +1492,7 @@ impl<'tcx> Repr<'tcx> for categorization<'tcx> { format!("{:?}", *self) } cat_deref(ref cmt, derefs, ptr) => { - format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs) + format!("{}-{}{}->", cmt.cat.repr(tcx), ptr.repr(tcx), derefs) } cat_interior(ref cmt, interior) => { format!("{}.{}", cmt.cat.repr(tcx), interior.repr(tcx)) @@ -1504,7 +1513,32 @@ pub fn ptr_sigil(ptr: PointerKind) -> &'static str { Implicit(ty::MutBorrow, _) => "&mut", BorrowedPtr(ty::UniqueImmBorrow, _) | Implicit(ty::UniqueImmBorrow, _) => "&unique", - UnsafePtr(_) => "*" + UnsafePtr(_) => "*", + } +} + +impl<'tcx> Repr<'tcx> for PointerKind { + fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { + match *self { + Unique => { + format!("Box") + } + BorrowedPtr(ty::ImmBorrow, ref r) | + Implicit(ty::ImmBorrow, ref r) => { + format!("&{}", r.repr(tcx)) + } + BorrowedPtr(ty::MutBorrow, ref r) | + Implicit(ty::MutBorrow, ref r) => { + format!("&{} mut", r.repr(tcx)) + } + BorrowedPtr(ty::UniqueImmBorrow, ref r) | + Implicit(ty::UniqueImmBorrow, ref r) => { + format!("&{} uniq", r.repr(tcx)) + } + UnsafePtr(_) => { + format!("*") + } + } } } @@ -1531,3 +1565,27 @@ fn element_kind(t: Ty) -> ElementKind { _ => OtherElement } } + +impl<'tcx> Repr<'tcx> for ty::UnboxedClosureKind { + fn repr(&self, _: &ty::ctxt) -> String { + format!("Upvar({:?})", self) + } +} + +impl<'tcx> Repr<'tcx> for Upvar { + fn repr(&self, tcx: &ty::ctxt) -> String { + format!("Upvar({})", self.kind.repr(tcx)) + } +} + +impl<'tcx> UserString<'tcx> for Upvar { + fn user_string(&self, _: &ty::ctxt) -> String { + let kind = match self.kind { + ty::FnUnboxedClosureKind => "Fn", + ty::FnMutUnboxedClosureKind => "FnMut", + ty::FnOnceUnboxedClosureKind => "FnOnce", + }; + format!("captured outer variable in an `{}` closure", kind) + } +} + diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 861c4a2c85e..aa37c2fe348 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -615,10 +615,10 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { match result { None => true, Some((span, msg, note)) => { - self.tcx.sess.span_err(span, msg.index(&FullRange)); + self.tcx.sess.span_err(span, &msg[]); match note { Some((span, msg)) => { - self.tcx.sess.span_note(span, msg.index(&FullRange)) + self.tcx.sess.span_note(span, &msg[]) } None => {}, } @@ -720,7 +720,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { UnnamedField(idx) => format!("field #{} of {} is private", idx + 1, struct_desc), }; - self.tcx.sess.span_err(span, msg.index(&FullRange)); + self.tcx.sess.span_err(span, &msg[]); } // Given the ID of a method, checks to ensure it's in scope. @@ -741,8 +741,8 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { self.report_error(self.ensure_public(span, method_id, None, - format!("method `{}`", - string).index(&FullRange))); + &format!("method `{}`", + string)[])); } // Checks that a path is in scope. @@ -756,7 +756,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { self.ensure_public(span, def, Some(origdid), - format!("{} `{}`", tyname, name).index(&FullRange)) + &format!("{} `{}`", tyname, name)[]) }; match self.last_private_map[path_id] { diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 51602e88f93..906607ddc5b 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -50,7 +50,7 @@ fn generics_require_inlining(generics: &ast::Generics) -> bool { // monomorphized or it was marked with `#[inline]`. This will only return // true for functions. fn item_might_be_inlined(item: &ast::Item) -> bool { - if attributes_specify_inlining(item.attrs.index(&FullRange)) { + if attributes_specify_inlining(&item.attrs[]) { return true } @@ -65,7 +65,7 @@ fn item_might_be_inlined(item: &ast::Item) -> bool { fn method_might_be_inlined(tcx: &ty::ctxt, method: &ast::Method, impl_src: ast::DefId) -> bool { - if attributes_specify_inlining(method.attrs.index(&FullRange)) || + if attributes_specify_inlining(&method.attrs[]) || generics_require_inlining(method.pe_generics()) { return true } @@ -202,7 +202,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { ast::MethodImplItem(ref method) => { if generics_require_inlining(method.pe_generics()) || attributes_specify_inlining( - method.attrs.index(&FullRange)) { + &method.attrs[]) { true } else { let impl_did = self.tcx @@ -247,9 +247,9 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { Some(ref item) => self.propagate_node(item, search_item), None if search_item == ast::CRATE_NODE_ID => {} None => { - self.tcx.sess.bug(format!("found unmapped ID in worklist: \ + self.tcx.sess.bug(&format!("found unmapped ID in worklist: \ {}", - search_item).index(&FullRange)) + search_item)[]) } } } @@ -338,10 +338,10 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { _ => { self.tcx .sess - .bug(format!("found unexpected thingy in worklist: {}", + .bug(&format!("found unexpected thingy in worklist: {}", self.tcx .map - .node_to_string(search_item)).index(&FullRange)) + .node_to_string(search_item))[]) } } } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 5d18843097f..5d33a7efd3b 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -643,7 +643,7 @@ fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { // A, but the inner rvalues `a()` and `b()` have an extended lifetime // due to rule C. // - // FIXME(#6308) -- Note that `.index(&FullRange)` patterns work more smoothly post-DST. + // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST. match local.init { Some(ref expr) => { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 8e03d774b81..b670099ff96 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -398,8 +398,8 @@ impl<'a> LifetimeContext<'a> { fn unresolved_lifetime_ref(&self, lifetime_ref: &ast::Lifetime) { self.sess.span_err( lifetime_ref.span, - format!("use of undeclared lifetime name `{}`", - token::get_name(lifetime_ref.name)).index(&FullRange)); + &format!("use of undeclared lifetime name `{}`", + token::get_name(lifetime_ref.name))[]); } fn check_lifetime_defs(&mut self, old_scope: Scope, lifetimes: &Vec<ast::LifetimeDef>) { @@ -411,9 +411,9 @@ impl<'a> LifetimeContext<'a> { if special_idents.iter().any(|&i| i.name == lifetime.lifetime.name) { self.sess.span_err( lifetime.lifetime.span, - format!("illegal lifetime parameter name: `{}`", + &format!("illegal lifetime parameter name: `{}`", token::get_name(lifetime.lifetime.name)) - .index(&FullRange)); + []); } } @@ -424,10 +424,10 @@ impl<'a> LifetimeContext<'a> { if lifetime_i.lifetime.name == lifetime_j.lifetime.name { self.sess.span_err( lifetime_j.lifetime.span, - format!("lifetime name `{}` declared twice in \ + &format!("lifetime name `{}` declared twice in \ the same scope", token::get_name(lifetime_j.lifetime.name)) - .index(&FullRange)); + []); } } diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 359ad8d3941..e712f510d9d 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -189,3 +189,19 @@ pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option<Stability> { } }) } + +pub fn is_staged_api(tcx: &ty::ctxt, id: DefId) -> bool { + match ty::trait_item_of_item(tcx, id) { + Some(ty::MethodTraitItemId(trait_method_id)) + if trait_method_id != id => { + is_staged_api(tcx, trait_method_id) + } + _ if is_local(id) => { + // Unused case + unreachable!() + } + _ => { + csearch::is_staged_api(&tcx.sess.cstore, id) + } + } +} diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 98bb0645bef..9ac6b8a86b6 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -313,6 +313,17 @@ impl<T> VecPerParamSpace<T> { self.content.insert(limit, value); } + /// Appends `values` to the vector associated with `space`. + /// + /// Unlike the `extend` method in `Vec`, this should not be assumed + /// to be a cheap operation (even when amortized over many calls). + pub fn extend<I:Iterator<Item=T>>(&mut self, space: ParamSpace, mut values: I) { + // This could be made more efficient, obviously. + for item in values { + self.push(space, item); + } + } + pub fn pop(&mut self, space: ParamSpace) -> Option<T> { let (start, limit) = self.limits(space); if start == limit { @@ -394,7 +405,7 @@ impl<T> VecPerParamSpace<T> { self.content.as_slice() } - pub fn to_vec(self) -> Vec<T> { + pub fn into_vec(self) -> Vec<T> { self.content } @@ -599,12 +610,12 @@ impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, - format!("Type parameter out of range \ + &format!("Type parameter out of range \ when substituting in region {} (root type={}) \ (space={:?}, index={})", region_name.as_str(), self.root_ty.repr(self.tcx()), - space, i).index(&FullRange)); + space, i)[]); } } } @@ -654,14 +665,14 @@ impl<'a,'tcx> SubstFolder<'a,'tcx> { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, - format!("Type parameter `{}` ({}/{:?}/{}) out of range \ + &format!("Type parameter `{}` ({}/{:?}/{}) out of range \ when substituting (root type={}) substs={}", p.repr(self.tcx()), source_ty.repr(self.tcx()), p.space, p.idx, self.root_ty.repr(self.tcx()), - self.substs.repr(self.tcx())).index(&FullRange)); + self.substs.repr(self.tcx()))[]); } }; diff --git a/src/librustc/middle/traits/coherence.rs b/src/librustc/middle/traits/coherence.rs index 49c7d6aafaa..b6d45ab89e7 100644 --- a/src/librustc/middle/traits/coherence.rs +++ b/src/librustc/middle/traits/coherence.rs @@ -12,6 +12,7 @@ use super::SelectionContext; use super::{Obligation, ObligationCause}; +use super::project; use super::util; use middle::subst::{Subst}; @@ -34,22 +35,28 @@ pub fn impl_can_satisfy(infcx: &InferCtxt, impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx.tcx)); + let param_env = ty::empty_parameter_environment(infcx.tcx); + let mut selcx = SelectionContext::intercrate(infcx, ¶m_env); + let cause = ObligationCause::dummy(); + // `impl1` provides an implementation of `Foo<X,Y> for Z`. let impl1_substs = util::fresh_substs_for_impl(infcx, DUMMY_SP, impl1_def_id); let impl1_trait_ref = (*ty::impl_trait_ref(infcx.tcx, impl1_def_id).unwrap()).subst(infcx.tcx, &impl1_substs); + let impl1_trait_ref = + project::normalize(&mut selcx, cause.clone(), &impl1_trait_ref); // Determine whether `impl2` can provide an implementation for those // same types. - let param_env = ty::empty_parameter_environment(infcx.tcx); - let mut selcx = SelectionContext::intercrate(infcx, ¶m_env); - let obligation = Obligation::new(ObligationCause::dummy(), + let obligation = Obligation::new(cause, ty::Binder(ty::TraitPredicate { - trait_ref: Rc::new(impl1_trait_ref), + trait_ref: Rc::new(impl1_trait_ref.value), })); debug!("impl_can_satisfy(obligation={})", obligation.repr(infcx.tcx)); - selcx.evaluate_impl(impl2_def_id, &obligation) + selcx.evaluate_impl(impl2_def_id, &obligation) && + impl1_trait_ref.obligations.iter().all( + |o| selcx.evaluate_obligation(o)) } #[allow(missing_copy_implementations)] @@ -136,8 +143,8 @@ fn ty_is_local_constructor<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { ty::ty_open(..) | ty::ty_err => { tcx.sess.bug( - format!("ty_is_local invoked on unexpected type: {}", - ty.repr(tcx)).index(&FullRange)) + &format!("ty_is_local invoked on unexpected type: {}", + ty.repr(tcx))[]) } } } diff --git a/src/librustc/middle/traits/error_reporting.rs b/src/librustc/middle/traits/error_reporting.rs index fd6773afb76..02c913a9e81 100644 --- a/src/librustc/middle/traits/error_reporting.rs +++ b/src/librustc/middle/traits/error_reporting.rs @@ -337,7 +337,7 @@ pub fn suggest_new_overflow_limit(tcx: &ty::ctxt, span: Span) { let suggested_limit = current_limit * 2; tcx.sess.span_note( span, - format!( + &format!( "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate", - suggested_limit).index(&FullRange)); + suggested_limit)[]); } diff --git a/src/librustc/middle/traits/fulfill.rs b/src/librustc/middle/traits/fulfill.rs index 71a3ad64faf..c3b9be85eb5 100644 --- a/src/librustc/middle/traits/fulfill.rs +++ b/src/librustc/middle/traits/fulfill.rs @@ -227,7 +227,7 @@ impl<'tcx> FulfillmentContext<'tcx> { } pub fn pending_obligations(&self) -> &[PredicateObligation<'tcx>] { - self.predicates.index(&FullRange) + &self.predicates[] } /// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index aaf0d4fcb33..c0399112c33 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -178,7 +178,7 @@ fn object_safety_violations_for_method<'tcx>(tcx: &ty::ctxt<'tcx>, // The `Self` type is erased, so it should not appear in list of // arguments or return type apart from the receiver. let ref sig = method.fty.sig; - for &input_ty in sig.0.inputs.index(&(1..)).iter() { + for &input_ty in sig.0.inputs[1..].iter() { if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) { return Some(MethodViolationCode::ReferencesSelf); } diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index 3e16e2965a6..95a938328cf 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -206,6 +206,7 @@ impl<'a,'b,'tcx> TypeFolder<'tcx> for AssociatedTypeNormalizer<'a,'b,'tcx> { // normalize it when we instantiate those bound regions (which // should occur eventually). + let ty = ty_fold::super_fold_ty(self, ty); match ty.sty { ty::ty_projection(ref data) if !data.has_escaping_regions() => { // (*) @@ -229,8 +230,9 @@ impl<'a,'b,'tcx> TypeFolder<'tcx> for AssociatedTypeNormalizer<'a,'b,'tcx> { self.obligations.extend(obligations.into_iter()); ty } + _ => { - ty_fold::super_fold_ty(self, ty) + ty } } } @@ -243,6 +245,12 @@ pub struct Normalized<'tcx,T> { pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>; +impl<'tcx,T> Normalized<'tcx,T> { + pub fn with<U>(self, value: U) -> Normalized<'tcx,U> { + Normalized { value: value, obligations: self.obligations } + } +} + pub fn normalize_projection_type<'a,'b,'tcx>( selcx: &'a mut SelectionContext<'b,'tcx>, projection_ty: ty::ProjectionTy<'tcx>, @@ -452,7 +460,9 @@ fn assemble_candidates_from_predicates<'cx,'tcx>( for predicate in elaborate_predicates(selcx.tcx(), env_predicates) { match predicate { ty::Predicate::Projection(ref data) => { - let is_match = infcx.probe(|_| { + let same_name = data.item_name() == obligation.predicate.item_name; + + let is_match = same_name && infcx.probe(|_| { let origin = infer::Misc(obligation.cause.span); let obligation_poly_trait_ref = obligation_trait_ref.to_poly_trait_ref(); @@ -465,6 +475,9 @@ fn assemble_candidates_from_predicates<'cx,'tcx>( }); if is_match { + debug!("assemble_candidates_from_predicates: candidate {}", + data.repr(selcx.tcx())); + candidate_set.vec.push( ProjectionTyCandidate::ParamEnv(data.clone())); } @@ -527,6 +540,9 @@ fn assemble_candidates_from_impls<'cx,'tcx>( match vtable { super::VtableImpl(data) => { + debug!("assemble_candidates_from_impls: impl candidate {}", + data.repr(selcx.tcx())); + candidate_set.vec.push( ProjectionTyCandidate::Impl(data)); } @@ -641,7 +657,7 @@ fn confirm_candidate<'cx,'tcx>( } match impl_ty { - Some(ty) => (ty, impl_vtable.nested.to_vec()), + Some(ty) => (ty, impl_vtable.nested.into_vec()), None => { // This means that the impl is missing a // definition for the associated type. This error diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 7c8e0d90e11..d6302976b9f 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -19,6 +19,7 @@ use self::EvaluationResult::*; use super::{DerivedObligationCause}; use super::{project}; +use super::project::Normalized; use super::{PredicateObligation, Obligation, TraitObligation, ObligationCause}; use super::{ObligationCauseCode, BuiltinDerivedObligation}; use super::{SelectionError, Unimplemented, Overflow, OutputTypeParameterMismatch}; @@ -713,12 +714,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { debug!("obligation self ty is {}", obligation.predicate.0.self_ty().repr(self.tcx())); - // If the user has asked for the older, compatibility - // behavior, ignore user-defined impls here. This will - // go away by the time 1.0 is released. - if !self.tcx().sess.features.borrow().opt_out_copy { - try!(self.assemble_candidates_from_impls(obligation, &mut candidates.vec)); - } + try!(self.assemble_candidates_from_impls(obligation, &mut candidates.vec)); try!(self.assemble_builtin_bound_candidates(ty::BoundCopy, stack, @@ -835,7 +831,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { bounds.repr(self.tcx())); let matching_bound = - util::elaborate_predicates(self.tcx(), bounds.predicates.to_vec()) + util::elaborate_predicates(self.tcx(), bounds.predicates.into_vec()) .filter_to_traits() .find( |bound| self.infcx.probe( @@ -903,7 +899,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let all_bounds = util::transitive_bounds( - self.tcx(), caller_trait_refs.index(&FullRange)); + self.tcx(), &caller_trait_refs[]); let matching_bounds = all_bounds.filter( @@ -1160,7 +1156,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let impl_trait_ref = ty::impl_trait_ref(self.tcx(), impl_def_id).unwrap(); let impl_trait_ref = - impl_trait_ref.subst(self.tcx(), &impl_substs); + impl_trait_ref.subst(self.tcx(), &impl_substs.value); let poly_impl_trait_ref = ty::Binder(impl_trait_ref); let origin = @@ -1457,17 +1453,32 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Ok(AmbiguousBuiltin) } + ty::ty_open(ty) => { + // these only crop up in trans, and represent an + // "opened" unsized/existential type (one that has + // been dereferenced) + match bound { + ty::BoundCopy | + ty::BoundSync | + ty::BoundSend => { + Ok(If(vec!(ty))) + } + + ty::BoundSized => { + Err(Unimplemented) + } + } + } ty::ty_err => { Ok(If(Vec::new())) } - ty::ty_open(_) | ty::ty_infer(ty::FreshTy(_)) | ty::ty_infer(ty::FreshIntTy(_)) => { self.tcx().sess.bug( - format!( + &format!( "asked to assemble builtin bounds of unexpected type: {}", - self_ty.repr(self.tcx())).index(&FullRange)); + self_ty.repr(self.tcx()))[]); } }; @@ -1490,21 +1501,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } ty::BoundCopy => { - // This is an Opt-In Built-In Trait. So, unless - // the user is asking for the old behavior, we - // don't supply any form of builtin impl. - if !this.tcx().sess.features.borrow().opt_out_copy { - return Ok(ParameterBuiltin) - } else { - // Older, backwards compatibility behavior: - if - Some(def_id) == tcx.lang_items.no_copy_bound() || - Some(def_id) == tcx.lang_items.managed_bound() || - ty::has_dtor(tcx, def_id) - { - return Err(Unimplemented); - } - } + return Ok(ParameterBuiltin) } ty::BoundSync => { @@ -1636,8 +1633,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { AmbiguousBuiltin | ParameterBuiltin => { self.tcx().sess.span_bug( obligation.cause.span, - format!("builtin bound for {} was ambig", - obligation.repr(self.tcx())).index(&FullRange)); + &format!("builtin bound for {} was ambig", + obligation.repr(self.tcx()))[]); } } } @@ -1716,7 +1713,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let substs = self.rematch_impl(impl_def_id, obligation, snapshot, &skol_map, skol_obligation_trait_ref.trait_ref); - debug!("confirm_impl_candidate substs={:?}", substs); + debug!("confirm_impl_candidate substs={}", substs.repr(self.tcx())); Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(), obligation.recursion_depth + 1, skol_map, snapshot)) }) @@ -1724,7 +1721,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn vtable_impl(&mut self, impl_def_id: ast::DefId, - substs: Substs<'tcx>, + substs: Normalized<'tcx, Substs<'tcx>>, cause: ObligationCause<'tcx>, recursion_depth: uint, skol_map: infer::SkolemizationMap, @@ -1737,21 +1734,23 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { recursion_depth, skol_map.repr(self.tcx())); - let impl_predicates = - self.impl_predicates(cause, + let mut impl_obligations = + self.impl_obligations(cause, recursion_depth, impl_def_id, - &substs, + &substs.value, skol_map, snapshot); - debug!("vtable_impl: impl_def_id={} impl_predicates={}", + debug!("vtable_impl: impl_def_id={} impl_obligations={}", impl_def_id.repr(self.tcx()), - impl_predicates.repr(self.tcx())); + impl_obligations.repr(self.tcx())); + + impl_obligations.extend(TypeSpace, substs.obligations.into_iter()); VtableImplData { impl_def_id: impl_def_id, - substs: substs, - nested: impl_predicates } + substs: substs.value, + nested: impl_obligations } } fn confirm_object_candidate(&mut self, @@ -1815,8 +1814,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { _ => { self.tcx().sess.span_bug( obligation.cause.span, - format!("Fn pointer candidate for inappropriate self type: {}", - self_ty.repr(self.tcx())).index(&FullRange)); + &format!("Fn pointer candidate for inappropriate self type: {}", + self_ty.repr(self.tcx()))[]); } }; @@ -1935,7 +1934,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { snapshot: &infer::CombinedSnapshot, skol_map: &infer::SkolemizationMap, skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>) - -> Substs<'tcx> + -> Normalized<'tcx, Substs<'tcx>> { match self.match_impl(impl_def_id, obligation, snapshot, skol_map, skol_obligation_trait_ref) { @@ -1944,9 +1943,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } Err(()) => { self.tcx().sess.bug( - format!("Impl {} was matchable against {} but now is not", + &format!("Impl {} was matchable against {} but now is not", impl_def_id.repr(self.tcx()), - obligation.repr(self.tcx())).index(&FullRange)); + obligation.repr(self.tcx()))[]); } } } @@ -1957,7 +1956,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { snapshot: &infer::CombinedSnapshot, skol_map: &infer::SkolemizationMap, skol_obligation_trait_ref: Rc<ty::TraitRef<'tcx>>) - -> Result<Substs<'tcx>, ()> + -> Result<Normalized<'tcx, Substs<'tcx>>, ()> { let impl_trait_ref = ty::impl_trait_ref(self.tcx(), impl_def_id).unwrap(); @@ -1975,6 +1974,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let impl_trait_ref = impl_trait_ref.subst(self.tcx(), &impl_substs); + let impl_trait_ref = + project::normalize_with_depth(self, + obligation.cause.clone(), + obligation.recursion_depth + 1, + &impl_trait_ref); + debug!("match_impl(impl_def_id={}, obligation={}, \ impl_trait_ref={}, skol_obligation_trait_ref={})", impl_def_id.repr(self.tcx()), @@ -1985,7 +1990,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let origin = infer::RelateOutputImplTypes(obligation.cause.span); match self.infcx.sub_trait_refs(false, origin, - impl_trait_ref, + impl_trait_ref.value.clone(), skol_obligation_trait_ref) { Ok(()) => { } Err(e) => { @@ -2005,7 +2010,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } debug!("match_impl: success impl_substs={}", impl_substs.repr(self.tcx())); - Ok(impl_substs) + Ok(Normalized { value: impl_substs, + obligations: impl_trait_ref.obligations }) } fn fast_reject_trait_refs(&mut self, @@ -2146,14 +2152,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - fn impl_predicates(&mut self, - cause: ObligationCause<'tcx>, - recursion_depth: uint, - impl_def_id: ast::DefId, - impl_substs: &Substs<'tcx>, - skol_map: infer::SkolemizationMap, - snapshot: &infer::CombinedSnapshot) - -> VecPerParamSpace<PredicateObligation<'tcx>> + fn impl_obligations(&mut self, + cause: ObligationCause<'tcx>, + recursion_depth: uint, + impl_def_id: ast::DefId, + impl_substs: &Substs<'tcx>, + skol_map: infer::SkolemizationMap, + snapshot: &infer::CombinedSnapshot) + -> VecPerParamSpace<PredicateObligation<'tcx>> { let impl_generics = ty::lookup_item_type(self.tcx(), impl_def_id).generics; let bounds = impl_generics.to_bounds(self.tcx(), impl_substs); @@ -2166,9 +2172,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { cause, recursion_depth, &normalized_bounds.value); - for obligation in normalized_bounds.obligations.into_iter() { - impl_obligations.push(TypeSpace, obligation); - } + impl_obligations.extend(TypeSpace, normalized_bounds.obligations.into_iter()); impl_obligations } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 9b9a58178cc..ef86e67de16 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -72,7 +72,7 @@ use std::borrow::BorrowFrom; use std::cell::{Cell, RefCell}; use std::cmp::{self, Ordering}; use std::fmt::{self, Show}; -use std::hash::{Hash, sip, Writer}; +use std::hash::{Hash, Writer, SipHasher, Hasher}; use std::mem; use std::ops; use std::rc::Rc; @@ -107,7 +107,7 @@ pub struct CrateAnalysis<'tcx> { pub glob_map: Option<GlobMap>, } -#[derive(Copy, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct field<'tcx> { pub name: ast::Name, pub mt: mt<'tcx> @@ -946,11 +946,18 @@ impl<'tcx> PartialEq for TyS<'tcx> { } impl<'tcx> Eq for TyS<'tcx> {} +#[cfg(stage0)] impl<'tcx, S: Writer> Hash<S> for TyS<'tcx> { fn hash(&self, s: &mut S) { (self as *const _).hash(s) } } +#[cfg(not(stage0))] +impl<'tcx, S: Writer + Hasher> Hash<S> for TyS<'tcx> { + fn hash(&self, s: &mut S) { + (self as *const _).hash(s) + } +} pub type Ty<'tcx> = &'tcx TyS<'tcx>; @@ -968,7 +975,7 @@ impl<'tcx> PartialEq for InternedTy<'tcx> { impl<'tcx> Eq for InternedTy<'tcx> {} -impl<'tcx, S: Writer> Hash<S> for InternedTy<'tcx> { +impl<'tcx, S: Writer + Hasher> Hash<S> for InternedTy<'tcx> { fn hash(&self, s: &mut S) { self.ty.sty.hash(s) } @@ -1491,10 +1498,12 @@ impl<'tcx> PolyTraitRef<'tcx> { } pub fn substs(&self) -> &'tcx Substs<'tcx> { + // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<> self.0.substs } pub fn input_types(&self) -> &[Ty<'tcx>] { + // FIXME(#20664) every use of this fn is probably a bug, it should yield Binder<> self.0.input_types() } @@ -1892,6 +1901,10 @@ pub struct ProjectionPredicate<'tcx> { pub type PolyProjectionPredicate<'tcx> = Binder<ProjectionPredicate<'tcx>>; impl<'tcx> PolyProjectionPredicate<'tcx> { + pub fn item_name(&self) -> ast::Name { + self.0.projection_ty.item_name // safe to skip the binder to access a name + } + pub fn sort_key(&self) -> (ast::DefId, ast::Name) { self.0.projection_ty.sort_key() } @@ -2032,8 +2045,8 @@ impl<'tcx> Predicate<'tcx> { /// struct Foo<T,U:Bar<T>> { ... } /// /// Here, the `Generics` for `Foo` would contain a list of bounds like -/// `[.index(&FullRange), [U:Bar<T>]]`. Now if there were some particular reference -/// like `Foo<int,uint>`, then the `GenericBounds` would be `[.index(&FullRange), +/// `[[], [U:Bar<T>]]`. Now if there were some particular reference +/// like `Foo<int,uint>`, then the `GenericBounds` would be `[[], /// [uint:Bar<int>]]`. #[derive(Clone, Show)] pub struct GenericBounds<'tcx> { @@ -2208,9 +2221,9 @@ impl<'a, 'tcx> ParameterEnvironment<'a, 'tcx> { ParameterEnvironment::for_item(cx, cx.map.get_parent(id)) } _ => { - cx.sess.bug(format!("ParameterEnvironment::from_item(): \ + cx.sess.bug(&format!("ParameterEnvironment::from_item(): \ `{}` is not an item", - cx.map.node_to_string(id)).index(&FullRange)) + cx.map.node_to_string(id))[]) } } } @@ -2295,7 +2308,7 @@ impl UnboxedClosureKind { }; match result { Ok(trait_did) => trait_did, - Err(err) => cx.sess.fatal(err.index(&FullRange)), + Err(err) => cx.sess.fatal(&err[]), } } } @@ -2328,12 +2341,12 @@ impl<'tcx> CommonTypes<'tcx> { bool: intern_ty(arena, interner, ty_bool), char: intern_ty(arena, interner, ty_char), err: intern_ty(arena, interner, ty_err), - int: intern_ty(arena, interner, ty_int(ast::TyIs)), + int: intern_ty(arena, interner, ty_int(ast::TyIs(false))), i8: intern_ty(arena, interner, ty_int(ast::TyI8)), i16: intern_ty(arena, interner, ty_int(ast::TyI16)), i32: intern_ty(arena, interner, ty_int(ast::TyI32)), i64: intern_ty(arena, interner, ty_int(ast::TyI64)), - uint: intern_ty(arena, interner, ty_uint(ast::TyUs)), + uint: intern_ty(arena, interner, ty_uint(ast::TyUs(false))), u8: intern_ty(arena, interner, ty_uint(ast::TyU8)), u16: intern_ty(arena, interner, ty_uint(ast::TyU16)), u32: intern_ty(arena, interner, ty_uint(ast::TyU32)), @@ -2616,7 +2629,7 @@ impl FlagComputation { } &ty_tup(ref ts) => { - self.add_tys(ts.index(&FullRange)); + self.add_tys(&ts[]); } &ty_bare_fn(_, ref f) => { @@ -2639,7 +2652,7 @@ impl FlagComputation { fn add_fn_sig(&mut self, fn_sig: &PolyFnSig) { let mut computation = FlagComputation::new(); - computation.add_tys(fn_sig.0.inputs.index(&FullRange)); + computation.add_tys(&fn_sig.0.inputs[]); if let ty::FnConverging(output) = fn_sig.0.output { computation.add_ty(output); @@ -2679,7 +2692,7 @@ impl FlagComputation { pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> { match tm { - ast::TyIs => tcx.types.int, + ast::TyIs(_) => tcx.types.int, ast::TyI8 => tcx.types.i8, ast::TyI16 => tcx.types.i16, ast::TyI32 => tcx.types.i32, @@ -2689,7 +2702,7 @@ pub fn mk_mach_int<'tcx>(tcx: &ctxt<'tcx>, tm: ast::IntTy) -> Ty<'tcx> { pub fn mk_mach_uint<'tcx>(tcx: &ctxt<'tcx>, tm: ast::UintTy) -> Ty<'tcx> { match tm { - ast::TyUs => tcx.types.uint, + ast::TyUs(_) => tcx.types.uint, ast::TyU8 => tcx.types.u8, ast::TyU16 => tcx.types.u16, ast::TyU32 => tcx.types.u32, @@ -2808,7 +2821,7 @@ pub fn mk_trait<'tcx>(cx: &ctxt<'tcx>, fn bound_list_is_sorted(bounds: &[ty::PolyProjectionPredicate]) -> bool { bounds.len() == 0 || - bounds.index(&(1..)).iter().enumerate().all( + bounds[1..].iter().enumerate().all( |(index, bound)| bounds[index].sort_key() <= bound.sort_key()) } @@ -3062,8 +3075,8 @@ pub fn sequence_element_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { ty_vec(ty, _) => ty, ty_str => mk_mach_uint(cx, ast::TyU8), ty_open(ty) => sequence_element_type(cx, ty), - _ => cx.sess.bug(format!("sequence_element_type called on non-sequence value: {}", - ty_to_string(cx, ty)).index(&FullRange)), + _ => cx.sess.bug(&format!("sequence_element_type called on non-sequence value: {}", + ty_to_string(cx, ty))[]), } } @@ -3350,7 +3363,7 @@ pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents { let result = match ty.sty { // uint and int are ffi-unsafe - ty_uint(ast::TyUs) | ty_int(ast::TyIs) => { + ty_uint(ast::TyUs(_)) | ty_int(ast::TyIs(_)) => { TC::ReachesFfiUnsafe } @@ -3397,7 +3410,7 @@ pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents { ty_struct(did, substs) => { let flds = struct_fields(cx, did, substs); let mut res = - TypeContents::union(flds.index(&FullRange), + TypeContents::union(&flds[], |f| tc_mt(cx, f.mt, cache)); if !lookup_repr_hints(cx, did).contains(&attr::ReprExtern) { @@ -3421,15 +3434,15 @@ pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents { } ty_tup(ref tys) => { - TypeContents::union(tys.index(&FullRange), + TypeContents::union(&tys[], |ty| tc_ty(cx, *ty, cache)) } ty_enum(did, substs) => { let variants = substd_enum_variants(cx, did, substs); let mut res = - TypeContents::union(variants.index(&FullRange), |variant| { - TypeContents::union(variant.args.index(&FullRange), + TypeContents::union(&variants[], |variant| { + TypeContents::union(&variant.args[], |arg_ty| { tc_ty(cx, *arg_ty, cache) }) @@ -3924,7 +3937,7 @@ pub fn type_is_fresh(ty: Ty) -> bool { pub fn type_is_uint(ty: Ty) -> bool { match ty.sty { - ty_infer(IntVar(_)) | ty_uint(ast::TyUs) => true, + ty_infer(IntVar(_)) | ty_uint(ast::TyUs(_)) => true, _ => false } } @@ -3970,7 +3983,7 @@ pub fn type_is_signed(ty: Ty) -> bool { pub fn type_is_machine(ty: Ty) -> bool { match ty.sty { - ty_int(ast::TyIs) | ty_uint(ast::TyUs) => false, + ty_int(ast::TyIs(_)) | ty_uint(ast::TyUs(_)) => false, ty_int(..) | ty_uint(..) | ty_float(..) => true, _ => false } @@ -4013,8 +4026,8 @@ pub fn deref<'tcx>(ty: Ty<'tcx>, explicit: bool) -> Option<mt<'tcx>> { pub fn close_type<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { match ty.sty { ty_open(ty) => mk_rptr(cx, cx.mk_region(ReStatic), mt {ty: ty, mutbl:ast::MutImmutable}), - _ => cx.sess.bug(format!("Trying to close a non-open type {}", - ty_to_string(cx, ty)).index(&FullRange)) + _ => cx.sess.bug(&format!("Trying to close a non-open type {}", + ty_to_string(cx, ty))[]) } } @@ -4114,8 +4127,8 @@ pub fn node_id_to_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) match cx.trait_refs.borrow().get(&id) { Some(ty) => ty.clone(), None => cx.sess.bug( - format!("node_id_to_trait_ref: no trait ref for node `{}`", - cx.map.node_to_string(id)).index(&FullRange)) + &format!("node_id_to_trait_ref: no trait ref for node `{}`", + cx.map.node_to_string(id))[]) } } @@ -4127,8 +4140,8 @@ pub fn node_id_to_type<'tcx>(cx: &ctxt<'tcx>, id: ast::NodeId) -> Ty<'tcx> { match try_node_id_to_type(cx, id) { Some(ty) => ty, None => cx.sess.bug( - format!("node_id_to_type: no type for node `{}`", - cx.map.node_to_string(id)).index(&FullRange)) + &format!("node_id_to_type: no type for node `{}`", + cx.map.node_to_string(id))[]) } } @@ -4214,8 +4227,8 @@ pub fn ty_region(tcx: &ctxt, ref s => { tcx.sess.span_bug( span, - format!("ty_region() invoked on an inappropriate ty: {:?}", - s).index(&FullRange)); + &format!("ty_region() invoked on an inappropriate ty: {:?}", + s)[]); } } } @@ -4274,13 +4287,13 @@ pub fn expr_span(cx: &ctxt, id: NodeId) -> Span { e.span } Some(f) => { - cx.sess.bug(format!("Node id {} is not an expr: {:?}", + cx.sess.bug(&format!("Node id {} is not an expr: {:?}", id, - f).index(&FullRange)); + f)[]); } None => { - cx.sess.bug(format!("Node id {} is not present \ - in the node map", id).index(&FullRange)); + cx.sess.bug(&format!("Node id {} is not present \ + in the node map", id)[]); } } } @@ -4294,16 +4307,16 @@ pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString { } _ => { cx.sess.bug( - format!("Variable id {} maps to {:?}, not local", + &format!("Variable id {} maps to {:?}, not local", id, - pat).index(&FullRange)); + pat)[]); } } } r => { - cx.sess.bug(format!("Variable id {} maps to {:?}, not local", + cx.sess.bug(&format!("Variable id {} maps to {:?}, not local", id, - r).index(&FullRange)); + r)[]); } } } @@ -4332,9 +4345,9 @@ pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>, } ref b => { cx.sess.bug( - format!("AdjustReifyFnPointer adjustment on non-fn-item: \ + &format!("AdjustReifyFnPointer adjustment on non-fn-item: \ {:?}", - b).index(&FullRange)); + b)[]); } } } @@ -4361,11 +4374,11 @@ pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>, None => { cx.sess.span_bug( span, - format!("the {}th autoderef failed: \ + &format!("the {}th autoderef failed: \ {}", i, ty_to_string(cx, adjusted_ty)) - .index(&FullRange)); + []); } } } @@ -4427,8 +4440,8 @@ pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>, mk_vec(cx, ty, None) } _ => cx.sess.span_bug(span, - format!("UnsizeLength with bad sty: {:?}", - ty_to_string(cx, ty)).index(&FullRange)) + &format!("UnsizeLength with bad sty: {:?}", + ty_to_string(cx, ty))[]) }, &UnsizeStruct(box ref k, tp_index) => match ty.sty { ty_struct(did, substs) => { @@ -4439,8 +4452,8 @@ pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>, mk_struct(cx, did, cx.mk_substs(unsized_substs)) } _ => cx.sess.span_bug(span, - format!("UnsizeStruct with bad sty: {:?}", - ty_to_string(cx, ty)).index(&FullRange)) + &format!("UnsizeStruct with bad sty: {:?}", + ty_to_string(cx, ty))[]) }, &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => { mk_trait(cx, principal.clone(), bounds.clone()) @@ -4452,8 +4465,8 @@ pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> def::Def { match tcx.def_map.borrow().get(&expr.id) { Some(&def) => def, None => { - tcx.sess.span_bug(expr.span, format!( - "no def-map entry for expr {}", expr.id).index(&FullRange)); + tcx.sess.span_bug(expr.span, &format!( + "no def-map entry for expr {}", expr.id)[]); } } } @@ -4546,9 +4559,9 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind { def => { tcx.sess.span_bug( expr.span, - format!("uncategorized def for expr {}: {:?}", + &format!("uncategorized def for expr {}: {:?}", expr.id, - def).index(&FullRange)); + def)[]); } } } @@ -4668,12 +4681,12 @@ pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field]) -> uint { let mut i = 0u; for f in fields.iter() { if f.name == name { return i; } i += 1u; } - tcx.sess.bug(format!( + tcx.sess.bug(&format!( "no field named `{}` found in the list of fields `{:?}`", token::get_name(name), fields.iter() .map(|f| token::get_name(f.name).get().to_string()) - .collect::<Vec<String>>()).index(&FullRange)); + .collect::<Vec<String>>())[]); } pub fn impl_or_trait_item_idx(id: ast::Name, trait_items: &[ImplOrTraitItem]) @@ -4928,7 +4941,7 @@ pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) match item.node { ItemTrait(_, _, _, ref ms) => { let (_, p) = - ast_util::split_trait_methods(ms.index(&FullRange)); + ast_util::split_trait_methods(&ms[]); p.iter() .map(|m| { match impl_or_trait_item( @@ -4945,16 +4958,16 @@ pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) }).collect() } _ => { - cx.sess.bug(format!("provided_trait_methods: `{:?}` is \ + cx.sess.bug(&format!("provided_trait_methods: `{:?}` is \ not a trait", - id).index(&FullRange)) + id)[]) } } } _ => { - cx.sess.bug(format!("provided_trait_methods: `{:?}` is not a \ + cx.sess.bug(&format!("provided_trait_methods: `{:?}` is not a \ trait", - id).index(&FullRange)) + id)[]) } } } else { @@ -5192,7 +5205,7 @@ impl<'tcx> VariantInfo<'tcx> { }; }, ast::StructVariantKind(ref struct_def) => { - let fields: &[StructField] = struct_def.fields.index(&FullRange); + let fields: &[StructField] = &struct_def.fields[]; assert!(fields.len() > 0); @@ -5342,8 +5355,8 @@ pub fn enum_variants<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) Err(ref err) => { cx.sess .span_err(e.span, - format!("expected constant: {}", - *err).index(&FullRange)); + &format!("expected constant: {}", + *err)[]); } }, None => {} @@ -5632,8 +5645,8 @@ pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> { Some(fields) => (**fields).clone(), _ => { cx.sess.bug( - format!("ID not mapped to struct fields: {}", - cx.map.node_to_string(did.node)).index(&FullRange)); + &format!("ID not mapped to struct fields: {}", + cx.map.node_to_string(did.node))[]); } } } else { @@ -5666,7 +5679,7 @@ pub fn struct_fields<'tcx>(cx: &ctxt<'tcx>, did: ast::DefId, substs: &Substs<'tc pub fn tup_fields<'tcx>(v: &[Ty<'tcx>]) -> Vec<field<'tcx>> { v.iter().enumerate().map(|(i, &f)| { field { - name: token::intern(i.to_string().index(&FullRange)), + name: token::intern(&i.to_string()[]), mt: mt { ty: f, mutbl: MutImmutable @@ -5841,9 +5854,9 @@ pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint { const_eval::const_binary(_) => "binary array" }; - tcx.sess.span_err(count_expr.span, format!( + tcx.sess.span_err(count_expr.span, &format!( "expected positive integer for repeat count, found {}", - found).index(&FullRange)); + found)[]); } Err(_) => { let found = match count_expr.node { @@ -5856,9 +5869,9 @@ pub fn eval_repeat_count(tcx: &ctxt, count_expr: &ast::Expr) -> uint { _ => "non-constant expression" }; - tcx.sess.span_err(count_expr.span, format!( + tcx.sess.span_err(count_expr.span, &format!( "expected constant integer for repeat count, found {}", - found).index(&FullRange)); + found)[]); } } 0 @@ -6164,15 +6177,16 @@ pub fn trait_item_of_item(tcx: &ctxt, def_id: ast::DefId) /// Creates a hash of the type `Ty` which will be the same no matter what crate /// context it's calculated within. This is used by the `type_id` intrinsic. pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) -> u64 { - let mut state = sip::SipState::new(); + let mut state = SipHasher::new(); helper(tcx, ty, svh, &mut state); - return state.result(); + return state.finish(); - fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh, state: &mut sip::SipState) { + fn helper<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh, + state: &mut SipHasher) { macro_rules! byte { ($b:expr) => { ($b as u8).hash(state) } } macro_rules! hash { ($e:expr) => { $e.hash(state) } } - let region = |&: state: &mut sip::SipState, r: Region| { + let region = |&: state: &mut SipHasher, r: Region| { match r { ReStatic => {} ReLateBound(db, BrAnon(i)) => { @@ -6189,7 +6203,7 @@ pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) - } } }; - let did = |&: state: &mut sip::SipState, did: DefId| { + let did = |&: state: &mut SipHasher, did: DefId| { let h = if ast_util::is_local(did) { svh.clone() } else { @@ -6198,10 +6212,10 @@ pub fn hash_crate_independent<'tcx>(tcx: &ctxt<'tcx>, ty: Ty<'tcx>, svh: &Svh) - h.as_str().hash(state); did.node.hash(state); }; - let mt = |&: state: &mut sip::SipState, mt: mt| { + let mt = |&: state: &mut SipHasher, mt: mt| { mt.mutbl.hash(state); }; - let fn_sig = |&: state: &mut sip::SipState, sig: &Binder<FnSig<'tcx>>| { + let fn_sig = |&: state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| { let sig = anonymize_late_bound_regions(tcx, sig).0; for a in sig.inputs.iter() { helper(tcx, *a, svh, state); } if let ty::FnConverging(output) = sig.output { @@ -6642,7 +6656,7 @@ pub fn with_freevars<T, F>(tcx: &ty::ctxt, fid: ast::NodeId, f: F) -> T where { match tcx.freevars.borrow().get(&fid) { None => f(&[]), - Some(d) => f(d.index(&FullRange)) + Some(d) => f(&d[]) } } @@ -6672,7 +6686,7 @@ pub fn liberate_late_bound_regions<'tcx, T>( { replace_late_bound_regions( tcx, value, - |br, _| ty::ReFree(ty::FreeRegion{scope: scope, bound_region: br})).0 + |br| ty::ReFree(ty::FreeRegion{scope: scope, bound_region: br})).0 } pub fn count_late_bound_regions<'tcx, T>( @@ -6681,7 +6695,7 @@ pub fn count_late_bound_regions<'tcx, T>( -> uint where T : TypeFoldable<'tcx> + Repr<'tcx> { - let (_, skol_map) = replace_late_bound_regions(tcx, value, |_, _| ty::ReStatic); + let (_, skol_map) = replace_late_bound_regions(tcx, value, |_| ty::ReStatic); skol_map.len() } @@ -6712,7 +6726,7 @@ pub fn erase_late_bound_regions<'tcx, T>( -> T where T : TypeFoldable<'tcx> + Repr<'tcx> { - replace_late_bound_regions(tcx, value, |_, _| ty::ReStatic).0 + replace_late_bound_regions(tcx, value, |_| ty::ReStatic).0 } /// Rewrite any late-bound regions so that they are anonymous. Region numbers are @@ -6730,9 +6744,9 @@ pub fn anonymize_late_bound_regions<'tcx, T>( where T : TypeFoldable<'tcx> + Repr<'tcx>, { let mut counter = 0; - ty::Binder(replace_late_bound_regions(tcx, sig, |_, db| { + ty::Binder(replace_late_bound_regions(tcx, sig, |_| { counter += 1; - ReLateBound(db, BrAnon(counter)) + ReLateBound(ty::DebruijnIndex::new(1), BrAnon(counter)) }).0) } @@ -6743,7 +6757,7 @@ pub fn replace_late_bound_regions<'tcx, T, F>( mut mapf: F) -> (T, FnvHashMap<ty::BoundRegion,ty::Region>) where T : TypeFoldable<'tcx> + Repr<'tcx>, - F : FnMut(BoundRegion, DebruijnIndex) -> ty::Region, + F : FnMut(BoundRegion) -> ty::Region, { debug!("replace_late_bound_regions({})", binder.repr(tcx)); @@ -6755,8 +6769,19 @@ pub fn replace_late_bound_regions<'tcx, T, F>( debug!("region={}", region.repr(tcx)); match region { ty::ReLateBound(debruijn, br) if debruijn.depth == current_depth => { - * map.entry(br).get().unwrap_or_else( - |vacant_entry| vacant_entry.insert(mapf(br, debruijn))) + let region = + * map.entry(br).get().unwrap_or_else( + |vacant_entry| vacant_entry.insert(mapf(br))); + + if let ty::ReLateBound(debruijn1, br) = region { + // If the callback returns a late-bound region, + // that region should always use depth 1. Then we + // adjust it to the correct depth. + assert_eq!(debruijn1.depth, 1); + ty::ReLateBound(debruijn, br) + } else { + region + } } _ => { region @@ -6903,6 +6928,7 @@ pub enum CopyImplementationError { FieldDoesNotImplementCopy(ast::Name), VariantDoesNotImplementCopy(ast::Name), TypeIsStructural, + TypeHasDestructor, } pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tcx>, @@ -6912,7 +6938,7 @@ pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tc { let tcx = param_env.tcx; - match self_type.sty { + let did = match self_type.sty { ty::ty_struct(struct_did, substs) => { let fields = ty::struct_fields(tcx, struct_did, substs); for field in fields.iter() { @@ -6920,6 +6946,7 @@ pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tc return Err(FieldDoesNotImplementCopy(field.name)) } } + struct_did } ty::ty_enum(enum_did, substs) => { let enum_variants = ty::enum_variants(tcx, enum_did); @@ -6932,8 +6959,13 @@ pub fn can_type_implement_copy<'a,'tcx>(param_env: &ParameterEnvironment<'a, 'tc } } } + enum_did } _ => return Err(TypeIsStructural), + }; + + if ty::has_dtor(tcx, did) { + return Err(TypeHasDestructor) } Ok(()) @@ -6958,6 +6990,13 @@ impl<'tcx> RegionEscape for Ty<'tcx> { } } +impl<'tcx> RegionEscape for Substs<'tcx> { + fn has_regions_escaping_depth(&self, depth: u32) -> bool { + self.types.has_regions_escaping_depth(depth) || + self.regions.has_regions_escaping_depth(depth) + } +} + impl<'tcx,T:RegionEscape> RegionEscape for VecPerParamSpace<T> { fn has_regions_escaping_depth(&self, depth: u32) -> bool { self.iter_enumerated().any(|(space, _, t)| { @@ -7212,6 +7251,12 @@ impl<'tcx> HasProjectionTypes for FnSig<'tcx> { } } +impl<'tcx> HasProjectionTypes for field<'tcx> { + fn has_projection_types(&self) -> bool { + self.mt.ty.has_projection_types() + } +} + impl<'tcx> HasProjectionTypes for BareFnTy<'tcx> { fn has_projection_types(&self) -> bool { self.sig.has_projection_types() @@ -7311,3 +7356,11 @@ impl<'tcx> Repr<'tcx> for UnboxedClosureUpvar<'tcx> { self.ty.repr(tcx)) } } + +impl<'tcx> Repr<'tcx> for field<'tcx> { + fn repr(&self, tcx: &ctxt<'tcx>) -> String { + format!("field({},{})", + self.name.repr(tcx), + self.mt.repr(tcx)) + } +} diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 424e357d8d4..b81a4ed2f58 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -273,6 +273,15 @@ impl<'tcx> TypeFoldable<'tcx> for ty::TraitRef<'tcx> { } } +impl<'tcx> TypeFoldable<'tcx> for ty::field<'tcx> { + fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::field<'tcx> { + ty::field { + name: self.name, + mt: self.mt.fold_with(folder), + } + } +} + impl<'tcx> TypeFoldable<'tcx> for ty::Region { fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Region { folder.fold_region(*self) @@ -853,7 +862,10 @@ impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> /////////////////////////////////////////////////////////////////////////// // Region eraser // -// Replaces all free regions with 'static. Useful in trans. +// Replaces all free regions with 'static. Useful in contexts, such as +// method probing, where precise region relationships are not +// important. Note that in trans you should use +// `common::erase_regions` instead. pub struct RegionEraser<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx>, diff --git a/src/librustc/plugin/load.rs b/src/librustc/plugin/load.rs index a38298d52dd..ef8a89c40fb 100644 --- a/src/librustc/plugin/load.rs +++ b/src/librustc/plugin/load.rs @@ -11,7 +11,7 @@ //! Used by `rustc` when loading a plugin, or a crate with exported macros. use session::Session; -use metadata::creader::CrateReader; +use metadata::creader::{CrateOrString, CrateReader}; use plugin::registry::Registry; use std::mem; @@ -44,11 +44,11 @@ pub struct Plugins { pub registrars: Vec<PluginRegistrar>, } -struct PluginLoader<'a> { +pub struct PluginLoader<'a> { sess: &'a Session, span_whitelist: HashSet<Span>, reader: CrateReader<'a>, - plugins: Plugins, + pub plugins: Plugins, } impl<'a> PluginLoader<'a> { @@ -67,7 +67,7 @@ impl<'a> PluginLoader<'a> { /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, krate: &ast::Crate, - addl_plugins: Option<Plugins>) -> Plugins { + addl_plugins: Option<Vec<String>>) -> Plugins { let mut loader = PluginLoader::new(sess); // We need to error on `#[macro_use] extern crate` when it isn't at the @@ -79,19 +79,14 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate, visit::walk_crate(&mut loader, krate); - let mut plugins = loader.plugins; - - match addl_plugins { - Some(addl_plugins) => { - // Add in the additional plugins requested by the frontend - let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins; - plugins.macros.extend(addl_macros.into_iter()); - plugins.registrars.extend(addl_registrars.into_iter()); + if let Some(plugins) = addl_plugins { + for plugin in plugins.iter() { + loader.load_plugin(CrateOrString::Str(plugin.as_slice()), + None, None, None) } - None => () } - return plugins; + return loader.plugins; } // note that macros aren't expanded yet, and therefore macros can't add plugins. @@ -160,22 +155,39 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { } } + self.load_plugin(CrateOrString::Krate(vi), plugin_attr, macro_selection, Some(reexport)) + } + + fn visit_mac(&mut self, _: &ast::Mac) { + // bummer... can't see plugins inside macros. + // do nothing. + } +} + +impl<'a> PluginLoader<'a> { + pub fn load_plugin<'b>(&mut self, + c: CrateOrString<'b>, + plugin_attr: Option<P<ast::MetaItem>>, + macro_selection: Option<HashSet<token::InternedString>>, + reexport: Option<HashSet<token::InternedString>>) { let mut macros = vec![]; let mut registrar = None; - let load_macros = match macro_selection.as_ref() { - Some(sel) => sel.len() != 0 || reexport.len() != 0, - None => true, + let load_macros = match (macro_selection.as_ref(), reexport.as_ref()) { + (Some(sel), Some(re)) => sel.len() != 0 || re.len() != 0, + _ => true, }; let load_registrar = plugin_attr.is_some(); - if load_macros && !self.span_whitelist.contains(&vi.span) { - self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \ - the crate root"); - } + if let CrateOrString::Krate(vi) = c { + if load_macros && !self.span_whitelist.contains(&vi.span) { + self.sess.span_err(vi.span, "an `extern crate` loading macros must be at \ + the crate root"); + } + } if load_macros || load_registrar { - let pmd = self.reader.read_plugin_metadata(vi); + let pmd = self.reader.read_plugin_metadata(c); if load_macros { macros = pmd.exported_macros(); } @@ -190,12 +202,16 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { None => true, Some(sel) => sel.contains(&name), }; - def.export = reexport.contains(&name); + def.export = if let Some(ref re) = reexport { + re.contains(&name) + } else { + false // Don't reexport macros from crates loaded from the command line + }; self.plugins.macros.push(def); } if let Some((lib, symbol)) = registrar { - let fun = self.dylink_registrar(vi, lib, symbol); + let fun = self.dylink_registrar(c, lib, symbol); self.plugins.registrars.push(PluginRegistrar { fun: fun, args: plugin_attr.unwrap(), @@ -203,16 +219,9 @@ impl<'a, 'v> Visitor<'v> for PluginLoader<'a> { } } - fn visit_mac(&mut self, _: &ast::Mac) { - // bummer... can't see plugins inside macros. - // do nothing. - } -} - -impl<'a> PluginLoader<'a> { // Dynamically link a registrar function into the compiler process. - fn dylink_registrar(&mut self, - vi: &ast::ViewItem, + fn dylink_registrar<'b>(&mut self, + c: CrateOrString<'b>, path: Path, symbol: String) -> PluginRegistrarFun { // Make sure the path contains a / or the linker will search for it. @@ -223,17 +232,29 @@ impl<'a> PluginLoader<'a> { // this is fatal: there are almost certainly macros we need // inside this crate, so continue would spew "macro undefined" // errors - Err(err) => self.sess.span_fatal(vi.span, err.index(&FullRange)) + Err(err) => { + if let CrateOrString::Krate(cr) = c { + self.sess.span_fatal(cr.span, &err[]) + } else { + self.sess.fatal(&err[]) + } + } }; unsafe { let registrar = - match lib.symbol(symbol.index(&FullRange)) { + match lib.symbol(&symbol[]) { Ok(registrar) => { mem::transmute::<*mut u8,PluginRegistrarFun>(registrar) } // again fatal if we can't register macros - Err(err) => self.sess.span_fatal(vi.span, err.index(&FullRange)) + Err(err) => { + if let CrateOrString::Krate(cr) = c { + self.sess.span_fatal(cr.span, &err[]) + } else { + self.sess.fatal(&err[]) + } + } }; // Intentionally leak the dynamic library. We can't ever unload it diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 4968066f7b6..d9bb1d769bf 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -99,7 +99,7 @@ pub struct Options { pub parse_only: bool, pub no_trans: bool, pub no_analysis: bool, - pub debugging_opts: u64, + pub debugging_opts: DebuggingOptions, /// Whether to write dependency files. It's (enabled, optional filename). pub write_dependency_info: (bool, Option<Path>), pub prints: Vec<PrintRequest>, @@ -111,7 +111,24 @@ pub struct Options { /// An optional name to use as the crate for std during std injection, /// written `extern crate std = "name"`. Default to "std". Used by /// out-of-tree drivers. - pub alt_std_name: Option<String> + pub alt_std_name: Option<String>, + /// Indicates how the compiler should treat unstable features + pub unstable_features: UnstableFeatures +} + +#[derive(Clone, Copy)] +pub enum UnstableFeatures { + /// Hard errors for unstable features are active, as on + /// beta/stable channels. + Disallow, + /// Use the default lint levels + Default, + /// Errors are bypassed for bootstrapping. This is required any time + /// during the build that feature-related lints are set to warn or above + /// because the build turns on warnings-as-errors and uses lots of unstable + /// features. As a result, this this is always required for building Rust + /// itself. + Cheat } #[derive(Clone, PartialEq, Eq)] @@ -207,7 +224,7 @@ pub fn basic_options() -> Options { parse_only: false, no_trans: false, no_analysis: false, - debugging_opts: 0, + debugging_opts: basic_debugging_options(), write_dependency_info: (false, None), prints: Vec::new(), cg: basic_codegen_options(), @@ -217,6 +234,7 @@ pub fn basic_options() -> Options { crate_name: None, alt_std_name: None, libs: Vec::new(), + unstable_features: UnstableFeatures::Disallow } } @@ -239,103 +257,6 @@ pub enum CrateType { CrateTypeStaticlib, } -macro_rules! debugging_opts { - ([ $opt:ident ] $cnt:expr ) => ( - pub const $opt: u64 = 1 << $cnt; - ); - ([ $opt:ident, $($rest:ident),* ] $cnt:expr ) => ( - pub const $opt: u64 = 1 << $cnt; - debugging_opts! { [ $($rest),* ] $cnt + 1 } - ) -} - -debugging_opts! { - [ - VERBOSE, - TIME_PASSES, - COUNT_LLVM_INSNS, - TIME_LLVM_PASSES, - TRANS_STATS, - ASM_COMMENTS, - NO_VERIFY, - BORROWCK_STATS, - NO_LANDING_PADS, - DEBUG_LLVM, - COUNT_TYPE_SIZES, - META_STATS, - GC, - PRINT_LINK_ARGS, - PRINT_LLVM_PASSES, - AST_JSON, - AST_JSON_NOEXPAND, - LS, - SAVE_ANALYSIS, - PRINT_MOVE_FRAGMENTS, - FLOWGRAPH_PRINT_LOANS, - FLOWGRAPH_PRINT_MOVES, - FLOWGRAPH_PRINT_ASSIGNS, - FLOWGRAPH_PRINT_ALL, - PRINT_REGION_GRAPH, - PARSE_ONLY, - NO_TRANS, - NO_ANALYSIS, - UNSTABLE_OPTIONS, - PRINT_ENUM_SIZES - ] - 0 -} - -pub fn debugging_opts_map() -> Vec<(&'static str, &'static str, u64)> { - vec![("verbose", "in general, enable more debug printouts", VERBOSE), - ("time-passes", "measure time of each rustc pass", TIME_PASSES), - ("count-llvm-insns", "count where LLVM \ - instrs originate", COUNT_LLVM_INSNS), - ("time-llvm-passes", "measure time of each LLVM pass", - TIME_LLVM_PASSES), - ("trans-stats", "gather trans statistics", TRANS_STATS), - ("asm-comments", "generate comments into the assembly (may change behavior)", - ASM_COMMENTS), - ("no-verify", "skip LLVM verification", NO_VERIFY), - ("borrowck-stats", "gather borrowck statistics", BORROWCK_STATS), - ("no-landing-pads", "omit landing pads for unwinding", - NO_LANDING_PADS), - ("debug-llvm", "enable debug output from LLVM", DEBUG_LLVM), - ("count-type-sizes", "count the sizes of aggregate types", - COUNT_TYPE_SIZES), - ("meta-stats", "gather metadata statistics", META_STATS), - ("print-link-args", "Print the arguments passed to the linker", - PRINT_LINK_ARGS), - ("gc", "Garbage collect shared data (experimental)", GC), - ("print-llvm-passes", - "Prints the llvm optimization passes being run", - PRINT_LLVM_PASSES), - ("ast-json", "Print the AST as JSON and halt", AST_JSON), - ("ast-json-noexpand", "Print the pre-expansion AST as JSON and halt", AST_JSON_NOEXPAND), - ("ls", "List the symbols defined by a library crate", LS), - ("save-analysis", "Write syntax and type analysis information \ - in addition to normal output", SAVE_ANALYSIS), - ("print-move-fragments", "Print out move-fragment data for every fn", - PRINT_MOVE_FRAGMENTS), - ("flowgraph-print-loans", "Include loan analysis data in \ - --pretty flowgraph output", FLOWGRAPH_PRINT_LOANS), - ("flowgraph-print-moves", "Include move analysis data in \ - --pretty flowgraph output", FLOWGRAPH_PRINT_MOVES), - ("flowgraph-print-assigns", "Include assignment analysis data in \ - --pretty flowgraph output", FLOWGRAPH_PRINT_ASSIGNS), - ("flowgraph-print-all", "Include all dataflow analysis data in \ - --pretty flowgraph output", FLOWGRAPH_PRINT_ALL), - ("print-region-graph", "Prints region inference graph. \ - Use with RUST_REGION_GRAPH=help for more info", - PRINT_REGION_GRAPH), - ("parse-only", "Parse only; do not compile, assemble, or link", PARSE_ONLY), - ("no-trans", "Run all passes except translation; no output", NO_TRANS), - ("no-analysis", "Parse and expand the source, but run no analysis and", - NO_ANALYSIS), - ("unstable-options", "Adds unstable command line options to rustc interface", - UNSTABLE_OPTIONS), - ("print-enum-sizes", "Print the size of enums and their variants", PRINT_ENUM_SIZES), - ] -} #[derive(Clone)] pub enum Passes { @@ -352,7 +273,7 @@ impl Passes { } } -/// Declare a macro that will define all CodegenOptions fields and parsers all +/// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all /// at once. The goal of this macro is to define an interface that can be /// programmatically used by the option parser in order to initialize the struct /// without hardcoding field names all over the place. @@ -362,23 +283,70 @@ impl Passes { /// cgsetters module which is a bunch of generated code to parse an option into /// its respective field in the struct. There are a few hand-written parsers for /// parsing specific types of values in this module. -macro_rules! cgoptions { - ($($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) => +macro_rules! options { + ($struct_name:ident, $setter_name:ident, $defaultfn:ident, + $buildfn:ident, $prefix:expr, $outputname:expr, + $stat:ident, $mod_desc:ident, $mod_set:ident, + $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) => ( #[derive(Clone)] - pub struct CodegenOptions { $(pub $opt: $t),* } + #[allow(missing_copy_implementations)] + pub struct $struct_name { $(pub $opt: $t),* } + + pub fn $defaultfn() -> $struct_name { + $struct_name { $($opt: $init),* } + } - pub fn basic_codegen_options() -> CodegenOptions { - CodegenOptions { $($opt: $init),* } + pub fn $buildfn(matches: &getopts::Matches) -> $struct_name + { + let mut op = $defaultfn(); + for option in matches.opt_strs($prefix).into_iter() { + let mut iter = option.splitn(1, '='); + let key = iter.next().unwrap(); + let value = iter.next(); + let option_to_lookup = key.replace("-", "_"); + let mut found = false; + for &(candidate, setter, opt_type_desc, _) in $stat.iter() { + if option_to_lookup != candidate { continue } + if !setter(&mut op, value) { + match (value, opt_type_desc) { + (Some(..), None) => { + early_error(&format!("{} option `{}` takes no \ + value", $outputname, key)[]) + } + (None, Some(type_desc)) => { + early_error(&format!("{0} option `{1}` requires \ + {2} ({3} {1}=<value>)", + $outputname, key, + type_desc, $prefix)[]) + } + (Some(value), Some(type_desc)) => { + early_error(&format!("incorrect value `{}` for {} \ + option `{}` - {} was expected", + value, $outputname, + key, type_desc)[]) + } + (None, None) => unreachable!() + } + } + found = true; + break; + } + if !found { + early_error(&format!("unknown codegen option: `{}`", + key)[]); + } + } + return op; } - pub type CodegenSetter = fn(&mut CodegenOptions, v: Option<&str>) -> bool; - pub const CG_OPTIONS: &'static [(&'static str, CodegenSetter, + pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool; + pub const $stat: &'static [(&'static str, $setter_name, Option<&'static str>, &'static str)] = - &[ $( (stringify!($opt), cgsetters::$opt, cg_type_descs::$parse, $desc) ),* ]; + &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ]; - #[allow(non_upper_case_globals)] - mod cg_type_descs { + #[allow(non_upper_case_globals, dead_code)] + mod $mod_desc { pub const parse_bool: Option<&'static str> = None; pub const parse_opt_bool: Option<&'static str> = None; pub const parse_string: Option<&'static str> = Some("a string"); @@ -392,11 +360,12 @@ macro_rules! cgoptions { Some("a number"); } - mod cgsetters { - use super::{CodegenOptions, Passes, SomePasses, AllPasses}; + #[allow(dead_code)] + mod $mod_set { + use super::{$struct_name, Passes, SomePasses, AllPasses}; $( - pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool { + pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool { $parse(&mut cg.$opt, v) } )* @@ -488,7 +457,9 @@ macro_rules! cgoptions { } ) } -cgoptions! { +options! {CodegenOptions, CodegenSetter, basic_codegen_options, + build_codegen_options, "C", "codegen", + CG_OPTIONS, cg_type_desc, cgsetters, ar: Option<String> = (None, parse_opt_string, "tool to assemble archives with"), linker: Option<String> = (None, parse_opt_string, @@ -544,45 +515,73 @@ cgoptions! { "Optimize with possible levels 0-3"), } -pub fn build_codegen_options(matches: &getopts::Matches) -> CodegenOptions -{ - let mut cg = basic_codegen_options(); - for option in matches.opt_strs("C").into_iter() { - let mut iter = option.splitn(1, '='); - let key = iter.next().unwrap(); - let value = iter.next(); - let option_to_lookup = key.replace("-", "_"); - let mut found = false; - for &(candidate, setter, opt_type_desc, _) in CG_OPTIONS.iter() { - if option_to_lookup != candidate { continue } - if !setter(&mut cg, value) { - match (value, opt_type_desc) { - (Some(..), None) => { - early_error(format!("codegen option `{}` takes no \ - value", key).index(&FullRange)) - } - (None, Some(type_desc)) => { - early_error(format!("codegen option `{0}` requires \ - {1} (-C {0}=<value>)", - key, type_desc).index(&FullRange)) - } - (Some(value), Some(type_desc)) => { - early_error(format!("incorrect value `{}` for codegen \ - option `{}` - {} was expected", - value, key, type_desc).index(&FullRange)) - } - (None, None) => unreachable!() - } - } - found = true; - break; - } - if !found { - early_error(format!("unknown codegen option: `{}`", - key).index(&FullRange)); - } - } - return cg; + +options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, + build_debugging_options, "Z", "debugging", + DB_OPTIONS, db_type_desc, dbsetters, + verbose: bool = (false, parse_bool, + "in general, enable more debug printouts"), + time_passes: bool = (false, parse_bool, + "measure time of each rustc pass"), + count_llvm_insns: bool = (false, parse_bool, + "count where LLVM instrs originate"), + time_llvm_passes: bool = (false, parse_bool, + "measure time of each LLVM pass"), + trans_stats: bool = (false, parse_bool, + "gather trans statistics"), + asm_comments: bool = (false, parse_bool, + "generate comments into the assembly (may change behavior)"), + no_verify: bool = (false, parse_bool, + "skip LLVM verification"), + borrowck_stats: bool = (false, parse_bool, + "gather borrowck statistics"), + no_landing_pads: bool = (false, parse_bool, + "omit landing pads for unwinding"), + debug_llvm: bool = (false, parse_bool, + "enable debug output from LLVM"), + count_type_sizes: bool = (false, parse_bool, + "count the sizes of aggregate types"), + meta_stats: bool = (false, parse_bool, + "gather metadata statistics"), + print_link_args: bool = (false, parse_bool, + "Print the arguments passed to the linker"), + gc: bool = (false, parse_bool, + "Garbage collect shared data (experimental)"), + print_llvm_passes: bool = (false, parse_bool, + "Prints the llvm optimization passes being run"), + ast_json: bool = (false, parse_bool, + "Print the AST as JSON and halt"), + ast_json_noexpand: bool = (false, parse_bool, + "Print the pre-expansion AST as JSON and halt"), + ls: bool = (false, parse_bool, + "List the symbols defined by a library crate"), + save_analysis: bool = (false, parse_bool, + "Write syntax and type analysis information in addition to normal output"), + print_move_fragments: bool = (false, parse_bool, + "Print out move-fragment data for every fn"), + flowgraph_print_loans: bool = (false, parse_bool, + "Include loan analysis data in --pretty flowgraph output"), + flowgraph_print_moves: bool = (false, parse_bool, + "Include move analysis data in --pretty flowgraph output"), + flowgraph_print_assigns: bool = (false, parse_bool, + "Include assignment analysis data in --pretty flowgraph output"), + flowgraph_print_all: bool = (false, parse_bool, + "Include all dataflow analysis data in --pretty flowgraph output"), + print_region_graph: bool = (false, parse_bool, + "Prints region inference graph. \ + Use with RUST_REGION_GRAPH=help for more info"), + parse_only: bool = (false, parse_bool, + "Parse only; do not compile, assemble, or link"), + no_trans: bool = (false, parse_bool, + "Run all passes except translation; no output"), + no_analysis: bool = (false, parse_bool, + "Parse and expand the source, but run no analysis"), + extra_plugins: Vec<String> = (Vec::new(), parse_list, + "load extra plugins"), + unstable_options: bool = (false, parse_bool, + "Adds unstable command line options to rustc interface"), + print_enum_sizes: bool = (false, parse_bool, + "Print the size of enums and their variants"), } pub fn default_lib_output() -> CrateType { @@ -592,10 +591,10 @@ pub fn default_lib_output() -> CrateType { pub fn default_configuration(sess: &Session) -> ast::CrateConfig { use syntax::parse::token::intern_and_get_ident as intern; - let end = sess.target.target.target_endian.index(&FullRange); - let arch = sess.target.target.arch.index(&FullRange); - let wordsz = sess.target.target.target_word_size.index(&FullRange); - let os = sess.target.target.target_os.index(&FullRange); + let end = &sess.target.target.target_endian[]; + let arch = &sess.target.target.arch[]; + let wordsz = &sess.target.target.target_pointer_width[]; + let os = &sess.target.target.target_os[]; let fam = match sess.target.target.options.is_like_windows { true => InternedString::new("windows"), @@ -609,7 +608,7 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig { mk(InternedString::new("target_family"), fam), mk(InternedString::new("target_arch"), intern(arch)), mk(InternedString::new("target_endian"), intern(end)), - mk(InternedString::new("target_word_size"), + mk(InternedString::new("target_pointer_width"), intern(wordsz)) ); } @@ -631,23 +630,23 @@ pub fn build_configuration(sess: &Session) -> ast::CrateConfig { append_configuration(&mut user_cfg, InternedString::new("test")) } let mut v = user_cfg.into_iter().collect::<Vec<_>>(); - v.push_all(default_cfg.index(&FullRange)); + v.push_all(&default_cfg[]); v } pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config { - let target = match Target::search(opts.target_triple.index(&FullRange)) { + let target = match Target::search(&opts.target_triple[]) { Ok(t) => t, Err(e) => { sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice()); } }; - let (int_type, uint_type) = match target.target_word_size.index(&FullRange) { + let (int_type, uint_type) = match &target.target_pointer_width[] { "32" => (ast::TyI32, ast::TyU32), "64" => (ast::TyI64, ast::TyU64), - w => sp.handler().fatal((format!("target specification was invalid: unrecognized \ - target-word-size {}", w)).index(&FullRange)) + w => sp.handler().fatal(&format!("target specification was invalid: unrecognized \ + target-word-size {}", w)[]) }; Config { @@ -845,7 +844,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let unparsed_crate_types = matches.opt_strs("crate-type"); let crate_types = parse_crate_types_from_list(unparsed_crate_types) - .unwrap_or_else(|e| early_error(e.index(&FullRange))); + .unwrap_or_else(|e| early_error(&e[])); let mut lint_opts = vec!(); let mut describe_lints = false; @@ -860,52 +859,36 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { } } - let mut debugging_opts = 0; - let debug_flags = matches.opt_strs("Z"); - let debug_map = debugging_opts_map(); - for debug_flag in debug_flags.iter() { - let mut this_bit = 0; - for &(name, _, bit) in debug_map.iter() { - if name == *debug_flag { - this_bit = bit; - break; - } - } - if this_bit == 0 { - early_error(format!("unknown debug flag: {}", - *debug_flag).index(&FullRange)) - } - debugging_opts |= this_bit; - } + let debugging_opts = build_debugging_options(matches); let parse_only = if matches.opt_present("parse-only") { // FIXME(acrichto) remove this eventually early_warn("--parse-only is deprecated in favor of -Z parse-only"); true } else { - debugging_opts & PARSE_ONLY != 0 + debugging_opts.parse_only }; let no_trans = if matches.opt_present("no-trans") { // FIXME(acrichto) remove this eventually early_warn("--no-trans is deprecated in favor of -Z no-trans"); true } else { - debugging_opts & NO_TRANS != 0 + debugging_opts.no_trans }; let no_analysis = if matches.opt_present("no-analysis") { // FIXME(acrichto) remove this eventually early_warn("--no-analysis is deprecated in favor of -Z no-analysis"); true } else { - debugging_opts & NO_ANALYSIS != 0 + debugging_opts.no_analysis }; - if debugging_opts & DEBUG_LLVM != 0 { + if debugging_opts.debug_llvm { unsafe { llvm::LLVMSetDebug(1); } } let mut output_types = Vec::new(); - if !parse_only && !no_trans { + if !debugging_opts.parse_only && !no_trans { let unparsed_output_types = matches.opt_strs("emit"); for unparsed_output_type in unparsed_output_types.iter() { for part in unparsed_output_type.split(',') { @@ -917,8 +900,8 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { "link" => OutputTypeExe, "dep-info" => OutputTypeDepInfo, _ => { - early_error(format!("unknown emission type: `{}`", - part).index(&FullRange)) + early_error(&format!("unknown emission type: `{}`", + part)[]) } }; output_types.push(output_type) @@ -955,9 +938,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { Some("2") => Default, Some("3") => Aggressive, Some(arg) => { - early_error(format!("optimization level needs to be \ + early_error(&format!("optimization level needs to be \ between 0-3 (instead was `{}`)", - arg).index(&FullRange)); + arg)[]); } } } else { @@ -975,7 +958,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { } } }; - let gc = debugging_opts & GC != 0; + let gc = debugging_opts.gc; let debuginfo = if matches.opt_present("g") { if matches.opt_present("debuginfo") { early_error("-g and --debuginfo both provided"); @@ -993,9 +976,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { None | Some("2") => FullDebugInfo, Some(arg) => { - early_error(format!("debug info level needs to be between \ + early_error(&format!("debug info level needs to be between \ 0-2 (instead was `{}`)", - arg).index(&FullRange)); + arg)[]); } } } else { @@ -1013,7 +996,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let mut search_paths = SearchPaths::new(); for s in matches.opt_strs("L").iter() { - search_paths.add_path(s.index(&FullRange)); + search_paths.add_path(&s[]); } let libs = matches.opt_strs("l").into_iter().map(|s| { @@ -1043,9 +1026,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { (Some(name), "framework") => (name, cstore::NativeFramework), (Some(name), "static") => (name, cstore::NativeStatic), (_, s) => { - early_error(format!("unknown library kind `{}`, expected \ + early_error(&format!("unknown library kind `{}`, expected \ one of dylib, framework, or static", - s).index(&FullRange)); + s)[]); } }; (name.to_string(), kind) @@ -1089,7 +1072,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { --debuginfo"); } - let color = match matches.opt_str("color").as_ref().map(|s| s.index(&FullRange)) { + let color = match matches.opt_str("color").as_ref().map(|s| &s[]) { Some("auto") => Auto, Some("always") => Always, Some("never") => Never, @@ -1097,9 +1080,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { None => Auto, Some(arg) => { - early_error(format!("argument for --color must be auto, always \ + early_error(&format!("argument for --color must be auto, always \ or never (instead was `{}`)", - arg).index(&FullRange)) + arg)[]) } }; @@ -1149,6 +1132,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { crate_name: crate_name, alt_std_name: None, libs: libs, + unstable_features: UnstableFeatures::Disallow } } @@ -1201,7 +1185,7 @@ mod test { #[test] fn test_switch_implies_cfg_test() { let matches = - &match getopts(&["--test".to_string()], optgroups().index(&FullRange)) { + &match getopts(&["--test".to_string()], &optgroups()[]) { Ok(m) => m, Err(f) => panic!("test_switch_implies_cfg_test: {}", f) }; @@ -1209,7 +1193,7 @@ mod test { let sessopts = build_session_options(matches); let sess = build_session(sessopts, None, registry); let cfg = build_configuration(&sess); - assert!((attr::contains_name(cfg.index(&FullRange), "test"))); + assert!((attr::contains_name(&cfg[], "test"))); } // When the user supplies --test and --cfg test, don't implicitly add @@ -1218,7 +1202,7 @@ mod test { fn test_switch_implies_cfg_test_unless_cfg_test() { let matches = &match getopts(&["--test".to_string(), "--cfg=test".to_string()], - optgroups().index(&FullRange)) { + &optgroups()[]) { Ok(m) => m, Err(f) => { panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f) @@ -1238,7 +1222,7 @@ mod test { { let matches = getopts(&[ "-Awarnings".to_string() - ], optgroups().index(&FullRange)).unwrap(); + ], &optgroups()[]).unwrap(); let registry = diagnostics::registry::Registry::new(&[]); let sessopts = build_session_options(&matches); let sess = build_session(sessopts, None, registry); @@ -1249,7 +1233,7 @@ mod test { let matches = getopts(&[ "-Awarnings".to_string(), "-Dwarnings".to_string() - ], optgroups().index(&FullRange)).unwrap(); + ], &optgroups()[]).unwrap(); let registry = diagnostics::registry::Registry::new(&[]); let sessopts = build_session_options(&matches); let sess = build_session(sessopts, None, registry); @@ -1259,7 +1243,7 @@ mod test { { let matches = getopts(&[ "-Adead_code".to_string() - ], optgroups().index(&FullRange)).unwrap(); + ], &optgroups()[]).unwrap(); let registry = diagnostics::registry::Registry::new(&[]); let sessopts = build_session_options(&matches); let sess = build_session(sessopts, None, registry); diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 94a6bca4e06..79e4d0f7aea 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -164,9 +164,6 @@ impl Session { pub fn diagnostic<'a>(&'a self) -> &'a diagnostic::SpanHandler { &self.parse_sess.span_diagnostic } - pub fn debugging_opt(&self, opt: u64) -> bool { - (self.opts.debugging_opts & opt) != 0 - } pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap { &self.parse_sess.span_diagnostic.cm } @@ -174,38 +171,38 @@ impl Session { // cases later on pub fn impossible_case(&self, sp: Span, msg: &str) -> ! { self.span_bug(sp, - format!("impossible case reached: {}", msg).index(&FullRange)); + &format!("impossible case reached: {}", msg)[]); } - pub fn verbose(&self) -> bool { self.debugging_opt(config::VERBOSE) } - pub fn time_passes(&self) -> bool { self.debugging_opt(config::TIME_PASSES) } + pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose } + pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes } pub fn count_llvm_insns(&self) -> bool { - self.debugging_opt(config::COUNT_LLVM_INSNS) + self.opts.debugging_opts.count_llvm_insns } pub fn count_type_sizes(&self) -> bool { - self.debugging_opt(config::COUNT_TYPE_SIZES) + self.opts.debugging_opts.count_type_sizes } pub fn time_llvm_passes(&self) -> bool { - self.debugging_opt(config::TIME_LLVM_PASSES) + self.opts.debugging_opts.time_llvm_passes } - pub fn trans_stats(&self) -> bool { self.debugging_opt(config::TRANS_STATS) } - pub fn meta_stats(&self) -> bool { self.debugging_opt(config::META_STATS) } - pub fn asm_comments(&self) -> bool { self.debugging_opt(config::ASM_COMMENTS) } - pub fn no_verify(&self) -> bool { self.debugging_opt(config::NO_VERIFY) } - pub fn borrowck_stats(&self) -> bool { self.debugging_opt(config::BORROWCK_STATS) } + pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats } + pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats } + pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments } + pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify } + pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats } pub fn print_llvm_passes(&self) -> bool { - self.debugging_opt(config::PRINT_LLVM_PASSES) + self.opts.debugging_opts.print_llvm_passes } pub fn lto(&self) -> bool { self.opts.cg.lto } pub fn no_landing_pads(&self) -> bool { - self.debugging_opt(config::NO_LANDING_PADS) + self.opts.debugging_opts.no_landing_pads } pub fn unstable_options(&self) -> bool { - self.debugging_opt(config::UNSTABLE_OPTIONS) + self.opts.debugging_opts.unstable_options } pub fn print_enum_sizes(&self) -> bool { - self.debugging_opt(config::PRINT_ENUM_SIZES) + self.opts.debugging_opts.print_enum_sizes } pub fn sysroot<'a>(&'a self) -> &'a Path { match self.opts.maybe_sysroot { @@ -216,7 +213,7 @@ impl Session { } pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch { filesearch::FileSearch::new(self.sysroot(), - self.opts.target_triple.index(&FullRange), + &self.opts.target_triple[], &self.opts.search_paths, kind) } diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 26f98e28a8d..c505e9e3112 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -16,6 +16,7 @@ use std::fmt::Show; use std::hash::{Hash, Hasher}; use std::iter::repeat; use std::time::Duration; +use std::collections::hash_state::HashState; use syntax::ast; use syntax::visit; @@ -140,11 +141,11 @@ pub fn block_query<P>(b: &ast::Block, p: P) -> bool where P: FnMut(&ast::Expr) - /// Efficiency note: This is implemented in an inefficient way because it is typically invoked on /// very small graphs. If the graphs become larger, a more efficient graph representation and /// algorithm would probably be advised. -pub fn can_reach<S,H:Hasher<S>,T:Eq+Clone+Hash<S>>( - edges_map: &HashMap<T,Vec<T>,H>, - source: T, - destination: T) - -> bool +pub fn can_reach<T, S>(edges_map: &HashMap<T, Vec<T>, S>, source: T, + destination: T) -> bool + where S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64>, + T: Hash< <S as HashState>::Hasher> + Eq + Clone, { if source == destination { return true; @@ -202,11 +203,12 @@ pub fn can_reach<S,H:Hasher<S>,T:Eq+Clone+Hash<S>>( /// } /// ``` #[inline(always)] -pub fn memoized<T, U, S, H, F>(cache: &RefCell<HashMap<T, U, H>>, arg: T, f: F) -> U where - T: Clone + Hash<S> + Eq, - U: Clone, - H: Hasher<S>, - F: FnOnce(T) -> U, +pub fn memoized<T, U, S, F>(cache: &RefCell<HashMap<T, U, S>>, arg: T, f: F) -> U + where T: Clone + Hash<<S as HashState>::Hasher> + Eq, + U: Clone, + S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64>, + F: FnOnce(T) -> U, { let key = arg.clone(); let result = cache.borrow().get(&key).map(|result| result.clone()); diff --git a/src/librustc/util/lev_distance.rs b/src/librustc/util/lev_distance.rs index 8f5820d92c5..ec840498ae6 100644 --- a/src/librustc/util/lev_distance.rs +++ b/src/librustc/util/lev_distance.rs @@ -48,7 +48,7 @@ fn test_lev_distance() { for c in range(0u32, MAX as u32) .filter_map(|i| from_u32(i)) .map(|i| i.to_string()) { - assert_eq!(lev_distance(c.index(&FullRange), c.index(&FullRange)), 0); + assert_eq!(lev_distance(&c[], &c[]), 0); } let a = "\nMäry häd ä little lämb\n\nLittle lämb\n"; diff --git a/src/librustc/util/nodemap.rs b/src/librustc/util/nodemap.rs index ee224d1ec80..044534ae852 100644 --- a/src/librustc/util/nodemap.rs +++ b/src/librustc/util/nodemap.rs @@ -12,12 +12,14 @@ #![allow(non_snake_case)] +use std::collections::hash_state::{DefaultState}; use std::collections::{HashMap, HashSet}; -use std::hash::{Hasher, Hash, Writer}; +use std::default::Default; +use std::hash::{Hasher, Writer}; use syntax::ast; -pub type FnvHashMap<K, V> = HashMap<K, V, FnvHasher>; -pub type FnvHashSet<V> = HashSet<V, FnvHasher>; +pub type FnvHashMap<K, V> = HashMap<K, V, DefaultState<FnvHasher>>; +pub type FnvHashSet<V> = HashSet<V, DefaultState<FnvHasher>>; pub type NodeMap<T> = FnvHashMap<ast::NodeId, T>; pub type DefIdMap<T> = FnvHashMap<ast::DefId, T>; @@ -28,16 +30,16 @@ pub type DefIdSet = FnvHashSet<ast::DefId>; // Hacks to get good names pub mod FnvHashMap { use std::hash::Hash; - use std::collections::HashMap; - pub fn new<K: Hash<super::FnvState> + Eq, V>() -> super::FnvHashMap<K, V> { - HashMap::with_hasher(super::FnvHasher) + use std::default::Default; + pub fn new<K: Hash<super::FnvHasher> + Eq, V>() -> super::FnvHashMap<K, V> { + Default::default() } } pub mod FnvHashSet { use std::hash::Hash; - use std::collections::HashSet; - pub fn new<V: Hash<super::FnvState> + Eq>() -> super::FnvHashSet<V> { - HashSet::with_hasher(super::FnvHasher) + use std::default::Default; + pub fn new<V: Hash<super::FnvHasher> + Eq>() -> super::FnvHashSet<V> { + Default::default() } } pub mod NodeMap { @@ -68,28 +70,26 @@ pub mod DefIdSet { /// /// This uses FNV hashing, as described here: /// http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function -#[derive(Clone, Copy, Default)] -pub struct FnvHasher; - #[allow(missing_copy_implementations)] -pub struct FnvState(u64); +pub struct FnvHasher(u64); -impl Hasher<FnvState> for FnvHasher { - fn hash<T: ?Sized + Hash<FnvState>>(&self, t: &T) -> u64 { - let mut state = FnvState(0xcbf29ce484222325); - t.hash(&mut state); - let FnvState(ret) = state; - return ret; - } +impl Default for FnvHasher { + fn default() -> FnvHasher { FnvHasher(0xcbf29ce484222325) } +} + +impl Hasher for FnvHasher { + type Output = u64; + fn reset(&mut self) { *self = Default::default(); } + fn finish(&self) -> u64 { self.0 } } -impl Writer for FnvState { +impl Writer for FnvHasher { fn write(&mut self, bytes: &[u8]) { - let FnvState(mut hash) = *self; + let FnvHasher(mut hash) = *self; for byte in bytes.iter() { hash = hash ^ (*byte as u64); hash = hash * 0x100000001b3; } - *self = FnvState(hash); + *self = FnvHasher(hash); } } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 2d433369366..559ec533baa 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -26,6 +26,7 @@ use middle::ty; use middle::ty_fold::TypeFoldable; use std::collections::HashMap; +use std::collections::hash_state::HashState; use std::hash::{Hash, Hasher}; use std::rc::Rc; use syntax::abi; @@ -55,12 +56,12 @@ pub fn note_and_explain_region(cx: &ctxt, (ref str, Some(span)) => { cx.sess.span_note( span, - format!("{}{}{}", prefix, *str, suffix).index(&FullRange)); + &format!("{}{}{}", prefix, *str, suffix)[]); Some(span) } (ref str, None) => { cx.sess.note( - format!("{}{}{}", prefix, *str, suffix).index(&FullRange)); + &format!("{}{}{}", prefix, *str, suffix)[]); None } } @@ -271,7 +272,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { }; if abi != abi::Rust { - s.push_str(format!("extern {} ", abi.to_string()).index(&FullRange)); + s.push_str(&format!("extern {} ", abi.to_string())[]); }; s.push_str("fn"); @@ -290,7 +291,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { Some(def_id) => { s.push_str(" {"); let path_str = ty::item_path_str(cx, def_id); - s.push_str(path_str.index(&FullRange)); + s.push_str(&path_str[]); s.push_str("}"); } None => { } @@ -305,7 +306,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { match cty.store { ty::UniqTraitStore => {} ty::RegionTraitStore(region, _) => { - s.push_str(region_to_string(cx, "", true, region).index(&FullRange)); + s.push_str(®ion_to_string(cx, "", true, region)[]); } } @@ -324,7 +325,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { assert_eq!(cty.onceness, ast::Once); s.push_str("proc"); push_sig_to_string(cx, &mut s, '(', ')', &cty.sig, - bounds_str.index(&FullRange)); + &bounds_str[]); } ty::RegionTraitStore(..) => { match cty.onceness { @@ -332,7 +333,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { ast::Once => s.push_str("once ") } push_sig_to_string(cx, &mut s, '|', '|', &cty.sig, - bounds_str.index(&FullRange)); + &bounds_str[]); } } @@ -365,7 +366,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { ty::FnConverging(t) => { if !ty::type_is_nil(t) { s.push_str(" -> "); - s.push_str(ty_to_string(cx, t).index(&FullRange)); + s.push_str(&ty_to_string(cx, t)[]); } } ty::FnDiverging => { @@ -402,7 +403,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { } ty_rptr(r, ref tm) => { let mut buf = region_ptr_to_string(cx, *r); - buf.push_str(mt_to_string(cx, tm).index(&FullRange)); + buf.push_str(&mt_to_string(cx, tm)[]); buf } ty_open(typ) => @@ -412,7 +413,7 @@ pub fn ty_to_string<'tcx>(cx: &ctxt<'tcx>, typ: &ty::TyS<'tcx>) -> String { .iter() .map(|elem| ty_to_string(cx, *elem)) .collect::<Vec<_>>(); - match strs.index(&FullRange) { + match &strs[] { [ref string] => format!("({},)", string), strs => format!("({})", strs.connect(", ")) } @@ -541,7 +542,7 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, 0 }; - for t in tps.index(&(0..(tps.len() - num_defaults))).iter() { + for t in tps[0..(tps.len() - num_defaults)].iter() { strs.push(ty_to_string(cx, *t)) } @@ -549,11 +550,11 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, format!("{}({}){}", base, if strs[0].starts_with("(") && strs[0].ends_with(",)") { - strs[0].index(&(1 .. (strs[0].len() - 2))) // Remove '(' and ',)' + &strs[0][1 .. (strs[0].len() - 2)] // Remove '(' and ',)' } else if strs[0].starts_with("(") && strs[0].ends_with(")") { - strs[0].index(&(1 .. (strs[0].len() - 1))) // Remove '(' and ')' + &strs[0][1 .. (strs[0].len() - 1)] // Remove '(' and ')' } else { - strs[0].index(&FullRange) + &strs[0][] }, if &*strs[1] == "()" { String::new() } else { format!(" -> {}", strs[1]) }) } else if strs.len() > 0 { @@ -566,7 +567,7 @@ pub fn parameterized<'tcx>(cx: &ctxt<'tcx>, pub fn ty_to_short_str<'tcx>(cx: &ctxt<'tcx>, typ: Ty<'tcx>) -> String { let mut s = typ.repr(cx).to_string(); if s.len() >= 32u { - s = s.index(&(0u..32u)).to_string(); + s = (&s[0u..32u]).to_string(); } return s; } @@ -631,7 +632,7 @@ impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for [T] { impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - repr_vec(tcx, self.index(&FullRange)) + repr_vec(tcx, &self[]) } } @@ -639,7 +640,7 @@ impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for OwnedSlice<T> { // autoderef cannot convert the &[T] handler impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for Vec<T> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - repr_vec(tcx, self.index(&FullRange)) + repr_vec(tcx, &self[]) } } @@ -1182,8 +1183,8 @@ impl<'tcx, T> UserString<'tcx> for ty::Binder<T> // the output. We'll probably want to tweak this over time to // decide just how much information to give. let mut names = Vec::new(); - let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br, debruijn| { - ty::ReLateBound(debruijn, match br { + let (unbound_value, _) = ty::replace_late_bound_regions(tcx, self, |br| { + ty::ReLateBound(ty::DebruijnIndex::new(1), match br { ty::BrNamed(_, name) => { names.push(token::get_name(name)); br @@ -1350,11 +1351,11 @@ impl<'tcx, T:Repr<'tcx>> Repr<'tcx> for ty::Binder<T> { } } -#[old_impl_check] -impl<'tcx, S, H, K, V> Repr<'tcx> for HashMap<K,V,H> - where K : Hash<S> + Eq + Repr<'tcx>, - V : Repr<'tcx>, - H : Hasher<S> +impl<'tcx, S, K, V> Repr<'tcx> for HashMap<K, V, S> + where K: Hash<<S as HashState>::Hasher> + Eq + Repr<'tcx>, + V: Repr<'tcx>, + S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64>, { fn repr(&self, tcx: &ctxt<'tcx>) -> String { format!("HashMap({})", diff --git a/src/librustc/util/snapshot_vec.rs b/src/librustc/util/snapshot_vec.rs index d68b13aa2ff..8fc95529bc0 100644 --- a/src/librustc/util/snapshot_vec.rs +++ b/src/librustc/util/snapshot_vec.rs @@ -116,7 +116,7 @@ impl<T,U,D:SnapshotVecDelegate<T,U>> SnapshotVec<T,U,D> { pub fn actions_since_snapshot(&self, snapshot: &Snapshot) -> &[UndoLog<T,U>] { - self.undo_log.index(&(snapshot.length..)) + &self.undo_log[snapshot.length..] } fn assert_open_snapshot(&self, snapshot: &Snapshot) { diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index 48004acaac0..7ea192b8d6b 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -53,7 +53,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>, args: &str, cwd: Option<&Path>, paths: &[&Path]) -> ProcessOutput { let ar = match *maybe_ar_prog { - Some(ref ar) => ar.index(&FullRange), + Some(ref ar) => &ar[], None => "ar" }; let mut cmd = Command::new(ar); @@ -73,24 +73,21 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option<String>, Ok(prog) => { let o = prog.wait_with_output().unwrap(); if !o.status.success() { - handler.err(format!("{} failed with: {}", + handler.err(&format!("{} failed with: {}", cmd, - o.status).index(&FullRange)); - handler.note(format!("stdout ---\n{}", - str::from_utf8(o.output - .index(&FullRange)).unwrap()) - .index(&FullRange)); - handler.note(format!("stderr ---\n{}", - str::from_utf8(o.error - .index(&FullRange)).unwrap()) - .index(&FullRange)); + o.status)[]); + handler.note(&format!("stdout ---\n{}", + str::from_utf8(&o.output[]).unwrap())[]); + handler.note(&format!("stderr ---\n{}", + str::from_utf8(&o.error[]).unwrap()) + []); handler.abort_if_errors(); } o }, Err(e) => { - handler.err(format!("could not exec `{}`: {}", ar.index(&FullRange), - e).index(&FullRange)); + handler.err(&format!("could not exec `{}`: {}", &ar[], + e)[]); handler.abort_if_errors(); panic!("rustc::back::archive::run_ar() should not reach this point"); } @@ -106,16 +103,16 @@ pub fn find_library(name: &str, osprefix: &str, ossuffix: &str, for path in search_paths.iter() { debug!("looking for {} inside {:?}", name, path.display()); - let test = path.join(oslibname.index(&FullRange)); + let test = path.join(&oslibname[]); if test.exists() { return test } if oslibname != unixlibname { - let test = path.join(unixlibname.index(&FullRange)); + let test = path.join(&unixlibname[]); if test.exists() { return test } } } - handler.fatal(format!("could not find native static library `{}`, \ + handler.fatal(&format!("could not find native static library `{}`, \ perhaps an -L flag is missing?", - name).index(&FullRange)); + name)[]); } impl<'a> Archive<'a> { @@ -147,7 +144,7 @@ impl<'a> Archive<'a> { /// Lists all files in an archive pub fn files(&self) -> Vec<String> { let output = run_ar(self.handler, &self.maybe_ar_prog, "t", None, &[&self.dst]); - let output = str::from_utf8(output.output.index(&FullRange)).unwrap(); + let output = str::from_utf8(&output.output[]).unwrap(); // use lines_any because windows delimits output with `\r\n` instead of // just `\n` output.lines_any().map(|s| s.to_string()).collect() @@ -179,9 +176,9 @@ impl<'a> ArchiveBuilder<'a> { /// search in the relevant locations for a library named `name`. pub fn add_native_library(&mut self, name: &str) -> io::IoResult<()> { let location = find_library(name, - self.archive.slib_prefix.index(&FullRange), - self.archive.slib_suffix.index(&FullRange), - self.archive.lib_search_paths.index(&FullRange), + &self.archive.slib_prefix[], + &self.archive.slib_suffix[], + &self.archive.lib_search_paths[], self.archive.handler); self.add_archive(&location, name, |_| false) } @@ -197,12 +194,12 @@ impl<'a> ArchiveBuilder<'a> { // as simple comparison is not enough - there // might be also an extra name suffix let obj_start = format!("{}", name); - let obj_start = obj_start.index(&FullRange); + let obj_start = &obj_start[]; // Ignoring all bytecode files, no matter of // name let bc_ext = ".bytecode.deflate"; - self.add_archive(rlib, name.index(&FullRange), |fname: &str| { + self.add_archive(rlib, &name[], |fname: &str| { let skip_obj = lto && fname.starts_with(obj_start) && fname.ends_with(".o"); skip_obj || fname.ends_with(bc_ext) || fname == METADATA_FILENAME @@ -239,7 +236,7 @@ impl<'a> ArchiveBuilder<'a> { // allow running `ar s file.a` to update symbols only. if self.should_update_symbols { run_ar(self.archive.handler, &self.archive.maybe_ar_prog, - "s", Some(self.work_dir.path()), args.index(&FullRange)); + "s", Some(self.work_dir.path()), &args[]); } return self.archive; } @@ -259,7 +256,7 @@ impl<'a> ArchiveBuilder<'a> { // Add the archive members seen so far, without updating the // symbol table (`S`). run_ar(self.archive.handler, &self.archive.maybe_ar_prog, - "cruS", Some(self.work_dir.path()), args.index(&FullRange)); + "cruS", Some(self.work_dir.path()), &args[]); args.clear(); args.push(&abs_dst); @@ -274,7 +271,7 @@ impl<'a> ArchiveBuilder<'a> { // necessary. let flags = if self.should_update_symbols { "crus" } else { "cruS" }; run_ar(self.archive.handler, &self.archive.maybe_ar_prog, - flags, Some(self.work_dir.path()), args.index(&FullRange)); + flags, Some(self.work_dir.path()), &args[]); self.archive } @@ -316,7 +313,7 @@ impl<'a> ArchiveBuilder<'a> { } else { filename }; - let new_filename = self.work_dir.path().join(filename.index(&FullRange)); + let new_filename = self.work_dir.path().join(&filename[]); try!(fs::rename(file, &new_filename)); self.members.push(Path::new(filename)); } diff --git a/src/librustc_back/lib.rs b/src/librustc_back/lib.rs index ca39477fbdc..d29a47b65b0 100644 --- a/src/librustc_back/lib.rs +++ b/src/librustc_back/lib.rs @@ -22,13 +22,16 @@ //! build speedups. #![crate_name = "rustc_back"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(slicing_syntax)] +#![allow(unknown_features)] +#![feature(slicing_syntax, box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate syntax; extern crate serialize; diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index db1dfa6b6ee..d24fd6a5b3f 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -44,15 +44,15 @@ pub fn get_rpath_flags<F, G>(config: RPathConfig<F, G>) -> Vec<String> where l.map(|p| p.clone()) }).collect::<Vec<_>>(); - let rpaths = get_rpaths(config, libs.index(&FullRange)); - flags.push_all(rpaths_to_flags(rpaths.index(&FullRange)).index(&FullRange)); + let rpaths = get_rpaths(config, &libs[]); + flags.push_all(&rpaths_to_flags(&rpaths[])[]); flags } fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> { let mut ret = Vec::new(); for rpath in rpaths.iter() { - ret.push(format!("-Wl,-rpath,{}", (*rpath).index(&FullRange))); + ret.push(format!("-Wl,-rpath,{}", &(*rpath)[])); } return ret; } @@ -82,14 +82,14 @@ fn get_rpaths<F, G>(mut config: RPathConfig<F, G>, libs: &[Path]) -> Vec<String> } } - log_rpaths("relative", rel_rpaths.index(&FullRange)); - log_rpaths("fallback", fallback_rpaths.index(&FullRange)); + log_rpaths("relative", &rel_rpaths[]); + log_rpaths("fallback", &fallback_rpaths[]); let mut rpaths = rel_rpaths; - rpaths.push_all(fallback_rpaths.index(&FullRange)); + rpaths.push_all(&fallback_rpaths[]); // Remove duplicates - let rpaths = minimize_rpaths(rpaths.index(&FullRange)); + let rpaths = minimize_rpaths(&rpaths[]); return rpaths; } @@ -140,7 +140,7 @@ fn minimize_rpaths(rpaths: &[String]) -> Vec<String> { let mut set = HashSet::new(); let mut minimized = Vec::new(); for rpath in rpaths.iter() { - if set.insert(rpath.index(&FullRange)) { + if set.insert(&rpath[]) { minimized.push(rpath.clone()); } } diff --git a/src/librustc_back/sha2.rs b/src/librustc_back/sha2.rs index f33971a6ac0..ac5662f534c 100644 --- a/src/librustc_back/sha2.rs +++ b/src/librustc_back/sha2.rs @@ -140,7 +140,7 @@ impl FixedBuffer for FixedBuffer64 { if input.len() >= buffer_remaining { copy_memory( self.buffer.slice_mut(self.buffer_idx, size), - input.index(&(0..buffer_remaining))); + &input[0..buffer_remaining]); self.buffer_idx = 0; func(&self.buffer); i += buffer_remaining; @@ -156,7 +156,7 @@ impl FixedBuffer for FixedBuffer64 { // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { - func(input.index(&(i..(i + size)))); + func(&input[i..(i + size)]); i += size; } @@ -166,7 +166,7 @@ impl FixedBuffer for FixedBuffer64 { let input_remaining = input.len() - i; copy_memory( self.buffer.slice_to_mut(input_remaining), - input.index(&(i..))); + &input[i..]); self.buffer_idx += input_remaining; } @@ -188,7 +188,7 @@ impl FixedBuffer for FixedBuffer64 { fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; - return self.buffer.index(&(0..64)); + return &self.buffer[0..64]; } fn position(&self) -> uint { self.buffer_idx } diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index 863c1a7c865..4e260da2e4d 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -47,8 +47,7 @@ //! Original issue: https://github.com/rust-lang/rust/issues/10207 use std::fmt; -use std::hash::Hash; -use std::hash::sip::SipState; +use std::hash::{Hash, SipHasher, Hasher}; use std::iter::range_step; use syntax::ast; use syntax::visit; @@ -65,7 +64,7 @@ impl Svh { } pub fn as_str<'a>(&'a self) -> &'a str { - self.hash.index(&FullRange) + &self.hash[] } pub fn calculate(metadata: &Vec<String>, krate: &ast::Crate) -> Svh { @@ -78,7 +77,7 @@ impl Svh { // FIXME: this should use SHA1, not SipHash. SipHash is not built to // avoid collisions. - let mut state = SipState::new(); + let mut state = SipHasher::new(); for data in metadata.iter() { data.hash(&mut state); @@ -102,7 +101,7 @@ impl Svh { attr.node.value.hash(&mut state); } - let hash = state.result(); + let hash = state.finish(); return Svh { hash: range_step(0u, 64u, 4u).map(|i| hex(hash >> i)).collect() }; @@ -120,9 +119,7 @@ impl Svh { impl fmt::Show for Svh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - //NOTE(stage0): uncomment after snapshot - //write!(f, "Svh {{ {} }}", self.as_str()) - fmt::String::fmt(self, f) + write!(f, "Svh {{ {} }}", self.as_str()) } } @@ -149,14 +146,13 @@ mod svh_visitor { use syntax::visit; use syntax::visit::{Visitor, FnKind}; - use std::hash::Hash; - use std::hash::sip::SipState; + use std::hash::{Hash, SipHasher}; pub struct StrictVersionHashVisitor<'a> { - pub st: &'a mut SipState, + pub st: &'a mut SipHasher, } - pub fn make<'a>(st: &'a mut SipState) -> StrictVersionHashVisitor<'a> { + pub fn make<'a>(st: &'a mut SipHasher) -> StrictVersionHashVisitor<'a> { StrictVersionHashVisitor { st: st } } @@ -366,7 +362,7 @@ mod svh_visitor { fn macro_name(mac: &Mac) -> token::InternedString { match &mac.node { &MacInvocTT(ref path, ref _tts, ref _stx_ctxt) => { - let s = path.segments.index(&FullRange); + let s = &path.segments[]; assert_eq!(s.len(), 1); content(s[0].identifier) } @@ -400,7 +396,7 @@ mod svh_visitor { } // All of the remaining methods just record (in the hash - // SipState) that the visitor saw that particular variant + // SipHasher) that the visitor saw that particular variant // (with its payload), and continue walking as the default // visitor would. // diff --git a/src/librustc_back/target/aarch64_unknown_linux_gnu.rs b/src/librustc_back/target/aarch64_unknown_linux_gnu.rs index 296552a6abd..a3ef6372f06 100644 --- a/src/librustc_back/target/aarch64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/aarch64_unknown_linux_gnu.rs @@ -18,7 +18,7 @@ pub fn target() -> Target { n32:64-S128".to_string(), llvm_target: "aarch64-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "aarch64".to_string(), target_os: "linux".to_string(), options: base, diff --git a/src/librustc_back/target/arm_apple_ios.rs b/src/librustc_back/target/arm_apple_ios.rs index 8bb64eae625..e0afef6e390 100644 --- a/src/librustc_back/target/arm_apple_ios.rs +++ b/src/librustc_back/target/arm_apple_ios.rs @@ -19,7 +19,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "arm-apple-ios".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "arm".to_string(), target_os: "ios".to_string(), options: TargetOptions { diff --git a/src/librustc_back/target/arm_linux_androideabi.rs b/src/librustc_back/target/arm_linux_androideabi.rs index ecfb1667f60..6fc77a715a5 100644 --- a/src/librustc_back/target/arm_linux_androideabi.rs +++ b/src/librustc_back/target/arm_linux_androideabi.rs @@ -27,7 +27,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "arm-linux-androideabi".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "arm".to_string(), target_os: "android".to_string(), options: base, diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs index 985af35e145..32eccaf54b0 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabi.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabi.rs @@ -20,7 +20,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "arm-unknown-linux-gnueabi".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "arm".to_string(), target_os: "linux".to_string(), diff --git a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs index 3cf0c312820..eff3601250f 100644 --- a/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs +++ b/src/librustc_back/target/arm_unknown_linux_gnueabihf.rs @@ -20,7 +20,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "arm-unknown-linux-gnueabihf".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "arm".to_string(), target_os: "linux".to_string(), diff --git a/src/librustc_back/target/i386_apple_ios.rs b/src/librustc_back/target/i386_apple_ios.rs index 45669bc9585..a1fcc9ac53f 100644 --- a/src/librustc_back/target/i386_apple_ios.rs +++ b/src/librustc_back/target/i386_apple_ios.rs @@ -19,7 +19,7 @@ pub fn target() -> Target { -n8:16:32".to_string(), llvm_target: "i386-apple-ios".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "ios".to_string(), diff --git a/src/librustc_back/target/i686_apple_darwin.rs b/src/librustc_back/target/i686_apple_darwin.rs index feef5b98dcb..1b079323bf9 100644 --- a/src/librustc_back/target/i686_apple_darwin.rs +++ b/src/librustc_back/target/i686_apple_darwin.rs @@ -22,7 +22,7 @@ pub fn target() -> Target { -n8:16:32".to_string(), llvm_target: "i686-apple-darwin".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "macos".to_string(), options: base, diff --git a/src/librustc_back/target/i686_pc_windows_gnu.rs b/src/librustc_back/target/i686_pc_windows_gnu.rs index 4d75590e664..c2ab68ee052 100644 --- a/src/librustc_back/target/i686_pc_windows_gnu.rs +++ b/src/librustc_back/target/i686_pc_windows_gnu.rs @@ -26,7 +26,7 @@ pub fn target() -> Target { data_layout: "e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-pc-windows-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "windows".to_string(), options: options, diff --git a/src/librustc_back/target/i686_unknown_dragonfly.rs b/src/librustc_back/target/i686_unknown_dragonfly.rs index a12657ff4dc..7910eba7ea1 100644 --- a/src/librustc_back/target/i686_unknown_dragonfly.rs +++ b/src/librustc_back/target/i686_unknown_dragonfly.rs @@ -18,7 +18,7 @@ pub fn target() -> Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-dragonfly".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "dragonfly".to_string(), options: base, diff --git a/src/librustc_back/target/i686_unknown_linux_gnu.rs b/src/librustc_back/target/i686_unknown_linux_gnu.rs index 1a4560d5cd5..c93a564fef5 100644 --- a/src/librustc_back/target/i686_unknown_linux_gnu.rs +++ b/src/librustc_back/target/i686_unknown_linux_gnu.rs @@ -18,7 +18,7 @@ pub fn target() -> Target { data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(), llvm_target: "i686-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "x86".to_string(), target_os: "linux".to_string(), options: base, diff --git a/src/librustc_back/target/mips_unknown_linux_gnu.rs b/src/librustc_back/target/mips_unknown_linux_gnu.rs index c8c5ddcbd0d..8acc248e234 100644 --- a/src/librustc_back/target/mips_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mips_unknown_linux_gnu.rs @@ -19,7 +19,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "mips-unknown-linux-gnu".to_string(), target_endian: "big".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "mips".to_string(), target_os: "linux".to_string(), options: super::linux_base::opts() diff --git a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs index 3571f7b26c0..604c62eb69f 100644 --- a/src/librustc_back/target/mipsel_unknown_linux_gnu.rs +++ b/src/librustc_back/target/mipsel_unknown_linux_gnu.rs @@ -19,7 +19,7 @@ pub fn target() -> Target { -a:0:64-n32".to_string(), llvm_target: "mipsel-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "32".to_string(), + target_pointer_width: "32".to_string(), arch: "mips".to_string(), target_os: "linux".to_string(), diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 23c8fc7de51..069e798887b 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -85,8 +85,8 @@ pub struct Target { pub llvm_target: String, /// String to use as the `target_endian` `cfg` variable. pub target_endian: String, - /// String to use as the `target_word_size` `cfg` variable. - pub target_word_size: String, + /// String to use as the `target_pointer_width` `cfg` variable. + pub target_pointer_width: String, /// OS name to use for conditional compilation. pub target_os: String, /// Architecture to use for ABI considerations. Valid options: "x86", "x86_64", "arm", @@ -224,8 +224,7 @@ impl Target { .and_then(|os| os.map(|s| s.to_string())) { Some(val) => val, None => - handler.fatal((format!("Field {} in target specification is required", name)) - .index(&FullRange)) + handler.fatal(&format!("Field {} in target specification is required", name)[]) } }; @@ -233,7 +232,7 @@ impl Target { data_layout: get_req_field("data-layout"), llvm_target: get_req_field("llvm-target"), target_endian: get_req_field("target-endian"), - target_word_size: get_req_field("target-word-size"), + target_pointer_width: get_req_field("target-word-size"), arch: get_req_field("arch"), target_os: get_req_field("os"), options: Default::default(), @@ -242,18 +241,18 @@ impl Target { macro_rules! key { ($key_name:ident) => ( { let name = (stringify!($key_name)).replace("_", "-"); - obj.find(name.index(&FullRange)).map(|o| o.as_string() + obj.find(&name[]).map(|o| o.as_string() .map(|s| base.options.$key_name = s.to_string())); } ); ($key_name:ident, bool) => ( { let name = (stringify!($key_name)).replace("_", "-"); - obj.find(name.index(&FullRange)) + obj.find(&name[]) .map(|o| o.as_boolean() .map(|s| base.options.$key_name = s)); } ); ($key_name:ident, list) => ( { let name = (stringify!($key_name)).replace("_", "-"); - obj.find(name.index(&FullRange)).map(|o| o.as_array() + obj.find(&name[]).map(|o| o.as_array() .map(|v| base.options.$key_name = v.iter() .map(|a| a.as_string().unwrap().to_string()).collect() ) @@ -369,7 +368,7 @@ impl Target { let target_path = os::getenv("RUST_TARGET_PATH").unwrap_or(String::new()); - let paths = os::split_paths(target_path.index(&FullRange)); + let paths = os::split_paths(&target_path[]); // FIXME 16351: add a sane default search path? for dir in paths.iter() { diff --git a/src/librustc_back/target/x86_64_apple_darwin.rs b/src/librustc_back/target/x86_64_apple_darwin.rs index 07e6cdfed2c..0ebd3bd3215 100644 --- a/src/librustc_back/target/x86_64_apple_darwin.rs +++ b/src/librustc_back/target/x86_64_apple_darwin.rs @@ -21,7 +21,7 @@ pub fn target() -> Target { s0:64:64-f80:128:128-n8:16:32:64".to_string(), llvm_target: "x86_64-apple-darwin".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "macos".to_string(), options: base, diff --git a/src/librustc_back/target/x86_64_pc_windows_gnu.rs b/src/librustc_back/target/x86_64_pc_windows_gnu.rs index 6ca74eb7fc0..9e1294a8962 100644 --- a/src/librustc_back/target/x86_64_pc_windows_gnu.rs +++ b/src/librustc_back/target/x86_64_pc_windows_gnu.rs @@ -23,7 +23,7 @@ pub fn target() -> Target { s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-pc-windows-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "windows".to_string(), options: base, diff --git a/src/librustc_back/target/x86_64_unknown_dragonfly.rs b/src/librustc_back/target/x86_64_unknown_dragonfly.rs index bff3eaf6bc8..6635306b0e1 100644 --- a/src/librustc_back/target/x86_64_unknown_dragonfly.rs +++ b/src/librustc_back/target/x86_64_unknown_dragonfly.rs @@ -20,7 +20,7 @@ pub fn target() -> Target { s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-dragonfly".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "dragonfly".to_string(), options: base, diff --git a/src/librustc_back/target/x86_64_unknown_freebsd.rs b/src/librustc_back/target/x86_64_unknown_freebsd.rs index 8d5603a3878..2aba2b8defb 100644 --- a/src/librustc_back/target/x86_64_unknown_freebsd.rs +++ b/src/librustc_back/target/x86_64_unknown_freebsd.rs @@ -20,7 +20,7 @@ pub fn target() -> Target { s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-freebsd".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "freebsd".to_string(), options: base, diff --git a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs index e0a67cd6250..d7a6df3a8b0 100644 --- a/src/librustc_back/target/x86_64_unknown_linux_gnu.rs +++ b/src/librustc_back/target/x86_64_unknown_linux_gnu.rs @@ -20,7 +20,7 @@ pub fn target() -> Target { s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(), llvm_target: "x86_64-unknown-linux-gnu".to_string(), target_endian: "little".to_string(), - target_word_size: "64".to_string(), + target_pointer_width: "64".to_string(), arch: "x86_64".to_string(), target_os: "linux".to_string(), options: base, diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index d942581ca62..d5ad201eabf 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -463,38 +463,38 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { (ty::MutBorrow, ty::MutBorrow) => { self.bccx.span_err( new_loan.span, - format!("cannot borrow `{}`{} as mutable \ + &format!("cannot borrow `{}`{} as mutable \ more than once at a time", - nl, new_loan_msg).index(&FullRange)) + nl, new_loan_msg)[]) } (ty::UniqueImmBorrow, _) => { self.bccx.span_err( new_loan.span, - format!("closure requires unique access to `{}` \ + &format!("closure requires unique access to `{}` \ but {} is already borrowed{}", - nl, ol_pronoun, old_loan_msg).index(&FullRange)); + nl, ol_pronoun, old_loan_msg)[]); } (_, ty::UniqueImmBorrow) => { self.bccx.span_err( new_loan.span, - format!("cannot borrow `{}`{} as {} because \ + &format!("cannot borrow `{}`{} as {} because \ previous closure requires unique access", - nl, new_loan_msg, new_loan.kind.to_user_str()).index(&FullRange)); + nl, new_loan_msg, new_loan.kind.to_user_str())[]); } (_, _) => { self.bccx.span_err( new_loan.span, - format!("cannot borrow `{}`{} as {} because \ + &format!("cannot borrow `{}`{} as {} because \ {} is also borrowed as {}{}", nl, new_loan_msg, new_loan.kind.to_user_str(), ol_pronoun, old_loan.kind.to_user_str(), - old_loan_msg).index(&FullRange)); + old_loan_msg)[]); } } @@ -502,8 +502,8 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { euv::ClosureCapture(span) => { self.bccx.span_note( span, - format!("borrow occurs due to use of `{}` in closure", - nl).index(&FullRange)); + &format!("borrow occurs due to use of `{}` in closure", + nl)[]); } _ => { } } @@ -552,7 +552,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { self.bccx.span_note( old_loan.span, - format!("{}; {}", borrow_summary, rule_summary).index(&FullRange)); + &format!("{}; {}", borrow_summary, rule_summary)[]); let old_loan_span = self.tcx().map.span(old_loan.kill_scope.node_id()); self.bccx.span_end_note(old_loan_span, @@ -621,14 +621,14 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { UseWhileBorrowed(loan_path, loan_span) => { self.bccx.span_err( span, - format!("cannot use `{}` because it was mutably borrowed", - self.bccx.loan_path_to_string(copy_path).index(&FullRange)) - .index(&FullRange)); + &format!("cannot use `{}` because it was mutably borrowed", + &self.bccx.loan_path_to_string(copy_path)[]) + []); self.bccx.span_note( loan_span, - format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_string(&*loan_path).index(&FullRange)) - .index(&FullRange)); + &format!("borrow of `{}` occurs here", + &self.bccx.loan_path_to_string(&*loan_path)[]) + []); } } } @@ -647,20 +647,20 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { let err_message = match move_kind { move_data::Captured => format!("cannot move `{}` into closure because it is borrowed", - self.bccx.loan_path_to_string(move_path).index(&FullRange)), + &self.bccx.loan_path_to_string(move_path)[]), move_data::Declared | move_data::MoveExpr | move_data::MovePat => format!("cannot move out of `{}` because it is borrowed", - self.bccx.loan_path_to_string(move_path).index(&FullRange)) + &self.bccx.loan_path_to_string(move_path)[]) }; - self.bccx.span_err(span, err_message.index(&FullRange)); + self.bccx.span_err(span, &err_message[]); self.bccx.span_note( loan_span, - format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_string(&*loan_path).index(&FullRange)) - .index(&FullRange)); + &format!("borrow of `{}` occurs here", + &self.bccx.loan_path_to_string(&*loan_path)[]) + []); } } } @@ -809,34 +809,34 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { if kind == ty::FnUnboxedClosureKind { self.bccx.span_err( assignment_span, - format!("cannot assign to {}", - self.bccx.cmt_to_string(&*assignee_cmt)).index(&FullRange)); + &format!("cannot assign to {}", + self.bccx.cmt_to_string(&*assignee_cmt))[]); self.bccx.span_help( self.tcx().map.span(upvar_id.closure_expr_id), "consider changing this closure to take self by mutable reference"); } else { self.bccx.span_err( assignment_span, - format!("cannot assign to {} {}", + &format!("cannot assign to {} {}", assignee_cmt.mutbl.to_user_str(), - self.bccx.cmt_to_string(&*assignee_cmt)).index(&FullRange)); + self.bccx.cmt_to_string(&*assignee_cmt))[]); } } _ => match opt_loan_path(&assignee_cmt) { Some(lp) => { self.bccx.span_err( assignment_span, - format!("cannot assign to {} {} `{}`", + &format!("cannot assign to {} {} `{}`", assignee_cmt.mutbl.to_user_str(), self.bccx.cmt_to_string(&*assignee_cmt), - self.bccx.loan_path_to_string(&*lp)).index(&FullRange)); + self.bccx.loan_path_to_string(&*lp))[]); } None => { self.bccx.span_err( assignment_span, - format!("cannot assign to {} {}", + &format!("cannot assign to {} {}", assignee_cmt.mutbl.to_user_str(), - self.bccx.cmt_to_string(&*assignee_cmt)).index(&FullRange)); + self.bccx.cmt_to_string(&*assignee_cmt))[]); } } } @@ -955,11 +955,11 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { loan: &Loan) { self.bccx.span_err( span, - format!("cannot assign to `{}` because it is borrowed", - self.bccx.loan_path_to_string(loan_path)).index(&FullRange)); + &format!("cannot assign to `{}` because it is borrowed", + self.bccx.loan_path_to_string(loan_path))[]); self.bccx.span_note( loan.span, - format!("borrow of `{}` occurs here", - self.bccx.loan_path_to_string(loan_path)).index(&FullRange)); + &format!("borrow of `{}` occurs here", + self.bccx.loan_path_to_string(loan_path))[]); } } diff --git a/src/librustc_borrowck/borrowck/fragments.rs b/src/librustc_borrowck/borrowck/fragments.rs index d7527487465..e2942719f2a 100644 --- a/src/librustc_borrowck/borrowck/fragments.rs +++ b/src/librustc_borrowck/borrowck/fragments.rs @@ -19,7 +19,6 @@ use borrowck::LoanPathKind::{LpVar, LpUpvar, LpDowncast, LpExtend}; use borrowck::LoanPathElem::{LpDeref, LpInterior}; use borrowck::move_data::{InvalidMovePathIndex}; use borrowck::move_data::{MoveData, MovePathIndex}; -use rustc::session::config; use rustc::middle::ty; use rustc::middle::mem_categorization as mc; use rustc::util::ppaux::{Repr, UserString}; @@ -38,7 +37,7 @@ enum Fragment { // This represents the collection of all but one of the elements // from an array at the path described by the move path index. // Note that attached MovePathIndex should have mem_categorization - // of InteriorElement (i.e. array dereference `.index(&FullRange)`). + // of InteriorElement (i.e. array dereference `&foo[]`). AllButOneFrom(MovePathIndex), } @@ -123,17 +122,17 @@ pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>, let attrs : &[ast::Attribute]; attrs = match tcx.map.find(id) { Some(ast_map::NodeItem(ref item)) => - item.attrs.index(&FullRange), + &item.attrs[], Some(ast_map::NodeImplItem(&ast::MethodImplItem(ref m))) => - m.attrs.index(&FullRange), + &m.attrs[], Some(ast_map::NodeTraitItem(&ast::ProvidedMethod(ref m))) => - m.attrs.index(&FullRange), - _ => [].index(&FullRange), + &m.attrs[], + _ => &[][], }; let span_err = attrs.iter().any(|a| a.check_name("rustc_move_fragments")); - let print = tcx.sess.debugging_opt(config::PRINT_MOVE_FRAGMENTS); + let print = tcx.sess.opts.debugging_opts.print_move_fragments; (span_err, print) }; @@ -144,7 +143,7 @@ pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>, for (i, mpi) in vec_rc.iter().enumerate() { let render = |&:| this.path_loan_path(*mpi).user_string(tcx); if span_err { - tcx.sess.span_err(sp, format!("{}: `{}`", kind, render()).index(&FullRange)); + tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]); } if print { println!("id:{} {}[{}] `{}`", id, kind, i, render()); @@ -156,7 +155,7 @@ pub fn instrument_move_fragments<'tcx>(this: &MoveData<'tcx>, for (i, f) in vec_rc.iter().enumerate() { let render = |&:| f.loan_path_user_string(this, tcx); if span_err { - tcx.sess.span_err(sp, format!("{}: `{}`", kind, render()).index(&FullRange)); + tcx.sess.span_err(sp, &format!("{}: `{}`", kind, render())[]); } if print { println!("id:{} {}[{}] `{}`", id, kind, i, render()); @@ -198,11 +197,11 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { // First, filter out duplicates moved.sort(); moved.dedup(); - debug!("fragments 1 moved: {:?}", path_lps(moved.index(&FullRange))); + debug!("fragments 1 moved: {:?}", path_lps(&moved[])); assigned.sort(); assigned.dedup(); - debug!("fragments 1 assigned: {:?}", path_lps(assigned.index(&FullRange))); + debug!("fragments 1 assigned: {:?}", path_lps(&assigned[])); // Second, build parents from the moved and assigned. for m in moved.iter() { @@ -222,14 +221,14 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { parents.sort(); parents.dedup(); - debug!("fragments 2 parents: {:?}", path_lps(parents.index(&FullRange))); + debug!("fragments 2 parents: {:?}", path_lps(&parents[])); // Third, filter the moved and assigned fragments down to just the non-parents - moved.retain(|f| non_member(*f, parents.index(&FullRange))); - debug!("fragments 3 moved: {:?}", path_lps(moved.index(&FullRange))); + moved.retain(|f| non_member(*f, &parents[])); + debug!("fragments 3 moved: {:?}", path_lps(&moved[])); - assigned.retain(|f| non_member(*f, parents.index(&FullRange))); - debug!("fragments 3 assigned: {:?}", path_lps(assigned.index(&FullRange))); + assigned.retain(|f| non_member(*f, &parents[])); + debug!("fragments 3 assigned: {:?}", path_lps(&assigned[])); // Fourth, build the leftover from the moved, assigned, and parents. for m in moved.iter() { @@ -247,16 +246,16 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { unmoved.sort(); unmoved.dedup(); - debug!("fragments 4 unmoved: {:?}", frag_lps(unmoved.index(&FullRange))); + debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[])); // Fifth, filter the leftover fragments down to its core. unmoved.retain(|f| match *f { AllButOneFrom(_) => true, - Just(mpi) => non_member(mpi, parents.index(&FullRange)) && - non_member(mpi, moved.index(&FullRange)) && - non_member(mpi, assigned.index(&FullRange)) + Just(mpi) => non_member(mpi, &parents[]) && + non_member(mpi, &moved[]) && + non_member(mpi, &assigned[]) }); - debug!("fragments 5 unmoved: {:?}", frag_lps(unmoved.index(&FullRange))); + debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[])); // Swap contents back in. fragments.unmoved_fragments = unmoved; @@ -433,7 +432,7 @@ fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>, let msg = format!("type {} ({:?}) is not fragmentable", parent_ty.repr(tcx), sty_and_variant_info); let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id)); - tcx.sess.opt_span_bug(opt_span, msg.index(&FullRange)) + tcx.sess.opt_span_bug(opt_span, &msg[]) } } } diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 2c48e0da01d..889a359b019 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -306,8 +306,8 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, - format!("invalid borrow lifetime: {:?}", - loan_region).index(&FullRange)); + &format!("invalid borrow lifetime: {:?}", + loan_region)[]); } }; debug!("loan_scope = {:?}", loan_scope); diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs index 1bb143e1dc8..28d02161eeb 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs @@ -115,29 +115,31 @@ fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, match move_from.cat { mc::cat_deref(_, _, mc::BorrowedPtr(..)) | mc::cat_deref(_, _, mc::Implicit(..)) | - mc::cat_deref(_, _, mc::UnsafePtr(..)) | mc::cat_static_item => { - bccx.span_err( - move_from.span, - format!("cannot move out of {}", - bccx.cmt_to_string(&*move_from)).index(&FullRange)); + bccx.span_err(move_from.span, + &format!("cannot move out of {}", + move_from.descriptive_string(bccx.tcx))[]); } mc::cat_downcast(ref b, _) | mc::cat_interior(ref b, _) => { match b.ty.sty { - ty::ty_struct(did, _) - | ty::ty_enum(did, _) if ty::has_dtor(bccx.tcx, did) => { + ty::ty_struct(did, _) | + ty::ty_enum(did, _) if ty::has_dtor(bccx.tcx, did) => { bccx.span_err( move_from.span, - format!("cannot move out of type `{}`, \ + &format!("cannot move out of type `{}`, \ which defines the `Drop` trait", - b.ty.user_string(bccx.tcx)).index(&FullRange)); + b.ty.user_string(bccx.tcx))[]); }, - _ => panic!("this path should not cause illegal move") + _ => { + bccx.span_bug(move_from.span, "this path should not cause illegal move") + } } } - _ => panic!("this path should not cause illegal move") + _ => { + bccx.span_bug(move_from.span, "this path should not cause illegal move") + } } } @@ -152,13 +154,13 @@ fn note_move_destination(bccx: &BorrowckCtxt, "attempting to move value to here"); bccx.span_help( move_to_span, - format!("to prevent the move, \ + &format!("to prevent the move, \ use `ref {0}` or `ref mut {0}` to capture value by \ reference", - pat_name).index(&FullRange)); + pat_name)[]); } else { bccx.span_note(move_to_span, - format!("and here (use `ref {0}` or `ref mut {0}`)", - pat_name).index(&FullRange)); + &format!("and here (use `ref {0}` or `ref mut {0}`)", + pat_name)[]); } } diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 88f56f68622..b87fed1601c 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -137,7 +137,7 @@ fn borrowck_fn(this: &mut BorrowckCtxt, check_loans::check_loans(this, &loan_dfcx, flowed_moves, - all_loans.index(&FullRange), + &all_loans[], id, decl, body); @@ -505,7 +505,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { pub fn report(&self, err: BckError<'tcx>) { self.span_err( err.span, - self.bckerr_to_string(&err).index(&FullRange)); + &self.bckerr_to_string(&err)[]); self.note_and_explain_bckerr(err); } @@ -525,9 +525,9 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { move_data::Declared => { self.tcx.sess.span_err( use_span, - format!("{} of possibly uninitialized variable: `{}`", + &format!("{} of possibly uninitialized variable: `{}`", verb, - self.loan_path_to_string(lp)).index(&FullRange)); + self.loan_path_to_string(lp))[]); (self.loan_path_to_string(moved_lp), String::new()) } @@ -566,10 +566,10 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { else { "" }; self.tcx.sess.span_err( use_span, - format!("{} of {}moved value: `{}`", + &format!("{} of {}moved value: `{}`", verb, msg, - nl).index(&FullRange)); + nl)[]); (ol, moved_lp_msg) } }; @@ -585,32 +585,32 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { (ty::expr_ty_adjusted(self.tcx, &*expr), expr.span) } r => { - self.tcx.sess.bug(format!("MoveExpr({}) maps to \ + self.tcx.sess.bug(&format!("MoveExpr({}) maps to \ {:?}, not Expr", the_move.id, - r).index(&FullRange)) + r)[]) } }; let (suggestion, _) = move_suggestion(param_env, expr_span, expr_ty, ("moved by default", "")); self.tcx.sess.span_note( expr_span, - format!("`{}` moved here{} because it has type `{}`, which is {}", + &format!("`{}` moved here{} because it has type `{}`, which is {}", ol, moved_lp_msg, expr_ty.user_string(self.tcx), - suggestion).index(&FullRange)); + suggestion)[]); } move_data::MovePat => { let pat_ty = ty::node_id_to_type(self.tcx, the_move.id); let span = self.tcx.map.span(the_move.id); self.tcx.sess.span_note(span, - format!("`{}` moved here{} because it has type `{}`, \ + &format!("`{}` moved here{} because it has type `{}`, \ which is moved by default", ol, moved_lp_msg, - pat_ty.user_string(self.tcx)).index(&FullRange)); + pat_ty.user_string(self.tcx))[]); self.tcx.sess.span_help(span, "use `ref` to override"); } @@ -623,10 +623,10 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { (ty::expr_ty_adjusted(self.tcx, &*expr), expr.span) } r => { - self.tcx.sess.bug(format!("Captured({}) maps to \ + self.tcx.sess.bug(&format!("Captured({}) maps to \ {:?}, not Expr", the_move.id, - r).index(&FullRange)) + r)[]) } }; let (suggestion, help) = @@ -637,12 +637,12 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { "make a copy and capture that instead to override")); self.tcx.sess.span_note( expr_span, - format!("`{}` moved into closure environment here{} because it \ + &format!("`{}` moved into closure environment here{} because it \ has type `{}`, which is {}", ol, moved_lp_msg, expr_ty.user_string(self.tcx), - suggestion).index(&FullRange)); + suggestion)[]); self.tcx.sess.span_help(expr_span, help); } } @@ -672,8 +672,8 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { &move_data::Assignment) { self.tcx.sess.span_err( span, - format!("re-assignment of immutable variable `{}`", - self.loan_path_to_string(lp)).index(&FullRange)); + &format!("re-assignment of immutable variable `{}`", + self.loan_path_to_string(lp))[]); self.tcx.sess.span_note(assign.span, "prior assignment occurs here"); } @@ -681,6 +681,10 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { self.tcx.sess.span_err(s, m); } + pub fn span_bug(&self, s: Span, m: &str) { + self.tcx.sess.span_bug(s, m); + } + pub fn span_note(&self, s: Span, m: &str) { self.tcx.sess.span_note(s, m); } @@ -798,8 +802,8 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { mc::AliasableOther => { self.tcx.sess.span_err( span, - format!("{} in an aliasable location", - prefix).index(&FullRange)); + &format!("{} in an aliasable location", + prefix)[]); } mc::AliasableClosure(id) => { self.tcx.sess.span_err(span, @@ -812,12 +816,12 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { mc::AliasableStaticMut(..) => { self.tcx.sess.span_err( span, - format!("{} in a static location", prefix).index(&FullRange)); + &format!("{} in a static location", prefix)[]); } mc::AliasableBorrowed => { self.tcx.sess.span_err( span, - format!("{} in a `&` reference", prefix).index(&FullRange)); + &format!("{} in a `&` reference", prefix)[]); } } @@ -884,13 +888,13 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { }; note_and_explain_region( self.tcx, - format!("{} would have to be valid for ", - descr).index(&FullRange), + &format!("{} would have to be valid for ", + descr)[], loan_scope, "..."); note_and_explain_region( self.tcx, - format!("...but {} is only valid for ", descr).index(&FullRange), + &format!("...but {} is only valid for ", descr)[], ptr_scope, ""); } @@ -910,7 +914,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { out.push('('); self.append_loan_path_to_string(&**lp_base, out); out.push_str(DOWNCAST_PRINTED_OPERATOR); - out.push_str(ty::item_path_str(self.tcx, variant_def_id).index(&FullRange)); + out.push_str(&ty::item_path_str(self.tcx, variant_def_id)[]); out.push(')'); } @@ -924,7 +928,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } mc::PositionalField(idx) => { out.push('.'); - out.push_str(idx.to_string().index(&FullRange)); + out.push_str(&idx.to_string()[]); } } } @@ -956,7 +960,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { out.push('('); self.append_autoderefd_loan_path_to_string(&**lp_base, out); out.push(':'); - out.push_str(ty::item_path_str(self.tcx, variant_def_id).index(&FullRange)); + out.push_str(&ty::item_path_str(self.tcx, variant_def_id)[]); out.push(')'); } diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index 647a5dd559c..20ad1307da3 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -60,7 +60,7 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> { if seen_one { sets.push_str(" "); } else { seen_one = true; } sets.push_str(variant.short_name()); sets.push_str(": "); - sets.push_str(self.dataflow_for_variant(e, n, variant).index(&FullRange)); + sets.push_str(&self.dataflow_for_variant(e, n, variant)[]); } sets } @@ -89,7 +89,7 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> { set.push_str(", "); } let loan_str = self.borrowck_ctxt.loan_path_to_string(&*lp); - set.push_str(loan_str.index(&FullRange)); + set.push_str(&loan_str[]); saw_some = true; true }); diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index 26bcd5f4c10..eedad75c89f 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -9,7 +9,8 @@ // except according to those terms. #![crate_name = "rustc_borrowck"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -20,6 +21,7 @@ #![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] +#![allow(unknown_features)] #![feature(int_uint)] #![allow(non_camel_case_types)] #[macro_use] extern crate log; diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 52d49924d05..c2af4315b06 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -47,7 +47,7 @@ pub fn compile_input(sess: Session, input: &Input, outdir: &Option<Path>, output: &Option<Path>, - addl_plugins: Option<Plugins>) { + addl_plugins: Option<Vec<String>>) { // We need nested scopes here, because the intermediate results can keep // large chunks of memory alive and we want to free them as soon as // possible to keep the peak memory usage low @@ -58,12 +58,12 @@ pub fn compile_input(sess: Session, let outputs = build_output_filenames(input, outdir, output, - krate.attrs.index(&FullRange), + &krate.attrs[], &sess); - let id = link::find_crate_name(Some(&sess), krate.attrs.index(&FullRange), + let id = link::find_crate_name(Some(&sess), &krate.attrs[], input); let expanded_crate - = match phase_2_configure_and_expand(&sess, krate, id.index(&FullRange), + = match phase_2_configure_and_expand(&sess, krate, &id[], addl_plugins) { None => return, Some(k) => k @@ -75,7 +75,7 @@ pub fn compile_input(sess: Session, let mut forest = ast_map::Forest::new(expanded_crate); let ast_map = assign_node_ids_and_map(&sess, &mut forest); - write_out_deps(&sess, input, &outputs, id.index(&FullRange)); + write_out_deps(&sess, input, &outputs, &id[]); if stop_after_phase_2(&sess) { return; } @@ -142,7 +142,7 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) } }); - if sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0 { + if sess.opts.debugging_opts.ast_json_noexpand { println!("{}", json::as_json(&krate)); } @@ -166,14 +166,14 @@ pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) pub fn phase_2_configure_and_expand(sess: &Session, mut krate: ast::Crate, crate_name: &str, - addl_plugins: Option<Plugins>) + addl_plugins: Option<Vec<String>>) -> Option<ast::Crate> { let time_passes = sess.time_passes(); *sess.crate_types.borrow_mut() = - collect_crate_types(sess, krate.attrs.index(&FullRange)); + collect_crate_types(sess, &krate.attrs[]); *sess.crate_metadata.borrow_mut() = - collect_crate_metadata(sess, krate.attrs.index(&FullRange)); + collect_crate_metadata(sess, &krate.attrs[]); time(time_passes, "recursion limit", (), |_| { middle::recursion_limit::update_recursion_limit(sess, &krate); @@ -268,8 +268,8 @@ pub fn phase_2_configure_and_expand(sess: &Session, if cfg!(windows) { _old_path = os::getenv("PATH").unwrap_or(_old_path); let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths(); - new_path.extend(os::split_paths(_old_path.index(&FullRange)).into_iter()); - os::setenv("PATH", os::join_paths(new_path.index(&FullRange)).unwrap()); + new_path.extend(os::split_paths(&_old_path[]).into_iter()); + os::setenv("PATH", os::join_paths(&new_path[]).unwrap()); } let cfg = syntax::ext::expand::ExpansionConfig { crate_name: crate_name.to_string(), @@ -334,7 +334,7 @@ pub fn assign_node_ids_and_map<'ast>(sess: &Session, let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest| ast_map::map_crate(forest, NodeIdAssigner { sess: sess })); - if sess.opts.debugging_opts & config::AST_JSON != 0 { + if sess.opts.debugging_opts.ast_json { println!("{}", json::as_json(map.krate())); } @@ -484,7 +484,7 @@ pub fn phase_3_run_analysis_passes<'tcx>(sess: Session, } fn save_analysis(sess: &Session) -> bool { - (sess.opts.debugging_opts & config::SAVE_ANALYSIS) != 0 + sess.opts.debugging_opts.save_analysis } pub fn phase_save_analysis(sess: &Session, @@ -533,7 +533,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session, time(sess.time_passes(), "LLVM passes", (), |_| write::run_passes(sess, trans, - sess.opts.output_types.index(&FullRange), + &sess.opts.output_types[], outputs)); } @@ -547,14 +547,14 @@ pub fn phase_6_link_output(sess: &Session, outputs: &OutputFilenames) { let old_path = os::getenv("PATH").unwrap_or_else(||String::new()); let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(); - new_path.extend(os::split_paths(old_path.index(&FullRange)).into_iter()); - os::setenv("PATH", os::join_paths(new_path.index(&FullRange)).unwrap()); + new_path.extend(os::split_paths(&old_path[]).into_iter()); + os::setenv("PATH", os::join_paths(&new_path[]).unwrap()); time(sess.time_passes(), "linking", (), |_| link::link_binary(sess, trans, outputs, - trans.link.crate_name.index(&FullRange))); + &trans.link.crate_name[])); os::setenv("PATH", old_path); } @@ -575,7 +575,7 @@ pub fn stop_after_phase_1(sess: &Session) -> bool { if sess.opts.show_span.is_some() { return true; } - return sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0; + return sess.opts.debugging_opts.ast_json_noexpand; } pub fn stop_after_phase_2(sess: &Session) -> bool { @@ -583,7 +583,7 @@ pub fn stop_after_phase_2(sess: &Session) -> bool { debug!("invoked with --no-analysis, returning early from compile_input"); return true; } - return sess.opts.debugging_opts & config::AST_JSON != 0; + return sess.opts.debugging_opts.ast_json; } pub fn stop_after_phase_5(sess: &Session) -> bool { @@ -643,7 +643,7 @@ fn write_out_deps(sess: &Session, // write Makefile-compatible dependency rules let files: Vec<String> = sess.codemap().files.borrow() .iter().filter(|fmap| fmap.is_real_file()) - .map(|fmap| escape_dep_filename(fmap.name.index(&FullRange))) + .map(|fmap| escape_dep_filename(&fmap.name[])) .collect(); let mut file = try!(io::File::create(&deps_filename)); for path in out_filenames.iter() { @@ -656,8 +656,8 @@ fn write_out_deps(sess: &Session, match result { Ok(()) => {} Err(e) => { - sess.fatal(format!("error writing dependencies to `{}`: {}", - deps_filename.display(), e).index(&FullRange)); + sess.fatal(&format!("error writing dependencies to `{}`: {}", + deps_filename.display(), e)[]); } } } @@ -726,9 +726,9 @@ pub fn collect_crate_types(session: &Session, let res = !link::invalid_output_for_target(session, *crate_type); if !res { - session.warn(format!("dropping unsupported crate type `{:?}` \ + session.warn(&format!("dropping unsupported crate type `{:?}` \ for target `{}`", - *crate_type, session.opts.target_triple).index(&FullRange)); + *crate_type, session.opts.target_triple)[]); } res diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 5af114abeea..9122a34a793 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -15,16 +15,20 @@ //! This API is completely unstable and subject to change. #![crate_name = "rustc_driver"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] +#![feature(box_syntax)] #![feature(rustc_diagnostic_macros)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate arena; extern crate flate; @@ -46,10 +50,11 @@ pub use syntax::diagnostic; use rustc_trans::back::link; use rustc::session::{config, Session, build_session}; -use rustc::session::config::{Input, PrintRequest}; +use rustc::session::config::{Input, PrintRequest, UnstableFeatures}; use rustc::lint::Lint; use rustc::lint; use rustc::metadata; +use rustc::metadata::creader::CrateOrString::Str; use rustc::DIAGNOSTICS; use std::cmp::Ordering::Equal; @@ -89,12 +94,12 @@ fn run_compiler(args: &[String]) { let descriptions = diagnostics::registry::Registry::new(&DIAGNOSTICS); match matches.opt_str("explain") { Some(ref code) => { - match descriptions.find_description(code.index(&FullRange)) { + match descriptions.find_description(&code[]) { Some(ref description) => { println!("{}", description); } None => { - early_error(format!("no extended information for {}", code).index(&FullRange)); + early_error(&format!("no extended information for {}", code)[]); } } return; @@ -120,7 +125,7 @@ fn run_compiler(args: &[String]) { early_error("no input filename given"); } 1u => { - let ifile = matches.free[0].index(&FullRange); + let ifile = &matches.free[0][]; if ifile == "-" { let contents = io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); @@ -132,7 +137,11 @@ fn run_compiler(args: &[String]) { _ => early_error("multiple input filenames provided") }; + let mut sopts = sopts; + sopts.unstable_features = get_unstable_features_setting(); + let mut sess = build_session(sopts, input_file_path, descriptions); + let cfg = config::build_configuration(&sess); if print_crate_info(&sess, Some(&input), &odir, &ofile) { return @@ -178,7 +187,23 @@ fn run_compiler(args: &[String]) { return; } - driver::compile_input(sess, cfg, &input, &odir, &ofile, None); + let plugins = sess.opts.debugging_opts.extra_plugins.clone(); + driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins)); +} + +pub fn get_unstable_features_setting() -> UnstableFeatures { + // Whether this is a feature-staged build, i.e. on the beta or stable channel + let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); + // The secret key needed to get through the rustc build itself by + // subverting the unstable features lints + let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY"); + // The matching key to the above, only known by the build system + let bootstrap_provided_key = os::getenv("RUSTC_BOOTSTRAP_KEY"); + match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) { + (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat, + (true, _, _) => UnstableFeatures::Disallow, + (false, _, _) => UnstableFeatures::Default + } } /// Returns a version string such as "0.12.0-dev". @@ -297,7 +322,7 @@ Available lint options: for lint in lints.into_iter() { let name = lint.name_lower().replace("_", "-"); println!(" {} {:7.7} {}", - padded(name.index(&FullRange)), lint.default_level.as_str(), lint.desc); + padded(&name[]), lint.default_level.as_str(), lint.desc); } println!("\n"); }; @@ -327,7 +352,7 @@ Available lint options: let desc = to.into_iter().map(|x| x.as_str().replace("_", "-")) .collect::<Vec<String>>().connect(", "); println!(" {} {}", - padded(name.index(&FullRange)), desc); + padded(&name[]), desc); } println!("\n"); }; @@ -356,13 +381,13 @@ Available lint options: fn describe_debug_flags() { println!("\nAvailable debug options:\n"); - let r = config::debugging_opts_map(); - for tuple in r.iter() { - match *tuple { - (ref name, ref desc, _) => { - println!(" -Z {:>20} -- {}", *name, *desc); - } - } + for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS.iter() { + let (width, extra) = match opt_type_desc { + Some(..) => (21, "=val"), + None => (25, "") + }; + println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"), + extra, desc, width=width); } } @@ -393,7 +418,7 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> { } let matches = - match getopts::getopts(args.index(&FullRange), config::optgroups().index(&FullRange)) { + match getopts::getopts(&args[], &config::optgroups()[]) { Ok(m) => m, Err(f_stable_attempt) => { // redo option parsing, including unstable options this time, @@ -567,15 +592,15 @@ pub fn monitor<F:FnOnce()+Send>(f: F) { "run with `RUST_BACKTRACE=1` for a backtrace".to_string(), ]; for note in xs.iter() { - emitter.emit(None, note.index(&FullRange), None, diagnostic::Note) + emitter.emit(None, ¬e[], None, diagnostic::Note) } match r.read_to_string() { Ok(s) => println!("{}", s), Err(e) => { emitter.emit(None, - format!("failed to read internal \ - stderr: {}", e).index(&FullRange), + &format!("failed to read internal \ + stderr: {}", e)[], None, diagnostic::Error) } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 44a35ef6be7..1765c80f943 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -23,7 +23,7 @@ use rustc::middle::ty; use rustc::middle::cfg; use rustc::middle::cfg::graphviz::LabelledCFG; use rustc::session::Session; -use rustc::session::config::{self, Input}; +use rustc::session::config::Input; use rustc::util::ppaux; use rustc_borrowck as borrowck; use rustc_borrowck::graphviz as borrowck_dot; @@ -294,9 +294,9 @@ impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> { try!(pp::word(&mut s.s, "as")); try!(pp::space(&mut s.s)); try!(pp::word(&mut s.s, - ppaux::ty_to_string( + &ppaux::ty_to_string( tcx, - ty::expr_ty(tcx, expr)).index(&FullRange))); + ty::expr_ty(tcx, expr))[])); s.pclose() } _ => Ok(()) @@ -305,19 +305,18 @@ impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> { } fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> { - let print_loans = config::FLOWGRAPH_PRINT_LOANS; - let print_moves = config::FLOWGRAPH_PRINT_MOVES; - let print_assigns = config::FLOWGRAPH_PRINT_ASSIGNS; - let print_all = config::FLOWGRAPH_PRINT_ALL; - let opt = |&: print_which| sess.debugging_opt(print_which); + let print_loans = sess.opts.debugging_opts.flowgraph_print_loans; + let print_moves = sess.opts.debugging_opts.flowgraph_print_moves; + let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns; + let print_all = sess.opts.debugging_opts.flowgraph_print_all; let mut variants = Vec::new(); - if opt(print_all) || opt(print_loans) { + if print_all || print_loans { variants.push(borrowck_dot::Loans); } - if opt(print_all) || opt(print_moves) { + if print_all || print_moves { variants.push(borrowck_dot::Moves); } - if opt(print_all) || opt(print_assigns) { + if print_all || print_assigns { variants.push(borrowck_dot::Assigns); } variants @@ -350,8 +349,8 @@ impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> { fn next(&mut self) -> Option<ast::NodeId> { match self { - &NodesMatchingDirect(ref mut iter) => iter.next(), - &NodesMatchingSuffix(ref mut iter) => iter.next(), + &mut NodesMatchingDirect(ref mut iter) => iter.next(), + &mut NodesMatchingSuffix(ref mut iter) => iter.next(), } } } @@ -370,7 +369,7 @@ impl UserIdentifiedItem { ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()), ItemViaPath(ref parts) => - NodesMatchingSuffix(map.nodes_matching_suffix(parts.index(&FullRange))), + NodesMatchingSuffix(map.nodes_matching_suffix(&parts[])), } } @@ -382,7 +381,7 @@ impl UserIdentifiedItem { user_option, self.reconstructed_input(), is_wrong_because); - sess.fatal(message.index(&FullRange)) + sess.fatal(&message[]) }; let mut saw_node = ast::DUMMY_NODE_ID; @@ -509,7 +508,7 @@ pub fn pretty_print_input(sess: Session, let is_expanded = needs_expansion(&ppm); let compute_ast_map = needs_ast_map(&ppm, &opt_uii); let krate = if compute_ast_map { - match driver::phase_2_configure_and_expand(&sess, krate, id.index(&FullRange), None) { + match driver::phase_2_configure_and_expand(&sess, krate, &id[], None) { None => return, Some(k) => k } @@ -528,7 +527,7 @@ pub fn pretty_print_input(sess: Session, }; let src_name = driver::source_name(input); - let src = sess.codemap().get_filemap(src_name.index(&FullRange)) + let src = sess.codemap().get_filemap(&src_name[]) .src.as_bytes().to_vec(); let mut rdr = MemReader::new(src); @@ -588,16 +587,16 @@ pub fn pretty_print_input(sess: Session, (PpmFlowGraph, opt_uii) => { debug!("pretty printing flow graph for {:?}", opt_uii); let uii = opt_uii.unwrap_or_else(|| { - sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or - unique path suffix (b::c::d)").index(&FullRange)) + sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or + unique path suffix (b::c::d)")[]) }); let ast_map = ast_map.expect("--pretty flowgraph missing ast_map"); let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map); let node = ast_map.find(nodeid).unwrap_or_else(|| { - sess.fatal(format!("--pretty flowgraph couldn't find id: {}", - nodeid).index(&FullRange)) + sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", + nodeid)[]) }); let code = blocks::Code::from_node(node); @@ -615,8 +614,8 @@ pub fn pretty_print_input(sess: Session, // point to what was found, if there's an // accessible span. match ast_map.opt_span(nodeid) { - Some(sp) => sess.span_fatal(sp, message.index(&FullRange)), - None => sess.fatal(message.index(&FullRange)) + Some(sp) => sess.span_fatal(sp, &message[]), + None => sess.fatal(&message[]) } } } diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index d301e9c7b5c..f68c76f4c44 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -61,7 +61,7 @@ fn remove_message(e: &mut ExpectErrorEmitter, msg: &str, lvl: Level) { e.messages.remove(i); } None => { - panic!("Unexpected error: {} Expected: {}", + panic!("Unexpected error: {} Expected: {:?}", msg, e.messages); } } @@ -99,7 +99,7 @@ fn test_env<F>(source_string: &str, { let mut options = config::basic_options(); - options.debugging_opts |= config::VERBOSE; + options.debugging_opts.verbose = true; let codemap = CodeMap::new(); let diagnostic_handler = @@ -279,7 +279,7 @@ impl<'a, 'tcx> Env<'a, 'tcx> { pub fn t_param(&self, space: subst::ParamSpace, index: u32) -> Ty<'tcx> { let name = format!("T{}", index); - ty::mk_param(self.infcx.tcx, space, index, token::intern(name.index(&FullRange))) + ty::mk_param(self.infcx.tcx, space, index, token::intern(&name[])) } pub fn re_early_bound(&self, diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 0bed754aa3c..a4f9b1f98d4 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -14,14 +14,18 @@ #![allow(dead_code)] #![crate_name = "rustc_llvm"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(link_args)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate libc; diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index ca6b1469f85..466bd608736 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -219,16 +219,16 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { // had the duplicate. let ns = ns.unwrap(); self.resolve_error(sp, - format!("duplicate definition of {} `{}`", + &format!("duplicate definition of {} `{}`", namespace_error_to_string(duplicate_type), - token::get_name(name)).index(&FullRange)); + token::get_name(name))[]); { let r = child.span_for_namespace(ns); for sp in r.iter() { self.session.span_note(*sp, - format!("first definition of {} `{}` here", + &format!("first definition of {} `{}` here", namespace_error_to_string(duplicate_type), - token::get_name(name)).index(&FullRange)); + token::get_name(name))[]); } } } @@ -1200,8 +1200,8 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { SingleImport(target, _) => { debug!("(building import directive) building import \ directive: {}::{}", - self.names_to_string(module_.imports.borrow().last().unwrap() - .module_path.index(&FullRange)), + self.names_to_string(&module_.imports.borrow().last().unwrap(). + module_path[]), token::get_name(target)); let mut import_resolutions = module_.import_resolutions diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 93ad69e03b1..ea6ecfbb92b 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -9,7 +9,8 @@ // except according to those terms. #![crate_name = "rustc_resolve"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -18,6 +19,7 @@ #![feature(slicing_syntax)] #![feature(rustc_diagnostic_macros)] +#![allow(unknown_features)] #![feature(int_uint)] #[macro_use] extern crate log; #[macro_use] extern crate syntax; @@ -818,15 +820,15 @@ impl PrimitiveTypeTable { table.intern("char", TyChar); table.intern("f32", TyFloat(TyF32)); table.intern("f64", TyFloat(TyF64)); - table.intern("int", TyInt(TyIs)); - table.intern("isize", TyInt(TyIs)); + table.intern("int", TyInt(TyIs(true))); + table.intern("isize", TyInt(TyIs(false))); table.intern("i8", TyInt(TyI8)); table.intern("i16", TyInt(TyI16)); table.intern("i32", TyInt(TyI32)); table.intern("i64", TyInt(TyI64)); table.intern("str", TyStr); - table.intern("uint", TyUint(TyUs)); - table.intern("usize", TyUint(TyUs)); + table.intern("uint", TyUint(TyUs(true))); + table.intern("usize", TyUint(TyUs(false))); table.intern("u8", TyUint(TyU8)); table.intern("u16", TyUint(TyU16)); table.intern("u32", TyUint(TyU32)); @@ -1057,11 +1059,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { }; let msg = format!("unresolved import `{}`{}", self.import_path_to_string( - import_directive.module_path - .index(&FullRange), + &import_directive.module_path[], import_directive.subclass), help); - self.resolve_error(span, msg.index(&FullRange)); + self.resolve_error(span, &msg[]); } Indeterminate => break, // Bail out. We'll come around next time. Success(()) => () // Good. Continue. @@ -1091,7 +1092,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { .iter() .map(|seg| seg.identifier.name) .collect(); - self.names_to_string(names.index(&FullRange)) + self.names_to_string(&names[]) } fn import_directive_subclass_to_string(&mut self, @@ -1155,7 +1156,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let module_path = &import_directive.module_path; debug!("(resolving import for module) resolving import `{}::...` in `{}`", - self.names_to_string(module_path.index(&FullRange)), + self.names_to_string(&module_path[]), self.module_to_string(&*module_)); // First, resolve the module path for the directive, if necessary. @@ -1164,7 +1165,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some((self.graph_root.get_module(), LastMod(AllPublic))) } else { match self.resolve_module_path(module_.clone(), - module_path.index(&FullRange), + &module_path[], DontUseLexicalScope, import_directive.span, ImportSearch) { @@ -1761,7 +1762,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ValueNS => "value", }, token::get_name(name).get()); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); } Some(_) | None => {} } @@ -1776,7 +1777,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if !name_bindings.defined_in_namespace_with(namespace, IMPORTABLE) { let msg = format!("`{}` is not directly importable", token::get_name(name)); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); } } @@ -1801,7 +1802,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { crate in this module \ (maybe you meant `use {0}::*`?)", token::get_name(name).get()); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); } Some(_) | None => {} } @@ -1823,7 +1824,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let msg = format!("import `{}` conflicts with value \ in this module", token::get_name(name).get()); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); if let Some(span) = value.value_span { self.session.span_note(span, "conflicting value here"); @@ -1841,7 +1842,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let msg = format!("import `{}` conflicts with type in \ this module", token::get_name(name).get()); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); if let Some(span) = ty.type_span { self.session.span_note(span, "note conflicting type here") @@ -1854,7 +1855,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let msg = format!("inherent implementations \ are only allowed on types \ defined in the current module"); - self.session.span_err(span, msg.index(&FullRange)); + self.session.span_err(span, &msg[]); self.session.span_note(import_span, "import from other module here") } @@ -1863,7 +1864,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let msg = format!("import `{}` conflicts with existing \ submodule", token::get_name(name).get()); - self.session.span_err(import_span, msg.index(&FullRange)); + self.session.span_err(import_span, &msg[]); if let Some(span) = ty.type_span { self.session.span_note(span, "note conflicting module here") @@ -1891,9 +1892,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if module.external_module_children.borrow().contains_key(&name) { self.session .span_err(span, - format!("an external crate named `{}` has already \ + &format!("an external crate named `{}` has already \ been imported into this module", - token::get_name(name).get()).index(&FullRange)); + token::get_name(name).get())[]); } } @@ -1909,10 +1910,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if module.external_module_children.borrow().contains_key(&name) { self.session .span_err(span, - format!("the name `{}` conflicts with an external \ + &format!("the name `{}` conflicts with an external \ crate that has been imported into this \ module", - token::get_name(name).get()).index(&FullRange)); + token::get_name(name).get())[]); } } @@ -1960,7 +1961,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let segment_name = token::get_name(name); let module_name = self.module_to_string(&*search_module); let mut span = span; - let msg = if "???" == module_name.index(&FullRange) { + let msg = if "???" == &module_name[] { span.hi = span.lo + Pos::from_uint(segment_name.get().len()); match search_parent_externals(name, @@ -2073,14 +2074,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match module_prefix_result { Failed(None) => { let mpath = self.names_to_string(module_path); - let mpath = mpath.index(&FullRange); + let mpath = &mpath[]; match mpath.rfind(':') { Some(idx) => { let msg = format!("Could not find `{}` in `{}`", // idx +- 1 to account for the // colons on either side - mpath.index(&((idx + 1)..)), - mpath.index(&(0..(idx - 1)))); + &mpath[(idx + 1)..], + &mpath[0..(idx - 1)]); return Failed(Some((span, msg))); }, None => { @@ -2254,8 +2255,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { PathSearch, true) { Failed(Some((span, msg))) => - self.resolve_error(span, format!("failed to resolve. {}", - msg).index(&FullRange)), + self.resolve_error(span, &format!("failed to resolve. {}", + msg)[]), Failed(None) => (), // Continue up the search chain. Indeterminate => { // We couldn't see through the higher scope because of an @@ -2515,7 +2516,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } else { let err = format!("unresolved import (maybe you meant `{}::*`?)", sn); - self.resolve_error((*imports)[index].span, err.index(&FullRange)); + self.resolve_error((*imports)[index].span, &err[]); } } @@ -2607,7 +2608,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match def_like { DlDef(d @ DefUpvar(..)) => { self.session.span_bug(span, - format!("unexpected {:?} in bindings", d).index(&FullRange)) + &format!("unexpected {:?} in bindings", d)[]) } DlDef(d @ DefLocal(_)) => { let node_id = d.def_id().node; @@ -2753,7 +2754,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { for (i, rib) in ribs.iter().enumerate().rev() { match rib.bindings.get(&name).cloned() { Some(def_like) => { - return self.upvarify(ribs.index(&((i + 1)..)), def_like, span); + return self.upvarify(&ribs[(i + 1)..], def_like, span); } None => { // Continue. @@ -2846,7 +2847,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { generics, implemented_traits, &**self_type, - impl_items.index(&FullRange)); + &impl_items[]); } ItemTrait(_, ref generics, ref bounds, ref trait_items) => { @@ -2924,7 +2925,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ItemStruct(ref struct_def, ref generics) => { self.resolve_struct(item.id, generics, - struct_def.fields.index(&FullRange)); + &struct_def.fields[]); } ItemMod(ref module_) => { @@ -2943,8 +2944,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { HasTypeParameters( generics, FnSpace, foreign_item.id, ItemRibKind), - |this| visit::walk_foreign_item(this, - &**foreign_item)); + |this| { + this.resolve_type_parameters(&generics.ty_params); + this.resolve_where_clause(&generics.where_clause); + visit::walk_foreign_item(this, &**foreign_item) + }); } ForeignItemStatic(..) => { visit::walk_foreign_item(this, @@ -2992,12 +2996,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if seen_bindings.contains(&name) { self.resolve_error(type_parameter.span, - format!("the name `{}` is already \ + &format!("the name `{}` is already \ used for a type \ parameter in this type \ parameter list", token::get_name( - name)).index(&FullRange)) + name))[]) } seen_bindings.insert(name); @@ -3169,7 +3173,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { }; let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str); - self.resolve_error(trait_reference.path.span, msg.index(&FullRange)); + self.resolve_error(trait_reference.path.span, &msg[]); } Some(def) => { match def { @@ -3179,16 +3183,16 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } (def, _) => { self.resolve_error(trait_reference.path.span, - format!("`{}` is not a trait", + &format!("`{}` is not a trait", self.path_names_to_string( - &trait_reference.path)).index(&FullRange)); + &trait_reference.path))[]); // If it's a typedef, give a note if let DefTy(..) = def { self.session.span_note( trait_reference.path.span, - format!("`type` aliases cannot be used for traits") - .index(&FullRange)); + &format!("`type` aliases cannot be used for traits") + []); } } } @@ -3383,9 +3387,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if self.trait_item_map.get(&(name, did)).is_none() { let path_str = self.path_names_to_string(&trait_ref.path); self.resolve_error(span, - format!("method `{}` is not a member of trait `{}`", + &format!("method `{}` is not a member of trait `{}`", token::get_name(name), - path_str).index(&FullRange)); + path_str)[]); } } } @@ -3451,19 +3455,19 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None => { self.resolve_error( p.span, - format!("variable `{}` from pattern #1 is \ + &format!("variable `{}` from pattern #1 is \ not bound in pattern #{}", token::get_name(key), - i + 1).index(&FullRange)); + i + 1)[]); } Some(binding_i) => { if binding_0.binding_mode != binding_i.binding_mode { self.resolve_error( binding_i.span, - format!("variable `{}` is bound with different \ + &format!("variable `{}` is bound with different \ mode in pattern #{} than in pattern #1", token::get_name(key), - i + 1).index(&FullRange)); + i + 1)[]); } } } @@ -3473,10 +3477,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if !map_0.contains_key(&key) { self.resolve_error( binding.span, - format!("variable `{}` from pattern {}{} is \ + &format!("variable `{}` from pattern {}{} is \ not bound in pattern {}1", token::get_name(key), - "#", i + 1, "#").index(&FullRange)); + "#", i + 1, "#")[]); } } } @@ -3591,7 +3595,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None => { let msg = format!("use of undeclared type name `{}`", self.path_names_to_string(path)); - self.resolve_error(ty.span, msg.index(&FullRange)); + self.resolve_error(ty.span, &msg[]); } } } @@ -3660,10 +3664,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { FoundStructOrEnumVariant(..) => { self.resolve_error( pattern.span, - format!("declaration of `{}` shadows an enum \ + &format!("declaration of `{}` shadows an enum \ variant or unit-like struct in \ scope", - token::get_name(renamed)).index(&FullRange)); + token::get_name(renamed))[]); } FoundConst(ref def, lp) if mode == RefutableMode => { debug!("(resolving pattern) resolving `{}` to \ @@ -3708,23 +3712,23 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // Forbid duplicate bindings in the same // parameter list. self.resolve_error(pattern.span, - format!("identifier `{}` \ + &format!("identifier `{}` \ is bound more \ than once in \ this parameter \ list", token::get_ident( ident)) - .index(&FullRange)) + []) } else if bindings_list.get(&renamed) == Some(&pat_id) { // Then this is a duplicate variable in the // same disjunction, which is an error. self.resolve_error(pattern.span, - format!("identifier `{}` is bound \ + &format!("identifier `{}` is bound \ more than once in the same \ pattern", - token::get_ident(ident)).index(&FullRange)); + token::get_ident(ident))[]); } // Else, not bound in the same pattern: do // nothing. @@ -3787,7 +3791,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { def: {:?}", result); let msg = format!("`{}` does not name a structure", self.path_names_to_string(path)); - self.resolve_error(path.span, msg.index(&FullRange)); + self.resolve_error(path.span, &msg[]); } } } @@ -3848,8 +3852,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Failed(err) => { match err { Some((span, msg)) => { - self.resolve_error(span, format!("failed to resolve: {}", - msg).index(&FullRange)); + self.resolve_error(span, &format!("failed to resolve: {}", + msg)[]); } None => () } @@ -4044,7 +4048,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let last_private; let module = self.current_module.clone(); match self.resolve_module_path(module, - module_path.index(&FullRange), + &module_path[], UseLexicalScope, path.span, PathSearch) { @@ -4058,8 +4062,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } }; - self.resolve_error(span, format!("failed to resolve. {}", - msg).index(&FullRange)); + self.resolve_error(span, &format!("failed to resolve. {}", + msg)[]); return None; } Indeterminate => panic!("indeterminate unexpected"), @@ -4102,7 +4106,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let containing_module; let last_private; match self.resolve_module_path_from_root(root_module, - module_path.index(&FullRange), + &module_path[], 0, path.span, PathSearch, @@ -4112,13 +4116,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some((span, msg)) => (span, msg), None => { let msg = format!("Use of undeclared module `::{}`", - self.names_to_string(module_path.index(&FullRange))); + self.names_to_string(&module_path[])); (path.span, msg) } }; - self.resolve_error(span, format!("failed to resolve. {}", - msg).index(&FullRange)); + self.resolve_error(span, &format!("failed to resolve. {}", + msg)[]); return None; } @@ -4159,7 +4163,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } TypeNS => { let name = ident.name; - self.search_ribs(self.type_ribs.index(&FullRange), name, span) + self.search_ribs(&self.type_ribs[], name, span) } }; @@ -4213,8 +4217,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Failed(err) => { match err { Some((span, msg)) => - self.resolve_error(span, format!("failed to resolve. {}", - msg).index(&FullRange)), + self.resolve_error(span, &format!("failed to resolve. {}", + msg)[]), None => () } @@ -4271,7 +4275,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } } else { match this.resolve_module_path(root, - name_path.index(&FullRange), + &name_path[], UseLexicalScope, span, PathSearch) { @@ -4309,7 +4313,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let name_path = path.segments.iter().map(|seg| seg.identifier.name).collect::<Vec<_>>(); // Look for a method in the current self type's impl module. - match get_module(self, path.span, name_path.index(&FullRange)) { + match get_module(self, path.span, &name_path[]) { Some(module) => match module.children.borrow().get(&name) { Some(binding) => { let p_str = self.path_names_to_string(&path); @@ -4520,7 +4524,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { def: {:?}", result); let msg = format!("`{}` does not name a structure", self.path_names_to_string(path)); - self.resolve_error(path.span, msg.index(&FullRange)); + self.resolve_error(path.span, &msg[]); } } @@ -4580,8 +4584,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None => { self.resolve_error( expr.span, - format!("use of undeclared label `{}`", - token::get_ident(label)).index(&FullRange)) + &format!("use of undeclared label `{}`", + token::get_ident(label))[]) } Some(DlDef(def @ DefLabel(_))) => { // Since this def is a label, it is never read. @@ -4716,11 +4720,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // the same conclusion! - nmatsakis Occupied(entry) => if def != *entry.get() { self.session - .bug(format!("node_id {} resolved first to {:?} and \ + .bug(&format!("node_id {} resolved first to {:?} and \ then {:?}", node_id, *entry.get(), - def).index(&FullRange)); + def)[]); }, Vacant(entry) => { entry.insert(def); }, } @@ -4734,9 +4738,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { BindByValue(_) => {} BindByRef(..) => { self.resolve_error(pat.span, - format!("cannot use `ref` binding mode \ + &format!("cannot use `ref` binding mode \ with {}", - descr).index(&FullRange)); + descr)[]); } } } @@ -4771,8 +4775,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { if names.len() == 0 { return "???".to_string(); } - self.names_to_string(names.into_iter().rev() - .collect::<Vec<ast::Name>>().index(&FullRange)) + self.names_to_string(&names.into_iter().rev() + .collect::<Vec<ast::Name>>()[]) } #[allow(dead_code)] // useful for debugging diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 26241ace76f..351be70cf52 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -128,7 +128,7 @@ pub fn find_crate_name(sess: Option<&Session>, attrs: &[ast::Attribute], input: &Input) -> String { let validate = |&: s: String, span: Option<Span>| { - creader::validate_crate_name(sess, s.index(&FullRange), span); + creader::validate_crate_name(sess, &s[], span); s }; @@ -146,7 +146,7 @@ pub fn find_crate_name(sess: Option<&Session>, let msg = format!("--crate-name and #[crate_name] are \ required to match, but `{}` != `{}`", s, name); - sess.span_err(attr.span, msg.index(&FullRange)); + sess.span_err(attr.span, &msg[]); } } return validate(s.clone(), None); @@ -192,17 +192,17 @@ fn symbol_hash<'tcx>(tcx: &ty::ctxt<'tcx>, // to be independent of one another in the crate. symbol_hasher.reset(); - symbol_hasher.input_str(link_meta.crate_name.index(&FullRange)); + symbol_hasher.input_str(&link_meta.crate_name[]); symbol_hasher.input_str("-"); symbol_hasher.input_str(link_meta.crate_hash.as_str()); for meta in tcx.sess.crate_metadata.borrow().iter() { - symbol_hasher.input_str(meta.index(&FullRange)); + symbol_hasher.input_str(&meta[]); } symbol_hasher.input_str("-"); - symbol_hasher.input_str(encoder::encoded_ty(tcx, t).index(&FullRange)); + symbol_hasher.input_str(&encoder::encoded_ty(tcx, t)[]); // Prefix with 'h' so that it never blends into adjacent digits let mut hash = String::from_str("h"); - hash.push_str(truncated_hash_result(symbol_hasher).index(&FullRange)); + hash.push_str(&truncated_hash_result(symbol_hasher)[]); hash } @@ -251,7 +251,7 @@ pub fn sanitize(s: &str) -> String { let mut tstr = String::new(); for c in c.escape_unicode() { tstr.push(c) } result.push('$'); - result.push_str(tstr.index(&(1..))); + result.push_str(&tstr[1..]); } } } @@ -260,7 +260,7 @@ pub fn sanitize(s: &str) -> String { if result.len() > 0u && result.as_bytes()[0] != '_' as u8 && ! (result.as_bytes()[0] as char).is_xid_start() { - return format!("_{}", result.index(&FullRange)); + return format!("_{}", &result[]); } return result; @@ -286,12 +286,12 @@ pub fn mangle<PI: Iterator<Item=PathElem>>(mut path: PI, fn push(n: &mut String, s: &str) { let sani = sanitize(s); - n.push_str(format!("{}{}", sani.len(), sani).index(&FullRange)); + n.push_str(&format!("{}{}", sani.len(), sani)[]); } // First, connect each component with <len, name> pairs. for e in path { - push(&mut n, token::get_name(e.name()).get().index(&FullRange)) + push(&mut n, &token::get_name(e.name()).get()[]) } match hash { @@ -329,17 +329,17 @@ pub fn mangle_exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, path: PathEl hash.push(EXTRA_CHARS.as_bytes()[extra2] as char); hash.push(EXTRA_CHARS.as_bytes()[extra3] as char); - exported_name(path, hash.index(&FullRange)) + exported_name(path, &hash[]) } pub fn mangle_internal_name_by_type_and_seq<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, name: &str) -> String { let s = ppaux::ty_to_string(ccx.tcx(), t); - let path = [PathName(token::intern(s.index(&FullRange))), + let path = [PathName(token::intern(&s[])), gensym_name(name)]; let hash = get_symbol_hash(ccx, t); - mangle(ast_map::Values(path.iter()), Some(hash.index(&FullRange))) + mangle(ast_map::Values(path.iter()), Some(&hash[])) } pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String { @@ -357,9 +357,9 @@ pub fn remove(sess: &Session, path: &Path) { match fs::unlink(path) { Ok(..) => {} Err(e) => { - sess.err(format!("failed to remove {}: {}", + sess.err(&format!("failed to remove {}: {}", path.display(), - e).index(&FullRange)); + e)[]); } } } @@ -373,8 +373,8 @@ pub fn link_binary(sess: &Session, let mut out_filenames = Vec::new(); for &crate_type in sess.crate_types.borrow().iter() { if invalid_output_for_target(sess, crate_type) { - sess.bug(format!("invalid output type `{:?}` for target os `{}`", - crate_type, sess.opts.target_triple).index(&FullRange)); + sess.bug(&format!("invalid output type `{:?}` for target os `{}`", + crate_type, sess.opts.target_triple)[]); } let out_file = link_binary_output(sess, trans, crate_type, outputs, crate_name); @@ -439,8 +439,8 @@ pub fn filename_for_input(sess: &Session, out_filename.with_filename(format!("lib{}.rlib", libname)) } config::CrateTypeDylib => { - let (prefix, suffix) = (sess.target.target.options.dll_prefix.index(&FullRange), - sess.target.target.options.dll_suffix.index(&FullRange)); + let (prefix, suffix) = (&sess.target.target.options.dll_prefix[], + &sess.target.target.options.dll_suffix[]); out_filename.with_filename(format!("{}{}{}", prefix, libname, @@ -450,7 +450,7 @@ pub fn filename_for_input(sess: &Session, out_filename.with_filename(format!("lib{}.a", libname)) } config::CrateTypeExecutable => { - let suffix = sess.target.target.options.exe_suffix.index(&FullRange); + let suffix = &sess.target.target.options.exe_suffix[]; out_filename.with_filename(format!("{}{}", libname, suffix)) } } @@ -477,14 +477,14 @@ fn link_binary_output(sess: &Session, let obj_is_writeable = is_writeable(&obj_filename); let out_is_writeable = is_writeable(&out_filename); if !out_is_writeable { - sess.fatal(format!("output file {} is not writeable -- check its \ + sess.fatal(&format!("output file {} is not writeable -- check its \ permissions.", - out_filename.display()).index(&FullRange)); + out_filename.display())[]); } else if !obj_is_writeable { - sess.fatal(format!("object file {} is not writeable -- check its \ + sess.fatal(&format!("object file {} is not writeable -- check its \ permissions.", - obj_filename.display()).index(&FullRange)); + obj_filename.display())[]); } match crate_type { @@ -539,7 +539,7 @@ fn link_rlib<'a>(sess: &'a Session, for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() { match kind { cstore::NativeStatic => { - ab.add_native_library(l.index(&FullRange)).unwrap(); + ab.add_native_library(&l[]).unwrap(); } cstore::NativeFramework | cstore::NativeUnknown => {} } @@ -586,13 +586,13 @@ fn link_rlib<'a>(sess: &'a Session, // the same filename for metadata (stomping over one another) let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir"); let metadata = tmpdir.path().join(METADATA_FILENAME); - match fs::File::create(&metadata).write(trans.metadata - .index(&FullRange)) { + match fs::File::create(&metadata).write(&trans.metadata + []) { Ok(..) => {} Err(e) => { - sess.err(format!("failed to write {}: {}", + sess.err(&format!("failed to write {}: {}", metadata.display(), - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); } } @@ -610,25 +610,25 @@ fn link_rlib<'a>(sess: &'a Session, // was exactly 16 bytes. let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice()); let bc_deflated_filename = obj_filename.with_extension( - format!("{}.bytecode.deflate", i).index(&FullRange)); + &format!("{}.bytecode.deflate", i)[]); let bc_data = match fs::File::open(&bc_filename).read_to_end() { Ok(buffer) => buffer, - Err(e) => sess.fatal(format!("failed to read bytecode: {}", - e).index(&FullRange)) + Err(e) => sess.fatal(&format!("failed to read bytecode: {}", + e)[]) }; - let bc_data_deflated = match flate::deflate_bytes(bc_data.index(&FullRange)) { + let bc_data_deflated = match flate::deflate_bytes(&bc_data[]) { Some(compressed) => compressed, - None => sess.fatal(format!("failed to compress bytecode from {}", - bc_filename.display()).index(&FullRange)) + None => sess.fatal(&format!("failed to compress bytecode from {}", + bc_filename.display())[]) }; let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) { Ok(file) => file, Err(e) => { - sess.fatal(format!("failed to create compressed bytecode \ - file: {}", e).index(&FullRange)) + sess.fatal(&format!("failed to create compressed bytecode \ + file: {}", e)[]) } }; @@ -636,8 +636,8 @@ fn link_rlib<'a>(sess: &'a Session, bc_data_deflated.as_slice()) { Ok(()) => {} Err(e) => { - sess.err(format!("failed to write compressed bytecode: \ - {}", e).index(&FullRange)); + sess.err(&format!("failed to write compressed bytecode: \ + {}", e)[]); sess.abort_if_errors() } }; @@ -677,7 +677,7 @@ fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T, try! { writer.write(RLIB_BYTECODE_OBJECT_MAGIC) }; try! { writer.write_le_u32(1) }; try! { writer.write_le_u64(bc_data_deflated_size) }; - try! { writer.write(bc_data_deflated.index(&FullRange)) }; + try! { writer.write(&bc_data_deflated[]) }; let number_of_bytes_written_so_far = RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id @@ -727,12 +727,12 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) { let ref name = sess.cstore.get_crate_data(cnum).name; let p = match *path { Some(ref p) => p.clone(), None => { - sess.err(format!("could not find rlib for: `{}`", - name).index(&FullRange)); + sess.err(&format!("could not find rlib for: `{}`", + name)[]); continue } }; - ab.add_rlib(&p, name.index(&FullRange), sess.lto()).unwrap(); + ab.add_rlib(&p, &name[], sess.lto()).unwrap(); let native_libs = csearch::get_native_libraries(&sess.cstore, cnum); all_native_libs.extend(native_libs.into_iter()); @@ -754,7 +754,7 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) { cstore::NativeUnknown => "library", cstore::NativeFramework => "framework", }; - sess.note(format!("{}: {}", name, *lib).index(&FullRange)); + sess.note(&format!("{}: {}", name, *lib)[]); } } @@ -768,17 +768,17 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, // The invocations of cc share some flags across platforms let pname = get_cc_prog(sess); - let mut cmd = Command::new(pname.index(&FullRange)); + let mut cmd = Command::new(&pname[]); - cmd.args(sess.target.target.options.pre_link_args.index(&FullRange)); + cmd.args(&sess.target.target.options.pre_link_args[]); link_args(&mut cmd, sess, dylib, tmpdir.path(), trans, obj_filename, out_filename); - cmd.args(sess.target.target.options.post_link_args.index(&FullRange)); + cmd.args(&sess.target.target.options.post_link_args[]); if !sess.target.target.options.no_compiler_rt { cmd.arg("-lcompiler-rt"); } - if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 { + if sess.opts.debugging_opts.print_link_args { println!("{}", &cmd); } @@ -791,22 +791,22 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, match prog { Ok(prog) => { if !prog.status.success() { - sess.err(format!("linking with `{}` failed: {}", + sess.err(&format!("linking with `{}` failed: {}", pname, - prog.status).index(&FullRange)); - sess.note(format!("{}", &cmd).index(&FullRange)); + prog.status)[]); + sess.note(&format!("{}", &cmd)[]); let mut output = prog.error.clone(); - output.push_all(prog.output.index(&FullRange)); - sess.note(str::from_utf8(output.index(&FullRange)).unwrap()); + output.push_all(&prog.output[]); + sess.note(str::from_utf8(&output[]).unwrap()); sess.abort_if_errors(); } debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap()); debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap()); }, Err(e) => { - sess.err(format!("could not exec the linker `{}`: {}", + sess.err(&format!("could not exec the linker `{}`: {}", pname, - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); } } @@ -818,7 +818,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool, match Command::new("dsymutil").arg(out_filename).output() { Ok(..) => {} Err(e) => { - sess.err(format!("failed to run dsymutil: {}", e).index(&FullRange)); + sess.err(&format!("failed to run dsymutil: {}", e)[]); sess.abort_if_errors(); } } @@ -867,7 +867,7 @@ fn link_args(cmd: &mut Command, let mut v = b"-Wl,-force_load,".to_vec(); v.push_all(morestack.as_vec()); - cmd.arg(v.index(&FullRange)); + cmd.arg(&v[]); } else { cmd.args(&["-Wl,--whole-archive", "-lmorestack", "-Wl,--no-whole-archive"]); } @@ -992,7 +992,7 @@ fn link_args(cmd: &mut Command, if sess.opts.cg.rpath { let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec(); v.push_all(out_filename.filename().unwrap()); - cmd.arg(v.index(&FullRange)); + cmd.arg(&v[]); } } else { cmd.arg("-shared"); @@ -1004,7 +1004,7 @@ fn link_args(cmd: &mut Command, // addl_lib_search_paths if sess.opts.cg.rpath { let sysroot = sess.sysroot(); - let target_triple = sess.opts.target_triple.index(&FullRange); + let target_triple = &sess.opts.target_triple[]; let get_install_prefix_lib_path = |:| { let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX"); let tlib = filesearch::relative_target_lib_path(sysroot, target_triple); @@ -1021,14 +1021,14 @@ fn link_args(cmd: &mut Command, get_install_prefix_lib_path: get_install_prefix_lib_path, realpath: ::util::fs::realpath }; - cmd.args(rpath::get_rpath_flags(rpath_config).index(&FullRange)); + cmd.args(&rpath::get_rpath_flags(rpath_config)[]); } // Finally add all the linker arguments provided on the command line along // with any #[link_args] attributes found inside the crate let empty = Vec::new(); - cmd.args(sess.opts.cg.link_args.as_ref().unwrap_or(&empty).index(&FullRange)); - cmd.args(used_link_args.index(&FullRange)); + cmd.args(&sess.opts.cg.link_args.as_ref().unwrap_or(&empty)[]); + cmd.args(&used_link_args[]); } // # Native library linking @@ -1082,14 +1082,14 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { } else { // -force_load is the OSX equivalent of --whole-archive, but it // involves passing the full path to the library to link. - let lib = archive::find_library(l.index(&FullRange), + let lib = archive::find_library(&l[], sess.target.target.options.staticlib_prefix.as_slice(), sess.target.target.options.staticlib_suffix.as_slice(), - search_path.index(&FullRange), + &search_path[], &sess.diagnostic().handler); let mut v = b"-Wl,-force_load,".to_vec(); v.push_all(lib.as_vec()); - cmd.arg(v.index(&FullRange)); + cmd.arg(&v[]); } } if takes_hints { @@ -1102,7 +1102,7 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { cmd.arg(format!("-l{}", l)); } cstore::NativeFramework => { - cmd.arg("-framework").arg(l.index(&FullRange)); + cmd.arg("-framework").arg(&l[]); } cstore::NativeStatic => unreachable!(), } @@ -1158,7 +1158,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // Converts a library file-stem into a cc -l argument fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] { if stem.starts_with("lib".as_bytes()) && !config.target.options.is_like_windows { - stem.index(&(3..)) + &stem[3..] } else { stem } @@ -1183,18 +1183,18 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // against the archive. if sess.lto() { let name = cratepath.filename_str().unwrap(); - let name = name.index(&(3..(name.len() - 5))); // chop off lib/.rlib + let name = &name[3..(name.len() - 5)]; // chop off lib/.rlib time(sess.time_passes(), - format!("altering {}.rlib", name).index(&FullRange), + &format!("altering {}.rlib", name)[], (), |()| { let dst = tmpdir.join(cratepath.filename().unwrap()); match fs::copy(&cratepath, &dst) { Ok(..) => {} Err(e) => { - sess.err(format!("failed to copy {} to {}: {}", + sess.err(&format!("failed to copy {} to {}: {}", cratepath.display(), dst.display(), - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); } } @@ -1204,9 +1204,9 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, match fs::chmod(&dst, io::USER_READ | io::USER_WRITE) { Ok(..) => {} Err(e) => { - sess.err(format!("failed to chmod {} when preparing \ + sess.err(&format!("failed to chmod {} when preparing \ for LTO: {}", dst.display(), - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); } } @@ -1220,9 +1220,9 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, maybe_ar_prog: sess.opts.cg.ar.clone() }; let mut archive = Archive::open(config); - archive.remove_file(format!("{}.o", name).index(&FullRange)); + archive.remove_file(&format!("{}.o", name)[]); let files = archive.files(); - if files.iter().any(|s| s.index(&FullRange).ends_with(".o")) { + if files.iter().any(|s| s[].ends_with(".o")) { cmd.arg(dst); } }); @@ -1244,7 +1244,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, let mut v = "-l".as_bytes().to_vec(); v.push_all(unlib(&sess.target, cratepath.filestem().unwrap())); - cmd.arg(v.index(&FullRange)); + cmd.arg(&v[]); } } @@ -1286,7 +1286,7 @@ fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) { } cstore::NativeFramework => { cmd.arg("-framework"); - cmd.arg(lib.index(&FullRange)); + cmd.arg(&lib[]); } cstore::NativeStatic => { sess.bug("statics shouldn't be propagated"); diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index ecf2e9ed724..b6a6b526fac 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -53,30 +53,30 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let path = match path { Some(p) => p, None => { - sess.fatal(format!("could not find rlib for: `{}`", - name).index(&FullRange)); + sess.fatal(&format!("could not find rlib for: `{}`", + name)[]); } }; let archive = ArchiveRO::open(&path).expect("wanted an rlib"); let file = path.filename_str().unwrap(); - let file = file.index(&(3..(file.len() - 5))); // chop off lib/.rlib + let file = &file[3..(file.len() - 5)]; // chop off lib/.rlib debug!("reading {}", file); for i in iter::count(0u, 1) { let bc_encoded = time(sess.time_passes(), format!("check for {}.{}.bytecode.deflate", name, i).as_slice(), (), |_| { - archive.read(format!("{}.{}.bytecode.deflate", - file, i).index(&FullRange)) + archive.read(&format!("{}.{}.bytecode.deflate", + file, i)[]) }); let bc_encoded = match bc_encoded { Some(data) => data, None => { if i == 0 { // No bitcode was found at all. - sess.fatal(format!("missing compressed bytecode in {}", - path.display()).index(&FullRange)); + sess.fatal(&format!("missing compressed bytecode in {}", + path.display())[]); } // No more bitcode files to read. break; @@ -91,20 +91,20 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, if version == 1 { // The only version existing so far let data_size = extract_compressed_bytecode_size_v1(bc_encoded); - let compressed_data = bc_encoded.index(&( + let compressed_data = &bc_encoded[ link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET.. - (link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET + data_size as uint))); + (link::RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET + data_size as uint)]; match flate::inflate_bytes(compressed_data) { Some(inflated) => inflated, None => { - sess.fatal(format!("failed to decompress bc of `{}`", - name).index(&FullRange)) + sess.fatal(&format!("failed to decompress bc of `{}`", + name)[]) } } } else { - sess.fatal(format!("Unsupported bytecode format version {}", - version).index(&FullRange)) + sess.fatal(&format!("Unsupported bytecode format version {}", + version)[]) } }) } else { @@ -114,8 +114,8 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, match flate::inflate_bytes(bc_encoded) { Some(bc) => bc, None => { - sess.fatal(format!("failed to decompress bc of `{}`", - name).index(&FullRange)) + sess.fatal(&format!("failed to decompress bc of `{}`", + name)[]) } } }) @@ -124,7 +124,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let ptr = bc_decoded.as_slice().as_ptr(); debug!("linking {}, part {}", name, i); time(sess.time_passes(), - format!("ll link {}.{}", name, i).index(&FullRange), + &format!("ll link {}.{}", name, i)[], (), |()| unsafe { if !llvm::LLVMRustLinkInExternalBitcode(llmod, @@ -132,7 +132,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, bc_decoded.len() as libc::size_t) { write::llvm_err(sess.diagnostic().handler(), format!("failed to load bc of `{}`", - name.index(&FullRange))); + &name[])); } }); } @@ -142,7 +142,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let cstrs: Vec<CString> = reachable.iter().map(|s| { CString::from_slice(s.as_bytes()) }).collect(); - let arr: Vec<*const i8> = cstrs.iter().map(|c| c.as_ptr()).collect(); + let arr: Vec<*const libc::c_char> = cstrs.iter().map(|c| c.as_ptr()).collect(); let ptr = arr.as_ptr(); unsafe { llvm::LLVMRustRunRestrictionPass(llmod, @@ -186,7 +186,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, fn is_versioned_bytecode_format(bc: &[u8]) -> bool { let magic_id_byte_count = link::RLIB_BYTECODE_OBJECT_MAGIC.len(); return bc.len() > magic_id_byte_count && - bc.index(&(0..magic_id_byte_count)) == link::RLIB_BYTECODE_OBJECT_MAGIC; + &bc[0..magic_id_byte_count] == link::RLIB_BYTECODE_OBJECT_MAGIC; } fn extract_bytecode_format_version(bc: &[u8]) -> u32 { @@ -198,8 +198,7 @@ fn extract_compressed_bytecode_size_v1(bc: &[u8]) -> u64 { } fn read_from_le_bytes<T: Int>(bytes: &[u8], position_in_bytes: uint) -> T { - let byte_data = bytes.index(&(position_in_bytes.. - (position_in_bytes + mem::size_of::<T>()))); + let byte_data = &bytes[position_in_bytes..(position_in_bytes + mem::size_of::<T>())]; let data = unsafe { *(byte_data.as_ptr() as *const T) }; diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 8a80019143e..c818dda7581 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -47,14 +47,14 @@ pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! { unsafe { let cstr = llvm::LLVMRustGetLastError(); if cstr == ptr::null() { - handler.fatal(msg.index(&FullRange)); + handler.fatal(&msg[]); } else { let err = ffi::c_str_to_bytes(&cstr); let err = String::from_utf8_lossy(err.as_slice()).to_string(); libc::free(cstr as *mut _); - handler.fatal(format!("{}: {}", - msg.index(&FullRange), - err.index(&FullRange)).index(&FullRange)); + handler.fatal(&format!("{}: {}", + &msg[], + &err[])[]); } } } @@ -104,13 +104,13 @@ impl SharedEmitter { match diag.code { Some(ref code) => { handler.emit_with_code(None, - diag.msg.index(&FullRange), - code.index(&FullRange), + &diag.msg[], + &code[], diag.lvl); }, None => { handler.emit(None, - diag.msg.index(&FullRange), + &diag.msg[], diag.lvl); }, } @@ -165,8 +165,8 @@ fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel { fn create_target_machine(sess: &Session) -> TargetMachineRef { let reloc_model_arg = match sess.opts.cg.relocation_model { - Some(ref s) => s.index(&FullRange), - None => sess.target.target.options.relocation_model.index(&FullRange) + Some(ref s) => &s[], + None => &sess.target.target.options.relocation_model[] }; let reloc_model = match reloc_model_arg { "pic" => llvm::RelocPIC, @@ -174,10 +174,10 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef { "default" => llvm::RelocDefault, "dynamic-no-pic" => llvm::RelocDynamicNoPic, _ => { - sess.err(format!("{:?} is not a valid relocation mode", + sess.err(&format!("{:?} is not a valid relocation mode", sess.opts .cg - .relocation_model).index(&FullRange)); + .relocation_model)[]); sess.abort_if_errors(); unreachable!(); } @@ -198,8 +198,8 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef { let fdata_sections = ffunction_sections; let code_model_arg = match sess.opts.cg.code_model { - Some(ref s) => s.index(&FullRange), - None => sess.target.target.options.code_model.index(&FullRange) + Some(ref s) => &s[], + None => &sess.target.target.options.code_model[] }; let code_model = match code_model_arg { @@ -209,16 +209,16 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef { "medium" => llvm::CodeModelMedium, "large" => llvm::CodeModelLarge, _ => { - sess.err(format!("{:?} is not a valid code model", + sess.err(&format!("{:?} is not a valid code model", sess.opts .cg - .code_model).index(&FullRange)); + .code_model)[]); sess.abort_if_errors(); unreachable!(); } }; - let triple = sess.target.target.llvm_target.index(&FullRange); + let triple = &sess.target.target.llvm_target[]; let tm = unsafe { let triple = CString::from_slice(triple.as_bytes()); @@ -350,13 +350,13 @@ unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef, match cgcx.lto_ctxt { Some((sess, _)) => { sess.codemap().with_expn_info(ExpnId::from_llvm_cookie(cookie), |info| match info { - Some(ei) => sess.span_err(ei.call_site, msg.index(&FullRange)), - None => sess.err(msg.index(&FullRange)), + Some(ei) => sess.span_err(ei.call_site, &msg[]), + None => sess.err(&msg[]), }); } None => { - cgcx.handler.err(msg.index(&FullRange)); + cgcx.handler.err(&msg[]); cgcx.handler.note("build without -C codegen-units for more exact errors"); } } @@ -518,14 +518,14 @@ unsafe fn optimize_and_codegen(cgcx: &CodegenContext, } if config.emit_asm { - let path = output_names.with_extension(format!("{}.s", name_extra).index(&FullRange)); + let path = output_names.with_extension(&format!("{}.s", name_extra)[]); with_codegen(tm, llmod, config.no_builtins, |cpm| { write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFileType); }); } if config.emit_obj { - let path = output_names.with_extension(format!("{}.o", name_extra).index(&FullRange)); + let path = output_names.with_extension(&format!("{}.o", name_extra)[]); with_codegen(tm, llmod, config.no_builtins, |cpm| { write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType); }); @@ -639,7 +639,7 @@ pub fn run_passes(sess: &Session, // Process the work items, optionally using worker threads. if sess.opts.cg.codegen_units == 1 { - run_work_singlethreaded(sess, trans.reachable.index(&FullRange), work_items); + run_work_singlethreaded(sess, &trans.reachable[], work_items); } else { run_work_multithreaded(sess, work_items, sess.opts.cg.codegen_units); } @@ -666,8 +666,8 @@ pub fn run_passes(sess: &Session, if crate_output.single_output_file.is_some() { // 2) Multiple codegen units, with `-o some_name`. We have // no good solution for this case, so warn the user. - sess.warn(format!("ignoring -o because multiple .{} files were produced", - ext).index(&FullRange)); + sess.warn(&format!("ignoring -o because multiple .{} files were produced", + ext)[]); } else { // 3) Multiple codegen units, but no `-o some_name`. We // just leave the `foo.0.x` files in place. @@ -700,22 +700,22 @@ pub fn run_passes(sess: &Session, }; let pname = get_cc_prog(sess); - let mut cmd = Command::new(pname.index(&FullRange)); + let mut cmd = Command::new(&pname[]); - cmd.args(sess.target.target.options.pre_link_args.index(&FullRange)); + cmd.args(&sess.target.target.options.pre_link_args[]); cmd.arg("-nostdlib"); for index in range(0, trans.modules.len()) { - cmd.arg(crate_output.with_extension(format!("{}.o", index).index(&FullRange))); + cmd.arg(crate_output.with_extension(&format!("{}.o", index)[])); } cmd.arg("-r") .arg("-o") .arg(windows_output_path.as_ref().unwrap_or(output_path)); - cmd.args(sess.target.target.options.post_link_args.index(&FullRange)); + cmd.args(&sess.target.target.options.post_link_args[]); - if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 { + if sess.opts.debugging_opts.print_link_args { println!("{}", &cmd); } @@ -725,15 +725,15 @@ pub fn run_passes(sess: &Session, match cmd.status() { Ok(status) => { if !status.success() { - sess.err(format!("linking of {} with `{}` failed", - output_path.display(), cmd).index(&FullRange)); + sess.err(&format!("linking of {} with `{}` failed", + output_path.display(), cmd)[]); sess.abort_if_errors(); } }, Err(e) => { - sess.err(format!("could not exec the linker `{}`: {}", + sess.err(&format!("could not exec the linker `{}`: {}", pname, - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); }, } @@ -818,12 +818,12 @@ pub fn run_passes(sess: &Session, for i in range(0, trans.modules.len()) { if modules_config.emit_obj { let ext = format!("{}.o", i); - remove(sess, &crate_output.with_extension(ext.index(&FullRange))); + remove(sess, &crate_output.with_extension(&ext[])); } if modules_config.emit_bc && !keep_numbered_bitcode { let ext = format!("{}.bc", i); - remove(sess, &crate_output.with_extension(ext.index(&FullRange))); + remove(sess, &crate_output.with_extension(&ext[])); } } @@ -949,7 +949,7 @@ fn run_work_multithreaded(sess: &Session, pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { let pname = get_cc_prog(sess); - let mut cmd = Command::new(pname.index(&FullRange)); + let mut cmd = Command::new(&pname[]); cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject)) .arg(outputs.temp_path(config::OutputTypeAssembly)); @@ -958,20 +958,20 @@ pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) { match cmd.output() { Ok(prog) => { if !prog.status.success() { - sess.err(format!("linking with `{}` failed: {}", + sess.err(&format!("linking with `{}` failed: {}", pname, - prog.status).index(&FullRange)); - sess.note(format!("{}", &cmd).index(&FullRange)); + prog.status)[]); + sess.note(&format!("{}", &cmd)[]); let mut note = prog.error.clone(); - note.push_all(prog.output.index(&FullRange)); - sess.note(str::from_utf8(note.index(&FullRange)).unwrap()); + note.push_all(&prog.output[]); + sess.note(str::from_utf8(¬e[]).unwrap()); sess.abort_if_errors(); } }, Err(e) => { - sess.err(format!("could not exec the linker `{}`: {}", + sess.err(&format!("could not exec the linker `{}`: {}", pname, - e).index(&FullRange)); + e)[]); sess.abort_if_errors(); } } @@ -1004,7 +1004,7 @@ unsafe fn configure_llvm(sess: &Session) { if sess.print_llvm_passes() { add("-debug-pass=Structure"); } for arg in sess.opts.cg.llvm_args.iter() { - add((*arg).index(&FullRange)); + add(&(*arg)[]); } } diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index b6f90a4c2f5..4859598e63c 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -15,16 +15,20 @@ //! This API is completely unstable and subject to change. #![crate_name = "rustc_trans"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] +#![feature(box_syntax)] #![feature(rustc_diagnostic_macros)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate arena; extern crate flate; diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 35f168f092a..eb163ed7406 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -94,7 +94,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { // dump info about all the external crates referenced from this crate self.sess.cstore.iter_crate_data(|n, cmd| { - self.fmt.external_crate_str(krate.span, cmd.name.index(&FullRange), n); + self.fmt.external_crate_str(krate.span, &cmd.name[], n); }); self.fmt.recorder.record("end_external_crates\n"); } @@ -143,7 +143,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, - qualname.index(&FullRange), + &qualname[], self.cur_scope); } } @@ -161,7 +161,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, - qualname.index(&FullRange), + &qualname[], self.cur_scope); } } @@ -180,17 +180,17 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { let (ref span, ref qualname) = sub_paths[len-2]; self.fmt.sub_type_ref_str(path.span, *span, - qualname.index(&FullRange)); + &qualname[]); // write the other sub-paths if len <= 2 { return; } - let sub_paths = sub_paths.index(&(0..(len-2))); + let sub_paths = &sub_paths[0..(len-2)]; for &(ref span, ref qualname) in sub_paths.iter() { self.fmt.sub_mod_ref_str(path.span, *span, - qualname.index(&FullRange), + &qualname[], self.cur_scope); } } @@ -198,8 +198,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { // looks up anything, not just a type fn lookup_type_ref(&self, ref_id: NodeId) -> Option<DefId> { if !self.analysis.ty_cx.def_map.borrow().contains_key(&ref_id) { - self.sess.bug(format!("def_map has no key for {} in lookup_type_ref", - ref_id).index(&FullRange)); + self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref", + ref_id)[]); } let def = (*self.analysis.ty_cx.def_map.borrow())[ref_id]; match def { @@ -211,8 +211,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { fn lookup_def_kind(&self, ref_id: NodeId, span: Span) -> Option<recorder::Row> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&ref_id) { - self.sess.span_bug(span, format!("def_map has no key for {} in lookup_def_kind", - ref_id).index(&FullRange)); + self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind", + ref_id)[]); } let def = (*def_map)[ref_id]; match def { @@ -240,8 +240,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { def::DefUse(_) | def::DefMethod(..) | def::DefPrimTy(_) => { - self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}", - def).index(&FullRange)); + self.sess.span_bug(span, &format!("lookup_def_kind for unexpected item: {:?}", + def)[]); }, } } @@ -262,8 +262,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { span_utils.span_for_last_ident(p.span), id, qualname, - path_to_string(p).index(&FullRange), - typ.index(&FullRange)); + &path_to_string(p)[], + &typ[]); } self.collected_paths.clear(); } @@ -285,7 +285,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { match item.node { ast::ItemImpl(_, _, _, _, ref ty, _) => { let mut result = String::from_str("<"); - result.push_str(ty_to_string(&**ty).index(&FullRange)); + result.push_str(&ty_to_string(&**ty)[]); match ty::trait_of_item(&self.analysis.ty_cx, ast_util::local_def(method.id)) { @@ -301,18 +301,18 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } _ => { self.sess.span_bug(method.span, - format!("Container {} for method {} not an impl?", - impl_id.node, method.id).index(&FullRange)); + &format!("Container {} for method {} not an impl?", + impl_id.node, method.id)[]); }, } }, _ => { self.sess.span_bug(method.span, - format!("Container {} for method {} is not a node item {:?}", - impl_id.node, - method.id, - self.analysis.ty_cx.map.get(impl_id.node) - ).index(&FullRange)); + &format!( + "Container {} for method {} is not a node item {:?}", + impl_id.node, + method.id, + self.analysis.ty_cx.map.get(impl_id.node))[]); }, }, None => match ty::trait_of_item(&self.analysis.ty_cx, @@ -327,21 +327,21 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } _ => { self.sess.span_bug(method.span, - format!("Could not find container {} for method {}", - def_id.node, method.id).index(&FullRange)); + &format!("Could not find container {} for method {}", + def_id.node, method.id)[]); } } }, None => { self.sess.span_bug(method.span, - format!("Could not find container for method {}", - method.id).index(&FullRange)); + &format!("Could not find container for method {}", + method.id)[]); }, }, }; qualname.push_str(get_ident(method.pe_ident()).get()); - let qualname = qualname.index(&FullRange); + let qualname = &qualname[]; // record the decl for this def (if it has one) let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx, @@ -430,13 +430,13 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { Some(sub_span) => self.fmt.field_str(field.span, Some(sub_span), field.node.id, - name.get().index(&FullRange), - qualname.index(&FullRange), - typ.index(&FullRange), + &name.get()[], + &qualname[], + &typ[], scope_id), None => self.sess.span_bug(field.span, - format!("Could not find sub-span for field {}", - qualname).index(&FullRange)), + &format!("Could not find sub-span for field {}", + qualname)[]), } }, _ => (), @@ -463,7 +463,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.fmt.typedef_str(full_span, Some(*param_ss), param.id, - name.index(&FullRange), + &name[], ""); } self.visit_generics(generics); @@ -480,10 +480,10 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.fmt.fn_str(item.span, sub_span, item.id, - qualname.index(&FullRange), + &qualname[], self.cur_scope); - self.process_formals(&decl.inputs, qualname.index(&FullRange)); + self.process_formals(&decl.inputs, &qualname[]); // walk arg and return types for arg in decl.inputs.iter() { @@ -497,7 +497,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { // walk the body self.nest(item.id, |v| v.visit_block(&*body)); - self.process_generic_params(ty_params, item.span, qualname.index(&FullRange), item.id); + self.process_generic_params(ty_params, item.span, &qualname[], item.id); } fn process_static(&mut self, @@ -519,9 +519,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { sub_span, item.id, get_ident(item.ident).get(), - qualname.index(&FullRange), - value.index(&FullRange), - ty_to_string(&*typ).index(&FullRange), + &qualname[], + &value[], + &ty_to_string(&*typ)[], self.cur_scope); // walk type and init value @@ -542,9 +542,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { sub_span, item.id, get_ident(item.ident).get(), - qualname.index(&FullRange), + &qualname[], "", - ty_to_string(&*typ).index(&FullRange), + &ty_to_string(&*typ)[], self.cur_scope); // walk type and init value @@ -568,17 +568,17 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { sub_span, item.id, ctor_id, - qualname.index(&FullRange), + &qualname[], self.cur_scope, - val.index(&FullRange)); + &val[]); // fields for field in def.fields.iter() { - self.process_struct_field_def(field, qualname.index(&FullRange), item.id); + self.process_struct_field_def(field, &qualname[], item.id); self.visit_ty(&*field.node.ty); } - self.process_generic_params(ty_params, item.span, qualname.index(&FullRange), item.id); + self.process_generic_params(ty_params, item.span, &qualname[], item.id); } fn process_enum(&mut self, @@ -591,12 +591,12 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { Some(sub_span) => self.fmt.enum_str(item.span, Some(sub_span), item.id, - enum_name.index(&FullRange), + &enum_name[], self.cur_scope, - val.index(&FullRange)), + &val[]), None => self.sess.span_bug(item.span, - format!("Could not find subspan for enum {}", - enum_name).index(&FullRange)), + &format!("Could not find subspan for enum {}", + enum_name)[]), } for variant in enum_definition.variants.iter() { let name = get_ident(variant.node.name); @@ -612,9 +612,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.span.span_for_first_ident(variant.span), variant.node.id, name, - qualname.index(&FullRange), - enum_name.index(&FullRange), - val.index(&FullRange), + &qualname[], + &enum_name[], + &val[], item.id); for arg in args.iter() { self.visit_ty(&*arg.ty); @@ -630,9 +630,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.span.span_for_first_ident(variant.span), variant.node.id, ctor_id, - qualname.index(&FullRange), - enum_name.index(&FullRange), - val.index(&FullRange), + &qualname[], + &enum_name[], + &val[], item.id); for field in struct_def.fields.iter() { @@ -643,7 +643,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } } - self.process_generic_params(ty_params, item.span, enum_name.index(&FullRange), item.id); + self.process_generic_params(ty_params, item.span, &enum_name[], item.id); } fn process_impl(&mut self, @@ -703,9 +703,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.fmt.trait_str(item.span, sub_span, item.id, - qualname.index(&FullRange), + &qualname[], self.cur_scope, - val.index(&FullRange)); + &val[]); // super-traits for super_bound in trait_refs.iter() { @@ -737,7 +737,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { } // walk generics and methods - self.process_generic_params(generics, item.span, qualname.index(&FullRange), item.id); + self.process_generic_params(generics, item.span, &qualname[], item.id); for method in methods.iter() { self.visit_trait_item(method) } @@ -755,9 +755,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.fmt.mod_str(item.span, sub_span, item.id, - qualname.index(&FullRange), + &qualname[], self.cur_scope, - filename.index(&FullRange)); + &filename[]); self.nest(item.id, |v| visit::walk_mod(v, m)); } @@ -840,8 +840,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { def_id, self.cur_scope), _ => self.sess.span_bug(span, - format!("Unexpected def kind while looking up path in '{}'", - self.span.snippet(span)).index(&FullRange)), + &format!("Unexpected def kind while looking up path in '{}'", + self.span.snippet(span))[]), } // modules or types in the path prefix match *def { @@ -959,7 +959,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.cur_scope); // walk receiver and args - visit::walk_exprs(self, args.index(&FullRange)); + visit::walk_exprs(self, &args[]); } fn process_pat(&mut self, p:&ast::Pat) { @@ -975,8 +975,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { Some(sd) => sd, None => { self.sess.span_bug(p.span, - format!("Could not find struct_def for `{}`", - self.span.snippet(p.span)).index(&FullRange)); + &format!("Could not find struct_def for `{}`", + self.span.snippet(p.span))[]); } }; for &Spanned { node: ref field, span } in fields.iter() { @@ -1061,8 +1061,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { self.fmt.typedef_str(item.span, sub_span, item.id, - qualname.index(&FullRange), - value.index(&FullRange)); + &qualname[], + &value[]); self.visit_ty(&**ty); self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id); @@ -1121,13 +1121,13 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { }, None => { self.sess.span_bug(method_type.span, - format!("Could not find trait for method {}", - method_type.id).index(&FullRange)); + &format!("Could not find trait for method {}", + method_type.id)[]); }, }; qualname.push_str(get_ident(method_type.ident).get()); - let qualname = qualname.index(&FullRange); + let qualname = &qualname[]; let sub_span = self.span.sub_span_after_keyword(method_type.span, keywords::Fn); self.fmt.method_decl_str(method_type.span, @@ -1262,7 +1262,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { id, cnum, name, - s.index(&FullRange), + &s[], self.cur_scope); }, } @@ -1371,8 +1371,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { } let mut id = String::from_str("$"); - id.push_str(ex.id.to_string().index(&FullRange)); - self.process_formals(&decl.inputs, id.index(&FullRange)); + id.push_str(&ex.id.to_string()[]); + self.process_formals(&decl.inputs, &id[]); // walk arg and return types for arg in decl.inputs.iter() { @@ -1418,8 +1418,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(p.span, - format!("def_map has no key for {} in visit_arm", - id).index(&FullRange)); + &format!("def_map has no key for {} in visit_arm", + id)[]); } let def = &(*def_map)[id]; match *def { @@ -1434,8 +1434,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { self.fmt.variable_str(p.span, Some(p.span), id, - path_to_string(p).index(&FullRange), - value.index(&FullRange), + &path_to_string(p)[], + &value[], "") } def::DefVariant(..) => { @@ -1490,9 +1490,9 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { self.fmt.variable_str(p.span, sub_span, id, - path_to_string(p).index(&FullRange), - value.index(&FullRange), - typ.index(&FullRange)); + &path_to_string(p)[], + &value[], + &typ[]); } self.collected_paths.clear(); @@ -1511,7 +1511,7 @@ pub fn process_crate(sess: &Session, } assert!(analysis.glob_map.is_some()); - let cratename = match attr::find_crate_name(krate.attrs.index(&FullRange)) { + let cratename = match attr::find_crate_name(&krate.attrs[]) { Some(name) => name.get().to_string(), None => { info!("Could not find crate name, using 'unknown_crate'"); @@ -1531,8 +1531,8 @@ pub fn process_crate(sess: &Session, }; match fs::mkdir_recursive(&root_path, io::USER_RWX) { - Err(e) => sess.err(format!("Could not create directory {}: {}", - root_path.display(), e).index(&FullRange)), + Err(e) => sess.err(&format!("Could not create directory {}: {}", + root_path.display(), e)[]), _ => (), } @@ -1549,7 +1549,7 @@ pub fn process_crate(sess: &Session, Ok(f) => box f, Err(e) => { let disp = root_path.display(); - sess.fatal(format!("Could not open {}: {}", disp, e).index(&FullRange)); + sess.fatal(&format!("Could not open {}: {}", disp, e)[]); } }; root_path.pop(); @@ -1575,7 +1575,7 @@ pub fn process_crate(sess: &Session, cur_scope: 0 }; - visitor.dump_crate_info(cratename.index(&FullRange), krate); + visitor.dump_crate_info(&cratename[], krate); visit::walk_crate(&mut visitor, krate); } diff --git a/src/librustc_trans/save/recorder.rs b/src/librustc_trans/save/recorder.rs index bb0fb387002..23598751c08 100644 --- a/src/librustc_trans/save/recorder.rs +++ b/src/librustc_trans/save/recorder.rs @@ -41,7 +41,7 @@ impl Recorder { assert!(self.dump_spans); let result = format!("span,kind,{},{},text,\"{}\"\n", kind, su.extent_str(span), escape(su.snippet(span))); - self.record(result.index(&FullRange)); + self.record(&result[]); } } @@ -158,17 +158,17 @@ impl<'a> FmtStrs<'a> { values: Vec<String>, span: Span) -> Option<String> { if values.len() != fields.len() { - self.span.sess.span_bug(span, format!( + self.span.sess.span_bug(span, &format!( "Mismatch between length of fields for '{}', expected '{}', found '{}'", - kind, fields.len(), values.len()).index(&FullRange)); + kind, fields.len(), values.len())[]); } let values = values.iter().map(|s| { // Never take more than 1020 chars if s.len() > 1020 { - s.index(&(0..1020)) + &s[0..1020] } else { - s.index(&FullRange) + &s[] } }); @@ -184,7 +184,7 @@ impl<'a> FmtStrs<'a> { } ))); Some(strs.fold(String::new(), |mut s, ss| { - s.push_str(ss.index(&FullRange)); + s.push_str(&ss[]); s })) } @@ -196,9 +196,9 @@ impl<'a> FmtStrs<'a> { let (label, ref fields, needs_span, dump_spans) = FmtStrs::lookup_row(kind); if needs_span { - self.span.sess.span_bug(span, format!( + self.span.sess.span_bug(span, &format!( "Called record_without_span for '{}' which does requires a span", - label).index(&FullRange)); + label)[]); } assert!(!dump_spans); @@ -212,9 +212,9 @@ impl<'a> FmtStrs<'a> { }; let mut result = String::from_str(label); - result.push_str(values_str.index(&FullRange)); + result.push_str(&values_str[]); result.push_str("\n"); - self.recorder.record(result.index(&FullRange)); + self.recorder.record(&result[]); } pub fn record_with_span(&mut self, @@ -245,7 +245,7 @@ impl<'a> FmtStrs<'a> { None => return, }; let result = format!("{},{}{}\n", label, self.span.extent_str(sub_span), values_str); - self.recorder.record(result.index(&FullRange)); + self.recorder.record(&result[]); } pub fn check_and_record(&mut self, @@ -275,7 +275,7 @@ impl<'a> FmtStrs<'a> { // variable def's node id let mut qualname = String::from_str(name); qualname.push_str("$"); - qualname.push_str(id.to_string().index(&FullRange)); + qualname.push_str(&id.to_string()[]); self.check_and_record(Variable, span, sub_span, diff --git a/src/librustc_trans/save/span_utils.rs b/src/librustc_trans/save/span_utils.rs index 8d249b8bfe9..77343612ac8 100644 --- a/src/librustc_trans/save/span_utils.rs +++ b/src/librustc_trans/save/span_utils.rs @@ -217,8 +217,8 @@ impl<'a> SpanUtils<'a> { if bracket_count != 0 { let loc = self.sess.codemap().lookup_char_pos(span.lo); self.sess.span_bug(span, - format!("Mis-counted brackets when breaking path? Parsing '{}' in {}, line {}", - self.snippet(span), loc.file.name, loc.line).index(&FullRange)); + &format!("Mis-counted brackets when breaking path? Parsing '{}' in {}, line {}", + self.snippet(span), loc.file.name, loc.line)[]); } if result.is_none() && prev.tok.is_ident() && bracket_count == 0 { return self.make_sub_span(span, Some(prev.sp)); @@ -242,9 +242,9 @@ impl<'a> SpanUtils<'a> { if ts.tok == token::Eof { if bracket_count != 0 { let loc = self.sess.codemap().lookup_char_pos(span.lo); - self.sess.span_bug(span, format!( + self.sess.span_bug(span, &format!( "Mis-counted brackets when breaking path? Parsing '{}' in {}, line {}", - self.snippet(span), loc.file.name, loc.line).index(&FullRange)); + self.snippet(span), loc.file.name, loc.line)[]); } return result } diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index 49b9ef5a40a..fc19a582db2 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -427,7 +427,7 @@ fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, let _indenter = indenter(); m.iter().filter_map(|br| { - e(br.pats.index(&FullRange)).map(|pats| { + e(&br.pats[]).map(|pats| { let this = br.pats[col]; let mut bound_ptrs = br.bound_ptrs.clone(); match this.node { @@ -471,8 +471,8 @@ fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // Collect all of the matches that can match against anything. enter_match(bcx, dm, m, col, val, |pats| { if pat_is_binding_or_wild(dm, &*pats[col]) { - let mut r = pats.index(&(0..col)).to_vec(); - r.push_all(pats.index(&((col + 1)..))); + let mut r = pats[0..col].to_vec(); + r.push_all(&pats[(col + 1)..]); Some(r) } else { None @@ -548,7 +548,7 @@ fn enter_opt<'a, 'p, 'blk, 'tcx>( param_env: param_env, }; enter_match(bcx, dm, m, col, val, |pats| - check_match::specialize(&mcx, pats.index(&FullRange), &ctor, col, variant_size) + check_match::specialize(&mcx, &pats[], &ctor, col, variant_size) ) } @@ -789,8 +789,8 @@ fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>, -> Result<'blk, 'tcx> { let did = langcall(cx, None, - format!("comparison of `{}`", - cx.ty_to_string(rhs_t)).index(&FullRange), + &format!("comparison of `{}`", + cx.ty_to_string(rhs_t))[], StrEqFnLangItem); callee::trans_lang_call(cx, did, &[lhs, rhs], None) } @@ -945,7 +945,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, if has_nested_bindings(m, col) { let expanded = expand_nested_bindings(bcx, m, col, val); compile_submatch_continue(bcx, - expanded.index(&FullRange), + &expanded[], vals, chk, col, @@ -967,7 +967,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bcx = compile_guard(bcx, &**guard_expr, m[0].data, - m.index(&(1..m.len())), + &m[1..m.len()], vals, chk, has_genuine_default); @@ -990,8 +990,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, let tcx = bcx.tcx(); let dm = &tcx.def_map; - let mut vals_left = vals.index(&(0u..col)).to_vec(); - vals_left.push_all(vals.index(&((col + 1u)..))); + let mut vals_left = vals[0u..col].to_vec(); + vals_left.push_all(&vals[(col + 1u)..]); let ccx = bcx.fcx.ccx; // Find a real id (we're adding placeholder wildcard patterns, but @@ -1191,10 +1191,10 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, } let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val); let mut opt_vals = unpacked; - opt_vals.push_all(vals_left.index(&FullRange)); + opt_vals.push_all(&vals_left[]); compile_submatch(opt_cx, - opt_ms.index(&FullRange), - opt_vals.index(&FullRange), + &opt_ms[], + &opt_vals[], branch_chk.as_ref().unwrap_or(chk), has_genuine_default); } @@ -1213,8 +1213,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, } _ => { compile_submatch(else_cx, - defaults.index(&FullRange), - vals_left.index(&FullRange), + &defaults[], + &vals_left[], chk, has_genuine_default); } @@ -1333,7 +1333,7 @@ fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat, "__llmatch"); trmode = TrByCopy(alloca_no_lifetime(bcx, llvariable_ty, - bcx.ident(ident).index(&FullRange))); + &bcx.ident(ident)[])); } ast::BindByValue(_) => { // in this case, the final type of the variable will be T, @@ -1341,13 +1341,13 @@ fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat, // above llmatch = alloca_no_lifetime(bcx, llvariable_ty.ptr_to(), - bcx.ident(ident).index(&FullRange)); + &bcx.ident(ident)[]); trmode = TrByMove; } ast::BindByRef(_) => { llmatch = alloca_no_lifetime(bcx, llvariable_ty, - bcx.ident(ident).index(&FullRange)); + &bcx.ident(ident)[]); trmode = TrByRef; } }; @@ -1415,7 +1415,7 @@ fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>, && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle) }); - compile_submatch(bcx, matches.index(&FullRange), &[discr_datum.val], &chk, has_default); + compile_submatch(bcx, &matches[], &[discr_datum.val], &chk, has_default); let mut arm_cxs = Vec::new(); for arm_data in arm_datas.iter() { @@ -1429,7 +1429,7 @@ fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>, arm_cxs.push(bcx); } - bcx = scope_cx.fcx.join_blocks(match_id, arm_cxs.index(&FullRange)); + bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[]); return bcx; } @@ -1582,7 +1582,7 @@ fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>, let var_ty = node_id_type(bcx, p_id); // Allocate memory on stack for the binding. - let llval = alloc_ty(bcx, var_ty, bcx.ident(*ident).index(&FullRange)); + let llval = alloc_ty(bcx, var_ty, &bcx.ident(*ident)[]); // Subtle: be sure that we *populate* the memory *before* // we schedule the cleanup. @@ -1619,8 +1619,8 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat.repr(bcx.tcx())); if bcx.sess().asm_comments() { - add_comment(bcx, format!("bind_irrefutable_pat(pat={})", - pat.repr(bcx.tcx())).index(&FullRange)); + add_comment(bcx, &format!("bind_irrefutable_pat(pat={})", + pat.repr(bcx.tcx()))[]); } let _indenter = indenter(); diff --git a/src/librustc_trans/trans/adt.rs b/src/librustc_trans/trans/adt.rs index 231de71848a..92883371ec9 100644 --- a/src/librustc_trans/trans/adt.rs +++ b/src/librustc_trans/trans/adt.rs @@ -51,7 +51,11 @@ use std::rc::Rc; use llvm::{ValueRef, True, IntEQ, IntNE}; use back::abi::FAT_PTR_ADDR; use middle::subst; -use middle::subst::Subst; +use middle::ty::{self, Ty, UnboxedClosureTyper}; +use middle::ty::Disr; +use syntax::ast; +use syntax::attr; +use syntax::attr::IntType; use trans::_match; use trans::build::*; use trans::cleanup; @@ -59,13 +63,9 @@ use trans::cleanup::CleanupMethods; use trans::common::*; use trans::datum; use trans::machine; +use trans::monomorphize; use trans::type_::Type; use trans::type_of; -use middle::ty::{self, Ty, UnboxedClosureTyper}; -use middle::ty::Disr; -use syntax::ast; -use syntax::attr; -use syntax::attr::IntType; use util::ppaux::ty_to_string; type Hint = attr::ReprAttr; @@ -154,28 +154,29 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Repr<'tcx> { match t.sty { ty::ty_tup(ref elems) => { - Univariant(mk_struct(cx, elems.index(&FullRange), false, t), false) + Univariant(mk_struct(cx, &elems[], false, t), false) } ty::ty_struct(def_id, substs) => { let fields = ty::lookup_struct_fields(cx.tcx(), def_id); let mut ftys = fields.iter().map(|field| { - ty::lookup_field_type(cx.tcx(), def_id, field.id, substs) + let fty = ty::lookup_field_type(cx.tcx(), def_id, field.id, substs); + monomorphize::normalize_associated_type(cx.tcx(), &fty) }).collect::<Vec<_>>(); let packed = ty::lookup_packed(cx.tcx(), def_id); let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag(); if dtor { ftys.push(cx.tcx().types.bool); } - Univariant(mk_struct(cx, ftys.index(&FullRange), packed, t), dtor) + Univariant(mk_struct(cx, &ftys[], packed, t), dtor) } ty::ty_unboxed_closure(def_id, _, substs) => { let typer = NormalizingUnboxedClosureTyper::new(cx.tcx()); let upvars = typer.unboxed_closure_upvars(def_id, substs).unwrap(); let upvar_types = upvars.iter().map(|u| u.ty).collect::<Vec<_>>(); - Univariant(mk_struct(cx, upvar_types.index(&FullRange), false, t), false) + Univariant(mk_struct(cx, &upvar_types[], false, t), false) } ty::ty_enum(def_id, substs) => { let cases = get_cases(cx.tcx(), def_id, substs); - let hint = *ty::lookup_repr_hints(cx.tcx(), def_id).index(&FullRange).get(0) + let hint = *ty::lookup_repr_hints(cx.tcx(), def_id)[].get(0) .unwrap_or(&attr::ReprAny); let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag(); @@ -185,7 +186,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // (Typechecking will reject discriminant-sizing attrs.) assert_eq!(hint, attr::ReprAny); let ftys = if dtor { vec!(cx.tcx().types.bool) } else { vec!() }; - return Univariant(mk_struct(cx, ftys.index(&FullRange), false, t), + return Univariant(mk_struct(cx, &ftys[], false, t), dtor); } @@ -205,10 +206,10 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // non-empty body, explicit discriminants should have // been rejected by a checker before this point. if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) { - cx.sess().bug(format!("non-C-like enum {} with specified \ + cx.sess().bug(&format!("non-C-like enum {} with specified \ discriminants", ty::item_path_str(cx.tcx(), - def_id)).index(&FullRange)); + def_id))[]); } if cases.len() == 1 { @@ -217,7 +218,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, assert_eq!(hint, attr::ReprAny); let mut ftys = cases[0].tys.clone(); if dtor { ftys.push(cx.tcx().types.bool); } - return Univariant(mk_struct(cx, ftys.index(&FullRange), false, t), + return Univariant(mk_struct(cx, &ftys[], false, t), dtor); } @@ -226,7 +227,7 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let mut discr = 0; while discr < 2 { if cases[1 - discr].is_zerolen(cx, t) { - let st = mk_struct(cx, cases[discr].tys.index(&FullRange), + let st = mk_struct(cx, &cases[discr].tys[], false, t); match cases[discr].find_ptr(cx) { Some(ref df) if df.len() == 1 && st.fields.len() == 1 => { @@ -316,17 +317,17 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let fields : Vec<_> = cases.iter().map(|c| { let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity)); - ftys.push_all(c.tys.index(&FullRange)); + ftys.push_all(&c.tys[]); if dtor { ftys.push(cx.tcx().types.bool); } - mk_struct(cx, ftys.index(&FullRange), false, t) + mk_struct(cx, &ftys[], false, t) }).collect(); - ensure_enum_fits_in_address_space(cx, ity, fields.index(&FullRange), t); + ensure_enum_fits_in_address_space(cx, ity, &fields[], t); General(ity, fields, dtor) } - _ => cx.sess().bug(format!("adt::represent_type called on non-ADT type: {}", - ty_to_string(cx.tcx(), t)).index(&FullRange)) + _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}", + ty_to_string(cx.tcx(), t))[]) } } @@ -412,7 +413,7 @@ fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>, impl<'tcx> Case<'tcx> { fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool { - mk_struct(cx, self.tys.index(&FullRange), false, scapegoat).size == 0 + mk_struct(cx, &self.tys[], false, scapegoat).size == 0 } fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> { @@ -432,7 +433,7 @@ fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>, -> Vec<Case<'tcx>> { ty::enum_variants(tcx, def_id).iter().map(|vi| { let arg_tys = vi.args.iter().map(|&raw_ty| { - raw_ty.subst(tcx, substs) + monomorphize::apply_param_substs(tcx, substs, &raw_ty) }).collect(); Case { discr: vi.disr_val, tys: arg_tys } }).collect() @@ -451,9 +452,9 @@ fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, .map(|&ty| type_of::sizing_type_of(cx, ty)).collect() }; - ensure_struct_fits_in_address_space(cx, lltys.index(&FullRange), packed, scapegoat); + ensure_struct_fits_in_address_space(cx, &lltys[], packed, scapegoat); - let llty_rec = Type::struct_(cx, lltys.index(&FullRange), packed); + let llty_rec = Type::struct_(cx, &lltys[], packed); Struct { size: machine::llsize_of_alloc(cx, llty_rec), align: machine::llalign_of_min(cx, llty_rec), @@ -502,7 +503,7 @@ fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntTyp return ity; } attr::ReprExtern => { - attempts = match cx.sess().target.target.arch.index(&FullRange) { + attempts = match &cx.sess().target.target.arch[] { // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32` // appears to be used on Linux and NetBSD, but some systems may use the variant // corresponding to `choose_shortest`. However, we don't run on those yet...? @@ -628,7 +629,7 @@ pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, match *r { CEnum(..) | General(..) | RawNullablePointer { .. } => { } Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } => - llty.set_struct_body(struct_llfields(cx, st, false, false).index(&FullRange), + llty.set_struct_body(&struct_llfields(cx, st, false, false)[], st.packed) } } @@ -644,7 +645,7 @@ fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } => { match name { None => { - Type::struct_(cx, struct_llfields(cx, st, sizing, dst).index(&FullRange), + Type::struct_(cx, &struct_llfields(cx, st, sizing, dst)[], st.packed) } Some(name) => { assert_eq!(sizing, false); Type::named_struct(cx, name) } @@ -663,7 +664,7 @@ fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, // of the size. // // FIXME #10604: this breaks when vector types are present. - let (size, align) = union_size_and_align(sts.index(&FullRange)); + let (size, align) = union_size_and_align(&sts[]); let align_s = align as u64; let discr_ty = ll_inttype(cx, ity); let discr_size = machine::llsize_of_alloc(cx, discr_ty); @@ -684,10 +685,10 @@ fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, Type::array(&discr_ty, align_s / discr_size - 1), fill_ty]; match name { - None => Type::struct_(cx, fields.index(&FullRange), false), + None => Type::struct_(cx, &fields[], false), Some(name) => { let mut llty = Type::named_struct(cx, name); - llty.set_struct_body(fields.index(&FullRange), false); + llty.set_struct_body(&fields[], false); llty } } @@ -765,7 +766,7 @@ pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField, scrutinee: ValueRef) -> ValueRef { - let llptrptr = GEPi(bcx, scrutinee, discrfield.index(&FullRange)); + let llptrptr = GEPi(bcx, scrutinee, &discrfield[]); let llptr = Load(bcx, llptrptr); let cmp = if nndiscr == 0 { IntEQ } else { IntNE }; ICmp(bcx, cmp, llptr, C_null(val_ty(llptr))) @@ -853,7 +854,7 @@ pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, } StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => { if discr != nndiscr { - let llptrptr = GEPi(bcx, val, discrfield.index(&FullRange)); + let llptrptr = GEPi(bcx, val, &discrfield[]); let llptrty = val_ty(llptrptr).element_type(); Store(bcx, C_null(llptrty), llptrptr) } @@ -935,7 +936,7 @@ pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, v let val = if needs_cast { let ccx = bcx.ccx(); let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>(); - let real_ty = Type::struct_(ccx, fields.index(&FullRange), st.packed); + let real_ty = Type::struct_(ccx, &fields[], st.packed); PointerCast(bcx, val, real_ty.ptr_to()) } else { val @@ -967,14 +968,14 @@ pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, for (discr, case) in cases.iter().enumerate() { let mut variant_cx = fcx.new_temp_block( - format!("enum-variant-iter-{}", discr.to_string()).index(&FullRange) + &format!("enum-variant-iter-{}", &discr.to_string())[] ); let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true); AddCase(llswitch, rhs_val, variant_cx.llbb); let fields = case.fields.iter().map(|&ty| type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>(); - let real_ty = Type::struct_(ccx, fields.index(&FullRange), case.packed); + let real_ty = Type::struct_(ccx, &fields[], case.packed); let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to()); variant_cx = f(variant_cx, case, variant_value); @@ -1051,14 +1052,14 @@ pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true); let mut f = vec![lldiscr]; f.push_all(vals); - let mut contents = build_const_struct(ccx, case, f.index(&FullRange)); + let mut contents = build_const_struct(ccx, case, &f[]); contents.push_all(&[padding(ccx, max_sz - case.size)]); - C_struct(ccx, contents.index(&FullRange), false) + C_struct(ccx, &contents[], false) } Univariant(ref st, _dro) => { assert!(discr == 0); let contents = build_const_struct(ccx, st, vals); - C_struct(ccx, contents.index(&FullRange), st.packed) + C_struct(ccx, &contents[], st.packed) } RawNullablePointer { nndiscr, nnty, .. } => { if discr == nndiscr { @@ -1070,9 +1071,9 @@ pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr } StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => { if discr == nndiscr { - C_struct(ccx, build_const_struct(ccx, + C_struct(ccx, &build_const_struct(ccx, nonnull, - vals).index(&FullRange), + vals)[], false) } else { let vals = nonnull.fields.iter().map(|&ty| { @@ -1080,9 +1081,9 @@ pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr // field; see #8506. C_null(type_of::sizing_type_of(ccx, ty)) }).collect::<Vec<ValueRef>>(); - C_struct(ccx, build_const_struct(ccx, + C_struct(ccx, &build_const_struct(ccx, nonnull, - vals.index(&FullRange)).index(&FullRange), + &vals[])[], false) } } diff --git a/src/librustc_trans/trans/asm.rs b/src/librustc_trans/trans/asm.rs index 890f046be1b..9b6fa32405f 100644 --- a/src/librustc_trans/trans/asm.rs +++ b/src/librustc_trans/trans/asm.rs @@ -71,7 +71,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm) callee::DontAutorefArg) }) }).collect::<Vec<_>>(); - inputs.push_all(ext_inputs.index(&FullRange)); + inputs.push_all(&ext_inputs[]); // no failure occurred preparing operands, no need to cleanup fcx.pop_custom_cleanup_scope(temp_scope); @@ -91,18 +91,18 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm) if !clobbers.is_empty() { clobbers.push(','); } - clobbers.push_str(more_clobbers.index(&FullRange)); + clobbers.push_str(&more_clobbers[]); } // Add the clobbers to our constraints list if clobbers.len() != 0 && constraints.len() != 0 { constraints.push(','); - constraints.push_str(clobbers.index(&FullRange)); + constraints.push_str(&clobbers[]); } else { - constraints.push_str(clobbers.index(&FullRange)); + constraints.push_str(&clobbers[]); } - debug!("Asm Constraints: {}", constraints.index(&FullRange)); + debug!("Asm Constraints: {}", &constraints[]); let num_outputs = outputs.len(); @@ -112,7 +112,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm) } else if num_outputs == 1 { output_types[0] } else { - Type::struct_(bcx.ccx(), output_types.index(&FullRange), false) + Type::struct_(bcx.ccx(), &output_types[], false) }; let dialect = match ia.dialect { diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 057d0f378e6..88ce36a710a 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -249,7 +249,7 @@ fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>, let f = decl_rust_fn(ccx, fn_ty, name); csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| { - set_llvm_fn_attrs(ccx, attrs.index(&FullRange), f) + set_llvm_fn_attrs(ccx, &attrs[], f) }); ccx.externs().borrow_mut().insert(name.to_string(), f); @@ -281,8 +281,15 @@ pub fn kind_for_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId) pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>, name: &str) -> ValueRef { + debug!("decl_rust_fn(fn_ty={}, name={:?})", + fn_ty.repr(ccx.tcx()), + name); + let fn_ty = monomorphize::normalize_associated_type(ccx.tcx(), &fn_ty); + debug!("decl_rust_fn: fn_ty={} (after normalized associated types)", + fn_ty.repr(ccx.tcx())); + let function_type; // placeholder so that the memory ownership works out ok let (sig, abi, env) = match fn_ty.sty { @@ -305,10 +312,12 @@ pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let sig = ty::erase_late_bound_regions(ccx.tcx(), sig); let sig = ty::Binder(sig); + debug!("decl_rust_fn: sig={} (after erasing regions)", + sig.repr(ccx.tcx())); + let llfty = type_of_rust_fn(ccx, env, &sig, abi); - debug!("decl_rust_fn(sig={}, type={})", - sig.repr(ccx.tcx()), + debug!("decl_rust_fn: llfty={}", ccx.tn().type_to_string(llfty)); let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, sig.0.output /* (1) */); @@ -372,9 +381,9 @@ fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, match bcx.tcx().lang_items.require(it) { Ok(id) => id, Err(s) => { - bcx.sess().fatal(format!("allocation of `{}` {}", + bcx.sess().fatal(&format!("allocation of `{}` {}", bcx.ty_to_string(info_ty), - s).index(&FullRange)); + s)[]); } } } @@ -493,7 +502,7 @@ pub fn unset_split_stack(f: ValueRef) { // silently mangles such symbols, breaking our linkage model. pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) { if ccx.all_llvm_symbols().borrow().contains(&sym) { - ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).index(&FullRange)); + ccx.sess().bug(&format!("duplicate LLVM symbol: {}", sym)[]); } ccx.all_llvm_symbols().borrow_mut().insert(sym); } @@ -530,7 +539,7 @@ pub fn get_res_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty::mk_nil(ccx.tcx())); get_extern_fn(ccx, &mut *ccx.externs().borrow_mut(), - name.index(&FullRange), + &name[], llvm::CCallConv, llty, dtor_ty) @@ -778,9 +787,9 @@ pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>, for variant in (*variants).iter() { let variant_cx = fcx.new_temp_block( - format!("enum-iter-variant-{}", - variant.disr_val.to_string().index(&FullRange)) - .index(&FullRange)); + &format!("enum-iter-variant-{}", + &variant.disr_val.to_string()[]) + []); match adt::trans_case(cx, &*repr, variant.disr_val) { _match::SingleResult(r) => { AddCase(llswitch, r.val, variant_cx.llbb) @@ -804,8 +813,8 @@ pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>, } } _ => { - cx.sess().unimpl(format!("type in iter_structural_ty: {}", - ty_to_string(cx.tcx(), t)).index(&FullRange)) + cx.sess().unimpl(&format!("type in iter_structural_ty: {}", + ty_to_string(cx.tcx(), t))[]) } } return cx; @@ -886,8 +895,8 @@ pub fn fail_if_zero_or_overflows<'blk, 'tcx>( (ICmp(cx, llvm::IntEQ, rhs, zero), false) } _ => { - cx.sess().bug(format!("fail-if-zero on unexpected type: {}", - ty_to_string(cx.tcx(), rhs_t)).index(&FullRange)); + cx.sess().bug(&format!("fail-if-zero on unexpected type: {}", + ty_to_string(cx.tcx(), rhs_t))[]); } }; let bcx = with_cond(cx, is_zero, |bcx| { @@ -908,8 +917,8 @@ pub fn fail_if_zero_or_overflows<'blk, 'tcx>( ty::ty_int(t) => { let llty = Type::int_from_ty(cx.ccx(), t); let min = match t { - ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64, - ast::TyIs => i64::MIN as u64, + ast::TyIs(_) if llty == Type::i32(cx.ccx()) => i32::MIN as u64, + ast::TyIs(_) => i64::MIN as u64, ast::TyI8 => i8::MIN as u64, ast::TyI16 => i16::MIN as u64, ast::TyI32 => i32::MIN as u64, @@ -941,14 +950,14 @@ pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty::ty_bare_fn(_, ref fn_ty) => { match ccx.sess().target.target.adjust_abi(fn_ty.abi) { Rust | RustCall => { - get_extern_rust_fn(ccx, t, name.index(&FullRange), did) + get_extern_rust_fn(ccx, t, &name[], did) } RustIntrinsic => { ccx.sess().bug("unexpected intrinsic in trans_external_path") } _ => { foreign::register_foreign_item_fn(ccx, fn_ty.abi, t, - name.index(&FullRange)) + &name[]) } } } @@ -995,7 +1004,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let llresult = Invoke(bcx, llfn, - llargs.index(&FullRange), + &llargs[], normal_bcx.llbb, landing_pad, Some(attributes)); @@ -1011,7 +1020,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, None => debuginfo::clear_source_location(bcx.fcx) }; - let llresult = Call(bcx, llfn, llargs.index(&FullRange), Some(attributes)); + let llresult = Call(bcx, llfn, &llargs[], Some(attributes)); return (llresult, bcx); } } @@ -1128,7 +1137,7 @@ pub fn call_lifetime_end(cx: Block, ptr: ValueRef) { pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) { let _icx = push_ctxt("call_memcpy"); let ccx = cx.ccx(); - let key = match ccx.sess().target.target.target_word_size.index(&FullRange) { + let key = match &ccx.sess().target.target.target_pointer_width[] { "32" => "llvm.memcpy.p0i8.p0i8.i32", "64" => "llvm.memcpy.p0i8.p0i8.i64", tws => panic!("Unsupported target word size for memcpy: {}", tws), @@ -1175,7 +1184,7 @@ fn memzero<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>) { let llty = type_of::type_of(ccx, ty); - let intrinsic_key = match ccx.sess().target.target.target_word_size.index(&FullRange) { + let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[] { "32" => "llvm.memset.p0i8.i32", "64" => "llvm.memset.p0i8.i64", tws => panic!("Unsupported target word size for memset: {}", tws), @@ -1663,7 +1672,7 @@ fn copy_unboxed_closure_args_to_allocas<'blk, 'tcx>( "argtuple", arg_scope_id)); let untupled_arg_types = match monomorphized_arg_types[0].sty { - ty::ty_tup(ref types) => types.index(&FullRange), + ty::ty_tup(ref types) => &types[], _ => { bcx.tcx().sess.span_bug(args[0].pat.span, "first arg to `rust-call` ABI function \ @@ -1851,12 +1860,12 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let arg_datums = if abi != RustCall { create_datums_for_fn_args(&fcx, - monomorphized_arg_types.index(&FullRange)) + &monomorphized_arg_types[]) } else { create_datums_for_fn_args_under_call_abi( bcx, arg_scope, - monomorphized_arg_types.index(&FullRange)) + &monomorphized_arg_types[]) }; bcx = match closure_env.kind { @@ -1864,16 +1873,16 @@ pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>, copy_args_to_allocas(&fcx, arg_scope, bcx, - decl.inputs.index(&FullRange), + &decl.inputs[], arg_datums) } closure::UnboxedClosure(..) => { copy_unboxed_closure_args_to_allocas( bcx, arg_scope, - decl.inputs.index(&FullRange), + &decl.inputs[], arg_datums, - monomorphized_arg_types.index(&FullRange)) + &monomorphized_arg_types[]) } }; @@ -1990,9 +1999,9 @@ pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap() } _ => ccx.sess().bug( - format!("trans_enum_variant_constructor: \ + &format!("trans_enum_variant_constructor: \ unexpected ctor return type {}", - ctor_ty.repr(tcx)).index(&FullRange)) + ctor_ty.repr(tcx))[]) }; // Get location to store the result. If the user does not care about @@ -2015,7 +2024,7 @@ pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, bcx = expr::trans_adt(bcx, result_ty, disr, - fields.index(&FullRange), + &fields[], None, expr::SaveIn(llresult), call_info); @@ -2064,9 +2073,9 @@ fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output()) } _ => ccx.sess().bug( - format!("trans_enum_variant_or_tuple_like_struct: \ + &format!("trans_enum_variant_or_tuple_like_struct: \ unexpected ctor return type {}", - ty_to_string(ccx.tcx(), ctor_ty)).index(&FullRange)) + ty_to_string(ccx.tcx(), ctor_ty))[]) }; let arena = TypedArena::new(); @@ -2080,7 +2089,7 @@ fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx ty::erase_late_bound_regions( ccx.tcx(), &ty::ty_fn_args(ctor_ty)); - let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.index(&FullRange)); + let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[]); if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) { let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot"); @@ -2164,9 +2173,9 @@ fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, // pass for the latter already ran. lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES, *lvlsrc.unwrap(), Some(sp), - format!("enum variant is more than three times larger \ + &format!("enum variant is more than three times larger \ ({} bytes) than the next largest (ignoring padding)", - largest).index(&FullRange)); + largest)[]); ccx.sess().span_note(enum_def.variants[largest_index].span, "this variant is the largest"); @@ -2284,7 +2293,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { match item.node { ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => { if !generics.is_type_parameterized() { - let trans_everywhere = attr::requests_inline(item.attrs.index(&FullRange)); + let trans_everywhere = attr::requests_inline(&item.attrs[]); // Ignore `trans_everywhere` for cross-crate inlined items // (`from_external`). `trans_item` will be called once for each // compilation unit that references the item, so it will still get @@ -2295,7 +2304,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { foreign::trans_rust_fn_with_foreign_abi(ccx, &**decl, &**body, - item.attrs.index(&FullRange), + &item.attrs[], llfn, &Substs::trans_empty(), item.id, @@ -2307,7 +2316,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { llfn, &Substs::trans_empty(), item.id, - item.attrs.index(&FullRange)); + &item.attrs[]); } update_linkage(ccx, llfn, @@ -2324,7 +2333,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => { meth::trans_impl(ccx, item.ident, - impl_items.index(&FullRange), + &impl_items[], generics, item.id); } @@ -2354,7 +2363,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { // Do static_assert checking. It can't really be done much earlier // because we need to get the value of the bool out of LLVM - if attr::contains_name(item.attrs.index(&FullRange), "static_assert") { + if attr::contains_name(&item.attrs[], "static_assert") { if m == ast::MutMutable { ccx.sess().span_fatal(expr.span, "cannot have static_assert on a mutable \ @@ -2431,7 +2440,7 @@ fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, _ => panic!("expected bare rust fn") }; - let llfn = decl_rust_fn(ccx, node_type, sym.index(&FullRange)); + let llfn = decl_rust_fn(ccx, node_type, &sym[]); finish_register_fn(ccx, sp, sym, node_id, llfn); llfn } @@ -2476,7 +2485,7 @@ pub fn get_fn_llvm_attributes<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty< match fn_sig.inputs[1].sty { ty::ty_tup(ref t_in) => { - inputs.push_all(t_in.index(&FullRange)); + inputs.push_all(&t_in[]); inputs } _ => ccx.sess().bug("expected tuple'd inputs") @@ -2612,7 +2621,7 @@ pub fn register_fn_llvmty(ccx: &CrateContext, debug!("register_fn_llvmty id={} sym={}", node_id, sym); let llfn = decl_fn(ccx, - sym.index(&FullRange), + &sym[], cc, llfty, ty::FnConverging(ty::mk_nil(ccx.tcx()))); @@ -2668,7 +2677,7 @@ pub fn create_entry_wrapper(ccx: &CrateContext, let (start_fn, args) = if use_start_lang_item { let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) { Ok(id) => id, - Err(s) => { ccx.sess().fatal(s.index(&FullRange)); } + Err(s) => { ccx.sess().fatal(&s[]); } }; let start_fn = if start_def_id.krate == ast::LOCAL_CRATE { get_item_val(ccx, start_def_id.node) @@ -2760,7 +2769,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { let val = match item { ast_map::NodeItem(i) => { let ty = ty::node_id_to_type(ccx.tcx(), i.id); - let sym = |&:| exported_name(ccx, id, ty, i.attrs.index(&FullRange)); + let sym = |&:| exported_name(ccx, id, ty, &i.attrs[]); let v = match i.node { ast::ItemStatic(_, _, ref expr) => { @@ -2783,16 +2792,16 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } else { llvm::LLVMTypeOf(v) }; - if contains_null(sym.index(&FullRange)) { + if contains_null(&sym[]) { ccx.sess().fatal( - format!("Illegal null byte in export_name \ - value: `{}`", sym).index(&FullRange)); + &format!("Illegal null byte in export_name \ + value: `{}`", sym)[]); } let buf = CString::from_slice(sym.as_bytes()); let g = llvm::LLVMAddGlobal(ccx.llmod(), llty, buf.as_ptr()); - if attr::contains_name(i.attrs.index(&FullRange), + if attr::contains_name(&i.attrs[], "thread_local") { llvm::set_thread_local(g, true); } @@ -2817,19 +2826,19 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { sym, i.id) }; - set_llvm_fn_attrs(ccx, i.attrs.index(&FullRange), llfn); + set_llvm_fn_attrs(ccx, &i.attrs[], llfn); llfn } _ => panic!("get_item_val: weird result in table") }; - match attr::first_attr_value_str_by_name(i.attrs.index(&FullRange), + match attr::first_attr_value_str_by_name(&i.attrs[], "link_section") { Some(sect) => { if contains_null(sect.get()) { - ccx.sess().fatal(format!("Illegal null byte in link_section value: `{}`", - sect.get()).index(&FullRange)); + ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", + sect.get())[]); } unsafe { let buf = CString::from_slice(sect.get().as_bytes()); @@ -2872,7 +2881,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { let abi = ccx.tcx().map.get_foreign_abi(id); let ty = ty::node_id_to_type(ccx.tcx(), ni.id); let name = foreign::link_name(&*ni); - foreign::register_foreign_item_fn(ccx, abi, ty, name.get().index(&FullRange)) + foreign::register_foreign_item_fn(ccx, abi, ty, &name.get()[]) } ast::ForeignItemStatic(..) => { foreign::register_static(ccx, &*ni) @@ -2895,7 +2904,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { let sym = exported_name(ccx, id, ty, - enm.attrs.index(&FullRange)); + &enm.attrs[]); llfn = match enm.node { ast::ItemEnum(_, _) => { @@ -2922,8 +2931,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { let sym = exported_name(ccx, id, ty, - struct_item.attrs - .index(&FullRange)); + &struct_item.attrs[]); let llfn = register_fn(ccx, struct_item.span, sym, ctor_id, ty); set_inline_hint(llfn); @@ -2931,8 +2939,8 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } ref variant => { - ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}", - variant).index(&FullRange)) + ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}", + variant)[]) } }; @@ -2953,10 +2961,10 @@ fn register_method(ccx: &CrateContext, id: ast::NodeId, m: &ast::Method) -> ValueRef { let mty = ty::node_id_to_type(ccx.tcx(), id); - let sym = exported_name(ccx, id, mty, m.attrs.index(&FullRange)); + let sym = exported_name(ccx, id, mty, &m.attrs[]); let llfn = register_fn(ccx, m.span, sym, id, mty); - set_llvm_fn_attrs(ccx, m.attrs.index(&FullRange), llfn); + set_llvm_fn_attrs(ccx, &m.attrs[], llfn); llfn } @@ -2995,7 +3003,7 @@ pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> { Some(compressed) => compressed, None => cx.sess().fatal("failed to compress metadata"), }.as_slice()); - let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.index(&FullRange)); + let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[]); let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false); let name = format!("rust_metadata_{}_{}", cx.link_meta().crate_name, @@ -3124,7 +3132,7 @@ pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>) let link_meta = link::build_link_meta(&tcx.sess, krate, name); let codegen_units = tcx.sess.opts.cg.codegen_units; - let shared_ccx = SharedCrateContext::new(link_meta.crate_name.index(&FullRange), + let shared_ccx = SharedCrateContext::new(&link_meta.crate_name[], codegen_units, tcx, export_map, @@ -3226,7 +3234,7 @@ pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>) llmod: shared_ccx.metadata_llmod(), }; let formats = shared_ccx.tcx().dependency_formats.borrow().clone(); - let no_builtins = attr::contains_name(krate.attrs.index(&FullRange), "no_builtins"); + let no_builtins = attr::contains_name(&krate.attrs[], "no_builtins"); let translation = CrateTranslation { modules: modules, diff --git a/src/librustc_trans/trans/builder.rs b/src/librustc_trans/trans/builder.rs index d0eaf799af1..b80088e4690 100644 --- a/src/librustc_trans/trans/builder.rs +++ b/src/librustc_trans/trans/builder.rs @@ -552,11 +552,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs.iter()) { *small_vec_e = C_i32(self.ccx, ix as i32); } - self.inbounds_gep(base, small_vec.index(&(0..ixs.len()))) + self.inbounds_gep(base, &small_vec[0..ixs.len()]) } else { let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>(); self.count_insn("gepi"); - self.inbounds_gep(base, v.index(&FullRange)) + self.inbounds_gep(base, &v[]) } } @@ -764,8 +764,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let s = format!("{} ({})", text, self.ccx.sess().codemap().span_to_string(sp)); - debug!("{}", s.index(&FullRange)); - self.add_comment(s.index(&FullRange)); + debug!("{}", &s[]); + self.add_comment(&s[]); } } @@ -802,7 +802,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }).collect::<Vec<_>>(); debug!("Asm Output Type: {}", self.ccx.tn().type_to_string(output)); - let fty = Type::func(argtys.index(&FullRange), &output); + let fty = Type::func(&argtys[], &output); unsafe { let v = llvm::LLVMInlineAsm( fty.to_ref(), asm, cons, volatile, alignstack, dia as c_uint); diff --git a/src/librustc_trans/trans/cabi.rs b/src/librustc_trans/trans/cabi.rs index a901142467b..8a2a2534cab 100644 --- a/src/librustc_trans/trans/cabi.rs +++ b/src/librustc_trans/trans/cabi.rs @@ -108,7 +108,7 @@ pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { - match ccx.sess().target.target.arch.index(&FullRange) { + match &ccx.sess().target.target.arch[] { "x86" => cabi_x86::compute_abi_info(ccx, atys, rty, ret_def), "x86_64" => if ccx.sess().target.target.options.is_like_windows { cabi_x86_win64::compute_abi_info(ccx, atys, rty, ret_def) @@ -118,7 +118,7 @@ pub fn compute_abi_info(ccx: &CrateContext, "arm" => cabi_arm::compute_abi_info(ccx, atys, rty, ret_def), "aarch64" => cabi_aarch64::compute_abi_info(ccx, atys, rty, ret_def), "mips" => cabi_mips::compute_abi_info(ccx, atys, rty, ret_def), - a => ccx.sess().fatal((format!("unrecognized arch \"{}\" in target specification", a)) - .index(&FullRange)), + a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a) + []), } } diff --git a/src/librustc_trans/trans/cabi_x86_64.rs b/src/librustc_trans/trans/cabi_x86_64.rs index f40072d1cba..86190b1e566 100644 --- a/src/librustc_trans/trans/cabi_x86_64.rs +++ b/src/librustc_trans/trans/cabi_x86_64.rs @@ -318,7 +318,7 @@ fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type { tys.push(Type::i64(ccx)); } SSEFv => { - let vec_len = llvec_len(cls.index(&((i + 1u)..))); + let vec_len = llvec_len(&cls[(i + 1u)..]); let vec_ty = Type::vector(&Type::f32(ccx), (vec_len * 2u) as u64); tys.push(vec_ty); i += vec_len; diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index b7b486f1d0a..6196f9e5eab 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -112,9 +112,9 @@ fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr) _ => { bcx.tcx().sess.span_bug( expr.span, - format!("type of callee is neither bare-fn nor closure: \ + &format!("type of callee is neither bare-fn nor closure: \ {}", - bcx.ty_to_string(datum.ty)).index(&FullRange)); + bcx.ty_to_string(datum.ty))[]); } } } @@ -206,8 +206,8 @@ fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr) def::DefSelfTy(..) | def::DefAssociatedPath(..) => { bcx.tcx().sess.span_bug( ref_expr.span, - format!("cannot translate def {:?} \ - to a callable thing!", def).index(&FullRange)); + &format!("cannot translate def {:?} \ + to a callable thing!", def)[]); } } } @@ -265,7 +265,7 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>( let _icx = push_ctxt("trans_fn_pointer_shim"); let tcx = ccx.tcx(); - let bare_fn_ty = normalize_ty(tcx, bare_fn_ty); + let bare_fn_ty = erase_regions(tcx, &bare_fn_ty); match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty) { Some(&llval) => { return llval; } None => { } @@ -289,8 +289,8 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>( } _ => { - tcx.sess.bug(format!("trans_fn_pointer_shim invoked on invalid type: {}", - bare_fn_ty.repr(tcx)).index(&FullRange)); + tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}", + bare_fn_ty.repr(tcx))[]); } }; let sig = ty::erase_late_bound_regions(tcx, sig); @@ -315,7 +315,7 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>( let llfn = decl_internal_rust_fn(ccx, tuple_fn_ty, - function_name.index(&FullRange)); + &function_name[]); // let block_arena = TypedArena::new(); @@ -350,7 +350,7 @@ pub fn trans_fn_pointer_shim<'a, 'tcx>( None, bare_fn_ty, |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) }, - ArgVals(llargs.index(&FullRange)), + ArgVals(&llargs[]), dest).bcx; finish_fn(&fcx, bcx, sig.output); @@ -776,7 +776,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, // Invoke the actual rust fn and update bcx/llresult. let (llret, b) = base::invoke(bcx, llfn, - llargs.index(&FullRange), + &llargs[], callee_ty, call_info); bcx = b; @@ -815,7 +815,7 @@ pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, bcx = foreign::trans_native_call(bcx, callee_ty, llfn, opt_llretslot.unwrap(), - llargs.index(&FullRange), arg_tys); + &llargs[], arg_tys); } fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope); diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 92a96cd02b5..5658889aaf3 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -403,8 +403,8 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { } self.ccx.sess().bug( - format!("no cleanup scope {} found", - self.ccx.tcx().map.node_to_string(cleanup_scope)).index(&FullRange)); + &format!("no cleanup scope {} found", + self.ccx.tcx().map.node_to_string(cleanup_scope))[]); } /// Schedules a cleanup to occur in the top-most scope, which must be a temporary scope. @@ -584,9 +584,9 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx } LoopExit(id, _) => { - self.ccx.sess().bug(format!( + self.ccx.sess().bug(&format!( "cannot exit from scope {}, \ - not in scope", id).index(&FullRange)); + not in scope", id)[]); } } } @@ -655,7 +655,7 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx let name = scope.block_name("clean"); debug!("generating cleanups for {}", name); let bcx_in = self.new_block(label.is_unwind(), - name.index(&FullRange), + &name[], None); let mut bcx_out = bcx_in; for cleanup in scope.cleanups.iter().rev() { @@ -702,7 +702,7 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx Some(llbb) => { return llbb; } None => { let name = last_scope.block_name("unwind"); - pad_bcx = self.new_block(true, name.index(&FullRange), None); + pad_bcx = self.new_block(true, &name[], None); last_scope.cached_landing_pad = Some(pad_bcx.llbb); } } @@ -1022,8 +1022,8 @@ pub fn temporary_scope(tcx: &ty::ctxt, r } None => { - tcx.sess.bug(format!("no temporary scope available for expr {}", - id).index(&FullRange)) + tcx.sess.bug(&format!("no temporary scope available for expr {}", + id)[]) } } } diff --git a/src/librustc_trans/trans/closure.rs b/src/librustc_trans/trans/closure.rs index ad2ed67b22c..8989dfd4932 100644 --- a/src/librustc_trans/trans/closure.rs +++ b/src/librustc_trans/trans/closure.rs @@ -154,7 +154,7 @@ pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let tcx = ccx.tcx(); // compute the type of the closure - let cdata_ty = mk_closure_tys(tcx, bound_values.index(&FullRange)); + let cdata_ty = mk_closure_tys(tcx, &bound_values[]); // cbox_ty has the form of a tuple: (a, b, c) we want a ptr to a // tuple. This could be a ptr in uniq or a box or on stack, @@ -182,8 +182,8 @@ pub fn store_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, debug!("Copy {} into closure", bv.to_string(ccx)); if ccx.sess().asm_comments() { - add_comment(bcx, format!("Copy {} into closure", - bv.to_string(ccx)).index(&FullRange)); + add_comment(bcx, &format!("Copy {} into closure", + bv.to_string(ccx))[]); } let bound_data = GEPi(bcx, llbox, &[0u, abi::BOX_FIELD_BODY, i]); @@ -420,7 +420,7 @@ pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let s = tcx.map.with_path(id, |path| { mangle_internal_name_by_path_and_seq(path, "closure") }); - let llfn = decl_internal_rust_fn(ccx, fty, s.index(&FullRange)); + let llfn = decl_internal_rust_fn(ccx, fty, &s[]); // set an inline hint for all closures set_inline_hint(llfn); @@ -444,7 +444,7 @@ pub fn trans_expr_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, &[], ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fty)), ty::ty_fn_abi(fty), - ClosureEnv::new(freevars.index(&FullRange), + ClosureEnv::new(&freevars[], BoxedClosure(cdata_ty, store))); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx @@ -466,7 +466,7 @@ pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext // Normalize type so differences in regions and typedefs don't cause // duplicate declarations - let function_type = normalize_ty(ccx.tcx(), function_type); + let function_type = erase_regions(ccx.tcx(), &function_type); let params = match function_type.sty { ty::ty_unboxed_closure(_, _, ref substs) => substs.types.clone(), _ => unreachable!() @@ -489,7 +489,7 @@ pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext mangle_internal_name_by_path_and_seq(path, "unboxed_closure") }); - let llfn = decl_internal_rust_fn(ccx, function_type, symbol.index(&FullRange)); + let llfn = decl_internal_rust_fn(ccx, function_type, &symbol[]); // set an inline hint for all closures set_inline_hint(llfn); @@ -544,7 +544,7 @@ pub fn trans_unboxed_closure<'blk, 'tcx>( &[], sig.output, function_type.abi, - ClosureEnv::new(freevars.index(&FullRange), + ClosureEnv::new(&freevars[], UnboxedClosure(freevar_mode))); // Don't hoist this to the top of the function. It's perfectly legitimate diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 237fc185636..3afd33d324d 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -50,7 +50,7 @@ use std::vec::Vec; use syntax::ast::Ident; use syntax::ast; use syntax::ast_map::{PathElem, PathName}; -use syntax::codemap::Span; +use syntax::codemap::{DUMMY_SP, Span}; use syntax::parse::token::InternedString; use syntax::parse::token; use util::common::memoized; @@ -58,16 +58,21 @@ use util::nodemap::FnvHashSet; pub use trans::context::CrateContext; -/// Returns an equivalent type with all the typedefs and self regions removed. -pub fn normalize_ty<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - let u = TypeNormalizer(cx).fold_ty(ty); - debug!("normalize_ty({}) = {}", - ty.repr(cx), u.repr(cx)); - return u; +/// Returns an equivalent value with all free regions removed (note +/// that late-bound regions remain, because they are important for +/// subtyping, but they are anonymized and normalized as well). This +/// is a stronger, caching version of `ty_fold::erase_regions`. +pub fn erase_regions<'tcx,T>(cx: &ty::ctxt<'tcx>, value: &T) -> T + where T : TypeFoldable<'tcx> + Repr<'tcx> +{ + let value1 = value.fold_with(&mut RegionEraser(cx)); + debug!("erase_regions({}) = {}", + value.repr(cx), value1.repr(cx)); + return value1; - struct TypeNormalizer<'a, 'tcx: 'a>(&'a ty::ctxt<'tcx>); + struct RegionEraser<'a, 'tcx: 'a>(&'a ty::ctxt<'tcx>); - impl<'a, 'tcx> TypeFolder<'tcx> for TypeNormalizer<'a, 'tcx> { + impl<'a, 'tcx> TypeFolder<'tcx> for RegionEraser<'a, 'tcx> { fn tcx(&self) -> &ty::ctxt<'tcx> { self.0 } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { @@ -84,7 +89,6 @@ pub fn normalize_ty<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T> where T : TypeFoldable<'tcx> + Repr<'tcx> { - // FIXME(#20526) this should replace `enter_region_binder`/`exit_region_binder`. let u = ty::anonymize_late_bound_regions(self.tcx(), t); ty_fold::super_fold_binder(self, &u) } @@ -114,149 +118,150 @@ pub fn normalize_ty<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { } // Is the type's representation size known at compile time? -pub fn type_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { -ty::type_contents(cx, ty).is_sized(cx) +pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { + let param_env = ty::empty_parameter_environment(tcx); + ty::type_is_sized(¶m_env, DUMMY_SP, ty) } pub fn lltype_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { -match ty.sty { - ty::ty_open(_) => true, - _ => type_is_sized(cx, ty), -} + match ty.sty { + ty::ty_open(_) => true, + _ => type_is_sized(cx, ty), + } } pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { -match ty.sty { - ty::ty_ptr(ty::mt{ty, ..}) | - ty::ty_rptr(_, ty::mt{ty, ..}) | - ty::ty_uniq(ty) => { - !type_is_sized(cx, ty) - } - _ => { - false + match ty.sty { + ty::ty_ptr(ty::mt{ty, ..}) | + ty::ty_rptr(_, ty::mt{ty, ..}) | + ty::ty_uniq(ty) => { + !type_is_sized(cx, ty) + } + _ => { + false + } } } -} // Return the smallest part of `ty` which is unsized. Fails if `ty` is sized. // 'Smallest' here means component of the static representation of the type; not // the size of an object at runtime. pub fn unsized_part_of_type<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { -match ty.sty { - ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty, - ty::ty_struct(def_id, substs) => { - let unsized_fields: Vec<_> = - ty::struct_fields(cx, def_id, substs) - .iter() - .map(|f| f.mt.ty) - .filter(|ty| !type_is_sized(cx, *ty)) - .collect(); - - // Exactly one of the fields must be unsized. - assert!(unsized_fields.len() == 1); - - unsized_part_of_type(cx, unsized_fields[0]) - } - _ => { - assert!(type_is_sized(cx, ty), - "unsized_part_of_type failed even though ty is unsized"); - panic!("called unsized_part_of_type with sized ty"); + match ty.sty { + ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty, + ty::ty_struct(def_id, substs) => { + let unsized_fields: Vec<_> = + ty::struct_fields(cx, def_id, substs) + .iter() + .map(|f| f.mt.ty) + .filter(|ty| !type_is_sized(cx, *ty)) + .collect(); + + // Exactly one of the fields must be unsized. + assert!(unsized_fields.len() == 1); + + unsized_part_of_type(cx, unsized_fields[0]) + } + _ => { + assert!(type_is_sized(cx, ty), + "unsized_part_of_type failed even though ty is unsized"); + panic!("called unsized_part_of_type with sized ty"); + } } } -} // Some things don't need cleanups during unwinding because the // task can free them all at once later. Currently only things // that only contain scalars and shared boxes can avoid unwind // cleanups. pub fn type_needs_unwind_cleanup<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { -return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| { - type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet::new()) -}); - -fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>, - ty: Ty<'tcx>, - tycache: &mut FnvHashSet<Ty<'tcx>>) - -> bool -{ - // Prevent infinite recursion - if !tycache.insert(ty) { - return false; - } - - let mut needs_unwind_cleanup = false; - ty::maybe_walk_ty(ty, |ty| { - needs_unwind_cleanup |= match ty.sty { - ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) | - ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false, + return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| { + type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet::new()) + }); - ty::ty_enum(did, substs) => - ty::enum_variants(tcx, did).iter().any(|v| - v.args.iter().any(|&aty| { - let t = aty.subst(tcx, substs); - type_needs_unwind_cleanup_(tcx, t, tycache) - }) - ), + fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>, + ty: Ty<'tcx>, + tycache: &mut FnvHashSet<Ty<'tcx>>) + -> bool + { + // Prevent infinite recursion + if !tycache.insert(ty) { + return false; + } - _ => true - }; - !needs_unwind_cleanup - }); - needs_unwind_cleanup -} + let mut needs_unwind_cleanup = false; + ty::maybe_walk_ty(ty, |ty| { + needs_unwind_cleanup |= match ty.sty { + ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) | + ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false, + + ty::ty_enum(did, substs) => + ty::enum_variants(tcx, did).iter().any(|v| + v.args.iter().any(|&aty| { + let t = aty.subst(tcx, substs); + type_needs_unwind_cleanup_(tcx, t, tycache) + }) + ), + + _ => true + }; + !needs_unwind_cleanup + }); + needs_unwind_cleanup + } } pub fn type_needs_drop<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { -ty::type_contents(cx, ty).needs_drop(cx) + ty::type_contents(cx, ty).needs_drop(cx) } fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { -match ty.sty { - ty::ty_struct(def_id, substs) => { - let fields = ty::struct_fields(ccx.tcx(), def_id, substs); - fields.len() == 1 && - fields[0].name == - token::special_idents::unnamed_field.name && - type_is_immediate(ccx, fields[0].mt.ty) + match ty.sty { + ty::ty_struct(def_id, substs) => { + let fields = ty::struct_fields(ccx.tcx(), def_id, substs); + fields.len() == 1 && + fields[0].name == + token::special_idents::unnamed_field.name && + type_is_immediate(ccx, fields[0].mt.ty) + } + _ => false } - _ => false -} } pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { -use trans::machine::llsize_of_alloc; -use trans::type_of::sizing_type_of; - -let tcx = ccx.tcx(); -let simple = ty::type_is_scalar(ty) || - ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) || - type_is_newtype_immediate(ccx, ty) || - ty::type_is_simd(tcx, ty); -if simple && !type_is_fat_ptr(tcx, ty) { - return true; -} -if !type_is_sized(tcx, ty) { - return false; -} -match ty.sty { - ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | - ty::ty_unboxed_closure(..) => { - let llty = sizing_type_of(ccx, ty); - llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type()) + use trans::machine::llsize_of_alloc; + use trans::type_of::sizing_type_of; + + let tcx = ccx.tcx(); + let simple = ty::type_is_scalar(ty) || + ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) || + type_is_newtype_immediate(ccx, ty) || + ty::type_is_simd(tcx, ty); + if simple && !type_is_fat_ptr(tcx, ty) { + return true; + } + if !type_is_sized(tcx, ty) { + return false; + } + match ty.sty { + ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | + ty::ty_unboxed_closure(..) => { + let llty = sizing_type_of(ccx, ty); + llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type()) + } + _ => type_is_zero_size(ccx, ty) } - _ => type_is_zero_size(ccx, ty) -} } /// Identify types which have size zero at runtime. pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { -use trans::machine::llsize_of_alloc; -use trans::type_of::sizing_type_of; -let llty = sizing_type_of(ccx, ty); -llsize_of_alloc(ccx, llty) == 0 + use trans::machine::llsize_of_alloc; + use trans::type_of::sizing_type_of; + let llty = sizing_type_of(ccx, ty); + llsize_of_alloc(ccx, llty) == 0 } /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function @@ -264,25 +269,25 @@ llsize_of_alloc(ccx, llty) == 0 /// zero-size, but not all zero-size types use a `void` return type (in order to aid with C ABI /// compatibility). pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool { -ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty) + ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty) } /// Generates a unique symbol based off the name given. This is used to create /// unique symbols for things like closures. pub fn gensym_name(name: &str) -> PathElem { -let num = token::gensym(name).uint(); -// use one colon which will get translated to a period by the mangler, and -// we're guaranteed that `num` is globally unique for this crate. -PathName(token::gensym(format!("{}:{}", name, num).index(&FullRange))) + let num = token::gensym(name).uint(); + // use one colon which will get translated to a period by the mangler, and + // we're guaranteed that `num` is globally unique for this crate. + PathName(token::gensym(&format!("{}:{}", name, num)[])) } #[derive(Copy)] pub struct tydesc_info<'tcx> { -pub ty: Ty<'tcx>, -pub tydesc: ValueRef, -pub size: ValueRef, -pub align: ValueRef, -pub name: ValueRef, + pub ty: Ty<'tcx>, + pub tydesc: ValueRef, + pub size: ValueRef, + pub align: ValueRef, + pub name: ValueRef, } /* @@ -313,36 +318,36 @@ pub name: ValueRef, #[derive(Copy)] pub struct NodeInfo { -pub id: ast::NodeId, -pub span: Span, + pub id: ast::NodeId, + pub span: Span, } pub fn expr_info(expr: &ast::Expr) -> NodeInfo { -NodeInfo { id: expr.id, span: expr.span } + NodeInfo { id: expr.id, span: expr.span } } pub struct BuilderRef_res { -pub b: BuilderRef, + pub b: BuilderRef, } impl Drop for BuilderRef_res { -fn drop(&mut self) { - unsafe { - llvm::LLVMDisposeBuilder(self.b); + fn drop(&mut self) { + unsafe { + llvm::LLVMDisposeBuilder(self.b); + } } } -} pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res { -BuilderRef_res { - b: b -} + BuilderRef_res { + b: b + } } pub type ExternMap = FnvHashMap<String, ValueRef>; pub fn validate_substs(substs: &Substs) { -assert!(substs.types.all(|t| !ty::type_needs_infer(*t))); + assert!(substs.types.all(|t| !ty::type_needs_infer(*t))); } // work around bizarre resolve errors @@ -352,183 +357,183 @@ type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>; // Function context. Every LLVM function we create will have one of // these. pub struct FunctionContext<'a, 'tcx: 'a> { -// The ValueRef returned from a call to llvm::LLVMAddFunction; the -// address of the first instruction in the sequence of -// instructions for this function that will go in the .text -// section of the executable we're generating. -pub llfn: ValueRef, + // The ValueRef returned from a call to llvm::LLVMAddFunction; the + // address of the first instruction in the sequence of + // instructions for this function that will go in the .text + // section of the executable we're generating. + pub llfn: ValueRef, -// always an empty parameter-environment -pub param_env: ty::ParameterEnvironment<'a, 'tcx>, + // always an empty parameter-environment + pub param_env: ty::ParameterEnvironment<'a, 'tcx>, -// The environment argument in a closure. -pub llenv: Option<ValueRef>, + // The environment argument in a closure. + pub llenv: Option<ValueRef>, -// A pointer to where to store the return value. If the return type is -// immediate, this points to an alloca in the function. Otherwise, it's a -// pointer to the hidden first parameter of the function. After function -// construction, this should always be Some. -pub llretslotptr: Cell<Option<ValueRef>>, + // A pointer to where to store the return value. If the return type is + // immediate, this points to an alloca in the function. Otherwise, it's a + // pointer to the hidden first parameter of the function. After function + // construction, this should always be Some. + pub llretslotptr: Cell<Option<ValueRef>>, -// These pub elements: "hoisted basic blocks" containing -// administrative activities that have to happen in only one place in -// the function, due to LLVM's quirks. -// A marker for the place where we want to insert the function's static -// allocas, so that LLVM will coalesce them into a single alloca call. -pub alloca_insert_pt: Cell<Option<ValueRef>>, -pub llreturn: Cell<Option<BasicBlockRef>>, + // These pub elements: "hoisted basic blocks" containing + // administrative activities that have to happen in only one place in + // the function, due to LLVM's quirks. + // A marker for the place where we want to insert the function's static + // allocas, so that LLVM will coalesce them into a single alloca call. + pub alloca_insert_pt: Cell<Option<ValueRef>>, + pub llreturn: Cell<Option<BasicBlockRef>>, -// If the function has any nested return's, including something like: -// fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then -// we use a separate alloca for each return -pub needs_ret_allocas: bool, + // If the function has any nested return's, including something like: + // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then + // we use a separate alloca for each return + pub needs_ret_allocas: bool, -// The a value alloca'd for calls to upcalls.rust_personality. Used when -// outputting the resume instruction. -pub personality: Cell<Option<ValueRef>>, + // The a value alloca'd for calls to upcalls.rust_personality. Used when + // outputting the resume instruction. + pub personality: Cell<Option<ValueRef>>, -// True if the caller expects this fn to use the out pointer to -// return. Either way, your code should write into the slot llretslotptr -// points to, but if this value is false, that slot will be a local alloca. -pub caller_expects_out_pointer: bool, + // True if the caller expects this fn to use the out pointer to + // return. Either way, your code should write into the slot llretslotptr + // points to, but if this value is false, that slot will be a local alloca. + pub caller_expects_out_pointer: bool, -// Maps the DefId's for local variables to the allocas created for -// them in llallocas. -pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>, + // Maps the DefId's for local variables to the allocas created for + // them in llallocas. + pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>, -// Same as above, but for closure upvars -pub llupvars: RefCell<NodeMap<ValueRef>>, + // Same as above, but for closure upvars + pub llupvars: RefCell<NodeMap<ValueRef>>, -// The NodeId of the function, or -1 if it doesn't correspond to -// a user-defined function. -pub id: ast::NodeId, + // The NodeId of the function, or -1 if it doesn't correspond to + // a user-defined function. + pub id: ast::NodeId, -// If this function is being monomorphized, this contains the type -// substitutions used. -pub param_substs: &'a Substs<'tcx>, + // If this function is being monomorphized, this contains the type + // substitutions used. + pub param_substs: &'a Substs<'tcx>, -// The source span and nesting context where this function comes from, for -// error reporting and symbol generation. -pub span: Option<Span>, + // The source span and nesting context where this function comes from, for + // error reporting and symbol generation. + pub span: Option<Span>, -// The arena that blocks are allocated from. -pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>, + // The arena that blocks are allocated from. + pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>, -// This function's enclosing crate context. -pub ccx: &'a CrateContext<'a, 'tcx>, + // This function's enclosing crate context. + pub ccx: &'a CrateContext<'a, 'tcx>, -// Used and maintained by the debuginfo module. -pub debug_context: debuginfo::FunctionDebugContext, + // Used and maintained by the debuginfo module. + pub debug_context: debuginfo::FunctionDebugContext, -// Cleanup scopes. -pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>, + // Cleanup scopes. + pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>, -pub cfg: Option<cfg::CFG>, + pub cfg: Option<cfg::CFG>, } impl<'a, 'tcx> FunctionContext<'a, 'tcx> { -pub fn arg_pos(&self, arg: uint) -> uint { - let arg = self.env_arg_pos() + arg; - if self.llenv.is_some() { - arg + 1 - } else { - arg + pub fn arg_pos(&self, arg: uint) -> uint { + let arg = self.env_arg_pos() + arg; + if self.llenv.is_some() { + arg + 1 + } else { + arg + } } -} -pub fn env_arg_pos(&self) -> uint { - if self.caller_expects_out_pointer { - 1u - } else { - 0u + pub fn env_arg_pos(&self) -> uint { + if self.caller_expects_out_pointer { + 1u + } else { + 0u + } } -} -pub fn cleanup(&self) { - unsafe { - llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt - .get() - .unwrap()); + pub fn cleanup(&self) { + unsafe { + llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt + .get() + .unwrap()); + } } -} -pub fn get_llreturn(&self) -> BasicBlockRef { - if self.llreturn.get().is_none() { + pub fn get_llreturn(&self) -> BasicBlockRef { + if self.llreturn.get().is_none() { - self.llreturn.set(Some(unsafe { - llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, - "return\0".as_ptr() as *const _) - })) - } + self.llreturn.set(Some(unsafe { + llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, + "return\0".as_ptr() as *const _) + })) + } - self.llreturn.get().unwrap() -} + self.llreturn.get().unwrap() + } -pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>, - output: ty::FnOutput<'tcx>, - name: &str) -> ValueRef { - if self.needs_ret_allocas { - base::alloca_no_lifetime(bcx, match output { - ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type), - ty::FnDiverging => Type::void(bcx.ccx()) - }, name) - } else { - self.llretslotptr.get().unwrap() + pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>, + output: ty::FnOutput<'tcx>, + name: &str) -> ValueRef { + if self.needs_ret_allocas { + base::alloca_no_lifetime(bcx, match output { + ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type), + ty::FnDiverging => Type::void(bcx.ccx()) + }, name) + } else { + self.llretslotptr.get().unwrap() + } } -} -pub fn new_block(&'a self, - is_lpad: bool, - name: &str, - opt_node_id: Option<ast::NodeId>) - -> Block<'a, 'tcx> { - unsafe { - let name = CString::from_slice(name.as_bytes()); - let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), - self.llfn, - name.as_ptr()); - BlockS::new(llbb, is_lpad, opt_node_id, self) + pub fn new_block(&'a self, + is_lpad: bool, + name: &str, + opt_node_id: Option<ast::NodeId>) + -> Block<'a, 'tcx> { + unsafe { + let name = CString::from_slice(name.as_bytes()); + let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), + self.llfn, + name.as_ptr()); + BlockS::new(llbb, is_lpad, opt_node_id, self) + } } -} -pub fn new_id_block(&'a self, - name: &str, - node_id: ast::NodeId) - -> Block<'a, 'tcx> { - self.new_block(false, name, Some(node_id)) -} + pub fn new_id_block(&'a self, + name: &str, + node_id: ast::NodeId) + -> Block<'a, 'tcx> { + self.new_block(false, name, Some(node_id)) + } -pub fn new_temp_block(&'a self, - name: &str) - -> Block<'a, 'tcx> { - self.new_block(false, name, None) -} + pub fn new_temp_block(&'a self, + name: &str) + -> Block<'a, 'tcx> { + self.new_block(false, name, None) + } -pub fn join_blocks(&'a self, - id: ast::NodeId, - in_cxs: &[Block<'a, 'tcx>]) - -> Block<'a, 'tcx> { - let out = self.new_id_block("join", id); - let mut reachable = false; - for bcx in in_cxs.iter() { - if !bcx.unreachable.get() { - build::Br(*bcx, out.llbb); - reachable = true; + pub fn join_blocks(&'a self, + id: ast::NodeId, + in_cxs: &[Block<'a, 'tcx>]) + -> Block<'a, 'tcx> { + let out = self.new_id_block("join", id); + let mut reachable = false; + for bcx in in_cxs.iter() { + if !bcx.unreachable.get() { + build::Br(*bcx, out.llbb); + reachable = true; + } } + if !reachable { + build::Unreachable(out); + } + return out; } - if !reachable { - build::Unreachable(out); - } - return out; -} -pub fn monomorphize<T>(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone -{ - monomorphize::apply_param_substs(self.ccx.tcx(), - self.param_substs, - value) -} + pub fn monomorphize<T>(&self, value: &T) -> T + where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone + { + monomorphize::apply_param_substs(self.ccx.tcx(), + self.param_substs, + value) + } } // Basic block context. We create a block context for each basic block @@ -537,277 +542,277 @@ pub fn monomorphize<T>(&self, value: &T) -> T // with many basic blocks per function. All the basic blocks attached to a // function are organized as a directed graph. pub struct BlockS<'blk, 'tcx: 'blk> { -// The BasicBlockRef returned from a call to -// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic -// block to the function pointed to by llfn. We insert -// instructions into that block by way of this block context. -// The block pointing to this one in the function's digraph. -pub llbb: BasicBlockRef, -pub terminated: Cell<bool>, -pub unreachable: Cell<bool>, + // The BasicBlockRef returned from a call to + // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic + // block to the function pointed to by llfn. We insert + // instructions into that block by way of this block context. + // The block pointing to this one in the function's digraph. + pub llbb: BasicBlockRef, + pub terminated: Cell<bool>, + pub unreachable: Cell<bool>, -// Is this block part of a landing pad? -pub is_lpad: bool, + // Is this block part of a landing pad? + pub is_lpad: bool, -// AST node-id associated with this block, if any. Used for -// debugging purposes only. -pub opt_node_id: Option<ast::NodeId>, + // AST node-id associated with this block, if any. Used for + // debugging purposes only. + pub opt_node_id: Option<ast::NodeId>, -// The function context for the function to which this block is -// attached. -pub fcx: &'blk FunctionContext<'blk, 'tcx>, + // The function context for the function to which this block is + // attached. + pub fcx: &'blk FunctionContext<'blk, 'tcx>, } pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>; impl<'blk, 'tcx> BlockS<'blk, 'tcx> { -pub fn new(llbb: BasicBlockRef, - is_lpad: bool, - opt_node_id: Option<ast::NodeId>, - fcx: &'blk FunctionContext<'blk, 'tcx>) - -> Block<'blk, 'tcx> { - fcx.block_arena.alloc(BlockS { - llbb: llbb, - terminated: Cell::new(false), - unreachable: Cell::new(false), - is_lpad: is_lpad, - opt_node_id: opt_node_id, - fcx: fcx - }) -} + pub fn new(llbb: BasicBlockRef, + is_lpad: bool, + opt_node_id: Option<ast::NodeId>, + fcx: &'blk FunctionContext<'blk, 'tcx>) + -> Block<'blk, 'tcx> { + fcx.block_arena.alloc(BlockS { + llbb: llbb, + terminated: Cell::new(false), + unreachable: Cell::new(false), + is_lpad: is_lpad, + opt_node_id: opt_node_id, + fcx: fcx + }) + } -pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> { - self.fcx.ccx -} -pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> { - self.fcx.ccx.tcx() -} -pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() } + pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> { + self.fcx.ccx + } + pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> { + self.fcx.ccx.tcx() + } + pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() } -pub fn ident(&self, ident: Ident) -> String { - token::get_ident(ident).get().to_string() -} + pub fn ident(&self, ident: Ident) -> String { + token::get_ident(ident).get().to_string() + } -pub fn node_id_to_string(&self, id: ast::NodeId) -> String { - self.tcx().map.node_to_string(id).to_string() -} + pub fn node_id_to_string(&self, id: ast::NodeId) -> String { + self.tcx().map.node_to_string(id).to_string() + } -pub fn expr_to_string(&self, e: &ast::Expr) -> String { - e.repr(self.tcx()) -} + pub fn expr_to_string(&self, e: &ast::Expr) -> String { + e.repr(self.tcx()) + } -pub fn def(&self, nid: ast::NodeId) -> def::Def { - match self.tcx().def_map.borrow().get(&nid) { - Some(v) => v.clone(), - None => { - self.tcx().sess.bug(format!( - "no def associated with node id {}", nid).index(&FullRange)); + pub fn def(&self, nid: ast::NodeId) -> def::Def { + match self.tcx().def_map.borrow().get(&nid) { + Some(v) => v.clone(), + None => { + self.tcx().sess.bug(&format!( + "no def associated with node id {}", nid)[]); + } } } -} -pub fn val_to_string(&self, val: ValueRef) -> String { - self.ccx().tn().val_to_string(val) -} + pub fn val_to_string(&self, val: ValueRef) -> String { + self.ccx().tn().val_to_string(val) + } -pub fn llty_str(&self, ty: Type) -> String { - self.ccx().tn().type_to_string(ty) -} + pub fn llty_str(&self, ty: Type) -> String { + self.ccx().tn().type_to_string(ty) + } -pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { - t.repr(self.tcx()) -} + pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { + t.repr(self.tcx()) + } -pub fn to_str(&self) -> String { - format!("[block {:p}]", self) -} + pub fn to_str(&self) -> String { + format!("[block {:p}]", self) + } -pub fn monomorphize<T>(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone -{ - monomorphize::apply_param_substs(self.tcx(), - self.fcx.param_substs, - value) -} + pub fn monomorphize<T>(&self, value: &T) -> T + where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone + { + monomorphize::apply_param_substs(self.tcx(), + self.fcx.param_substs, + value) + } } impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> { -fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { - self.tcx() -} + fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { + self.tcx() + } -fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> { - Ok(node_id_type(self, id)) -} + fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> { + Ok(node_id_type(self, id)) + } -fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> { - Ok(expr_ty_adjusted(self, expr)) -} + fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> { + Ok(expr_ty_adjusted(self, expr)) + } -fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> { - self.tcx() - .method_map - .borrow() - .get(&method_call) - .map(|method| monomorphize_type(self, method.ty)) -} + fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> { + self.tcx() + .method_map + .borrow() + .get(&method_call) + .map(|method| monomorphize_type(self, method.ty)) + } -fn node_method_origin(&self, method_call: ty::MethodCall) - -> Option<ty::MethodOrigin<'tcx>> -{ - self.tcx() - .method_map - .borrow() - .get(&method_call) - .map(|method| method.origin.clone()) -} + fn node_method_origin(&self, method_call: ty::MethodCall) + -> Option<ty::MethodOrigin<'tcx>> + { + self.tcx() + .method_map + .borrow() + .get(&method_call) + .map(|method| method.origin.clone()) + } -fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> { - &self.tcx().adjustments -} + fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> { + &self.tcx().adjustments + } -fn is_method_call(&self, id: ast::NodeId) -> bool { - self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id)) -} + fn is_method_call(&self, id: ast::NodeId) -> bool { + self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id)) + } -fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> { - self.tcx().region_maps.temporary_scope(rvalue_id) -} + fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> { + self.tcx().region_maps.temporary_scope(rvalue_id) + } -fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> { - Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone()) -} + fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> { + Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone()) + } -fn capture_mode(&self, closure_expr_id: ast::NodeId) - -> ast::CaptureClause { - self.tcx().capture_modes.borrow()[closure_expr_id].clone() -} + fn capture_mode(&self, closure_expr_id: ast::NodeId) + -> ast::CaptureClause { + self.tcx().capture_modes.borrow()[closure_expr_id].clone() + } -fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool { - self.fcx.param_env.type_moves_by_default(span, ty) -} + fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool { + self.fcx.param_env.type_moves_by_default(span, ty) + } } impl<'blk, 'tcx> ty::UnboxedClosureTyper<'tcx> for BlockS<'blk, 'tcx> { -fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> { - &self.fcx.param_env -} + fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> { + &self.fcx.param_env + } -fn unboxed_closure_kind(&self, - def_id: ast::DefId) - -> ty::UnboxedClosureKind -{ - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_kind(def_id) -} + fn unboxed_closure_kind(&self, + def_id: ast::DefId) + -> ty::UnboxedClosureKind + { + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_kind(def_id) + } -fn unboxed_closure_type(&self, - def_id: ast::DefId, - substs: &subst::Substs<'tcx>) - -> ty::ClosureTy<'tcx> -{ - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_type(def_id, substs) -} + fn unboxed_closure_type(&self, + def_id: ast::DefId, + substs: &subst::Substs<'tcx>) + -> ty::ClosureTy<'tcx> + { + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_type(def_id, substs) + } -fn unboxed_closure_upvars(&self, - def_id: ast::DefId, - substs: &Substs<'tcx>) - -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>> -{ - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_upvars(def_id, substs) -} + fn unboxed_closure_upvars(&self, + def_id: ast::DefId, + substs: &Substs<'tcx>) + -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>> + { + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_upvars(def_id, substs) + } } pub struct Result<'blk, 'tcx: 'blk> { -pub bcx: Block<'blk, 'tcx>, -pub val: ValueRef + pub bcx: Block<'blk, 'tcx>, + pub val: ValueRef } impl<'b, 'tcx> Result<'b, 'tcx> { -pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> { - Result { - bcx: bcx, - val: val, + pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> { + Result { + bcx: bcx, + val: val, + } } } -} pub fn val_ty(v: ValueRef) -> Type { -unsafe { - Type::from_ref(llvm::LLVMTypeOf(v)) -} + unsafe { + Type::from_ref(llvm::LLVMTypeOf(v)) + } } // LLVM constant constructors. pub fn C_null(t: Type) -> ValueRef { -unsafe { - llvm::LLVMConstNull(t.to_ref()) -} + unsafe { + llvm::LLVMConstNull(t.to_ref()) + } } pub fn C_undef(t: Type) -> ValueRef { -unsafe { - llvm::LLVMGetUndef(t.to_ref()) -} + unsafe { + llvm::LLVMGetUndef(t.to_ref()) + } } pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef { -unsafe { - llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool) -} + unsafe { + llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool) + } } pub fn C_floating(s: &str, t: Type) -> ValueRef { -unsafe { - let s = CString::from_slice(s.as_bytes()); - llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr()) -} + unsafe { + let s = CString::from_slice(s.as_bytes()); + llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr()) + } } pub fn C_nil(ccx: &CrateContext) -> ValueRef { -C_struct(ccx, &[], false) + C_struct(ccx, &[], false) } pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef { -C_integral(Type::i1(ccx), val as u64, false) + C_integral(Type::i1(ccx), val as u64, false) } pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { -C_integral(Type::i32(ccx), i as u64, true) + C_integral(Type::i32(ccx), i as u64, true) } pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef { -C_integral(Type::i64(ccx), i as u64, true) + C_integral(Type::i64(ccx), i as u64, true) } pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { -C_integral(Type::i64(ccx), i, false) + C_integral(Type::i64(ccx), i, false) } pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef { -let v = i.as_i64(); + let v = i.as_i64(); -match machine::llbitsize_of_real(ccx, ccx.int_type()) { - 32 => assert!(v < (1<<31) && v >= -(1<<31)), - 64 => {}, - n => panic!("unsupported target size: {}", n) -} + match machine::llbitsize_of_real(ccx, ccx.int_type()) { + 32 => assert!(v < (1<<31) && v >= -(1<<31)), + 64 => {}, + n => panic!("unsupported target size: {}", n) + } -C_integral(ccx.int_type(), v as u64, true) + C_integral(ccx.int_type(), v as u64, true) } pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef { -let v = i.as_u64(); + let v = i.as_u64(); -match machine::llbitsize_of_real(ccx, ccx.int_type()) { - 32 => assert!(v < (1<<32)), - 64 => {}, - n => panic!("unsupported target size: {}", n) -} + match machine::llbitsize_of_real(ccx, ccx.int_type()) { + 32 => assert!(v < (1<<32)), + 64 => {}, + n => panic!("unsupported target size: {}", n) + } -C_integral(ccx.int_type(), v, false) + C_integral(ccx.int_type(), v, false) } pub trait AsI64 { fn as_i64(self) -> i64; } @@ -824,157 +829,157 @@ impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }} impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }} pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef { -C_integral(Type::i8(ccx), i as u64, false) + C_integral(Type::i8(ccx), i as u64, false) } // This is a 'c-like' raw string, which differs from // our boxed-and-length-annotated strings. pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef { -unsafe { - match cx.const_cstr_cache().borrow().get(&s) { - Some(&llval) => return llval, - None => () - } + unsafe { + match cx.const_cstr_cache().borrow().get(&s) { + Some(&llval) => return llval, + None => () + } - let sc = llvm::LLVMConstStringInContext(cx.llcx(), - s.get().as_ptr() as *const c_char, - s.get().len() as c_uint, - !null_terminated as Bool); + let sc = llvm::LLVMConstStringInContext(cx.llcx(), + s.get().as_ptr() as *const c_char, + s.get().len() as c_uint, + !null_terminated as Bool); - let gsym = token::gensym("str"); - let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes()); - let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr()); - llvm::LLVMSetInitializer(g, sc); - llvm::LLVMSetGlobalConstant(g, True); - llvm::SetLinkage(g, llvm::InternalLinkage); + let gsym = token::gensym("str"); + let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes()); + let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr()); + llvm::LLVMSetInitializer(g, sc); + llvm::LLVMSetGlobalConstant(g, True); + llvm::SetLinkage(g, llvm::InternalLinkage); - cx.const_cstr_cache().borrow_mut().insert(s, g); - g -} + cx.const_cstr_cache().borrow_mut().insert(s, g); + g + } } // NB: Do not use `do_spill_noroot` to make this into a constant string, or // you will be kicked off fast isel. See issue #4352 for an example of this. pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef { -let len = s.get().len(); -let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx)); -C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)]) + let len = s.get().len(); + let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx)); + C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)]) } pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef { -unsafe { - let len = data.len(); - let lldata = C_bytes(cx, data); - - let gsym = token::gensym("binary"); - let name = format!("binary{}", gsym.uint()); - let name = CString::from_vec(name.into_bytes()); - let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), - name.as_ptr()); - llvm::LLVMSetInitializer(g, lldata); - llvm::LLVMSetGlobalConstant(g, True); - llvm::SetLinkage(g, llvm::InternalLinkage); - - let cs = consts::ptrcast(g, Type::i8p(cx)); - C_struct(cx, &[cs, C_uint(cx, len)], false) -} + unsafe { + let len = data.len(); + let lldata = C_bytes(cx, data); + + let gsym = token::gensym("binary"); + let name = format!("binary{}", gsym.uint()); + let name = CString::from_vec(name.into_bytes()); + let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), + name.as_ptr()); + llvm::LLVMSetInitializer(g, lldata); + llvm::LLVMSetGlobalConstant(g, True); + llvm::SetLinkage(g, llvm::InternalLinkage); + + let cs = consts::ptrcast(g, Type::i8p(cx)); + C_struct(cx, &[cs, C_uint(cx, len)], false) + } } pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef { -C_struct_in_context(cx.llcx(), elts, packed) + C_struct_in_context(cx.llcx(), elts, packed) } pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef { -unsafe { - llvm::LLVMConstStructInContext(llcx, - elts.as_ptr(), elts.len() as c_uint, - packed as Bool) -} + unsafe { + llvm::LLVMConstStructInContext(llcx, + elts.as_ptr(), elts.len() as c_uint, + packed as Bool) + } } pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef { -unsafe { - llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint) -} + unsafe { + llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint) + } } pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef { -unsafe { - return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint); -} + unsafe { + return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint); + } } pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef { -C_bytes_in_context(cx.llcx(), bytes) + C_bytes_in_context(cx.llcx(), bytes) } pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef { -unsafe { - let ptr = bytes.as_ptr() as *const c_char; - return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True); -} + unsafe { + let ptr = bytes.as_ptr() as *const c_char; + return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True); + } } pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint]) -> ValueRef { -unsafe { - let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); + unsafe { + let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); - debug!("const_get_elt(v={}, us={:?}, r={})", - cx.tn().val_to_string(v), us, cx.tn().val_to_string(r)); + debug!("const_get_elt(v={}, us={:?}, r={})", + cx.tn().val_to_string(v), us, cx.tn().val_to_string(r)); - return r; -} + return r; + } } pub fn is_const(v: ValueRef) -> bool { -unsafe { - llvm::LLVMIsConstant(v) == True -} + unsafe { + llvm::LLVMIsConstant(v) == True + } } pub fn const_to_int(v: ValueRef) -> i64 { -unsafe { - llvm::LLVMConstIntGetSExtValue(v) -} + unsafe { + llvm::LLVMConstIntGetSExtValue(v) + } } pub fn const_to_uint(v: ValueRef) -> u64 { -unsafe { - llvm::LLVMConstIntGetZExtValue(v) -} + unsafe { + llvm::LLVMConstIntGetZExtValue(v) + } } pub fn is_undef(val: ValueRef) -> bool { -unsafe { - llvm::LLVMIsUndef(val) != False -} + unsafe { + llvm::LLVMIsUndef(val) != False + } } #[allow(dead_code)] // potentially useful pub fn is_null(val: ValueRef) -> bool { -unsafe { - llvm::LLVMIsNull(val) != False -} + unsafe { + llvm::LLVMIsNull(val) != False + } } pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> { -bcx.fcx.monomorphize(&t) + bcx.fcx.monomorphize(&t) } pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> { -let tcx = bcx.tcx(); -let t = ty::node_id_to_type(tcx, id); -monomorphize_type(bcx, t) + let tcx = bcx.tcx(); + let t = ty::node_id_to_type(tcx, id); + monomorphize_type(bcx, t) } pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> { -node_id_type(bcx, ex.id) + node_id_type(bcx, ex.id) } pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> { -monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex)) + monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex)) } /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we @@ -985,117 +990,117 @@ pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) -> traits::Vtable<'tcx, ()> { -let tcx = ccx.tcx(); - -// Remove any references to regions; this helps improve caching. -let trait_ref = ty_fold::erase_regions(tcx, trait_ref); - -// First check the cache. -match ccx.trait_cache().borrow().get(&trait_ref) { - Some(vtable) => { - info!("Cache hit: {}", trait_ref.repr(ccx.tcx())); - return (*vtable).clone(); - } - None => { } -} - -debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx())); - -ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id()); -let infcx = infer::new_infer_ctxt(tcx); - -// Do the initial selection for the obligation. This yields the -// shallow result we are looking for -- that is, what specific impl. -let typer = NormalizingUnboxedClosureTyper::new(tcx); -let mut selcx = traits::SelectionContext::new(&infcx, &typer); -let obligation = traits::Obligation::new(traits::ObligationCause::dummy(), - trait_ref.to_poly_trait_predicate()); -let selection = match selcx.select(&obligation) { - Ok(Some(selection)) => selection, - Ok(None) => { - // Ambiguity can happen when monomorphizing during trans - // expands to some humongo type that never occurred - // statically -- this humongo type can then overflow, - // leading to an ambiguous result. So report this as an - // overflow bug, since I believe this is the only case - // where ambiguity can result. - debug!("Encountered ambiguity selecting `{}` during trans, \ - presuming due to overflow", - trait_ref.repr(tcx)); - ccx.sess().span_fatal( - span, - "reached the recursion limit during monomorphization"); - } - Err(e) => { - tcx.sess.span_bug( - span, - format!("Encountered error `{}` selecting `{}` during trans", - e.repr(tcx), - trait_ref.repr(tcx)).index(&FullRange)) - } -}; - -// Currently, we use a fulfillment context to completely resolve -// all nested obligations. This is because they can inform the -// inference of the impl's type parameters. -let mut fulfill_cx = traits::FulfillmentContext::new(); -let vtable = selection.map_move_nested(|predicate| { - fulfill_cx.register_predicate_obligation(&infcx, predicate); -}); -let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable); - -info!("Cache miss: {}", trait_ref.repr(ccx.tcx())); -ccx.trait_cache().borrow_mut().insert(trait_ref, - vtable.clone()); - -vtable + let tcx = ccx.tcx(); + + // Remove any references to regions; this helps improve caching. + let trait_ref = erase_regions(tcx, &trait_ref); + + // First check the cache. + match ccx.trait_cache().borrow().get(&trait_ref) { + Some(vtable) => { + info!("Cache hit: {}", trait_ref.repr(ccx.tcx())); + return (*vtable).clone(); + } + None => { } + } + + debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx())); + + ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id()); + let infcx = infer::new_infer_ctxt(tcx); + + // Do the initial selection for the obligation. This yields the + // shallow result we are looking for -- that is, what specific impl. + let typer = NormalizingUnboxedClosureTyper::new(tcx); + let mut selcx = traits::SelectionContext::new(&infcx, &typer); + let obligation = traits::Obligation::new(traits::ObligationCause::dummy(), + trait_ref.to_poly_trait_predicate()); + let selection = match selcx.select(&obligation) { + Ok(Some(selection)) => selection, + Ok(None) => { + // Ambiguity can happen when monomorphizing during trans + // expands to some humongo type that never occurred + // statically -- this humongo type can then overflow, + // leading to an ambiguous result. So report this as an + // overflow bug, since I believe this is the only case + // where ambiguity can result. + debug!("Encountered ambiguity selecting `{}` during trans, \ + presuming due to overflow", + trait_ref.repr(tcx)); + ccx.sess().span_fatal( + span, + "reached the recursion limit during monomorphization"); + } + Err(e) => { + tcx.sess.span_bug( + span, + &format!("Encountered error `{}` selecting `{}` during trans", + e.repr(tcx), + trait_ref.repr(tcx))[]) + } + }; + + // Currently, we use a fulfillment context to completely resolve + // all nested obligations. This is because they can inform the + // inference of the impl's type parameters. + let mut fulfill_cx = traits::FulfillmentContext::new(); + let vtable = selection.map_move_nested(|predicate| { + fulfill_cx.register_predicate_obligation(&infcx, predicate); + }); + let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable); + + info!("Cache miss: {}", trait_ref.repr(ccx.tcx())); + ccx.trait_cache().borrow_mut().insert(trait_ref, + vtable.clone()); + + vtable } pub struct NormalizingUnboxedClosureTyper<'a,'tcx:'a> { -param_env: ty::ParameterEnvironment<'a, 'tcx> + param_env: ty::ParameterEnvironment<'a, 'tcx> } impl<'a,'tcx> NormalizingUnboxedClosureTyper<'a,'tcx> { -pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> { - // Parameter environment is used to give details about type parameters, - // but since we are in trans, everything is fully monomorphized. - NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) } -} + pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> { + // Parameter environment is used to give details about type parameters, + // but since we are in trans, everything is fully monomorphized. + NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) } + } } impl<'a,'tcx> ty::UnboxedClosureTyper<'tcx> for NormalizingUnboxedClosureTyper<'a,'tcx> { -fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> { - &self.param_env -} + fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> { + &self.param_env + } -fn unboxed_closure_kind(&self, - def_id: ast::DefId) - -> ty::UnboxedClosureKind -{ - self.param_env.tcx.unboxed_closure_kind(def_id) -} + fn unboxed_closure_kind(&self, + def_id: ast::DefId) + -> ty::UnboxedClosureKind + { + self.param_env.tcx.unboxed_closure_kind(def_id) + } -fn unboxed_closure_type(&self, - def_id: ast::DefId, - substs: &subst::Substs<'tcx>) - -> ty::ClosureTy<'tcx> -{ - // the substitutions in `substs` are already monomorphized, - // but we still must normalize associated types - let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs); - monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty) -} + fn unboxed_closure_type(&self, + def_id: ast::DefId, + substs: &subst::Substs<'tcx>) + -> ty::ClosureTy<'tcx> + { + // the substitutions in `substs` are already monomorphized, + // but we still must normalize associated types + let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs); + monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty) + } -fn unboxed_closure_upvars(&self, - def_id: ast::DefId, - substs: &Substs<'tcx>) - -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>> -{ - // the substitutions in `substs` are already monomorphized, - // but we still must normalize associated types - let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs); - monomorphize::normalize_associated_type(self.param_env.tcx, &result) -} + fn unboxed_closure_upvars(&self, + def_id: ast::DefId, + substs: &Substs<'tcx>) + -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>> + { + // the substitutions in `substs` are already monomorphized, + // but we still must normalize associated types + let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs); + monomorphize::normalize_associated_type(self.param_env.tcx, &result) + } } pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span, @@ -1103,73 +1108,73 @@ pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span, fulfill_cx: &mut traits::FulfillmentContext<'tcx>, result: &T) -> T -where T : TypeFoldable<'tcx> + Repr<'tcx> + where T : TypeFoldable<'tcx> + Repr<'tcx> { -debug!("drain_fulfillment_cx(result={})", - result.repr(infcx.tcx)); - -// In principle, we only need to do this so long as `result` -// contains unbound type parameters. It could be a slight -// optimization to stop iterating early. -let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx); -match fulfill_cx.select_all_or_error(infcx, &typer) { - Ok(()) => { } - Err(errors) => { - if errors.iter().all(|e| e.is_overflow()) { - // See Ok(None) case above. - infcx.tcx.sess.span_fatal( - span, - "reached the recursion limit during monomorphization"); - } else { - infcx.tcx.sess.span_bug( - span, - format!("Encountered errors `{}` fulfilling during trans", - errors.repr(infcx.tcx)).index(&FullRange)); + debug!("drain_fulfillment_cx(result={})", + result.repr(infcx.tcx)); + + // In principle, we only need to do this so long as `result` + // contains unbound type parameters. It could be a slight + // optimization to stop iterating early. + let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx); + match fulfill_cx.select_all_or_error(infcx, &typer) { + Ok(()) => { } + Err(errors) => { + if errors.iter().all(|e| e.is_overflow()) { + // See Ok(None) case above. + infcx.tcx.sess.span_fatal( + span, + "reached the recursion limit during monomorphization"); + } else { + infcx.tcx.sess.span_bug( + span, + &format!("Encountered errors `{}` fulfilling during trans", + errors.repr(infcx.tcx))[]); + } } } -} -// Use freshen to simultaneously replace all type variables with -// their bindings and replace all regions with 'static. This is -// sort of overkill because we do not expect there to be any -// unbound type variables, hence no `TyFresh` types should ever be -// inserted. -result.fold_with(&mut infcx.freshener()) + // Use freshen to simultaneously replace all type variables with + // their bindings and replace all regions with 'static. This is + // sort of overkill because we do not expect there to be any + // unbound type variables, hence no `TyFresh` types should ever be + // inserted. + result.fold_with(&mut infcx.freshener()) } // Key used to lookup values supplied for type parameters in an expr. #[derive(Copy, PartialEq, Show)] pub enum ExprOrMethodCall { -// Type parameters for a path like `None::<int>` -ExprId(ast::NodeId), + // Type parameters for a path like `None::<int>` + ExprId(ast::NodeId), -// Type parameters for a method call like `a.foo::<int>()` -MethodCallKey(ty::MethodCall) + // Type parameters for a method call like `a.foo::<int>()` + MethodCallKey(ty::MethodCall) } pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, node: ExprOrMethodCall, param_substs: &subst::Substs<'tcx>) -> subst::Substs<'tcx> { -let tcx = ccx.tcx(); + let tcx = ccx.tcx(); -let substs = match node { - ExprId(id) => { - ty::node_id_item_substs(tcx, id).substs - } - MethodCallKey(method_call) => { - (*tcx.method_map.borrow())[method_call].substs.clone() - } -}; + let substs = match node { + ExprId(id) => { + ty::node_id_item_substs(tcx, id).substs + } + MethodCallKey(method_call) => { + (*tcx.method_map.borrow())[method_call].substs.clone() + } + }; -if substs.types.any(|t| ty::type_needs_infer(*t)) { - tcx.sess.bug(format!("type parameters for node {:?} include inference types: {:?}", - node, substs.repr(tcx)).index(&FullRange)); - } + if substs.types.any(|t| ty::type_needs_infer(*t)) { + tcx.sess.bug(&format!("type parameters for node {:?} include inference types: {:?}", + node, substs.repr(tcx))[]); + } - monomorphize::apply_param_substs(tcx, - param_substs, - &substs.erase_regions()) + monomorphize::apply_param_substs(tcx, + param_substs, + &substs.erase_regions()) } pub fn langcall(bcx: Block, @@ -1182,8 +1187,8 @@ pub fn langcall(bcx: Block, Err(s) => { let msg = format!("{} {}", msg, s); match span { - Some(span) => bcx.tcx().sess.span_fatal(span, msg.index(&FullRange)), - None => bcx.tcx().sess.fatal(msg.index(&FullRange)), + Some(span) => bcx.tcx().sess.span_fatal(span, &msg[]), + None => bcx.tcx().sess.fatal(&msg[]), } } } diff --git a/src/librustc_trans/trans/consts.rs b/src/librustc_trans/trans/consts.rs index b0474d7e011..00b97286de3 100644 --- a/src/librustc_trans/trans/consts.rs +++ b/src/librustc_trans/trans/consts.rs @@ -52,9 +52,9 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit) C_integral(Type::uint_from_ty(cx, t), i as u64, false) } _ => cx.sess().span_bug(lit.span, - format!("integer literal has type {} (expected int \ + &format!("integer literal has type {} (expected int \ or uint)", - ty_to_string(cx.tcx(), lit_int_ty)).index(&FullRange)) + ty_to_string(cx.tcx(), lit_int_ty))[]) } } ast::LitFloat(ref fs, t) => { @@ -74,7 +74,7 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit) } ast::LitBool(b) => C_bool(cx, b), ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()), - ast::LitBinary(ref data) => C_binary_slice(cx, data.index(&FullRange)), + ast::LitBinary(ref data) => C_binary_slice(cx, &data[]), } } @@ -93,9 +93,9 @@ fn const_vec(cx: &CrateContext, e: &ast::Expr, .collect::<Vec<_>>(); // If the vector contains enums, an LLVM array won't work. let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) { - C_struct(cx, vs.index(&FullRange), false) + C_struct(cx, &vs[], false) } else { - C_array(llunitty, vs.index(&FullRange)) + C_array(llunitty, &vs[]) }; (v, llunitty) } @@ -148,14 +148,14 @@ fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef, (const_deref_newtype(cx, v, t), mt.ty) } _ => { - cx.sess().bug(format!("unexpected dereferenceable type {}", - ty_to_string(cx.tcx(), t)).index(&FullRange)) + cx.sess().bug(&format!("unexpected dereferenceable type {}", + ty_to_string(cx.tcx(), t))[]) } } } None => { - cx.sess().bug(format!("cannot dereference const of type {}", - ty_to_string(cx.tcx(), t)).index(&FullRange)) + cx.sess().bug(&format!("cannot dereference const of type {}", + ty_to_string(cx.tcx(), t))[]) } } } @@ -251,16 +251,16 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr) ], false); } _ => cx.sess().span_bug(e.span, - format!("unimplemented type in const unsize: {}", - ty_to_string(cx.tcx(), ty)).index(&FullRange)) + &format!("unimplemented type in const unsize: {}", + ty_to_string(cx.tcx(), ty))[]) } } _ => { cx.sess() .span_bug(e.span, - format!("unimplemented const \ + &format!("unimplemented const \ autoref {:?}", - autoref).index(&FullRange)) + autoref)[]) } } } @@ -279,9 +279,9 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr) llvm::LLVMDumpValue(llconst); llvm::LLVMDumpValue(C_undef(llty)); } - cx.sess().bug(format!("const {} of type {} has size {} instead of {}", + cx.sess().bug(&format!("const {} of type {} has size {} instead of {}", e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety), - csize, tsize).index(&FullRange)); + csize, tsize)[]); } (llconst, ety_adjusted) } @@ -429,23 +429,23 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1])) }, _ => cx.sess().span_bug(base.span, - format!("index-expr base must be a vector \ + &format!("index-expr base must be a vector \ or string type, found {}", - ty_to_string(cx.tcx(), bt)).index(&FullRange)) + ty_to_string(cx.tcx(), bt))[]) }, ty::ty_rptr(_, mt) => match mt.ty.sty { ty::ty_vec(_, Some(u)) => { (const_deref_ptr(cx, bv), C_uint(cx, u)) }, _ => cx.sess().span_bug(base.span, - format!("index-expr base must be a vector \ + &format!("index-expr base must be a vector \ or string type, found {}", - ty_to_string(cx.tcx(), bt)).index(&FullRange)) + ty_to_string(cx.tcx(), bt))[]) }, _ => cx.sess().span_bug(base.span, - format!("index-expr base must be a vector \ + &format!("index-expr base must be a vector \ or string type, found {}", - ty_to_string(cx.tcx(), bt)).index(&FullRange)) + ty_to_string(cx.tcx(), bt))[]) }; let len = llvm::LLVMConstIntGetZExtValue(len) as u64; @@ -546,8 +546,8 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { ast::ExprTup(ref es) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); - let vals = map_list(es.index(&FullRange)); - adt::trans_const(cx, &*repr, 0, vals.index(&FullRange)) + let vals = map_list(&es[]); + adt::trans_const(cx, &*repr, 0, &vals[]) } ast::ExprStruct(_, ref fs, ref base_opt) => { let ety = ty::expr_ty(cx.tcx(), e); @@ -578,7 +578,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { } } }).collect::<Vec<_>>(); - adt::trans_const(cx, &*repr, discr, cs.index(&FullRange)) + adt::trans_const(cx, &*repr, discr, &cs[]) }) } ast::ExprVec(ref es) => { @@ -595,9 +595,9 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { }; let vs: Vec<_> = repeat(const_expr(cx, &**elem).0).take(n).collect(); if vs.iter().any(|vi| val_ty(*vi) != llunitty) { - C_struct(cx, vs.index(&FullRange), false) + C_struct(cx, &vs[], false) } else { - C_array(llunitty, vs.index(&FullRange)) + C_array(llunitty, &vs[]) } } ast::ExprPath(_) => { @@ -645,8 +645,8 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { Some(def::DefStruct(_)) => { let ety = ty::expr_ty(cx.tcx(), e); let repr = adt::represent_type(cx, ety); - let arg_vals = map_list(args.index(&FullRange)); - adt::trans_const(cx, &*repr, 0, arg_vals.index(&FullRange)) + let arg_vals = map_list(&args[]); + adt::trans_const(cx, &*repr, 0, &arg_vals[]) } Some(def::DefVariant(enum_did, variant_did, _)) => { let ety = ty::expr_ty(cx.tcx(), e); @@ -654,11 +654,11 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { let vinfo = ty::enum_variant_with_id(cx.tcx(), enum_did, variant_did); - let arg_vals = map_list(args.index(&FullRange)); + let arg_vals = map_list(&args[]); adt::trans_const(cx, &*repr, vinfo.disr_val, - arg_vals.index(&FullRange)) + &arg_vals[]) } _ => cx.sess().span_bug(e.span, "expected a struct or variant def") } diff --git a/src/librustc_trans/trans/context.rs b/src/librustc_trans/trans/context.rs index 35fb34eafb4..1abf3b0b886 100644 --- a/src/librustc_trans/trans/context.rs +++ b/src/librustc_trans/trans/context.rs @@ -284,7 +284,7 @@ impl<'tcx> SharedCrateContext<'tcx> { // such as a function name in the module. // 1. http://llvm.org/bugs/show_bug.cgi?id=11479 let llmod_id = format!("{}.{}.rs", crate_name, i); - let local_ccx = LocalCrateContext::new(&shared_ccx, llmod_id.index(&FullRange)); + let local_ccx = LocalCrateContext::new(&shared_ccx, &llmod_id[]); shared_ccx.local_ccxs.push(local_ccx); } @@ -369,12 +369,12 @@ impl<'tcx> LocalCrateContext<'tcx> { unsafe { let (llcx, llmod) = create_context_and_module(&shared.tcx.sess, name); - let td = mk_target_data(shared.tcx + let td = mk_target_data(&shared.tcx .sess .target .target .data_layout - .index(&FullRange)); + []); let dbg_cx = if shared.tcx.sess.opts.debuginfo != NoDebugInfo { Some(debuginfo::CrateDebugContext::new(llmod)) @@ -721,7 +721,7 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable /// address space on 64-bit ARMv8 and x86_64. pub fn obj_size_bound(&self) -> u64 { - match self.sess().target.target.target_word_size.index(&FullRange) { + match &self.sess().target.target.target_pointer_width[] { "32" => 1 << 31, "64" => 1 << 47, _ => unreachable!() // error handled by config::build_target_config @@ -730,8 +730,8 @@ impl<'b, 'tcx> CrateContext<'b, 'tcx> { pub fn report_overbig_object(&self, obj: Ty<'tcx>) -> ! { self.sess().fatal( - format!("the type `{}` is too big for the current architecture", - obj.repr(self.tcx())).index(&FullRange)) + &format!("the type `{}` is too big for the current architecture", + obj.repr(self.tcx()))[]) } } diff --git a/src/librustc_trans/trans/controlflow.rs b/src/librustc_trans/trans/controlflow.rs index 38d40a8322f..adf302501cd 100644 --- a/src/librustc_trans/trans/controlflow.rs +++ b/src/librustc_trans/trans/controlflow.rs @@ -48,7 +48,7 @@ pub fn trans_stmt<'blk, 'tcx>(cx: Block<'blk, 'tcx>, debug!("trans_stmt({})", s.repr(cx.tcx())); if cx.sess().asm_comments() { - add_span_comment(cx, s.span, s.repr(cx.tcx()).index(&FullRange)); + add_span_comment(cx, s.span, &s.repr(cx.tcx())[]); } let mut bcx = cx; @@ -188,7 +188,7 @@ pub fn trans_if<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } let name = format!("then-block-{}-", thn.id); - let then_bcx_in = bcx.fcx.new_id_block(name.index(&FullRange), thn.id); + let then_bcx_in = bcx.fcx.new_id_block(&name[], thn.id); let then_bcx_out = trans_block(then_bcx_in, &*thn, dest); trans::debuginfo::clear_source_location(bcx.fcx); @@ -439,8 +439,8 @@ pub fn trans_break_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, match bcx.tcx().def_map.borrow().get(&expr_id) { Some(&def::DefLabel(loop_id)) => loop_id, ref r => { - bcx.tcx().sess.bug(format!("{:?} in def-map for label", - r).index(&FullRange)) + bcx.tcx().sess.bug(&format!("{:?} in def-map for label", + r)[]) } } } @@ -504,7 +504,7 @@ pub fn trans_fail<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let v_str = C_str_slice(ccx, fail_str); let loc = bcx.sess().codemap().lookup_char_pos(sp.lo); - let filename = token::intern_and_get_ident(loc.file.name.index(&FullRange)); + let filename = token::intern_and_get_ident(&loc.file.name[]); let filename = C_str_slice(ccx, filename); let line = C_uint(ccx, loc.line); let expr_file_line_const = C_struct(ccx, &[v_str, filename, line], false); @@ -513,7 +513,7 @@ pub fn trans_fail<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let did = langcall(bcx, Some(sp), "", PanicFnLangItem); let bcx = callee::trans_lang_call(bcx, did, - args.index(&FullRange), + &args[], Some(expr::Ignore)).bcx; Unreachable(bcx); return bcx; @@ -529,7 +529,7 @@ pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // Extract the file/line from the span let loc = bcx.sess().codemap().lookup_char_pos(sp.lo); - let filename = token::intern_and_get_ident(loc.file.name.index(&FullRange)); + let filename = token::intern_and_get_ident(&loc.file.name[]); // Invoke the lang item let filename = C_str_slice(ccx, filename); @@ -540,7 +540,7 @@ pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let did = langcall(bcx, Some(sp), "", PanicBoundsCheckFnLangItem); let bcx = callee::trans_lang_call(bcx, did, - args.index(&FullRange), + &args[], Some(expr::Ignore)).bcx; Unreachable(bcx); return bcx; diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index 26518d4092f..8b52732f4ee 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -463,8 +463,8 @@ impl<'tcx> Datum<'tcx, Lvalue> { gep(base) } _ => bcx.tcx().sess.bug( - format!("Unexpected unsized type in get_element: {}", - bcx.ty_to_string(self.ty)).index(&FullRange)) + &format!("Unexpected unsized type in get_element: {}", + bcx.ty_to_string(self.ty))[]) }; Datum { val: val, diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index e2e1b3a799b..2f58baab7fc 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -284,8 +284,8 @@ impl<'tcx> TypeMap<'tcx> { type_: Ty<'tcx>, metadata: DIType) { if self.type_to_metadata.insert(type_, metadata).is_some() { - cx.sess().bug(format!("Type metadata for Ty '{}' is already in the TypeMap!", - ppaux::ty_to_string(cx.tcx(), type_)).index(&FullRange)); + cx.sess().bug(&format!("Type metadata for Ty '{}' is already in the TypeMap!", + ppaux::ty_to_string(cx.tcx(), type_))[]); } } @@ -297,8 +297,8 @@ impl<'tcx> TypeMap<'tcx> { metadata: DIType) { if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() { let unique_type_id_str = self.get_unique_type_id_as_string(unique_type_id); - cx.sess().bug(format!("Type metadata for unique id '{}' is already in the TypeMap!", - unique_type_id_str.index(&FullRange)).index(&FullRange)); + cx.sess().bug(&format!("Type metadata for unique id '{}' is already in the TypeMap!", + &unique_type_id_str[])[]); } } @@ -335,13 +335,13 @@ impl<'tcx> TypeMap<'tcx> { // unique ptr (~) -> {~ :pointee-uid:} // @-ptr (@) -> {@ :pointee-uid:} // sized vec ([T; x]) -> {[:size:] :element-uid:} - // unsized vec ([T]) -> {.index(&FullRange) :element-uid:} + // unsized vec ([T]) -> {[] :element-uid:} // trait (T) -> {trait_:svh: / :node-id:_<(:param-uid:),*> } // closure -> {<unsafe_> <once_> :store-sigil: |(:param-uid:),* <,_...>| -> \ // :return-type-uid: : (:bounds:)*} // function -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \ // :return-type-uid:} - // unique vec box (~.index(&FullRange)) -> {HEAP_VEC_BOX<:pointee-uid:>} + // unique vec box (~[]) -> {HEAP_VEC_BOX<:pointee-uid:>} // gc box -> {GC_BOX<:pointee-uid:>} match self.type_to_unique_id.get(&type_).cloned() { @@ -379,14 +379,14 @@ impl<'tcx> TypeMap<'tcx> { self.get_unique_type_id_of_type(cx, component_type); let component_type_id = self.get_unique_type_id_as_string(component_type_id); - unique_type_id.push_str(component_type_id.index(&FullRange)); + unique_type_id.push_str(&component_type_id[]); } }, ty::ty_uniq(inner_type) => { unique_type_id.push('~'); let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type); let inner_type_id = self.get_unique_type_id_as_string(inner_type_id); - unique_type_id.push_str(inner_type_id.index(&FullRange)); + unique_type_id.push_str(&inner_type_id[]); }, ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => { unique_type_id.push('*'); @@ -396,7 +396,7 @@ impl<'tcx> TypeMap<'tcx> { let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type); let inner_type_id = self.get_unique_type_id_as_string(inner_type_id); - unique_type_id.push_str(inner_type_id.index(&FullRange)); + unique_type_id.push_str(&inner_type_id[]); }, ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => { unique_type_id.push('&'); @@ -406,12 +406,12 @@ impl<'tcx> TypeMap<'tcx> { let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type); let inner_type_id = self.get_unique_type_id_as_string(inner_type_id); - unique_type_id.push_str(inner_type_id.index(&FullRange)); + unique_type_id.push_str(&inner_type_id[]); }, ty::ty_vec(inner_type, optional_length) => { match optional_length { Some(len) => { - unique_type_id.push_str(format!("[{}]", len).index(&FullRange)); + unique_type_id.push_str(&format!("[{}]", len)[]); } None => { unique_type_id.push_str("[]"); @@ -420,7 +420,7 @@ impl<'tcx> TypeMap<'tcx> { let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type); let inner_type_id = self.get_unique_type_id_as_string(inner_type_id); - unique_type_id.push_str(inner_type_id.index(&FullRange)); + unique_type_id.push_str(&inner_type_id[]); }, ty::ty_trait(ref trait_data) => { unique_type_id.push_str("trait "); @@ -451,7 +451,7 @@ impl<'tcx> TypeMap<'tcx> { self.get_unique_type_id_of_type(cx, parameter_type); let parameter_type_id = self.get_unique_type_id_as_string(parameter_type_id); - unique_type_id.push_str(parameter_type_id.index(&FullRange)); + unique_type_id.push_str(¶meter_type_id[]); unique_type_id.push(','); } @@ -464,7 +464,7 @@ impl<'tcx> TypeMap<'tcx> { ty::FnConverging(ret_ty) => { let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty); let return_type_id = self.get_unique_type_id_as_string(return_type_id); - unique_type_id.push_str(return_type_id.index(&FullRange)); + unique_type_id.push_str(&return_type_id[]); } ty::FnDiverging => { unique_type_id.push_str("!"); @@ -479,9 +479,9 @@ impl<'tcx> TypeMap<'tcx> { &mut unique_type_id); }, _ => { - cx.sess().bug(format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}", - ppaux::ty_to_string(cx.tcx(), type_).index(&FullRange), - type_.sty).index(&FullRange)) + cx.sess().bug(&format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}", + &ppaux::ty_to_string(cx.tcx(), type_)[], + type_.sty)[]) } }; @@ -524,7 +524,7 @@ impl<'tcx> TypeMap<'tcx> { output.push_str(crate_hash.as_str()); output.push_str("/"); - output.push_str(format!("{:x}", def_id.node).index(&FullRange)); + output.push_str(&format!("{:x}", def_id.node)[]); // Maybe check that there is no self type here. @@ -537,7 +537,7 @@ impl<'tcx> TypeMap<'tcx> { type_map.get_unique_type_id_of_type(cx, type_parameter); let param_type_id = type_map.get_unique_type_id_as_string(param_type_id); - output.push_str(param_type_id.index(&FullRange)); + output.push_str(¶m_type_id[]); output.push(','); } @@ -581,7 +581,7 @@ impl<'tcx> TypeMap<'tcx> { self.get_unique_type_id_of_type(cx, parameter_type); let parameter_type_id = self.get_unique_type_id_as_string(parameter_type_id); - unique_type_id.push_str(parameter_type_id.index(&FullRange)); + unique_type_id.push_str(¶meter_type_id[]); unique_type_id.push(','); } @@ -595,7 +595,7 @@ impl<'tcx> TypeMap<'tcx> { ty::FnConverging(ret_ty) => { let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty); let return_type_id = self.get_unique_type_id_as_string(return_type_id); - unique_type_id.push_str(return_type_id.index(&FullRange)); + unique_type_id.push_str(&return_type_id[]); } ty::FnDiverging => { unique_type_id.push_str("!"); @@ -625,8 +625,7 @@ impl<'tcx> TypeMap<'tcx> { -> UniqueTypeId { let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type); let enum_variant_type_id = format!("{}::{}", - self.get_unique_type_id_as_string(enum_type_id) - .index(&FullRange), + &self.get_unique_type_id_as_string(enum_type_id)[], variant_name); let interner_key = self.unique_id_interner.intern(Rc::new(enum_variant_type_id)); UniqueTypeId(interner_key) @@ -803,23 +802,23 @@ pub fn create_global_var_metadata(cx: &CrateContext, _ => { cx.sess() .span_bug(item.span, - format!("debuginfo::\ + &format!("debuginfo::\ create_global_var_metadata() - Captured var-id refers to \ unexpected ast_item variant: {:?}", - var_item).index(&FullRange)) + var_item)[]) } } }, - _ => cx.sess().bug(format!("debuginfo::create_global_var_metadata() \ + _ => cx.sess().bug(&format!("debuginfo::create_global_var_metadata() \ - Captured var-id refers to unexpected \ ast_map variant: {:?}", - var_item).index(&FullRange)) + var_item)[]) }; let (file_metadata, line_number) = if span != codemap::DUMMY_SP { let loc = span_start(cx, span); - (file_metadata(cx, loc.file.name.index(&FullRange)), loc.line as c_uint) + (file_metadata(cx, &loc.file.name[]), loc.line as c_uint) } else { (UNKNOWN_FILE_METADATA, UNKNOWN_LINE_NUMBER) }; @@ -830,7 +829,7 @@ pub fn create_global_var_metadata(cx: &CrateContext, let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id)); let var_name = token::get_ident(ident).get().to_string(); let linkage_name = - namespace_node.mangled_name_of_contained_item(var_name.index(&FullRange)); + namespace_node.mangled_name_of_contained_item(&var_name[]); let var_scope = namespace_node.scope; let var_name = CString::from_slice(var_name.as_bytes()); @@ -868,8 +867,8 @@ pub fn create_local_var_metadata(bcx: Block, local: &ast::Local) { Some(datum) => datum, None => { bcx.sess().span_bug(span, - format!("no entry in lllocals table for {}", - node_id).index(&FullRange)); + &format!("no entry in lllocals table for {}", + node_id)[]); } }; @@ -919,21 +918,21 @@ pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => { cx.sess() .span_bug(span, - format!( + &format!( "debuginfo::create_captured_var_metadata() - \ Captured var-id refers to unexpected \ ast_map variant: {:?}", - ast_item).index(&FullRange)); + ast_item)[]); } } } _ => { cx.sess() .span_bug(span, - format!("debuginfo::create_captured_var_metadata() - \ + &format!("debuginfo::create_captured_var_metadata() - \ Captured var-id refers to unexpected \ ast_map variant: {:?}", - ast_item).index(&FullRange)); + ast_item)[]); } }; @@ -963,7 +962,7 @@ pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let variable_access = IndirectVariable { alloca: env_pointer, - address_operations: address_operations.index(&(0..address_op_count)) + address_operations: &address_operations[0..address_op_count] }; declare_local(bcx, @@ -1039,8 +1038,8 @@ pub fn create_argument_metadata(bcx: Block, arg: &ast::Arg) { Some(v) => v, None => { bcx.sess().span_bug(span, - format!("no entry in lllocals table for {}", - node_id).index(&FullRange)); + &format!("no entry in lllocals table for {}", + node_id)[]); } }; @@ -1154,7 +1153,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, if let Some(code_snippet) = code_snippet { let bytes = code_snippet.as_bytes(); - if bytes.len() > 0 && bytes.index(&((bytes.len()-1)..)) == b"}" { + if bytes.len() > 0 && &bytes[(bytes.len()-1)..] == b"}" { cleanup_span = Span { lo: node_span.hi - codemap::BytePos(1), hi: node_span.hi, @@ -1298,7 +1297,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, match expr.node { ast::ExprClosure(_, _, ref fn_decl, ref top_level_block) => { let name = format!("fn{}", token::gensym("fn")); - let name = token::str_to_ident(name.index(&FullRange)); + let name = token::str_to_ident(&name[]); (name, &**fn_decl, // This is not quite right. It should actually inherit // the generics of the enclosing function. @@ -1328,9 +1327,9 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } _ => { cx.sess() - .bug(format!("create_function_debug_context: \ + .bug(&format!("create_function_debug_context: \ unexpected sort of node: {:?}", - fnitem).index(&FullRange)) + fnitem)[]) } } } @@ -1339,9 +1338,9 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ast_map::NodeStructCtor(..) => { return FunctionDebugContext::FunctionWithoutDebugInfo; } - _ => cx.sess().bug(format!("create_function_debug_context: \ + _ => cx.sess().bug(&format!("create_function_debug_context: \ unexpected sort of node: {:?}", - fnitem).index(&FullRange)) + fnitem)[]) }; // This can be the case for functions inlined from another crate @@ -1350,7 +1349,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.name.index(&FullRange)); + let file_metadata = file_metadata(cx, &loc.file.name[]); let function_type_metadata = unsafe { let fn_signature = get_function_signature(cx, @@ -1377,7 +1376,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let (linkage_name, containing_scope) = if has_path { let namespace_node = namespace_for_item(cx, ast_util::local_def(fn_ast_id)); let linkage_name = namespace_node.mangled_name_of_contained_item( - function_name.index(&FullRange)); + &function_name[]); let containing_scope = namespace_node.scope; (linkage_name, containing_scope) } else { @@ -1465,7 +1464,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP)); } - return create_DIArray(DIB(cx), signature.index(&FullRange)); + return create_DIArray(DIB(cx), &signature[]); } fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, @@ -1500,7 +1499,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, actual_self_type, true); - name_to_append_suffix_to.push_str(actual_self_type_name.index(&FullRange)); + name_to_append_suffix_to.push_str(&actual_self_type_name[]); if generics.is_type_parameterized() { name_to_append_suffix_to.push_str(","); @@ -1539,7 +1538,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let actual_type_name = compute_debuginfo_type_name(cx, actual_type, true); - name_to_append_suffix_to.push_str(actual_type_name.index(&FullRange)); + name_to_append_suffix_to.push_str(&actual_type_name[]); if index != generics.ty_params.len() - 1 { name_to_append_suffix_to.push_str(","); @@ -1566,7 +1565,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, name_to_append_suffix_to.push('>'); - return create_DIArray(DIB(cx), template_params.index(&FullRange)); + return create_DIArray(DIB(cx), &template_params[]); } } @@ -1660,7 +1659,7 @@ fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let cx: &CrateContext = bcx.ccx(); let filename = span_start(cx, span).file.name.clone(); - let file_metadata = file_metadata(cx, filename.index(&FullRange)); + let file_metadata = file_metadata(cx, &filename[]); let name = token::get_ident(variable_ident); let loc = span_start(cx, span); @@ -1746,7 +1745,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile { let work_dir = cx.sess().working_dir.as_str().unwrap(); let file_name = if full_path.starts_with(work_dir) { - full_path.index(&((work_dir.len() + 1u)..full_path.len())) + &full_path[(work_dir.len() + 1u)..full_path.len()] } else { full_path }; @@ -1777,8 +1776,8 @@ fn scope_metadata(fcx: &FunctionContext, let node = fcx.ccx.tcx().map.get(node_id); fcx.ccx.sess().span_bug(error_reporting_span, - format!("debuginfo: Could not find scope info for node {:?}", - node).index(&FullRange)); + &format!("debuginfo: Could not find scope info for node {:?}", + node)[]); } } } @@ -1805,14 +1804,14 @@ fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::ty_bool => ("bool".to_string(), DW_ATE_boolean), ty::ty_char => ("char".to_string(), DW_ATE_unsigned_char), ty::ty_int(int_ty) => match int_ty { - ast::TyIs => ("isize".to_string(), DW_ATE_signed), + ast::TyIs(_) => ("isize".to_string(), DW_ATE_signed), ast::TyI8 => ("i8".to_string(), DW_ATE_signed), ast::TyI16 => ("i16".to_string(), DW_ATE_signed), ast::TyI32 => ("i32".to_string(), DW_ATE_signed), ast::TyI64 => ("i64".to_string(), DW_ATE_signed) }, ty::ty_uint(uint_ty) => match uint_ty { - ast::TyUs => ("usize".to_string(), DW_ATE_unsigned), + ast::TyUs(_) => ("usize".to_string(), DW_ATE_unsigned), ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned), ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned), ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned), @@ -1971,10 +1970,10 @@ impl<'tcx> RecursiveTypeDescription<'tcx> { let type_map = debug_context(cx).type_map.borrow(); if type_map.find_metadata_for_unique_id(unique_type_id).is_none() || type_map.find_metadata_for_type(unfinished_type).is_none() { - cx.sess().bug(format!("Forward declaration of potentially recursive type \ + cx.sess().bug(&format!("Forward declaration of potentially recursive type \ '{}' was not found in TypeMap!", ppaux::ty_to_string(cx.tcx(), unfinished_type)) - .index(&FullRange)); + []); } } @@ -1986,7 +1985,7 @@ impl<'tcx> RecursiveTypeDescription<'tcx> { set_members_of_composite_type(cx, metadata_stub, llvm_type, - member_descriptions.index(&FullRange)); + &member_descriptions[]); return MetadataCreationResult::new(metadata_stub, true); } } @@ -2058,7 +2057,7 @@ fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let struct_metadata_stub = create_struct_stub(cx, struct_llvm_type, - struct_name.index(&FullRange), + &struct_name[], unique_type_id, containing_scope); @@ -2119,7 +2118,7 @@ fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, unique_type_id, create_struct_stub(cx, tuple_llvm_type, - tuple_name.index(&FullRange), + &tuple_name[], unique_type_id, UNKNOWN_SCOPE_METADATA), tuple_llvm_type, @@ -2179,7 +2178,7 @@ impl<'tcx> EnumMemberDescriptionFactory<'tcx> { set_members_of_composite_type(cx, variant_type_metadata, variant_llvm_type, - member_descriptions.index(&FullRange)); + &member_descriptions[]); MemberDescription { name: "".to_string(), llvm_type: variant_llvm_type, @@ -2212,7 +2211,7 @@ impl<'tcx> EnumMemberDescriptionFactory<'tcx> { set_members_of_composite_type(cx, variant_type_metadata, variant_llvm_type, - member_descriptions.index(&FullRange)); + &member_descriptions[]); vec![ MemberDescription { name: "".to_string(), @@ -2312,7 +2311,7 @@ impl<'tcx> EnumMemberDescriptionFactory<'tcx> { set_members_of_composite_type(cx, variant_type_metadata, variant_llvm_type, - variant_member_descriptions.index(&FullRange)); + &variant_member_descriptions[]); // Encode the information about the null variant in the union // member's name. @@ -2387,11 +2386,11 @@ fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, span: Span) -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) { let variant_llvm_type = - Type::struct_(cx, struct_def.fields + Type::struct_(cx, &struct_def.fields .iter() .map(|&t| type_of::type_of(cx, t)) .collect::<Vec<_>>() - .index(&FullRange), + [], struct_def.packed); // Could do some consistency checks here: size, align, field count, discr type @@ -2458,7 +2457,7 @@ fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, enum_def_id); let loc = span_start(cx, definition_span); - let file_metadata = file_metadata(cx, loc.file.name.index(&FullRange)); + let file_metadata = file_metadata(cx, &loc.file.name[]); let variants = ty::enum_variants(cx.tcx(), enum_def_id); @@ -2638,14 +2637,14 @@ fn set_members_of_composite_type(cx: &CrateContext, let min_supported_llvm_version = 3 * 1000000 + 4 * 1000; if actual_llvm_version < min_supported_llvm_version { - cx.sess().warn(format!("This version of rustc was built with LLVM \ + cx.sess().warn(&format!("This version of rustc was built with LLVM \ {}.{}. Rustc just ran into a known \ debuginfo corruption problem thatoften \ occurs with LLVM versions below 3.4. \ Please use a rustc built with anewer \ version of LLVM.", llvm_version_major, - llvm_version_minor).index(&FullRange)); + llvm_version_minor)[]); } else { cx.sess().bug("debuginfo::set_members_of_composite_type() - \ Already completed forward declaration re-encountered."); @@ -2683,7 +2682,7 @@ fn set_members_of_composite_type(cx: &CrateContext, .collect(); unsafe { - let type_array = create_DIArray(DIB(cx), member_metadata.index(&FullRange)); + let type_array = create_DIArray(DIB(cx), &member_metadata[]); llvm::LLVMDICompositeTypeSetTypeArray(composite_type_metadata, type_array); } } @@ -2782,7 +2781,7 @@ fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let member_llvm_types = slice_llvm_type.field_types(); assert!(slice_layout_is_correct(cx, - member_llvm_types.index(&FullRange), + &member_llvm_types[], element_type)); let member_descriptions = [ MemberDescription { @@ -2804,11 +2803,11 @@ fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, assert!(member_descriptions.len() == member_llvm_types.len()); let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.name.index(&FullRange)); + let file_metadata = file_metadata(cx, &loc.file.name[]); let metadata = composite_type_metadata(cx, slice_llvm_type, - slice_type_name.index(&FullRange), + &slice_type_name[], unique_type_id, &member_descriptions, UNKNOWN_SCOPE_METADATA, @@ -2857,7 +2856,7 @@ fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, llvm::LLVMDIBuilderCreateSubroutineType( DIB(cx), UNKNOWN_FILE_METADATA, - create_DIArray(DIB(cx), signature_metadata.index(&FullRange))) + create_DIArray(DIB(cx), &signature_metadata[])) }, false); } @@ -2881,9 +2880,9 @@ fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::ty_trait(ref data) => data.principal_def_id(), _ => { let pp_type_name = ppaux::ty_to_string(cx.tcx(), trait_type); - cx.sess().bug(format!("debuginfo: Unexpected trait-object type in \ + cx.sess().bug(&format!("debuginfo: Unexpected trait-object type in \ trait_pointer_metadata(): {}", - pp_type_name.index(&FullRange)).index(&FullRange)); + &pp_type_name[])[]); } }; @@ -2897,7 +2896,7 @@ fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, composite_type_metadata(cx, trait_llvm_type, - trait_type_name.index(&FullRange), + &trait_type_name[], unique_type_id, &[], containing_scope, @@ -3017,13 +3016,13 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::ty_tup(ref elements) => { prepare_tuple_metadata(cx, t, - elements.index(&FullRange), + &elements[], unique_type_id, usage_site_span).finalize(cx) } _ => { - cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {:?}", - sty).index(&FullRange)) + cx.sess().bug(&format!("debuginfo: unexpected type in type_metadata: {:?}", + sty)[]) } }; @@ -3041,9 +3040,9 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, type id '{}' to already be in \ the debuginfo::TypeMap but it \ was not. (Ty = {})", - unique_type_id_str.index(&FullRange), + &unique_type_id_str[], ppaux::ty_to_string(cx.tcx(), t)); - cx.sess().span_bug(usage_site_span, error_message.index(&FullRange)); + cx.sess().span_bug(usage_site_span, &error_message[]); } }; @@ -3056,9 +3055,9 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, UniqueTypeId maps in \ debuginfo::TypeMap. \ UniqueTypeId={}, Ty={}", - unique_type_id_str.index(&FullRange), + &unique_type_id_str[], ppaux::ty_to_string(cx.tcx(), t)); - cx.sess().span_bug(usage_site_span, error_message.index(&FullRange)); + cx.sess().span_bug(usage_site_span, &error_message[]); } } None => { @@ -3264,7 +3263,7 @@ fn create_scope_map(cx: &CrateContext, { // Create a new lexical scope and push it onto the stack let loc = cx.sess().codemap().lookup_char_pos(scope_span.lo); - let file_metadata = file_metadata(cx, loc.file.name.index(&FullRange)); + let file_metadata = file_metadata(cx, &loc.file.name[]); let parent_scope = scope_stack.last().unwrap().scope_metadata; let scope_metadata = unsafe { @@ -3386,7 +3385,7 @@ fn create_scope_map(cx: &CrateContext, if need_new_scope { // Create a new lexical scope and push it onto the stack let loc = cx.sess().codemap().lookup_char_pos(pat.span.lo); - let file_metadata = file_metadata(cx, loc.file.name.index(&FullRange)); + let file_metadata = file_metadata(cx, &loc.file.name[]); let parent_scope = scope_stack.last().unwrap().scope_metadata; let scope_metadata = unsafe { @@ -3740,12 +3739,12 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::ty_bool => output.push_str("bool"), ty::ty_char => output.push_str("char"), ty::ty_str => output.push_str("str"), - ty::ty_int(ast::TyIs) => output.push_str("isize"), + ty::ty_int(ast::TyIs(_)) => output.push_str("isize"), ty::ty_int(ast::TyI8) => output.push_str("i8"), ty::ty_int(ast::TyI16) => output.push_str("i16"), ty::ty_int(ast::TyI32) => output.push_str("i32"), ty::ty_int(ast::TyI64) => output.push_str("i64"), - ty::ty_uint(ast::TyUs) => output.push_str("usize"), + ty::ty_uint(ast::TyUs(_)) => output.push_str("usize"), ty::ty_uint(ast::TyU8) => output.push_str("u8"), ty::ty_uint(ast::TyU16) => output.push_str("u16"), ty::ty_uint(ast::TyU32) => output.push_str("u32"), @@ -3861,8 +3860,8 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, ty::ty_open(_) | ty::ty_projection(..) | ty::ty_param(_) => { - cx.sess().bug(format!("debuginfo: Trying to create type name for \ - unexpected type: {}", ppaux::ty_to_string(cx.tcx(), t)).index(&FullRange)); + cx.sess().bug(&format!("debuginfo: Trying to create type name for \ + unexpected type: {}", ppaux::ty_to_string(cx.tcx(), t))[]); } } @@ -3945,13 +3944,13 @@ impl NamespaceTreeNode { None => {} } let string = token::get_name(node.name); - output.push_str(format!("{}", string.get().len()).index(&FullRange)); + output.push_str(&format!("{}", string.get().len())[]); output.push_str(string.get()); } let mut name = String::from_str("_ZN"); fill_nested(self, &mut name); - name.push_str(format!("{}", item_name.len()).index(&FullRange)); + name.push_str(&format!("{}", item_name.len())[]); name.push_str(item_name); name.push('E'); name @@ -3959,7 +3958,7 @@ impl NamespaceTreeNode { } fn crate_root_namespace<'a>(cx: &'a CrateContext) -> &'a str { - cx.link_meta().crate_name.index(&FullRange) + &cx.link_meta().crate_name[] } fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTreeNode> { @@ -4034,9 +4033,9 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTree match parent_node { Some(node) => node, None => { - cx.sess().bug(format!("debuginfo::namespace_for_item(): \ + cx.sess().bug(&format!("debuginfo::namespace_for_item(): \ path too short for {:?}", - def_id).index(&FullRange)); + def_id)[]); } } }) diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 120e2e955e4..ac50445be2f 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -50,6 +50,7 @@ use trans::debuginfo; use trans::glue; use trans::machine; use trans::meth; +use trans::monomorphize; use trans::inline; use trans::tvec; use trans::type_of; @@ -317,8 +318,8 @@ fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // should just be the identity function. unsized_info(bcx, k, id, ty_substs[tp_index], identity) } - _ => bcx.sess().bug(format!("UnsizeStruct with bad sty: {}", - bcx.ty_to_string(unadjusted_ty)).index(&FullRange)) + _ => bcx.sess().bug(&format!("UnsizeStruct with bad sty: {}", + bcx.ty_to_string(unadjusted_ty))[]) }, &ty::UnsizeVtable(ty::TyTrait { ref principal, .. }, _) => { // Note that we preserve binding levels here: @@ -450,8 +451,8 @@ fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let datum_ty = datum.ty; let unboxed_ty = match datum_ty.sty { ty::ty_uniq(t) => t, - _ => bcx.sess().bug(format!("Expected ty_uniq, found {}", - bcx.ty_to_string(datum_ty)).index(&FullRange)) + _ => bcx.sess().bug(&format!("Expected ty_uniq, found {}", + bcx.ty_to_string(datum_ty))[]) }; let result_ty = ty::mk_uniq(tcx, ty::unsize_ty(tcx, unboxed_ty, k, expr.span)); @@ -622,9 +623,9 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => { bcx.tcx().sess.span_bug( expr.span, - format!("trans_rvalue_datum_unadjusted reached \ + &format!("trans_rvalue_datum_unadjusted reached \ fall-through case: {:?}", - expr.node).index(&FullRange)); + expr.node)[]); } } } @@ -975,9 +976,9 @@ fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => { bcx.tcx().sess.span_bug( expr.span, - format!("trans_rvalue_stmt_unadjusted reached \ + &format!("trans_rvalue_stmt_unadjusted reached \ fall-through case: {:?}", - expr.node).index(&FullRange)); + expr.node)[]); } } } @@ -1003,14 +1004,14 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest) } ast::ExprMatch(ref discr, ref arms, _) => { - _match::trans_match(bcx, expr, &**discr, arms.index(&FullRange), dest) + _match::trans_match(bcx, expr, &**discr, &arms[], dest) } ast::ExprBlock(ref blk) => { controlflow::trans_block(bcx, &**blk, dest) } ast::ExprStruct(_, ref fields, ref base) => { trans_struct(bcx, - fields.index(&FullRange), + &fields[], base.as_ref().map(|e| &**e), expr.span, expr.id, @@ -1075,7 +1076,7 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, trans_adt(bcx, expr_ty(bcx, expr), 0, - numbered_fields.index(&FullRange), + &numbered_fields[], None, dest, Some(NodeInfo { id: expr.id, span: expr.span })) @@ -1119,13 +1120,13 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, trans_overloaded_call(bcx, expr, &**f, - args.index(&FullRange), + &args[], Some(dest)) } else { callee::trans_call(bcx, expr, &**f, - callee::ArgExprs(args.index(&FullRange)), + callee::ArgExprs(&args[]), dest) } } @@ -1133,7 +1134,7 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, callee::trans_method_call(bcx, expr, &*args[0], - callee::ArgExprs(args.index(&FullRange)), + callee::ArgExprs(&args[]), dest) } ast::ExprBinary(op, ref lhs, ref rhs) => { @@ -1180,9 +1181,9 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => { bcx.tcx().sess.span_bug( expr.span, - format!("trans_rvalue_dps_unadjusted reached fall-through \ + &format!("trans_rvalue_dps_unadjusted reached fall-through \ case: {:?}", - expr.node).index(&FullRange)); + expr.node)[]); } } } @@ -1230,9 +1231,9 @@ fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bcx } _ => { - bcx.tcx().sess.span_bug(ref_expr.span, format!( + bcx.tcx().sess.span_bug(ref_expr.span, &format!( "Non-DPS def {:?} referened by {}", - def, bcx.node_id_to_string(ref_expr.id)).index(&FullRange)); + def, bcx.node_id_to_string(ref_expr.id))[]); } } } @@ -1258,10 +1259,10 @@ pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, param_substs) } _ => { - ccx.tcx().sess.span_bug(ref_expr.span, format!( + ccx.tcx().sess.span_bug(ref_expr.span, &format!( "trans_def_fn_unadjusted invoked on: {:?} for {}", def, - ref_expr.repr(ccx.tcx())).index(&FullRange)); + ref_expr.repr(ccx.tcx()))[]); } } } @@ -1279,9 +1280,9 @@ pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, match bcx.fcx.llupvars.borrow().get(&nid) { Some(&val) => Datum::new(val, local_ty, Lvalue), None => { - bcx.sess().bug(format!( + bcx.sess().bug(&format!( "trans_local_var: no llval for upvar {} found", - nid).index(&FullRange)); + nid)[]); } } } @@ -1289,9 +1290,9 @@ pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let datum = match bcx.fcx.lllocals.borrow().get(&nid) { Some(&v) => v, None => { - bcx.sess().bug(format!( + bcx.sess().bug(&format!( "trans_local_var: no datum for local/arg {} found", - nid).index(&FullRange)); + nid)[]); } }; debug!("take_local(nid={}, v={}, ty={})", @@ -1299,9 +1300,9 @@ pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, datum } _ => { - bcx.sess().unimpl(format!( + bcx.sess().unimpl(&format!( "unsupported def type in trans_local_var: {:?}", - def).index(&FullRange)); + def)[]); } } } @@ -1318,21 +1319,23 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>, { match ty.sty { ty::ty_struct(did, substs) => { - op(0, struct_fields(tcx, did, substs).index(&FullRange)) + let fields = struct_fields(tcx, did, substs); + let fields = monomorphize::normalize_associated_type(tcx, &fields); + op(0, &fields[]) } ty::ty_tup(ref v) => { - op(0, tup_fields(v.index(&FullRange)).index(&FullRange)) + op(0, &tup_fields(&v[])[]) } ty::ty_enum(_, substs) => { // We want the *variant* ID here, not the enum ID. match node_id_opt { None => { - tcx.sess.bug(format!( + tcx.sess.bug(&format!( "cannot get field types from the enum type {} \ without a node ID", - ty.repr(tcx)).index(&FullRange)); + ty.repr(tcx))[]); } Some(node_id) => { let def = tcx.def_map.borrow()[node_id].clone(); @@ -1340,10 +1343,9 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>, def::DefVariant(enum_id, variant_id, _) => { let variant_info = ty::enum_variant_with_id( tcx, enum_id, variant_id); - op(variant_info.disr_val, - struct_fields(tcx, - variant_id, - substs).index(&FullRange)) + let fields = struct_fields(tcx, variant_id, substs); + let fields = monomorphize::normalize_associated_type(tcx, &fields); + op(variant_info.disr_val, &fields[]) } _ => { tcx.sess.bug("resolve didn't map this expr to a \ @@ -1355,9 +1357,9 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>, } _ => { - tcx.sess.bug(format!( + tcx.sess.bug(&format!( "cannot get field types from the type {}", - ty.repr(tcx)).index(&FullRange)); + ty.repr(tcx))[]); } } } @@ -2045,21 +2047,21 @@ fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, lldiscrim_a, true), cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out), _ => { - ccx.sess().bug(format!("translating unsupported cast: \ + ccx.sess().bug(&format!("translating unsupported cast: \ {} ({:?}) -> {} ({:?})", t_in.repr(bcx.tcx()), k_in, t_out.repr(bcx.tcx()), - k_out).index(&FullRange)) + k_out)[]) } } } - _ => ccx.sess().bug(format!("translating unsupported cast: \ + _ => ccx.sess().bug(&format!("translating unsupported cast: \ {} ({:?}) -> {} ({:?})", t_in.repr(bcx.tcx()), k_in, t_out.repr(bcx.tcx()), - k_out).index(&FullRange)) + k_out)[]) }; return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock(); } @@ -2224,8 +2226,8 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => { bcx.tcx().sess.span_bug( expr.span, - format!("deref invoked on expr of illegal type {}", - datum.ty.repr(bcx.tcx())).index(&FullRange)); + &format!("deref invoked on expr of illegal type {}", + datum.ty.repr(bcx.tcx()))[]); } }; diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index 25eb66ab2eb..3dfb36c854b 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -109,7 +109,7 @@ pub fn register_static(ccx: &CrateContext, let llty = type_of::type_of(ccx, ty); let ident = link_name(foreign_item); - match attr::first_attr_value_str_by_name(foreign_item.attrs.index(&FullRange), + match attr::first_attr_value_str_by_name(&foreign_item.attrs[], "linkage") { // If this is a static with a linkage specified, then we need to handle // it a little specially. The typesystem prevents things like &T and @@ -235,13 +235,13 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, _ => ccx.sess().bug("trans_native_call called on non-function type") }; let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig); - let llsig = foreign_signature(ccx, &fn_sig, passed_arg_tys.index(&FullRange)); + let llsig = foreign_signature(ccx, &fn_sig, &passed_arg_tys[]); let fn_type = cabi::compute_abi_info(ccx, - llsig.llarg_tys.index(&FullRange), + &llsig.llarg_tys[], llsig.llret_ty, llsig.ret_def); - let arg_tys: &[cabi::ArgType] = fn_type.arg_tys.index(&FullRange); + let arg_tys: &[cabi::ArgType] = &fn_type.arg_tys[]; let mut llargs_foreign = Vec::new(); @@ -367,7 +367,7 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let llforeign_retval = CallWithConv(bcx, llfn, - llargs_foreign.index(&FullRange), + &llargs_foreign[], cc, Some(attrs)); @@ -437,7 +437,7 @@ pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) { abi => { let ty = ty::node_id_to_type(ccx.tcx(), foreign_item.id); register_foreign_item_fn(ccx, abi, ty, - lname.get().index(&FullRange)); + &lname.get()[]); // Unlike for other items, we shouldn't call // `base::update_linkage` here. Foreign items have // special linkage requirements, which are handled @@ -566,10 +566,10 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, assert!(f.abi != Rust && f.abi != RustIntrinsic); } _ => { - ccx.sess().bug(format!("build_rust_fn: extern fn {} has ty {}, \ + ccx.sess().bug(&format!("build_rust_fn: extern fn {} has ty {}, \ expected a bare fn ty", ccx.tcx().map.path_to_string(id), - t.repr(tcx)).index(&FullRange)); + t.repr(tcx))[]); } }; @@ -577,7 +577,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ccx.tcx().map.path_to_string(id), id, t.repr(tcx)); - let llfn = base::decl_internal_rust_fn(ccx, t, ps.index(&FullRange)); + let llfn = base::decl_internal_rust_fn(ccx, t, &ps[]); base::set_llvm_fn_attrs(ccx, attrs, llfn); base::trans_fn(ccx, decl, body, llfn, param_substs, id, &[]); llfn @@ -817,9 +817,9 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, // the massive simplifications that have occurred. pub fn link_name(i: &ast::ForeignItem) -> InternedString { - match attr::first_attr_value_str_by_name(i.attrs.index(&FullRange), "link_name") { + match attr::first_attr_value_str_by_name(&i.attrs[], "link_name") { Some(ln) => ln.clone(), - None => match weak_lang_items::link_name(i.attrs.index(&FullRange)) { + None => match weak_lang_items::link_name(&i.attrs[]) { Some(name) => name, None => token::get_ident(i.ident), } @@ -862,7 +862,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig); let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs.as_slice()); let fn_ty = cabi::compute_abi_info(ccx, - llsig.llarg_tys.index(&FullRange), + &llsig.llarg_tys[], llsig.llret_ty, llsig.ret_def); debug!("foreign_types_for_fn_ty(\ @@ -871,7 +871,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty={} -> {}, \ ret_def={}", ty.repr(ccx.tcx()), - ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)), + ccx.tn().types_to_str(&llsig.llarg_tys[]), ccx.tn().type_to_string(llsig.llret_ty), ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()), ccx.tn().type_to_string(fn_ty.ret_ty.ty), @@ -923,7 +923,7 @@ fn lltype_for_fn_from_foreign_types(ccx: &CrateContext, tys: &ForeignTypes) -> T if tys.fn_sig.variadic { Type::variadic_func(llargument_tys.as_slice(), &llreturn_ty) } else { - Type::func(llargument_tys.index(&FullRange), &llreturn_ty) + Type::func(&llargument_tys[], &llreturn_ty) } } diff --git a/src/librustc_trans/trans/glue.rs b/src/librustc_trans/trans/glue.rs index 52e7a986d7e..2219cd59263 100644 --- a/src/librustc_trans/trans/glue.rs +++ b/src/librustc_trans/trans/glue.rs @@ -161,7 +161,7 @@ pub fn get_drop_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Val let (glue, new_sym) = match ccx.available_drop_glues().borrow().get(&t) { Some(old_sym) => { - let glue = decl_cdecl_fn(ccx, old_sym.index(&FullRange), llfnty, ty::mk_nil(ccx.tcx())); + let glue = decl_cdecl_fn(ccx, &old_sym[], llfnty, ty::mk_nil(ccx.tcx())); (glue, None) }, None => { @@ -233,8 +233,8 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, assert!(sig.inputs.len() == 1); sig.inputs[0] } - _ => bcx.sess().bug(format!("Expected function type, found {}", - bcx.ty_to_string(fty)).index(&FullRange)) + _ => bcx.sess().bug(&format!("Expected function type, found {}", + bcx.ty_to_string(fty))[]) }; let (struct_data, info) = if type_is_sized(bcx.tcx(), t) { @@ -295,7 +295,7 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, class_did, &[get_drop_glue_type(bcx.ccx(), t)], ty::mk_nil(bcx.tcx())); - let (_, variant_cx) = invoke(variant_cx, dtor_addr, args.index(&FullRange), dtor_ty, None); + let (_, variant_cx) = invoke(variant_cx, dtor_addr, &args[], dtor_ty, None); variant_cx.fcx.pop_and_trans_custom_cleanup_scope(variant_cx, field_scope); variant_cx @@ -353,8 +353,8 @@ fn size_and_align_of_dst<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, info: let unit_size = llsize_of_alloc(bcx.ccx(), llunit_ty); (Mul(bcx, info, C_uint(bcx.ccx(), unit_size)), C_uint(bcx.ccx(), 8u)) } - _ => bcx.sess().bug(format!("Unexpected unsized type, found {}", - bcx.ty_to_string(t)).index(&FullRange)) + _ => bcx.sess().bug(&format!("Unexpected unsized type, found {}", + bcx.ty_to_string(t))[]) } } @@ -423,10 +423,10 @@ fn make_drop_glue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, v0: ValueRef, t: Ty<'tcx>) } else { // Give the user a heads up that we are doing something // stupid and dangerous. - bcx.sess().warn(format!("Ignoring drop flag in destructor for {}\ + bcx.sess().warn(&format!("Ignoring drop flag in destructor for {}\ because the struct is unsized. See issue\ #16758", - bcx.ty_to_string(t)).index(&FullRange)); + bcx.ty_to_string(t))[]); trans_struct_drop(bcx, t, v0, dtor, did, substs) } } @@ -496,7 +496,7 @@ pub fn declare_tydesc<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) note_unique_llvm_symbol(ccx, name); let ty_name = token::intern_and_get_ident( - ppaux::ty_to_string(ccx.tcx(), t).index(&FullRange)); + &ppaux::ty_to_string(ccx.tcx(), t)[]); let ty_name = C_str_slice(ccx, ty_name); debug!("--- declare_tydesc {}", ppaux::ty_to_string(ccx.tcx(), t)); @@ -515,8 +515,8 @@ fn declare_generic_glue<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, let fn_nm = mangle_internal_name_by_type_and_seq( ccx, t, - format!("glue_{}", name).index(&FullRange)); - let llfn = decl_cdecl_fn(ccx, fn_nm.index(&FullRange), llfnty, ty::mk_nil(ccx.tcx())); + &format!("glue_{}", name)[]); + let llfn = decl_cdecl_fn(ccx, &fn_nm[], llfnty, ty::mk_nil(ccx.tcx())); note_unique_llvm_symbol(ccx, fn_nm.clone()); return (fn_nm, llfn); } diff --git a/src/librustc_trans/trans/intrinsic.rs b/src/librustc_trans/trans/intrinsic.rs index ed75445b993..b22c7f763f0 100644 --- a/src/librustc_trans/trans/intrinsic.rs +++ b/src/librustc_trans/trans/intrinsic.rs @@ -313,7 +313,7 @@ pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, (_, "size_of") => { let tp_ty = *substs.types.get(FnSpace, 0); let lltp_ty = type_of::type_of(ccx, tp_ty); - C_uint(ccx, machine::llsize_of_real(ccx, lltp_ty)) + C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty)) } (_, "min_align_of") => { let tp_ty = *substs.types.get(FnSpace, 0); diff --git a/src/librustc_trans/trans/machine.rs b/src/librustc_trans/trans/machine.rs index 41738f1e58f..95d67cd54c1 100644 --- a/src/librustc_trans/trans/machine.rs +++ b/src/librustc_trans/trans/machine.rs @@ -43,8 +43,10 @@ pub fn llsize_of_alloc(cx: &CrateContext, ty: Type) -> llsize { // Returns, as near as we can figure, the "real" size of a type. As in, the // bits in this number of bytes actually carry data related to the datum -// with the type. Not junk, padding, accidentally-damaged words, or -// whatever. Rounds up to the nearest byte though, so if you have a 1-bit +// with the type. Not junk, accidentally-damaged words, or whatever. +// Note that padding of the type will be included for structs, but not for the +// other types (i.e. SIMD types). +// Rounds up to the nearest byte though, so if you have a 1-bit // value, we return 1 here, not 0. Most of rustc works in bytes. Be warned // that LLVM *does* distinguish between e.g. a 1-bit value and an 8-bit value // at the codegen level! In general you should prefer `llbitsize_of_real` diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 28718ffa980..7ac062108f3 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -77,7 +77,7 @@ pub fn trans_impl(ccx: &CrateContext, match *impl_item { ast::MethodImplItem(ref method) => { if method.pe_generics().ty_params.len() == 0u { - let trans_everywhere = attr::requests_inline(method.attrs.index(&FullRange)); + let trans_everywhere = attr::requests_inline(&method.attrs[]); for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) { let llfn = get_item_val(ccx, method.id); trans_fn(ccx, @@ -229,7 +229,7 @@ pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, // Here, in this call, which I've written with explicit UFCS // notation, the set of type parameters will be: // - // rcvr_type: .index(&FullRange) <-- nothing declared on the trait itself + // rcvr_type: [] <-- nothing declared on the trait itself // rcvr_self: [Vec<int>] <-- the self type // rcvr_method: [String] <-- method type parameter // @@ -268,11 +268,11 @@ pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, // // Recall that we matched `<Vec<int> as Convert>`. Trait // resolution will have given us a substitution - // containing `impl_substs=[[T=int],.index(&FullRange),.index(&FullRange)]` (the type + // containing `impl_substs=[[T=int],[],[]]` (the type // parameters defined on the impl). We combine // that with the `rcvr_method` from before, which tells us // the type parameters from the *method*, to yield - // `callee_substs=[[T=int],.index(&FullRange),[U=String]]`. + // `callee_substs=[[T=int],[],[U=String]]`. let subst::SeparateVecsPerParamSpace { types: impl_type, selfs: impl_self, @@ -289,8 +289,8 @@ pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, callee_substs) } _ => { - tcx.sess.bug(format!("static call to invalid vtable: {}", - vtbl.repr(tcx)).index(&FullRange)); + tcx.sess.bug(&format!("static call to invalid vtable: {}", + vtbl.repr(tcx))[]); } } } @@ -377,8 +377,8 @@ fn trans_monomorphized_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, traits::VtableBuiltin(..) | traits::VtableParam(..) => { bcx.sess().bug( - format!("resolved vtable bad vtable {} in trans", - vtable.repr(bcx.tcx())).index(&FullRange)); + &format!("resolved vtable bad vtable {} in trans", + vtable.repr(bcx.tcx()))[]); } } } @@ -738,9 +738,9 @@ pub fn get_vtable<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } traits::VtableParam => { bcx.sess().bug( - format!("resolved vtable for {} to bad vtable {} in trans", + &format!("resolved vtable for {} to bad vtable {} in trans", trait_ref.repr(bcx.tcx()), - vtable.repr(bcx.tcx())).index(&FullRange)); + vtable.repr(bcx.tcx()))[]); } } }); @@ -772,7 +772,7 @@ pub fn make_vtable<I: Iterator<Item=ValueRef>>(ccx: &CrateContext, let components: Vec<_> = head.into_iter().chain(ptrs).collect(); unsafe { - let tbl = C_struct(ccx, components.index(&FullRange), false); + let tbl = C_struct(ccx, &components[], false); let sym = token::gensym("vtable"); let buf = CString::from_vec(format!("vtable{}", sym.uint()).into_bytes()); let vt_gvar = llvm::LLVMAddGlobal(ccx.llmod(), val_ty(tbl).to_ref(), diff --git a/src/librustc_trans/trans/monomorphize.rs b/src/librustc_trans/trans/monomorphize.rs index e2594765f4f..93076260349 100644 --- a/src/librustc_trans/trans/monomorphize.rs +++ b/src/librustc_trans/trans/monomorphize.rs @@ -32,7 +32,7 @@ use syntax::ast_map; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::attr; use syntax::codemap::DUMMY_SP; -use std::hash::{sip, Hash}; +use std::hash::{Hasher, Hash, SipHasher}; pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_id: ast::DefId, @@ -125,13 +125,13 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let hash; let s = { - let mut state = sip::SipState::new(); + let mut state = SipHasher::new(); hash_id.hash(&mut state); mono_ty.hash(&mut state); - hash = format!("h{}", state.result()); + hash = format!("h{}", state.finish()); ccx.tcx().map.with_path(fn_id.node, |path| { - exported_name(path, hash.index(&FullRange)) + exported_name(path, &hash[]) }) }; @@ -141,9 +141,9 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let mut hash_id = Some(hash_id); let mut mk_lldecl = |&mut : abi: abi::Abi| { let lldecl = if abi != abi::Rust { - foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, s.index(&FullRange)) + foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s[]) } else { - decl_internal_rust_fn(ccx, mono_ty, s.index(&FullRange)) + decl_internal_rust_fn(ccx, mono_ty, &s[]) }; ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl); @@ -177,12 +177,12 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, .. } => { let d = mk_lldecl(abi); - let needs_body = setup_lldecl(d, i.attrs.index(&FullRange)); + let needs_body = setup_lldecl(d, &i.attrs[]); if needs_body { if abi != abi::Rust { foreign::trans_rust_fn_with_foreign_abi( ccx, &**decl, &**body, &[], d, psubsts, fn_id.node, - Some(hash.index(&FullRange))); + Some(&hash[])); } else { trans_fn(ccx, &**decl, &**body, d, psubsts, fn_id.node, &[]); } @@ -206,7 +206,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, trans_enum_variant(ccx, parent, &*v, - args.index(&FullRange), + &args[], this_tv.disr_val, psubsts, d); @@ -220,7 +220,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, match *ii { ast::MethodImplItem(ref mth) => { let d = mk_lldecl(abi::Rust); - let needs_body = setup_lldecl(d, mth.attrs.index(&FullRange)); + let needs_body = setup_lldecl(d, &mth.attrs[]); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), @@ -241,7 +241,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, match *method { ast::ProvidedMethod(ref mth) => { let d = mk_lldecl(abi::Rust); - let needs_body = setup_lldecl(d, mth.attrs.index(&FullRange)); + let needs_body = setup_lldecl(d, &mth.attrs[]); if needs_body { trans_fn(ccx, mth.pe_fn_decl(), mth.pe_body(), d, psubsts, mth.id, &[]); @@ -249,8 +249,8 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, d } _ => { - ccx.sess().bug(format!("can't monomorphize a {:?}", - map_node).index(&FullRange)) + ccx.sess().bug(&format!("can't monomorphize a {:?}", + map_node)[]) } } } @@ -258,7 +258,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let d = mk_lldecl(abi::Rust); set_inline_hint(d); base::trans_tuple_struct(ccx, - struct_def.fields.index(&FullRange), + &struct_def.fields[], struct_def.ctor_id.expect("ast-mapped tuple struct \ didn't have a ctor id"), psubsts, @@ -275,8 +275,8 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ast_map::NodeBlock(..) | ast_map::NodePat(..) | ast_map::NodeLocal(..) => { - ccx.sess().bug(format!("can't monomorphize a {:?}", - map_node).index(&FullRange)) + ccx.sess().bug(&format!("can't monomorphize a {:?}", + map_node)[]) } }; @@ -300,8 +300,6 @@ pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>, -> T where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone { - assert!(param_substs.regions.is_erased()); - let substituted = value.subst(tcx, param_substs); normalize_associated_type(tcx, &substituted) } @@ -315,8 +313,10 @@ pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T { debug!("normalize_associated_type(t={})", value.repr(tcx)); + let value = erase_regions(tcx, value); + if !value.has_projection_types() { - return value.clone(); + return value; } // FIXME(#20304) -- cache @@ -326,7 +326,7 @@ pub fn normalize_associated_type<'tcx,T>(tcx: &ty::ctxt<'tcx>, value: &T) -> T let mut selcx = traits::SelectionContext::new(&infcx, &typer); let cause = traits::ObligationCause::dummy(); let traits::Normalized { value: result, obligations } = - traits::normalize(&mut selcx, cause, value); + traits::normalize(&mut selcx, cause, &value); debug!("normalize_associated_type: result={} obligations={}", result.repr(tcx), diff --git a/src/librustc_trans/trans/type_.rs b/src/librustc_trans/trans/type_.rs index 66e27ed1188..71a7789eb39 100644 --- a/src/librustc_trans/trans/type_.rs +++ b/src/librustc_trans/trans/type_.rs @@ -103,7 +103,7 @@ impl Type { } pub fn int(ccx: &CrateContext) -> Type { - match ccx.tcx().sess.target.target.target_word_size.index(&FullRange) { + match &ccx.tcx().sess.target.target.target_pointer_width[] { "32" => Type::i32(ccx), "64" => Type::i64(ccx), tws => panic!("Unsupported target word size for int: {}", tws), @@ -112,7 +112,7 @@ impl Type { pub fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type { match t { - ast::TyIs => ccx.int_type(), + ast::TyIs(_) => ccx.int_type(), ast::TyI8 => Type::i8(ccx), ast::TyI16 => Type::i16(ccx), ast::TyI32 => Type::i32(ccx), @@ -122,7 +122,7 @@ impl Type { pub fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type { match t { - ast::TyUs => ccx.int_type(), + ast::TyUs(_) => ccx.int_type(), ast::TyU8 => Type::i8(ccx), ast::TyU16 => Type::i16(ccx), ast::TyU32 => Type::i32(ccx), diff --git a/src/librustc_trans/trans/type_of.rs b/src/librustc_trans/trans/type_of.rs index 19d50cdd483..99330797422 100644 --- a/src/librustc_trans/trans/type_of.rs +++ b/src/librustc_trans/trans/type_of.rs @@ -140,7 +140,7 @@ pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); - Type::func(atys.index(&FullRange), &lloutputtype) + Type::func(&atys[], &lloutputtype) } // Given a function type and a count of ty params, construct an llvm type @@ -180,8 +180,8 @@ pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Typ let llsizingty = match t.sty { _ if !lltype_is_sized(cx.tcx(), t) => { - cx.sess().bug(format!("trying to take the sizing type of {}, an unsized type", - ppaux::ty_to_string(cx.tcx(), t)).index(&FullRange)) + cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type", + ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_bool => Type::bool(cx), @@ -233,8 +233,8 @@ pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Typ } ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => { - cx.sess().bug(format!("fictitious type {} in sizing_type_of()", - ppaux::ty_to_string(cx.tcx(), t)).index(&FullRange)) + cx.sess().bug(&format!("fictitious type {} in sizing_type_of()", + ppaux::ty_to_string(cx.tcx(), t))[]) } ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable") }; @@ -263,7 +263,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { } match unsized_part_of_type(cx.tcx(), t).sty { - ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs), + ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs(false)), ty::ty_trait(_) => Type::vtable_ptr(cx), _ => panic!("Unexpected type returned from unsized_part_of_type : {}", t.repr(cx.tcx())) @@ -285,7 +285,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. - let t_norm = normalize_ty(cx.tcx(), t); + let t_norm = erase_regions(cx.tcx(), &t); if t != t_norm { let llty = type_of(cx, t_norm); @@ -313,7 +313,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, an_enum, did, tps); - adt::incomplete_type_of(cx, &*repr, name.index(&FullRange)) + adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_unboxed_closure(did, _, ref substs) => { // Only create the named struct, but don't fill it in. We @@ -324,7 +324,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // contents of the VecPerParamSpace to to construct the llvm // name let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice()); - adt::incomplete_type_of(cx, &*repr, name.index(&FullRange)) + adt::incomplete_type_of(cx, &*repr, &name[]) } ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => { @@ -380,7 +380,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { let repr = adt::represent_type(cx, t); let tps = substs.types.get_slice(subst::TypeSpace); let name = llvm_type_name(cx, a_struct, did, tps); - adt::incomplete_type_of(cx, &*repr, name.index(&FullRange)) + adt::incomplete_type_of(cx, &*repr, &name[]) } } @@ -398,8 +398,8 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), - _ => cx.sess().bug(format!("ty_open with sized type: {}", - ppaux::ty_to_string(cx.tcx(), t)).index(&FullRange)) + _ => cx.sess().bug(&format!("ty_open with sized type: {}", + ppaux::ty_to_string(cx.tcx(), t))[]) }, ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 265ebe00d53..2046ee015f6 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -52,7 +52,6 @@ use middle::const_eval; use middle::def; use middle::resolve_lifetime as rl; use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs}; -use middle::subst::{VecPerParamSpace}; use middle::traits; use middle::ty::{self, RegionEscape, ToPolyTraitRef, Ty}; use rscope::{self, UnelidableRscope, RegionScope, SpecificRscope, @@ -193,11 +192,11 @@ pub fn opt_ast_region_to_region<'tcx>( format!("`{}`", name) }; - m.push_str(if n == 1 { + m.push_str(&(if n == 1 { help_name } else { format!("one of {}'s {} elided lifetimes", help_name, n) - }.index(&FullRange)); + })[]); if len == 2 && i == 0 { m.push_str(" or "); @@ -244,7 +243,7 @@ pub fn opt_ast_region_to_region<'tcx>( /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, /// returns an appropriate set of substitutions for this particular reference to `I`. -fn ast_path_substs_for_ty<'tcx>( +pub fn ast_path_substs_for_ty<'tcx>( this: &AstConv<'tcx>, rscope: &RegionScope, decl_generics: &ty::Generics<'tcx>, @@ -344,10 +343,10 @@ fn create_substs_for_ast_path<'tcx>( "expected" }; this.tcx().sess.span_fatal(span, - format!("wrong number of type arguments: {} {}, found {}", + &format!("wrong number of type arguments: {} {}, found {}", expected, required_ty_param_count, - supplied_ty_param_count).index(&FullRange)); + supplied_ty_param_count)[]); } else if supplied_ty_param_count > formal_ty_param_count { let expected = if required_ty_param_count < formal_ty_param_count { "expected at most" @@ -355,10 +354,10 @@ fn create_substs_for_ast_path<'tcx>( "expected" }; this.tcx().sess.span_fatal(span, - format!("wrong number of type arguments: {} {}, found {}", + &format!("wrong number of type arguments: {} {}, found {}", expected, formal_ty_param_count, - supplied_ty_param_count).index(&FullRange)); + supplied_ty_param_count)[]); } let mut substs = Substs::new_type(types, regions); @@ -377,7 +376,7 @@ fn create_substs_for_ast_path<'tcx>( } } - for param in ty_param_defs.index(&(supplied_ty_param_count..)).iter() { + for param in ty_param_defs[supplied_ty_param_count..].iter() { match param.default { Some(default) => { // This is a default type parameter. @@ -556,8 +555,8 @@ pub fn instantiate_trait_ref<'tcx>( _ => { this.tcx().sess.span_fatal( ast_trait_ref.path.span, - format!("`{}` is not a trait", - ast_trait_ref.path.user_string(this.tcx())).index(&FullRange)); + &format!("`{}` is not a trait", + ast_trait_ref.path.user_string(this.tcx()))[]); } } } @@ -762,50 +761,6 @@ pub fn ast_path_to_ty<'tcx>( TypeAndSubsts { substs: substs, ty: ty } } -/// Returns the type that this AST path refers to. If the path has no type -/// parameters and the corresponding type has type parameters, fresh type -/// and/or region variables are substituted. -/// -/// This is used when checking the constructor in struct literals. -pub fn ast_path_to_ty_relaxed<'tcx>( - this: &AstConv<'tcx>, - rscope: &RegionScope, - did: ast::DefId, - path: &ast::Path) - -> TypeAndSubsts<'tcx> -{ - let tcx = this.tcx(); - let ty::TypeScheme { - generics, - ty: decl_ty - } = this.get_item_type_scheme(did); - - let wants_params = - generics.has_type_params(TypeSpace) || generics.has_region_params(TypeSpace); - - let needs_defaults = - wants_params && - path.segments.iter().all(|s| s.parameters.is_empty()); - - let substs = if needs_defaults { - let type_params: Vec<_> = range(0, generics.types.len(TypeSpace)) - .map(|_| this.ty_infer(path.span)).collect(); - let region_params = - rscope.anon_regions(path.span, generics.regions.len(TypeSpace)) - .unwrap(); - Substs::new(VecPerParamSpace::params_from_type(type_params), - VecPerParamSpace::params_from_type(region_params)) - } else { - ast_path_substs_for_ty(this, rscope, &generics, path) - }; - - let ty = decl_ty.subst(tcx, &substs); - TypeAndSubsts { - substs: substs, - ty: ty, - } -} - /// Converts the given AST type to a built-in type. A "built-in type" is, at /// present, either a core numeric type, a string, or `Box`. pub fn ast_ty_to_builtin_ty<'tcx>( @@ -825,8 +780,8 @@ pub fn ast_ty_to_builtin_ty<'tcx>( this.tcx() .sess .span_bug(ast_ty.span, - format!("unbound path {}", - path.repr(this.tcx())).index(&FullRange)) + &format!("unbound path {}", + path.repr(this.tcx()))[]) } Some(&d) => d }; @@ -847,8 +802,8 @@ pub fn ast_ty_to_builtin_ty<'tcx>( _ => { this.tcx().sess.span_bug( path.span, - format!("converting `Box` to `{}`", - ty.repr(this.tcx())).index(&FullRange)); + &format!("converting `Box` to `{}`", + ty.repr(this.tcx()))[]); } } } @@ -1068,14 +1023,14 @@ pub fn ast_ty_to_ty<'tcx>( ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None) } ast::TyObjectSum(ref ty, ref bounds) => { - match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) { + match ast_ty_to_trait_ref(this, rscope, &**ty, &bounds[]) { Ok((trait_ref, projection_bounds)) => { trait_ref_to_object_type(this, rscope, ast_ty.span, trait_ref, projection_bounds, - bounds.index(&FullRange)) + &bounds[]) } Err(ErrorReported) => { this.tcx().types.err @@ -1110,15 +1065,15 @@ pub fn ast_ty_to_ty<'tcx>( ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(bare_fn)) } ast::TyPolyTraitRef(ref bounds) => { - conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds.index(&FullRange)) + conv_ty_poly_trait_ref(this, rscope, ast_ty.span, &bounds[]) } ast::TyPath(ref path, id) => { let a_def = match tcx.def_map.borrow().get(&id) { None => { tcx.sess .span_bug(ast_ty.span, - format!("unbound path {}", - path.repr(tcx)).index(&FullRange)) + &format!("unbound path {}", + path.repr(tcx))[]) } Some(&d) => d }; @@ -1156,8 +1111,8 @@ pub fn ast_ty_to_ty<'tcx>( } def::DefMod(id) => { tcx.sess.span_fatal(ast_ty.span, - format!("found module name used as a type: {}", - tcx.map.node_to_string(id.node)).index(&FullRange)); + &format!("found module name used as a type: {}", + tcx.map.node_to_string(id.node))[]); } def::DefPrimTy(_) => { panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call"); @@ -1166,7 +1121,7 @@ pub fn ast_ty_to_ty<'tcx>( let path_str = tcx.map.path_to_string( tcx.map.get_parent(trait_type_id.node)); tcx.sess.span_err(ast_ty.span, - format!("ambiguous associated \ + &format!("ambiguous associated \ type; specify the type \ using the syntax `<Type \ as {}>::{}`", @@ -1176,7 +1131,7 @@ pub fn ast_ty_to_ty<'tcx>( .last() .unwrap() .identifier) - .get()).index(&FullRange)); + .get())[]); this.tcx().types.err } def::DefAssociatedPath(provenance, assoc_ident) => { @@ -1184,9 +1139,9 @@ pub fn ast_ty_to_ty<'tcx>( } _ => { tcx.sess.span_fatal(ast_ty.span, - format!("found value name used \ + &format!("found value name used \ as a type: {:?}", - a_def).index(&FullRange)); + a_def)[]); } } } @@ -1212,9 +1167,9 @@ pub fn ast_ty_to_ty<'tcx>( Err(ref r) => { tcx.sess.span_fatal( ast_ty.span, - format!("expected constant expr for array \ + &format!("expected constant expr for array \ length: {}", - *r).index(&FullRange)); + *r)[]); } } } @@ -1336,7 +1291,7 @@ fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>, let input_params = if self_ty.is_some() { decl.inputs.slice_from(1) } else { - decl.inputs.index(&FullRange) + &decl.inputs[] }; let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None)); let input_pats: Vec<String> = input_params.iter() @@ -1551,7 +1506,7 @@ fn conv_ty_poly_trait_ref<'tcx>( ast_bounds: &[ast::TyParamBound]) -> Ty<'tcx> { - let mut partitioned_bounds = partition_bounds(this.tcx(), span, ast_bounds.index(&FullRange)); + let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[]); let mut projection_bounds = Vec::new(); let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() { @@ -1600,8 +1555,8 @@ pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>( let b = &trait_bounds[0]; this.tcx().sess.span_err( b.trait_ref.path.span, - format!("only the builtin traits can be used \ - as closure or object bounds").index(&FullRange)); + &format!("only the builtin traits can be used \ + as closure or object bounds")[]); } let region_bound = compute_region_bound(this, @@ -1673,8 +1628,8 @@ fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>, if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) { tcx.sess.span_err( span, - format!("ambiguous lifetime bound, \ - explicit lifetime bound required").index(&FullRange)); + &format!("ambiguous lifetime bound, \ + explicit lifetime bound required")[]); } return Some(r); } @@ -1700,7 +1655,7 @@ fn compute_region_bound<'tcx>( None => { this.tcx().sess.span_err( span, - format!("explicit lifetime bound required").index(&FullRange)); + &format!("explicit lifetime bound required")[]); ty::ReStatic } } diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index d9829fd1416..cacf9bb19d2 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -195,14 +195,6 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, ast::PatRegion(ref inner, mutbl) => { let inner_ty = fcx.infcx().next_ty_var(); - // SNAP 340ac04 remove this `if`-`else` entirely after next snapshot - let mutbl = if mutbl == ast::MutImmutable { - ty::deref(fcx.infcx().shallow_resolve(expected), true) - .map(|mt| mt.mutbl).unwrap_or(ast::MutImmutable) - } else { - mutbl - }; - let mt = ty::mt { ty: inner_ty, mutbl: mutbl }; let region = fcx.infcx().next_region_var(infer::PatternRegion(pat.span)); let rptr_ty = ty::mk_rptr(tcx, tcx.mk_region(region), mt); diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index dff216ac293..19a88dfc553 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -73,7 +73,7 @@ pub fn check_call<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, autoderef(fcx, callee_expr.span, original_callee_ty, - Some(callee_expr.id), + Some(callee_expr), LvaluePreference::NoPreference, |adj_ty, idx| { let autoderefref = ty::AutoDerefRef { autoderefs: idx, autoref: None }; diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index cd27c20db45..79460774859 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -143,7 +143,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { // time writing the results into the various tables. let (autoderefd_ty, n, result) = check::autoderef( - self.fcx, self.span, unadjusted_self_ty, Some(self.self_expr.id), NoPreference, + self.fcx, self.span, unadjusted_self_ty, Some(self.self_expr), NoPreference, |_, n| if n == auto_deref_ref.autoderefs { Some(()) } else { None }); assert_eq!(n, auto_deref_ref.autoderefs); assert_eq!(result, Some(())); @@ -314,8 +314,8 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { None => { self.tcx().sess.span_bug( self.span, - format!("self-type `{}` for ObjectPick never dereferenced to an object", - self_ty.repr(self.tcx())).index(&FullRange)) + &format!("self-type `{}` for ObjectPick never dereferenced to an object", + self_ty.repr(self.tcx()))[]) } } } @@ -367,10 +367,10 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { Err(_) => { self.tcx().sess.span_bug( self.span, - format!( + &format!( "{} was a subtype of {} but now is not?", self_ty.repr(self.tcx()), - method_self_ty.repr(self.tcx())).index(&FullRange)); + method_self_ty.repr(self.tcx()))[]); } } } @@ -492,7 +492,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { exprs.repr(self.tcx())); // Fix up autoderefs and derefs. - for (i, expr) in exprs.iter().rev().enumerate() { + for (i, &expr) in exprs.iter().rev().enumerate() { // Count autoderefs. let autoderef_count = match self.fcx .inh @@ -512,8 +512,8 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { if autoderef_count > 0 { check::autoderef(self.fcx, expr.span, - self.fcx.expr_ty(*expr), - Some(expr.id), + self.fcx.expr_ty(expr), + Some(expr), PreferMutLvalue, |_, autoderefs| { if autoderefs == autoderef_count + 1 { @@ -567,7 +567,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { let result = check::try_index_step( self.fcx, MethodCall::expr(expr.id), - *expr, + expr, &**base_expr, adjusted_base_ty, base_adjustment, @@ -577,7 +577,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { if let Some((input_ty, return_ty)) = result { demand::suptype(self.fcx, index_expr.span, input_ty, index_expr_ty); - let expr_ty = self.fcx.expr_ty(&**expr); + let expr_ty = self.fcx.expr_ty(&*expr); demand::suptype(self.fcx, expr.span, expr_ty, return_ty); } } diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 87ea082b6b2..0c53a16a811 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -102,9 +102,9 @@ pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types)) } -pub fn lookup_in_trait<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, +pub fn lookup_in_trait<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, span: Span, - self_expr: Option<&'a ast::Expr>, + self_expr: Option<&ast::Expr>, m_name: ast::Name, trait_def_id: DefId, self_ty: Ty<'tcx>, @@ -125,9 +125,9 @@ pub fn lookup_in_trait<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, /// method-lookup code. In particular, autoderef on index is basically identical to autoderef with /// normal probes, except that the test also looks for built-in indexing. Also, the second half of /// this method is basically the same as confirmation. -pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, +pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, span: Span, - self_expr: Option<&'a ast::Expr>, + self_expr: Option<&ast::Expr>, m_name: ast::Name, trait_def_id: DefId, autoderefref: ty::AutoDerefRef<'tcx>, @@ -264,9 +264,9 @@ pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, _ => { fcx.tcx().sess.span_bug( span, - format!( + &format!( "trait method is &self but first arg is: {}", - transformed_self_ty.repr(fcx.tcx())).index(&FullRange)); + transformed_self_ty.repr(fcx.tcx()))[]); } } } @@ -274,9 +274,9 @@ pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, _ => { fcx.tcx().sess.span_bug( span, - format!( + &format!( "unexpected explicit self type in operator method: {:?}", - method_ty.explicit_self).index(&FullRange)); + method_ty.explicit_self)[]); } } } @@ -329,8 +329,8 @@ pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // If the method has the name of a field, give a help note if is_field { cx.sess.span_note(span, - format!("use `(s.{0})(...)` if you meant to call the \ - function stored in the `{0}` field", method_ustring).index(&FullRange)); + &format!("use `(s.{0})(...)` if you meant to call the \ + function stored in the `{0}` field", method_ustring)[]); } if static_sources.len() > 0 { diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 4ba161fa835..dc4d6c9a826 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -18,7 +18,7 @@ use middle::fast_reject; use middle::subst; use middle::subst::Subst; use middle::traits; -use middle::ty::{self, Ty, ToPolyTraitRef}; +use middle::ty::{self, RegionEscape, Ty, ToPolyTraitRef}; use middle::ty_fold::TypeFoldable; use middle::infer; use middle::infer::InferCtxt; @@ -62,6 +62,7 @@ enum CandidateKind<'tcx> { subst::Substs<'tcx>, MethodIndex), UnboxedClosureCandidate(/* Trait */ ast::DefId, MethodIndex), WhereClauseCandidate(ty::PolyTraitRef<'tcx>, MethodIndex), + ProjectionCandidate(ast::DefId, MethodIndex), } pub struct Pick<'tcx> { @@ -309,18 +310,20 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { // argument type like `&Trait`. let trait_ref = data.principal_trait_ref_with_self_ty(self.tcx(), self_ty); self.elaborate_bounds(&[trait_ref.clone()], false, |this, new_trait_ref, m, method_num| { + let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref); + let vtable_index = traits::get_vtable_index_of_object_method(tcx, trait_ref.clone(), - new_trait_ref.def_id(), + new_trait_ref.def_id, method_num); - let xform_self_ty = this.xform_self_ty(&m, new_trait_ref.substs()); + let xform_self_ty = this.xform_self_ty(&m, new_trait_ref.substs); this.inherent_candidates.push(Candidate { xform_self_ty: xform_self_ty, method_ty: m, - kind: ObjectCandidate(new_trait_ref.def_id(), method_num, vtable_index) + kind: ObjectCandidate(new_trait_ref.def_id, method_num, vtable_index) }); }); } @@ -353,34 +356,37 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { }) .collect(); - self.elaborate_bounds(bounds.as_slice(), true, |this, trait_ref, m, method_num| { + self.elaborate_bounds(bounds.as_slice(), true, |this, poly_trait_ref, m, method_num| { + let trait_ref = + this.erase_late_bound_regions(&poly_trait_ref); + let xform_self_ty = - this.xform_self_ty(&m, trait_ref.substs()); + this.xform_self_ty(&m, trait_ref.substs); debug!("found match: trait_ref={} substs={} m={}", trait_ref.repr(this.tcx()), - trait_ref.substs().repr(this.tcx()), + trait_ref.substs.repr(this.tcx()), m.repr(this.tcx())); assert_eq!(m.generics.types.get_slice(subst::TypeSpace).len(), - trait_ref.substs().types.get_slice(subst::TypeSpace).len()); + trait_ref.substs.types.get_slice(subst::TypeSpace).len()); assert_eq!(m.generics.regions.get_slice(subst::TypeSpace).len(), - trait_ref.substs().regions().get_slice(subst::TypeSpace).len()); + trait_ref.substs.regions().get_slice(subst::TypeSpace).len()); assert_eq!(m.generics.types.get_slice(subst::SelfSpace).len(), - trait_ref.substs().types.get_slice(subst::SelfSpace).len()); + trait_ref.substs.types.get_slice(subst::SelfSpace).len()); assert_eq!(m.generics.regions.get_slice(subst::SelfSpace).len(), - trait_ref.substs().regions().get_slice(subst::SelfSpace).len()); + trait_ref.substs.regions().get_slice(subst::SelfSpace).len()); // Because this trait derives from a where-clause, it // should not contain any inference variables or other // artifacts. This means it is safe to put into the // `WhereClauseCandidate` and (eventually) into the // `WhereClausePick`. - assert!(trait_ref.substs().types.iter().all(|&t| !ty::type_needs_infer(t))); + assert!(trait_ref.substs.types.iter().all(|&t| !ty::type_needs_infer(t))); this.inherent_candidates.push(Candidate { xform_self_ty: xform_self_ty, method_ty: m, - kind: WhereClauseCandidate(trait_ref, method_num) + kind: WhereClauseCandidate(poly_trait_ref, method_num) }); }); } @@ -474,6 +480,10 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { method.clone(), matching_index); + self.assemble_projection_candidates(trait_def_id, + method.clone(), + matching_index); + self.assemble_where_clause_candidates(trait_def_id, method, matching_index); @@ -575,8 +585,8 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { None => { self.tcx().sess.span_bug( self.span, - format!("No entry for unboxed closure: {}", - closure_def_id.repr(self.tcx())).index(&FullRange)); + &format!("No entry for unboxed closure: {}", + closure_def_id.repr(self.tcx()))[]); } }; @@ -603,6 +613,64 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { } } + fn assemble_projection_candidates(&mut self, + trait_def_id: ast::DefId, + method: Rc<ty::Method<'tcx>>, + method_index: uint) + { + debug!("assemble_projection_candidates(\ + trait_def_id={}, \ + method={}, \ + method_index={})", + trait_def_id.repr(self.tcx()), + method.repr(self.tcx()), + method_index); + + for step in self.steps.iter() { + debug!("assemble_projection_candidates: step={}", + step.repr(self.tcx())); + + let projection_trait_ref = match step.self_ty.sty { + ty::ty_projection(ref data) => &data.trait_ref, + _ => continue, + }; + + debug!("assemble_projection_candidates: projection_trait_ref={}", + projection_trait_ref.repr(self.tcx())); + + let trait_def = ty::lookup_trait_def(self.tcx(), projection_trait_ref.def_id); + let bounds = trait_def.generics.to_bounds(self.tcx(), projection_trait_ref.substs); + let predicates = bounds.predicates.into_vec(); + debug!("assemble_projection_candidates: predicates={}", + predicates.repr(self.tcx())); + for poly_bound in + traits::elaborate_predicates(self.tcx(), predicates) + .filter_map(|p| p.to_opt_poly_trait_ref()) + .filter(|b| b.def_id() == trait_def_id) + { + let bound = self.erase_late_bound_regions(&poly_bound); + + debug!("assemble_projection_candidates: projection_trait_ref={} bound={}", + projection_trait_ref.repr(self.tcx()), + bound.repr(self.tcx())); + + if self.infcx().can_equate(&step.self_ty, &bound.self_ty()).is_ok() { + let xform_self_ty = self.xform_self_ty(&method, bound.substs); + + debug!("assemble_projection_candidates: bound={} xform_self_ty={}", + bound.repr(self.tcx()), + xform_self_ty.repr(self.tcx())); + + self.extension_candidates.push(Candidate { + xform_self_ty: xform_self_ty, + method_ty: method.clone(), + kind: ProjectionCandidate(trait_def_id, method_index) + }); + } + } + } + } + fn assemble_where_clause_candidates(&mut self, trait_def_id: ast::DefId, method_ty: Rc<ty::Method<'tcx>>, @@ -611,14 +679,14 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { debug!("assemble_where_clause_candidates(trait_def_id={})", trait_def_id.repr(self.tcx())); - // Check whether there are any where-clauses pertaining to this trait. let caller_predicates = self.fcx.inh.param_env.caller_bounds.predicates.as_slice().to_vec(); - for bound in traits::elaborate_predicates(self.tcx(), caller_predicates) - .filter_map(|p| p.to_opt_poly_trait_ref()) - .filter(|b| b.def_id() == trait_def_id) + for poly_bound in traits::elaborate_predicates(self.tcx(), caller_predicates) + .filter_map(|p| p.to_opt_poly_trait_ref()) + .filter(|b| b.def_id() == trait_def_id) { - let xform_self_ty = self.xform_self_ty(&method_ty, bound.substs()); + let bound = self.erase_late_bound_regions(&poly_bound); + let xform_self_ty = self.xform_self_ty(&method_ty, bound.substs); debug!("assemble_where_clause_candidates: bound={} xform_self_ty={}", bound.repr(self.tcx()), @@ -627,7 +695,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { self.extension_candidates.push(Candidate { xform_self_ty: xform_self_ty, method_ty: method_ty.clone(), - kind: WhereClauseCandidate(bound, method_index) + kind: WhereClauseCandidate(poly_bound, method_index) }); } } @@ -745,7 +813,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { debug!("pick_method(self_ty={})", self.infcx().ty_to_string(self_ty)); debug!("searching inherent candidates"); - match self.consider_candidates(self_ty, self.inherent_candidates.index(&FullRange)) { + match self.consider_candidates(self_ty, &self.inherent_candidates[]) { None => {} Some(pick) => { return Some(pick); @@ -753,7 +821,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { } debug!("searching extension candidates"); - self.consider_candidates(self_ty, self.extension_candidates.index(&FullRange)) + self.consider_candidates(self_ty, &self.extension_candidates[]) } fn consider_candidates(&self, @@ -768,7 +836,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { debug!("applicable_candidates: {}", applicable_candidates.repr(self.tcx())); if applicable_candidates.len() > 1 { - match self.collapse_candidates_to_trait_pick(applicable_candidates.index(&FullRange)) { + match self.collapse_candidates_to_trait_pick(&applicable_candidates[]) { Some(pick) => { return Some(Ok(pick)); } None => { } } @@ -829,6 +897,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { norm_obligations.iter().all(|o| selcx.evaluate_obligation(o)) } + ProjectionCandidate(..) | ObjectCandidate(..) | UnboxedClosureCandidate(..) | WhereClauseCandidate(..) => { @@ -864,7 +933,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { Some(data) => data, None => return None, }; - if probes.index(&(1..)).iter().any(|p| p.to_trait_data() != Some(trait_data)) { + if probes[1..].iter().any(|p| p.to_trait_data() != Some(trait_data)) { return None; } @@ -920,6 +989,8 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { method.fty.sig.0.inputs[0].repr(self.tcx()), substs.repr(self.tcx())); + assert!(!substs.has_escaping_regions()); + // It is possible for type parameters or early-bound lifetimes // to appear in the signature of `self`. The substitutions we // are given do not include type/lifetime parameters for the @@ -949,14 +1020,13 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { substs = &placeholder; } - // Replace early-bound regions and types. - let xform_self_ty = method.fty.sig.0.inputs[0].subst(self.tcx(), substs); + // Erase any late-bound regions from the method and substitute + // in the values from the substitution. + let xform_self_ty = method.fty.sig.input(0); + let xform_self_ty = self.erase_late_bound_regions(&xform_self_ty); + let xform_self_ty = xform_self_ty.subst(self.tcx(), substs); - // Replace late-bound regions bound in the impl or - // where-clause (2 levels of binding) and method (1 level of binding). - self.erase_late_bound_regions( - &self.erase_late_bound_regions( - &ty::Binder(ty::Binder(xform_self_ty)))) + xform_self_ty } fn impl_substs(&self, @@ -1065,6 +1135,9 @@ impl<'tcx> Candidate<'tcx> { WhereClausePick((*trait_ref).clone(), index) } + ProjectionCandidate(def_id, index) => { + TraitPick(def_id, index) + } } } } @@ -1076,6 +1149,7 @@ impl<'tcx> Candidate<'tcx> { ExtensionImplCandidate(def_id, _, _, _) => ImplSource(def_id), UnboxedClosureCandidate(trait_def_id, _) => TraitSource(trait_def_id), WhereClauseCandidate(ref trait_ref, _) => TraitSource(trait_ref.def_id()), + ProjectionCandidate(trait_def_id, _) => TraitSource(trait_def_id), } } @@ -1094,6 +1168,9 @@ impl<'tcx> Candidate<'tcx> { WhereClauseCandidate(ref trait_ref, method_num) => { Some((trait_ref.def_id(), method_num)) } + ProjectionCandidate(trait_def_id, method_num) => { + Some((trait_def_id, method_num)) + } } } } @@ -1120,6 +1197,8 @@ impl<'tcx> Repr<'tcx> for CandidateKind<'tcx> { format!("UnboxedClosureCandidate({},{})", a.repr(tcx), b), WhereClauseCandidate(ref a, ref b) => format!("WhereClauseCandidate({},{})", a.repr(tcx), b), + ProjectionCandidate(ref a, ref b) => + format!("ProjectionCandidate({},{})", a.repr(tcx), b), } } } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 9563dd45ca2..1d184131ded 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -90,7 +90,7 @@ use middle::mem_categorization as mc; use middle::mem_categorization::McResult; use middle::pat_util::{self, pat_id_map}; use middle::region::CodeExtent; -use middle::subst::{self, Subst, Substs, VecPerParamSpace, ParamSpace}; +use middle::subst::{self, Subst, Substs, VecPerParamSpace, ParamSpace, TypeSpace}; use middle::traits; use middle::ty::{FnSig, VariantInfo, TypeScheme}; use middle::ty::{Disr, ParamTy, ParameterEnvironment}; @@ -593,7 +593,7 @@ fn check_fn<'a, 'tcx>(ccx: &'a CrateCtxt<'a, 'tcx>, let tcx = ccx.tcx; let err_count_on_creation = tcx.sess.err_count(); - let arg_tys = fn_sig.inputs.index(&FullRange); + let arg_tys = &fn_sig.inputs[]; let ret_ty = fn_sig.output; debug!("check_fn(arg_tys={}, ret_ty={}, fn_id={})", @@ -691,7 +691,7 @@ pub fn check_item(ccx: &CrateCtxt, it: &ast::Item) { ast::ItemEnum(ref enum_definition, _) => { check_enum_variants(ccx, it.span, - enum_definition.variants.index(&FullRange), + &enum_definition.variants[], it.id); } ast::ItemFn(ref decl, _, _, _, ref body) => { @@ -985,21 +985,21 @@ fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, (&ty::StaticExplicitSelfCategory, _) => { tcx.sess.span_err( impl_m_span, - format!("method `{}` has a `{}` declaration in the impl, \ + &format!("method `{}` has a `{}` declaration in the impl, \ but not in the trait", token::get_name(trait_m.name), ppaux::explicit_self_category_to_str( - &impl_m.explicit_self)).index(&FullRange)); + &impl_m.explicit_self))[]); return; } (_, &ty::StaticExplicitSelfCategory) => { tcx.sess.span_err( impl_m_span, - format!("method `{}` has a `{}` declaration in the trait, \ + &format!("method `{}` has a `{}` declaration in the trait, \ but not in the impl", token::get_name(trait_m.name), ppaux::explicit_self_category_to_str( - &trait_m.explicit_self)).index(&FullRange)); + &trait_m.explicit_self))[]); return; } _ => { @@ -1358,9 +1358,9 @@ fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, if trait_params.len() != impl_params.len() { tcx.sess.span_err( span, - format!("lifetime parameters or bounds on method `{}` do \ + &format!("lifetime parameters or bounds on method `{}` do \ not match the trait declaration", - token::get_name(impl_m.name)).index(&FullRange)); + token::get_name(impl_m.name))[]); return false; } @@ -1406,13 +1406,13 @@ fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, let err = if missing.len() != 0 || extra.len() != 0 { tcx.sess.span_err( span, - format!( + &format!( "the lifetime parameter `{}` declared in the impl \ has a distinct set of bounds \ from its counterpart `{}` \ declared in the trait", impl_param.name.user_string(tcx), - trait_param.name.user_string(tcx)).index(&FullRange)); + trait_param.name.user_string(tcx))[]); true } else { false @@ -1421,15 +1421,15 @@ fn compare_impl_method<'tcx>(tcx: &ty::ctxt<'tcx>, if missing.len() != 0 { tcx.sess.span_note( span, - format!("the impl is missing the following bounds: `{}`", - missing.user_string(tcx)).index(&FullRange)); + &format!("the impl is missing the following bounds: `{}`", + missing.user_string(tcx))[]); } if extra.len() != 0 { tcx.sess.span_note( span, - format!("the impl has the following extra bounds: `{}`", - extra.user_string(tcx)).index(&FullRange)); + &format!("the impl has the following extra bounds: `{}`", + extra.user_string(tcx))[]); } if err { @@ -1699,8 +1699,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => { self.tcx().sess.span_bug( span, - format!("no type for local variable {}", - nid).index(&FullRange)); + &format!("no type for local variable {}", + nid)[]); } } } @@ -1709,7 +1709,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// ! gets replaced with (), unconstrained ints with i32, and unconstrained floats with f64. pub fn default_type_parameters(&self) { use middle::ty::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat, Neither}; - for (_, &ref ty) in self.inh.node_types.borrow_mut().iter_mut() { + for (_, &mut ref ty) in self.inh.node_types.borrow_mut().iter_mut() { let resolved = self.infcx().resolve_type_vars_if_possible(ty); if self.infcx().type_var_diverges(resolved) { demand::eqtype(self, codemap::DUMMY_SP, *ty, ty::mk_nil(self.tcx())); @@ -1947,6 +1947,43 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } + /// Returns the type that this AST path refers to. If the path has no type + /// parameters and the corresponding type has type parameters, fresh type + /// and/or region variables are substituted. + /// + /// This is used when checking the constructor in struct literals. + fn instantiate_struct_literal_ty(&self, + did: ast::DefId, + path: &ast::Path) + -> TypeAndSubsts<'tcx> + { + let tcx = self.tcx(); + + let ty::TypeScheme { generics, ty: decl_ty } = ty::lookup_item_type(tcx, did); + + let wants_params = + generics.has_type_params(TypeSpace) || generics.has_region_params(TypeSpace); + + let needs_defaults = + wants_params && + path.segments.iter().all(|s| s.parameters.is_empty()); + + let substs = if needs_defaults { + let tps = + self.infcx().next_ty_vars(generics.types.len(TypeSpace)); + let rps = + self.infcx().region_vars_for_defs(path.span, + generics.regions.get_slice(TypeSpace)); + Substs::new_type(tps, rps) + } else { + astconv::ast_path_substs_for_ty(self, self, &generics, path) + }; + + let ty = self.instantiate_type_scheme(path.span, &substs, &decl_ty); + + TypeAndSubsts { substs: substs, ty: ty } + } + pub fn write_nil(&self, node_id: ast::NodeId) { self.write_ty(node_id, ty::mk_nil(self.tcx())); } @@ -2033,8 +2070,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match self.inh.node_types.borrow().get(&ex.id) { Some(&t) => t, None => { - self.tcx().sess.bug(format!("no type for expr in fcx {}", - self.tag()).index(&FullRange)); + self.tcx().sess.bug(&format!("no type for expr in fcx {}", + self.tag())[]); } } } @@ -2062,9 +2099,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(&t) => t, None => { self.tcx().sess.bug( - format!("no type for node {}: {} in fcx {}", + &format!("no type for node {}: {} in fcx {}", id, self.tcx().map.node_to_string(id), - self.tag()).index(&FullRange)); + self.tag())[]); } } } @@ -2231,12 +2268,17 @@ pub enum LvaluePreference { pub fn autoderef<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>, sp: Span, base_ty: Ty<'tcx>, - expr_id: Option<ast::NodeId>, + opt_expr: Option<&ast::Expr>, mut lvalue_pref: LvaluePreference, mut should_stop: F) - -> (Ty<'tcx>, uint, Option<T>) where - F: FnMut(Ty<'tcx>, uint) -> Option<T>, + -> (Ty<'tcx>, uint, Option<T>) + where F: FnMut(Ty<'tcx>, uint) -> Option<T>, { + debug!("autoderef(base_ty={}, opt_expr={}, lvalue_pref={:?})", + base_ty.repr(fcx.tcx()), + opt_expr.repr(fcx.tcx()), + lvalue_pref); + let mut t = base_ty; for autoderefs in range(0, fcx.tcx().sess.recursion_limit.get()) { let resolved_t = structurally_resolved_type(fcx, sp, t); @@ -2254,7 +2296,19 @@ pub fn autoderef<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>, let mt = match ty::deref(resolved_t, false) { Some(mt) => Some(mt), None => { - let method_call = expr_id.map(|id| MethodCall::autoderef(id, autoderefs)); + let method_call = opt_expr.map(|expr| MethodCall::autoderef(expr.id, autoderefs)); + + // Super subtle: it might seem as though we should + // pass `opt_expr` to `try_overloaded_deref`, so that + // the (implicit) autoref of using an overloaded deref + // would get added to the adjustment table. However we + // do not do that, because it's kind of a + // "meta-adjustment" -- instead, we just leave it + // unrecorded and know that there "will be" an + // autoref. regionck and other bits of the code base, + // when they encounter an overloaded autoderef, have + // to do some reconstructive surgery. This is a pretty + // complex mess that is begging for a proper MIR. try_overloaded_deref(fcx, sp, method_call, None, resolved_t, lvalue_pref) } }; @@ -2287,7 +2341,7 @@ fn try_overloaded_deref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // Try DerefMut first, if preferred. let method = match (lvalue_pref, fcx.tcx().lang_items.deref_mut_trait()) { (PreferMutLvalue, Some(trait_did)) => { - method::lookup_in_trait(fcx, span, base_expr.map(|x| &*x), + method::lookup_in_trait(fcx, span, base_expr, token::intern("deref_mut"), trait_did, base_ty, None) } @@ -2297,7 +2351,7 @@ fn try_overloaded_deref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // Otherwise, fall back to Deref. let method = match (method, fcx.tcx().lang_items.deref_trait()) { (None, Some(trait_did)) => { - method::lookup_in_trait(fcx, span, base_expr.map(|x| &*x), + method::lookup_in_trait(fcx, span, base_expr, token::intern("deref"), trait_did, base_ty, None) } @@ -2353,7 +2407,7 @@ fn autoderef_for_index<'a, 'tcx, T, F>(fcx: &FnCtxt<'a, 'tcx>, // consolidated. let (ty, autoderefs, final_mt) = - autoderef(fcx, base_expr.span, base_ty, Some(base_expr.id), lvalue_pref, |adj_ty, idx| { + autoderef(fcx, base_expr.span, base_ty, Some(base_expr), lvalue_pref, |adj_ty, idx| { let autoderefref = ty::AutoDerefRef { autoderefs: idx, autoref: None }; step(adj_ty, autoderefref) }); @@ -2405,7 +2459,7 @@ fn try_index_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, // First, try built-in indexing. match (ty::index(adjusted_ty), &index_ty.sty) { - (Some(ty), &ty::ty_uint(ast::TyUs)) | (Some(ty), &ty::ty_infer(ty::IntVar(_))) => { + (Some(ty), &ty::ty_uint(ast::TyUs(_))) | (Some(ty), &ty::ty_infer(ty::IntVar(_))) => { debug!("try_index_step: success, using built-in indexing"); fcx.write_adjustment(base_expr.id, base_expr.span, ty::AdjustDerefRef(adjustment)); return Some((tcx.types.uint, ty)); @@ -2466,7 +2520,7 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, Ok(trait_did) => trait_did, Err(ref err_string) => { fcx.tcx().sess.span_err(iterator_expr.span, - err_string.index(&FullRange)); + &err_string[]); return fcx.tcx().types.err } }; @@ -2490,10 +2544,10 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, if !ty::type_is_error(true_expr_type) { let ty_string = fcx.infcx().ty_to_string(true_expr_type); fcx.tcx().sess.span_err(iterator_expr.span, - format!("`for` loop expression has type `{}` which does \ + &format!("`for` loop expression has type `{}` which does \ not implement the `Iterator` trait; \ maybe try .iter()", - ty_string).index(&FullRange)); + ty_string)[]); } fcx.tcx().types.err } @@ -2528,10 +2582,10 @@ fn lookup_method_for_for_loop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, } _ => { fcx.tcx().sess.span_err(iterator_expr.span, - format!("`next` method of the `Iterator` \ + &format!("`next` method of the `Iterator` \ trait has an unexpected type `{}`", fcx.infcx().ty_to_string(return_type)) - .index(&FullRange)); + []); fcx.tcx().types.err } } @@ -2558,7 +2612,7 @@ fn check_method_argument_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, check_argument_types(fcx, sp, - err_inputs.index(&FullRange), + &err_inputs[], args_no_rcvr, autoref_args, false, @@ -3010,7 +3064,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, }; // Call the generic checker. - let args: Vec<_> = args.index(&(1..)).iter().map(|x| x).collect(); + let args: Vec<_> = args[1..].iter().map(|x| x).collect(); let ret_ty = check_method_argument_types(fcx, method_name.span, fn_ty, @@ -3171,8 +3225,24 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, if ty::type_is_integral(lhs_t) && ast_util::is_shift_binop(op) { // Shift is a special case: rhs must be uint, no matter what lhs is - check_expr_has_type(fcx, &**rhs, fcx.tcx().types.uint); - fcx.write_ty(expr.id, lhs_t); + check_expr(fcx, &**rhs); + let rhs_ty = fcx.expr_ty(&**rhs); + let rhs_ty = fcx.infcx().resolve_type_vars_if_possible(&rhs_ty); + if ty::type_is_integral(rhs_ty) { + fcx.write_ty(expr.id, lhs_t); + } else { + fcx.type_error_message( + expr.span, + |actual| { + format!( + "right-hand-side of a shift operation must have integral type, \ + not `{}`", + actual) + }, + rhs_ty, + None); + fcx.write_ty(expr.id, fcx.tcx().types.err); + } return; } @@ -3323,12 +3393,12 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, fcx.expr_ty(base)); // FIXME(eddyb) #12808 Integrate privacy into this auto-deref loop. let (_, autoderefs, field_ty) = - autoderef(fcx, expr.span, expr_t, Some(base.id), lvalue_pref, |base_t, _| { + autoderef(fcx, expr.span, expr_t, Some(base), lvalue_pref, |base_t, _| { match base_t.sty { ty::ty_struct(base_id, substs) => { debug!("struct named {}", ppaux::ty_to_string(tcx, base_t)); let fields = ty::lookup_struct_fields(tcx, base_id); - lookup_field_ty(tcx, base_id, fields.index(&FullRange), + lookup_field_ty(tcx, base_id, &fields[], field.node.name, &(*substs)) } _ => None @@ -3384,14 +3454,14 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let mut tuple_like = false; // FIXME(eddyb) #12808 Integrate privacy into this auto-deref loop. let (_, autoderefs, field_ty) = - autoderef(fcx, expr.span, expr_t, Some(base.id), lvalue_pref, |base_t, _| { + autoderef(fcx, expr.span, expr_t, Some(base), lvalue_pref, |base_t, _| { match base_t.sty { ty::ty_struct(base_id, substs) => { tuple_like = ty::is_tuple_struct(tcx, base_id); if tuple_like { debug!("tuple struct named {}", ppaux::ty_to_string(tcx, base_t)); let fields = ty::lookup_struct_fields(tcx, base_id); - lookup_tup_field_ty(tcx, base_id, fields.index(&FullRange), + lookup_tup_field_ty(tcx, base_id, &fields[], idx.node, &(*substs)) } else { None @@ -3490,17 +3560,18 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, expected_field_type = ty::lookup_field_type( tcx, class_id, field_id, substitutions); + expected_field_type = + fcx.normalize_associated_types_in( + field.span, &expected_field_type); class_field_map.insert( field.ident.node.name, (field_id, true)); fields_found += 1; } } + // Make sure to give a type to the field even if there's // an error, so we can continue typechecking - check_expr_coercable_to_type( - fcx, - &*field.expr, - expected_field_type); + check_expr_coercable_to_type(fcx, &*field.expr, expected_field_type); } if error_happened { @@ -3556,7 +3627,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, class_id, id, fcx.ccx.tcx.mk_substs(struct_substs), - class_fields.index(&FullRange), + &class_fields[], fields, base_expr.is_none(), None); @@ -3599,7 +3670,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, variant_id, id, fcx.ccx.tcx.mk_substs(substitutions), - variant_fields.index(&FullRange), + &variant_fields[], fields, true, Some(enum_id)); @@ -4066,7 +4137,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let expected = expected.only_has_type(); let flds = expected.map_to_option(fcx, |ty| { match ty.sty { - ty::ty_tup(ref flds) => Some(flds.index(&FullRange)), + ty::ty_tup(ref flds) => Some(&flds[]), _ => None } }); @@ -4100,7 +4171,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let struct_id = match def { Some(def::DefVariant(enum_id, variant_id, true)) => { check_struct_enum_variant(fcx, id, expr.span, enum_id, - variant_id, fields.index(&FullRange)); + variant_id, &fields[]); enum_id } Some(def::DefTrait(def_id)) => { @@ -4109,7 +4180,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, pprust::path_to_string(path)); check_struct_fields_on_error(fcx, id, - fields.index(&FullRange), + &fields[], base_expr); def_id }, @@ -4122,7 +4193,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, id, expr.span, struct_did, - fields.index(&FullRange), + &fields[], base_expr.as_ref().map(|e| &**e)); } _ => { @@ -4131,7 +4202,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, pprust::path_to_string(path)); check_struct_fields_on_error(fcx, id, - fields.index(&FullRange), + &fields[], base_expr); } } @@ -4149,10 +4220,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, // parameters correctly. let actual_structure_type = fcx.expr_ty(&*expr); if !ty::type_is_error(actual_structure_type) { - let type_and_substs = astconv::ast_path_to_ty_relaxed(fcx, - fcx, - struct_id, - path); + let type_and_substs = fcx.instantiate_struct_literal_ty(struct_id, path); match fcx.mk_subty(false, infer::Misc(path.span), actual_structure_type, @@ -4164,7 +4232,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, fcx.tcx() .sess .span_err(path.span, - format!("structure constructor specifies a \ + &format!("structure constructor specifies a \ structure of type `{}`, but this \ structure has type `{}`: {}", fcx.infcx() @@ -4172,7 +4240,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, fcx.infcx() .ty_to_string( actual_structure_type), - type_error_description).index(&FullRange)); + type_error_description)[]); ty::note_and_explain_type_err(tcx, &type_error); } } @@ -4735,7 +4803,7 @@ pub fn check_enum_variants(ccx: &CrateCtxt, ast::TyU16 => disr as u16 as Disr == disr, ast::TyU32 => disr as u32 as Disr == disr, ast::TyU64 => disr as u64 as Disr == disr, - ast::TyUs => uint_in_range(ccx, ccx.tcx.sess.target.uint_type, disr) + ast::TyUs(_) => uint_in_range(ccx, ccx.tcx.sess.target.uint_type, disr) } } fn int_in_range(ccx: &CrateCtxt, ty: ast::IntTy, disr: ty::Disr) -> bool { @@ -4744,7 +4812,7 @@ pub fn check_enum_variants(ccx: &CrateCtxt, ast::TyI16 => disr as i16 as Disr == disr, ast::TyI32 => disr as i32 as Disr == disr, ast::TyI64 => disr as i64 as Disr == disr, - ast::TyIs => int_in_range(ccx, ccx.tcx.sess.target.int_type, disr) + ast::TyIs(_) => int_in_range(ccx, ccx.tcx.sess.target.int_type, disr) } } match ty { @@ -4847,7 +4915,7 @@ pub fn check_enum_variants(ccx: &CrateCtxt, } let hint = *ty::lookup_repr_hints(ccx.tcx, ast::DefId { krate: ast::LOCAL_CRATE, node: id }) - .index(&FullRange).get(0).unwrap_or(&attr::ReprAny); + [].get(0).unwrap_or(&attr::ReprAny); if hint != attr::ReprAny && vs.len() <= 1 { if vs.len() == 1 { @@ -5518,7 +5586,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) { "get_tydesc" => { let tydesc_ty = match ty::get_tydesc_ty(ccx.tcx) { Ok(t) => t, - Err(s) => { tcx.sess.span_fatal(it.span, s.index(&FullRange)); } + Err(s) => { tcx.sess.span_fatal(it.span, &s[]); } }; let td_ptr = ty::mk_ptr(ccx.tcx, ty::mt { ty: tydesc_ty, @@ -5534,7 +5602,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) { ty::mk_struct(ccx.tcx, did, ccx.tcx.mk_substs(subst::Substs::empty()))), Err(msg) => { - tcx.sess.span_fatal(it.span, msg.index(&FullRange)); + tcx.sess.span_fatal(it.span, &msg[]); } } }, diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 11ad7bcb091..3b5027dbb9e 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -188,8 +188,8 @@ fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region { } } _ => { - tcx.sess.bug(format!("unexpected def in region_of_def: {:?}", - def).index(&FullRange)) + tcx.sess.bug(&format!("unexpected def in region_of_def: {:?}", + def)[]) } } } @@ -282,13 +282,13 @@ impl<'a, 'tcx> Rcx<'a, 'tcx> { Some(f) => f, None => { self.tcx().sess.bug( - format!("No fn-sig entry for id={}", id).index(&FullRange)); + &format!("No fn-sig entry for id={}", id)[]); } }; let len = self.region_bound_pairs.len(); - self.relate_free_regions(fn_sig.index(&FullRange), body.id); - link_fn_args(self, CodeExtent::from_node_id(body.id), fn_decl.inputs.index(&FullRange)); + self.relate_free_regions(&fn_sig[], body.id); + link_fn_args(self, CodeExtent::from_node_id(body.id), &fn_decl.inputs[]); self.visit_block(body); self.visit_region_obligations(body.id); self.region_bound_pairs.truncate(len); @@ -629,7 +629,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { } ast::ExprMatch(ref discr, ref arms, _) => { - link_match(rcx, &**discr, arms.index(&FullRange)); + link_match(rcx, &**discr, &arms[]); visit::walk_expr(rcx, expr); } @@ -936,29 +936,47 @@ fn constrain_call<'a, I: Iterator<Item=&'a ast::Expr>>(rcx: &mut Rcx, fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>, deref_expr: &ast::Expr, derefs: uint, - mut derefd_ty: Ty<'tcx>) { + mut derefd_ty: Ty<'tcx>) +{ + debug!("constrain_autoderefs(deref_expr={}, derefs={}, derefd_ty={})", + deref_expr.repr(rcx.tcx()), + derefs, + derefd_ty.repr(rcx.tcx())); + let r_deref_expr = ty::ReScope(CodeExtent::from_node_id(deref_expr.id)); for i in range(0u, derefs) { - debug!("constrain_autoderefs(deref_expr=?, derefd_ty={}, derefs={}/{}", - rcx.fcx.infcx().ty_to_string(derefd_ty), - i, derefs); - let method_call = MethodCall::autoderef(deref_expr.id, i); + debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs); + derefd_ty = match rcx.fcx.inh.method_map.borrow().get(&method_call) { Some(method) => { + debug!("constrain_autoderefs: #{} is overloaded, method={}", + i, method.repr(rcx.tcx())); + // Treat overloaded autoderefs as if an AutoRef adjustment // was applied on the base type, as that is always the case. let fn_sig = ty::ty_fn_sig(method.ty); - let self_ty = fn_sig.0.inputs[0]; + let fn_sig = // late-bound regions should have been instantiated + ty::assert_no_late_bound_regions(rcx.tcx(), fn_sig); + let self_ty = fn_sig.inputs[0]; let (m, r) = match self_ty.sty { ty::ty_rptr(r, ref m) => (m.mutbl, r), - _ => rcx.tcx().sess.span_bug(deref_expr.span, - format!("bad overloaded deref type {}", - method.ty.repr(rcx.tcx())).index(&FullRange)) + _ => { + rcx.tcx().sess.span_bug( + deref_expr.span, + &format!("bad overloaded deref type {}", + method.ty.repr(rcx.tcx()))[]) + } }; + + debug!("constrain_autoderefs: receiver r={:?} m={:?}", + r.repr(rcx.tcx()), m); + { let mc = mc::MemCategorizationContext::new(rcx.fcx); let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i)); + debug!("constrain_autoderefs: self_cmt={:?}", + self_cmt.repr(rcx.tcx())); link_region(rcx, deref_expr.span, *r, ty::BorrowKind::from_mutbl(m), self_cmt); } @@ -966,7 +984,7 @@ fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>, // Specialized version of constrain_call. type_must_outlive(rcx, infer::CallRcvr(deref_expr.span), self_ty, r_deref_expr); - match fn_sig.0.output { + match fn_sig.output { ty::FnConverging(return_type) => { type_must_outlive(rcx, infer::CallReturn(deref_expr.span), return_type, r_deref_expr); @@ -1049,13 +1067,16 @@ fn type_of_node_must_outlive<'a, 'tcx>( /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the /// resulting pointer is linked to the lifetime of its guarantor (if any). fn link_addr_of(rcx: &mut Rcx, expr: &ast::Expr, - mutability: ast::Mutability, base: &ast::Expr) { - debug!("link_addr_of(base=?)"); + mutability: ast::Mutability, base: &ast::Expr) { + debug!("link_addr_of(expr={}, base={})", expr.repr(rcx.tcx()), base.repr(rcx.tcx())); let cmt = { let mc = mc::MemCategorizationContext::new(rcx.fcx); ignore_err!(mc.cat_expr(base)) }; + + debug!("link_addr_of: cmt={}", cmt.repr(rcx.tcx())); + link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt); } @@ -1182,6 +1203,9 @@ fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, id: ast::NodeId, mutbl: ast::Mutability, cmt_borrowed: mc::cmt<'tcx>) { + debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={})", + id, mutbl, cmt_borrowed.repr(rcx.tcx())); + let rptr_ty = rcx.resolve_node_type(id); if !ty::type_is_error(rptr_ty) { let tcx = rcx.fcx.ccx.tcx; @@ -1318,9 +1342,9 @@ fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>, None => { rcx.tcx().sess.span_bug( span, - format!("Illegal upvar id: {}", + &format!("Illegal upvar id: {}", upvar_id.repr( - rcx.tcx())).index(&FullRange)); + rcx.tcx()))[]); } } } diff --git a/src/librustc_typeck/check/regionmanip.rs b/src/librustc_typeck/check/regionmanip.rs index 84d94b0392e..8730858f66e 100644 --- a/src/librustc_typeck/check/regionmanip.rs +++ b/src/librustc_typeck/check/regionmanip.rs @@ -146,8 +146,8 @@ impl<'a, 'tcx> Wf<'a, 'tcx> { ty::ty_open(_) => { self.tcx.sess.bug( - format!("Unexpected type encountered while doing wf check: {}", - ty.repr(self.tcx)).index(&FullRange)); + &format!("Unexpected type encountered while doing wf check: {}", + ty.repr(self.tcx))[]); } } } diff --git a/src/librustc_typeck/check/vtable.rs b/src/librustc_typeck/check/vtable.rs index e302609bf22..3940092eb72 100644 --- a/src/librustc_typeck/check/vtable.rs +++ b/src/librustc_typeck/check/vtable.rs @@ -72,17 +72,17 @@ pub fn check_object_cast<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, (_, &ty::ty_uniq(..)) => { fcx.ccx.tcx.sess.span_err( source_expr.span, - format!("can only cast an boxed pointer \ + &format!("can only cast an boxed pointer \ to a boxed object, not a {}", - ty::ty_sort_string(fcx.tcx(), source_ty)).index(&FullRange)); + ty::ty_sort_string(fcx.tcx(), source_ty))[]); } (_, &ty::ty_rptr(..)) => { fcx.ccx.tcx.sess.span_err( source_expr.span, - format!("can only cast a &-pointer \ + &format!("can only cast a &-pointer \ to an &-object, not a {}", - ty::ty_sort_string(fcx.tcx(), source_ty)).index(&FullRange)); + ty::ty_sort_string(fcx.tcx(), source_ty))[]); } _ => { diff --git a/src/librustc_typeck/check/wf.rs b/src/librustc_typeck/check/wf.rs index 898a5f9fe0c..89de1ea80fc 100644 --- a/src/librustc_typeck/check/wf.rs +++ b/src/librustc_typeck/check/wf.rs @@ -24,6 +24,7 @@ use syntax::ast; use syntax::ast_util::{local_def}; use syntax::attr; use syntax::codemap::Span; +use syntax::parse::token; use syntax::visit; use syntax::visit::Visitor; @@ -77,6 +78,14 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> { enum_variants(fcx, enum_def) }); } + ast::ItemTrait(..) => { + let trait_def = + ty::lookup_trait_def(ccx.tcx, local_def(item.id)); + reject_non_type_param_bounds( + ccx.tcx, + item.span, + &trait_def.generics); + } _ => {} } } @@ -226,9 +235,16 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> { // Find the supertrait bounds. This will add `int:Bar`. let poly_trait_ref = ty::Binder(trait_ref); let predicates = ty::predicates_for_trait_ref(fcx.tcx(), &poly_trait_ref); - for predicate in predicates.into_iter() { + let predicates = { + let selcx = &mut traits::SelectionContext::new(fcx.infcx(), fcx); + traits::normalize(selcx, cause.clone(), &predicates) + }; + for predicate in predicates.value.into_iter() { fcx.register_predicate(traits::Obligation::new(cause.clone(), predicate)); } + for obligation in predicates.obligations.into_iter() { + fcx.register_predicate(obligation); + } }); } } @@ -237,21 +253,32 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> { fn reject_non_type_param_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, generics: &ty::Generics<'tcx>) { + for predicate in generics.predicates.iter() { match predicate { &ty::Predicate::Trait(ty::Binder(ref tr)) => { - let self_ty = tr.self_ty(); - if !self_ty.walk().any(|t| is_ty_param(t)) { - tcx.sess.span_err( - span, - format!("cannot bound type `{}`, where clause \ - bounds may only be attached to types involving \ - type parameters", - self_ty.repr(tcx)).as_slice()) - } + let found_param = tr.input_types().iter() + .flat_map(|ty| ty.walk()) + .any(is_ty_param); + if !found_param { report_bound_error(tcx, span, tr.self_ty() )} + } + &ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(ty, _))) => { + let found_param = ty.walk().any(|t| is_ty_param(t)); + if !found_param { report_bound_error(tcx, span, ty) } } _ => {} - } + }; + } + + fn report_bound_error<'t>(tcx: &ty::ctxt<'t>, + span: Span, + bounded_ty: ty::Ty<'t>) { + tcx.sess.span_err( + span, + format!("cannot bound type `{}`, where clause \ + bounds may only be attached to types involving \ + type parameters", + bounded_ty.repr(tcx)).as_slice()) } fn is_ty_param(ty: ty::Ty) -> bool { @@ -262,11 +289,68 @@ fn reject_non_type_param_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, } } +fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>, + span: Span, + generics: &ty::Generics<'tcx>) { + let impl_params = generics.types.get_slice(subst::TypeSpace).iter() + .map(|tp| tp.name).collect::<HashSet<_>>(); + + for method_param in generics.types.get_slice(subst::FnSpace).iter() { + if impl_params.contains(&method_param.name) { + tcx.sess.span_err( + span, + &*format!("type parameter `{}` shadows another type parameter of the same name", + token::get_name(method_param.name))); + } + } +} + impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> { fn visit_item(&mut self, i: &ast::Item) { self.check_item_well_formed(i); visit::walk_item(self, i); } + + fn visit_fn(&mut self, + fk: visit::FnKind<'v>, fd: &'v ast::FnDecl, + b: &'v ast::Block, span: Span, id: ast::NodeId) { + match fk { + visit::FkFnBlock | visit::FkItemFn(..) => {} + visit::FkMethod(..) => { + match ty::impl_or_trait_item(self.ccx.tcx, local_def(id)) { + ty::ImplOrTraitItem::MethodTraitItem(ty_method) => { + reject_shadowing_type_parameters(self.ccx.tcx, span, &ty_method.generics) + } + _ => {} + } + } + } + visit::walk_fn(self, fk, fd, b, span) + } + + fn visit_trait_item(&mut self, t: &'v ast::TraitItem) { + match t { + &ast::TraitItem::ProvidedMethod(_) | + &ast::TraitItem::TypeTraitItem(_) => {}, + &ast::TraitItem::RequiredMethod(ref method) => { + match ty::impl_or_trait_item(self.ccx.tcx, local_def(method.id)) { + ty::ImplOrTraitItem::MethodTraitItem(ty_method) => { + reject_non_type_param_bounds( + self.ccx.tcx, + method.span, + &ty_method.generics); + reject_shadowing_type_parameters( + self.ccx.tcx, + method.span, + &ty_method.generics); + } + _ => {} + } + } + } + + visit::walk_trait_item(self, t) + } } pub struct BoundsChecker<'cx,'tcx:'cx> { @@ -455,7 +539,6 @@ fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, let arg_tys = ty::assert_no_late_bound_regions( fcx.tcx(), &ty::ty_fn_args(ctor_ty)); - AdtVariant { fields: args.iter().enumerate().map(|(index, arg)| { let arg_ty = arg_tys[index]; diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index a0f30788bbd..9d4aa23960d 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -68,9 +68,13 @@ fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>, Some(t.principal_def_id()) } + ty_uniq(_) => { + inference_context.tcx.lang_items.owned_box() + } + ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) | ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_tup(..) | - ty_param(..) | ty_err | ty_open(..) | ty_uniq(_) | + ty_param(..) | ty_err | ty_open(..) | ty_ptr(_) | ty_rptr(_, _) | ty_projection(..) => { None } @@ -80,8 +84,8 @@ fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>, // that the user can type inference_context.tcx.sess.span_bug( span, - format!("coherence encountered unexpected type searching for base type: {}", - ty.repr(inference_context.tcx)).index(&FullRange)); + &format!("coherence encountered unexpected type searching for base type: {}", + ty.repr(inference_context.tcx))[]); } } } @@ -487,18 +491,18 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { Err(ty::FieldDoesNotImplementCopy(name)) => { tcx.sess .span_err(span, - format!("the trait `Copy` may not be \ + &format!("the trait `Copy` may not be \ implemented for this type; field \ `{}` does not implement `Copy`", - token::get_name(name)).index(&FullRange)) + token::get_name(name))[]) } Err(ty::VariantDoesNotImplementCopy(name)) => { tcx.sess .span_err(span, - format!("the trait `Copy` may not be \ + &format!("the trait `Copy` may not be \ implemented for this type; variant \ `{}` does not implement `Copy`", - token::get_name(name)).index(&FullRange)) + token::get_name(name))[]) } Err(ty::TypeIsStructural) => { tcx.sess @@ -507,6 +511,11 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { for this type; type is not a structure or \ enumeration") } + Err(ty::TypeHasDestructor) => { + span_err!(tcx.sess, span, E0184, + "the trait `Copy` may not be implemented for this type; \ + the type has a destructor"); + } } } } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 79e98f15a2d..c56952abc44 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -212,7 +212,7 @@ fn get_enum_variant_types<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ast::TupleVariantKind(ref args) if args.len() > 0 => { let rs = ExplicitRscope; let input_tys: Vec<_> = args.iter().map(|va| ccx.to_ty(&rs, &*va.ty)).collect(); - ty::mk_ctor_fn(tcx, variant_def_id, input_tys.index(&FullRange), enum_ty) + ty::mk_ctor_fn(tcx, variant_def_id, &input_tys[], enum_ty) } ast::TupleVariantKind(_) => { @@ -259,7 +259,7 @@ fn collect_trait_methods<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ccx, trait_id, &trait_def.generics, - trait_items.index(&FullRange), + &trait_items[], &m.id, &m.ident.name, &m.explicit_self, @@ -273,7 +273,7 @@ fn collect_trait_methods<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ccx, trait_id, &trait_def.generics, - trait_items.index(&FullRange), + &trait_items[], &m.id, &m.pe_ident().name, m.pe_explicit_self(), @@ -607,6 +607,11 @@ fn convert(ccx: &CollectCtxt, it: &ast::Item) { methods.push(&**method); } ast::TypeImplItem(ref typedef) => { + if opt_trait_ref.is_none() { + tcx.sess.span_err(typedef.span, + "associated items are not allowed in inherent impls"); + } + let typ = ccx.to_ty(&ExplicitRscope, &*typedef.typ); tcx.tcache .borrow_mut() @@ -779,7 +784,7 @@ fn convert_struct<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, local_def(field.node.id)].ty).collect(); let ctor_fn_ty = ty::mk_ctor_fn(tcx, local_def(ctor_id), - inputs.index(&FullRange), + &inputs[], selfty); write_ty_to_tcx(tcx, ctor_id, ctor_fn_ty); tcx.tcache.borrow_mut().insert(local_def(ctor_id), @@ -819,8 +824,8 @@ fn get_trait_def<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, match ccx.tcx.map.get(trait_id.node) { ast_map::NodeItem(item) => trait_def_of_item(ccx, &*item), _ => { - ccx.tcx.sess.bug(format!("get_trait_def({}): not an item", - trait_id.node).index(&FullRange)) + ccx.tcx.sess.bug(&format!("get_trait_def({}): not an item", + trait_id.node)[]) } } } @@ -845,7 +850,7 @@ fn trait_def_of_item<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ref s => { tcx.sess.span_bug( it.span, - format!("trait_def_of_item invoked on {:?}", s).index(&FullRange)); + &format!("trait_def_of_item invoked on {:?}", s)[]); } }; @@ -1030,8 +1035,8 @@ fn ty_generics_for_type_or_impl<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, -> ty::Generics<'tcx> { ty_generics(ccx, subst::TypeSpace, - generics.lifetimes.index(&FullRange), - generics.ty_params.index(&FullRange), + &generics.lifetimes[], + &generics.ty_params[], ty::Generics::empty(), &generics.where_clause) } @@ -1049,8 +1054,8 @@ fn ty_generics_for_trait<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, let mut generics = ty_generics(ccx, subst::TypeSpace, - ast_generics.lifetimes.index(&FullRange), - ast_generics.ty_params.index(&FullRange), + &ast_generics.lifetimes[], + &ast_generics.ty_params[], ty::Generics::empty(), &ast_generics.where_clause); @@ -1135,8 +1140,8 @@ fn ty_generics_for_fn_or_method<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, let early_lifetimes = resolve_lifetime::early_bound_lifetimes(generics); ty_generics(ccx, subst::FnSpace, - early_lifetimes.index(&FullRange), - generics.ty_params.index(&FullRange), + &early_lifetimes[], + &generics.ty_params[], base_generics, &generics.where_clause) } @@ -1323,7 +1328,7 @@ fn get_or_create_type_parameter_def<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, let param_ty = ty::ParamTy::new(space, index, param.ident.name); let bounds = compute_bounds(ccx, param_ty.to_ty(ccx.tcx), - param.bounds.index(&FullRange), + ¶m.bounds[], SizedByDefault::Yes, param.span); let default = match param.default { @@ -1404,7 +1409,7 @@ fn check_bounds_compatible<'tcx>(tcx: &ty::ctxt<'tcx>, if !param_bounds.builtin_bounds.contains(&ty::BoundSized) { ty::each_bound_trait_and_supertraits( tcx, - param_bounds.trait_bounds.index(&FullRange), + ¶m_bounds.trait_bounds[], |trait_ref| { let trait_def = ty::lookup_trait_def(tcx, trait_ref.def_id()); if trait_def.bounds.builtin_bounds.contains(&ty::BoundSized) { diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index 9657bf82a8b..c9e15b93ad4 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -157,5 +157,6 @@ register_diagnostics! { E0180, E0181, E0182, - E0183 + E0183, + E0184 } diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index ae8731dfa47..f15d53290e7 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -64,16 +64,20 @@ This API is completely unstable and subject to change. */ #![crate_name = "rustc_typeck"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] +#![feature(box_syntax)] #![feature(rustc_diagnostic_macros)] +#![allow(unknown_features)] #![feature(int_uint)] #![allow(non_camel_case_types)] #[macro_use] extern crate log; @@ -190,10 +194,10 @@ fn require_same_types<'a, 'tcx, M>(tcx: &ty::ctxt<'tcx>, Ok(_) => true, Err(ref terr) => { tcx.sess.span_err(span, - format!("{}: {}", + &format!("{}: {}", msg(), ty::type_err_to_str(tcx, - terr)).index(&FullRange)); + terr))[]); ty::note_and_explain_type_err(tcx, terr); false } @@ -239,10 +243,10 @@ fn check_main_fn_ty(ccx: &CrateCtxt, } _ => { tcx.sess.span_bug(main_span, - format!("main has a non-function type: found \ + &format!("main has a non-function type: found \ `{}`", ppaux::ty_to_string(tcx, - main_t)).index(&FullRange)); + main_t))[]); } } } @@ -291,9 +295,9 @@ fn check_start_fn_ty(ccx: &CrateCtxt, } _ => { tcx.sess.span_bug(start_span, - format!("start has a non-function type: found \ + &format!("start has a non-function type: found \ `{}`", - ppaux::ty_to_string(tcx, start_t)).index(&FullRange)); + ppaux::ty_to_string(tcx, start_t))[]); } } } diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 393ba19ba18..b33921e07e8 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -562,9 +562,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { match self.terms_cx.inferred_map.get(¶m_id) { Some(&index) => index, None => { - self.tcx().sess.bug(format!( + self.tcx().sess.bug(&format!( "no inferred index entry for {}", - self.tcx().map.node_to_string(param_id)).index(&FullRange)); + self.tcx().map.node_to_string(param_id))[]); } } } @@ -837,9 +837,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { ty::ty_infer(..) | ty::ty_err => { self.tcx().sess.bug( - format!("unexpected type encountered in \ + &format!("unexpected type encountered in \ variance inference: {}", - ty.repr(self.tcx())).index(&FullRange)); + ty.repr(self.tcx()))[]); } } } @@ -917,9 +917,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { // regions when visiting member types or method types. self.tcx() .sess - .bug(format!("unexpected region encountered in variance \ + .bug(&format!("unexpected region encountered in variance \ inference: {}", - region.repr(self.tcx())).index(&FullRange)); + region.repr(self.tcx()))[]); } } } @@ -1055,7 +1055,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { // attribute and report an error with various results if found. if ty::has_attr(tcx, item_def_id, "rustc_variance") { let found = item_variances.repr(tcx); - tcx.sess.span_err(tcx.map.span(item_id), found.index(&FullRange)); + tcx.sess.span_err(tcx.map.span(item_id), &found[]); } let newly_added = tcx.item_variance_map.borrow_mut() diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index bf2664bba6a..a44c73e8c41 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -530,7 +530,8 @@ fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>, _ => { return PathParameters::AngleBracketed { lifetimes: lifetimes, - types: types.clean(cx) + types: types.clean(cx), + bindings: vec![] } } }; @@ -547,6 +548,7 @@ fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>, PathParameters::AngleBracketed { lifetimes: lifetimes, types: types.clean(cx), + bindings: vec![] // FIXME(#20646) } } } @@ -798,7 +800,7 @@ impl Clean<Item> for ast::Method { let all_inputs = &self.pe_fn_decl().inputs; let inputs = match self.pe_explicit_self().node { ast::SelfStatic => all_inputs.as_slice(), - _ => all_inputs.index(&(1..)) + _ => &all_inputs[1..] }; let decl = FnDecl { inputs: Arguments { @@ -836,7 +838,7 @@ impl Clean<Item> for ast::TypeMethod { fn clean(&self, cx: &DocContext) -> Item { let inputs = match self.explicit_self.node { ast::SelfStatic => self.decl.inputs.as_slice(), - _ => self.decl.inputs.index(&(1..)) + _ => &self.decl.inputs[1..] }; let decl = FnDecl { inputs: Arguments { @@ -1132,7 +1134,7 @@ impl<'tcx> Clean<Item> for ty::Method<'tcx> { self.fty.sig.clone()), s => { let sig = ty::Binder(ty::FnSig { - inputs: self.fty.sig.0.inputs.index(&(1..)).to_vec(), + inputs: self.fty.sig.0.inputs[1..].to_vec(), ..self.fty.sig.0.clone() }); let s = match s { @@ -1387,12 +1389,12 @@ impl<'tcx> Clean<Type> for ty::Ty<'tcx> { match self.sty { ty::ty_bool => Primitive(Bool), ty::ty_char => Primitive(Char), - ty::ty_int(ast::TyIs) => Primitive(Isize), + ty::ty_int(ast::TyIs(_)) => Primitive(Isize), ty::ty_int(ast::TyI8) => Primitive(I8), ty::ty_int(ast::TyI16) => Primitive(I16), ty::ty_int(ast::TyI32) => Primitive(I32), ty::ty_int(ast::TyI64) => Primitive(I64), - ty::ty_uint(ast::TyUs) => Primitive(Usize), + ty::ty_uint(ast::TyUs(_)) => Primitive(Usize), ty::ty_uint(ast::TyU8) => Primitive(U8), ty::ty_uint(ast::TyU16) => Primitive(U16), ty::ty_uint(ast::TyU32) => Primitive(U32), @@ -1766,6 +1768,7 @@ pub enum PathParameters { AngleBracketed { lifetimes: Vec<Lifetime>, types: Vec<Type>, + bindings: Vec<TypeBinding> }, Parenthesized { inputs: Vec<Type>, @@ -1779,7 +1782,8 @@ impl Clean<PathParameters> for ast::PathParameters { ast::AngleBracketedParameters(ref data) => { PathParameters::AngleBracketed { lifetimes: data.lifetimes.clean(cx), - types: data.types.clean(cx) + types: data.types.clean(cx), + bindings: data.bindings.clean(cx) } } @@ -2265,12 +2269,12 @@ fn resolve_type(cx: &DocContext, ast::TyStr => return Primitive(Str), ast::TyBool => return Primitive(Bool), ast::TyChar => return Primitive(Char), - ast::TyInt(ast::TyIs) => return Primitive(Isize), + ast::TyInt(ast::TyIs(_)) => return Primitive(Isize), ast::TyInt(ast::TyI8) => return Primitive(I8), ast::TyInt(ast::TyI16) => return Primitive(I16), ast::TyInt(ast::TyI32) => return Primitive(I32), ast::TyInt(ast::TyI64) => return Primitive(I64), - ast::TyUint(ast::TyUs) => return Primitive(Usize), + ast::TyUint(ast::TyUs(_)) => return Primitive(Usize), ast::TyUint(ast::TyU8) => return Primitive(U8), ast::TyUint(ast::TyU16) => return Primitive(U16), ast::TyUint(ast::TyU32) => return Primitive(U32), @@ -2442,8 +2446,25 @@ fn lang_struct(cx: &DocContext, did: Option<ast::DefId>, params: PathParameters::AngleBracketed { lifetimes: vec![], types: vec![t.clean(cx)], + bindings: vec![] } }], }, } } + +/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>` +#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Show)] +pub struct TypeBinding { + pub name: String, + pub ty: Type +} + +impl Clean<TypeBinding> for ast::TypeBinding { + fn clean(&self, cx: &DocContext) -> TypeBinding { + TypeBinding { + name: self.ident.clean(cx), + ty: self.ty.clean(cx) + } + } +} diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 46c212a9f2d..4885bd373eb 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -11,6 +11,7 @@ pub use self::MaybeTyped::*; use rustc_driver::driver; use rustc::session::{self, config}; +use rustc::session::config::UnstableFeatures; use rustc::session::search_paths::SearchPaths; use rustc::middle::{privacy, ty}; use rustc::lint; @@ -95,10 +96,11 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec<String>, externs: Externs, externs: externs, target_triple: triple.unwrap_or(config::host_triple().to_string()), cfg: config::parse_cfgspecs(cfgs), + // Ensure that rustdoc works even if rustc is feature-staged + unstable_features: UnstableFeatures::Default, ..config::basic_options().clone() }; - let codemap = codemap::CodeMap::new(); let diagnostic_handler = diagnostic::default_handler(diagnostic::Auto, None); let span_diagnostic_handler = diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index 99cd467cdfc..6fb78d9a833 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -19,14 +19,6 @@ use std::fmt; /// string when passed to a format string. pub struct Escape<'a>(pub &'a str); -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Escape<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Escape<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Because the internet is always right, turns out there's not that many diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index b24e7a7a4cf..2ae22b8fc0d 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -51,6 +51,8 @@ pub struct ConciseStability<'a>(pub &'a Option<clean::Stability>); pub struct WhereClause<'a>(pub &'a clean::Generics); /// Wrapper struct for emitting type parameter bounds. pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]); +/// Wrapper struct for emitting a comma-separated list of items +pub struct CommaSep<'a, T: 'a>(pub &'a [T]); impl VisSpace { pub fn get(&self) -> Option<ast::Visibility> { @@ -64,11 +66,13 @@ impl UnsafetySpace { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for TyParamBounds<'a> { +impl<'a, T: fmt::String> fmt::String for CommaSep<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + for (i, item) in self.0.iter().enumerate() { + if i != 0 { try!(write!(f, ", ")); } + try!(write!(f, "{}", item)); + } + Ok(()) } } @@ -85,14 +89,6 @@ impl<'a> fmt::String for TyParamBounds<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::Generic { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::Generics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) } @@ -130,14 +126,6 @@ impl fmt::String for clean::Generics { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for WhereClause<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for WhereClause<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &WhereClause(gens) = self; @@ -175,14 +163,6 @@ impl<'a> fmt::String for WhereClause<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::Lifetime { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::Lifetime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.get_ref())); @@ -190,14 +170,6 @@ impl fmt::String for clean::Lifetime { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::PolyTrait { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::PolyTrait { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() > 0 { @@ -214,14 +186,6 @@ impl fmt::String for clean::PolyTrait { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::TyParamBound { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::TyParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -239,19 +203,13 @@ impl fmt::String for clean::TyParamBound { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::PathParameters { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::PathParameters { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - clean::PathParameters::AngleBracketed { ref lifetimes, ref types } => { - if lifetimes.len() > 0 || types.len() > 0 { + clean::PathParameters::AngleBracketed { + ref lifetimes, ref types, ref bindings + } => { + if lifetimes.len() > 0 || types.len() > 0 || bindings.len() > 0 { try!(f.write_str("<")); let mut comma = false; for lifetime in lifetimes.iter() { @@ -268,6 +226,13 @@ impl fmt::String for clean::PathParameters { comma = true; try!(write!(f, "{}", *ty)); } + for binding in bindings.iter() { + if comma { + try!(f.write_str(", ")); + } + comma = true; + try!(write!(f, "{}", *binding)); + } try!(f.write_str(">")); } } @@ -292,14 +257,6 @@ impl fmt::String for clean::PathParameters { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::PathSegment { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::PathSegment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.name.as_slice())); @@ -307,14 +264,6 @@ impl fmt::String for clean::PathSegment { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::Path { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.global { @@ -383,7 +332,7 @@ fn path<F, G>(w: &mut fmt::Formatter, match rel_root { Some(root) => { let mut root = String::from_str(root.as_slice()); - for seg in path.segments.index(&(0..amt)).iter() { + for seg in path.segments[0..amt].iter() { if "super" == seg.name || "self" == seg.name { try!(write!(w, "{}::", seg.name)); @@ -398,7 +347,7 @@ fn path<F, G>(w: &mut fmt::Formatter, } } None => { - for seg in path.segments.index(&(0..amt)).iter() { + for seg in path.segments[0..amt].iter() { try!(write!(w, "{}::", seg.name)); } } @@ -501,14 +450,6 @@ fn tybounds(w: &mut fmt::Formatter, } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::Type { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -530,7 +471,8 @@ impl fmt::String for clean::Type { lifetimes = if decl.lifetimes.len() == 0 { "".to_string() } else { - format!("for <{:#}>", decl.lifetimes) + format!("for <{}>", + CommaSep(decl.lifetimes.as_slice())) }, args = decl.decl.inputs, arrow = decl.decl.output, @@ -562,7 +504,8 @@ impl fmt::String for clean::Type { lifetimes = if decl.lifetimes.len() == 0 { "".to_string() } else { - format!("for <{:#}>", decl.lifetimes) + format!("for <{}>", + CommaSep(decl.lifetimes.as_slice())) }, args = decl.decl.inputs, bounds = if decl.bounds.len() == 0 { @@ -592,7 +535,8 @@ impl fmt::String for clean::Type { primitive_link(f, clean::PrimitiveTuple, match typs.as_slice() { [ref one] => format!("({},)", one), - many => format!("({:#})", many) + many => format!("({})", + CommaSep(many.as_slice())) }.as_slice()) } clean::Vector(ref t) => { @@ -650,15 +594,6 @@ impl fmt::String for clean::Type { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::Arguments { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - - impl fmt::String for clean::Arguments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, input) in self.values.iter().enumerate() { @@ -672,14 +607,6 @@ impl fmt::String for clean::Arguments { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::FunctionRetTy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::FunctionRetTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -690,28 +617,12 @@ impl fmt::String for clean::FunctionRetTy { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::FnDecl { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::FnDecl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output) } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Method<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Method<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Method(selfty, d) = *self; @@ -742,14 +653,6 @@ impl<'a> fmt::String for Method<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for VisSpace { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for VisSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { @@ -759,14 +662,6 @@ impl fmt::String for VisSpace { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for UnsafetySpace { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for UnsafetySpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { @@ -776,14 +671,6 @@ impl fmt::String for UnsafetySpace { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::ViewPath { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::ViewPath { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -811,14 +698,6 @@ impl fmt::String for clean::ViewPath { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::ImportSource { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::ImportSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.did { @@ -836,14 +715,6 @@ impl fmt::String for clean::ImportSource { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for clean::ViewListIdent { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for clean::ViewListIdent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.source { @@ -855,6 +726,7 @@ impl fmt::String for clean::ViewListIdent { params: clean::PathParameters::AngleBracketed { lifetimes: Vec::new(), types: Vec::new(), + bindings: Vec::new() } }) }; @@ -865,11 +737,9 @@ impl fmt::String for clean::ViewListIdent { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for MutableSpace { +impl fmt::String for clean::TypeBinding { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) + write!(f, "{}={}", self.name, self.ty) } } @@ -882,14 +752,6 @@ impl fmt::String for MutableSpace { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for RawMutableSpace { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for RawMutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -899,14 +761,6 @@ impl fmt::String for RawMutableSpace { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Stability<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Stability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Stability(stab) = *self; @@ -921,14 +775,6 @@ impl<'a> fmt::String for Stability<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for ConciseStability<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for ConciseStability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ConciseStability(stab) = *self; @@ -946,14 +792,6 @@ impl<'a> fmt::String for ConciseStability<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for ModuleSummary { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for ModuleSummary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt_inner<'a>(f: &mut fmt::Formatter, diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 3d2c5e2cbb5..885017152de 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -34,7 +34,7 @@ pub fn highlight(src: &str, class: Option<&str>, id: Option<&str>) -> String { class, id, &mut out).unwrap(); - String::from_utf8_lossy(out.index(&FullRange)).into_owned() + String::from_utf8_lossy(&out[]).into_owned() } /// Exhausts the `lexer` writing the output into `out`. diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index 13a06f842a2..db3319eb765 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -103,14 +103,6 @@ impl ItemType { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl fmt::Show for ItemType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index f4660a81be4..a063191a12f 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -435,14 +435,6 @@ pub fn reset_headers() { TEST_IDX.with(|s| s.set(0)); } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Markdown<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Markdown<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Markdown(md) = *self; @@ -452,14 +444,6 @@ impl<'a> fmt::String for Markdown<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for MarkdownWithToc<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for MarkdownWithToc<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let MarkdownWithToc(md) = *self; diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 08abdc2af18..839dfa339b3 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1351,14 +1351,6 @@ impl<'a> Item<'a> { } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Item<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Item<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Write the breadcrumb trail header for the top @@ -1634,14 +1626,6 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, struct Initializer<'a>(&'a str); -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Initializer<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s) = *self; @@ -2204,14 +2188,6 @@ fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item, document(w, it) } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Sidebar<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Sidebar<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let cx = self.cx; @@ -2267,14 +2243,6 @@ impl<'a> fmt::String for Sidebar<'a> { } } -//NOTE(stage0): remove impl after snapshot -#[cfg(stage0)] -impl<'a> fmt::Show for Source<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a> fmt::String for Source<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Source(s) = *self; diff --git a/src/librustdoc/html/static/main.css b/src/librustdoc/html/static/main.css index a5a48254141..5951ac2bae7 100644 --- a/src/librustdoc/html/static/main.css +++ b/src/librustdoc/html/static/main.css @@ -157,7 +157,6 @@ nav.sub { left: 0; top: 0; min-height: 100%; - z-index: -1; } .content, nav { max-width: 960px; } @@ -221,6 +220,7 @@ nav.sub { .content pre.line-numbers { float: left; border: none; + position: relative; -webkit-user-select: none; -moz-user-select: none; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index ee65ef06623..6d5df3d777d 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -9,7 +9,8 @@ // except according to those terms. #![crate_name = "rustdoc"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -17,6 +18,8 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![feature(slicing_syntax)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate arena; extern crate getopts; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index bbe35eb0e9c..8e0f4b2d443 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -22,6 +22,7 @@ use std::collections::{HashSet, HashMap}; use testing; use rustc::session::{self, config}; use rustc::session::search_paths::{SearchPaths, PathKind}; +use rustc_driver::get_unstable_features_setting; use rustc_driver::driver; use syntax::ast; use syntax::codemap::{CodeMap, dummy_spanned}; @@ -52,6 +53,7 @@ pub fn run(input: &str, search_paths: libs.clone(), crate_types: vec!(config::CrateTypeDylib), externs: externs.clone(), + unstable_features: get_unstable_features_setting(), ..config::basic_options().clone() }; @@ -128,6 +130,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, .. config::basic_codegen_options() }, test: as_test_harness, + unstable_features: get_unstable_features_setting(), ..config::basic_options().clone() }; diff --git a/src/libserialize/collection_impls.rs b/src/libserialize/collection_impls.rs index d89a4754d2e..10698259739 100644 --- a/src/libserialize/collection_impls.rs +++ b/src/libserialize/collection_impls.rs @@ -13,6 +13,7 @@ use std::uint; use std::default::Default; use std::hash::{Hash, Hasher}; +use std::collections::hash_state::HashState; use {Decodable, Encodable, Decoder, Encoder}; use std::collections::{DList, RingBuf, BTreeMap, BTreeSet, HashMap, HashSet, VecMap}; @@ -156,14 +157,13 @@ impl< } } -#[old_impl_check] -impl< - K: Encodable + Hash<X> + Eq, - V: Encodable, - X, - H: Hasher<X> -> Encodable for HashMap<K, V, H> { - fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { +impl<K, V, S> Encodable for HashMap<K, V, S> + where K: Encodable + Hash< <S as HashState>::Hasher> + Eq, + V: Encodable, + S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64> +{ + fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { e.emit_map(self.len(), |e| { let mut i = 0; for (key, val) in self.iter() { @@ -176,17 +176,16 @@ impl< } } -#[old_impl_check] -impl< - K: Decodable + Hash<S> + Eq, - V: Decodable, - S, - H: Hasher<S> + Default -> Decodable for HashMap<K, V, H> { - fn decode<D: Decoder>(d: &mut D) -> Result<HashMap<K, V, H>, D::Error> { +impl<K, V, S> Decodable for HashMap<K, V, S> + where K: Decodable + Hash< <S as HashState>::Hasher> + Eq, + V: Decodable, + S: HashState + Default, + <S as HashState>::Hasher: Hasher<Output=u64> +{ + fn decode<D: Decoder>(d: &mut D) -> Result<HashMap<K, V, S>, D::Error> { d.read_map(|d, len| { - let hasher = Default::default(); - let mut map = HashMap::with_capacity_and_hasher(len, hasher); + let state = Default::default(); + let mut map = HashMap::with_capacity_and_hash_state(len, state); for i in range(0u, len) { let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); @@ -197,13 +196,12 @@ impl< } } -#[old_impl_check] -impl< - T: Encodable + Hash<X> + Eq, - X, - H: Hasher<X> -> Encodable for HashSet<T, H> { - fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { +impl<T, S> Encodable for HashSet<T, S> + where T: Encodable + Hash< <S as HashState>::Hasher> + Eq, + S: HashState, + <S as HashState>::Hasher: Hasher<Output=u64> +{ + fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> { s.emit_seq(self.len(), |s| { let mut i = 0; for e in self.iter() { @@ -215,15 +213,15 @@ impl< } } -#[old_impl_check] -impl< - T: Decodable + Hash<S> + Eq, - S, - H: Hasher<S> + Default -> Decodable for HashSet<T, H> { - fn decode<D: Decoder>(d: &mut D) -> Result<HashSet<T, H>, D::Error> { +impl<T, S> Decodable for HashSet<T, S> + where T: Decodable + Hash< <S as HashState>::Hasher> + Eq, + S: HashState + Default, + <S as HashState>::Hasher: Hasher<Output=u64> +{ + fn decode<D: Decoder>(d: &mut D) -> Result<HashSet<T, S>, D::Error> { d.read_seq(|d, len| { - let mut set = HashSet::with_capacity_and_hasher(len, Default::default()); + let state = Default::default(); + let mut set = HashSet::with_capacity_and_hash_state(len, state); for i in range(0u, len) { set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index b7bf40a6ec5..62acef2ca1c 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -383,7 +383,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { }; if start < i { - try!(wr.write_str(v.index(&(start..i)))); + try!(wr.write_str(&v[start..i])); } try!(wr.write_str(escaped)); @@ -392,7 +392,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { } if start != v.len() { - try!(wr.write_str(v.index(&(start..)))); + try!(wr.write_str(&v[start..])); } wr.write_str("\"") @@ -401,7 +401,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result { let mut buf = [0; 4]; let n = v.encode_utf8(&mut buf).unwrap(); - let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) }; + let buf = unsafe { str::from_utf8_unchecked(&buf[0..n]) }; escape_str(writer, buf) } @@ -414,7 +414,7 @@ fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result { } if n > 0 { - wr.write_str(BUF.index(&(0..n))) + wr.write_str(&BUF[0..n]) } else { Ok(()) } @@ -623,7 +623,7 @@ impl<'a> ::Encoder for Encoder<'a> { let mut check_encoder = Encoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf.index(&FullRange)).unwrap(); + let out = str::from_utf8(&buf[]).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -894,7 +894,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> { let mut check_encoder = PrettyEncoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf.index(&FullRange)).unwrap(); + let out = str::from_utf8(&buf[]).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -1027,7 +1027,7 @@ impl Json { /// Returns None otherwise. pub fn as_string<'a>(&'a self) -> Option<&'a str> { match *self { - Json::String(ref s) => Some(s.index(&FullRange)), + Json::String(ref s) => Some(&s[]), _ => None } } @@ -1137,7 +1137,7 @@ impl Index<uint> for Json { fn index<'a>(&'a self, idx: &uint) -> &'a Json { match self { - &Json::Array(ref v) => v.index(idx), + &Json::Array(ref v) => &v[*idx], _ => panic!("can only index Json with uint if it is an array") } } @@ -1222,7 +1222,7 @@ impl Stack { InternalIndex(i) => StackElement::Index(i), InternalKey(start, size) => { StackElement::Key(str::from_utf8( - self.str_buffer.index(&((start as uint) .. (start as uint + size as uint)))) + &self.str_buffer[(start as uint) .. (start as uint + size as uint)]) .unwrap()) } } @@ -1265,7 +1265,7 @@ impl Stack { Some(&InternalIndex(i)) => Some(StackElement::Index(i)), Some(&InternalKey(start, size)) => { Some(StackElement::Key(str::from_utf8( - self.str_buffer.index(&((start as uint) .. (start+size) as uint)) + &self.str_buffer[(start as uint) .. (start+size) as uint] ).unwrap())) } } @@ -1396,7 +1396,7 @@ impl<T: Iterator<Item=char>> Parser<T> { self.ch == Some(c) } - fn error<T>(&self, reason: ErrorCode) -> Result<T, ParserError> { + fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> { Err(SyntaxError(reason, self.line, self.col)) } @@ -2144,7 +2144,7 @@ impl ::Decoder for Decoder { return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) } }; - let idx = match names.iter().position(|n| *n == name.index(&FullRange)) { + let idx = match names.iter().position(|n| *n == &name[]) { Some(idx) => idx, None => return Err(UnknownVariantError(name)) }; @@ -2458,14 +2458,6 @@ impl<'a> fmt::String for PrettyJson<'a> { } } -#[cfg(stage0)] -//NOTE(stage0): remove impl after snapshot -impl<'a, T: Encodable> fmt::Show for AsJson<'a, T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl<'a, T: Encodable> fmt::String for AsJson<'a, T> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -2519,7 +2511,6 @@ mod tests { use std::{i64, u64, f32, f64, io}; use std::collections::BTreeMap; use std::num::Float; - use std::ops::Index; use std::string; #[derive(RustcDecodable, Eq, PartialEq, Show)] @@ -3361,7 +3352,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap(); + let json_str = from_utf8(&mem_buf[]).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {:?}", json_str), _ => {} // it parsed and we are good to go @@ -3377,7 +3368,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap(); + let json_str = from_utf8(&mem_buf[]).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {:?}", json_str), _ => {} // it parsed and we are good to go @@ -3417,7 +3408,7 @@ mod tests { write!(&mut writer, "{}", super::as_pretty_json(&json).indent(i)).unwrap(); - let printed = from_utf8(writer.index(&FullRange)).unwrap(); + let printed = from_utf8(&writer[]).unwrap(); // Check for indents at each line let lines: Vec<&str> = printed.lines().collect(); @@ -3481,7 +3472,7 @@ mod tests { } } #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064) fn test_streaming_parser() { assert_stream_equal( r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#, @@ -3520,7 +3511,7 @@ mod tests { } #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064) fn test_read_object_streaming() { assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3))); assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2))); @@ -3604,7 +3595,7 @@ mod tests { ); } #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) + #[cfg_attr(target_pointer_width = "32", ignore)] // FIXME(#14064) fn test_read_array_streaming() { assert_stream_equal( "[]", diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs index 139170fc012..942a8cfa2c5 100644 --- a/src/libserialize/lib.rs +++ b/src/libserialize/lib.rs @@ -16,6 +16,7 @@ Core encoding and decoding interfaces. #![crate_name = "serialize"] #![unstable = "deprecated in favor of rustc-serialize on crates.io"] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -23,9 +24,11 @@ Core encoding and decoding interfaces. html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(slicing_syntax)] -#![feature(old_impl_check)] #![cfg_attr(stage0, allow(unused_attributes))] +#![feature(box_syntax)] +#![feature(old_impl_check)] +#![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] // test harness access #[cfg(test)] extern crate test; diff --git a/src/libserialize/serialize.rs b/src/libserialize/serialize.rs index 7b6ca10669d..fe2d57486a8 100644 --- a/src/libserialize/serialize.rs +++ b/src/libserialize/serialize.rs @@ -326,7 +326,7 @@ impl Encodable for str { impl Encodable for String { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.index(&FullRange)) + s.emit_str(&self[]) } } diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 671408acebf..77c2315194b 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -22,7 +22,7 @@ use string::String; use vec::Vec; /// Extension methods for ASCII-subset only operations on owned strings -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] pub trait OwnedAsciiExt { /// Convert the string to ASCII upper case: /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', @@ -36,7 +36,7 @@ pub trait OwnedAsciiExt { } /// Extension methods for ASCII-subset only operations on string slices -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] pub trait AsciiExt<T = Self> { /// Check if within the ASCII range. fn is_ascii(&self) -> bool; @@ -57,7 +57,7 @@ pub trait AsciiExt<T = Self> { fn eq_ignore_ascii_case(&self, other: &Self) -> bool; } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl AsciiExt<String> for str { #[inline] fn is_ascii(&self) -> bool { @@ -82,7 +82,7 @@ impl AsciiExt<String> for str { } } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl OwnedAsciiExt for String { #[inline] fn into_ascii_uppercase(self) -> String { @@ -97,7 +97,7 @@ impl OwnedAsciiExt for String { } } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl AsciiExt<Vec<u8>> for [u8] { #[inline] fn is_ascii(&self) -> bool { @@ -123,7 +123,7 @@ impl AsciiExt<Vec<u8>> for [u8] { } } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl OwnedAsciiExt for Vec<u8> { #[inline] fn into_ascii_uppercase(mut self) -> Vec<u8> { @@ -142,7 +142,7 @@ impl OwnedAsciiExt for Vec<u8> { } } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl AsciiExt for u8 { #[inline] fn is_ascii(&self) -> bool { @@ -165,7 +165,7 @@ impl AsciiExt for u8 { } } -#[experimental = "would prefer to do this in a more general way"] +#[unstable = "would prefer to do this in a more general way"] impl AsciiExt for char { #[inline] fn is_ascii(&self) -> bool { diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index 5764962b51b..3a059766fef 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![experimental] +#![unstable] //! A typesafe bitmask flag generator. @@ -273,7 +273,7 @@ macro_rules! bitflags { #[cfg(test)] #[allow(non_upper_case_globals)] mod tests { - use hash; + use hash::{self, SipHasher}; use option::Option::{Some, None}; bitflags! { @@ -467,9 +467,9 @@ mod tests { fn test_hash() { let mut x = Flags::empty(); let mut y = Flags::empty(); - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<Flags, SipHasher>(&x) == hash::hash::<Flags, SipHasher>(&y)); x = Flags::all(); y = FlagABC; - assert!(hash::hash(&x) == hash::hash(&y)); + assert!(hash::hash::<Flags, SipHasher>(&x) == hash::hash::<Flags, SipHasher>(&y)); } } diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index c3381d5cd64..c3bdfbb12d8 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -19,16 +19,15 @@ use clone::Clone; use cmp::{max, Eq, PartialEq}; use default::Default; use fmt::{self, Show}; -use hash::{Hash, Hasher, RandomSipHasher}; +use hash::{self, Hash, SipHasher}; use iter::{self, Iterator, IteratorExt, FromIterator, Extend, Map}; use marker::Sized; use mem::{self, replace}; use num::{Int, UnsignedInt}; use ops::{Deref, FnMut, Index, IndexMut}; -use option::Option; -use option::Option::{Some, None}; -use result::Result; -use result::Result::{Ok, Err}; +use option::Option::{self, Some, None}; +use rand::{self, Rng}; +use result::Result::{self, Ok, Err}; use super::table::{ self, @@ -44,6 +43,7 @@ use super::table::BucketState::{ Empty, Full, }; +use super::state::HashState; const INITIAL_LOG2_CAP: uint = 5; pub const INITIAL_CAPACITY: uint = 1 << INITIAL_LOG2_CAP; // 2^5 @@ -297,9 +297,9 @@ fn test_resize_policy() { /// ``` #[derive(Clone)] #[stable] -pub struct HashMap<K, V, H = RandomSipHasher> { +pub struct HashMap<K, V, S = RandomState> { // All hashes are keyed on these values, to prevent hash collision attacks. - hasher: H, + hash_state: S, table: RawTable<K, V>, @@ -439,17 +439,20 @@ impl<K, V, M> SearchResult<K, V, M> { } } -#[old_impl_check] -impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { - fn make_hash<X: ?Sized + Hash<S>>(&self, x: &X) -> SafeHash { - table::make_hash(&self.hasher, x) +impl<K, V, S, H> HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash where X: Hash<H> { + table::make_hash(&self.hash_state, x) } /// Search for a key, yielding the index if it's found in the hashtable. /// If you already have the hash for the key lying around, use /// search_hashed. fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> Option<FullBucketImm<'a, K, V>> - where Q: BorrowFrom<K> + Eq + Hash<S> + where Q: BorrowFrom<K> + Eq + Hash<H> { let hash = self.make_hash(q); search_hashed(&self.table, hash, |k| q.eq(BorrowFrom::borrow_from(k))) @@ -457,7 +460,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { } fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> Option<FullBucketMut<'a, K, V>> - where Q: BorrowFrom<K> + Eq + Hash<S> + where Q: BorrowFrom<K> + Eq + Hash<H> { let hash = self.make_hash(q); search_hashed(&mut self.table, hash, |k| q.eq(BorrowFrom::borrow_from(k))) @@ -486,7 +489,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { } } -impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> { +impl<K: Hash<Hasher> + Eq, V> HashMap<K, V, RandomState> { /// Create an empty HashMap. /// /// # Example @@ -497,9 +500,8 @@ impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> { /// ``` #[inline] #[stable] - pub fn new() -> HashMap<K, V, RandomSipHasher> { - let hasher = RandomSipHasher::new(); - HashMap::with_hasher(hasher) + pub fn new() -> HashMap<K, V, RandomState> { + Default::default() } /// Creates an empty hash map with the given initial capacity. @@ -512,14 +514,16 @@ impl<K: Hash + Eq, V> HashMap<K, V, RandomSipHasher> { /// ``` #[inline] #[stable] - pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomSipHasher> { - let hasher = RandomSipHasher::new(); - HashMap::with_capacity_and_hasher(capacity, hasher) + pub fn with_capacity(capacity: uint) -> HashMap<K, V, RandomState> { + HashMap::with_capacity_and_hash_state(capacity, Default::default()) } } -#[old_impl_check] -impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { +impl<K, V, S, H> HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ /// Creates an empty hashmap which will use the given hasher to hash keys. /// /// The creates map has the default initial capacity. @@ -528,17 +532,17 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// /// ``` /// use std::collections::HashMap; - /// use std::hash::sip::SipHasher; + /// use std::collections::hash_map::RandomState; /// - /// let h = SipHasher::new(); - /// let mut map = HashMap::with_hasher(h); + /// let s = RandomState::new(); + /// let mut map = HashMap::with_hash_state(s); /// map.insert(1i, 2u); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] - pub fn with_hasher(hasher: H) -> HashMap<K, V, H> { + pub fn with_hash_state(hash_state: S) -> HashMap<K, V, S> { HashMap { - hasher: hasher, + hash_state: hash_state, resize_policy: DefaultResizePolicy::new(), table: RawTable::new(0), } @@ -556,21 +560,22 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// /// ``` /// use std::collections::HashMap; - /// use std::hash::sip::SipHasher; + /// use std::collections::hash_map::RandomState; /// - /// let h = SipHasher::new(); - /// let mut map = HashMap::with_capacity_and_hasher(10, h); + /// let s = RandomState::new(); + /// let mut map = HashMap::with_capacity_and_hash_state(10, s); /// map.insert(1i, 2u); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] - pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashMap<K, V, H> { + pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S) + -> HashMap<K, V, S> { let resize_policy = DefaultResizePolicy::new(); let min_cap = max(INITIAL_CAPACITY, resize_policy.min_capacity(capacity)); let internal_cap = min_cap.checked_next_power_of_two().expect("capacity overflow"); assert!(internal_cap >= capacity, "capacity overflow"); HashMap { - hasher: hasher, + hash_state: hash_state, resize_policy: resize_policy, table: RawTable::new(internal_cap), } @@ -1031,7 +1036,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// ``` #[stable] pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> - where Q: Hash<S> + Eq + BorrowFrom<K> + where Q: Hash<H> + Eq + BorrowFrom<K> { self.search(k).map(|bucket| bucket.into_refs().1) } @@ -1054,7 +1059,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// ``` #[stable] pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool - where Q: Hash<S> + Eq + BorrowFrom<K> + where Q: Hash<H> + Eq + BorrowFrom<K> { self.search(k).is_some() } @@ -1080,7 +1085,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// ``` #[stable] pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> - where Q: Hash<S> + Eq + BorrowFrom<K> + where Q: Hash<H> + Eq + BorrowFrom<K> { self.search_mut(k).map(|bucket| bucket.into_mut_refs().1) } @@ -1132,7 +1137,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// ``` #[stable] pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> - where Q: Hash<S> + Eq + BorrowFrom<K> + where Q: Hash<H> + Eq + BorrowFrom<K> { if self.table.size() == 0 { return None @@ -1189,10 +1194,12 @@ fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHas } } -#[stable] -#[old_impl_check] -impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, H> { - fn eq(&self, other: &HashMap<K, V, H>) -> bool { +impl<K, V, S, H> PartialEq for HashMap<K, V, S> + where K: Eq + Hash<H>, V: PartialEq, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + fn eq(&self, other: &HashMap<K, V, S>) -> bool { if self.len() != other.len() { return false; } self.iter().all(|(key, value)| @@ -1202,12 +1209,18 @@ impl<K: Eq + Hash<S>, V: PartialEq, S, H: Hasher<S>> PartialEq for HashMap<K, V, } #[stable] -#[old_impl_check] -impl<K: Eq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {} +impl<K, V, S, H> Eq for HashMap<K, V, S> + where K: Eq + Hash<H>, V: Eq, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{} #[stable] -#[old_impl_check] -impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> { +impl<K, V, S, H> Show for HashMap<K, V, S> + where K: Eq + Hash<H> + Show, V: Show, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "HashMap {{")); @@ -1221,18 +1234,22 @@ impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> } #[stable] -#[old_impl_check] -impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> { - #[stable] - fn default() -> HashMap<K, V, H> { - HashMap::with_hasher(Default::default()) +impl<K, V, S, H> Default for HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + fn default() -> HashMap<K, V, S> { + HashMap::with_hash_state(Default::default()) } } #[stable] -#[old_impl_check] -impl<K: Hash<S> + Eq, Q: ?Sized, V, S, H: Hasher<S>> Index<Q> for HashMap<K, V, H> - where Q: BorrowFrom<K> + Hash<S> + Eq +impl<K, Q: ?Sized, V, S, H> Index<Q> for HashMap<K, V, S> + where K: Eq + Hash<H>, + Q: Eq + Hash<H> + BorrowFrom<K>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Output = V; @@ -1243,9 +1260,11 @@ impl<K: Hash<S> + Eq, Q: ?Sized, V, S, H: Hasher<S>> Index<Q> for HashMap<K, V, } #[stable] -#[old_impl_check] -impl<K: Hash<S> + Eq, Q: ?Sized, V, S, H: Hasher<S>> IndexMut<Q> for HashMap<K, V, H> - where Q: BorrowFrom<K> + Hash<S> + Eq +impl<K, V, S, H, Q: ?Sized> IndexMut<Q> for HashMap<K, V, S> + where K: Eq + Hash<H>, + Q: Eq + Hash<H> + BorrowFrom<K>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Output = V; @@ -1473,19 +1492,26 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { } #[stable] -#[old_impl_check] -impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> { - fn from_iter<T: Iterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, H> { +impl<K, V, S, H> FromIterator<(K, V)> for HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + fn from_iter<T: Iterator<Item=(K, V)>>(iter: T) -> HashMap<K, V, S> { let lower = iter.size_hint().0; - let mut map = HashMap::with_capacity_and_hasher(lower, Default::default()); + let mut map = HashMap::with_capacity_and_hash_state(lower, + Default::default()); map.extend(iter); map } } #[stable] -#[old_impl_check] -impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Extend<(K, V)> for HashMap<K, V, H> { +impl<K, V, S, H> Extend<(K, V)> for HashMap<K, V, S> + where K: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ fn extend<T: Iterator<Item=(K, V)>>(&mut self, mut iter: T) { for (k, v) in iter { self.insert(k, v); @@ -1493,6 +1519,64 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Extend<(K, V)> for HashMap<K, V, H> { } } + +/// `RandomState` is the default state for `HashMap` types. +/// +/// A particular instance `RandomState` will create the same instances of +/// `Hasher`, but the hashers created by two different `RandomState` +/// instances are unlikely to produce the same result for the same values. +#[derive(Clone)] +#[allow(missing_copy_implementations)] +#[unstable = "hashing an hash maps may be altered"] +pub struct RandomState { + k0: u64, + k1: u64, +} + +#[unstable = "hashing an hash maps may be altered"] +impl RandomState { + /// Construct a new `RandomState` that is initialized with random keys. + #[inline] + pub fn new() -> RandomState { + let mut r = rand::thread_rng(); + RandomState { k0: r.gen(), k1: r.gen() } + } +} + +#[unstable = "hashing an hash maps may be altered"] +impl HashState for RandomState { + type Hasher = Hasher; + fn hasher(&self) -> Hasher { + Hasher { inner: SipHasher::new_with_keys(self.k0, self.k1) } + } +} + +#[unstable = "hashing an hash maps may be altered"] +impl Default for RandomState { + #[inline] + fn default() -> RandomState { + RandomState::new() + } +} + +/// A hasher implementation which is generated from `RandomState` instances. +/// +/// This is the default hasher used in a `HashMap` to hash keys. Types do not +/// typically declare an ability to explicitly hash into this particular type, +/// but rather in a `H: hash::Writer` type parameter. +#[allow(missing_copy_implementations)] +pub struct Hasher { inner: SipHasher } + +impl hash::Writer for Hasher { + fn write(&mut self, data: &[u8]) { self.inner.write(data) } +} + +impl hash::Hasher for Hasher { + type Output = u64; + fn reset(&mut self) { self.inner.reset() } + fn finish(&self) -> u64 { self.inner.finish() } +} + #[cfg(test)] mod test_map { use prelude::v1::*; diff --git a/src/libstd/collections/hash/mod.rs b/src/libstd/collections/hash/mod.rs index ee3fc1e6ac3..47e300af269 100644 --- a/src/libstd/collections/hash/mod.rs +++ b/src/libstd/collections/hash/mod.rs @@ -11,6 +11,7 @@ //! Unordered containers, implemented as hash-tables mod bench; +mod table; pub mod map; pub mod set; -mod table; +pub mod state; diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index f66e5384942..4003d3addf1 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -17,12 +17,13 @@ use core::marker::Sized; use default::Default; use fmt::Show; use fmt; -use hash::{Hash, Hasher, RandomSipHasher}; +use hash::{self, Hash}; use iter::{Iterator, IteratorExt, FromIterator, Map, Chain, Extend}; use ops::{BitOr, BitAnd, BitXor, Sub}; use option::Option::{Some, None, self}; -use super::map::{self, HashMap, Keys, INITIAL_CAPACITY}; +use super::map::{self, HashMap, Keys, INITIAL_CAPACITY, RandomState, Hasher}; +use super::state::HashState; // Future Optimization (FIXME!) // ============================= @@ -90,11 +91,11 @@ use super::map::{self, HashMap, Keys, INITIAL_CAPACITY}; /// ``` #[derive(Clone)] #[stable] -pub struct HashSet<T, H = RandomSipHasher> { - map: HashMap<T, (), H> +pub struct HashSet<T, S = RandomState> { + map: HashMap<T, (), S> } -impl<T: Hash + Eq> HashSet<T, RandomSipHasher> { +impl<T: Hash<Hasher> + Eq> HashSet<T, RandomState> { /// Create an empty HashSet. /// /// # Example @@ -105,7 +106,7 @@ impl<T: Hash + Eq> HashSet<T, RandomSipHasher> { /// ``` #[inline] #[stable] - pub fn new() -> HashSet<T, RandomSipHasher> { + pub fn new() -> HashSet<T, RandomState> { HashSet::with_capacity(INITIAL_CAPACITY) } @@ -120,13 +121,16 @@ impl<T: Hash + Eq> HashSet<T, RandomSipHasher> { /// ``` #[inline] #[stable] - pub fn with_capacity(capacity: uint) -> HashSet<T, RandomSipHasher> { + pub fn with_capacity(capacity: uint) -> HashSet<T, RandomState> { HashSet { map: HashMap::with_capacity(capacity) } } } -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { +impl<T, S, H> HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ /// Creates a new empty hash set which will use the given hasher to hash /// keys. /// @@ -136,16 +140,16 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// /// ``` /// use std::collections::HashSet; - /// use std::hash::sip::SipHasher; + /// use std::collections::hash_map::RandomState; /// - /// let h = SipHasher::new(); - /// let mut set = HashSet::with_hasher(h); + /// let s = RandomState::new(); + /// let mut set = HashSet::with_hash_state(s); /// set.insert(2u); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] - pub fn with_hasher(hasher: H) -> HashSet<T, H> { - HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher) + pub fn with_hash_state(hash_state: S) -> HashSet<T, S> { + HashSet::with_capacity_and_hash_state(INITIAL_CAPACITY, hash_state) } /// Create an empty HashSet with space for at least `capacity` @@ -160,16 +164,19 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// /// ``` /// use std::collections::HashSet; - /// use std::hash::sip::SipHasher; + /// use std::collections::hash_map::RandomState; /// - /// let h = SipHasher::new(); - /// let mut set = HashSet::with_capacity_and_hasher(10u, h); + /// let s = RandomState::new(); + /// let mut set = HashSet::with_capacity_and_hash_state(10u, s); /// set.insert(1i); /// ``` #[inline] #[unstable = "hasher stuff is unclear"] - pub fn with_capacity_and_hasher(capacity: uint, hasher: H) -> HashSet<T, H> { - HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) } + pub fn with_capacity_and_hash_state(capacity: uint, hash_state: S) + -> HashSet<T, S> { + HashSet { + map: HashMap::with_capacity_and_hash_state(capacity, hash_state), + } } /// Returns the number of elements the set can hold without reallocating. @@ -300,7 +307,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(diff, [4i].iter().map(|&x| x).collect()); /// ``` #[stable] - pub fn difference<'a>(&'a self, other: &'a HashSet<T, H>) -> Difference<'a, T, H> { + pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> { Difference { iter: self.iter(), other: other, @@ -328,8 +335,8 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(diff1, [1i, 4].iter().map(|&x| x).collect()); /// ``` #[stable] - pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, H>) - -> SymmetricDifference<'a, T, H> { + pub fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) + -> SymmetricDifference<'a, T, S> { SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) } } @@ -351,7 +358,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(diff, [2i, 3].iter().map(|&x| x).collect()); /// ``` #[stable] - pub fn intersection<'a>(&'a self, other: &'a HashSet<T, H>) -> Intersection<'a, T, H> { + pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> { Intersection { iter: self.iter(), other: other, @@ -376,7 +383,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(diff, [1i, 2, 3, 4].iter().map(|&x| x).collect()); /// ``` #[stable] - pub fn union<'a>(&'a self, other: &'a HashSet<T, H>) -> Union<'a, T, H> { + pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> { Union { iter: self.iter().chain(other.difference(self)) } } @@ -452,7 +459,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// ``` #[stable] pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool - where Q: BorrowFrom<T> + Hash<S> + Eq + where Q: BorrowFrom<T> + Hash<H> + Eq { self.map.contains_key(value) } @@ -475,7 +482,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(a.is_disjoint(&b), false); /// ``` #[stable] - pub fn is_disjoint(&self, other: &HashSet<T, H>) -> bool { + pub fn is_disjoint(&self, other: &HashSet<T, S>) -> bool { self.iter().all(|v| !other.contains(v)) } @@ -496,7 +503,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// assert_eq!(set.is_subset(&sup), false); /// ``` #[stable] - pub fn is_subset(&self, other: &HashSet<T, H>) -> bool { + pub fn is_subset(&self, other: &HashSet<T, S>) -> bool { self.iter().all(|v| other.contains(v)) } @@ -521,7 +528,7 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// ``` #[inline] #[stable] - pub fn is_superset(&self, other: &HashSet<T, H>) -> bool { + pub fn is_superset(&self, other: &HashSet<T, S>) -> bool { other.is_subset(self) } @@ -562,16 +569,19 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> { /// ``` #[stable] pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool - where Q: BorrowFrom<T> + Hash<S> + Eq + where Q: BorrowFrom<T> + Hash<H> + Eq { self.map.remove(value).is_some() } } #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> { - fn eq(&self, other: &HashSet<T, H>) -> bool { +impl<T, S, H> PartialEq for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ + fn eq(&self, other: &HashSet<T, S>) -> bool { if self.len() != other.len() { return false; } self.iter().all(|key| other.contains(key)) @@ -579,12 +589,18 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> PartialEq for HashSet<T, H> { } #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {} +impl<T, S, H> Eq for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{} #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> { +impl<T, S, H> fmt::Show for HashSet<T, S> + where T: Eq + Hash<H> + fmt::Show, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "HashSet {{")); @@ -598,19 +614,25 @@ impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> { } #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> { - fn from_iter<I: Iterator<Item=T>>(iter: I) -> HashSet<T, H> { +impl<T, S, H> FromIterator<T> for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + fn from_iter<I: Iterator<Item=T>>(iter: I) -> HashSet<T, S> { let lower = iter.size_hint().0; - let mut set = HashSet::with_capacity_and_hasher(lower, Default::default()); + let mut set = HashSet::with_capacity_and_hash_state(lower, Default::default()); set.extend(iter); set } } #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S>> Extend<T> for HashSet<T, H> { +impl<T, S, H> Extend<T> for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> +{ fn extend<I: Iterator<Item=T>>(&mut self, mut iter: I) { for k in iter { self.insert(k); @@ -619,21 +641,26 @@ impl<T: Eq + Hash<S>, S, H: Hasher<S>> Extend<T> for HashSet<T, H> { } #[stable] -#[old_impl_check] -impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Default for HashSet<T, H> { +impl<T, S, H> Default for HashSet<T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ #[stable] - fn default() -> HashSet<T, H> { - HashSet::with_hasher(Default::default()) + fn default() -> HashSet<T, S> { + HashSet::with_hash_state(Default::default()) } } #[stable] -#[old_impl_check] -impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default> -BitOr<&'b HashSet<T, H>> for &'a HashSet<T, H> { - type Output = HashSet<T, H>; +impl<'a, 'b, T, S, H> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S> + where T: Eq + Hash<H> + Clone, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + type Output = HashSet<T, S>; - /// Returns the union of `self` and `rhs` as a new `HashSet<T, H>`. + /// Returns the union of `self` and `rhs` as a new `HashSet<T, S>`. /// /// # Examples /// @@ -653,18 +680,20 @@ BitOr<&'b HashSet<T, H>> for &'a HashSet<T, H> { /// } /// assert_eq!(i, expected.len()); /// ``` - fn bitor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> { + fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> { self.union(rhs).cloned().collect() } } #[stable] -#[old_impl_check] -impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default> -BitAnd<&'b HashSet<T, H>> for &'a HashSet<T, H> { - type Output = HashSet<T, H>; +impl<'a, 'b, T, S, H> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S> + where T: Eq + Hash<H> + Clone, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + type Output = HashSet<T, S>; - /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, H>`. + /// Returns the intersection of `self` and `rhs` as a new `HashSet<T, S>`. /// /// # Examples /// @@ -684,18 +713,20 @@ BitAnd<&'b HashSet<T, H>> for &'a HashSet<T, H> { /// } /// assert_eq!(i, expected.len()); /// ``` - fn bitand(self, rhs: &HashSet<T, H>) -> HashSet<T, H> { + fn bitand(self, rhs: &HashSet<T, S>) -> HashSet<T, S> { self.intersection(rhs).cloned().collect() } } #[stable] -#[old_impl_check] -impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default> -BitXor<&'b HashSet<T, H>> for &'a HashSet<T, H> { - type Output = HashSet<T, H>; +impl<'a, 'b, T, S, H> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S> + where T: Eq + Hash<H> + Clone, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + type Output = HashSet<T, S>; - /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, H>`. + /// Returns the symmetric difference of `self` and `rhs` as a new `HashSet<T, S>`. /// /// # Examples /// @@ -715,18 +746,20 @@ BitXor<&'b HashSet<T, H>> for &'a HashSet<T, H> { /// } /// assert_eq!(i, expected.len()); /// ``` - fn bitxor(self, rhs: &HashSet<T, H>) -> HashSet<T, H> { + fn bitxor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> { self.symmetric_difference(rhs).cloned().collect() } } #[stable] -#[old_impl_check] -impl<'a, 'b, T: Eq + Hash<S> + Clone, S, H: Hasher<S> + Default> -Sub<&'b HashSet<T, H>> for &'a HashSet<T, H> { - type Output = HashSet<T, H>; +impl<'a, 'b, T, S, H> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S> + where T: Eq + Hash<H> + Clone, + S: HashState<Hasher=H> + Default, + H: hash::Hasher<Output=u64> +{ + type Output = HashSet<T, S>; - /// Returns the difference of `self` and `rhs` as a new `HashSet<T, H>`. + /// Returns the difference of `self` and `rhs` as a new `HashSet<T, S>`. /// /// # Examples /// @@ -746,7 +779,7 @@ Sub<&'b HashSet<T, H>> for &'a HashSet<T, H> { /// } /// assert_eq!(i, expected.len()); /// ``` - fn sub(self, rhs: &HashSet<T, H>) -> HashSet<T, H> { + fn sub(self, rhs: &HashSet<T, S>) -> HashSet<T, S> { self.difference(rhs).cloned().collect() } } @@ -771,32 +804,32 @@ pub struct Drain<'a, K: 'a> { /// Intersection iterator #[stable] -pub struct Intersection<'a, T: 'a, H: 'a> { +pub struct Intersection<'a, T: 'a, S: 'a> { // iterator of the first set iter: Iter<'a, T>, // the second set - other: &'a HashSet<T, H>, + other: &'a HashSet<T, S>, } /// Difference iterator #[stable] -pub struct Difference<'a, T: 'a, H: 'a> { +pub struct Difference<'a, T: 'a, S: 'a> { // iterator of the first set iter: Iter<'a, T>, // the second set - other: &'a HashSet<T, H>, + other: &'a HashSet<T, S>, } /// Symmetric difference iterator. #[stable] -pub struct SymmetricDifference<'a, T: 'a, H: 'a> { - iter: Chain<Difference<'a, T, H>, Difference<'a, T, H>> +pub struct SymmetricDifference<'a, T: 'a, S: 'a> { + iter: Chain<Difference<'a, T, S>, Difference<'a, T, S>> } /// Set union iterator. #[stable] -pub struct Union<'a, T: 'a, H: 'a> { - iter: Chain<Iter<'a, T>, Difference<'a, T, H>> +pub struct Union<'a, T: 'a, S: 'a> { + iter: Chain<Iter<'a, T>, Difference<'a, T, S>> } #[stable] @@ -824,9 +857,10 @@ impl<'a, K: 'a> Iterator for Drain<'a, K> { } #[stable] -#[old_impl_check] -impl<'a, T, S, H> Iterator for Intersection<'a, T, H> - where T: Eq + Hash<S>, H: Hasher<S> +impl<'a, T, S, H> Iterator for Intersection<'a, T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Item = &'a T; @@ -848,9 +882,10 @@ impl<'a, T, S, H> Iterator for Intersection<'a, T, H> } #[stable] -#[old_impl_check] -impl<'a, T, S, H> Iterator for Difference<'a, T, H> - where T: Eq + Hash<S>, H: Hasher<S> +impl<'a, T, S, H> Iterator for Difference<'a, T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Item = &'a T; @@ -872,9 +907,10 @@ impl<'a, T, S, H> Iterator for Difference<'a, T, H> } #[stable] -#[old_impl_check] -impl<'a, T, S, H> Iterator for SymmetricDifference<'a, T, H> - where T: Eq + Hash<S>, H: Hasher<S> +impl<'a, T, S, H> Iterator for SymmetricDifference<'a, T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Item = &'a T; @@ -883,9 +919,10 @@ impl<'a, T, S, H> Iterator for SymmetricDifference<'a, T, H> } #[stable] -#[old_impl_check] -impl<'a, T, S, H> Iterator for Union<'a, T, H> - where T: Eq + Hash<S>, H: Hasher<S> +impl<'a, T, S, H> Iterator for Union<'a, T, S> + where T: Eq + Hash<H>, + S: HashState<Hasher=H>, + H: hash::Hasher<Output=u64> { type Item = &'a T; diff --git a/src/libstd/collections/hash/state.rs b/src/libstd/collections/hash/state.rs new file mode 100644 index 00000000000..ffbc958f179 --- /dev/null +++ b/src/libstd/collections/hash/state.rs @@ -0,0 +1,51 @@ +// 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. + +use clone::Clone; +use default::Default; +use hash; + +/// A trait representing stateful hashes which can be used to hash keys in a +/// `HashMap`. +/// +/// A HashState is used as a factory for instances of `Hasher` which a `HashMap` +/// can then use to hash keys independently. A `HashMap` by default uses a state +/// which will create instances of a `SipHasher`, but a custom state factory can +/// be provided to the `with_hash_state` function. +/// +/// If a hashing algorithm has no initial state, then the `Hasher` type for that +/// algorithm can implement the `Default` trait and create hash maps with the +/// `DefaultState` structure. This state is 0-sized and will simply delegate +/// to `Default` when asked to create a hasher. +pub trait HashState { + type Hasher: hash::Hasher; + + /// Creates a new hasher based on the given state of this object. + fn hasher(&self) -> Self::Hasher; +} + +/// A structure which is a factory for instances of `Hasher` which implement the +/// default trait. +/// +/// This struct has is 0-sized and does not need construction. +pub struct DefaultState<H>; + +impl<H: Default + hash::Hasher> HashState for DefaultState<H> { + type Hasher = H; + fn hasher(&self) -> H { Default::default() } +} + +impl<H> Clone for DefaultState<H> { + fn clone(&self) -> DefaultState<H> { DefaultState } +} + +impl<H> Default for DefaultState<H> { + fn default() -> DefaultState<H> { DefaultState } +} diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index 6eb98da4da4..456f3763b39 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -26,6 +26,7 @@ use option::Option::{Some, None}; use ptr::{Unique, PtrExt, copy_nonoverlapping_memory, zero_memory}; use ptr; use rt::heap::{allocate, deallocate}; +use collections::hash_state::HashState; const EMPTY_BUCKET: u64 = 0u64; @@ -138,12 +139,18 @@ impl SafeHash { /// We need to remove hashes of 0. That's reserved for empty buckets. /// This function wraps up `hash_keyed` to be the only way outside this /// module to generate a SafeHash. -pub fn make_hash<T: ?Sized + Hash<S>, S, H: Hasher<S>>(hasher: &H, t: &T) -> SafeHash { +pub fn make_hash<T: ?Sized, S, H>(hash_state: &S, t: &T) -> SafeHash + where T: Hash<H>, + S: HashState<Hasher=H>, + H: Hasher<Output=u64> +{ + let mut state = hash_state.hasher(); + t.hash(&mut state); // We need to avoid 0u64 in order to prevent collisions with // EMPTY_HASH. We can maintain our precious uniform distribution // of initial indexes by unconditionally setting the MSB, // effectively reducing 64-bits hashes to 63 bits. - SafeHash { hash: 0x8000_0000_0000_0000 | hasher.hash(t) } + SafeHash { hash: 0x8000_0000_0000_0000 | state.finish() } } // `replace` casts a `*u64` to a `*SafeHash`. Since we statically @@ -625,7 +632,7 @@ impl<K, V> RawTable<K, V> { /// Creates a new raw table from a given capacity. All buckets are /// initially empty. - #[allow(experimental)] + #[allow(unstable)] pub fn new(capacity: uint) -> RawTable<K, V> { unsafe { let ret = RawTable::new_uninitialized(capacity); diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index 9b2a4926bcb..71ab89027ff 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -333,3 +333,10 @@ pub mod hash_set { //! A hashset pub use super::hash::set::*; } + +/// Experimental support for providing custom hash algorithms to a HashMap and +/// HashSet. +#[unstable = "module was recently added"] +pub mod hash_state { + pub use super::hash::state::*; +} diff --git a/src/libstd/dynamic_lib.rs b/src/libstd/dynamic_lib.rs index 2d013a8a5b8..3eeb09b79da 100644 --- a/src/libstd/dynamic_lib.rs +++ b/src/libstd/dynamic_lib.rs @@ -12,7 +12,7 @@ //! //! A simple wrapper over the platform's dynamic library facilities -#![experimental] +#![unstable] #![allow(missing_docs)] use prelude::v1::*; diff --git a/src/libstd/failure.rs b/src/libstd/failure.rs index 50538d3e43d..54191cf2404 100644 --- a/src/libstd/failure.rs +++ b/src/libstd/failure.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![experimental] +#![unstable] use prelude::v1::*; @@ -37,7 +37,7 @@ pub fn on_fail(obj: &(Any+Send), file: &'static str, line: uint) { let msg = match obj.downcast_ref::<&'static str>() { Some(s) => *s, None => match obj.downcast_ref::<String>() { - Some(s) => s.index(&FullRange), + Some(s) => &s[], None => "Box<Any>", } }; diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 70ea366bbf4..d7f8eb2e415 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -84,7 +84,7 @@ impl CString { unsafe { CString::from_vec_unchecked(v) } } - /// Create a C-compatibel string from a byte vector without checking for + /// Create a C-compatible string from a byte vector without checking for /// interior 0 bytes. /// /// This method is equivalent to `from_vec` except that no runtime assertion diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 1623b6452b7..907925e93d3 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -175,7 +175,7 @@ //! use std::f64; //! use std::num::Float; //! -//! #[deriving(Show)] +//! #[derive(Show)] //! struct Vector2D { //! x: int, //! y: int, @@ -410,7 +410,7 @@ //! them with the same character. For example, the `{` character is escaped with //! `{{` and the `}` character is escaped with `}}`. -#![experimental] +#![unstable] use string; @@ -439,7 +439,7 @@ pub use core::fmt::{argument, argumentuint}; /// let s = fmt::format(format_args!("Hello, {}!", "world")); /// assert_eq!(s, "Hello, world!".to_string()); /// ``` -#[experimental = "this is an implementation detail of format! and should not \ +#[unstable = "this is an implementation detail of format! and should not \ be called directly"] pub fn format(args: Arguments) -> string::String { let mut output = string::String::new(); diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs deleted file mode 100644 index 69e7e429d07..00000000000 --- a/src/libstd/hash.rs +++ /dev/null @@ -1,105 +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. - -//! Generic hashing support. -//! -//! This module provides a generic way to compute the hash of a value. The -//! simplest way to make a type hashable is to use `#[derive(Hash)]`: -//! -//! # Example -//! -//! ```rust -//! use std::hash; -//! use std::hash::Hash; -//! -//! #[derive(Hash)] -//! struct Person { -//! id: uint, -//! name: String, -//! phone: u64, -//! } -//! -//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; -//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; -//! -//! assert!(hash::hash(&person1) != hash::hash(&person2)); -//! ``` -//! -//! If you need more control over how a value is hashed, you need to implement -//! the trait `Hash`: -//! -//! ```rust -//! use std::hash; -//! use std::hash::Hash; -//! use std::hash::sip::SipState; -//! -//! struct Person { -//! id: uint, -//! name: String, -//! phone: u64, -//! } -//! -//! impl Hash for Person { -//! fn hash(&self, state: &mut SipState) { -//! self.id.hash(state); -//! self.phone.hash(state); -//! } -//! } -//! -//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 }; -//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 }; -//! -//! assert!(hash::hash(&person1) == hash::hash(&person2)); -//! ``` - -#![experimental] - -pub use core::hash::{Hash, Hasher, Writer, hash, sip}; - -use core::marker::Sized; -use default::Default; -use rand::Rng; -use rand; - -/// `RandomSipHasher` computes the SipHash algorithm from a stream of bytes -/// initialized with random keys. -#[derive(Clone)] -pub struct RandomSipHasher { - hasher: sip::SipHasher, -} - -impl RandomSipHasher { - /// Construct a new `RandomSipHasher` that is initialized with random keys. - #[inline] - pub fn new() -> RandomSipHasher { - let mut r = rand::thread_rng(); - let r0 = r.gen(); - let r1 = r.gen(); - RandomSipHasher { - hasher: sip::SipHasher::new_with_keys(r0, r1), - } - } -} - -impl Hasher<sip::SipState> for RandomSipHasher { - #[inline] - fn hash<T: ?Sized + Hash<sip::SipState>>(&self, value: &T) -> u64 { - self.hasher.hash(value) - } -} - -#[stable] -impl Default for RandomSipHasher { - #[stable] - #[inline] - fn default() -> RandomSipHasher { - RandomSipHasher::new() - } -} diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 74c503e6f2b..ba13bd05dc5 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -15,7 +15,7 @@ use cmp; use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult}; use iter::{IteratorExt, ExactSizeIterator}; -use ops::{Drop, Index}; +use ops::Drop; use option::Option; use option::Option::{Some, None}; use result::Result::Ok; @@ -97,7 +97,7 @@ impl<R: Reader> Buffer for BufferedReader<R> { self.cap = try!(self.inner.read(self.buf.as_mut_slice())); self.pos = 0; } - Ok(self.buf.index(&(self.pos..self.cap))) + Ok(&self.buf[self.pos..self.cap]) } fn consume(&mut self, amt: uint) { @@ -114,7 +114,7 @@ impl<R: Reader> Reader for BufferedReader<R> { let nread = { let available = try!(self.fill_buf()); let nread = cmp::min(available.len(), buf.len()); - slice::bytes::copy_memory(buf, available.index(&(0..nread))); + slice::bytes::copy_memory(buf, &available[0..nread]); nread }; self.pos += nread; @@ -168,7 +168,7 @@ impl<W: Writer> BufferedWriter<W> { fn flush_buf(&mut self) -> IoResult<()> { if self.pos != 0 { - let ret = self.inner.as_mut().unwrap().write(self.buf.index(&(0..self.pos))); + let ret = self.inner.as_mut().unwrap().write(&self.buf[0..self.pos]); self.pos = 0; ret } else { @@ -260,9 +260,9 @@ impl<W: Writer> Writer for LineBufferedWriter<W> { fn write(&mut self, buf: &[u8]) -> IoResult<()> { match buf.iter().rposition(|&b| b == b'\n') { Some(i) => { - try!(self.inner.write(buf.index(&(0..(i + 1))))); + try!(self.inner.write(&buf[0..(i + 1)])); try!(self.inner.flush()); - try!(self.inner.write(buf.index(&((i + 1)..)))); + try!(self.inner.write(&buf[(i + 1)..])); Ok(()) } None => self.inner.write(buf), @@ -510,7 +510,7 @@ mod test { assert_eq!(a, &w.get_ref()[]); let w = w.into_inner(); let a: &[_] = &[0, 1]; - assert_eq!(a, w.index(&FullRange)); + assert_eq!(a, &w[]); } // This is just here to make sure that we don't infinite loop in the @@ -607,14 +607,14 @@ mod test { #[test] fn read_char_buffered() { let buf = [195u8, 159u8]; - let mut reader = BufferedReader::with_capacity(1, buf.index(&FullRange)); + let mut reader = BufferedReader::with_capacity(1, &buf[]); assert_eq!(reader.read_char(), Ok('ß')); } #[test] fn test_chars() { let buf = [195u8, 159u8, b'a']; - let mut reader = BufferedReader::with_capacity(1, buf.index(&FullRange)); + let mut reader = BufferedReader::with_capacity(1, &buf[]); let mut it = reader.chars(); assert_eq!(it.next(), Some(Ok('ß'))); assert_eq!(it.next(), Some(Ok('a'))); diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index bce097e17ef..b578f4d5adc 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -13,7 +13,6 @@ use cmp; use sync::mpsc::{Sender, Receiver}; use io; use option::Option::{None, Some}; -use ops::Index; use result::Result::{Ok, Err}; use slice::{bytes, SliceExt}; use super::{Buffer, Reader, Writer, IoResult}; @@ -91,7 +90,7 @@ impl Reader for ChanReader { Some(src) => { let dst = buf.slice_from_mut(num_read); let count = cmp::min(src.len(), dst.len()); - bytes::copy_memory(dst, src.index(&(0..count))); + bytes::copy_memory(dst, &src[0..count]); count }, None => 0, diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index eadca8e42e5..dbccc81c4cc 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -889,7 +889,7 @@ mod test { let mut read_buf = [0; 1028]; let read_str = match check!(read_stream.read(&mut read_buf)) { -1|0 => panic!("shouldn't happen"), - n => str::from_utf8(read_buf.index(&(0..n))).unwrap().to_string() + n => str::from_utf8(&read_buf[0..n]).unwrap().to_string() }; assert_eq!(read_str.as_slice(), message); } diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 9a6ad04fdbc..c5e289398e0 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -13,7 +13,6 @@ //! Readers and Writers for in-memory buffers use cmp::min; -use ops::Index; use option::Option::None; use result::Result::{Err, Ok}; use io; @@ -160,7 +159,7 @@ impl Reader for MemReader { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = self.buf.index(&(self.pos.. (self.pos + write_len))); + let input = &self.buf[self.pos.. (self.pos + write_len)]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); @@ -188,7 +187,7 @@ impl Buffer for MemReader { #[inline] fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { if self.pos < self.buf.len() { - Ok(self.buf.index(&(self.pos..))) + Ok(&self.buf[self.pos..]) } else { Err(io::standard_error(io::EndOfFile)) } @@ -205,7 +204,7 @@ impl<'a> Reader for &'a [u8] { let write_len = min(buf.len(), self.len()); { - let input = self.index(&(0..write_len)); + let input = &self[0..write_len]; let output = buf.slice_to_mut(write_len); slice::bytes::copy_memory(output, input); } @@ -228,7 +227,7 @@ impl<'a> Buffer for &'a [u8] { #[inline] fn consume(&mut self, amt: uint) { - *self = self.index(&(amt..)); + *self = &self[amt..]; } } @@ -287,7 +286,7 @@ impl<'a> Writer for BufWriter<'a> { Ok(()) } else { - slice::bytes::copy_memory(dst, src.index(&(0..dst_len))); + slice::bytes::copy_memory(dst, &src[0..dst_len]); self.pos += dst_len; @@ -350,7 +349,7 @@ impl<'a> Reader for BufReader<'a> { let write_len = min(buf.len(), self.buf.len() - self.pos); { - let input = self.buf.index(&(self.pos.. (self.pos + write_len))); + let input = &self.buf[self.pos.. (self.pos + write_len)]; let output = buf.slice_to_mut(write_len); assert_eq!(input.len(), output.len()); slice::bytes::copy_memory(output, input); @@ -378,7 +377,7 @@ impl<'a> Buffer for BufReader<'a> { #[inline] fn fill_buf(&mut self) -> IoResult<&[u8]> { if self.pos < self.buf.len() { - Ok(self.buf.index(&(self.pos..))) + Ok(&self.buf[self.pos..]) } else { Err(io::standard_error(io::EndOfFile)) } @@ -393,7 +392,7 @@ mod test { extern crate "test" as test_crate; use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt}; - use prelude::v1::{IteratorExt, Index}; + use prelude::v1::IteratorExt; use io; use iter::repeat; use self::test_crate::Bencher; @@ -499,7 +498,7 @@ mod test { assert_eq!(buf, b); assert_eq!(reader.read(&mut buf), Ok(3)); let b: &[_] = &[5, 6, 7]; - assert_eq!(buf.index(&(0..3)), b); + assert_eq!(&buf[0..3], b); assert!(reader.read(&mut buf).is_err()); let mut reader = MemReader::new(vec!(0, 1, 2, 3, 4, 5, 6, 7)); assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); @@ -525,7 +524,7 @@ mod test { assert_eq!(buf.as_slice(), b); assert_eq!(reader.read(&mut buf), Ok(3)); let b: &[_] = &[5, 6, 7]; - assert_eq!(buf.index(&(0..3)), b); + assert_eq!(&buf[0..3], b); assert!(reader.read(&mut buf).is_err()); let mut reader = &mut in_buf.as_slice(); assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); @@ -552,7 +551,7 @@ mod test { assert_eq!(buf, b); assert_eq!(reader.read(&mut buf), Ok(3)); let b: &[_] = &[5, 6, 7]; - assert_eq!(buf.index(&(0..3)), b); + assert_eq!(&buf[0..3], b); assert!(reader.read(&mut buf).is_err()); let mut reader = BufReader::new(in_buf.as_slice()); assert_eq!(reader.read_until(3).unwrap(), vec!(0, 1, 2, 3)); diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 9ef9081bc3c..3968dda2a82 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -219,7 +219,7 @@ //! concerned with error handling; instead its caller is responsible for //! responding to errors that may occur while attempting to read the numbers. -#![experimental] +#![unstable] #![deny(unused_must_use)] pub use self::SeekStyle::*; @@ -236,7 +236,7 @@ use int; use iter::{Iterator, IteratorExt}; use marker::Sized; use mem::transmute; -use ops::{FnOnce, Index}; +use ops::FnOnce; use option::Option; use option::Option::{Some, None}; use os; @@ -1069,7 +1069,7 @@ pub trait Writer { fn write_char(&mut self, c: char) -> IoResult<()> { let mut buf = [0u8; 4]; let n = c.encode_utf8(buf.as_mut_slice()).unwrap_or(0); - self.write(buf.index(&(0..n))) + self.write(&buf[0..n]) } /// Write the result of passing n through `int::to_str_bytes`. @@ -1284,7 +1284,7 @@ impl<'a> Writer for &'a mut (Writer+'a) { /// process_input(tee); /// } /// -/// println!("input processed: {}", output); +/// println!("input processed: {:?}", output); /// # } /// ``` pub struct RefWriter<'a, W:'a> { @@ -1454,7 +1454,7 @@ pub trait Buffer: Reader { }; match available.iter().position(|&b| b == byte) { Some(i) => { - res.push_all(available.index(&(0..(i + 1)))); + res.push_all(&available[0..(i + 1)]); used = i + 1; break } @@ -1493,7 +1493,7 @@ pub trait Buffer: Reader { } } } - match str::from_utf8(buf.index(&(0..width))).ok() { + match str::from_utf8(&buf[0..width]).ok() { Some(s) => Ok(s.char_at(0)), None => Err(standard_error(InvalidInput)) } @@ -1783,9 +1783,8 @@ pub struct UnstableFileStat { } -// NOTE(stage0): change this one last #[doc=..] to /// after the next snapshot bitflags! { - #[doc = "A set of permissions for a file or directory is represented by a set of"] + /// A set of permissions for a file or directory is represented by a set of /// flags which are or'd together. flags FilePermission: u32 { const USER_READ = 0o400, diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index b9f653f86c2..d09afea94dc 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -22,7 +22,7 @@ use fmt; use io::{self, IoResult, IoError}; use io::net; use iter::{Iterator, IteratorExt}; -use ops::{FnOnce, FnMut, Index}; +use ops::{FnOnce, FnMut}; use option::Option; use option::Option::{None, Some}; use result::Result::{Ok, Err}; @@ -313,7 +313,7 @@ impl<'a> Parser<'a> { let mut tail = [0u16; 8]; let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size); - Some(ipv6_addr_from_head_tail(head.index(&(0..head_size)), tail.index(&(0..tail_size)))) + Some(ipv6_addr_from_head_tail(&head[0..head_size], &tail[0..tail_size])) } fn read_ipv6_addr(&mut self) -> Option<IpAddr> { diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/io/net/pipe.rs index 29295b5751c..42d9fff6d15 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/io/net/pipe.rs @@ -68,7 +68,7 @@ impl UnixStream { /// /// If a `timeout` with zero or negative duration is specified then /// the function returns `Err`, with the error kind set to `TimedOut`. - #[experimental = "the timeout argument is likely to change types"] + #[unstable = "the timeout argument is likely to change types"] pub fn connect_timeout<P>(path: P, timeout: Duration) -> IoResult<UnixStream> where P: BytesContainer { @@ -107,7 +107,7 @@ impl UnixStream { /// Sets the read/write timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_timeout(timeout_ms) } @@ -115,7 +115,7 @@ impl UnixStream { /// Sets the read timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_read_timeout(timeout_ms) } @@ -123,7 +123,7 @@ impl UnixStream { /// Sets the write timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_write_timeout(timeout_ms) } @@ -219,7 +219,7 @@ impl UnixAcceptor { /// When using this method, it is likely necessary to reset the timeout as /// appropriate, the timeout specified is specific to this object, not /// specific to the next request. - #[experimental = "the name and arguments to this function are likely \ + #[unstable = "the name and arguments to this function are likely \ to change"] pub fn set_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_timeout(timeout_ms) @@ -229,7 +229,7 @@ impl UnixAcceptor { /// /// This function has the same semantics as `TcpAcceptor::close_accept`, and /// more information can be found in that documentation. - #[experimental] + #[unstable] pub fn close_accept(&mut self) -> IoResult<()> { self.inner.close_accept() } diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index 7a376b50cd7..6a3f5fcb2c6 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -85,7 +85,7 @@ impl TcpStream { /// /// If a `timeout` with zero or negative duration is specified then /// the function returns `Err`, with the error kind set to `TimedOut`. - #[experimental = "the timeout argument may eventually change types"] + #[unstable = "the timeout argument may eventually change types"] pub fn connect_timeout<A: ToSocketAddr>(addr: A, timeout: Duration) -> IoResult<TcpStream> { if timeout <= Duration::milliseconds(0) { @@ -109,7 +109,7 @@ impl TcpStream { } /// Sets the nodelay flag on this connection to the boolean specified - #[experimental] + #[unstable] pub fn set_nodelay(&mut self, nodelay: bool) -> IoResult<()> { self.inner.set_nodelay(nodelay) } @@ -119,7 +119,7 @@ impl TcpStream { /// If the value specified is `None`, then the keepalive flag is cleared on /// this connection. Otherwise, the keepalive timeout will be set to the /// specified time, in seconds. - #[experimental] + #[unstable] pub fn set_keepalive(&mut self, delay_in_seconds: Option<uint>) -> IoResult<()> { self.inner.set_keepalive(delay_in_seconds) } @@ -187,7 +187,7 @@ impl TcpStream { /// /// For clarification on the semantics of interrupting a read and a write, /// take a look at `set_read_timeout` and `set_write_timeout`. - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_timeout(timeout_ms) } @@ -204,7 +204,7 @@ impl TcpStream { /// action is taken. Otherwise, the read operation will be scheduled to /// promptly return. If a timeout error is returned, then no data was read /// during the timeout period. - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_read_timeout(timeout_ms) } @@ -231,7 +231,7 @@ impl TcpStream { /// does not know how many bytes were written as part of the timeout /// operation. It may be the case that bytes continue to be written in an /// asynchronous fashion after the call to write returns. - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_write_timeout(timeout_ms) } @@ -374,7 +374,7 @@ impl TcpAcceptor { /// # Example /// /// ```no_run - /// # #![allow(experimental)] + /// # #![allow(unstable)] /// use std::io::TcpListener; /// use std::io::{Listener, Acceptor, TimedOut}; /// @@ -397,7 +397,7 @@ impl TcpAcceptor { /// a.set_timeout(None); /// let socket = a.accept(); /// ``` - #[experimental = "the type of the argument and name of this function are \ + #[unstable = "the type of the argument and name of this function are \ subject to change"] pub fn set_timeout(&mut self, ms: Option<u64>) { self.inner.set_timeout(ms); } @@ -418,7 +418,7 @@ impl TcpAcceptor { /// # Example /// /// ``` - /// # #![allow(experimental)] + /// # #![allow(unstable)] /// use std::io::{TcpListener, Listener, Acceptor, EndOfFile}; /// use std::thread::Thread; /// @@ -444,7 +444,7 @@ impl TcpAcceptor { /// // Signal our accept loop to exit /// assert!(a.close_accept().is_ok()); /// ``` - #[experimental] + #[unstable] pub fn close_accept(&mut self) -> IoResult<()> { self.inner.close_accept() } @@ -482,7 +482,7 @@ impl sys_common::AsInner<TcpAcceptorImp> for TcpAcceptor { } #[cfg(test)] -#[allow(experimental)] +#[allow(unstable)] mod test { use prelude::v1::*; diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index a4db0d4f5de..8cdad3f528a 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -92,13 +92,13 @@ impl UdpSocket { } /// Joins a multicast IP address (becomes a member of it) - #[experimental] + #[unstable] pub fn join_multicast(&mut self, multi: IpAddr) -> IoResult<()> { self.inner.join_multicast(multi) } /// Leaves a multicast IP address (drops membership from it) - #[experimental] + #[unstable] pub fn leave_multicast(&mut self, multi: IpAddr) -> IoResult<()> { self.inner.leave_multicast(multi) } @@ -106,25 +106,25 @@ impl UdpSocket { /// Set the multicast loop flag to the specified value /// /// This lets multicast packets loop back to local sockets (if enabled) - #[experimental] + #[unstable] pub fn set_multicast_loop(&mut self, on: bool) -> IoResult<()> { self.inner.set_multicast_loop(on) } /// Sets the multicast TTL - #[experimental] + #[unstable] pub fn set_multicast_ttl(&mut self, ttl: int) -> IoResult<()> { self.inner.multicast_time_to_live(ttl) } /// Sets this socket's TTL - #[experimental] + #[unstable] pub fn set_ttl(&mut self, ttl: int) -> IoResult<()> { self.inner.time_to_live(ttl) } /// Sets the broadcast flag on or off - #[experimental] + #[unstable] pub fn set_broadcast(&mut self, broadcast: bool) -> IoResult<()> { self.inner.set_broadcast(broadcast) } @@ -132,7 +132,7 @@ impl UdpSocket { /// Sets the read/write timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_timeout(timeout_ms) } @@ -140,7 +140,7 @@ impl UdpSocket { /// Sets the read timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_read_timeout(timeout_ms) } @@ -148,7 +148,7 @@ impl UdpSocket { /// Sets the write timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` - #[experimental = "the timeout argument may change in type and value"] + #[unstable = "the timeout argument may change in type and value"] pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) { self.inner.set_write_timeout(timeout_ms) } @@ -176,7 +176,7 @@ impl sys_common::AsInner<UdpSocketImp> for UdpSocket { } #[cfg(test)] -#[allow(experimental)] +#[allow(unstable)] mod test { use prelude::v1::*; diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 55df6330dd3..a093e748d57 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -10,7 +10,7 @@ //! Bindings for executing child processes -#![allow(experimental)] +#![allow(unstable)] #![allow(non_upper_case_globals)] pub use self::StdioContainer::*; @@ -34,7 +34,7 @@ use sys::process::Process as ProcessImp; use sys; use thread::Thread; -#[cfg(windows)] use std::hash::sip::SipState; +#[cfg(windows)] use hash; #[cfg(windows)] use str; /// Signal a process to exit, without forcibly killing it. Corresponds to @@ -98,7 +98,7 @@ pub struct Process { /// A representation of environment variable name /// It compares case-insensitive on Windows and case-sensitive everywhere else. #[cfg(not(windows))] -#[derive(PartialEq, Eq, Hash, Clone, Show)] +#[derive(Hash, PartialEq, Eq, Clone, Show)] struct EnvKey(CString); #[doc(hidden)] @@ -107,8 +107,8 @@ struct EnvKey(CString); struct EnvKey(CString); #[cfg(windows)] -impl Hash for EnvKey { - fn hash(&self, state: &mut SipState) { +impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for EnvKey { + fn hash(&self, state: &mut H) { let &EnvKey(ref x) = self; match str::from_utf8(x.as_bytes()) { Ok(s) => for ch in s.chars() { @@ -395,13 +395,6 @@ impl Command { } } -#[cfg(stage0)] -impl fmt::Show for Command { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for Command { /// Format the program and arguments of a Command for display. Any /// non-utf8 data is lossily converted using the utf8 replacement @@ -668,7 +661,7 @@ impl Process { /// # Example /// /// ```no_run - /// # #![allow(experimental)] + /// # #![allow(unstable)] /// use std::io::{Command, IoResult}; /// use std::io::process::ProcessExit; /// @@ -696,7 +689,7 @@ impl Process { /// p.wait() /// } /// ``` - #[experimental = "the type of the timeout is likely to change"] + #[unstable = "the type of the timeout is likely to change"] pub fn set_timeout(&mut self, timeout_ms: Option<u64>) { self.deadline = timeout_ms.map(|i| i + sys::timer::now()).unwrap_or(0); } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index c0254a3e7a2..5a7219495f5 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -59,7 +59,7 @@ impl<R: Reader> Reader for LimitReader<R> { impl<R: Buffer> Buffer for LimitReader<R> { fn fill_buf<'a>(&'a mut self) -> io::IoResult<&'a [u8]> { let amt = try!(self.inner.fill_buf()); - let buf = amt.index(&(0..cmp::min(amt.len(), self.limit))); + let buf = &amt[0..cmp::min(amt.len(), self.limit)]; if buf.len() == 0 { Err(io::standard_error(io::EndOfFile)) } else { @@ -220,7 +220,7 @@ impl<R: Reader, W: Writer> TeeReader<R, W> { impl<R: Reader, W: Writer> Reader for TeeReader<R, W> { fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> { self.reader.read(buf).and_then(|len| { - self.writer.write(buf.index_mut(&(0..len))).map(|()| len) + self.writer.write(&mut buf[0..len]).map(|()| len) }) } } @@ -234,7 +234,7 @@ pub fn copy<R: Reader, W: Writer>(r: &mut R, w: &mut W) -> io::IoResult<()> { Err(ref e) if e.kind == io::EndOfFile => return Ok(()), Err(e) => return Err(e), }; - try!(w.write(buf.index(&(0..len)))); + try!(w.write(&buf[0..len])); } } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index eef5bdb60ee..dc157c7d676 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -96,6 +96,7 @@ #![crate_name = "std"] #![stable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -107,8 +108,9 @@ #![feature(linkage, thread_local, asm)] #![feature(lang_items, unsafe_destructor)] #![feature(slicing_syntax, unboxed_closures)] +#![feature(box_syntax)] #![feature(old_impl_check)] -#![cfg_attr(stage0, allow(unused_attributes))] +#![allow(unknown_features)] #![feature(int_uint)] // Don't link to std. We are std. #![no_std] @@ -120,8 +122,7 @@ extern crate log; #[macro_use] -#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq, - unreachable, unimplemented, write, writeln)] +#[macro_reexport(write, writeln)] extern crate core; #[macro_use] @@ -150,9 +151,9 @@ pub use core::clone; #[cfg(not(test))] pub use core::cmp; pub use core::default; pub use core::finally; +pub use core::hash; pub use core::intrinsics; pub use core::iter; -#[cfg(stage0)] #[cfg(not(test))] pub use core::marker as kinds; #[cfg(not(test))] pub use core::marker; pub use core::mem; #[cfg(not(test))] pub use core::ops; @@ -176,7 +177,7 @@ pub use unicode::char; /* Exported macros */ #[macro_use] -pub mod macros; +mod macros; #[macro_use] pub mod bitflags; @@ -203,12 +204,14 @@ mod int_macros; 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; #[path = "num/u32.rs"] pub mod u32; @@ -242,7 +245,6 @@ pub mod time; /* Common data structures */ pub mod collections; -pub mod hash; /* Threads and communication */ @@ -274,6 +276,7 @@ mod std { pub use clone; pub use cmp; pub use hash; + pub use default; pub use sync; // used for select!() pub use error; // used for try!() @@ -284,8 +287,6 @@ mod std { pub use vec; // used for vec![] pub use cell; // used for tls! pub use thread_local; // used for thread_local! - #[cfg(stage0)] - pub use marker as kinds; pub use marker; // used for tls! pub use ops; // used for bitflags! diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index befdc156094..626372db23b 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -14,7 +14,7 @@ //! library. Each macro is available for use when linking against the standard //! library. -#![experimental] +#![unstable] /// The entry point for panic of Rust tasks. /// @@ -36,23 +36,27 @@ /// panic!("this is a {} {message}", "fancy", message = "message"); /// ``` #[macro_export] +#[stable] macro_rules! panic { () => ({ panic!("explicit panic") }); ($msg:expr) => ({ - // static requires less code at runtime, more constant data - static _FILE_LINE: (&'static str, uint) = (file!(), line!()); - ::std::rt::begin_unwind($msg, &_FILE_LINE) + $crate::rt::begin_unwind($msg, { + // static requires less code at runtime, more constant data + static _FILE_LINE: (&'static str, usize) = (file!(), line!()); + &_FILE_LINE + }) }); - ($fmt:expr, $($arg:tt)*) => ({ - // The leading _'s are to avoid dead code warnings if this is - // used inside a dead function. Just `#[allow(dead_code)]` is - // insufficient, since the user may have - // `#[forbid(dead_code)]` and which cannot be overridden. - static _FILE_LINE: (&'static str, uint) = (file!(), line!()); - ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE) - + ($fmt:expr, $($arg:tt)+) => ({ + $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), { + // The leading _'s are to avoid dead code warnings if this is + // used inside a dead function. Just `#[allow(dead_code)]` is + // insufficient, since the user may have + // `#[forbid(dead_code)]` and which cannot be overridden. + static _FILE_LINE: (&'static str, usize) = (file!(), line!()); + &_FILE_LINE + }) }); } @@ -77,15 +81,16 @@ macro_rules! panic { /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] +#[stable] macro_rules! assert { ($cond:expr) => ( if !$cond { panic!(concat!("assertion failed: ", stringify!($cond))) } ); - ($cond:expr, $($arg:expr),+) => ( + ($cond:expr, $($arg:tt)+) => ( if !$cond { - panic!($($arg),+) + panic!($($arg)+) } ); } @@ -103,6 +108,7 @@ macro_rules! assert { /// assert_eq!(a, b); /// ``` #[macro_export] +#[stable] macro_rules! assert_eq { ($left:expr , $right:expr) => ({ match (&($left), &($right)) { @@ -144,6 +150,7 @@ macro_rules! assert_eq { /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] +#[stable] macro_rules! debug_assert { ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); }) } @@ -210,6 +217,7 @@ macro_rules! debug_assert_eq { /// } /// ``` #[macro_export] +#[unstable = "relationship with panic is unclear"] macro_rules! unreachable { () => ({ panic!("internal error: entered unreachable code") @@ -225,6 +233,7 @@ macro_rules! unreachable { /// A standardised placeholder for marking unfinished code. It panics with the /// message `"not yet implemented"` when executed. #[macro_export] +#[unstable = "relationship with panic is unclear"] macro_rules! unimplemented { () => (panic!("not yet implemented")) } @@ -242,7 +251,7 @@ macro_rules! unimplemented { #[macro_export] #[stable] macro_rules! format { - ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*))) + ($($arg:tt)*) => ($crate::fmt::format(format_args!($($arg)*))) } /// Equivalent to the `println!` macro except that a newline is not printed at @@ -250,7 +259,7 @@ macro_rules! format { #[macro_export] #[stable] macro_rules! print { - ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*))) + ($($arg:tt)*) => ($crate::io::stdio::print_args(format_args!($($arg)*))) } /// Macro for printing to a task's stdout handle. @@ -268,20 +277,19 @@ macro_rules! print { #[macro_export] #[stable] macro_rules! println { - ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*))) + ($($arg:tt)*) => ($crate::io::stdio::println_args(format_args!($($arg)*))) } /// Helper macro for unwrapping `Result` values while returning early with an /// error if the value of the expression is `Err`. For more information, see /// `std::io`. #[macro_export] +#[stable] macro_rules! try { - ($expr:expr) => ({ - use $crate::result::Result::{Ok, Err}; - - match $expr { - Ok(val) => val, - Err(err) => return Err($crate::error::FromError::from_error(err)), + ($expr:expr) => (match $expr { + $crate::result::Result::Ok(val) => val, + $crate::result::Result::Err(err) => { + return $crate::result::Result::Err($crate::error::FromError::from_error(err)) } }) } @@ -316,7 +324,7 @@ macro_rules! try { /// /// For more information about select, see the `std::sync::mpsc::Select` structure. #[macro_export] -#[experimental] +#[unstable] macro_rules! select { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ @@ -412,26 +420,6 @@ pub mod builtin { #[macro_export] macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) } - /// Concatenate literals into a static byte slice. - /// - /// This macro takes any number of comma-separated literal expressions, - /// yielding an expression of type `&'static [u8]` which is the - /// concatenation (left to right) of all the literals in their byte format. - /// - /// This extension currently only supports string literals, character - /// literals, and integers less than 256. The byte slice returned is the - /// utf8-encoding of strings and characters. - /// - /// # Example - /// - /// ``` - /// let rust = bytes!("r", 'u', "st", 255); - /// assert_eq!(rust[1], b'u'); - /// assert_eq!(rust[4], 255); - /// ``` - #[macro_export] - macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) } - /// Concatenate identifiers into one identifier. /// /// This macro takes any number of comma-separated identifiers, and @@ -478,7 +466,7 @@ pub mod builtin { /// A macro which expands to the line number on which it was invoked. /// - /// The expanded expression has type `uint`, and the returned line is not + /// The expanded expression has type `usize`, and the returned line is not /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. /// @@ -493,7 +481,7 @@ pub mod builtin { /// A macro which expands to the column number on which it was invoked. /// - /// The expanded expression has type `uint`, and the returned column is not + /// The expanded expression has type `usize`, and the returned column is not /// the invocation of the `column!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `column!()` macro. /// @@ -565,10 +553,6 @@ pub mod builtin { #[macro_export] macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) } - /// Deprecated alias for `include_bytes!()`. - #[macro_export] - macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) } - /// Expands to a string that represents the current module path. /// /// The current module path can be thought of as the hierarchy of modules diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index 0a1c17fab47..adbce893887 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -366,7 +366,7 @@ impl Float for f32 { /// /// * num - The float value #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_string(num: f32) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigAll, ExpNone, false); @@ -379,7 +379,7 @@ pub fn to_string(num: f32) -> String { /// /// * num - The float value #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_hex(num: f32) -> String { let (r, _) = strconv::float_to_str_common( num, 16u, true, SignNeg, DigAll, ExpNone, false); @@ -394,7 +394,7 @@ pub fn to_str_hex(num: f32) -> String { /// * num - The float value /// * radix - The base to use #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_radix_special(num: f32, rdx: uint) -> (String, bool) { strconv::float_to_str_common(num, rdx, true, SignNeg, DigAll, ExpNone, false) } @@ -407,7 +407,7 @@ pub fn to_str_radix_special(num: f32, rdx: uint) -> (String, bool) { /// * num - The float value /// * digits - The number of significant digits #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exact(num: f32, dig: uint) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigExact(dig), ExpNone, false); @@ -422,7 +422,7 @@ pub fn to_str_exact(num: f32, dig: uint) -> String { /// * num - The float value /// * digits - The number of significant digits #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_digits(num: f32, dig: uint) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigMax(dig), ExpNone, false); @@ -438,7 +438,7 @@ pub fn to_str_digits(num: f32, dig: uint) -> String { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigExact(dig), ExpDec, upper); @@ -454,7 +454,7 @@ pub fn to_str_exp_exact(num: f32, dig: uint, upper: bool) -> String { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigMax(dig), ExpDec, upper); diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index 2806154a016..baff14125ee 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -375,7 +375,7 @@ impl Float for f64 { /// /// * num - The float value #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_string(num: f64) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigAll, ExpNone, false); @@ -388,7 +388,7 @@ pub fn to_string(num: f64) -> String { /// /// * num - The float value #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_hex(num: f64) -> String { let (r, _) = strconv::float_to_str_common( num, 16u, true, SignNeg, DigAll, ExpNone, false); @@ -403,7 +403,7 @@ pub fn to_str_hex(num: f64) -> String { /// * num - The float value /// * radix - The base to use #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_radix_special(num: f64, rdx: uint) -> (String, bool) { strconv::float_to_str_common(num, rdx, true, SignNeg, DigAll, ExpNone, false) } @@ -416,7 +416,7 @@ pub fn to_str_radix_special(num: f64, rdx: uint) -> (String, bool) { /// * num - The float value /// * digits - The number of significant digits #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exact(num: f64, dig: uint) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigExact(dig), ExpNone, false); @@ -431,7 +431,7 @@ pub fn to_str_exact(num: f64, dig: uint) -> String { /// * num - The float value /// * digits - The number of significant digits #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_digits(num: f64, dig: uint) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigMax(dig), ExpNone, false); @@ -447,7 +447,7 @@ pub fn to_str_digits(num: f64, dig: uint) -> String { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigExact(dig), ExpDec, upper); @@ -463,7 +463,7 @@ pub fn to_str_exp_exact(num: f64, dig: uint, upper: bool) -> String { /// * digits - The number of digits after the decimal point /// * upper - Use `E` instead of `e` for the exponent sign #[inline] -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> String { let (r, _) = strconv::float_to_str_common( num, 10u, true, SignNeg, DigMax(dig), ExpDec, upper); diff --git a/src/libstd/num/float_macros.rs b/src/libstd/num/float_macros.rs index 4c52f29b12d..ec168eaaa9d 100644 --- a/src/libstd/num/float_macros.rs +++ b/src/libstd/num/float_macros.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![experimental] +#![unstable] #![doc(hidden)] macro_rules! assert_approx_eq { diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs index 9ccb1544fdc..69439f85115 100644 --- a/src/libstd/num/int.rs +++ b/src/libstd/num/int.rs @@ -8,10 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Operations and constants for architecture-sized signed integers (`int` type) +//! 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. -#![stable] -#![doc(primitive = "int")] +#![deprecated = "replaced by isize"] pub use core::int::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index ebcb2086187..5bc54152874 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![experimental] +#![unstable] #![doc(hidden)] macro_rules! int_module { ($T:ty) => ( diff --git a/src/libstd/num/isize.rs b/src/libstd/num/isize.rs new file mode 100644 index 00000000000..22395a1c0ff --- /dev/null +++ b/src/libstd/num/isize.rs @@ -0,0 +1,22 @@ +// 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. +// +// 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. + +//! Operations and constants for pointer-sized signed integers (`isize` type) +//! +//! This type was recently added to replace `int`. The rollout of the +//! new type will gradually take place over the alpha cycle along with +//! the development of clearer conventions around integer types. + +#![stable] +#![doc(primitive = "isize")] + +pub use core::isize::{BITS, BYTES, MIN, MAX}; + +int_module! { isize } diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index f433cd1e664..e804408b4d0 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -33,7 +33,7 @@ pub use core::num::{FpCategory}; use option::Option; -#[experimental = "may be removed or relocated"] +#[unstable = "may be removed or relocated"] pub mod strconv; /// Mathematical operations on primitive floating point numbers. @@ -424,12 +424,14 @@ mod tests { assert_eq!(int::MIN.to_u32(), None); assert_eq!(int::MIN.to_u64(), None); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(int::MIN.to_i32(), Some(int::MIN as i32)); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(int::MIN.to_i32(), None); } @@ -492,12 +494,14 @@ mod tests { assert_eq!(i64::MIN.to_u32(), None); assert_eq!(i64::MIN.to_u64(), None); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(i64::MIN.to_int(), None); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(i64::MIN.to_int(), Some(i64::MIN as int)); } @@ -517,13 +521,15 @@ mod tests { // int::MAX.to_u32() is word-size specific assert_eq!(int::MAX.to_u64(), Some(int::MAX as u64)); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(int::MAX.to_i32(), Some(int::MAX as i32)); assert_eq!(int::MAX.to_u32(), Some(int::MAX as u32)); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(int::MAX.to_i32(), None); assert_eq!(int::MAX.to_u32(), None); @@ -587,13 +593,15 @@ mod tests { assert_eq!(i64::MAX.to_u32(), None); assert_eq!(i64::MAX.to_u64(), Some(i64::MAX as u64)); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(i64::MAX.to_int(), None); assert_eq!(i64::MAX.to_uint(), None); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(i64::MAX.to_int(), Some(i64::MAX as int)); assert_eq!(i64::MAX.to_uint(), Some(i64::MAX as uint)); @@ -684,13 +692,15 @@ mod tests { // uint::MAX.to_u32() is word-size specific assert_eq!(uint::MAX.to_u64(), Some(uint::MAX as u64)); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(uint::MAX.to_u32(), Some(uint::MAX as u32)); assert_eq!(uint::MAX.to_i64(), Some(uint::MAX as i64)); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(uint::MAX.to_u32(), None); assert_eq!(uint::MAX.to_i64(), None); @@ -740,12 +750,14 @@ mod tests { assert_eq!(u32::MAX.to_u32(), Some(u32::MAX as u32)); assert_eq!(u32::MAX.to_u64(), Some(u32::MAX as u64)); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(u32::MAX.to_int(), None); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(u32::MAX.to_int(), Some(u32::MAX as int)); } @@ -766,12 +778,14 @@ mod tests { assert_eq!(u64::MAX.to_u32(), None); assert_eq!(u64::MAX.to_u64(), Some(u64::MAX as u64)); - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] fn check_word_size() { assert_eq!(u64::MAX.to_uint(), None); } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] fn check_word_size() { assert_eq!(u64::MAX.to_uint(), Some(u64::MAX as uint)); } diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs index 0fbc0953b20..0e12eff205f 100644 --- a/src/libstd/num/uint.rs +++ b/src/libstd/num/uint.rs @@ -8,10 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Operations and constants for architecture-sized unsigned integers (`uint` type) +//! 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. -#![stable] -#![doc(primitive = "uint")] +#![deprecated = "replaced by usize"] pub use core::uint::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index 4ce15491a0e..f480a3b420f 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![experimental] +#![unstable] #![doc(hidden)] #![allow(unsigned_negation)] diff --git a/src/libstd/num/usize.rs b/src/libstd/num/usize.rs new file mode 100644 index 00000000000..74dd38e13c5 --- /dev/null +++ b/src/libstd/num/usize.rs @@ -0,0 +1,22 @@ +// 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. +// +// 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. + +//! Operations and constants for pointer-sized unsigned integers (`usize` type) +//! +//! This type was recently added to replace `uint`. The rollout of the +//! new type will gradually take place over the alpha cycle along with +//! the development of clearer conventions around integer types. + +#![stable] +#![doc(primitive = "usize")] + +pub use core::usize::{BITS, BYTES, MIN, MAX}; + +uint_module! { usize } diff --git a/src/libstd/os.rs b/src/libstd/os.rs index cef85c260a7..6e3949b9e22 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -22,7 +22,7 @@ //! so we will not _hide_ the facts of which OS the user is on -- they should be given the //! opportunity to write OS-ignorant code by default. -#![experimental] +#![unstable] #![allow(missing_docs)] #![allow(non_snake_case)] diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 581969e98fb..1ec7b6b3edc 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -59,7 +59,7 @@ //! println!("path exists: {}", path.exists()); //! ``` -#![experimental] +#![unstable] use core::marker::Sized; use ffi::CString; @@ -68,7 +68,7 @@ use fmt; use iter::IteratorExt; use option::Option; use option::Option::{None, Some}; -use ops::{FullRange, Index}; +use ops::FullRange; use str; use str::StrExt; use string::{String, CowString}; @@ -352,7 +352,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { match name.rposition_elem(&dot) { None | Some(0) => name, Some(1) if name == b".." => name, - Some(pos) => name.index(&(0..pos)) + Some(pos) => &name[0..pos] } }) } @@ -399,7 +399,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { match name.rposition_elem(&dot) { None | Some(0) => None, Some(1) if name == b".." => None, - Some(pos) => Some(name.index(&((pos+1)..))) + Some(pos) => Some(&name[(pos+1)..]) } } } @@ -475,7 +475,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { let extlen = extension.container_as_bytes().len(); match (name.rposition_elem(&dot), extlen) { (None, 0) | (Some(0), 0) => None, - (Some(idx), 0) => Some(name.index(&(0..idx)).to_vec()), + (Some(idx), 0) => Some(name[0..idx].to_vec()), (idx, extlen) => { let idx = match idx { None | Some(0) => name.len(), @@ -484,7 +484,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { let mut v; v = Vec::with_capacity(idx + extlen + 1); - v.push_all(name.index(&(0..idx))); + v.push_all(&name[0..idx]); v.push(dot); v.push_all(extension.container_as_bytes()); Some(v) @@ -823,7 +823,6 @@ pub struct Display<'a, P:'a> { filename: bool } -//NOTE(stage0): replace with deriving(Show) after snapshot impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, f) @@ -877,7 +876,7 @@ impl BytesContainer for String { } #[inline] fn container_as_str(&self) -> Option<&str> { - Some(self.index(&FullRange)) + Some(&self[]) } #[inline] fn is_str(_: Option<&String>) -> bool { true } @@ -893,7 +892,7 @@ impl BytesContainer for [u8] { impl BytesContainer for Vec<u8> { #[inline] fn container_as_bytes(&self) -> &[u8] { - self.index(&FullRange) + &self[] } } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 0b7dc19fcab..293696d5cca 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -17,7 +17,6 @@ use hash; use io::Writer; use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map}; -use ops::Index; use marker::Sized; use option::Option::{self, Some, None}; use slice::{AsSlice, Split, SliceExt, SliceConcatExt}; @@ -60,7 +59,7 @@ pub fn is_sep(c: char) -> bool { impl fmt::Show for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Path {{ {} }}", self.display()) + fmt::Show::fmt(&self.display(), f) } } @@ -91,7 +90,7 @@ impl FromStr for Path { } } -impl<S: hash::Writer> hash::Hash<S> for Path { +impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Path { #[inline] fn hash(&self, state: &mut S) { self.repr.hash(state) @@ -127,7 +126,7 @@ impl GenericPathUnsafe for Path { None => { self.repr = Path::normalize(filename); } - Some(idx) if self.repr.index(&((idx+1)..)) == b".." => { + Some(idx) if &self.repr[(idx+1)..] == b".." => { let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len()); v.push_all(self.repr.as_slice()); v.push(SEP_BYTE); @@ -137,7 +136,7 @@ impl GenericPathUnsafe for Path { } Some(idx) => { let mut v = Vec::with_capacity(idx + 1 + filename.len()); - v.push_all(self.repr.index(&(0..(idx+1)))); + v.push_all(&self.repr[0..(idx+1)]); v.push_all(filename); // FIXME: this is slow self.repr = Path::normalize(v.as_slice()); @@ -178,9 +177,9 @@ impl GenericPath for Path { match self.sepidx { None if b".." == self.repr => self.repr.as_slice(), None => dot_static, - Some(0) => self.repr.index(&(0..1)), - Some(idx) if self.repr.index(&((idx+1)..)) == b".." => self.repr.as_slice(), - Some(idx) => self.repr.index(&(0..idx)) + Some(0) => &self.repr[0..1], + Some(idx) if &self.repr[(idx+1)..] == b".." => self.repr.as_slice(), + Some(idx) => &self.repr[0..idx] } } @@ -189,9 +188,9 @@ impl GenericPath for Path { None if b"." == self.repr || b".." == self.repr => None, None => Some(self.repr.as_slice()), - Some(idx) if self.repr.index(&((idx+1)..)) == b".." => None, - Some(0) if self.repr.index(&(1..)).is_empty() => None, - Some(idx) => Some(self.repr.index(&((idx+1)..))) + Some(idx) if &self.repr[(idx+1)..] == b".." => None, + Some(0) if self.repr[1..].is_empty() => None, + Some(idx) => Some(&self.repr[(idx+1)..]) } } @@ -333,7 +332,7 @@ impl Path { // borrowck is being very picky let val = { let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE; - let v_ = if is_abs { v.as_slice().index(&(1..)) } else { v.as_slice() }; + let v_ = if is_abs { &v.as_slice()[1..] } else { v.as_slice() }; let comps = normalize_helper(v_, is_abs); match comps { None => None, @@ -372,7 +371,7 @@ impl Path { /// A path of "/" yields no components. A path of "." yields one component. pub fn components<'a>(&'a self) -> Components<'a> { let v = if self.repr[0] == SEP_BYTE { - self.repr.index(&(1..)) + &self.repr[1..] } else { self.repr.as_slice() }; let is_sep_byte: fn(&u8) -> bool = is_sep_byte; // coerce to fn ptr let mut ret = v.split(is_sep_byte); diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 5c4e7aa9ac2..2a1f1794e49 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -25,7 +25,7 @@ use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map, repeat}; use mem; use option::Option::{self, Some, None}; -use ops::{FullRange, Index}; +use ops::FullRange; use slice::{SliceExt, SliceConcatExt}; use str::{SplitTerminator, FromStr, StrExt}; use string::{String, ToString}; @@ -87,7 +87,7 @@ pub struct Path { impl fmt::Show for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Path {{ {} }}", self.display()) + fmt::Show::fmt(&self.display(), f) } } @@ -118,7 +118,7 @@ impl FromStr for Path { } } -impl<S: hash::Writer> hash::Hash<S> for Path { +impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Path { #[cfg(not(test))] #[inline] fn hash(&self, state: &mut S) { @@ -173,30 +173,30 @@ impl GenericPathUnsafe for Path { s.push_str(".."); s.push(SEP); s.push_str(filename); - self.update_normalized(s.index(&FullRange)); + self.update_normalized(&s[]); } None => { self.update_normalized(filename); } - Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => { + Some((_,idxa,end)) if &self.repr[idxa..end] == ".." => { let mut s = String::with_capacity(end + 1 + filename.len()); - s.push_str(self.repr.index(&(0..end))); + s.push_str(&self.repr[0..end]); s.push(SEP); s.push_str(filename); - self.update_normalized(s.index(&FullRange)); + self.update_normalized(&s[]); } Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => { let mut s = String::with_capacity(idxb + filename.len()); - s.push_str(self.repr.index(&(0..idxb))); + s.push_str(&self.repr[0..idxb]); s.push_str(filename); - self.update_normalized(s.index(&FullRange)); + self.update_normalized(&s[]); } Some((idxb,_,_)) => { let mut s = String::with_capacity(idxb + 1 + filename.len()); - s.push_str(self.repr.index(&(0..idxb))); + s.push_str(&self.repr[0..idxb]); s.push(SEP); s.push_str(filename); - self.update_normalized(s.index(&FullRange)); + self.update_normalized(&s[]); } } } @@ -215,12 +215,12 @@ impl GenericPathUnsafe for Path { let path = path.container_as_str().unwrap(); fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool { // assume prefix is Some(DiskPrefix) - let rest = path.index(&(prefix_len(prefix)..)); + let rest = &path[prefix_len(prefix)..]; !rest.is_empty() && rest.as_bytes()[0].is_ascii() && is_sep(rest.as_bytes()[0] as char) } fn shares_volume(me: &Path, path: &str) -> bool { // path is assumed to have a prefix of Some(DiskPrefix) - let repr = me.repr.index(&FullRange); + let repr = &me.repr[]; match me.prefix { Some(DiskPrefix) => { repr.as_bytes()[0] == path.as_bytes()[0].to_ascii_uppercase() @@ -252,7 +252,7 @@ impl GenericPathUnsafe for Path { else { None }; let pathlen = path_.as_ref().map_or(path.len(), |p| p.len()); let mut s = String::with_capacity(me.repr.len() + 1 + pathlen); - s.push_str(me.repr.index(&FullRange)); + s.push_str(&me.repr[]); let plen = me.prefix_len(); // if me is "C:" we don't want to add a path separator match me.prefix { @@ -264,9 +264,9 @@ impl GenericPathUnsafe for Path { } match path_ { None => s.push_str(path), - Some(p) => s.push_str(p.index(&FullRange)), + Some(p) => s.push_str(&p[]), }; - me.update_normalized(s.index(&FullRange)) + me.update_normalized(&s[]) } if !path.is_empty() { @@ -274,7 +274,7 @@ impl GenericPathUnsafe for Path { match prefix { Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => { // cwd-relative path, self is on the same volume - append_path(self, path.index(&(prefix_len(prefix)..))); + append_path(self, &path[prefix_len(prefix)..]); } Some(_) => { // absolute path, or cwd-relative and self is not same volume @@ -320,7 +320,7 @@ impl GenericPath for Path { /// Always returns a `Some` value. #[inline] fn as_str<'a>(&'a self) -> Option<&'a str> { - Some(self.repr.index(&FullRange)) + Some(&self.repr[]) } #[inline] @@ -342,21 +342,21 @@ impl GenericPath for Path { /// Always returns a `Some` value. fn dirname_str<'a>(&'a self) -> Option<&'a str> { Some(match self.sepidx_or_prefix_len() { - None if ".." == self.repr => self.repr.index(&FullRange), + None if ".." == self.repr => &self.repr[], None => ".", - Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => { - self.repr.index(&FullRange) + Some((_,idxa,end)) if &self.repr[idxa..end] == ".." => { + &self.repr[] } - Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => { - self.repr.index(&FullRange) + Some((idxb,_,end)) if &self.repr[idxb..end] == "\\" => { + &self.repr[] } - Some((0,idxa,_)) => self.repr.index(&(0..idxa)), + Some((0,idxa,_)) => &self.repr[0..idxa], Some((idxb,idxa,_)) => { match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => { - self.repr.index(&(0..idxa)) + &self.repr[0..idxa] } - _ => self.repr.index(&(0..idxb)) + _ => &self.repr[0..idxb] } } }) @@ -370,13 +370,13 @@ impl GenericPath for Path { /// See `GenericPath::filename_str` for info. /// Always returns a `Some` value if `filename` returns a `Some` value. fn filename_str<'a>(&'a self) -> Option<&'a str> { - let repr = self.repr.index(&FullRange); + let repr = &self.repr[]; match self.sepidx_or_prefix_len() { None if "." == repr || ".." == repr => None, None => Some(repr), - Some((_,idxa,end)) if repr.index(&(idxa..end)) == ".." => None, + Some((_,idxa,end)) if &repr[idxa..end] == ".." => None, Some((_,idxa,end)) if idxa == end => None, - Some((_,idxa,end)) => Some(repr.index(&(idxa..end))) + Some((_,idxa,end)) => Some(&repr[idxa..end]) } } @@ -408,7 +408,7 @@ impl GenericPath for Path { true } Some((idxb,idxa,end)) if idxb == idxa && idxb == end => false, - Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => false, + Some((idxb,_,end)) if &self.repr[idxb..end] == "\\" => false, Some((idxb,idxa,_)) => { let trunc = match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => { @@ -428,15 +428,15 @@ impl GenericPath for Path { if self.prefix.is_some() { Some(Path::new(match self.prefix { Some(DiskPrefix) if self.is_absolute() => { - self.repr.index(&(0..(self.prefix_len()+1))) + &self.repr[0..(self.prefix_len()+1)] } Some(VerbatimDiskPrefix) => { - self.repr.index(&(0..(self.prefix_len()+1))) + &self.repr[0..(self.prefix_len()+1)] } - _ => self.repr.index(&(0..self.prefix_len())) + _ => &self.repr[0..self.prefix_len()] })) } else if is_vol_relative(self) { - Some(Path::new(self.repr.index(&(0..1)))) + Some(Path::new(&self.repr[0..1])) } else { None } @@ -455,7 +455,7 @@ impl GenericPath for Path { fn is_absolute(&self) -> bool { match self.prefix { Some(DiskPrefix) => { - let rest = self.repr.index(&(self.prefix_len()..)); + let rest = &self.repr[self.prefix_len()..]; rest.len() > 0 && rest.as_bytes()[0] == SEP_BYTE } Some(_) => true, @@ -630,15 +630,15 @@ impl Path { /// Does not distinguish between absolute and cwd-relative paths, e.g. /// C:\foo and C:foo. pub fn str_components<'a>(&'a self) -> StrComponents<'a> { - let repr = self.repr.index(&FullRange); + let repr = &self.repr[]; let s = match self.prefix { Some(_) => { let plen = self.prefix_len(); if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE { - repr.index(&((plen+1)..)) - } else { repr.index(&(plen..)) } + &repr[(plen+1)..] + } else { &repr[plen..] } } - None if repr.as_bytes()[0] == SEP_BYTE => repr.index(&(1..)), + None if repr.as_bytes()[0] == SEP_BYTE => &repr[1..], None => repr }; let some: fn(&'a str) -> Option<&'a str> = Some; // coerce to fn ptr @@ -658,8 +658,8 @@ impl Path { } fn equiv_prefix(&self, other: &Path) -> bool { - let s_repr = self.repr.index(&FullRange); - let o_repr = other.repr.index(&FullRange); + let s_repr = &self.repr[]; + let o_repr = &other.repr[]; match (self.prefix, other.prefix) { (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => { self.is_absolute() && @@ -676,14 +676,14 @@ impl Path { o_repr.as_bytes()[4].to_ascii_lowercase() } (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => { - s_repr.index(&(2..self.prefix_len())) == o_repr.index(&(8..other.prefix_len())) + &s_repr[2..self.prefix_len()] == &o_repr[8..other.prefix_len()] } (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => { - s_repr.index(&(8..self.prefix_len())) == o_repr.index(&(2..other.prefix_len())) + &s_repr[8..self.prefix_len()] == &o_repr[2..other.prefix_len()] } (None, None) => true, (a, b) if a == b => { - s_repr.index(&(0..self.prefix_len())) == o_repr.index(&(0..other.prefix_len())) + &s_repr[0..self.prefix_len()] == &o_repr[0..other.prefix_len()] } _ => false } @@ -737,7 +737,7 @@ impl Path { match prefix.unwrap() { DiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; - let mut s = String::from_str(s.index(&(0..len))); + let mut s = String::from_str(&s[0..len]); unsafe { let v = s.as_mut_vec(); v[0] = (*v)[0].to_ascii_uppercase(); @@ -752,7 +752,7 @@ impl Path { } VerbatimDiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; - let mut s = String::from_str(s.index(&(0..len))); + let mut s = String::from_str(&s[0..len]); unsafe { let v = s.as_mut_vec(); v[4] = (*v)[4].to_ascii_uppercase(); @@ -762,14 +762,14 @@ impl Path { _ => { let plen = prefix_len(prefix); if s.len() > plen { - Some(String::from_str(s.index(&(0..plen)))) + Some(String::from_str(&s[0..plen])) } else { None } } } } else if is_abs && comps.is_empty() { Some(repeat(SEP).take(1).collect()) } else { - let prefix_ = s.index(&(0..prefix_len(prefix))); + let prefix_ = &s[0..prefix_len(prefix)]; let n = prefix_.len() + if is_abs { comps.len() } else { comps.len() - 1} + comps.iter().map(|v| v.len()).sum(); @@ -780,15 +780,15 @@ impl Path { s.push(':'); } Some(VerbatimDiskPrefix) => { - s.push_str(prefix_.index(&(0..4))); + s.push_str(&prefix_[0..4]); s.push(prefix_.as_bytes()[4].to_ascii_uppercase() as char); - s.push_str(prefix_.index(&(5..))); + s.push_str(&prefix_[5..]); } Some(UNCPrefix(a,b)) => { s.push_str("\\\\"); - s.push_str(prefix_.index(&(2..(a+2)))); + s.push_str(&prefix_[2..(a+2)]); s.push(SEP); - s.push_str(prefix_.index(&((3+a)..(3+a+b)))); + s.push_str(&prefix_[(3+a)..(3+a+b)]); } Some(_) => s.push_str(prefix_), None => () @@ -813,8 +813,8 @@ impl Path { fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { - self.repr.index(&(0..(self.repr.len()-1))) - } else { self.repr.index(&FullRange) }; + &self.repr[0..(self.repr.len()-1)] + } else { &self.repr[] }; let sep_test: fn(char) -> bool = if !prefix_is_verbatim(self.prefix) { is_sep } else { @@ -893,17 +893,17 @@ pub fn is_verbatim(path: &Path) -> bool { /// non-verbatim, the non-verbatim version is returned. /// Otherwise, None is returned. pub fn make_non_verbatim(path: &Path) -> Option<Path> { - let repr = path.repr.index(&FullRange); + let repr = &path.repr[]; let new_path = match path.prefix { Some(VerbatimPrefix(_)) | Some(DeviceNSPrefix(_)) => return None, Some(UNCPrefix(_,_)) | Some(DiskPrefix) | None => return Some(path.clone()), Some(VerbatimDiskPrefix) => { // \\?\D:\ - Path::new(repr.index(&(4..))) + Path::new(&repr[4..]) } Some(VerbatimUNCPrefix(_,_)) => { // \\?\UNC\server\share - Path::new(format!(r"\{}", repr.index(&(7..)))) + Path::new(format!(r"\{}", &repr[7..])) } }; if new_path.prefix.is_none() { @@ -912,8 +912,7 @@ pub fn make_non_verbatim(path: &Path) -> Option<Path> { return None; } // now ensure normalization didn't change anything - if repr.index(&(path.prefix_len()..)) == - new_path.repr.index(&(new_path.prefix_len()..)) { + if &repr[path.prefix_len()..] == &new_path.repr[new_path.prefix_len()..] { Some(new_path) } else { None @@ -978,13 +977,13 @@ pub enum PathPrefix { fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { if path.starts_with("\\\\") { // \\ - path = path.index(&(2..)); + path = &path[2..]; if path.starts_with("?\\") { // \\?\ - path = path.index(&(2..)); + path = &path[2..]; if path.starts_with("UNC\\") { // \\?\UNC\server\share - path = path.index(&(4..)); + path = &path[4..]; let (idx_a, idx_b) = match parse_two_comps(path, is_sep_verbatim) { Some(x) => x, None => (path.len(), 0) @@ -1005,7 +1004,7 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { } } else if path.starts_with(".\\") { // \\.\path - path = path.index(&(2..)); + path = &path[2..]; let idx = path.find('\\').unwrap_or(path.len()); return Some(DeviceNSPrefix(idx)); } @@ -1030,7 +1029,7 @@ fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { None => return None, Some(x) => x }; - path = path.index(&((idx_a+1)..)); + path = &path[(idx_a+1)..]; let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } @@ -1044,8 +1043,8 @@ fn normalize_helper<'a>(s: &'a str, prefix: Option<PathPrefix>) -> (bool, Option is_sep_verbatim }; let is_abs = s.len() > prefix_len(prefix) && f(s.char_at(prefix_len(prefix))); - let s_ = s.index(&(prefix_len(prefix)..)); - let s_ = if is_abs { s_.index(&(1..)) } else { s_ }; + let s_ = &s[prefix_len(prefix)..]; + let s_ = if is_abs { &s_[1..] } else { s_ }; if is_abs && s_.is_empty() { return (is_abs, match prefix { diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index dcb342b9ca2..d9c942c0185 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -17,7 +17,7 @@ #[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; // TEMPORARY -#[unstable] #[doc(no_inline)] pub use ops::{Index, IndexMut, FullRange}; +#[unstable] #[doc(no_inline)] pub use ops::FullRange; // Reexported functions #[stable] #[doc(no_inline)] pub use mem::drop; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index d3e6cd166ec..60d490982db 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -219,7 +219,7 @@ //! } //! ``` -#![experimental] +#![unstable] use cell::RefCell; use clone::Clone; @@ -230,9 +230,9 @@ use rc::Rc; use result::Result::{Ok, Err}; use vec::Vec; -#[cfg(not(target_word_size="64"))] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] use core_rand::IsaacRng as IsaacWordRng; -#[cfg(target_word_size="64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] use core_rand::Isaac64Rng as IsaacWordRng; pub use core_rand::{Rand, Rng, SeedableRng, Open01, Closed01}; @@ -403,7 +403,7 @@ pub fn random<T: Rand>() -> T { /// /// let mut rng = thread_rng(); /// let sample = sample(&mut rng, range(1i, 100), 5); -/// println!("{}", sample); +/// println!("{:?}", sample); /// ``` pub fn sample<T, I: Iterator<Item=T>, R: Rng>(rng: &mut R, mut iter: I, diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index 5ef55f5b487..e3e4e132b81 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -16,7 +16,7 @@ //! and should be considered as private implementation details for the //! time being. -#![experimental] +#![unstable] // FIXME: this should not be here. #![allow(missing_docs)] diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index fd84f220942..4cd0b29688a 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -544,7 +544,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> // MAX_CALLBACKS, so we're sure to clamp it as necessary. let callbacks = { let amt = CALLBACK_CNT.load(Ordering::SeqCst); - CALLBACKS.index(&(0..cmp::min(amt, MAX_CALLBACKS))) + &CALLBACKS[0..cmp::min(amt, MAX_CALLBACKS)] }; for cb in callbacks.iter() { match cb.load(Ordering::SeqCst) { @@ -582,7 +582,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> /// Only a limited number of callbacks can be registered, and this function /// returns whether the callback was successfully registered or not. It is not /// currently possible to unregister a callback once it has been registered. -#[experimental] +#[unstable] pub unsafe fn register(f: Callback) -> bool { match CALLBACK_CNT.fetch_add(1, Ordering::SeqCst) { // The invocation code has knowledge of this window where the count has diff --git a/src/libstd/rt/util.rs b/src/libstd/rt/util.rs index 59f654a95ca..c076f0a7c6c 100644 --- a/src/libstd/rt/util.rs +++ b/src/libstd/rt/util.rs @@ -131,7 +131,7 @@ pub fn abort(args: fmt::Arguments) -> ! { impl<'a> fmt::Writer for BufWriter<'a> { fn write_str(&mut self, bytes: &str) -> fmt::Result { let left = self.buf.slice_from_mut(self.pos); - let to_write = bytes.as_bytes().index(&(0..cmp::min(bytes.len(), left.len()))); + let to_write = &bytes.as_bytes()[0..cmp::min(bytes.len(), left.len())]; slice::bytes::copy_memory(left, to_write); self.pos += to_write.len(); Ok(()) @@ -142,7 +142,7 @@ pub fn abort(args: fmt::Arguments) -> ! { let mut msg = [0u8; 512]; let mut w = BufWriter { buf: &mut msg, pos: 0 }; let _ = write!(&mut w, "{}", args); - let msg = str::from_utf8(w.buf.index_mut(&(0..w.pos))).unwrap_or("aborted"); + let msg = str::from_utf8(&w.buf[0..w.pos]).unwrap_or("aborted"); let msg = if msg.is_empty() {"aborted"} else {msg}; // Give some context to the message diff --git a/src/libstd/rtdeps.rs b/src/libstd/rtdeps.rs index 862808a9e3d..f4fbd378899 100644 --- a/src/libstd/rtdeps.rs +++ b/src/libstd/rtdeps.rs @@ -12,7 +12,7 @@ //! the standard library This varies per-platform, but these libraries are //! necessary for running libstd. -#![experimental] +#![unstable] // All platforms need to link to rustrt #[cfg(not(test))] diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index f8eae1322bf..83de98fdbff 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -35,7 +35,7 @@ //! method, and see the method for more information about it. Due to this //! caveat, this queue may not be appropriate for all use-cases. -#![experimental] +#![unstable] // http://www.1024cores.net/home/lock-free-algorithms // /queues/non-intrusive-mpsc-node-based-queue diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index b7bb22b3ef3..0da458a51f1 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -46,7 +46,7 @@ //! ``` #![allow(dead_code)] -#![experimental = "This implementation, while likely sufficient, is unsafe and \ +#![unstable = "This implementation, while likely sufficient, is unsafe and \ likely to be error prone. At some point in the future this \ module will likely be replaced, and it is currently \ unknown how much API breakage that will cause. The ability \ diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index e8d6e380be5..46c69f6f547 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -33,7 +33,7 @@ //! concurrently between two tasks. This data structure is safe to use and //! enforces the semantics that there is one pusher and one popper. -#![experimental] +#![unstable] use core::prelude::*; diff --git a/src/libstd/sync/mpsc/stream.rs b/src/libstd/sync/mpsc/stream.rs index bd1e74a3390..f4b20c7b742 100644 --- a/src/libstd/sync/mpsc/stream.rs +++ b/src/libstd/sync/mpsc/stream.rs @@ -338,7 +338,7 @@ impl<T: Send> Packet<T> { // upgrade pending, then go through the whole recv rigamarole to update // the internal state. match self.queue.peek() { - Some(&GoUp(..)) => { + Some(&mut GoUp(..)) => { match self.recv() { Err(Upgraded(port)) => Err(port), _ => unreachable!(), @@ -367,7 +367,7 @@ impl<T: Send> Packet<T> { Ok(()) => SelSuccess, Err(token) => { let ret = match self.queue.peek() { - Some(&GoUp(..)) => { + Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => SelUpgraded(token, port), _ => unreachable!(), @@ -457,7 +457,7 @@ impl<T: Send> Packet<T> { // upgraded port. if has_data { match self.queue.peek() { - Some(&GoUp(..)) => { + Some(&mut GoUp(..)) => { match self.queue.pop() { Some(GoUp(port)) => Err(port), _ => unreachable!(), diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index be44aa99f49..f6161ec193d 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -12,8 +12,11 @@ use prelude::v1::*; use io::IoResult; -#[cfg(target_word_size = "64")] pub const HEX_WIDTH: uint = 18; -#[cfg(target_word_size = "32")] pub const HEX_WIDTH: uint = 10; +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] +pub const HEX_WIDTH: uint = 18; + +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] +pub const HEX_WIDTH: uint = 10; // All rust symbols are in theory lists of "::"-separated identifiers. Some // assemblers, however, can't handle these characters in symbol names. To get diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 902942d7244..4cf891ac498 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -469,7 +469,7 @@ pub fn write<T, L, W>(fd: sock_t, // Also as with read(), we use MSG_DONTWAIT to guard ourselves // against unforeseen circumstances. let _guard = lock(); - let ptr = buf.index(&(written..)).as_ptr(); + let ptr = buf[written..].as_ptr(); let len = buf.len() - written; match retry(|| write(deadline.is_some(), ptr, len)) { -1 if wouldblock() => {} diff --git a/src/libstd/sys/unix/c.rs b/src/libstd/sys/unix/c.rs index cc661877bc0..1d523ed6edd 100644 --- a/src/libstd/sys/unix/c.rs +++ b/src/libstd/sys/unix/c.rs @@ -169,13 +169,13 @@ mod signal { unsafe impl ::marker::Sync for sigaction { } #[repr(C)] - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] pub struct sigset_t { __val: [libc::c_ulong; 32], } #[repr(C)] - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] pub struct sigset_t { __val: [libc::c_ulong; 16], } diff --git a/src/libstd/sys/unix/ext.rs b/src/libstd/sys/unix/ext.rs index ae3c939bf78..0e4a9d1b307 100644 --- a/src/libstd/sys/unix/ext.rs +++ b/src/libstd/sys/unix/ext.rs @@ -29,7 +29,7 @@ //! } //! ``` -#![experimental] +#![unstable] use sys_common::AsInner; use libc; diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 1357bbdd5a3..36bf696dba5 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -11,7 +11,8 @@ use prelude::v1::*; use self::Req::*; -use collections; +use collections::HashMap; +use collections::hash_map::Hasher; use ffi::CString; use hash::Hash; use io::process::{ProcessExit, ExitStatus, ExitSignal}; @@ -60,7 +61,7 @@ impl Process { out_fd: Option<P>, err_fd: Option<P>) -> IoResult<Process> where C: ProcessConfig<K, V>, P: AsInner<FileDesc>, - K: BytesContainer + Eq + Hash, V: BytesContainer + K: BytesContainer + Eq + Hash<Hasher>, V: BytesContainer { use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp}; use libc::funcs::bsd44::getdtablesize; @@ -553,11 +554,11 @@ fn with_argv<T,F>(prog: &CString, args: &[CString], cb(ptrs.as_ptr()) } -fn with_envp<K,V,T,F>(env: Option<&collections::HashMap<K, V>>, +fn with_envp<K,V,T,F>(env: Option<&HashMap<K, V>>, cb: F) -> T where F : FnOnce(*const c_void) -> T, - K : BytesContainer + Eq + Hash, + K : BytesContainer + Eq + Hash<Hasher>, V : BytesContainer { // On posixy systems we can pass a char** for envp, which is a diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index 1fd619a28db..48a51813ba4 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -182,12 +182,14 @@ mod imp { sa_restorer: *mut libc::c_void, } - #[cfg(target_word_size = "32")] + #[cfg(any(all(stage0, target_word_size = "32"), + all(not(stage0), target_pointer_width = "32")))] #[repr(C)] pub struct sigset_t { __val: [libc::c_ulong; 32], } - #[cfg(target_word_size = "64")] + #[cfg(any(all(stage0, target_word_size = "64"), + all(not(stage0), target_pointer_width = "64")))] #[repr(C)] pub struct sigset_t { __val: [libc::c_ulong; 16], diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index eb76f13afe7..ee2dd14955b 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -362,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(bytes.index(&(..(bytes.len()-1))))), + Err(..) => try!(w.write(&bytes[..(bytes.len()-1)])), } } try!(w.write(&['\n' as u8])); diff --git a/src/libstd/sys/windows/ext.rs b/src/libstd/sys/windows/ext.rs index 049aca3f590..87ff31ab73c 100644 --- a/src/libstd/sys/windows/ext.rs +++ b/src/libstd/sys/windows/ext.rs @@ -14,7 +14,7 @@ //! descriptors, and sockets, but its functionality will grow over //! time. -#![experimental] +#![unstable] use sys_common::AsInner; use libc; diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index f8c75335b35..a7330f7c67c 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -270,7 +270,7 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { return Err(IoError { kind: io::InvalidInput, desc: "path was not valid UTF-16", - detail: Some(format!("path was not valid UTF-16: {}", filename)), + detail: Some(format!("path was not valid UTF-16: {:?}", filename)), }) }, // FIXME #12056: Convert the UCS-2 to invalid utf-8 instead of erroring } diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index fcde5c01080..064633f321c 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -36,7 +36,7 @@ const BUF_BYTES : uint = 2048u; pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] { match v.iter().position(|c| *c == 0) { // don't include the 0 - Some(i) => v.index(&(0..i)), + Some(i) => &v[0..i], None => v } } diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 016757ef63e..9996909f2f5 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -453,7 +453,7 @@ impl UnixStream { } let ret = unsafe { libc::WriteFile(self.handle(), - buf.index(&(offset..)).as_ptr() as libc::LPVOID, + buf[offset..].as_ptr() as libc::LPVOID, (buf.len() - offset) as libc::DWORD, &mut bytes_written, &mut overlapped) diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index 8e1f169b5cd..1b837385d1e 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -13,6 +13,7 @@ use prelude::v1::*; use collections; use ffi::CString; use hash::Hash; +use collections::hash_map::Hasher; use io::fs::PathExtensions; use io::process::{ProcessExit, ExitStatus, ExitSignal}; use io::{IoResult, IoError}; @@ -109,7 +110,7 @@ impl Process { out_fd: Option<P>, err_fd: Option<P>) -> IoResult<Process> where C: ProcessConfig<K, V>, P: AsInner<FileDesc>, - K: BytesContainer + Eq + Hash, V: BytesContainer + K: BytesContainer + Eq + Hash<Hasher>, V: BytesContainer { use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO}; use libc::consts::os::extra::{ @@ -424,8 +425,10 @@ fn make_command_line(prog: &CString, args: &[CString]) -> String { } } -fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T where - K: BytesContainer + Eq + Hash, V: BytesContainer, F: FnOnce(*mut c_void) -> T, +fn with_envp<K, V, T, F>(env: Option<&collections::HashMap<K, V>>, cb: F) -> T + where K: BytesContainer + Eq + Hash<Hasher>, + V: BytesContainer, + F: FnOnce(*mut c_void) -> T, { // On Windows we pass an "environment block" which is not a char**, but // rather a concatenation of null-terminated k=v\0 sequences, with a final diff --git a/src/libstd/sys/windows/timer.rs b/src/libstd/sys/windows/timer.rs index 343b78543bf..1ae3979cd9a 100644 --- a/src/libstd/sys/windows/timer.rs +++ b/src/libstd/sys/windows/timer.rs @@ -91,7 +91,7 @@ fn helper(input: libc::HANDLE, messages: Receiver<Req>, _: ()) { } else { let remove = { match &mut chans[idx as uint - 1] { - &(ref mut c, oneshot) => { c.call(); oneshot } + &mut (ref mut c, oneshot) => { c.call(); oneshot } } }; if remove { diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index c103365745c..932556fe1a6 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -207,14 +207,14 @@ impl Builder { } /// Redirect thread-local stdout. - #[experimental = "Will likely go away after proc removal"] + #[unstable = "Will likely go away after proc removal"] pub fn stdout(mut self, stdout: Box<Writer + Send>) -> Builder { self.stdout = Some(stdout); self } /// Redirect thread-local stderr. - #[experimental = "Will likely go away after proc removal"] + #[unstable = "Will likely go away after proc removal"] pub fn stderr(mut self, stderr: Box<Writer + Send>) -> Builder { self.stderr = Some(stderr); self @@ -483,7 +483,7 @@ impl<'a, T: Send + 'a> JoinGuard<'a, T> { impl<T: Send> JoinGuard<'static, T> { /// Detaches the child thread, allowing it to outlive its parent. - #[experimental = "unsure whether this API imposes limitations elsewhere"] + #[unstable = "unsure whether this API imposes limitations elsewhere"] pub fn detach(mut self) { unsafe { imp::detach(self.native) }; self.joined = true; // avoid joining in the destructor diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index a651d927c14..162c3677168 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -10,7 +10,7 @@ //! Temporal quantification -#![experimental] +#![unstable] use {fmt, i64}; use ops::{Add, Sub, Mul, Div, Neg, FnOnce}; diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 6766127a5f1..630f7768885 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -100,7 +100,6 @@ impl Ident { } } -//NOTE(stage0): remove after snapshot impl fmt::Show for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}#{}", self.name, self.ctxt) @@ -203,7 +202,7 @@ impl Encodable for Ident { impl Decodable for Ident { fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> { - Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) + Ok(str_to_ident(&try!(d.read_str())[])) } } @@ -1076,16 +1075,29 @@ pub struct Typedef { pub typ: P<Ty>, } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] pub enum IntTy { - TyIs, + TyIs(bool /* is this deprecated `int`? */), TyI8, TyI16, TyI32, TyI64, } -//NOTE(stage0): remove after snapshot +impl PartialEq for IntTy { + fn eq(&self, other: &IntTy) -> bool { + match (*self, *other) { + // true/false need to compare the same, so this can't be derived + (TyIs(_), TyIs(_)) | + (TyI8, TyI8) | + (TyI16, TyI16) | + (TyI32, TyI32) | + (TyI64, TyI64) => true, + _ => false + } + } +} + impl fmt::Show for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, f) @@ -1101,33 +1113,46 @@ impl fmt::String for IntTy { impl IntTy { pub fn suffix_len(&self) -> uint { match *self { - TyIs => 1, - TyI8 => 2, + TyIs(true) /* i */ => 1, + TyIs(false) /* is */ | TyI8 => 2, TyI16 | TyI32 | TyI64 => 3, } } } -#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] +#[derive(Clone, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] pub enum UintTy { - TyUs, + TyUs(bool /* is this deprecated uint? */), TyU8, TyU16, TyU32, TyU64, } +impl PartialEq for UintTy { + fn eq(&self, other: &UintTy) -> bool { + match (*self, *other) { + // true/false need to compare the same, so this can't be derived + (TyUs(_), TyUs(_)) | + (TyU8, TyU8) | + (TyU16, TyU16) | + (TyU32, TyU32) | + (TyU64, TyU64) => true, + _ => false + } + } +} + impl UintTy { pub fn suffix_len(&self) -> uint { match *self { - TyUs => 1, - TyU8 => 2, + TyUs(true) /* u */ => 1, + TyUs(false) /* us */ | TyU8 => 2, TyU16 | TyU32 | TyU64 => 3, } } } -//NOTE(stage0): remove after snapshot impl fmt::Show for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, f) @@ -1146,7 +1171,6 @@ pub enum FloatTy { TyF64, } -//NOTE(stage0): remove after snapshot impl fmt::Show for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::String::fmt(self, f) @@ -1734,11 +1758,8 @@ pub struct MacroDef { #[cfg(test)] mod test { - use serialize::json; use serialize; - use codemap::*; use super::*; - use std::fmt; // are ASTs encodable? #[test] diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index 7496a0f9f26..3ef57279175 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -32,7 +32,7 @@ use std::slice; pub mod blocks; -#[derive(Clone, Copy, PartialEq)] +#[derive(Clone, Copy, PartialEq, Show)] pub enum PathElem { PathMod(Name), PathName(Name) @@ -46,13 +46,6 @@ impl PathElem { } } -//NOTE(stage0): replace with deriving(Show) after snapshot -impl fmt::Show for PathElem { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::String::fmt(self, f) - } -} - impl fmt::String for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); @@ -90,7 +83,7 @@ impl<'a, T: Copy> Iterator for Values<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { - let &Values(ref mut items) = self; + let &mut Values(ref mut items) = self; items.next().map(|&x| x) } } @@ -106,7 +99,7 @@ pub fn path_to_string<PI: Iterator<Item=PathElem>>(path: PI) -> String { if !s.is_empty() { s.push_str("::"); } - s.push_str(e.index(&FullRange)); + s.push_str(&e[]); s }).to_string() } @@ -483,20 +476,20 @@ impl<'ast> Map<'ast> { F: FnOnce(Option<&[Attribute]>) -> T, { let attrs = match self.get(id) { - NodeItem(i) => Some(i.attrs.index(&FullRange)), - NodeForeignItem(fi) => Some(fi.attrs.index(&FullRange)), + NodeItem(i) => Some(&i.attrs[]), + NodeForeignItem(fi) => Some(&fi.attrs[]), NodeTraitItem(ref tm) => match **tm { - RequiredMethod(ref type_m) => Some(type_m.attrs.index(&FullRange)), - ProvidedMethod(ref m) => Some(m.attrs.index(&FullRange)), - TypeTraitItem(ref typ) => Some(typ.attrs.index(&FullRange)), + RequiredMethod(ref type_m) => Some(&type_m.attrs[]), + ProvidedMethod(ref m) => Some(&m.attrs[]), + TypeTraitItem(ref typ) => Some(&typ.attrs[]), }, NodeImplItem(ref ii) => { match **ii { - MethodImplItem(ref m) => Some(m.attrs.index(&FullRange)), - TypeImplItem(ref t) => Some(t.attrs.index(&FullRange)), + MethodImplItem(ref m) => Some(&m.attrs[]), + TypeImplItem(ref t) => Some(&t.attrs[]), } } - NodeVariant(ref v) => Some(v.node.attrs.index(&FullRange)), + NodeVariant(ref v) => Some(&v.node.attrs[]), // unit/tuple structs take the attributes straight from // the struct definition. // FIXME(eddyb) make this work again (requires access to the map). @@ -520,7 +513,7 @@ impl<'ast> Map<'ast> { NodesMatchingSuffix { map: self, item_name: parts.last().unwrap(), - in_which: parts.index(&(0..(parts.len() - 1))), + in_which: &parts[0..(parts.len() - 1)], idx: 0, } } @@ -597,7 +590,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { None => return false, Some((node_id, name)) => (node_id, name), }; - if part.index(&FullRange) != mod_name.as_str() { + if &part[] != mod_name.as_str() { return false; } cursor = self.map.get_parent(mod_id); @@ -635,7 +628,7 @@ impl<'a, 'ast> NodesMatchingSuffix<'a, 'ast> { // We are looking at some node `n` with a given name and parent // id; do their names match what I am seeking? fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool { - name.as_str() == self.item_name.index(&FullRange) && + name.as_str() == &self.item_name[] && self.suffix_matches(parent_of_n) } } @@ -1047,7 +1040,7 @@ impl<'a> NodePrinter for pprust::State<'a> { fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String { let id_str = format!(" (id={})", id); - let id_str = if include_id { id_str.index(&FullRange) } else { "" }; + let id_str = if include_id { &id_str[] } else { "" }; match map.find(id) { Some(NodeItem(item)) => { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 871f1237aee..bc7fbd46fd8 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -85,6 +85,13 @@ pub fn is_shift_binop(b: BinOp) -> bool { } } +pub fn is_comparison_binop(b: BinOp) -> bool { + match b { + BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true, + _ => false + } +} + /// Returns `true` if the binary operator takes its arguments by value pub fn is_by_value_binop(b: BinOp) -> bool { match b { @@ -120,8 +127,10 @@ pub fn is_path(e: P<Expr>) -> bool { /// We want to avoid "45int" and "-3int" in favor of "45" and "-3" pub fn int_ty_to_string(t: IntTy, val: Option<i64>) -> String { let s = match t { - TyIs if val.is_some() => "is", - TyIs => "isize", + TyIs(true) if val.is_some() => "i", + TyIs(true) => "int", + TyIs(false) if val.is_some() => "is", + TyIs(false) => "isize", TyI8 => "i8", TyI16 => "i16", TyI32 => "i32", @@ -141,7 +150,7 @@ pub fn int_ty_max(t: IntTy) -> u64 { match t { TyI8 => 0x80u64, TyI16 => 0x8000u64, - TyIs | TyI32 => 0x80000000u64, // actually ni about TyIs + TyIs(_) | TyI32 => 0x80000000u64, // actually ni about TyIs TyI64 => 0x8000000000000000u64 } } @@ -150,8 +159,10 @@ pub fn int_ty_max(t: IntTy) -> u64 { /// We want to avoid "42uint" in favor of "42u" pub fn uint_ty_to_string(t: UintTy, val: Option<u64>) -> String { let s = match t { - TyUs if val.is_some() => "us", - TyUs => "usize", + TyUs(true) if val.is_some() => "u", + TyUs(true) => "uint", + TyUs(false) if val.is_some() => "us", + TyUs(false) => "usize", TyU8 => "u8", TyU16 => "u16", TyU32 => "u32", @@ -168,7 +179,7 @@ pub fn uint_ty_max(t: UintTy) -> u64 { match t { TyU8 => 0xffu64, TyU16 => 0xffffu64, - TyUs | TyU32 => 0xffffffffu64, // actually ni about TyUs + TyUs(_) | TyU32 => 0xffffffffu64, // actually ni about TyUs TyU64 => 0xffffffffffffffffu64 } } @@ -238,11 +249,11 @@ pub fn impl_pretty_name(trait_ref: &Option<TraitRef>, ty: &Ty) -> Ident { match *trait_ref { Some(ref trait_ref) => { pretty.push('.'); - pretty.push_str(pprust::path_to_string(&trait_ref.path).index(&FullRange)); + pretty.push_str(&pprust::path_to_string(&trait_ref.path)[]); } None => {} } - token::gensym_ident(pretty.index(&FullRange)) + token::gensym_ident(&pretty[]) } pub fn trait_method_to_ty_method(method: &Method) -> TypeMethod { @@ -317,8 +328,7 @@ pub fn operator_prec(op: ast::BinOp) -> uint { BiBitAnd => 8u, BiBitXor => 7u, BiBitOr => 6u, - BiLt | BiLe | BiGe | BiGt => 4u, - BiEq | BiNe => 3u, + BiLt | BiLe | BiGe | BiGt | BiEq | BiNe => 3u, BiAnd => 2u, BiOr => 1u } @@ -704,7 +714,7 @@ pub fn pat_is_ident(pat: P<ast::Pat>) -> bool { pub fn path_name_eq(a : &ast::Path, b : &ast::Path) -> bool { (a.span == b.span) && (a.global == b.global) - && (segments_name_eq(a.segments.index(&FullRange), b.segments.index(&FullRange))) + && (segments_name_eq(&a.segments[], &b.segments[])) } // are two arrays of segments equal when compared unhygienically? @@ -791,14 +801,14 @@ mod test { #[test] fn idents_name_eq_test() { assert!(segments_name_eq( - [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange), - [Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange))); + &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(78),ctxt:182}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); assert!(!segments_name_eq( - [Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange), - [Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] - .iter().map(ident_to_segment).collect::<Vec<PathSegment>>().index(&FullRange))); + &[Ident{name:Name(3),ctxt:4}, Ident{name:Name(78),ctxt:82}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[], + &[Ident{name:Name(3),ctxt:104}, Ident{name:Name(77),ctxt:182}] + .iter().map(ident_to_segment).collect::<Vec<PathSegment>>()[])); } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 416fc8c2278..6f57c06d33e 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -98,7 +98,7 @@ impl AttrMetaMethods for MetaItem { fn meta_item_list<'a>(&'a self) -> Option<&'a [P<MetaItem>]> { match self.node { - MetaList(_, ref l) => Some(l.index(&FullRange)), + MetaList(_, ref l) => Some(&l[]), _ => None } } @@ -136,8 +136,8 @@ impl AttributeMethods for Attribute { let comment = self.value_str().unwrap(); let meta = mk_name_value_item_str( InternedString::new("doc"), - token::intern_and_get_ident(strip_doc_comment_decoration( - comment.get()).index(&FullRange))); + token::intern_and_get_ident(&strip_doc_comment_decoration( + comment.get())[])); if self.node.style == ast::AttrOuter { f(&mk_attr_outer(self.node.id, meta)) } else { @@ -297,9 +297,9 @@ pub fn find_inline_attr(attrs: &[Attribute]) -> InlineAttr { } MetaList(ref n, ref items) if *n == "inline" => { mark_used(attr); - if contains_name(items.index(&FullRange), "always") { + if contains_name(&items[], "always") { InlineAlways - } else if contains_name(items.index(&FullRange), "never") { + } else if contains_name(&items[], "never") { InlineNever } else { InlineHint @@ -403,7 +403,7 @@ pub fn require_unique_names(diagnostic: &SpanHandler, metas: &[P<MetaItem>]) { if !set.insert(name.clone()) { diagnostic.span_fatal(meta.span, - format!("duplicate meta item `{}`", name).index(&FullRange)); + &format!("duplicate meta item `{}`", name)[]); } } } @@ -464,10 +464,10 @@ fn int_type_of_word(s: &str) -> Option<IntType> { "u32" => Some(UnsignedInt(ast::TyU32)), "i64" => Some(SignedInt(ast::TyI64)), "u64" => Some(UnsignedInt(ast::TyU64)), - "int" => Some(SignedInt(ast::TyIs)), - "uint" => Some(UnsignedInt(ast::TyUs)), - "isize" => Some(SignedInt(ast::TyIs)), - "usize" => Some(UnsignedInt(ast::TyUs)), + "int" => Some(SignedInt(ast::TyIs(true))), + "uint" => Some(UnsignedInt(ast::TyUs(true))), + "isize" => Some(SignedInt(ast::TyIs(false))), + "usize" => Some(UnsignedInt(ast::TyUs(false))), _ => None } } @@ -511,7 +511,7 @@ impl IntType { SignedInt(ast::TyI16) | UnsignedInt(ast::TyU16) | SignedInt(ast::TyI32) | UnsignedInt(ast::TyU32) | SignedInt(ast::TyI64) | UnsignedInt(ast::TyU64) => true, - SignedInt(ast::TyIs) | UnsignedInt(ast::TyUs) => false + SignedInt(ast::TyIs(_)) | UnsignedInt(ast::TyUs(_)) => false } } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 31fe23847d9..9a422e17bb4 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -105,6 +105,11 @@ pub struct Span { pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION }; +// Generic span to be used for code originating from the command line +pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0), + hi: BytePos(0), + expn_id: COMMAND_LINE_EXPN }; + #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)] pub struct Spanned<T> { pub node: T, @@ -235,6 +240,8 @@ pub struct ExpnInfo { pub struct ExpnId(u32); pub const NO_EXPANSION: ExpnId = ExpnId(-1); +// For code appearing from the command line +pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(-2); impl ExpnId { pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId { @@ -304,9 +311,9 @@ impl FileMap { lines.get(line_number).map(|&line| { let begin: BytePos = line - self.start_pos; let begin = begin.to_uint(); - let slice = self.src.index(&(begin..)); + let slice = &self.src[begin..]; match slice.find('\n') { - Some(e) => slice.index(&(0..e)), + Some(e) => &slice[0..e], None => slice }.to_string() }) @@ -351,9 +358,9 @@ impl CodeMap { // FIXME #12884: no efficient/safe way to remove from the start of a string // and reuse the allocation. let mut src = if src.starts_with("\u{feff}") { - String::from_str(src.index(&(3..))) + String::from_str(&src[3..]) } else { - String::from_str(src.index(&FullRange)) + String::from_str(&src[]) }; // Append '\n' in case it's not already there. @@ -440,8 +447,7 @@ impl CodeMap { if begin.fm.start_pos != end.fm.start_pos { None } else { - Some(begin.fm.src.index(&(begin.pos.to_uint().. - end.pos.to_uint())).to_string()) + Some((&begin.fm.src[begin.pos.to_uint()..end.pos.to_uint()]).to_string()) } } @@ -590,7 +596,12 @@ impl CodeMap { Some(ref info) => { // save the parent expn_id for next loop iteration expnid = info.call_site.expn_id; - if info.callee.span.is_none() { + if info.callee.name == "format_args" { + // This is a hack because the format_args builtin calls unstable APIs. + // I spent like 6 hours trying to solve this more generally but am stupid. + is_internal = true; + false + } else if info.callee.span.is_none() { // it's a compiler built-in, we *really* don't want to mess with it // so we skip it, unless it was called by a regular macro, in which case // we will handle the caller macro next turn diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index fde2fdb3c55..64fdb61f2ec 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -13,7 +13,7 @@ pub use self::RenderSpan::*; pub use self::ColorConfig::*; use self::Destination::*; -use codemap::{Pos, Span}; +use codemap::{COMMAND_LINE_SP, Pos, Span}; use codemap; use diagnostics; @@ -123,7 +123,7 @@ impl SpanHandler { panic!(ExplicitBug); } pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { - self.span_bug(sp, format!("unimplemented {}", msg).index(&FullRange)); + self.span_bug(sp, &format!("unimplemented {}", msg)[]); } pub fn handler<'a>(&'a self) -> &'a Handler { &self.handler @@ -166,7 +166,7 @@ impl Handler { self.err_count.get()); } } - self.fatal(s.index(&FullRange)); + self.fatal(&s[]); } pub fn warn(&self, msg: &str) { self.emit.borrow_mut().emit(None, msg, None, Warning); @@ -182,7 +182,7 @@ impl Handler { panic!(ExplicitBug); } pub fn unimpl(&self, msg: &str) -> ! { - self.bug(format!("unimplemented {}", msg).index(&FullRange)); + self.bug(&format!("unimplemented {}", msg)[]); } pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, @@ -277,7 +277,7 @@ fn print_maybe_styled(w: &mut EmitterWriter, // to be miscolored. We assume this is rare enough that we don't // have to worry about it. if msg.ends_with("\n") { - try!(t.write_str(msg.index(&(0..(msg.len()-1))))); + try!(t.write_str(&msg[0..(msg.len()-1)])); try!(t.reset()); try!(t.write_str("\n")); } else { @@ -299,16 +299,16 @@ fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level, } try!(print_maybe_styled(dst, - format!("{}: ", lvl.to_string()).index(&FullRange), + &format!("{}: ", lvl.to_string())[], term::attr::ForegroundColor(lvl.color()))); try!(print_maybe_styled(dst, - format!("{}", msg).index(&FullRange), + &format!("{}", msg)[], term::attr::Bold)); match code { Some(code) => { let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA); - try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).index(&FullRange), style)); + try!(print_maybe_styled(dst, &format!(" [{}]", code.clone())[], style)); } None => () } @@ -368,6 +368,9 @@ impl Emitter for EmitterWriter { cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { let error = match cmsp { + Some((cm, COMMAND_LINE_SP)) => emit(self, cm, + FileLine(COMMAND_LINE_SP), + msg, code, lvl, false), Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false), None => print_diagnostic(self, "", lvl, msg, code), }; @@ -390,32 +393,37 @@ impl Emitter for EmitterWriter { fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan, msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> { let sp = rsp.span(); - let ss = cm.span_to_string(sp); - let lines = cm.span_to_lines(sp); + let ss = if sp == COMMAND_LINE_SP { + "<command line option>".to_string() + } else { + cm.span_to_string(sp) + }; if custom { // we want to tell compiletest/runtest to look at the last line of the // span (since `custom_highlight_lines` displays an arrow to the end of // the span) let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id}; let ses = cm.span_to_string(span_end); - try!(print_diagnostic(dst, ses.index(&FullRange), lvl, msg, code)); + try!(print_diagnostic(dst, &ses[], lvl, msg, code)); if rsp.is_full_span() { - try!(custom_highlight_lines(dst, cm, sp, lvl, lines)); + try!(custom_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } else { - try!(print_diagnostic(dst, ss.index(&FullRange), lvl, msg, code)); + try!(print_diagnostic(dst, &ss[], lvl, msg, code)); if rsp.is_full_span() { - try!(highlight_lines(dst, cm, sp, lvl, lines)); + try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp))); } } - try!(print_macro_backtrace(dst, cm, sp)); + if sp != COMMAND_LINE_SP { + try!(print_macro_backtrace(dst, cm, sp)); + } match code { Some(code) => match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) { Some(_) => { - try!(print_diagnostic(dst, ss.index(&FullRange), Help, - format!("pass `--explain {}` to see a detailed \ - explanation", code).index(&FullRange), None)); + try!(print_diagnostic(dst, &ss[], Help, + &format!("pass `--explain {}` to see a detailed \ + explanation", code)[], None)); } None => () }, @@ -432,9 +440,9 @@ fn highlight_lines(err: &mut EmitterWriter, let fm = &*lines.file; let mut elided = false; - let mut display_lines = lines.lines.index(&FullRange); + let mut display_lines = &lines.lines[]; if display_lines.len() > MAX_LINES { - display_lines = display_lines.index(&(0u..MAX_LINES)); + display_lines = &display_lines[0u..MAX_LINES]; elided = true; } // Print the offending lines @@ -494,7 +502,7 @@ fn highlight_lines(err: &mut EmitterWriter, } } try!(print_maybe_styled(err, - format!("{}\n", s).index(&FullRange), + &format!("{}\n", s)[], term::attr::ForegroundColor(lvl.color()))); } Ok(()) @@ -514,7 +522,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, -> io::IoResult<()> { let fm = &*lines.file; - let lines = lines.lines.index(&FullRange); + let lines = &lines.lines[]; if lines.len() > MAX_LINES { if let Some(line) = fm.get_line(lines[0]) { try!(write!(&mut w.dst, "{}:{} {}\n", fm.name, @@ -545,7 +553,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, s.push('^'); s.push('\n'); print_maybe_styled(w, - s.index(&FullRange), + &s[], term::attr::ForegroundColor(lvl.color())) } @@ -560,12 +568,12 @@ fn print_macro_backtrace(w: &mut EmitterWriter, codemap::MacroAttribute => ("#[", "]"), codemap::MacroBang => ("", "!") }; - try!(print_diagnostic(w, ss.index(&FullRange), Note, - format!("in expansion of {}{}{}", pre, + try!(print_diagnostic(w, &ss[], Note, + &format!("in expansion of {}{}{}", pre, ei.callee.name, - post).index(&FullRange), None)); + post)[], None)); let ss = cm.span_to_string(ei.call_site); - try!(print_diagnostic(w, ss.index(&FullRange), Note, "expansion site", None)); + try!(print_diagnostic(w, &ss[], Note, "expansion site", None)); Ok(Some(ei.call_site)) } None => Ok(None) @@ -578,6 +586,6 @@ pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where { match opt { Some(t) => t, - None => diag.handler().bug(msg().index(&FullRange)), + None => diag.handler().bug(&msg()[]), } } diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 0f4ebd74b66..1469c50061c 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -56,9 +56,9 @@ pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt, with_used_diagnostics(|diagnostics| { match diagnostics.insert(code.name, span) { Some(previous_span) => { - ecx.span_warn(span, format!( + ecx.span_warn(span, &format!( "diagnostic code {} already used", token::get_ident(code).get() - ).index(&FullRange)); + )[]); ecx.span_note(previous_span, "previous invocation"); }, None => () @@ -85,14 +85,14 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, }; with_registered_diagnostics(|diagnostics| { if diagnostics.insert(code.name, description).is_some() { - ecx.span_err(span, format!( + ecx.span_err(span, &format!( "diagnostic code {} already registered", token::get_ident(*code).get() - ).index(&FullRange)); + )[]); } }); - let sym = Ident::new(token::gensym(( + let sym = Ident::new(token::gensym(&( "__register_diagnostic_".to_string() + token::get_ident(*code).get() - ).index(&FullRange))); + )[])); MacItems::new(vec![quote_item!(ecx, mod $sym {}).unwrap()].into_iter()) } diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index 04dec0e8028..fd3bac5b2fc 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -99,8 +99,8 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let output = match constraint.get().slice_shift_char() { Some(('=', _)) => None, Some(('+', operand)) => { - Some(token::intern_and_get_ident(format!( - "={}", operand).index(&FullRange))) + Some(token::intern_and_get_ident(&format!( + "={}", operand)[])) } _ => { cx.span_err(span, "output operand constraint lacks '=' or '+'"); diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 52e402689ba..9b9d8a9ceb3 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -341,9 +341,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { let mut syntax_expanders = SyntaxEnv::new(); syntax_expanders.insert(intern("macro_rules"), MacroRulesTT); - syntax_expanders.insert(intern("fmt"), - builtin_normal_expander( - ext::fmt::expand_syntax_ext)); syntax_expanders.insert(intern("format_args"), builtin_normal_expander( ext::format::expand_format_args)); @@ -353,9 +350,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { syntax_expanders.insert(intern("option_env"), builtin_normal_expander( ext::env::expand_option_env)); - syntax_expanders.insert(intern("bytes"), - builtin_normal_expander( - ext::bytes::expand_syntax_ext)); syntax_expanders.insert(intern("concat_idents"), builtin_normal_expander( ext::concat_idents::expand_syntax_ext)); @@ -367,8 +361,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { ext::log_syntax::expand_syntax_ext)); syntax_expanders.insert(intern("derive"), Decorator(box ext::deriving::expand_meta_derive)); - syntax_expanders.insert(intern("deriving"), - Decorator(box ext::deriving::expand_meta_deriving)); if ecfg.enable_quotes { // Quasi-quoting expanders @@ -416,9 +408,6 @@ fn initial_syntax_expander_table(ecfg: &expand::ExpansionConfig) -> SyntaxEnv { syntax_expanders.insert(intern("include_str"), builtin_normal_expander( ext::source_util::expand_include_str)); - syntax_expanders.insert(intern("include_bin"), - builtin_normal_expander( - ext::source_util::expand_include_bin)); syntax_expanders.insert(intern("include_bytes"), builtin_normal_expander( ext::source_util::expand_include_bytes)); @@ -539,7 +528,7 @@ impl<'a> ExtCtxt<'a> { pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); } pub fn mod_path(&self) -> Vec<ast::Ident> { let mut v = Vec::new(); - v.push(token::str_to_ident(self.ecfg.crate_name.index(&FullRange))); + v.push(token::str_to_ident(&self.ecfg.crate_name[])); v.extend(self.mod_path.iter().map(|a| *a)); return v; } @@ -547,8 +536,8 @@ impl<'a> ExtCtxt<'a> { self.recursion_count += 1; if self.recursion_count > self.ecfg.recursion_limit { self.span_fatal(ei.call_site, - format!("recursion limit reached while expanding the macro `{}`", - ei.callee.name).index(&FullRange)); + &format!("recursion limit reached while expanding the macro `{}`", + ei.callee.name)[]); } let mut call_site = ei.call_site; @@ -670,7 +659,7 @@ pub fn check_zero_tts(cx: &ExtCtxt, tts: &[ast::TokenTree], name: &str) { if tts.len() != 0 { - cx.span_err(sp, format!("{} takes no arguments", name).index(&FullRange)); + cx.span_err(sp, &format!("{} takes no arguments", name)[]); } } @@ -683,12 +672,12 @@ pub fn get_single_str_from_tts(cx: &mut ExtCtxt, -> Option<String> { let mut p = cx.new_parser_from_tts(tts); if p.token == token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); + cx.span_err(sp, &format!("{} takes 1 argument", name)[]); return None } let ret = cx.expander().fold_expr(p.parse_expr()); if p.token != token::Eof { - cx.span_err(sp, format!("{} takes 1 argument", name).index(&FullRange)); + cx.span_err(sp, &format!("{} takes 1 argument", name)[]); } expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| { s.get().to_string() diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index bd4f295401c..c34142aec39 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -642,10 +642,11 @@ impl<'a> AstBuilder for ExtCtxt<'a> { self.expr(sp, ast::ExprLit(P(respan(sp, lit)))) } fn expr_uint(&self, span: Span, i: uint) -> P<ast::Expr> { - self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs))) + self.expr_lit(span, ast::LitInt(i as u64, ast::UnsignedIntLit(ast::TyUs(false)))) } fn expr_int(&self, sp: Span, i: int) -> P<ast::Expr> { - self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyIs, ast::Sign::new(i)))) + self.expr_lit(sp, ast::LitInt(i as u64, ast::SignedIntLit(ast::TyIs(false), + ast::Sign::new(i)))) } fn expr_u8(&self, sp: Span, u: u8) -> P<ast::Expr> { self.expr_lit(sp, ast::LitInt(u as u64, ast::UnsignedIntLit(ast::TyU8))) @@ -708,8 +709,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { fn expr_fail(&self, span: Span, msg: InternedString) -> P<ast::Expr> { let loc = self.codemap().lookup_char_pos(span.lo); let expr_file = self.expr_str(span, - token::intern_and_get_ident(loc.file - .name.index(&FullRange))); + token::intern_and_get_ident(&loc.file.name[])); let expr_line = self.expr_uint(span, loc.line); let expr_file_line_tuple = self.expr_tuple(span, vec!(expr_file, expr_line)); let expr_file_line_ptr = self.expr_addr_of(span, expr_file_line_tuple); diff --git a/src/libsyntax/ext/bytes.rs b/src/libsyntax/ext/bytes.rs deleted file mode 100644 index 9f225d55b44..00000000000 --- a/src/libsyntax/ext/bytes.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/* The compiler code necessary to support the bytes! extension. */ - -use ast; -use codemap::Span; -use ext::base::*; -use ext::base; -use ext::build::AstBuilder; -use std::ascii::AsciiExt; - -pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, - sp: Span, - tts: &[ast::TokenTree]) - -> Box<base::MacResult+'cx> { - cx.span_warn(sp, "`bytes!` is deprecated, use `b\"foo\"` literals instead"); - cx.parse_sess.span_diagnostic.span_help(sp, - "see http://doc.rust-lang.org/reference.html#byte-and-byte-string-literals \ - for documentation"); - cx.parse_sess.span_diagnostic.span_help(sp, - "see https://github.com/rust-lang/rust/blob/master/src/etc/2014-06-rewrite-bytes-macros.py \ - for an automated migration"); - - // Gather all argument expressions - let exprs = match get_exprs_from_tts(cx, sp, tts) { - None => return DummyResult::expr(sp), - Some(e) => e, - }; - let mut bytes = Vec::new(); - let mut err = false; - - for expr in exprs.iter() { - match expr.node { - // expression is a literal - ast::ExprLit(ref lit) => match lit.node { - // string literal, push each byte to vector expression - ast::LitStr(ref s, _) => { - for byte in s.get().bytes() { - bytes.push(cx.expr_u8(expr.span, byte)); - } - } - - // u8 literal, push to vector expression - ast::LitInt(v, ast::UnsignedIntLit(ast::TyU8)) => { - if v > 0xFF { - cx.span_err(expr.span, "too large u8 literal in bytes!"); - err = true; - } else { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } - } - - // integer literal, push to vector expression - ast::LitInt(_, ast::UnsuffixedIntLit(ast::Minus)) => { - cx.span_err(expr.span, "negative integer literal in bytes!"); - err = true; - } - ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => { - if v > 0xFF { - cx.span_err(expr.span, "too large integer literal in bytes!"); - err = true; - } else { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } - } - - // char literal, push to vector expression - ast::LitChar(v) => { - if v.is_ascii() { - bytes.push(cx.expr_u8(expr.span, v as u8)); - } else { - cx.span_err(expr.span, "non-ascii char literal in bytes!"); - err = true; - } - } - - _ => { - cx.span_err(expr.span, "unsupported literal in bytes!"); - err = true; - } - }, - - _ => { - cx.span_err(expr.span, "non-literal in bytes!"); - err = true; - } - } - } - - // For some reason using quote_expr!() here aborts if we threw an error. - // I'm assuming that the end of the recursive parse tricks the compiler - // into thinking this is a good time to stop. But we'd rather keep going. - if err { - // Since the compiler will stop after the macro expansion phase anyway, we - // don't need type info, so we can just return a DummyResult - return DummyResult::expr(sp); - } - - let len = bytes.len(); - let e = cx.expr_vec(sp, bytes); - let ty = cx.ty(sp, ast::TyFixedLengthVec(cx.ty_ident(sp, cx.ident_of("u8")), - cx.expr_uint(sp, len))); - let item = cx.item_static(sp, cx.ident_of("BYTES"), ty, ast::MutImmutable, e); - let ret = cx.expr_ident(sp, cx.ident_of("BYTES")); - let ret = cx.expr_addr_of(sp, ret); - let e = cx.expr_block(cx.block(sp, vec![cx.stmt_item(sp, item)], - Some(ret))); - MacExpr::new(e) -} diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index 1f1781dceb3..39895a3946a 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -40,14 +40,14 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, ast::LitInt(i, ast::UnsignedIntLit(_)) | ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Plus)) => { - accumulator.push_str(format!("{}", i).index(&FullRange)); + accumulator.push_str(&format!("{}", i)[]); } ast::LitInt(i, ast::SignedIntLit(_, ast::Minus)) | ast::LitInt(i, ast::UnsuffixedIntLit(ast::Minus)) => { - accumulator.push_str(format!("-{}", i).index(&FullRange)); + accumulator.push_str(&format!("-{}", i)[]); } ast::LitBool(b) => { - accumulator.push_str(format!("{}", b).index(&FullRange)); + accumulator.push_str(&format!("{}", b)[]); } ast::LitByte(..) | ast::LitBinary(..) => { @@ -62,5 +62,5 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, } base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(accumulator.index(&FullRange)))) + token::intern_and_get_ident(&accumulator[]))) } diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 02f702248cb..1af3ba1d326 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -40,7 +40,7 @@ pub fn expand_syntax_ext<'cx>(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree] } } } - let res = str_to_ident(res_str.index(&FullRange)); + let res = str_to_ident(&res_str[]); let e = P(ast::Expr { id: ast::DUMMY_NODE_ID, diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index d9d6cebd05c..784a92b9a0e 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -79,12 +79,12 @@ fn cs_clone( }, EnumNonMatchingCollapsed (..) => { cx.span_bug(trait_span, - format!("non-matching enum variants in \ - `deriving({})`", name).index(&FullRange)) + &format!("non-matching enum variants in \ + `deriving({})`", name)[]) } StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, - format!("static method in `deriving({})`", name).index(&FullRange)) + &format!("static method in `deriving({})`", name)[]) } } @@ -100,8 +100,8 @@ fn cs_clone( Some(i) => i, None => { cx.span_bug(trait_span, - format!("unnamed field in normal struct in \ - `deriving({})`", name).index(&FullRange)) + &format!("unnamed field in normal struct in \ + `deriving({})`", name)[]) } }; cx.field_imm(field.span, ident, subcall(field)) diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index a9289f0175a..7c65d2b4ff4 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -197,8 +197,7 @@ fn decode_static_fields<F>(cx: &mut ExtCtxt, } else { let fields = fields.iter().enumerate().map(|(i, &span)| { getarg(cx, span, - token::intern_and_get_ident(format!("_field{}", - i).index(&FullRange)), + token::intern_and_get_ident(&format!("_field{}", i)[]), i) }).collect(); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 7114217d51d..616390467f0 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -183,7 +183,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, let name = match name { Some(id) => token::get_ident(id), None => { - token::intern_and_get_ident(format!("_field{}", i).index(&FullRange)) + token::intern_and_get_ident(&format!("_field{}", i)[]) } }; let enc = cx.expr_method_call(span, self_.clone(), diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 50b3559f369..e6b6f7bbd49 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -510,15 +510,15 @@ impl<'a> TraitDef<'a> { self, struct_def, type_ident, - self_args.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) } else { method_def.expand_struct_method_body(cx, self, struct_def, type_ident, - self_args.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) }; method_def.create_method(cx, @@ -550,15 +550,15 @@ impl<'a> TraitDef<'a> { self, enum_def, type_ident, - self_args.index(&FullRange), - nonself_args.index(&FullRange)) + &self_args[], + &nonself_args[]) } else { method_def.expand_enum_method_body(cx, self, enum_def, type_ident, self_args, - nonself_args.index(&FullRange)) + &nonself_args[]) }; method_def.create_method(cx, @@ -645,7 +645,7 @@ impl<'a> MethodDef<'a> { for (i, ty) in self.args.iter().enumerate() { let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics); - let ident = cx.ident_of(format!("__arg_{}", i).index(&FullRange)); + let ident = cx.ident_of(&format!("__arg_{}", i)[]); arg_tys.push((ident, ast_ty)); let arg_expr = cx.expr_ident(trait_.span, ident); @@ -751,8 +751,8 @@ impl<'a> MethodDef<'a> { trait_.create_struct_pattern(cx, struct_path, struct_def, - format!("__self_{}", - i).index(&FullRange), + &format!("__self_{}", + i)[], ast::MutImmutable); patterns.push(pat); raw_fields.push(ident_expr); @@ -908,22 +908,22 @@ impl<'a> MethodDef<'a> { .collect::<Vec<String>>(); let self_arg_idents = self_arg_names.iter() - .map(|name|cx.ident_of(name.index(&FullRange))) + .map(|name|cx.ident_of(&name[])) .collect::<Vec<ast::Ident>>(); // The `vi_idents` will be bound, solely in the catch-all, to // a series of let statements mapping each self_arg to a uint // corresponding to its variant index. let vi_idents: Vec<ast::Ident> = self_arg_names.iter() - .map(|name| { let vi_suffix = format!("{}_vi", name.index(&FullRange)); - cx.ident_of(vi_suffix.index(&FullRange)) }) + .map(|name| { let vi_suffix = format!("{}_vi", &name[]); + cx.ident_of(&vi_suffix[]) }) .collect::<Vec<ast::Ident>>(); // Builds, via callback to call_substructure_method, the // delegated expression that handles the catch-all case, // using `__variants_tuple` to drive logic if necessary. let catch_all_substructure = EnumNonMatchingCollapsed( - self_arg_idents, variants.index(&FullRange), vi_idents.index(&FullRange)); + self_arg_idents, &variants[], &vi_idents[]); // These arms are of the form: // (Variant1, Variant1, ...) => Body1 @@ -945,12 +945,12 @@ impl<'a> MethodDef<'a> { let mut subpats = Vec::with_capacity(self_arg_names.len()); let mut self_pats_idents = Vec::with_capacity(self_arg_names.len() - 1); let first_self_pat_idents = { - let (p, idents) = mk_self_pat(cx, self_arg_names[0].index(&FullRange)); + let (p, idents) = mk_self_pat(cx, &self_arg_names[0][]); subpats.push(p); idents }; for self_arg_name in self_arg_names.tail().iter() { - let (p, idents) = mk_self_pat(cx, self_arg_name.index(&FullRange)); + let (p, idents) = mk_self_pat(cx, &self_arg_name[]); subpats.push(p); self_pats_idents.push(idents); } @@ -1006,7 +1006,7 @@ impl<'a> MethodDef<'a> { &**variant, field_tuples); let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, + cx, trait_, type_ident, &self_args[], nonself_args, &substructure); cx.arm(sp, vec![single_pat], arm_expr) @@ -1031,7 +1031,7 @@ impl<'a> MethodDef<'a> { let arms: Vec<ast::Arm> = variants.iter().enumerate() .map(|(index, variant)| { let pat = variant_to_pat(cx, sp, type_ident, &**variant); - let lit = ast::LitInt(index as u64, ast::UnsignedIntLit(ast::TyUs)); + let lit = ast::LitInt(index as u64, ast::UnsignedIntLit(ast::TyUs(false))); cx.arm(sp, vec![pat], cx.expr_lit(sp, lit)) }).collect(); @@ -1059,7 +1059,7 @@ impl<'a> MethodDef<'a> { } let arm_expr = self.call_substructure_method( - cx, trait_, type_ident, self_args.index(&FullRange), nonself_args, + cx, trait_, type_ident, &self_args[], nonself_args, &catch_all_substructure); // Builds the expression: @@ -1263,7 +1263,7 @@ impl<'a> TraitDef<'a> { cx.span_bug(sp, "a struct with named and unnamed fields in `derive`"); } }; - let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); + let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]); paths.push(codemap::Spanned{span: sp, node: ident}); let val = cx.expr( sp, ast::ExprParen(cx.expr_deref(sp, cx.expr_path(cx.path_ident(sp,ident))))); @@ -1309,7 +1309,7 @@ impl<'a> TraitDef<'a> { let mut ident_expr = Vec::new(); for (i, va) in variant_args.iter().enumerate() { let sp = self.set_expn_info(cx, va.ty.span); - let ident = cx.ident_of(format!("{}_{}", prefix, i).index(&FullRange)); + let ident = cx.ident_of(&format!("{}_{}", prefix, i)[]); let path1 = codemap::Spanned{span: sp, node: ident}; paths.push(path1); let expr_path = cx.expr_path(cx.path_ident(sp, ident)); @@ -1352,7 +1352,7 @@ pub fn cs_fold<F>(use_foldl: bool, field.span, old, field.self_.clone(), - field.other.index(&FullRange)) + &field.other[]) }) } else { all_fields.iter().rev().fold(base, |old, field| { @@ -1360,12 +1360,12 @@ pub fn cs_fold<F>(use_foldl: bool, field.span, old, field.self_.clone(), - field.other.index(&FullRange)) + &field.other[]) }) } }, EnumNonMatchingCollapsed(ref all_args, _, tuple) => - enum_nonmatch_f(cx, trait_span, (all_args.index(&FullRange), tuple), + enum_nonmatch_f(cx, trait_span, (&all_args[], tuple), substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") @@ -1405,7 +1405,7 @@ pub fn cs_same_method<F>(f: F, f(cx, trait_span, called) }, EnumNonMatchingCollapsed(ref all_self_args, _, tuple) => - enum_nonmatch_f(cx, trait_span, (all_self_args.index(&FullRange), tuple), + enum_nonmatch_f(cx, trait_span, (&all_self_args[], tuple), substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") diff --git a/src/libsyntax/ext/deriving/hash.rs b/src/libsyntax/ext/deriving/hash.rs index 844bd80d161..db99c142443 100644 --- a/src/libsyntax/ext/deriving/hash.rs +++ b/src/libsyntax/ext/deriving/hash.rs @@ -30,7 +30,8 @@ pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt, let generics = LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__S", - vec!(Path::new(vec!("std", "hash", "Writer"))))), + vec!(Path::new(vec!("std", "hash", "Writer")), + Path::new(vec!("std", "hash", "Hasher"))))), }; let args = Path::new_local("__S"); let inline = cx.meta_word(span, InternedString::new("inline")); diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 43a0e0606f8..603c4478007 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -40,16 +40,6 @@ pub mod totalord; pub mod generic; -pub fn expand_meta_deriving(cx: &mut ExtCtxt, - _span: Span, - mitem: &MetaItem, - item: &Item, - push: Box<FnMut(P<Item>)>) { - cx.span_warn(mitem.span, "`deriving` is deprecated; use `derive`"); - - expand_meta_derive(cx, _span, mitem, item, push) -} - pub fn expand_meta_derive(cx: &mut ExtCtxt, _span: Span, mitem: &MetaItem, @@ -121,9 +111,9 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, ref tname => { cx.span_err(titem.span, - format!("unknown `derive` \ + &format!("unknown `derive` \ trait: `{}`", - *tname).index(&FullRange)); + *tname)[]); } }; } diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 5517019f804..1359cada673 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -98,13 +98,13 @@ fn rand_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) rand_name, vec!(rng.clone())); - // need to specify the uint-ness of the random number - let uint_ty = cx.ty_ident(trait_span, cx.ident_of("uint")); + // need to specify the usize-ness of the random number + let usize_ty = cx.ty_ident(trait_span, cx.ident_of("usize")); let value_ident = cx.ident_of("__value"); let let_statement = cx.stmt_let_typed(trait_span, false, value_ident, - uint_ty, + usize_ty, rv_call); // rand() % variants.len() diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index fa9a7899a12..48034ce50ab 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -127,7 +127,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, let formatter = substr.nonself_args[0].clone(); let meth = cx.ident_of("write_fmt"); - let s = token::intern_and_get_ident(format_string.index(&FullRange)); + let s = token::intern_and_get_ident(&format_string[]); let format_string = cx.expr_str(span, s); // phew, not our responsibility any more! diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index eb3544e3c5c..9b54e259761 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -30,7 +30,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT Some(v) => v }; - let e = match os::getenv(var.index(&FullRange)) { + let e = match os::getenv(&var[]) { None => { cx.expr_path(cx.path_all(sp, true, @@ -56,7 +56,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenT cx.ident_of("Some")), vec!(cx.expr_str(sp, token::intern_and_get_ident( - s.index(&FullRange))))) + &s[])))) } }; MacExpr::new(e) @@ -81,9 +81,9 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) }; let msg = match exprs.next() { None => { - token::intern_and_get_ident(format!("environment variable `{}` \ + token::intern_and_get_ident(&format!("environment variable `{}` \ not defined", - var).index(&FullRange)) + var)[]) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { @@ -106,7 +106,7 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) cx.span_err(sp, msg.get()); cx.expr_uint(sp, 0) } - Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s.index(&FullRange))) + Some(s) => cx.expr_str(sp, token::intern_and_get_ident(&s[])) }; MacExpr::new(e) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 3e1bccf394a..9ef996ac317 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -286,8 +286,8 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, None => { fld.cx.span_err( pth.span, - format!("macro undefined: '{}!'", - extnamestr.get()).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr.get())[]); // let compilation continue None @@ -303,7 +303,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, }, }); let fm = fresh_mark(); - let marked_before = mark_tts(tts.index(&FullRange), fm); + let marked_before = mark_tts(&tts[], fm); // The span that we pass to the expanders we want to // be the root of the call stack. That's the most @@ -314,7 +314,7 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, let opt_parsed = { let expanded = expandfun.expand(fld.cx, mac_span, - marked_before.index(&FullRange)); + &marked_before[]); parse_thunk(expanded) }; let parsed = match opt_parsed { @@ -322,9 +322,9 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, None => { fld.cx.span_err( pth.span, - format!("non-expression macro in expression position: {}", - extnamestr.get().index(&FullRange) - ).index(&FullRange)); + &format!("non-expression macro in expression position: {}", + &extnamestr.get()[] + )[]); return None; } }; @@ -333,8 +333,8 @@ fn expand_mac_invoc<T, F, G>(mac: ast::Mac, span: codemap::Span, _ => { fld.cx.span_err( pth.span, - format!("'{}' is not a tt-style macro", - extnamestr.get()).index(&FullRange)); + &format!("'{}' is not a tt-style macro", + extnamestr.get())[]); None } } @@ -439,7 +439,7 @@ pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander) if valid_ident { fld.cx.mod_push(it.ident); } - let macro_use = contains_macro_use(fld, new_attrs.index(&FullRange)); + let macro_use = contains_macro_use(fld, &new_attrs[]); let result = with_exts_frame!(fld.cx.syntax_env, macro_use, noop_fold_item(it, fld)); @@ -565,8 +565,8 @@ pub fn expand_item_mac(it: P<ast::Item>, let expanded = match fld.cx.syntax_env.find(&extname.name) { None => { fld.cx.span_err(path_span, - format!("macro undefined: '{}!'", - extnamestr).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr)[]); // let compilation continue return SmallVector::zero(); } @@ -576,10 +576,10 @@ pub fn expand_item_mac(it: P<ast::Item>, if it.ident.name != parse::token::special_idents::invalid.name { fld.cx .span_err(path_span, - format!("macro {}! expects no ident argument, \ + &format!("macro {}! expects no ident argument, \ given '{}'", extnamestr, - token::get_ident(it.ident)).index(&FullRange)); + token::get_ident(it.ident))[]); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -591,14 +591,14 @@ pub fn expand_item_mac(it: P<ast::Item>, } }); // mark before expansion: - let marked_before = mark_tts(tts.index(&FullRange), fm); - expander.expand(fld.cx, it.span, marked_before.index(&FullRange)) + let marked_before = mark_tts(&tts[], fm); + expander.expand(fld.cx, it.span, &marked_before[]) } IdentTT(ref expander, span) => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, - format!("macro {}! expects an ident argument", - extnamestr.get()).index(&FullRange)); + &format!("macro {}! expects an ident argument", + extnamestr.get())[]); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -610,14 +610,14 @@ pub fn expand_item_mac(it: P<ast::Item>, } }); // mark before expansion: - let marked_tts = mark_tts(tts.index(&FullRange), fm); + let marked_tts = mark_tts(&tts[], fm); expander.expand(fld.cx, it.span, it.ident, marked_tts) } MacroRulesTT => { if it.ident.name == parse::token::special_idents::invalid.name { fld.cx.span_err(path_span, - format!("macro_rules! expects an ident argument") - .index(&FullRange)); + &format!("macro_rules! expects an ident argument") + []); return SmallVector::zero(); } fld.cx.bt_push(ExpnInfo { @@ -648,8 +648,8 @@ pub fn expand_item_mac(it: P<ast::Item>, } _ => { fld.cx.span_err(it.span, - format!("{}! is not legal in item position", - extnamestr.get()).index(&FullRange)); + &format!("{}! is not legal in item position", + extnamestr.get())[]); return SmallVector::zero(); } } @@ -667,8 +667,8 @@ pub fn expand_item_mac(it: P<ast::Item>, } None => { fld.cx.span_err(path_span, - format!("non-item macro in item position: {}", - extnamestr.get()).index(&FullRange)); + &format!("non-item macro in item position: {}", + extnamestr.get())[]); return SmallVector::zero(); } }; @@ -913,8 +913,8 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { let marked_after = match fld.cx.syntax_env.find(&extname.name) { None => { fld.cx.span_err(pth.span, - format!("macro undefined: '{}!'", - extnamestr).index(&FullRange)); + &format!("macro undefined: '{}!'", + extnamestr)[]); // let compilation continue return DummyResult::raw_pat(span); } @@ -931,19 +931,19 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { }); let fm = fresh_mark(); - let marked_before = mark_tts(tts.index(&FullRange), fm); + let marked_before = mark_tts(&tts[], fm); let mac_span = fld.cx.original_span(); let expanded = match expander.expand(fld.cx, mac_span, - marked_before.index(&FullRange)).make_pat() { + &marked_before[]).make_pat() { Some(e) => e, None => { fld.cx.span_err( pth.span, - format!( + &format!( "non-pattern macro in pattern position: {}", extnamestr.get() - ).index(&FullRange) + )[] ); return DummyResult::raw_pat(span); } @@ -954,8 +954,8 @@ fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> { } _ => { fld.cx.span_err(span, - format!("{}! is not legal in pattern position", - extnamestr.get()).index(&FullRange)); + &format!("{}! is not legal in pattern position", + extnamestr.get())[]); return DummyResult::raw_pat(span); } } @@ -1232,7 +1232,7 @@ impl Folder for Marker { node: match node { MacInvocTT(path, tts, ctxt) => { MacInvocTT(self.fold_path(path), - self.fold_tts(tts.index(&FullRange)), + self.fold_tts(&tts[]), mtwt::apply_mark(self.mark, ctxt)) } }, @@ -1295,7 +1295,7 @@ impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> { #[cfg(test)] mod test { - use super::{pattern_bindings, expand_crate, contains_macro_use}; + use super::{pattern_bindings, expand_crate}; use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig}; use ast; use ast::{Attribute_, AttrOuter, MetaWord, Name}; @@ -1404,22 +1404,6 @@ mod test { expand_crate(&sess, test_ecfg(), vec!(), vec!(), crate_ast); } - // make a MetaWord outer attribute with the given name - fn make_dummy_attr(s: &str) -> ast::Attribute { - Spanned { - span:codemap::DUMMY_SP, - node: Attribute_ { - id: attr::mk_attr_id(), - style: AttrOuter, - value: P(Spanned { - node: MetaWord(token::intern_and_get_ident(s)), - span: codemap::DUMMY_SP, - }), - is_sugared_doc: false, - } - } - } - fn expand_crate_str(crate_str: String) -> ast::Crate { let ps = parse::new_parse_sess(); let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod(); @@ -1655,7 +1639,7 @@ mod test { let varref_idents : Vec<ast::Ident> = varref.segments.iter().map(|s| s.identifier) .collect(); - println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name); + println!("varref #{}: {:?}, resolves to {}",idx, varref_idents, varref_name); let string = token::get_ident(final_varref_ident); println!("varref's first segment's string: \"{}\"", string.get()); println!("binding #{}: {}, resolves to {}", @@ -1713,7 +1697,7 @@ foo_module!(); let string = ident.get(); "xx" == string }).collect(); - let cxbinds: &[&ast::Ident] = cxbinds.index(&FullRange); + let cxbinds: &[&ast::Ident] = &cxbinds[]; let cxbind = match cxbinds { [b] => b, _ => panic!("expected just one binding for ext_cx") diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs deleted file mode 100644 index 5352cfaf749..00000000000 --- a/src/libsyntax/ext/fmt.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Deprecated fmt! syntax extension - -use ast; -use codemap::Span; -use ext::base; -use ext::build::AstBuilder; - - -pub fn expand_syntax_ext(ecx: &mut base::ExtCtxt, - sp: Span, - _tts: &[ast::TokenTree]) - -> Box<base::MacResult+'static> { - ecx.span_err(sp, "`fmt!` is deprecated, use `format!` instead"); - ecx.parse_sess.span_diagnostic.span_note(sp, - "see http://doc.rust-lang.org/std/fmt/ \ - for documentation"); - - base::MacExpr::new(ecx.expr_uint(sp, 2)) -} diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 44a596d2657..637b6d4649d 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -112,8 +112,8 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } _ => { ecx.span_err(p.span, - format!("expected ident for named argument, found `{}`", - p.this_token_to_string()).index(&FullRange)); + &format!("expected ident for named argument, found `{}`", + p.this_token_to_string())[]); return None; } }; @@ -125,8 +125,8 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) None => {} Some(prev) => { ecx.span_err(e.span, - format!("duplicate argument named `{}`", - name).index(&FullRange)); + &format!("duplicate argument named `{}`", + name)[]); ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here"); continue } @@ -217,7 +217,7 @@ impl<'a, 'b> Context<'a, 'b> { let msg = format!("invalid reference to argument `{}` ({})", arg, self.describe_num_args()); - self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); + self.ecx.span_err(self.fmtsp, &msg[]); return; } { @@ -237,7 +237,7 @@ impl<'a, 'b> Context<'a, 'b> { Some(e) => e.span, None => { let msg = format!("there is no argument named `{}`", name); - self.ecx.span_err(self.fmtsp, msg.index(&FullRange)); + self.ecx.span_err(self.fmtsp, &msg[]); return; } }; @@ -277,22 +277,22 @@ impl<'a, 'b> Context<'a, 'b> { match (cur, ty) { (&Known(ref cur), &Known(ref ty)) => { self.ecx.span_err(sp, - format!("argument redeclared with type `{}` when \ + &format!("argument redeclared with type `{}` when \ it was previously `{}`", *ty, - *cur).index(&FullRange)); + *cur)[]); } (&Known(ref cur), _) => { self.ecx.span_err(sp, - format!("argument used to format with `{}` was \ + &format!("argument used to format with `{}` was \ attempted to not be used for formatting", - *cur).index(&FullRange)); + *cur)[]); } (_, &Known(ref ty)) => { self.ecx.span_err(sp, - format!("argument previously used as a format \ + &format!("argument previously used as a format \ argument attempted to be used as `{}`", - *ty).index(&FullRange)); + *ty)[]); } (_, _) => { self.ecx.span_err(sp, "argument declared with multiple formats"); @@ -357,7 +357,7 @@ impl<'a, 'b> Context<'a, 'b> { /// Translate the accumulated string literals to a literal expression fn trans_literal_string(&mut self) -> P<ast::Expr> { let sp = self.fmtsp; - let s = token::intern_and_get_ident(self.literal.index(&FullRange)); + let s = token::intern_and_get_ident(&self.literal[]); self.literal.clear(); self.ecx.expr_str(sp, s) } @@ -509,7 +509,7 @@ impl<'a, 'b> Context<'a, 'b> { None => continue // error already generated }; - let name = self.ecx.ident_of(format!("__arg{}", i).index(&FullRange)); + let name = self.ecx.ident_of(&format!("__arg{}", i)[]); pats.push(self.ecx.pat_ident(e.span, name)); locals.push(Context::format_arg(self.ecx, e.span, arg_ty, self.ecx.expr_ident(e.span, name))); @@ -525,8 +525,8 @@ impl<'a, 'b> Context<'a, 'b> { None => continue }; - let lname = self.ecx.ident_of(format!("__arg{}", - *name).index(&FullRange)); + let lname = self.ecx.ident_of(&format!("__arg{}", + *name)[]); pats.push(self.ecx.pat_ident(e.span, lname)); names[self.name_positions[*name]] = Some(Context::format_arg(self.ecx, e.span, arg_ty, @@ -606,7 +606,7 @@ impl<'a, 'b> Context<'a, 'b> { -> P<ast::Expr> { let trait_ = match *ty { Known(ref tyname) => { - match tyname.index(&FullRange) { + match &tyname[] { "" => "String", "?" => "Show", "e" => "LowerExp", @@ -618,8 +618,8 @@ impl<'a, 'b> Context<'a, 'b> { "X" => "UpperHex", _ => { ecx.span_err(sp, - format!("unknown format trait `{}`", - *tyname).index(&FullRange)); + &format!("unknown format trait `{}`", + *tyname)[]); "Dummy" } } @@ -709,8 +709,8 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, } } if !parser.errors.is_empty() { - cx.ecx.span_err(cx.fmtsp, format!("invalid format string: {}", - parser.errors.remove(0)).index(&FullRange)); + cx.ecx.span_err(cx.fmtsp, &format!("invalid format string: {}", + parser.errors.remove(0))[]); return DummyResult::raw_expr(sp); } if !cx.literal.is_empty() { diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index bebd803ac4f..ae8ff118fcc 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -223,7 +223,7 @@ pub fn marksof(ctxt: SyntaxContext, stopname: Name) -> Vec<Mrk> { } // the internal function for computing marks -// it's not clear to me whether it's better to use a .index(&FullRange) mutable +// it's not clear to me whether it's better to use a [] mutable // vector or a cons-list for this. fn marksof_internal(ctxt: SyntaxContext, stopname: Name, diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 77aea0c370a..c42b188302c 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -244,10 +244,10 @@ pub mod rt { } macro_rules! impl_to_source_int { - (signed, $t:ty, $tag:ident) => ( + (signed, $t:ty, $tag:expr) => ( impl ToSource for $t { fn to_source(&self) -> String { - let lit = ast::LitInt(*self as u64, ast::SignedIntLit(ast::$tag, + let lit = ast::LitInt(*self as u64, ast::SignedIntLit($tag, ast::Sign::new(*self))); pprust::lit_to_string(&dummy_spanned(lit)) } @@ -258,10 +258,10 @@ pub mod rt { } } ); - (unsigned, $t:ty, $tag:ident) => ( + (unsigned, $t:ty, $tag:expr) => ( impl ToSource for $t { fn to_source(&self) -> String { - let lit = ast::LitInt(*self as u64, ast::UnsignedIntLit(ast::$tag)); + let lit = ast::LitInt(*self as u64, ast::UnsignedIntLit($tag)); pprust::lit_to_string(&dummy_spanned(lit)) } } @@ -273,17 +273,17 @@ pub mod rt { ); } - impl_to_source_int! { signed, int, TyIs } - impl_to_source_int! { signed, i8, TyI8 } - impl_to_source_int! { signed, i16, TyI16 } - impl_to_source_int! { signed, i32, TyI32 } - impl_to_source_int! { signed, i64, TyI64 } + impl_to_source_int! { signed, int, ast::TyIs(false) } + impl_to_source_int! { signed, i8, ast::TyI8 } + impl_to_source_int! { signed, i16, ast::TyI16 } + impl_to_source_int! { signed, i32, ast::TyI32 } + impl_to_source_int! { signed, i64, ast::TyI64 } - impl_to_source_int! { unsigned, uint, TyUs } - impl_to_source_int! { unsigned, u8, TyU8 } - impl_to_source_int! { unsigned, u16, TyU16 } - impl_to_source_int! { unsigned, u32, TyU32 } - impl_to_source_int! { unsigned, u64, TyU64 } + impl_to_source_int! { unsigned, uint, ast::TyUs(false) } + impl_to_source_int! { unsigned, u8, ast::TyU8 } + impl_to_source_int! { unsigned, u16, ast::TyU16 } + impl_to_source_int! { unsigned, u32, ast::TyU32 } + impl_to_source_int! { unsigned, u64, ast::TyU64 } // Alas ... we write these out instead. All redundant. @@ -473,7 +473,7 @@ pub fn expand_quote_stmt(cx: &mut ExtCtxt, } fn ids_ext(strs: Vec<String> ) -> Vec<ast::Ident> { - strs.iter().map(|str| str_to_ident((*str).index(&FullRange))).collect() + strs.iter().map(|str| str_to_ident(&(*str)[])).collect() } fn id_ext(str: &str) -> ast::Ident { @@ -675,7 +675,7 @@ fn mk_tt(cx: &ExtCtxt, tt: &ast::TokenTree) -> Vec<P<ast::Stmt>> { for i in range(0, tt.len()) { seq.push(tt.get_tt(i)); } - mk_tts(cx, seq.index(&FullRange)) + mk_tts(cx, &seq[]) } ast::TtToken(sp, ref tok) => { let e_sp = cx.expr_ident(sp, id_ext("_sp")); @@ -764,7 +764,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); let mut vector = vec!(stmt_let_sp, stmt_let_tt); - vector.extend(mk_tts(cx, tts.index(&FullRange)).into_iter()); + vector.extend(mk_tts(cx, &tts[]).into_iter()); let block = cx.expr_block( cx.block_all(sp, Vec::new(), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 1ba91dd371c..31a1a838b13 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -57,7 +57,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = cx.original_span_in_file(); let loc = cx.codemap().lookup_char_pos(topmost.lo); - let filename = token::intern_and_get_ident(loc.file.name.index(&FullRange)); + let filename = token::intern_and_get_ident(&loc.file.name[]); base::MacExpr::new(cx.expr_str(topmost, filename)) } @@ -65,7 +65,7 @@ pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let s = pprust::tts_to_string(tts); base::MacExpr::new(cx.expr_str(sp, - token::intern_and_get_ident(s.index(&FullRange)))) + token::intern_and_get_ident(&s[]))) } pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) @@ -78,7 +78,7 @@ pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) .connect("::"); base::MacExpr::new(cx.expr_str( sp, - token::intern_and_get_ident(string.index(&FullRange)))) + token::intern_and_get_ident(&string[]))) } /// include! : parse the given file as an expr @@ -135,9 +135,9 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let bytes = match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {:?}: {}", + &format!("couldn't read {:?}: {}", file.display(), - e).index(&FullRange)); + e)[]); return DummyResult::expr(sp); } Ok(bytes) => bytes, @@ -147,26 +147,20 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) // Add this input file to the code map to make it available as // dependency information let filename = format!("{:?}", file.display()); - let interned = token::intern_and_get_ident(src.index(&FullRange)); + let interned = token::intern_and_get_ident(&src[]); cx.codemap().new_filemap(filename, src); base::MacExpr::new(cx.expr_str(sp, interned)) } Err(_) => { cx.span_err(sp, - format!("{:?} wasn't a utf-8 file", - file.display()).index(&FullRange)); + &format!("{:?} wasn't a utf-8 file", + file.display())[]); return DummyResult::expr(sp); } } } -pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) - -> Box<base::MacResult+'static> { - cx.span_warn(sp, "include_bin! is deprecated; use include_bytes! instead"); - expand_include_bytes(cx, sp, tts) -} - pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'static> { let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") { @@ -177,7 +171,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {:?}: {}", file.display(), e).index(&FullRange)); + &format!("couldn't read {:?}: {}", file.display(), e)[]); return DummyResult::expr(sp); } Ok(bytes) => { diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index d33d03bbfa9..9eda4bcef99 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -153,7 +153,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { seq.num_captures } &TtDelimited(_, ref delim) => { - count_names(delim.tts.index(&FullRange)) + count_names(&delim.tts[]) } &TtToken(_, MatchNt(..)) => { 1 @@ -165,7 +165,7 @@ pub fn count_names(ms: &[TokenTree]) -> uint { pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { - let match_idx_hi = count_names(ms.index(&FullRange)); + let match_idx_hi = count_names(&ms[]); let matches: Vec<_> = range(0, match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], @@ -228,8 +228,8 @@ pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) let string = token::get_ident(bind_name); p_s.span_diagnostic .span_fatal(sp, - format!("duplicated bind name: {}", - string.get()).index(&FullRange)) + &format!("duplicated bind name: {}", + string.get())[]) } } } @@ -254,13 +254,13 @@ pub fn parse_or_else(sess: &ParseSess, rdr: TtReader, ms: Vec<TokenTree> ) -> HashMap<Ident, Rc<NamedMatch>> { - match parse(sess, cfg, rdr, ms.index(&FullRange)) { + match parse(sess, cfg, rdr, &ms[]) { Success(m) => m, Failure(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) + sess.span_diagnostic.span_fatal(sp, &str[]) } Error(sp, str) => { - sess.span_diagnostic.span_fatal(sp, str.index(&FullRange)) + sess.span_diagnostic.span_fatal(sp, &str[]) } } } @@ -447,7 +447,7 @@ pub fn parse(sess: &ParseSess, for dv in (&mut eof_eis[0]).matches.iter_mut() { v.push(dv.pop().unwrap()); } - return Success(nameize(sess, ms, v.index(&FullRange))); + return Success(nameize(sess, ms, &v[])); } else if eof_eis.len() > 1u { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { @@ -532,8 +532,8 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { token::Ident(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { let token_str = pprust::token_to_string(&p.token); - p.fatal((format!("expected ident, found {}", - token_str.index(&FullRange))).index(&FullRange)) + p.fatal(&format!("expected ident, found {}", + &token_str[])[]) } }, "path" => { @@ -541,7 +541,7 @@ pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal { } "meta" => token::NtMeta(p.parse_meta_item()), _ => { - p.fatal(format!("unsupported builtin nonterminal parser: {}", name).index(&FullRange)) + p.fatal(&format!("unsupported builtin nonterminal parser: {}", name)[]) } } } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 64c53e298ef..fc341e3bd85 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -52,7 +52,7 @@ impl<'a> ParserAnyMacro<'a> { following", token_str); let span = parser.span; - parser.span_err(span, msg.index(&FullRange)); + parser.span_err(span, &msg[]); } } } @@ -126,8 +126,8 @@ impl TTMacroExpander for MacroRulesMacroExpander { self.name, self.imported_from, arg, - self.lhses.index(&FullRange), - self.rhses.index(&FullRange)) + &self.lhses[], + &self.rhses[]) } } @@ -154,7 +154,7 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, match **lhs { MatchedNonterminal(NtTT(ref lhs_tt)) => { let lhs_tt = match **lhs_tt { - TtDelimited(_, ref delim) => delim.tts.index(&FullRange), + TtDelimited(_, ref delim) => &delim.tts[], _ => cx.span_fatal(sp, "malformed macro lhs") }; // `None` is because we're not interpolating @@ -195,13 +195,13 @@ fn generic_extension<'cx>(cx: &'cx ExtCtxt, best_fail_spot = sp; best_fail_msg = (*msg).clone(); }, - Error(sp, ref msg) => cx.span_fatal(sp, msg.index(&FullRange)) + Error(sp, ref msg) => cx.span_fatal(sp, &msg[]) } } _ => cx.bug("non-matcher found in parsed lhses") } } - cx.span_fatal(best_fail_spot, best_fail_msg.index(&FullRange)); + cx.span_fatal(best_fail_spot, &best_fail_msg[]); } // Note that macro-by-example's input is also matched against a token tree: diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index bc07c7f6cae..94b8356130a 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -255,7 +255,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { } LisContradiction(ref msg) => { // FIXME #2887 blame macro invoker instead - r.sp_diag.span_fatal(sp.clone(), msg.index(&FullRange)); + r.sp_diag.span_fatal(sp.clone(), &msg[]); } LisConstraint(len, _) => { if len == 0 { @@ -308,8 +308,8 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { MatchedSeq(..) => { r.sp_diag.span_fatal( r.cur_span, /* blame the macro writer */ - format!("variable '{:?}' is still repeating at this depth", - token::get_ident(ident)).index(&FullRange)); + &format!("variable '{:?}' is still repeating at this depth", + token::get_ident(ident))[]); } } } diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index f10113254de..8175c0a9eec 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -70,6 +70,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("associated_types", Accepted), ("visible_private_types", Active), ("slicing_syntax", Active), + ("box_syntax", Active), ("if_let", Accepted), ("while_let", Accepted), @@ -81,7 +82,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("issue_5723_bootstrap", Accepted), // A way to temporarily opt out of opt in copy. This will *never* be accepted. - ("opt_out_copy", Deprecated), + ("opt_out_copy", Removed), // A way to temporarily opt out of the new orphan rules. This will *never* be accepted. ("old_orphan_check", Deprecated), @@ -92,6 +93,9 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ // OIBIT specific features ("optin_builtin_traits", Active), + // int and uint are now deprecated + ("int_uint", Active), + // These are used to test this portion of the compiler, they don't actually // mean anything ("test_accepted_feature", Accepted), @@ -122,7 +126,6 @@ pub struct Features { pub import_shadowing: bool, pub visible_private_types: bool, pub quote: bool, - pub opt_out_copy: bool, pub old_orphan_check: bool, } @@ -134,7 +137,6 @@ impl Features { import_shadowing: false, visible_private_types: false, quote: false, - opt_out_copy: false, old_orphan_check: false, } } @@ -150,12 +152,20 @@ impl<'a> Context<'a> { fn gate_feature(&self, feature: &str, span: Span, explain: &str) { if !self.has_feature(feature) { self.span_handler.span_err(span, explain); - self.span_handler.span_help(span, format!("add #![feature({})] to the \ + self.span_handler.span_help(span, &format!("add #![feature({})] to the \ crate attributes to enable", - feature).index(&FullRange)); + feature)[]); } } + fn warn_feature(&self, feature: &str, span: Span, explain: &str) { + if !self.has_feature(feature) { + self.span_handler.span_warn(span, explain); + self.span_handler.span_help(span, &format!("add #![feature({})] to the \ + crate attributes to silence this warning", + feature)[]); + } + } fn has_feature(&self, feature: &str) -> bool { self.features.iter().any(|&n| n == feature) } @@ -243,7 +253,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } match i.node { ast::ItemForeignMod(ref foreign_module) => { - if attr::contains_name(i.attrs.index(&FullRange), "link_args") { + if attr::contains_name(&i.attrs[], "link_args") { self.gate_feature("link_args", i.span, "the `link_args` attribute is not portable \ across platforms, it is recommended to \ @@ -257,14 +267,14 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } ast::ItemFn(..) => { - if attr::contains_name(i.attrs.index(&FullRange), "plugin_registrar") { + if attr::contains_name(&i.attrs[], "plugin_registrar") { self.gate_feature("plugin_registrar", i.span, "compiler plugins are experimental and possibly buggy"); } } ast::ItemStruct(..) => { - if attr::contains_name(i.attrs.index(&FullRange), "simd") { + if attr::contains_name(&i.attrs[], "simd") { self.gate_feature("simd", i.span, "SIMD types are experimental and possibly buggy"); } @@ -290,7 +300,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { removed in the future"); } - if attr::contains_name(i.attrs.index(&FullRange), + if attr::contains_name(&i.attrs[], "old_orphan_check") { self.gate_feature( "old_orphan_check", @@ -298,7 +308,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { "the new orphan check rules will eventually be strictly enforced"); } - if attr::contains_name(i.attrs.index(&FullRange), + if attr::contains_name(&i.attrs[], "old_impl_check") { self.gate_feature("old_impl_check", i.span, @@ -313,7 +323,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_foreign_item(&mut self, i: &ast::ForeignItem) { - if attr::contains_name(i.attrs.index(&FullRange), "linkage") { + if attr::contains_name(&i.attrs[], "linkage") { self.gate_feature("linkage", i.span, "the `linkage` attribute is experimental \ and not portable across platforms") @@ -333,15 +343,60 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { } fn visit_ty(&mut self, t: &ast::Ty) { + match t.node { + ast::TyPath(ref p, _) => { + match &*p.segments { + + [ast::PathSegment { identifier, .. }] => { + let name = token::get_ident(identifier); + let msg = if name == "int" { + Some("the `int` type is deprecated; \ + use `isize` or a fixed-sized integer") + } else if name == "uint" { + Some("the `uint` type is deprecated; \ + use `usize` or a fixed-sized integer") + } else { + None + }; + + if let Some(msg) = msg { + self.context.warn_feature("int_uint", t.span, msg) + } + } + _ => {} + } + } + _ => {} + } visit::walk_ty(self, t); } fn visit_expr(&mut self, e: &ast::Expr) { match e.node { - ast::ExprRange(..) => { - self.gate_feature("slicing_syntax", + ast::ExprBox(..) | ast::ExprUnary(ast::UnOp::UnUniq, _) => { + self.gate_feature("box_syntax", e.span, - "range syntax is experimental"); + "box expression syntax is experimental in alpha release; \ + you can call `Box::new` instead."); + } + ast::ExprLit(ref lit) => { + match lit.node { + ast::LitInt(_, ty) => { + let msg = if let ast::SignedIntLit(ast::TyIs(true), _) = ty { + Some("the `i` suffix on integers is deprecated; use `is` \ + or one of the fixed-sized suffixes") + } else if let ast::UnsignedIntLit(ast::TyUs(true)) = ty { + Some("the `u` suffix on integers is deprecated; use `us` \ + or one of the fixed-sized suffixes") + } else { + None + }; + if let Some(msg) = msg { + self.context.warn_feature("int_uint", e.span, msg); + } + } + _ => {} + } } _ => {} } @@ -365,6 +420,11 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { but at the end of a slice (e.g. \ `[0, ..xs, 0]` are experimental") } + ast::PatBox(..) => { + self.gate_feature("box_syntax", + pattern.span, + "box pattern syntax is experimental in alpha release"); + } _ => {} } visit::walk_pat(self, pattern) @@ -458,7 +518,6 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::C import_shadowing: cx.has_feature("import_shadowing"), visible_private_types: cx.has_feature("visible_private_types"), quote: cx.has_feature("quote"), - opt_out_copy: cx.has_feature("opt_out_copy"), old_orphan_check: cx.has_feature("old_orphan_check"), }, unknown_features) diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 9e14f9dd1ea..9c947f422e9 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -15,7 +15,8 @@ //! This API is completely unstable and subject to change. #![crate_name = "syntax"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -24,7 +25,9 @@ #![allow(unknown_features)] #![feature(slicing_syntax)] +#![feature(box_syntax)] #![feature(quote, unsafe_destructor)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate arena; extern crate fmt_macros; @@ -81,7 +84,6 @@ pub mod ext { pub mod asm; pub mod base; pub mod build; - pub mod bytes; pub mod cfg; pub mod cfg_attr; pub mod concat; @@ -89,7 +91,6 @@ pub mod ext { pub mod deriving; pub mod env; pub mod expand; - pub mod fmt; pub mod format; pub mod log_syntax; pub mod mtwt; diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 4aad7f911db..54ec9c7b146 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -92,7 +92,7 @@ impl<'a> ParserAttr for Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `#`, found `{}`", token_str).index(&FullRange)); + self.fatal(&format!("expected `#`, found `{}`", token_str)[]); } }; diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index e7fc5aac9c7..16ade904be8 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -82,7 +82,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { while j > i && lines[j - 1].trim().is_empty() { j -= 1; } - return lines.index(&(i..j)).iter().map(|x| (*x).clone()).collect(); + return lines[i..j].iter().map(|x| (*x).clone()).collect(); } /// remove a "[ \t]*\*" block from each line, if possible @@ -116,7 +116,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { if can_trim { lines.iter().map(|line| { - line.index(&((i + 1)..line.len())).to_string() + (&line[(i + 1)..line.len()]).to_string() }).collect() } else { lines @@ -127,12 +127,12 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { static ONLINERS: &'static [&'static str] = &["///!", "///", "//!", "//"]; for prefix in ONLINERS.iter() { if comment.starts_with(*prefix) { - return comment.index(&(prefix.len()..)).to_string(); + return (&comment[prefix.len()..]).to_string(); } } if comment.starts_with("/*") { - let lines = comment.index(&(3u..(comment.len() - 2u))) + let lines = comment[3u..(comment.len() - 2u)] .lines_any() .map(|s| s.to_string()) .collect::<Vec<String> >(); @@ -187,7 +187,7 @@ fn read_line_comments(rdr: &mut StringReader, code_to_the_left: bool, let line = rdr.read_one_line_comment(); debug!("{}", line); // Doc comments are not put in comments. - if is_doc_comment(line.index(&FullRange)) { + if is_doc_comment(&line[]) { break; } lines.push(line); @@ -224,10 +224,10 @@ fn all_whitespace(s: &str, col: CharPos) -> Option<uint> { fn trim_whitespace_prefix_and_push_line(lines: &mut Vec<String> , s: String, col: CharPos) { let len = s.len(); - let s1 = match all_whitespace(s.index(&FullRange), col) { + let s1 = match all_whitespace(&s[], col) { Some(col) => { if col < len { - s.index(&(col..len)).to_string() + (&s[col..len]).to_string() } else { "".to_string() } @@ -261,7 +261,7 @@ fn read_block_comment(rdr: &mut StringReader, rdr.bump(); rdr.bump(); } - if is_block_doc_comment(curr_line.index(&FullRange)) { + if is_block_doc_comment(&curr_line[]) { return } assert!(!curr_line.contains_char('\n')); diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 153b18b8760..4cdafb36eec 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -196,7 +196,7 @@ impl<'a> StringReader<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } - self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); + self.fatal_span_(from_pos, to_pos, &m[]); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an @@ -205,7 +205,7 @@ impl<'a> StringReader<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } - self.err_span_(from_pos, to_pos, m.index(&FullRange)); + self.err_span_(from_pos, to_pos, &m[]); } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the @@ -214,8 +214,8 @@ impl<'a> StringReader<'a> { m.push_str(": "); let from = self.byte_offset(from_pos).to_uint(); let to = self.byte_offset(to_pos).to_uint(); - m.push_str(self.filemap.src.index(&(from..to))); - self.fatal_span_(from_pos, to_pos, m.index(&FullRange)); + m.push_str(&self.filemap.src[from..to]); + self.fatal_span_(from_pos, to_pos, &m[]); } /// Advance peek_tok and peek_span to refer to the next token, and @@ -301,7 +301,7 @@ impl<'a> StringReader<'a> { while i < s.len() { let str::CharRange { ch, next } = s.char_range_at(i); if ch == '\r' { - if j < i { buf.push_str(s.index(&(j..i))); } + if j < i { buf.push_str(&s[j..i]); } j = next; if next >= s.len() || s.char_at(next) != '\n' { let pos = start + BytePos(i as u32); @@ -311,7 +311,7 @@ impl<'a> StringReader<'a> { } i = next; } - if j < s.len() { buf.push_str(s.index(&(j..))); } + if j < s.len() { buf.push_str(&s[j..]); } buf } } @@ -556,7 +556,7 @@ impl<'a> StringReader<'a> { self.translate_crlf(start_bpos, string, "bare CR not allowed in block doc-comment") } else { string.into_cow() }; - token::DocComment(token::intern(string.index(&FullRange))) + token::DocComment(token::intern(&string[])) } else { token::Comment }; @@ -1110,7 +1110,7 @@ impl<'a> StringReader<'a> { // expansion purposes. See #12512 for the gory details of why // this is necessary. let ident = self.with_str_from(start, |lifetime_name| { - str_to_ident(format!("'{}", lifetime_name).index(&FullRange)) + str_to_ident(&format!("'{}", lifetime_name)[]) }); // Conjure up a "keyword checking ident" to make sure that diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index d26b3af67bd..f1f547ba0c7 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -253,19 +253,19 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option<Span>) let bytes = match File::open(path).read_to_end() { Ok(bytes) => bytes, Err(e) => { - err(format!("couldn't read {:?}: {:?}", + err(&format!("couldn't read {:?}: {:?}", path.display(), - e).index(&FullRange)); + e)[]); unreachable!() } }; - match str::from_utf8(bytes.index(&FullRange)).ok() { + match str::from_utf8(&bytes[]).ok() { Some(s) => { return string_to_filemap(sess, s.to_string(), path.as_str().unwrap().to_string()) } None => { - err(format!("{:?} is not UTF-8 encoded", path.display()).index(&FullRange)) + err(&format!("{:?} is not UTF-8 encoded", path.display())[]) } } unreachable!() @@ -399,10 +399,10 @@ pub fn char_lit(lit: &str) -> (char, int) { } let msg = format!("lexer should have rejected a bad character escape {}", lit); - let msg2 = msg.index(&FullRange); + let msg2 = &msg[]; fn esc(len: uint, lit: &str) -> Option<(char, int)> { - num::from_str_radix(lit.index(&(2..len)), 16) + num::from_str_radix(&lit[2..len], 16) .and_then(char::from_u32) .map(|x| (x, len as int)) } @@ -410,7 +410,7 @@ pub fn char_lit(lit: &str) -> (char, int) { let unicode_escape = |&: | -> Option<(char, int)> if lit.as_bytes()[2] == b'{' { let idx = lit.find('}').expect(msg2); - let subslice = lit.index(&(3..idx)); + let subslice = &lit[3..idx]; num::from_str_radix(subslice, 16) .and_then(char::from_u32) .map(|x| (x, subslice.chars().count() as int + 4)) @@ -472,7 +472,7 @@ pub fn str_lit(lit: &str) -> String { eat(&mut chars); } else { // otherwise, a normal escape - let (c, n) = char_lit(lit.index(&(i..))); + let (c, n) = char_lit(&lit[i..]); for _ in range(0, n - 1) { // we don't need to move past the first \ chars.next(); } @@ -535,7 +535,7 @@ pub fn raw_str_lit(lit: &str) -> String { fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { s.len() > 1 && first_chars.contains(&s.char_at(0)) && - s.index(&(1..)).chars().all(|c| '0' <= c && c <= '9') + s[1..].chars().all(|c| '0' <= c && c <= '9') } fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, @@ -548,7 +548,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, if suf.len() >= 2 && looks_like_width_suffix(&['f'], suf) { // if it looks like a width, lets try to be helpful. sd.span_err(sp, &*format!("illegal width `{}` for float literal, \ - valid widths are 32 and 64", suf.index(&(1..)))); + valid widths are 32 and 64", &suf[1..])); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for float literal, \ valid suffixes are `f32` and `f64`", suf)); @@ -584,7 +584,7 @@ pub fn byte_lit(lit: &str) -> (u8, uint) { b'\'' => b'\'', b'0' => b'\0', _ => { - match ::std::num::from_str_radix::<u64>(lit.index(&(2..4)), 16) { + match ::std::num::from_str_radix::<u64>(&lit[2..4], 16) { Some(c) => if c > 0xFF { panic!(err(2)) @@ -634,7 +634,7 @@ pub fn binary_lit(lit: &str) -> Rc<Vec<u8>> { } _ => { // otherwise, a normal escape - let (c, n) = byte_lit(lit.index(&(i..))); + let (c, n) = byte_lit(&lit[i..]); // we don't need to move past the first \ for _ in range(0, n - 1) { chars.next(); @@ -663,7 +663,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> // s can only be ascii, byte indexing is fine let s2 = s.chars().filter(|&c| c != '_').collect::<String>(); - let mut s = s2.index(&FullRange); + let mut s = &s2[]; debug!("integer_lit: {}, {:?}", s, suffix); @@ -696,20 +696,20 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } if base != 10 { - s = s.index(&(2..)); + s = &s[2..]; } if let Some(suf) = suffix { if suf.is_empty() { sd.span_bug(sp, "found empty literal suffix in Some")} ty = match suf { - "i" => ast::SignedIntLit(ast::TyIs, ast::Plus), - "is" => ast::SignedIntLit(ast::TyIs, ast::Plus), + "i" => ast::SignedIntLit(ast::TyIs(true), ast::Plus), + "is" => ast::SignedIntLit(ast::TyIs(false), ast::Plus), "i8" => ast::SignedIntLit(ast::TyI8, ast::Plus), "i16" => ast::SignedIntLit(ast::TyI16, ast::Plus), "i32" => ast::SignedIntLit(ast::TyI32, ast::Plus), "i64" => ast::SignedIntLit(ast::TyI64, ast::Plus), - "u" => ast::UnsignedIntLit(ast::TyUs), - "us" => ast::UnsignedIntLit(ast::TyUs), + "u" => ast::UnsignedIntLit(ast::TyUs(true)), + "us" => ast::UnsignedIntLit(ast::TyUs(false)), "u8" => ast::UnsignedIntLit(ast::TyU8), "u16" => ast::UnsignedIntLit(ast::TyU16), "u32" => ast::UnsignedIntLit(ast::TyU32), @@ -720,7 +720,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> if looks_like_width_suffix(&['i', 'u'], suf) { sd.span_err(sp, &*format!("illegal width `{}` for integer literal; \ valid widths are 8, 16, 32 and 64", - suf.index(&(1..)))); + &suf[1..])); } else { sd.span_err(sp, &*format!("illegal suffix `{}` for numeric literal", suf)); } @@ -818,7 +818,7 @@ mod test { #[test] fn string_to_tts_macro () { let tts = string_to_tts("macro_rules! zip (($a)=>($a))".to_string()); - let tts: &[ast::TokenTree] = tts.index(&FullRange); + let tts: &[ast::TokenTree] = &tts[]; match tts { [ast::TtToken(_, token::Ident(name_macro_rules, token::Plain)), ast::TtToken(_, token::Not), @@ -826,19 +826,19 @@ mod test { ast::TtDelimited(_, ref macro_delimed)] if name_macro_rules.as_str() == "macro_rules" && name_zip.as_str() == "zip" => { - match macro_delimed.tts.index(&FullRange) { + match ¯o_delimed.tts[] { [ast::TtDelimited(_, ref first_delimed), ast::TtToken(_, token::FatArrow), ast::TtDelimited(_, ref second_delimed)] if macro_delimed.delim == token::Paren => { - match first_delimed.tts.index(&FullRange) { + match &first_delimed.tts[] { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if first_delimed.delim == token::Paren && name.as_str() == "a" => {}, _ => panic!("value 3: {:?}", **first_delimed), } - match second_delimed.tts.index(&FullRange) { + match &second_delimed.tts[] { [ast::TtToken(_, token::Dollar), ast::TtToken(_, token::Ident(name, token::Plain))] if second_delimed.delim == token::Paren @@ -1116,24 +1116,24 @@ mod test { let use_s = "use foo::bar::baz;"; let vitem = string_to_view_item(use_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), use_s); + assert_eq!(&vitem_s[], use_s); let use_s = "use foo::bar as baz;"; let vitem = string_to_view_item(use_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), use_s); + assert_eq!(&vitem_s[], use_s); } #[test] fn parse_extern_crate() { let ex_s = "extern crate foo;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), ex_s); + assert_eq!(&vitem_s[], ex_s); let ex_s = "extern crate \"foo\" as bar;"; let vitem = string_to_view_item(ex_s.to_string()); let vitem_s = view_item_to_string(&vitem); - assert_eq!(vitem_s.index(&FullRange), ex_s); + assert_eq!(&vitem_s[], ex_s); } fn get_spans_of_pat_idents(src: &str) -> Vec<Span> { @@ -1212,7 +1212,7 @@ mod test { let docs = item.attrs.iter().filter(|a| a.name().get() == "doc") .map(|a| a.value_str().unwrap().get().to_string()).collect::<Vec<_>>(); let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()]; - assert_eq!(docs.index(&FullRange), b); + assert_eq!(&docs[], b); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); let item = parse_item_from_source_str(name, source, Vec::new(), &sess).unwrap(); diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 23728c74ae8..e9e207e7dbc 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -127,13 +127,13 @@ impl<'a> ParserObsoleteMethods for parser::Parser<'a> { kind_str: &str, desc: &str) { self.span_err(sp, - format!("obsolete syntax: {}", kind_str).index(&FullRange)); + &format!("obsolete syntax: {}", kind_str)[]); if !self.obsolete_set.contains(&kind) { self.sess .span_diagnostic .handler() - .note(format!("{}", desc).index(&FullRange)); + .note(&format!("{}", desc)[]); self.obsolete_set.insert(kind); } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 9c16dbb2c5c..531e611594a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -16,7 +16,7 @@ use ast::{AssociatedType, BareFnTy}; use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier}; use ast::{ProvidedMethod, Public, Unsafety}; use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue}; -use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block}; +use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block}; use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause}; use ast::{Crate, CrateConfig, Decl, DeclItem}; use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf}; @@ -388,13 +388,13 @@ impl<'a> Parser<'a> { pub fn unexpected_last(&mut self, t: &token::Token) -> ! { let token_str = Parser::token_to_string(t); let last_span = self.last_span; - self.span_fatal(last_span, format!("unexpected token: `{}`", - token_str).index(&FullRange)); + self.span_fatal(last_span, &format!("unexpected token: `{}`", + token_str)[]); } pub fn unexpected(&mut self) -> ! { let this_token = self.this_token_to_string(); - self.fatal(format!("unexpected token: `{}`", this_token).index(&FullRange)); + self.fatal(&format!("unexpected token: `{}`", this_token)[]); } /// Expect and consume the token t. Signal an error if @@ -406,9 +406,9 @@ impl<'a> Parser<'a> { } else { let token_str = Parser::token_to_string(t); let this_token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - this_token_str).index(&FullRange)) + this_token_str)[]) } } else { self.expect_one_of(slice::ref_slice(t), &[]); @@ -449,10 +449,10 @@ impl<'a> Parser<'a> { expected.push_all(&*self.expected_tokens); expected.sort_by(|a, b| a.to_string().cmp(&b.to_string())); expected.dedup(); - let expect = tokens_to_string(expected.index(&FullRange)); + let expect = tokens_to_string(&expected[]); let actual = self.this_token_to_string(); self.fatal( - (if expected.len() != 1 { + &(if expected.len() != 1 { (format!("expected one of {}, found `{}`", expect, actual)) @@ -460,7 +460,7 @@ impl<'a> Parser<'a> { (format!("expected {}, found `{}`", expect, actual)) - }).index(&FullRange) + }[]) ) } } @@ -493,7 +493,7 @@ impl<'a> Parser<'a> { // might be unit-struct construction; check for recoverableinput error. let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); expected.push_all(inedible); - self.check_for_erroneous_unit_struct_expecting(expected.index(&FullRange)); + self.check_for_erroneous_unit_struct_expecting(&expected[]); } self.expect_one_of(edible, inedible) } @@ -510,9 +510,9 @@ impl<'a> Parser<'a> { .as_ref() .map_or(false, |t| t.is_ident() || t.is_path()) { let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>(); - expected.push_all(inedible.index(&FullRange)); + expected.push_all(&inedible[]); self.check_for_erroneous_unit_struct_expecting( - expected.index(&FullRange)); + &expected[]); } self.expect_one_of(edible, inedible) } @@ -534,8 +534,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal((format!("expected ident, found `{}`", - token_str)).index(&FullRange)) + self.fatal(&format!("expected ident, found `{}`", + token_str)[]) } } } @@ -592,8 +592,8 @@ impl<'a> Parser<'a> { if !self.eat_keyword(kw) { let id_interned_str = token::get_name(kw.to_name()); let token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", - id_interned_str, token_str).index(&FullRange)) + self.fatal(&format!("expected `{}`, found `{}`", + id_interned_str, token_str)[]) } } @@ -603,8 +603,8 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); let span = self.span; self.span_err(span, - format!("expected identifier, found keyword `{}`", - token_str).index(&FullRange)); + &format!("expected identifier, found keyword `{}`", + token_str)[]); } } @@ -612,8 +612,8 @@ impl<'a> Parser<'a> { pub fn check_reserved_keywords(&mut self) { if self.token.is_reserved_keyword() { let token_str = self.this_token_to_string(); - self.fatal(format!("`{}` is a reserved keyword", - token_str).index(&FullRange)) + self.fatal(&format!("`{}` is a reserved keyword", + token_str)[]) } } @@ -631,9 +631,9 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); let found_token = Parser::token_to_string(&token::BinOp(token::And)); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", found_token, - token_str).index(&FullRange)) + token_str)[]) } } } @@ -652,9 +652,9 @@ impl<'a> Parser<'a> { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::BinOp(token::Or)); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - found_token).index(&FullRange)) + found_token)[]) } } } @@ -695,9 +695,9 @@ impl<'a> Parser<'a> { if !self.eat_lt() { let found_token = self.this_token_to_string(); let token_str = Parser::token_to_string(&token::Lt); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", token_str, - found_token).index(&FullRange)) + found_token)[]) } } @@ -747,9 +747,9 @@ impl<'a> Parser<'a> { _ => { let gt_str = Parser::token_to_string(&token::Gt); let this_token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", + self.fatal(&format!("expected `{}`, found `{}`", gt_str, - this_token_str).index(&FullRange)) + this_token_str)[]) } } } @@ -1371,7 +1371,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = p.parse_inner_attrs_and_block(); let mut attrs = attrs; - attrs.push_all(inner_attrs.index(&FullRange)); + attrs.push_all(&inner_attrs[]); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, @@ -1389,8 +1389,8 @@ impl<'a> Parser<'a> { _ => { let token_str = p.this_token_to_string(); - p.fatal((format!("expected `;` or `{{`, found `{}`", - token_str)).index(&FullRange)) + p.fatal(&format!("expected `;` or `{{`, found `{}`", + token_str)[]) } } } @@ -1586,7 +1586,7 @@ impl<'a> Parser<'a> { } else { let this_token_str = self.this_token_to_string(); let msg = format!("expected type, found `{}`", this_token_str); - self.fatal(msg.index(&FullRange)); + self.fatal(&msg[]); }; let sp = mk_sp(lo, self.last_span.hi); @@ -1734,8 +1734,7 @@ impl<'a> Parser<'a> { token::StrRaw(s, n) => { (true, LitStr( - token::intern_and_get_ident( - parse::raw_str_lit(s.as_str()).index(&FullRange)), + token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]), ast::RawStr(n))) } token::Binary(i) => @@ -1979,7 +1978,7 @@ impl<'a> Parser<'a> { }; } _ => { - self.fatal(format!("expected a lifetime name").index(&FullRange)); + self.fatal(&format!("expected a lifetime name")[]); } } } @@ -2017,7 +2016,7 @@ impl<'a> Parser<'a> { let msg = format!("expected `,` or `>` after lifetime \ name, found `{}`", this_token_str); - self.fatal(msg.index(&FullRange)); + self.fatal(&msg[]); } } } @@ -2501,16 +2500,16 @@ impl<'a> Parser<'a> { let last_span = self.last_span; let fstr = n.as_str(); self.span_err(last_span, - format!("unexpected token: `{}`", n.as_str()).index(&FullRange)); + &format!("unexpected token: `{}`", n.as_str())[]); if fstr.chars().all(|x| "0123456789.".contains_char(x)) { let float = match fstr.parse::<f64>() { Some(f) => f, None => continue, }; self.span_help(last_span, - format!("try parenthesizing the first index; e.g., `(foo.{}){}`", + &format!("try parenthesizing the first index; e.g., `(foo.{}){}`", float.trunc() as uint, - float.fract().to_string().index(&(1..))).index(&FullRange)); + &float.fract().to_string()[1..])[]); } self.abort_if_errors(); @@ -2536,7 +2535,7 @@ impl<'a> Parser<'a> { } // expr[...] - // An index expression. + // Could be either an index expression or a slicing expression. token::OpenDelim(token::Bracket) => { let bracket_pos = self.span.lo; self.bump(); @@ -2576,22 +2575,6 @@ impl<'a> Parser<'a> { "use `&expr[]` to construct a slice of the whole of expr"); } } - - // A range expression, either `expr..expr` or `expr..`. - token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { - self.bump(); - - let opt_end = if self.token.can_begin_expr() { - let end = self.parse_expr_res(RESTRICTION_NO_DOTS); - Some(end) - } else { - None - }; - - let hi = self.span.hi; - let range = self.mk_range(Some(e), opt_end); - return self.mk_expr(lo, hi, range); - } _ => return e } } @@ -2655,8 +2638,8 @@ impl<'a> Parser<'a> { if self.quote_depth == 0u { match self.token { token::SubstNt(name, _) => - self.fatal(format!("unknown macro variable `{}`", - token::get_ident(name)).index(&FullRange)), + self.fatal(&format!("unknown macro variable `{}`", + token::get_ident(name))[]), _ => {} } } @@ -2717,8 +2700,8 @@ impl<'a> Parser<'a> { Some(&sp) => p.span_note(sp, "unclosed delimiter"), }; let token_str = p.this_token_to_string(); - p.fatal(format!("incorrect close delimiter: `{}`", - token_str).index(&FullRange)) + p.fatal(&format!("incorrect close delimiter: `{}`", + token_str)[]) }, /* we ought to allow different depths of unquotation */ token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => { @@ -2834,7 +2817,7 @@ impl<'a> Parser<'a> { token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { // A range, closed above: `..expr`. self.bump(); - let e = self.parse_prefix_expr(); + let e = self.parse_expr(); hi = e.span.hi; ex = self.mk_range(None, Some(e)); } @@ -2858,8 +2841,8 @@ impl<'a> Parser<'a> { let span = self.span; let this_token_to_string = self.this_token_to_string(); self.span_err(span, - format!("expected expression, found `{}`", - this_token_to_string).index(&FullRange)); + &format!("expected expression, found `{}`", + this_token_to_string)[]); let box_span = mk_sp(lo, self.last_span.hi); self.span_help(box_span, "perhaps you meant `box() (foo)` instead?"); @@ -2901,11 +2884,15 @@ impl<'a> Parser<'a> { self.restrictions.contains(RESTRICTION_NO_BAR_OP) { return lhs; } + self.expected_tokens.push(TokenType::Operator); let cur_opt = self.token.to_binop(); match cur_opt { Some(cur_op) => { + if ast_util::is_comparison_binop(cur_op) { + self.check_no_chained_comparison(&*lhs, cur_op) + } let cur_prec = operator_prec(cur_op); if cur_prec > min_prec { self.bump(); @@ -2934,6 +2921,25 @@ impl<'a> Parser<'a> { } } + /// Produce an error if comparison operators are chained (RFC #558). + /// We only need to check lhs, not rhs, because all comparison ops + /// have same precedence and are left-associative + fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) { + debug_assert!(ast_util::is_comparison_binop(outer_op)); + match lhs.node { + ExprBinary(op, _, _) if ast_util::is_comparison_binop(op) => { + let op_span = self.span; + self.span_err(op_span, + "Chained comparison operators require parentheses"); + if op == BiLt && outer_op == BiGt { + self.span_help(op_span, + "Use ::< instead of < if you meant to specify type arguments."); + } + } + _ => {} + } + } + /// Parse an assignment expression.... /// actually, this seems to be the main entry point for /// parsing an arbitrary expression. @@ -2970,6 +2976,23 @@ impl<'a> Parser<'a> { let assign_op = self.mk_assign_op(aop, lhs, rhs); self.mk_expr(span.lo, rhs_span.hi, assign_op) } + // A range expression, either `expr..expr` or `expr..`. + token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => { + self.bump(); + + let opt_end = if self.token.can_begin_expr() { + let end = self.parse_expr_res(RESTRICTION_NO_DOTS); + Some(end) + } else { + None + }; + + let lo = lhs.span.lo; + let hi = self.span.hi; + let range = self.mk_range(Some(lhs), opt_end); + return self.mk_expr(lo, hi, range); + } + _ => { lhs } @@ -3241,8 +3264,8 @@ impl<'a> Parser<'a> { self.bump(); if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `{}`, found `{}`", "}", - token_str).index(&FullRange)) + self.fatal(&format!("expected `{}`, found `{}`", "}", + token_str)[]) } etc = true; break; @@ -3262,8 +3285,8 @@ impl<'a> Parser<'a> { match bind_type { BindByRef(..) | BindByValue(MutMutable) => { let token_str = self.this_token_to_string(); - self.fatal(format!("unexpected `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("unexpected `{}`", + token_str)[]) } _ => {} } @@ -3546,7 +3569,7 @@ impl<'a> Parser<'a> { let span = self.span; let tok_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected identifier, found `{}`", tok_str).index(&FullRange)); + &format!("expected identifier, found `{}`", tok_str)[]); } let ident = self.parse_ident(); let last_span = self.last_span; @@ -3643,7 +3666,7 @@ impl<'a> Parser<'a> { let lo = self.span.lo; if self.token.is_keyword(keywords::Let) { - check_expected_item(self, item_attrs.index(&FullRange)); + check_expected_item(self, &item_attrs[]); self.expect_keyword(keywords::Let); let decl = self.parse_let(); P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))) @@ -3652,7 +3675,7 @@ impl<'a> Parser<'a> { && self.look_ahead(1, |t| *t == token::Not) { // it's a macro invocation: - check_expected_item(self, item_attrs.index(&FullRange)); + check_expected_item(self, &item_attrs[]); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... @@ -3678,9 +3701,9 @@ impl<'a> Parser<'a> { "" }; let tok_str = self.this_token_to_string(); - self.fatal(format!("expected {}`(` or `{{`, found `{}`", + self.fatal(&format!("expected {}`(` or `{{`, found `{}`", ident_str, - tok_str).index(&FullRange)) + tok_str)[]) }, }; @@ -3728,7 +3751,7 @@ impl<'a> Parser<'a> { } } else { let found_attrs = !item_attrs.is_empty(); - let item_err = Parser::expected_item_err(item_attrs.index(&FullRange)); + let item_err = Parser::expected_item_err(&item_attrs[]); match self.parse_item_or_view_item(item_attrs, false) { IoviItem(i) => { let hi = i.span.hi; @@ -3772,7 +3795,7 @@ impl<'a> Parser<'a> { let sp = self.span; let tok = self.this_token_to_string(); self.span_fatal_help(sp, - format!("expected `{{`, found `{}`", tok).index(&FullRange), + &format!("expected `{{`, found `{}`", tok)[], "place this code inside a block"); } @@ -3826,13 +3849,13 @@ impl<'a> Parser<'a> { while self.token != token::CloseDelim(token::Brace) { // parsing items even when they're not allowed lets us give // better error messages and recover more gracefully. - attributes_box.push_all(self.parse_outer_attributes().index(&FullRange)); + attributes_box.push_all(&self.parse_outer_attributes()[]); match self.token { token::Semi => { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box.index(&FullRange))); + Parser::expected_item_err(&attributes_box[])); attributes_box = Vec::new(); } self.bump(); // empty @@ -3924,7 +3947,7 @@ impl<'a> Parser<'a> { if !attributes_box.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attributes_box.index(&FullRange))); + Parser::expected_item_err(&attributes_box[])); } let hi = self.span.hi; @@ -4367,8 +4390,8 @@ impl<'a> Parser<'a> { }, _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `self`, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected `self`, found `{}`", + token_str)[]) } } } @@ -4521,8 +4544,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `,` or `)`, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected `,` or `)`, found `{}`", + token_str)[]) } } } @@ -4698,7 +4721,7 @@ impl<'a> Parser<'a> { let (inner_attrs, body) = self.parse_inner_attrs_and_block(); let body_span = body.span; let mut new_attrs = attrs; - new_attrs.push_all(inner_attrs.index(&FullRange)); + new_attrs.push_all(&inner_attrs[]); (ast::MethDecl(ident, generics, abi, @@ -4915,17 +4938,17 @@ impl<'a> Parser<'a> { } if fields.len() == 0 { - self.fatal(format!("unit-like struct definition should be \ + self.fatal(&format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone())).index(&FullRange)); + token::get_ident(class_name.clone()))[]); } self.bump(); } else { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `where`, or `{}` after struct \ + self.fatal(&format!("expected `where`, or `{}` after struct \ name, found `{}`", "{", - token_str).index(&FullRange)); + token_str)[]); } fields @@ -4954,9 +4977,9 @@ impl<'a> Parser<'a> { }); if fields.len() == 0 { - self.fatal(format!("unit-like struct definition should be \ + self.fatal(&format!("unit-like struct definition should be \ written as `struct {};`", - token::get_ident(class_name.clone())).index(&FullRange)); + token::get_ident(class_name.clone()))[]); } self.parse_where_clause(generics); @@ -4970,8 +4993,8 @@ impl<'a> Parser<'a> { // This case is where we see: `struct Foo<T>;` } else { let token_str = self.this_token_to_string(); - self.fatal(format!("expected `where`, `{}`, `(`, or `;` after struct \ - name, found `{}`", "{", token_str).index(&FullRange)); + self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \ + name, found `{}`", "{", token_str)[]); } } @@ -4990,8 +5013,8 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal_help(span, - format!("expected `,`, or `}}`, found `{}`", - token_str).index(&FullRange), + &format!("expected `,`, or `}}`, found `{}`", + token_str)[], "struct fields should be separated by commas") } } @@ -5078,7 +5101,7 @@ impl<'a> Parser<'a> { let mut attrs = self.parse_outer_attributes(); if first { let mut tmp = attrs_remaining.clone(); - tmp.push_all(attrs.index(&FullRange)); + tmp.push_all(&attrs[]); attrs = tmp; first = false; } @@ -5094,8 +5117,8 @@ impl<'a> Parser<'a> { } _ => { let token_str = self.this_token_to_string(); - self.fatal(format!("expected item, found `{}`", - token_str).index(&FullRange)) + self.fatal(&format!("expected item, found `{}`", + token_str)[]) } } } @@ -5104,7 +5127,7 @@ impl<'a> Parser<'a> { // We parsed attributes for the first item but didn't find it let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attrs_remaining.index(&FullRange))); + Parser::expected_item_err(&attrs_remaining[])); } ast::Mod { @@ -5174,7 +5197,7 @@ impl<'a> Parser<'a> { -> (ast::Item_, Vec<ast::Attribute> ) { let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span)); prefix.pop(); - let mod_path = Path::new(".").join_many(self.mod_path_stack.index(&FullRange)); + let mod_path = Path::new(".").join_many(&self.mod_path_stack[]); let dir_path = prefix.join(&mod_path); let mod_string = token::get_ident(id); let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name( @@ -5184,8 +5207,8 @@ impl<'a> Parser<'a> { let mod_name = mod_string.get().to_string(); let default_path_str = format!("{}.rs", mod_name); let secondary_path_str = format!("{}/mod.rs", mod_name); - let default_path = dir_path.join(default_path_str.index(&FullRange)); - let secondary_path = dir_path.join(secondary_path_str.index(&FullRange)); + let default_path = dir_path.join(&default_path_str[]); + let secondary_path = dir_path.join(&secondary_path_str[]); let default_exists = default_path.exists(); let secondary_exists = secondary_path.exists(); @@ -5197,16 +5220,16 @@ impl<'a> Parser<'a> { None => self.root_module_name.as_ref().unwrap().clone(), }; self.span_note(id_sp, - format!("maybe move this module `{0}` \ + &format!("maybe move this module `{0}` \ to its own directory via \ `{0}/mod.rs`", - this_module).index(&FullRange)); + this_module)[]); if default_exists || secondary_exists { self.span_note(id_sp, - format!("... or maybe `use` the module \ + &format!("... or maybe `use` the module \ `{}` instead of possibly \ redeclaring it", - mod_name).index(&FullRange)); + mod_name)[]); } self.abort_if_errors(); } @@ -5216,22 +5239,22 @@ impl<'a> Parser<'a> { (false, true) => (secondary_path, true), (false, false) => { self.span_fatal_help(id_sp, - format!("file not found for module `{}`", - mod_name).index(&FullRange), - format!("name the file either {} or {} inside \ + &format!("file not found for module `{}`", + mod_name)[], + &format!("name the file either {} or {} inside \ the directory {:?}", default_path_str, secondary_path_str, - dir_path.display()).index(&FullRange)); + dir_path.display())[]); } (true, true) => { self.span_fatal_help( id_sp, - format!("file for module `{}` found at both {} \ + &format!("file for module `{}` found at both {} \ and {}", mod_name, default_path_str, - secondary_path_str).index(&FullRange), + secondary_path_str)[], "delete or rename one of them to remove the ambiguity"); } } @@ -5253,11 +5276,11 @@ impl<'a> Parser<'a> { let mut err = String::from_str("circular modules: "); let len = included_mod_stack.len(); for p in included_mod_stack.slice(i, len).iter() { - err.push_str(p.display().as_cow().index(&FullRange)); + err.push_str(&p.display().as_cow()[]); err.push_str(" -> "); } - err.push_str(path.display().as_cow().index(&FullRange)); - self.span_fatal(id_sp, err.index(&FullRange)); + err.push_str(&path.display().as_cow()[]); + self.span_fatal(id_sp, &err[]); } None => () } @@ -5338,7 +5361,7 @@ impl<'a> Parser<'a> { if !attrs_remaining.is_empty() { let last_span = self.last_span; self.span_err(last_span, - Parser::expected_item_err(attrs_remaining.index(&FullRange))); + Parser::expected_item_err(&attrs_remaining[])); } assert!(self.token == token::CloseDelim(token::Brace)); ast::ForeignMod { @@ -5377,9 +5400,9 @@ impl<'a> Parser<'a> { self.span_err(span, "expected `;`, found `as`"); self.span_help(span, - format!("perhaps you meant to enclose the crate name `{}` in \ + &format!("perhaps you meant to enclose the crate name `{}` in \ a string?", - the_ident.as_str()).index(&FullRange)); + the_ident.as_str())[]); None } else { None @@ -5403,9 +5426,9 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected extern crate name but \ + &format!("expected extern crate name but \ found `{}`", - token_str).index(&FullRange)); + token_str)[]); } }; @@ -5501,9 +5524,9 @@ impl<'a> Parser<'a> { let struct_def = self.parse_struct_def(); if struct_def.fields.len() == 0 { self.span_err(start_span, - format!("unit-like struct variant should be written \ + &format!("unit-like struct variant should be written \ without braces, as `{},`", - token::get_ident(ident)).index(&FullRange)); + token::get_ident(ident))[]); } kind = StructVariantKind(struct_def); } else if self.check(&token::OpenDelim(token::Paren)) { @@ -5585,10 +5608,10 @@ impl<'a> Parser<'a> { let last_span = self.last_span; self.span_err( last_span, - format!("illegal ABI: expected one of [{}], \ + &format!("illegal ABI: expected one of [{}], \ found `{}`", abi::all_names().connect(", "), - the_string).index(&FullRange)); + the_string)[]); None } } @@ -5647,10 +5670,10 @@ impl<'a> Parser<'a> { if next_is_mod { let last_span = self.last_span; self.span_err(mk_sp(lo, last_span.hi), - format!("`extern mod` is obsolete, use \ + &format!("`extern mod` is obsolete, use \ `extern crate` instead \ to refer to external \ - crates.").index(&FullRange)) + crates.")[]) } return self.parse_item_extern_crate(lo, visibility, attrs); } @@ -5677,8 +5700,8 @@ impl<'a> Parser<'a> { let span = self.span; let token_str = self.this_token_to_string(); self.span_fatal(span, - format!("expected `{}` or `fn`, found `{}`", "{", - token_str).index(&FullRange)); + &format!("expected `{}` or `fn`, found `{}`", "{", + token_str)[]); } if self.eat_keyword(keywords::Virtual) { @@ -5791,7 +5814,7 @@ impl<'a> Parser<'a> { if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = - self.parse_item_mod(attrs.index(&FullRange)); + self.parse_item_mod(&attrs[]); let last_span = self.last_span; let item = self.mk_item(lo, last_span.hi, @@ -6131,7 +6154,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes().index(&FullRange)); + attrs.push_all(&self.parse_outer_attributes()[]); // First, parse view items. let mut view_items : Vec<ast::ViewItem> = Vec::new(); let mut items = Vec::new(); @@ -6213,7 +6236,7 @@ impl<'a> Parser<'a> { macros_allowed: bool) -> ParsedItemsAndViewItems { let mut attrs = first_item_attrs; - attrs.push_all(self.parse_outer_attributes().index(&FullRange)); + attrs.push_all(&self.parse_outer_attributes()[]); let mut foreign_items = Vec::new(); loop { match self.parse_foreign_item(attrs, macros_allowed) { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 43786738910..4b3573f84c5 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -480,7 +480,7 @@ macro_rules! declare_special_idents_and_keywords {( $(init_vec.push($si_str);)* $(init_vec.push($sk_str);)* $(init_vec.push($rk_str);)* - interner::StrInterner::prefill(init_vec.index(&FullRange)) + interner::StrInterner::prefill(&init_vec[]) } }} @@ -629,7 +629,7 @@ impl InternedString { #[inline] pub fn get<'a>(&'a self) -> &'a str { - self.string.index(&FullRange) + &self.string[] } } @@ -659,41 +659,41 @@ impl fmt::Show for InternedString { impl fmt::String for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.string.index(&FullRange)) + write!(f, "{}", &self.string[]) } } impl<'a> PartialEq<&'a str> for InternedString { #[inline(always)] fn eq(&self, other: & &'a str) -> bool { - PartialEq::eq(self.string.index(&FullRange), *other) + PartialEq::eq(&self.string[], *other) } #[inline(always)] fn ne(&self, other: & &'a str) -> bool { - PartialEq::ne(self.string.index(&FullRange), *other) + PartialEq::ne(&self.string[], *other) } } impl<'a> PartialEq<InternedString > for &'a str { #[inline(always)] fn eq(&self, other: &InternedString) -> bool { - PartialEq::eq(*self, other.string.index(&FullRange)) + PartialEq::eq(*self, &other.string[]) } #[inline(always)] fn ne(&self, other: &InternedString) -> bool { - PartialEq::ne(*self, other.string.index(&FullRange)) + PartialEq::ne(*self, &other.string[]) } } impl Decodable for InternedString { fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> { - Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange)))) + Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[]))) } } impl Encodable for InternedString { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.string.index(&FullRange)) + s.emit_str(&self.string[]) } } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 52306075c21..b69b812c958 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -138,9 +138,9 @@ pub fn buf_str(toks: Vec<Token>, if i != left { s.push_str(", "); } - s.push_str(format!("{}={}", + s.push_str(&format!("{}={}", szs[i], - tok_str(toks[i].clone())).index(&FullRange)); + tok_str(toks[i].clone()))[]); i += 1u; i %= n; } @@ -602,7 +602,7 @@ impl Printer { assert_eq!(l, len); // assert!(l <= space); self.space -= len; - self.print_str(s.index(&FullRange)) + self.print_str(&s[]) } Eof => { // Eof should never get here. diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 87dcc9e70f4..9b6f8e6002d 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -114,7 +114,7 @@ pub fn print_crate<'a>(cm: &'a CodeMap, out, ann, is_expanded); - try!(s.print_mod(&krate.module, krate.attrs.index(&FullRange))); + try!(s.print_mod(&krate.module, &krate.attrs[])); try!(s.print_remaining_comments()); eof(&mut s.s) } @@ -580,7 +580,7 @@ impl<'a> State<'a> { pub fn synth_comment(&mut self, text: String) -> IoResult<()> { try!(word(&mut self.s, "/*")); try!(space(&mut self.s)); - try!(word(&mut self.s, text.index(&FullRange))); + try!(word(&mut self.s, &text[])); try!(space(&mut self.s)); word(&mut self.s, "*/") } @@ -685,7 +685,7 @@ impl<'a> State<'a> { } ast::TyTup(ref elts) => { try!(self.popen()); - try!(self.commasep(Inconsistent, elts.index(&FullRange), + try!(self.commasep(Inconsistent, &elts[], |s, ty| s.print_type(&**ty))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -721,10 +721,10 @@ impl<'a> State<'a> { } ast::TyObjectSum(ref ty, ref bounds) => { try!(self.print_type(&**ty)); - try!(self.print_bounds("+", bounds.index(&FullRange))); + try!(self.print_bounds("+", &bounds[])); } ast::TyPolyTraitRef(ref bounds) => { - try!(self.print_bounds("", bounds.index(&FullRange))); + try!(self.print_bounds("", &bounds[])); } ast::TyQPath(ref qpath) => { try!(word(&mut self.s, "<")); @@ -759,7 +759,7 @@ impl<'a> State<'a> { item: &ast::ForeignItem) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); match item.node { ast::ForeignItemFn(ref decl, ref generics) => { try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics, @@ -769,8 +769,8 @@ impl<'a> State<'a> { self.end() // end the outer fn box } ast::ForeignItemStatic(ref t, m) => { - try!(self.head(visibility_qualified(item.vis, - "static").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "static")[])); if m { try!(self.word_space("mut")); } @@ -787,7 +787,7 @@ impl<'a> State<'a> { fn print_associated_type(&mut self, typedef: &ast::AssociatedType) -> IoResult<()> { - try!(self.print_outer_attributes(typedef.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&typedef.attrs[])); try!(self.word_space("type")); try!(self.print_ty_param(&typedef.ty_param)); word(&mut self.s, ";") @@ -806,12 +806,12 @@ impl<'a> State<'a> { pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); try!(self.ann.pre(self, NodeItem(item))); match item.node { ast::ItemStatic(ref ty, m, ref expr) => { - try!(self.head(visibility_qualified(item.vis, - "static").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "static")[])); if m == ast::MutMutable { try!(self.word_space("mut")); } @@ -827,8 +827,8 @@ impl<'a> State<'a> { try!(self.end()); // end the outer cbox } ast::ItemConst(ref ty, ref expr) => { - try!(self.head(visibility_qualified(item.vis, - "const").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "const")[])); try!(self.print_ident(item.ident)); try!(self.word_space(":")); try!(self.print_type(&**ty)); @@ -851,29 +851,28 @@ impl<'a> State<'a> { item.vis )); try!(word(&mut self.s, " ")); - try!(self.print_block_with_attrs(&**body, item.attrs.index(&FullRange))); + try!(self.print_block_with_attrs(&**body, &item.attrs[])); } ast::ItemMod(ref _mod) => { - try!(self.head(visibility_qualified(item.vis, - "mod").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis, + "mod")[])); try!(self.print_ident(item.ident)); try!(self.nbsp()); try!(self.bopen()); - try!(self.print_mod(_mod, item.attrs.index(&FullRange))); + try!(self.print_mod(_mod, &item.attrs[])); try!(self.bclose(item.span)); } ast::ItemForeignMod(ref nmod) => { try!(self.head("extern")); - try!(self.word_nbsp(nmod.abi.to_string().index(&FullRange))); + try!(self.word_nbsp(&nmod.abi.to_string()[])); try!(self.bopen()); - try!(self.print_foreign_mod(nmod, item.attrs.index(&FullRange))); + try!(self.print_foreign_mod(nmod, &item.attrs[])); try!(self.bclose(item.span)); } ast::ItemTy(ref ty, ref params) => { try!(self.ibox(indent_unit)); try!(self.ibox(0u)); - try!(self.word_nbsp(visibility_qualified(item.vis, - "type").index(&FullRange))); + try!(self.word_nbsp(&visibility_qualified(item.vis, "type")[])); try!(self.print_ident(item.ident)); try!(self.print_generics(params)); try!(self.end()); // end the inner ibox @@ -895,7 +894,7 @@ impl<'a> State<'a> { )); } ast::ItemStruct(ref struct_def, ref generics) => { - try!(self.head(visibility_qualified(item.vis,"struct").index(&FullRange))); + try!(self.head(&visibility_qualified(item.vis,"struct")[])); try!(self.print_struct(&**struct_def, generics, item.ident, item.span)); } @@ -936,7 +935,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.bopen()); - try!(self.print_inner_attributes(item.attrs.index(&FullRange))); + try!(self.print_inner_attributes(&item.attrs[])); for impl_item in impl_items.iter() { match *impl_item { ast::MethodImplItem(ref meth) => { @@ -967,7 +966,7 @@ impl<'a> State<'a> { real_bounds.push(b); } } - try!(self.print_bounds(":", real_bounds.index(&FullRange))); + try!(self.print_bounds(":", &real_bounds[])); try!(self.print_where_clause(generics)); try!(word(&mut self.s, " ")); try!(self.bopen()); @@ -985,7 +984,7 @@ impl<'a> State<'a> { try!(self.print_ident(item.ident)); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts.index(&FullRange))); + try!(self.print_tts(&tts[])); try!(self.pclose()); try!(word(&mut self.s, ";")); try!(self.end()); @@ -1019,12 +1018,12 @@ impl<'a> State<'a> { generics: &ast::Generics, ident: ast::Ident, span: codemap::Span, visibility: ast::Visibility) -> IoResult<()> { - try!(self.head(visibility_qualified(visibility, "enum").index(&FullRange))); + try!(self.head(&visibility_qualified(visibility, "enum")[])); try!(self.print_ident(ident)); try!(self.print_generics(generics)); try!(self.print_where_clause(generics)); try!(space(&mut self.s)); - self.print_variants(enum_definition.variants.index(&FullRange), span) + self.print_variants(&enum_definition.variants[], span) } pub fn print_variants(&mut self, @@ -1034,7 +1033,7 @@ impl<'a> State<'a> { for v in variants.iter() { try!(self.space_if_not_bol()); try!(self.maybe_print_comment(v.span.lo)); - try!(self.print_outer_attributes(v.node.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&v.node.attrs[])); try!(self.ibox(indent_unit)); try!(self.print_variant(&**v)); try!(word(&mut self.s, ",")); @@ -1062,7 +1061,7 @@ impl<'a> State<'a> { if !struct_def.fields.is_empty() { try!(self.popen()); try!(self.commasep( - Inconsistent, struct_def.fields.index(&FullRange), + Inconsistent, &struct_def.fields[], |s, field| { match field.node.kind { ast::NamedField(..) => panic!("unexpected named field"), @@ -1092,7 +1091,7 @@ impl<'a> State<'a> { ast::NamedField(ident, visibility) => { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(field.span.lo)); - try!(self.print_outer_attributes(field.node.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&field.node.attrs[])); try!(self.print_visibility(visibility)); try!(self.print_ident(ident)); try!(self.word_nbsp(":")); @@ -1116,7 +1115,7 @@ impl<'a> State<'a> { pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> { match *tt { ast::TtToken(_, ref tk) => { - try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(tk)[])); match *tk { parse::token::DocComment(..) => { hardbreak(&mut self.s) @@ -1125,11 +1124,11 @@ impl<'a> State<'a> { } } ast::TtDelimited(_, ref delimed) => { - try!(word(&mut self.s, token_to_string(&delimed.open_token()).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(&delimed.open_token())[])); try!(space(&mut self.s)); - try!(self.print_tts(delimed.tts.index(&FullRange))); + try!(self.print_tts(&delimed.tts[])); try!(space(&mut self.s)); - word(&mut self.s, token_to_string(&delimed.close_token()).index(&FullRange)) + word(&mut self.s, &token_to_string(&delimed.close_token())[]) }, ast::TtSequence(_, ref seq) => { try!(word(&mut self.s, "$(")); @@ -1139,7 +1138,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, ")")); match seq.separator { Some(ref tk) => { - try!(word(&mut self.s, token_to_string(tk).index(&FullRange))); + try!(word(&mut self.s, &token_to_string(tk)[])); } None => {}, } @@ -1170,7 +1169,7 @@ impl<'a> State<'a> { if !args.is_empty() { try!(self.popen()); try!(self.commasep(Consistent, - args.index(&FullRange), + &args[], |s, arg| s.print_type(&*arg.ty))); try!(self.pclose()); } @@ -1194,7 +1193,7 @@ impl<'a> State<'a> { pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(m.span.lo)); - try!(self.print_outer_attributes(m.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&m.attrs[])); try!(self.print_ty_fn(None, None, m.unsafety, @@ -1226,7 +1225,7 @@ impl<'a> State<'a> { pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(meth.span.lo)); - try!(self.print_outer_attributes(meth.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&meth.attrs[])); match meth.node { ast::MethDecl(ident, ref generics, @@ -1244,7 +1243,7 @@ impl<'a> State<'a> { Some(&explicit_self.node), vis)); try!(word(&mut self.s, " ")); - self.print_block_with_attrs(&**body, meth.attrs.index(&FullRange)) + self.print_block_with_attrs(&**body, &meth.attrs[]) }, ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _), ..}) => { @@ -1253,7 +1252,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "! ")); try!(self.cbox(indent_unit)); try!(self.popen()); - try!(self.print_tts(tts.index(&FullRange))); + try!(self.print_tts(&tts[])); try!(self.pclose()); try!(word(&mut self.s, ";")); self.end() @@ -1520,7 +1519,7 @@ impl<'a> State<'a> { ast::ExprVec(ref exprs) => { try!(self.ibox(indent_unit)); try!(word(&mut self.s, "[")); - try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); + try!(self.commasep_exprs(Inconsistent, &exprs[])); try!(word(&mut self.s, "]")); try!(self.end()); } @@ -1541,7 +1540,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "{")); try!(self.commasep_cmnt( Consistent, - fields.index(&FullRange), + &fields[], |s, field| { try!(s.ibox(indent_unit)); try!(s.print_ident(field.ident.node)); @@ -1568,7 +1567,7 @@ impl<'a> State<'a> { } ast::ExprTup(ref exprs) => { try!(self.popen()); - try!(self.commasep_exprs(Inconsistent, exprs.index(&FullRange))); + try!(self.commasep_exprs(Inconsistent, &exprs[])); if exprs.len() == 1 { try!(word(&mut self.s, ",")); } @@ -1576,7 +1575,7 @@ impl<'a> State<'a> { } ast::ExprCall(ref func, ref args) => { try!(self.print_expr_maybe_paren(&**func)); - try!(self.print_call_post(args.index(&FullRange))); + try!(self.print_call_post(&args[])); } ast::ExprMethodCall(ident, ref tys, ref args) => { let base_args = args.slice_from(1); @@ -1585,7 +1584,7 @@ impl<'a> State<'a> { try!(self.print_ident(ident.node)); if tys.len() > 0u { try!(word(&mut self.s, "::<")); - try!(self.commasep(Inconsistent, tys.index(&FullRange), + try!(self.commasep(Inconsistent, &tys[], |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ">")); } @@ -1782,11 +1781,11 @@ impl<'a> State<'a> { try!(self.print_string(a.asm.get(), a.asm_str_style)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.outputs.index(&FullRange), + try!(self.commasep(Inconsistent, &a.outputs[], |s, &(ref co, ref o, is_rw)| { match co.get().slice_shift_char() { Some(('=', operand)) if is_rw => { - try!(s.print_string(format!("+{}", operand).index(&FullRange), + try!(s.print_string(&format!("+{}", operand)[], ast::CookedStr)) } _ => try!(s.print_string(co.get(), ast::CookedStr)) @@ -1799,7 +1798,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.inputs.index(&FullRange), + try!(self.commasep(Inconsistent, &a.inputs[], |s, &(ref co, ref o)| { try!(s.print_string(co.get(), ast::CookedStr)); try!(s.popen()); @@ -1810,7 +1809,7 @@ impl<'a> State<'a> { try!(space(&mut self.s)); try!(self.word_space(":")); - try!(self.commasep(Inconsistent, a.clobbers.index(&FullRange), + try!(self.commasep(Inconsistent, &a.clobbers[], |s, co| { try!(s.print_string(co.get(), ast::CookedStr)); Ok(()) @@ -1884,7 +1883,7 @@ impl<'a> State<'a> { pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> { if self.encode_idents_with_hygiene { let encoded = ident.encode_with_hygiene(); - try!(word(&mut self.s, encoded.index(&FullRange))) + try!(word(&mut self.s, &encoded[])) } else { try!(word(&mut self.s, token::get_ident(ident).get())) } @@ -1892,7 +1891,7 @@ impl<'a> State<'a> { } pub fn print_uint(&mut self, i: uint) -> IoResult<()> { - word(&mut self.s, i.to_string().index(&FullRange)) + word(&mut self.s, &i.to_string()[]) } pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> { @@ -1966,7 +1965,7 @@ impl<'a> State<'a> { } try!(self.commasep( Inconsistent, - data.types.index(&FullRange), + &data.types[], |s, ty| s.print_type(&**ty))); comma = true; } @@ -1989,7 +1988,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, "(")); try!(self.commasep( Inconsistent, - data.inputs.index(&FullRange), + &data.inputs[], |s, ty| s.print_type(&**ty))); try!(word(&mut self.s, ")")); @@ -2042,7 +2041,7 @@ impl<'a> State<'a> { Some(ref args) => { if !args.is_empty() { try!(self.popen()); - try!(self.commasep(Inconsistent, args.index(&FullRange), + try!(self.commasep(Inconsistent, &args[], |s, p| s.print_pat(&**p))); try!(self.pclose()); } @@ -2054,7 +2053,7 @@ impl<'a> State<'a> { try!(self.nbsp()); try!(self.word_space("{")); try!(self.commasep_cmnt( - Consistent, fields.index(&FullRange), + Consistent, &fields[], |s, f| { try!(s.cbox(indent_unit)); if !f.node.is_shorthand { @@ -2075,7 +2074,7 @@ impl<'a> State<'a> { ast::PatTup(ref elts) => { try!(self.popen()); try!(self.commasep(Inconsistent, - elts.index(&FullRange), + &elts[], |s, p| s.print_pat(&**p))); if elts.len() == 1 { try!(word(&mut self.s, ",")); @@ -2103,7 +2102,7 @@ impl<'a> State<'a> { ast::PatVec(ref before, ref slice, ref after) => { try!(word(&mut self.s, "[")); try!(self.commasep(Inconsistent, - before.index(&FullRange), + &before[], |s, p| s.print_pat(&**p))); for p in slice.iter() { if !before.is_empty() { try!(self.word_space(",")); } @@ -2117,7 +2116,7 @@ impl<'a> State<'a> { if !after.is_empty() { try!(self.word_space(",")); } } try!(self.commasep(Inconsistent, - after.index(&FullRange), + &after[], |s, p| s.print_pat(&**p))); try!(word(&mut self.s, "]")); } @@ -2134,7 +2133,7 @@ impl<'a> State<'a> { } try!(self.cbox(indent_unit)); try!(self.ibox(0u)); - try!(self.print_outer_attributes(arm.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&arm.attrs[])); let mut first = true; for p in arm.pats.iter() { if first { @@ -2234,7 +2233,7 @@ impl<'a> State<'a> { // HACK(eddyb) ignore the separately printed self argument. let args = if first { - decl.inputs.index(&FullRange) + &decl.inputs[] } else { decl.inputs.slice_from(1) }; @@ -2400,7 +2399,7 @@ impl<'a> State<'a> { ints.push(i); } - try!(self.commasep(Inconsistent, ints.index(&FullRange), |s, &idx| { + try!(self.commasep(Inconsistent, &ints[], |s, &idx| { if idx < generics.lifetimes.len() { let lifetime = &generics.lifetimes[idx]; s.print_lifetime_def(lifetime) @@ -2417,7 +2416,7 @@ impl<'a> State<'a> { pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> { try!(self.print_ident(param.ident)); - try!(self.print_bounds(":", param.bounds.index(&FullRange))); + try!(self.print_bounds(":", ¶m.bounds[])); match param.default { Some(ref default) => { try!(space(&mut self.s)); @@ -2493,7 +2492,7 @@ impl<'a> State<'a> { try!(word(&mut self.s, name.get())); try!(self.popen()); try!(self.commasep(Consistent, - items.index(&FullRange), + &items[], |s, i| s.print_meta_item(&**i))); try!(self.pclose()); } @@ -2529,7 +2528,7 @@ impl<'a> State<'a> { try!(self.print_path(path, false)); try!(word(&mut self.s, "::{")); } - try!(self.commasep(Inconsistent, idents.index(&FullRange), |s, w| { + try!(self.commasep(Inconsistent, &idents[], |s, w| { match w.node { ast::PathListIdent { name, .. } => { s.print_ident(name) @@ -2547,7 +2546,7 @@ impl<'a> State<'a> { pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> { try!(self.hardbreak_if_not_bol()); try!(self.maybe_print_comment(item.span.lo)); - try!(self.print_outer_attributes(item.attrs.index(&FullRange))); + try!(self.print_outer_attributes(&item.attrs[])); try!(self.print_visibility(item.vis)); match item.node { ast::ViewItemExternCrate(id, ref optional_path, _) => { @@ -2689,7 +2688,7 @@ impl<'a> State<'a> { try!(self.pclose()); } - try!(self.print_bounds(":", bounds.index(&FullRange))); + try!(self.print_bounds(":", &bounds[])); try!(self.print_fn_output(decl)); @@ -2748,7 +2747,7 @@ impl<'a> State<'a> { try!(self.maybe_print_comment(lit.span.lo)); match self.next_lit(lit.span.lo) { Some(ref ltrl) => { - return word(&mut self.s, (*ltrl).lit.index(&FullRange)); + return word(&mut self.s, &(*ltrl).lit[]); } _ => () } @@ -2758,7 +2757,7 @@ impl<'a> State<'a> { let mut res = String::from_str("b'"); ascii::escape_default(byte, |c| res.push(c as char)); res.push('\''); - word(&mut self.s, res.index(&FullRange)) + word(&mut self.s, &res[]) } ast::LitChar(ch) => { let mut res = String::from_str("'"); @@ -2766,36 +2765,36 @@ impl<'a> State<'a> { res.push(c); } res.push('\''); - word(&mut self.s, res.index(&FullRange)) + word(&mut self.s, &res[]) } ast::LitInt(i, t) => { match t { ast::SignedIntLit(st, ast::Plus) => { word(&mut self.s, - ast_util::int_ty_to_string(st, Some(i as i64)).index(&FullRange)) + &ast_util::int_ty_to_string(st, Some(i as i64))[]) } ast::SignedIntLit(st, ast::Minus) => { let istr = ast_util::int_ty_to_string(st, Some(-(i as i64))); word(&mut self.s, - format!("-{}", istr).index(&FullRange)) + &format!("-{}", istr)[]) } ast::UnsignedIntLit(ut) => { word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice()) } ast::UnsuffixedIntLit(ast::Plus) => { - word(&mut self.s, format!("{}", i).index(&FullRange)) + word(&mut self.s, &format!("{}", i)[]) } ast::UnsuffixedIntLit(ast::Minus) => { - word(&mut self.s, format!("-{}", i).index(&FullRange)) + word(&mut self.s, &format!("-{}", i)[]) } } } ast::LitFloat(ref f, t) => { word(&mut self.s, - format!( + &format!( "{}{}", f.get(), - ast_util::float_ty_to_string(t).index(&FullRange)).index(&FullRange)) + &ast_util::float_ty_to_string(t)[])[]) } ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()), ast::LitBool(val) => { @@ -2807,7 +2806,7 @@ impl<'a> State<'a> { ascii::escape_default(ch as u8, |ch| escaped.push(ch as char)); } - word(&mut self.s, format!("b\"{}\"", escaped).index(&FullRange)) + word(&mut self.s, &format!("b\"{}\"", escaped)[]) } } } @@ -2848,7 +2847,7 @@ impl<'a> State<'a> { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1u); try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); + try!(word(&mut self.s, &cmnt.lines[0][])); zerobreak(&mut self.s) } comments::Isolated => { @@ -2857,7 +2856,7 @@ impl<'a> State<'a> { // Don't print empty lines because they will end up as trailing // whitespace if !line.is_empty() { - try!(word(&mut self.s, line.index(&FullRange))); + try!(word(&mut self.s, &line[])); } try!(hardbreak(&mut self.s)); } @@ -2866,13 +2865,13 @@ impl<'a> State<'a> { comments::Trailing => { try!(word(&mut self.s, " ")); if cmnt.lines.len() == 1u { - try!(word(&mut self.s, cmnt.lines[0].index(&FullRange))); + try!(word(&mut self.s, &cmnt.lines[0][])); hardbreak(&mut self.s) } else { try!(self.ibox(0u)); for line in cmnt.lines.iter() { if !line.is_empty() { - try!(word(&mut self.s, line.index(&FullRange))); + try!(word(&mut self.s, &line[])); } try!(hardbreak(&mut self.s)); } @@ -2905,7 +2904,7 @@ impl<'a> State<'a> { string=st)) } }; - word(&mut self.s, st.index(&FullRange)) + word(&mut self.s, &st[]) } pub fn next_comment(&mut self) -> Option<comments::Comment> { @@ -2936,7 +2935,7 @@ impl<'a> State<'a> { Some(abi::Rust) => Ok(()), Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string().index(&FullRange)) + self.word_nbsp(&abi.to_string()[]) } None => Ok(()) } @@ -2947,7 +2946,7 @@ impl<'a> State<'a> { match opt_abi { Some(abi) => { try!(self.word_nbsp("extern")); - self.word_nbsp(abi.to_string().index(&FullRange)) + self.word_nbsp(&abi.to_string()[]) } None => Ok(()) } @@ -2963,7 +2962,7 @@ impl<'a> State<'a> { if abi != abi::Rust { try!(self.word_nbsp("extern")); - try!(self.word_nbsp(abi.to_string().index(&FullRange))); + try!(self.word_nbsp(&abi.to_string()[])); } word(&mut self.s, "fn") diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 8abb46011e6..13a14d069d7 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -37,9 +37,11 @@ //! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. use std::fmt::{self, Show}; -use std::hash::Hash; +use std::hash::{Hash, Hasher}; +#[cfg(stage0)] use std::hash::Writer; use std::ops::Deref; use std::ptr; + use serialize::{Encodable, Decodable, Encoder, Decoder}; /// An owned smart pointer. @@ -105,7 +107,14 @@ impl<T: Show> Show for P<T> { } } -impl<S, T: Hash<S>> Hash<S> for P<T> { +#[cfg(stage0)] +impl<S: Writer, T: Hash<S>> Hash<S> for P<T> { + fn hash(&self, state: &mut S) { + (**self).hash(state); + } +} +#[cfg(not(stage0))] +impl<S: Hasher, T: Hash<S>> Hash<S> for P<T> { fn hash(&self, state: &mut S) { (**self).hash(state); } diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index daa51203287..28b9eaa54aa 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -40,7 +40,7 @@ pub fn maybe_inject_prelude(krate: ast::Crate) -> ast::Crate { } fn use_std(krate: &ast::Crate) -> bool { - !attr::contains_name(krate.attrs.index(&FullRange), "no_std") + !attr::contains_name(&krate.attrs[], "no_std") } fn no_prelude(attrs: &[ast::Attribute]) -> bool { @@ -48,7 +48,7 @@ fn no_prelude(attrs: &[ast::Attribute]) -> bool { } struct StandardLibraryInjector<'a> { - alt_std_name: Option<String>, + alt_std_name: Option<String> } impl<'a> fold::Folder for StandardLibraryInjector<'a> { @@ -56,7 +56,7 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { // The name to use in `extern crate "name" as std;` let actual_crate_name = match self.alt_std_name { - Some(ref s) => token::intern_and_get_ident(s.index(&FullRange)), + Some(ref s) => token::intern_and_get_ident(&s[]), None => token::intern_and_get_ident("std"), }; @@ -84,14 +84,13 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { fn inject_crates_ref(krate: ast::Crate, alt_std_name: Option<String>) -> ast::Crate { let mut fold = StandardLibraryInjector { - alt_std_name: alt_std_name, + alt_std_name: alt_std_name }; fold.fold_crate(krate) } struct PreludeInjector<'a>; - impl<'a> fold::Folder for PreludeInjector<'a> { fn fold_crate(&mut self, mut krate: ast::Crate) -> ast::Crate { // Add #![no_std] here, so we don't re-inject when compiling pretty-printed source. @@ -104,27 +103,17 @@ impl<'a> fold::Folder for PreludeInjector<'a> { attr::mark_used(&no_std_attr); krate.attrs.push(no_std_attr); - if !no_prelude(krate.attrs.index(&FullRange)) { - // only add `use std::prelude::*;` if there wasn't a - // `#![no_implicit_prelude]` at the crate level. - // fold_mod() will insert glob path. - let globs_attr = attr::mk_attr_inner(attr::mk_attr_id(), - attr::mk_list_item( - InternedString::new("feature"), - vec!( - attr::mk_word_item(InternedString::new("globs")), - ))); - // std_inject runs after feature checking so manually mark this attr - attr::mark_used(&globs_attr); - krate.attrs.push(globs_attr); - + // only add `use std::prelude::*;` if there wasn't a + // `#![no_implicit_prelude]` at the crate level. + // fold_mod() will insert glob path. + if !no_prelude(&krate.attrs[]) { krate.module = self.fold_mod(krate.module); } krate } fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> { - if !no_prelude(item.attrs.index(&FullRange)) { + if !no_prelude(&item.attrs[]) { // only recur if there wasn't `#![no_implicit_prelude]` // on this item, i.e. this means that the prelude is not // implicitly imported though the whole subtree diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 711715355e9..bacfa0bbfce 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -73,14 +73,14 @@ pub fn modify_for_testing(sess: &ParseSess, // We generate the test harness when building in the 'test' // configuration, either with the '--test' or '--cfg test' // command line options. - let should_test = attr::contains_name(krate.config.index(&FullRange), "test"); + let should_test = attr::contains_name(&krate.config[], "test"); // Check for #[reexport_test_harness_main = "some_name"] which // creates a `use some_name = __test::main;`. This needs to be // unconditional, so that the attribute is still marked as used in // non-test builds. let reexport_test_harness_main = - attr::first_attr_value_str_by_name(krate.attrs.index(&FullRange), + attr::first_attr_value_str_by_name(&krate.attrs[], "reexport_test_harness_main"); if should_test { @@ -119,7 +119,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { self.cx.path.push(ident); } debug!("current path: {}", - ast_util::path_name_i(self.cx.path.index(&FullRange))); + ast_util::path_name_i(&self.cx.path[])); if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) { match i.node { @@ -277,8 +277,8 @@ fn strip_test_functions(krate: ast::Crate) -> ast::Crate { // When not compiling with --test we should not compile the // #[test] functions config::strip_items(krate, |attrs| { - !attr::contains_name(attrs.index(&FullRange), "test") && - !attr::contains_name(attrs.index(&FullRange), "bench") + !attr::contains_name(&attrs[], "test") && + !attr::contains_name(&attrs[], "bench") }) } @@ -291,7 +291,7 @@ enum HasTestSignature { fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_test_attr = attr::contains_name(i.attrs.index(&FullRange), "test"); + let has_test_attr = attr::contains_name(&i.attrs[], "test"); fn has_test_signature(i: &ast::Item) -> HasTestSignature { match &i.node { @@ -329,7 +329,7 @@ fn is_test_fn(cx: &TestCtxt, i: &ast::Item) -> bool { } fn is_bench_fn(cx: &TestCtxt, i: &ast::Item) -> bool { - let has_bench_attr = attr::contains_name(i.attrs.index(&FullRange), "bench"); + let has_bench_attr = attr::contains_name(&i.attrs[], "bench"); fn has_test_signature(i: &ast::Item) -> bool { match i.node { @@ -384,7 +384,7 @@ We're going to be building a module that looks more or less like: mod __test { extern crate test (name = "test", vers = "..."); fn main() { - test::test_main_static(::os::args().index(&FullRange), tests) + test::test_main_static(&::os::args()[], tests) } static tests : &'static [test::TestDescAndFn] = &[ @@ -510,8 +510,8 @@ fn mk_tests(cx: &TestCtxt) -> P<ast::Item> { } fn is_test_crate(krate: &ast::Crate) -> bool { - match attr::find_crate_name(krate.attrs.index(&FullRange)) { - Some(ref s) if "test" == s.get().index(&FullRange) => true, + match attr::find_crate_name(&krate.attrs[]) { + Some(ref s) if "test" == &s.get()[] => true, _ => false } } @@ -551,11 +551,11 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> P<ast::Expr> { // creates $name: $expr let field = |&: name, expr| ecx.field_imm(span, ecx.ident_of(name), expr); - debug!("encoding {}", ast_util::path_name_i(path.index(&FullRange))); + debug!("encoding {}", ast_util::path_name_i(&path[])); // path to the #[test] function: "foo::bar::baz" - let path_string = ast_util::path_name_i(path.index(&FullRange)); - let name_expr = ecx.expr_str(span, token::intern_and_get_ident(path_string.index(&FullRange))); + let path_string = ast_util::path_name_i(&path[]); + let name_expr = ecx.expr_str(span, token::intern_and_get_ident(&path_string[])); // self::test::StaticTestName($name_expr) let name_expr = ecx.expr_call(span, diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 93de342d487..5dca39f1aea 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -20,6 +20,7 @@ use std::cmp::Ordering; use std::collections::HashMap; use std::fmt; use std::hash::Hash; +use std::collections::hash_map::Hasher; use std::ops::Deref; use std::rc::Rc; @@ -28,8 +29,8 @@ pub struct Interner<T> { vect: RefCell<Vec<T> >, } -// when traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) -impl<T: Eq + Hash + Clone + 'static> Interner<T> { +// when traits can extend traits, we should extend index<Name,T> to get [] +impl<T: Eq + Hash<Hasher> + Clone + 'static> Interner<T> { pub fn new() -> Interner<T> { Interner { map: RefCell::new(HashMap::new()), @@ -78,7 +79,7 @@ impl<T: Eq + Hash + Clone + 'static> Interner<T> { } pub fn find<Q: ?Sized>(&self, val: &Q) -> Option<Name> - where Q: BorrowFrom<T> + Eq + Hash { + where Q: BorrowFrom<T> + Eq + Hash<Hasher> { let map = self.map.borrow(); match (*map).get(val) { Some(v) => Some(*v), @@ -109,27 +110,27 @@ impl Eq for RcStr {} impl Ord for RcStr { fn cmp(&self, other: &RcStr) -> Ordering { - self.index(&FullRange).cmp(other.index(&FullRange)) + self[].cmp(&other[]) } } impl fmt::Show for RcStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Show; - self.index(&FullRange).fmt(f) + self[].fmt(f) } } impl BorrowFrom<RcStr> for str { fn borrow_from(owned: &RcStr) -> &str { - owned.string.index(&FullRange) + &owned.string[] } } impl Deref for RcStr { type Target = str; - fn deref(&self) -> &str { self.string.index(&FullRange) } + fn deref(&self) -> &str { &self.string[] } } /// A StrInterner differs from Interner<String> in that it accepts @@ -139,7 +140,7 @@ pub struct StrInterner { vect: RefCell<Vec<RcStr> >, } -/// When traits can extend traits, we should extend index<Name,T> to get .index(&FullRange) +/// When traits can extend traits, we should extend index<Name,T> to get [] impl StrInterner { pub fn new() -> StrInterner { StrInterner { @@ -203,7 +204,7 @@ impl StrInterner { } pub fn find<Q: ?Sized>(&self, val: &Q) -> Option<Name> - where Q: BorrowFrom<RcStr> + Eq + Hash { + where Q: BorrowFrom<RcStr> + Eq + Hash<Hasher> { match (*self.map.borrow()).get(val) { Some(v) => Some(*v), None => None, diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index c953f591d80..2117b68c08e 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -39,7 +39,8 @@ //! [ti]: https://en.wikipedia.org/wiki/Terminfo #![crate_name = "term"] -#![experimental = "use the crates.io `term` library instead"] +#![unstable = "use the crates.io `term` library instead"] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", @@ -49,6 +50,8 @@ #![allow(unknown_features)] #![feature(slicing_syntax)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] #![deny(missing_docs)] #[macro_use] extern crate log; diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index f2dcdc6160a..4933938f338 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -180,7 +180,7 @@ impl<T: Writer+Send> TerminfoTerminal<T> { } }; - let entry = open(term.index(&FullRange)); + let entry = open(&term[]); if entry.is_err() { if os::getenv("MSYSCON").map_or(false, |s| { "mintty.exe" == s diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 7a06849abd1..4735b6e8f2a 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -284,13 +284,13 @@ pub fn parse(file: &mut io::Reader, longnames: bool) // Find the offset of the NUL we want to go to - let nulpos = string_table.index(&((offset as uint) .. (string_table_bytes as uint))) + let nulpos = string_table[(offset as uint) .. (string_table_bytes as uint)] .iter().position(|&b| b == 0); match nulpos { Some(len) => { string_map.insert(name.to_string(), - string_table.index(&((offset as uint) .. - (offset as uint + len))).to_vec()) + string_table[(offset as uint) .. + (offset as uint + len)].to_vec()) }, None => { return Err("invalid file: missing NUL in \ diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index 2651be1ebb8..1fca3c62f78 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -61,13 +61,13 @@ pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> { for p in dirs_to_search.iter() { if p.exists() { let f = first_char.to_string(); - let newp = p.join_many(&[f.index(&FullRange), term]); + let newp = p.join_many(&[&f[], term]); if newp.exists() { return Some(box newp); } // on some installations the dir is named after the hex of the char (e.g. OS X) let f = format!("{:x}", first_char as uint); - let newp = p.join_many(&[f.index(&FullRange), term]); + let newp = p.join_many(&[&f[], term]); if newp.exists() { return Some(box newp); } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 68d06cc4dab..c4cb53d6cb7 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -24,13 +24,17 @@ // build off of. #![crate_name = "test"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] +#![allow(unknown_features)] #![feature(asm, slicing_syntax)] +#![feature(box_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate getopts; extern crate regex; @@ -948,7 +952,7 @@ fn should_sort_failures_before_printing_them() { st.write_failures().unwrap(); let s = match st.out { - Raw(ref m) => String::from_utf8_lossy(m.index(&FullRange)), + Raw(ref m) => String::from_utf8_lossy(&m[]), Pretty(_) => unreachable!() }; diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 1abb52459e4..6061c4fd1d3 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -12,7 +12,7 @@ use std::cmp::Ordering::{self, Less, Greater, Equal}; use std::collections::hash_map::Entry::{Occupied, Vacant}; -use std::collections::hash_map; +use std::collections::hash_map::{self, Hasher}; use std::fmt; use std::hash::Hash; use std::io; @@ -440,7 +440,7 @@ pub fn write_boxplot<W: Writer, T: Float + fmt::String + fmt::Show + FromPrimiti /// Returns a HashMap with the number of occurrences of every element in the /// sequence that the iterator exposes. pub fn freq_count<T, U>(mut iter: T) -> hash_map::HashMap<U, uint> - where T: Iterator<Item=U>, U: Eq + Clone + Hash + where T: Iterator<Item=U>, U: Eq + Clone + Hash<Hasher> { let mut map: hash_map::HashMap<U,uint> = hash_map::HashMap::new(); for elem in iter { diff --git a/src/libunicode/lib.rs b/src/libunicode/lib.rs index db98b429e40..17607383bee 100644 --- a/src/libunicode/lib.rs +++ b/src/libunicode/lib.rs @@ -21,7 +21,8 @@ //! (yet) aim to provide a full set of Unicode tables. #![crate_name = "unicode"] -#![experimental] +#![unstable] +#![staged_api] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", @@ -29,6 +30,7 @@ html_playground_url = "http://play.rust-lang.org/")] #![no_std] #![feature(slicing_syntax)] +#![allow(unknown_features)] #![feature(int_uint)] extern crate core; @@ -56,6 +58,7 @@ mod u_str; /// (inclusive) are allowed. A `char` can always be safely cast to a `u32`; /// however the converse is not always true due to the above range limits /// and, as such, should be performed via the `from_u32` function.. +#[stable] pub mod char { pub use core::char::{MAX, from_u32, from_digit}; diff --git a/src/libunicode/u_char.rs b/src/libunicode/u_char.rs index 5693c222de1..4142a62ba66 100644 --- a/src/libunicode/u_char.rs +++ b/src/libunicode/u_char.rs @@ -112,7 +112,7 @@ pub trait CharExt { /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. - #[experimental = "mainly needed for compiler internals"] + #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' @@ -121,7 +121,7 @@ pub trait CharExt { /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. - #[experimental = "mainly needed for compiler internals"] + #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. @@ -171,7 +171,7 @@ pub trait CharExt { /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. - #[experimental = "pending case transformation decisions"] + #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. @@ -194,7 +194,7 @@ pub trait CharExt { /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 - #[experimental = "pending case transformation decisions"] + #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a @@ -206,7 +206,7 @@ pub trait CharExt { /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. - #[experimental = "needs expert opinion. is_cjk flag stands out as ugly"] + #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } @@ -238,10 +238,10 @@ impl CharExt for char { } } - #[experimental = "mainly needed for compiler internals"] + #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } - #[experimental = "mainly needed for compiler internals"] + #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] @@ -288,12 +288,12 @@ impl CharExt for char { } } - #[experimental = "pending case transformation decisions"] + #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } - #[experimental = "pending case transformation decisions"] + #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } - #[experimental = "needs expert opinion. is_cjk flag stands out as ugly"] + #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } } diff --git a/src/rustbook/book.rs b/src/rustbook/book.rs new file mode 100644 index 00000000000..1d16de2a2fe --- /dev/null +++ b/src/rustbook/book.rs @@ -0,0 +1,166 @@ +// 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. + +//! Basic data structures for representing a book. + +use std::io::BufferedReader; +use std::iter; +use std::iter::AdditiveIterator; +use regex::Regex; + +pub struct BookItem { + pub title: String, + pub path: Path, + pub path_to_root: Path, + pub children: Vec<BookItem>, +} + +pub struct Book { + pub chapters: Vec<BookItem>, +} + +/// A depth-first iterator over a book. +pub struct BookItems<'a> { + cur_items: &'a [BookItem], + cur_idx: usize, + stack: Vec<(&'a [BookItem], usize)>, +} + +impl<'a> Iterator for BookItems<'a> { + type Item = (String, &'a BookItem); + + fn next(&mut self) -> Option<(String, &'a BookItem)> { + loop { + if self.cur_idx >= self.cur_items.len() { + match self.stack.pop() { + None => return None, + Some((parent_items, parent_idx)) => { + self.cur_items = parent_items; + self.cur_idx = parent_idx + 1; + } + } + } else { + let cur = self.cur_items.get(self.cur_idx).unwrap(); + + let mut section = "".to_string(); + for &(_, idx) in self.stack.iter() { + section.push_str(&(idx + 1).to_string()[]); + section.push('.'); + } + section.push_str(&(self.cur_idx + 1).to_string()[]); + section.push('.'); + + self.stack.push((self.cur_items, self.cur_idx)); + self.cur_items = &cur.children[]; + self.cur_idx = 0; + return Some((section, cur)) + } + } + } +} + +impl Book { + pub fn iter(&self) -> BookItems { + BookItems { + cur_items: &self.chapters[], + cur_idx: 0, + stack: Vec::new(), + } + } +} + +/// Construct a book by parsing a summary (markdown table of contents). +pub fn parse_summary<R: Reader>(input: R, src: &Path) -> Result<Book, Vec<String>> { + fn collapse(stack: &mut Vec<BookItem>, + top_items: &mut Vec<BookItem>, + to_level: usize) { + loop { + if stack.len() < to_level { return } + if stack.len() == 1 { + top_items.push(stack.pop().unwrap()); + return; + } + + let tip = stack.pop().unwrap(); + let last = stack.len() - 1; + stack[last].children.push(tip); + } + } + + let regex = r"(?P<indent>[\t ]*)\*[:space:]*\[(?P<title>.*)\]\((?P<path>.*)\)"; + let item_re = Regex::new(regex).unwrap(); + let mut top_items = vec!(); + let mut stack = vec!(); + let mut errors = vec!(); + + // always include the introduction + top_items.push(BookItem { + title: "Introduction".to_string(), + path: Path::new("README.md"), + path_to_root: Path::new("."), + children: vec!(), + }); + + for line_result in BufferedReader::new(input).lines() { + let line = match line_result { + Ok(line) => line, + Err(err) => { + errors.push(err.desc.to_string()); // FIXME: include detail + return Err(errors); + } + }; + + item_re.captures(&line[]).map(|cap| { + let given_path = cap.name("path"); + let title = cap.name("title").unwrap().to_string(); + + let path_from_root = match src.join(given_path.unwrap()).path_relative_from(src) { + Some(p) => p, + None => { + errors.push(format!("Paths in SUMMARY.md must be relative, \ + but path '{}' for section '{}' is not.", + given_path.unwrap(), title)); + Path::new("") + } + }; + let path_to_root = Path::new(iter::repeat("../") + .take(path_from_root.components().count() - 1) + .collect::<String>()); + let item = BookItem { + title: title, + path: path_from_root, + path_to_root: path_to_root, + children: vec!(), + }; + let level = cap.name("indent").unwrap().chars().map(|c| { + match c { + ' ' => 1us, + '\t' => 4, + _ => unreachable!() + } + }).sum() / 4 + 1; + + if level > stack.len() + 1 { + // FIXME: better error message + errors.push(format!("Section '{}' is indented too many levels.", item.title)); + } else if level <= stack.len() { + collapse(&mut stack, &mut top_items, level); + } + stack.push(item) + }); + } + + if errors.is_empty() { + collapse(&mut stack, &mut top_items, 1); + Ok(Book { chapters: top_items }) + } else { + Err(errors) + } +} diff --git a/src/rustbook/build.rs b/src/rustbook/build.rs new file mode 100644 index 00000000000..1cb5e38e190 --- /dev/null +++ b/src/rustbook/build.rs @@ -0,0 +1,192 @@ +// 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. + +//! Implementation of the `build` subcommand, used to compile a book. + +use std::os; +use std::io; +use std::io::{fs, File, BufferedWriter, TempDir, IoResult}; + +use subcommand::Subcommand; +use term::Term; +use error::{Error, CliResult, CommandResult}; +use book; +use book::{Book, BookItem}; +use css; + +use regex::Regex; + +use rustdoc; + +struct Build; + +pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> { + if name == "build" { + Some(box Build as Box<Subcommand>) + } else { + None + } +} + +fn write_toc(book: &Book, path_to_root: &Path, out: &mut Writer) -> IoResult<()> { + fn walk_items(items: &[BookItem], + section: &str, + path_to_root: &Path, + out: &mut Writer) -> IoResult<()> { + for (i, item) in items.iter().enumerate() { + try!(walk_item(item, &format!("{}{}.", section, i + 1)[], path_to_root, out)); + } + Ok(()) + } + fn walk_item(item: &BookItem, + section: &str, + path_to_root: &Path, + out: &mut Writer) -> IoResult<()> { + try!(writeln!(out, "<li><a href='{}'><b>{}</b> {}</a>", + path_to_root.join(item.path.with_extension("html")).display(), + section, + item.title)); + if !item.children.is_empty() { + try!(writeln!(out, "<ul class='section'>")); + let _ = walk_items(&item.children[], section, path_to_root, out); + try!(writeln!(out, "</ul>")); + } + try!(writeln!(out, "</li>")); + + Ok(()) + } + + try!(writeln!(out, "<div id='toc'>")); + try!(writeln!(out, "<ul class='chapter'>")); + try!(walk_items(&book.chapters[], "", path_to_root, out)); + try!(writeln!(out, "</ul>")); + try!(writeln!(out, "</div>")); + + Ok(()) +} + +fn render(book: &Book, tgt: &Path) -> CliResult<()> { + let tmp = TempDir::new("rust-book") + .ok() + // FIXME: lift to Result instead + .expect("could not create temporary directory"); + + for (section, item) in book.iter() { + println!("{} {}", section, item.title); + + let out_path = tgt.join(item.path.dirname()); + + let regex = r"\[(?P<title>[^]]*)\]\((?P<url_stem>[^)]*)\.(?P<ext>md|markdown)\)"; + let md_urls = Regex::new(regex).unwrap(); + + let src; + if os::args().len() < 3 { + src = os::getcwd().unwrap().clone(); + } else { + src = Path::new(os::args()[2].clone()); + } + // preprocess the markdown, rerouting markdown references to html references + let markdown_data = try!(File::open(&src.join(&item.path)).read_to_string()); + let preprocessed_path = tmp.path().join(item.path.filename().unwrap()); + { + let urls = md_urls.replace_all(&markdown_data[], "[$title]($url_stem.html)"); + try!(File::create(&preprocessed_path) + .write_str(&urls[])); + } + + // write the prelude to a temporary HTML file for rustdoc inclusion + let prelude = tmp.path().join("prelude.html"); + { + let mut toc = BufferedWriter::new(try!(File::create(&prelude))); + let _ = write_toc(book, &item.path_to_root, &mut toc); + try!(writeln!(&mut toc, "<div id='page-wrapper'>")); + try!(writeln!(&mut toc, "<div id='page'>")); + } + + // write the postlude to a temporary HTML file for rustdoc inclusion + let postlude = tmp.path().join("postlude.html"); + { + let mut toc = BufferedWriter::new(try!(File::create(&postlude))); + try!(writeln!(&mut toc, "</div></div>")); + } + + try!(fs::mkdir_recursive(&out_path, io::USER_DIR)); + + let rustdoc_args: &[String] = &[ + "".to_string(), + preprocessed_path.display().to_string(), + format!("-o{}", out_path.display()), + format!("--html-before-content={}", prelude.display()), + format!("--html-after-content={}", postlude.display()), + format!("--markdown-css={}", item.path_to_root.join("rust-book.css").display()), + "--markdown-no-toc".to_string(), + ]; + let output_result = rustdoc::main_args(rustdoc_args); + if output_result != 0 { + let message = format!("Could not execute `rustdoc` with {:?}: {}", + rustdoc_args, output_result); + return Err(box message as Box<Error>); + } + } + + // create index.html from the root README + try!(fs::copy(&tgt.join("README.html"), &tgt.join("index.html"))); + Ok(()) +} + +impl Subcommand for Build { + fn parse_args(&mut self, _: &[String]) -> CliResult<()> { + Ok(()) + } + fn usage(&self) {} + fn execute(&mut self, term: &mut Term) -> CommandResult<()> { + let cwd = os::getcwd().unwrap(); + let src; + let tgt; + + if os::args().len() < 3 { + src = cwd.clone(); + } else { + src = Path::new(os::args()[2].clone()); + } + + if os::args().len() < 4 { + tgt = cwd.join("_book"); + } else { + tgt = Path::new(os::args()[3].clone()); + } + + let _ = fs::mkdir(&tgt, io::USER_DIR); // FIXME: handle errors + + // FIXME: handle errors + let _ = File::create(&tgt.join("rust-book.css")).write_str(css::STYLE); + + let summary = File::open(&src.join("SUMMARY.md")); + match book::parse_summary(summary, &src) { + Ok(book) => { + // execute rustdoc on the whole book + try!(render(&book, &tgt).map_err(|err| { + term.err(&format!("error: {}", err.description())[]); + err.detail().map(|detail| { + term.err(&format!("detail: {}", detail)[]); + }); + err + })) + } + Err(errors) => { + for err in errors.into_iter() { + term.err(&err[]); + } + } + } + + Ok(()) // lol + } +} diff --git a/src/rustbook/css.rs b/src/rustbook/css.rs new file mode 100644 index 00000000000..8eb66e71d3a --- /dev/null +++ b/src/rustbook/css.rs @@ -0,0 +1,72 @@ +// 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. + +// The rust-book CSS in string form. + +pub static STYLE: &'static str = r#" +@import url("//static.rust-lang.org/doc/master/rust.css"); + +body { + max-width:none; +} + +#toc { + position: absolute; + left: 0px; + top: 0px; + bottom: 0px; + width: 250px; + overflow-y: auto; + border-right: 1px solid rgba(0, 0, 0, 0.07); + padding: 10px 10px; + font-size: 16px; + background: none repeat scroll 0% 0% #FFF; + box-sizing: border-box; +} + +#page-wrapper { + position: absolute; + overflow-y: auto; + left: 260px; + right: 0px; + top: 0px; + bottom: 0px; + box-sizing: border-box; + background: none repeat scroll 0% 0% #FFF; +} + +#page { + margin-left: auto; + margin-right:auto; + width: 750px; +} + +.chapter { + list-style: none outside none; + padding-left: 0px; + line-height: 30px; +} + +.section { + list-style: none outside none; + padding-left: 20px; + line-height: 30px; +} + +.section li { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.chapter li a { + color: #000000; +} +"#; diff --git a/src/rustbook/error.rs b/src/rustbook/error.rs new file mode 100644 index 00000000000..a5915ed4d73 --- /dev/null +++ b/src/rustbook/error.rs @@ -0,0 +1,82 @@ +// 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. + +//! Error handling utilities. WIP. + +use std::fmt; +use std::fmt::{Show, Formatter}; + +use std::io::IoError; + +pub type CliError = Box<Error + 'static>; +pub type CliResult<T> = Result<T, CliError>; + +pub type CommandError = Box<Error + 'static>; +pub type CommandResult<T> = Result<T, CommandError>; + +pub trait Error { + fn description(&self) -> &str; + + fn detail(&self) -> Option<&str> { None } + fn cause(&self) -> Option<&Error> { None } +} + +pub trait FromError<E> { + fn from_err(err: E) -> Self; +} + +impl Show for Box<Error + 'static> { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}", self.description()) + } +} + +impl<E: Error + 'static> FromError<E> for Box<Error + 'static> { + fn from_err(err: E) -> Box<Error + 'static> { + box err as Box<Error> + } +} + +impl<'a> Error for &'a str { + fn description<'b>(&'b self) -> &'b str { + *self + } +} + +impl Error for String { + fn description<'a>(&'a self) -> &'a str { + &self[] + } +} + +impl<'a> Error for Box<Error + 'a> { + fn description(&self) -> &str { (**self).description() } + fn detail(&self) -> Option<&str> { (**self).detail() } + fn cause(&self) -> Option<&Error> { (**self).cause() } +} + +impl FromError<()> for () { + fn from_err(_: ()) -> () { () } +} + +impl FromError<IoError> for IoError { + fn from_err(error: IoError) -> IoError { error } +} + +impl Error for IoError { + fn description(&self) -> &str { + self.desc + } + fn detail(&self) -> Option<&str> { + self.detail.as_ref().map(|s| &s[]) + } +} + +//fn iter_map_err<T, U, E, I: Iterator<Result<T,E>>>(iter: I, diff --git a/src/rustbook/help.rs b/src/rustbook/help.rs new file mode 100644 index 00000000000..7fd8214f731 --- /dev/null +++ b/src/rustbook/help.rs @@ -0,0 +1,46 @@ +// 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. + +//! Implementation of the `help` subcommand. Currently just prints basic usage info. + +use subcommand::Subcommand; +use error::CliResult; +use error::CommandResult; +use term::Term; + +struct Help; + +pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> { + match name { + "help" | "--help" | "-h" | "-?" => Some(box Help as Box<Subcommand>), + _ => None + } +} + +impl Subcommand for Help { + fn parse_args(&mut self, _: &[String]) -> CliResult<()> { + Ok(()) + } + fn usage(&self) {} + fn execute(&mut self, _: &mut Term) -> CommandResult<()> { + usage(); + Ok(()) + } +} + +pub fn usage() { + println!("Usage: rust-book <command> [<args>]"); + println!(""); + println!("The <command> must be one of:"); + println!(" help Print this message."); + println!(" build Build the book in subdirectory _book"); + println!(" serve --NOT YET IMPLEMENTED--"); + println!(" test --NOT YET IMPLEMENTED--"); +} diff --git a/src/rustbook/main.rs b/src/rustbook/main.rs new file mode 100644 index 00000000000..acb4edb7a45 --- /dev/null +++ b/src/rustbook/main.rs @@ -0,0 +1,74 @@ +// 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. + +#![feature(slicing_syntax, box_syntax)] + +extern crate regex; + +extern crate rustdoc; + +use std::os; +use subcommand::Subcommand; +use term::Term; + +macro_rules! try ( + ($expr:expr) => ({ + use error; + match $expr { + Ok(val) => val, + Err(err) => return Err(error::FromError::from_err(err)) + } + }) +); + +mod term; +mod error; +mod book; + +mod subcommand; +mod help; +mod build; +mod serve; +mod test; + +mod css; + +#[cfg(not(test))] // thanks #12327 +fn main() { + let mut term = Term::new(); + let cmd = os::args(); + + if cmd.len() < 1 { + help::usage() + } else { + match subcommand::parse_name(&cmd[1][]) { + Some(mut subcmd) => { + match subcmd.parse_args(cmd.tail()) { + Ok(_) => { + match subcmd.execute(&mut term) { + Ok(_) => (), + Err(_) => os::set_exit_status(-1), + } + } + Err(err) => { + println!("{}", err.description()); + println!(""); + subcmd.usage(); + } + } + } + None => { + println!("Unrecognized command '{}'.", cmd[1]); + println!(""); + help::usage(); + } + } + } +} diff --git a/src/rustbook/serve.rs b/src/rustbook/serve.rs new file mode 100644 index 00000000000..808527dcef9 --- /dev/null +++ b/src/rustbook/serve.rs @@ -0,0 +1,36 @@ +// 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. + +//! Implementation of the `serve` subcommand. Just a stub for now. + +use subcommand::Subcommand; +use error::CliResult; +use error::CommandResult; +use term::Term; + +struct Serve; + +pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> { + if name == "serve" { + Some(box Serve as Box<Subcommand>) + } else { + None + } +} + +impl Subcommand for Serve { + fn parse_args(&mut self, _: &[String]) -> CliResult<()> { + Ok(()) + } + fn usage(&self) {} + fn execute(&mut self, _: &mut Term) -> CommandResult<()> { + Ok(()) + } +} diff --git a/src/rustbook/subcommand.rs b/src/rustbook/subcommand.rs new file mode 100644 index 00000000000..473739c919d --- /dev/null +++ b/src/rustbook/subcommand.rs @@ -0,0 +1,44 @@ +// 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. + +//! Common API for all rust-book subcommands. + +use error::CliResult; +use error::CommandResult; +use term::Term; + +use help; +use build; +use serve; +use test; + +pub trait Subcommand { + /// Mutate the subcommand by parsing its arguments. + /// + /// Returns `Err` on a parsing error. + fn parse_args(&mut self, args: &[String]) -> CliResult<()>; + /// Print the CLI usage information. + fn usage(&self); + /// Actually execute the subcommand. + fn execute(&mut self, term: &mut Term) -> CommandResult<()>; +} + +/// Create a Subcommand object based on its name. +pub fn parse_name(name: &str) -> Option<Box<Subcommand>> { + for parser in [ + help::parse_cmd as fn(&str) -> Option<Box<Subcommand>>, + build::parse_cmd as fn(&str) -> Option<Box<Subcommand>>, + serve::parse_cmd as fn(&str) -> Option<Box<Subcommand>>, + test::parse_cmd as fn(&str) -> Option<Box<Subcommand>>].iter() { + let parsed = (*parser)(name); + if parsed.is_some() { return parsed } + } + None +} diff --git a/src/rustbook/term.rs b/src/rustbook/term.rs new file mode 100644 index 00000000000..471e22ce7c1 --- /dev/null +++ b/src/rustbook/term.rs @@ -0,0 +1,33 @@ +// 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. + +//! An abstraction of the terminal. Eventually, provide color and +//! verbosity support. For now, just a wrapper around stdout/stderr. + +use std::os; +use std::io::stdio; + +pub struct Term { + err: Box<Writer + 'static> +} + +impl Term { + pub fn new() -> Term { + Term { + err: box stdio::stderr() as Box<Writer>, + } + } + + pub fn err(&mut self, msg: &str) { + // swallow any errors + let _ = self.err.write_line(msg); + os::set_exit_status(101); + } +} diff --git a/src/rustbook/test.rs b/src/rustbook/test.rs new file mode 100644 index 00000000000..f2bf92585f7 --- /dev/null +++ b/src/rustbook/test.rs @@ -0,0 +1,75 @@ +// 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. + +//! Implementation of the `test` subcommand. Just a stub for now. + +use subcommand::Subcommand; +use error::CliResult; +use error::CommandResult; +use error::Error; +use term::Term; +use book; +use std::io::{Command, File}; +use std::os; + +struct Test; + +pub fn parse_cmd(name: &str) -> Option<Box<Subcommand>> { + if name == "test" { + Some(box Test as Box<Subcommand>) + } else { + None + } +} + +impl Subcommand for Test { + fn parse_args(&mut self, _: &[String]) -> CliResult<()> { + Ok(()) + } + fn usage(&self) {} + fn execute(&mut self, term: &mut Term) -> CommandResult<()> { + let cwd = os::getcwd().unwrap(); + let src = cwd.clone(); + + let summary = File::open(&src.join("SUMMARY.md")); + match book::parse_summary(summary, &src) { + Ok(book) => { + for (_, item) in book.iter() { + let output_result = Command::new("rustdoc") + .arg(&item.path) + .arg("--test") + .output(); + match output_result { + Ok(output) => { + if !output.status.success() { + term.err(&format!("{}\n{}", + String::from_utf8_lossy(&output.output[]), + String::from_utf8_lossy(&output.error[]))[]); + return Err(box "Some tests failed." as Box<Error>); + } + + } + Err(e) => { + let message = format!("Could not execute `rustdoc`: {}", e); + return Err(box message as Box<Error>); + } + } + } + } + Err(errors) => { + for err in errors.into_iter() { + term.err(&err[]); + } + return Err(box "There was an error." as Box<Error>); + } + } + Ok(()) // lol + } +} diff --git a/src/snapshots.txt b/src/snapshots.txt index d6134898cbd..aa31974c67a 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,12 @@ +S 2015-01-07 9e4e524 + freebsd-x86_64 2563d33151bce1bbe08a85d712564bddc7503fc6 + linux-i386 d8b73fc9aa3ad72ce1408a41e35d78dba10eb4d4 + linux-x86_64 697880d3640e981bbbf23284363e8e9a158b588d + macos-i386 a73b1fc03e8cac747aab0aa186292bb4332a7a98 + macos-x86_64 e4ae2670ea4ba5c2e5b4245409c9cab45c9eeb5b + winnt-i386 ddffa59d9605aa05e83e8f664db802da512611e9 + winnt-x86_64 a56261ebbc580c6c14b1c1d0be25010f5201dc3f + S 2015-01-06 340ac04 freebsd-x86_64 5413b8931d7076e90c873e0cc7a43e0793c2b17a linux-i386 cacb8e3ad15937916e455d8f63e740c30a807b10 diff --git a/src/test/auxiliary/cci_nested_lib.rs b/src/test/auxiliary/cci_nested_lib.rs index 44d001d45fd..8494917c615 100644 --- a/src/test/auxiliary/cci_nested_lib.rs +++ b/src/test/auxiliary/cci_nested_lib.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] use std::cell::RefCell; diff --git a/src/test/auxiliary/inherited_stability.rs b/src/test/auxiliary/inherited_stability.rs index 5691ce3bfa7..7a01ce3de0b 100644 --- a/src/test/auxiliary/inherited_stability.rs +++ b/src/test/auxiliary/inherited_stability.rs @@ -9,7 +9,8 @@ // except according to those terms. #![crate_name="inherited_stability"] #![crate_type = "lib"] -#![experimental] +#![unstable] +#![staged_api] pub fn experimental() {} @@ -26,7 +27,7 @@ pub mod stable_mod { #[unstable] pub mod unstable_mod { - #[experimental] + #[unstable] pub fn experimental() {} pub fn unstable() {} diff --git a/src/test/auxiliary/issue-2380.rs b/src/test/auxiliary/issue-2380.rs index af6bb050ef5..8eb6cd6e263 100644 --- a/src/test/auxiliary/issue-2380.rs +++ b/src/test/auxiliary/issue-2380.rs @@ -11,6 +11,8 @@ #![crate_name="a"] #![crate_type = "lib"] +#![allow(unknown_features)] +#![feature(box_syntax)] pub trait i<T> { } diff --git a/src/test/auxiliary/lint_group_plugin_test.rs b/src/test/auxiliary/lint_group_plugin_test.rs index 097a5827fc4..ae9804423bb 100644 --- a/src/test/auxiliary/lint_group_plugin_test.rs +++ b/src/test/auxiliary/lint_group_plugin_test.rs @@ -11,6 +11,7 @@ // force-host #![feature(plugin_registrar)] +#![feature(box_syntax)] extern crate syntax; diff --git a/src/test/auxiliary/lint_output_format.rs b/src/test/auxiliary/lint_output_format.rs index 181b651ef52..adbb90fe6c8 100755 --- a/src/test/auxiliary/lint_output_format.rs +++ b/src/test/auxiliary/lint_output_format.rs @@ -10,13 +10,14 @@ #![crate_name="lint_output_format"] #![crate_type = "lib"] +#![staged_api] #[deprecated] pub fn foo() -> uint { 20 } -#[experimental] +#[unstable] pub fn bar() -> uint { 40 } diff --git a/src/test/auxiliary/lint_plugin_test.rs b/src/test/auxiliary/lint_plugin_test.rs index 01ef08c4752..06051b87493 100644 --- a/src/test/auxiliary/lint_plugin_test.rs +++ b/src/test/auxiliary/lint_plugin_test.rs @@ -11,6 +11,7 @@ // force-host #![feature(plugin_registrar)] +#![feature(box_syntax)] extern crate syntax; diff --git a/src/test/auxiliary/lint_stability.rs b/src/test/auxiliary/lint_stability.rs index 708830d0259..73724713b21 100644 --- a/src/test/auxiliary/lint_stability.rs +++ b/src/test/auxiliary/lint_stability.rs @@ -9,15 +9,16 @@ // except according to those terms. #![crate_name="lint_stability"] #![crate_type = "lib"] +#![staged_api] #[deprecated] pub fn deprecated() {} #[deprecated="text"] pub fn deprecated_text() {} -#[experimental] +#[unstable] pub fn experimental() {} -#[experimental="text"] +#[unstable="text"] pub fn experimental_text() {} #[unstable] @@ -51,9 +52,9 @@ impl MethodTester { #[deprecated="text"] pub fn method_deprecated_text(&self) {} - #[experimental] + #[unstable] pub fn method_experimental(&self) {} - #[experimental="text"] + #[unstable="text"] pub fn method_experimental_text(&self) {} #[unstable] @@ -85,9 +86,9 @@ pub trait Trait { #[deprecated="text"] fn trait_deprecated_text(&self) {} - #[experimental] + #[unstable] fn trait_experimental(&self) {} - #[experimental="text"] + #[unstable="text"] fn trait_experimental_text(&self) {} #[unstable] @@ -115,12 +116,12 @@ pub trait Trait { impl Trait for MethodTester {} -#[experimental] +#[unstable] pub trait ExperimentalTrait {} #[deprecated] pub struct DeprecatedStruct { pub i: int } -#[experimental] +#[unstable] pub struct ExperimentalStruct { pub i: int } #[unstable] pub struct UnstableStruct { pub i: int } @@ -134,7 +135,7 @@ pub struct LockedStruct { pub i: int } #[deprecated] pub struct DeprecatedUnitStruct; -#[experimental] +#[unstable] pub struct ExperimentalUnitStruct; #[unstable] pub struct UnstableUnitStruct; @@ -149,7 +150,7 @@ pub struct LockedUnitStruct; pub enum Enum { #[deprecated] DeprecatedVariant, - #[experimental] + #[unstable] ExperimentalVariant, #[unstable] UnstableVariant, @@ -165,7 +166,7 @@ pub enum Enum { #[deprecated] pub struct DeprecatedTupleStruct(pub int); -#[experimental] +#[unstable] pub struct ExperimentalTupleStruct(pub int); #[unstable] pub struct UnstableTupleStruct(pub int); diff --git a/src/test/auxiliary/macro_crate_test.rs b/src/test/auxiliary/macro_crate_test.rs index 99f02cf2d58..9eeb7ee8857 100644 --- a/src/test/auxiliary/macro_crate_test.rs +++ b/src/test/auxiliary/macro_crate_test.rs @@ -11,6 +11,7 @@ // force-host #![feature(plugin_registrar, quote)] +#![feature(box_syntax)] extern crate syntax; extern crate rustc; diff --git a/src/test/auxiliary/method_self_arg1.rs b/src/test/auxiliary/method_self_arg1.rs index 37022131c3d..5865a8f467b 100644 --- a/src/test/auxiliary/method_self_arg1.rs +++ b/src/test/auxiliary/method_self_arg1.rs @@ -10,6 +10,9 @@ #![crate_type = "lib"] +#![allow(unknown_features)] +#![feature(box_syntax)] + static mut COUNT: u64 = 1; pub fn get_count() -> u64 { unsafe { COUNT } } diff --git a/src/test/auxiliary/method_self_arg2.rs b/src/test/auxiliary/method_self_arg2.rs index eb4d62b01ad..a28a877a374 100644 --- a/src/test/auxiliary/method_self_arg2.rs +++ b/src/test/auxiliary/method_self_arg2.rs @@ -10,6 +10,9 @@ #![crate_type = "lib"] +#![allow(unknown_features)] +#![feature(box_syntax)] + static mut COUNT: u64 = 1; pub fn get_count() -> u64 { unsafe { COUNT } } diff --git a/src/test/auxiliary/plugin_args.rs b/src/test/auxiliary/plugin_args.rs index b90c3f1d727..e01a95d461b 100644 --- a/src/test/auxiliary/plugin_args.rs +++ b/src/test/auxiliary/plugin_args.rs @@ -11,6 +11,7 @@ // force-host #![feature(plugin_registrar)] +#![feature(box_syntax)] extern crate syntax; extern crate rustc; diff --git a/src/test/auxiliary/plugin_crate_outlive_expansion_phase.rs b/src/test/auxiliary/plugin_crate_outlive_expansion_phase.rs index 021eae90cf8..c460c60b02b 100644 --- a/src/test/auxiliary/plugin_crate_outlive_expansion_phase.rs +++ b/src/test/auxiliary/plugin_crate_outlive_expansion_phase.rs @@ -11,6 +11,7 @@ // force-host #![feature(plugin_registrar)] +#![feature(box_syntax)] extern crate rustc; diff --git a/src/test/auxiliary/stability_cfg1.rs b/src/test/auxiliary/stability_cfg1.rs index 6b2e8e7758f..de806c65beb 100644 --- a/src/test/auxiliary/stability_cfg1.rs +++ b/src/test/auxiliary/stability_cfg1.rs @@ -10,3 +10,4 @@ #![cfg_attr(foo, experimental)] #![cfg_attr(not(foo), stable)] +#![staged_api] diff --git a/src/test/auxiliary/stability_cfg2.rs b/src/test/auxiliary/stability_cfg2.rs index 3387b319abf..842f35b08ae 100644 --- a/src/test/auxiliary/stability_cfg2.rs +++ b/src/test/auxiliary/stability_cfg2.rs @@ -10,6 +10,6 @@ // compile-flags:--cfg foo -#![cfg_attr(foo, experimental)] +#![cfg_attr(foo, unstable)] #![cfg_attr(not(foo), stable)] - +#![staged_api] diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index f0bd7e9c9d8..e638721a501 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -18,6 +18,7 @@ extern crate rand; use std::collections::BTreeSet; use std::collections::BitvSet; use std::collections::HashSet; +use std::collections::hash_map::Hasher; use std::hash::Hash; use std::os; use std::time::Duration; @@ -42,7 +43,7 @@ trait MutableSet<T> { fn contains(&self, k: &T) -> bool; } -impl<T: Hash + Eq> MutableSet<T> for HashSet<T> { +impl<T: Hash<Hasher> + Eq> MutableSet<T> for HashSet<T> { fn insert(&mut self, k: T) { self.insert(k); } fn remove(&mut self, k: &T) -> bool { self.remove(k) } fn contains(&self, k: &T) -> bool { self.contains(k) } diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 4c85d329b0a..7fe086f1d0e 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -102,6 +102,6 @@ fn main() { args.into_iter().map(|x| x.to_string()).collect() }; - println!("{}", args); + println!("{:?}", args); run(args.as_slice()); } diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index 16beee17352..fef78f413f6 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -109,6 +109,6 @@ fn main() { args.clone().into_iter().map(|x| x.to_string()).collect() }; - println!("{}", args); + println!("{:?}", args); run(args.as_slice()); } diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 8c06f7caa77..e8e8ac48485 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -38,8 +38,6 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. -#![feature(slicing_syntax)] - use std::{cmp, iter, mem}; use std::thread::Thread; diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index 9a6152dc13c..5a47f9fbc57 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -38,8 +38,6 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. -#![feature(slicing_syntax)] - use std::cmp::min; use std::io::{stdout, IoResult}; use std::iter::repeat; diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 29994f45d3a..e9da34615c1 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -38,8 +38,6 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. -#![feature(slicing_syntax)] - use std::cmp::min; use std::io::{BufferedWriter, File}; use std::io; diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 3845c6c593c..03268b40193 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -13,7 +13,7 @@ // multi tasking k-nucleotide -#![feature(slicing_syntax)] +#![feature(box_syntax)] use std::ascii::{AsciiExt, OwnedAsciiExt}; use std::cmp::Ordering::{self, Less, Greater, Equal}; @@ -64,7 +64,7 @@ fn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String { let mut buffer = String::new(); for &(ref k, v) in pairs_sorted.iter() { - buffer.push_str(format!("{} {:0.3}\n", + buffer.push_str(format!("{:?} {:0.3}\n", k.to_ascii_uppercase(), v).as_slice()); } @@ -193,8 +193,8 @@ fn main() { // start processing if this is the one ('>', false) => { match line.as_slice().slice_from(1).find_str("THREE") { - option::Option::Some(_) => { proc_mode = true; } - option::Option::None => { } + Some(_) => { proc_mode = true; } + None => { } } } @@ -223,6 +223,6 @@ fn main() { // now fetch and print result messages for (ii, _sz) in sizes.iter().enumerate() { - println!("{}", from_child[ii].recv().unwrap()); + println!("{:?}", from_child[ii].recv().unwrap()); } } diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index af5fd1a3520..5256e607d20 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -40,7 +40,7 @@ // ignore-android see #10393 #13206 -#![feature(slicing_syntax)] +#![feature(box_syntax)] use std::ascii::OwnedAsciiExt; use std::slice; diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index f6124c1271f..cf1264ff5d6 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -39,7 +39,7 @@ // OF THE POSSIBILITY OF SUCH DAMAGE. #![feature(simd)] -#![allow(experimental)] +#![allow(unstable)] // ignore-pretty very bad with line comments diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index 34a036eff37..0480c9d884a 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -118,7 +118,7 @@ fn transform(piece: Vec<(int, int)> , all: bool) -> Vec<Vec<(int, int)>> { // translating to (0, 0) as minimum coordinates. for cur_piece in res.iter_mut() { let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap(); - for &(ref mut y, ref mut x) in cur_piece.iter_mut() { + for &mut (ref mut y, ref mut x) in cur_piece.iter_mut() { *y -= dy; *x -= dx; } } diff --git a/src/test/bench/shootout-regex-dna.rs b/src/test/bench/shootout-regex-dna.rs index ef538eb6991..074c0592312 100644 --- a/src/test/bench/shootout-regex-dna.rs +++ b/src/test/bench/shootout-regex-dna.rs @@ -41,7 +41,7 @@ // ignore-stage1 // ignore-cross-compile #12102 -#![feature(plugin, slicing_syntax)] +#![feature(box_syntax)] extern crate regex; diff --git a/src/test/bench/shootout-reverse-complement.rs b/src/test/bench/shootout-reverse-complement.rs index e22d2fa61df..c8a74c7d735 100644 --- a/src/test/bench/shootout-reverse-complement.rs +++ b/src/test/bench/shootout-reverse-complement.rs @@ -40,7 +40,7 @@ // ignore-android see #10393 #13206 -#![feature(slicing_syntax, unboxed_closures)] +#![feature(unboxed_closures)] extern crate libc; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 58ba88c3769..67476eddbc7 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -10,6 +10,7 @@ // ignore-pretty very bad with line comments +#![feature(box_syntax)] #![allow(non_snake_case)] use std::io::BufferedReader; diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index 7706c53e554..03dc9dd4441 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(unsafe_destructor)] +#![feature(unsafe_destructor, box_syntax)] use std::os; use std::thread::Thread; diff --git a/src/test/compile-fail-fulldeps/issue-18986.rs b/src/test/compile-fail-fulldeps/issue-18986.rs index 25d78c273e7..6845116e4a4 100644 --- a/src/test/compile-fail-fulldeps/issue-18986.rs +++ b/src/test/compile-fail-fulldeps/issue-18986.rs @@ -15,6 +15,6 @@ pub use use_from_trait_xc::Trait; fn main() { match () { - Trait { x: 42u } => () //~ ERROR use of trait `Trait` in a struct pattern + Trait { x: 42us } => () //~ ERROR use of trait `Trait` in a struct pattern } } diff --git a/src/test/compile-fail/access-mode-in-closures.rs b/src/test/compile-fail/access-mode-in-closures.rs index f15157d126e..bad192fc2cf 100644 --- a/src/test/compile-fail/access-mode-in-closures.rs +++ b/src/test/compile-fail/access-mode-in-closures.rs @@ -9,9 +9,9 @@ // except according to those terms. -struct sty(Vec<int> ); +struct sty(Vec<isize> ); -fn unpack<F>(_unpack: F) where F: FnOnce(&sty) -> Vec<int> {} +fn unpack<F>(_unpack: F) where F: FnOnce(&sty) -> Vec<isize> {} fn main() { let _foo = unpack(|s| { diff --git a/src/test/compile-fail/arg-count-mismatch.rs b/src/test/compile-fail/arg-count-mismatch.rs index 472c66d9aad..673314ec4c9 100644 --- a/src/test/compile-fail/arg-count-mismatch.rs +++ b/src/test/compile-fail/arg-count-mismatch.rs @@ -10,6 +10,6 @@ // error-pattern: parameters were supplied -fn f(x: int) { } +fn f(x: isize) { } fn main() { let i: (); i = f(); } diff --git a/src/test/compile-fail/arg-type-mismatch.rs b/src/test/compile-fail/arg-type-mismatch.rs index 06fcc40f2e4..1f657ca5832 100644 --- a/src/test/compile-fail/arg-type-mismatch.rs +++ b/src/test/compile-fail/arg-type-mismatch.rs @@ -11,6 +11,6 @@ // error-pattern: mismatched types -fn f(x: int) { } +fn f(x: isize) { } fn main() { let i: (); i = f(()); } diff --git a/src/test/compile-fail/array-old-syntax-1.rs b/src/test/compile-fail/array-old-syntax-1.rs index 3c01a7756a6..3b4810a86ab 100644 --- a/src/test/compile-fail/array-old-syntax-1.rs +++ b/src/test/compile-fail/array-old-syntax-1.rs @@ -11,5 +11,5 @@ // Test that the old fixed length array syntax is a parsing error. fn main() { - let _x: [int, ..3] = [0i, 1, 2]; //~ ERROR + let _x: [isize, ..3] = [0is, 1, 2]; //~ ERROR } diff --git a/src/test/compile-fail/array-old-syntax-2.rs b/src/test/compile-fail/array-old-syntax-2.rs index df2cc305ca8..c1b88290bc3 100644 --- a/src/test/compile-fail/array-old-syntax-2.rs +++ b/src/test/compile-fail/array-old-syntax-2.rs @@ -11,5 +11,5 @@ // Test that the old repeating array syntax gives an error. fn main() { - let _ = [0i, ..3]; //~ ERROR + let _ = [0is, ..3]; //~ ERROR } diff --git a/src/test/compile-fail/asm-in-bad-modifier.rs b/src/test/compile-fail/asm-in-bad-modifier.rs index bc240df9b3b..ffbb25e266a 100644 --- a/src/test/compile-fail/asm-in-bad-modifier.rs +++ b/src/test/compile-fail/asm-in-bad-modifier.rs @@ -10,18 +10,18 @@ #![feature(asm)] -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] pub fn main() { - let x: int; - let y: int; + let x: isize; + let y: isize; unsafe { - asm!("mov $1, $0" : "=r"(x) : "=r"(5u)); //~ ERROR input operand constraint contains '=' - asm!("mov $1, $0" : "=r"(y) : "+r"(5u)); //~ ERROR input operand constraint contains '+' + asm!("mov $1, $0" : "=r"(x) : "=r"(5us)); //~ ERROR input operand constraint contains '=' + asm!("mov $1, $0" : "=r"(y) : "+r"(5us)); //~ ERROR input operand constraint contains '+' } foo(x); foo(y); diff --git a/src/test/compile-fail/asm-misplaced-option.rs b/src/test/compile-fail/asm-misplaced-option.rs index b29899e1940..8bc6f206dec 100644 --- a/src/test/compile-fail/asm-misplaced-option.rs +++ b/src/test/compile-fail/asm-misplaced-option.rs @@ -18,17 +18,17 @@ target_arch = "x86_64"))] pub fn main() { // assignment not dead - let mut x: int = 0; + let mut x: isize = 0; unsafe { // extra colon - asm!("mov $1, $0" : "=r"(x) : "r"(5u), "0"(x) : : "cc"); + asm!("mov $1, $0" : "=r"(x) : "r"(5us), "0"(x) : : "cc"); //~^ WARNING unrecognized option } assert_eq!(x, 5); unsafe { // comma in place of a colon - asm!("add $2, $1; mov $1, $0" : "=r"(x) : "r"(x), "r"(8u) : "cc", "volatile"); + asm!("add $2, $1; mov $1, $0" : "=r"(x) : "r"(x), "r"(8us) : "cc", "volatile"); //~^ WARNING expected a clobber, found an option } assert_eq!(x, 13); diff --git a/src/test/compile-fail/asm-out-assign-imm.rs b/src/test/compile-fail/asm-out-assign-imm.rs index 387b4bec47e..9ad5d7e9f09 100644 --- a/src/test/compile-fail/asm-out-assign-imm.rs +++ b/src/test/compile-fail/asm-out-assign-imm.rs @@ -10,18 +10,18 @@ #![feature(asm)] -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] pub fn main() { - let x: int; + let x: isize; x = 1; //~ NOTE prior assignment occurs here foo(x); unsafe { - asm!("mov $1, $0" : "=r"(x) : "r"(5u)); //~ ERROR re-assignment of immutable variable `x` + asm!("mov $1, $0" : "=r"(x) : "r"(5us)); //~ ERROR re-assignment of immutable variable `x` } foo(x); } diff --git a/src/test/compile-fail/asm-out-no-modifier.rs b/src/test/compile-fail/asm-out-no-modifier.rs index 4690bdc40cb..b58d41e1d82 100644 --- a/src/test/compile-fail/asm-out-no-modifier.rs +++ b/src/test/compile-fail/asm-out-no-modifier.rs @@ -10,16 +10,16 @@ #![feature(asm)] -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] pub fn main() { - let x: int; + let x: isize; unsafe { - asm!("mov $1, $0" : "r"(x) : "r"(5u)); //~ ERROR output operand constraint lacks '=' + asm!("mov $1, $0" : "r"(x) : "r"(5us)); //~ ERROR output operand constraint lacks '=' } foo(x); } diff --git a/src/test/compile-fail/asm-out-read-uninit.rs b/src/test/compile-fail/asm-out-read-uninit.rs index 2577dcc3f99..5e71a2c731d 100644 --- a/src/test/compile-fail/asm-out-read-uninit.rs +++ b/src/test/compile-fail/asm-out-read-uninit.rs @@ -10,14 +10,14 @@ #![feature(asm)] -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] pub fn main() { - let x: int; + let x: isize; unsafe { asm!("mov $1, $0" : "=r"(x) : "r"(x)); //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/assign-imm-local-twice.rs b/src/test/compile-fail/assign-imm-local-twice.rs index 77f47a028d6..540272a8e2c 100644 --- a/src/test/compile-fail/assign-imm-local-twice.rs +++ b/src/test/compile-fail/assign-imm-local-twice.rs @@ -9,7 +9,7 @@ // except according to those terms. fn test() { - let v: int; + let v: isize; v = 1; //~ NOTE prior assignment occurs here println!("v={}", v); v = 2; //~ ERROR re-assignment of immutable variable diff --git a/src/test/compile-fail/assign-to-method.rs b/src/test/compile-fail/assign-to-method.rs index f14668192f8..0694420e766 100644 --- a/src/test/compile-fail/assign-to-method.rs +++ b/src/test/compile-fail/assign-to-method.rs @@ -9,16 +9,16 @@ // except according to those terms. struct cat { - meows : uint, + meows : usize, - how_hungry : int, + how_hungry : isize, } impl cat { - pub fn speak(&self) { self.meows += 1u; } + pub fn speak(&self) { self.meows += 1us; } } -fn cat(in_x : uint, in_y : int) -> cat { +fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y @@ -26,6 +26,6 @@ fn cat(in_x : uint, in_y : int) -> cat { } fn main() { - let nyan : cat = cat(52u, 99); + let nyan : cat = cat(52us, 99); nyan.speak = |&:| println!("meow"); //~ ERROR attempted to take value of method } diff --git a/src/test/compile-fail/syntax-extension-bytes-too-large-integer-literal.rs b/src/test/compile-fail/assoc-inherent.rs index 8e7c6147758..ba8e4a652d3 100644 --- a/src/test/compile-fail/syntax-extension-bytes-too-large-integer-literal.rs +++ b/src/test/compile-fail/assoc-inherent.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// 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. // @@ -8,7 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main() { - let vec = bytes!(1024); //~ ERROR too large integer literal in bytes! - //~^ WARN `bytes!` is deprecated +// Test associated types are forbidden in inherant impls. + +struct Foo; + +impl Foo { + type Bar = isize; //~ERROR associated items are not allowed in inherent impls } + +fn main() {} diff --git a/src/test/compile-fail/associated-types-bound-failure.rs b/src/test/compile-fail/associated-types-bound-failure.rs index 918826bb390..adccd73beae 100644 --- a/src/test/compile-fail/associated-types-bound-failure.rs +++ b/src/test/compile-fail/associated-types-bound-failure.rs @@ -11,7 +11,7 @@ // Test equality constraints on associated types in a where clause. pub trait ToInt { - fn to_int(&self) -> int; + fn to_int(&self) -> isize; } pub trait GetToInt @@ -21,13 +21,13 @@ pub trait GetToInt fn get(&self) -> <Self as GetToInt>::R; } -fn foo<G>(g: G) -> int +fn foo<G>(g: G) -> isize where G : GetToInt { ToInt::to_int(&g.get()) //~ ERROR not implemented } -fn bar<G : GetToInt>(g: G) -> int +fn bar<G : GetToInt>(g: G) -> isize where G::R : ToInt { ToInt::to_int(&g.get()) // OK diff --git a/src/test/compile-fail/associated-types-coherence-failure.rs b/src/test/compile-fail/associated-types-coherence-failure.rs new file mode 100644 index 00000000000..95a68dd6698 --- /dev/null +++ b/src/test/compile-fail/associated-types-coherence-failure.rs @@ -0,0 +1,59 @@ +// 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. + +// Test that coherence detects overlap when some of the types in the +// impls are projections of associated type. Issue #20624. + +use std::ops::Deref; + +pub struct Cow<'a, B: ?Sized>; + +/// Trait for moving into a `Cow` +pub trait IntoCow<'a, B: ?Sized> { + /// Moves `self` into `Cow` + fn into_cow(self) -> Cow<'a, B>; +} + +impl<'a, B: ?Sized> IntoCow<'a, B> for Cow<'a, B> where B: ToOwned { +//~^ ERROR E0119 + fn into_cow(self) -> Cow<'a, B> { + self + } +} + +impl<'a, B: ?Sized> IntoCow<'a, B> for <B as ToOwned>::Owned where B: ToOwned { +//~^ ERROR E0119 + fn into_cow(self) -> Cow<'a, B> { + Cow + } +} + +impl<'a, B: ?Sized> IntoCow<'a, B> for &'a B where B: ToOwned { + fn into_cow(self) -> Cow<'a, B> { + Cow + } +} + +impl ToOwned for u8 { + type Owned = &'static u8; + fn to_owned(&self) -> &'static u8 { panic!() } +} + +/// A generalization of Clone to borrowed data. +pub trait ToOwned { + type Owned; + + /// Create owned data from borrowed data, usually by copying. + fn to_owned(&self) -> Self::Owned; +} + + +fn main() {} + diff --git a/src/test/compile-fail/associated-types-eq-2.rs b/src/test/compile-fail/associated-types-eq-2.rs index e298d05d11d..755a9f2d73f 100644 --- a/src/test/compile-fail/associated-types-eq-2.rs +++ b/src/test/compile-fail/associated-types-eq-2.rs @@ -18,9 +18,9 @@ pub trait Foo { struct Bar; -impl Foo for int { - type A = uint; - fn boo(&self) -> uint { 42 } +impl Foo for isize { + type A = usize; + fn boo(&self) -> usize { 42 } } fn baz<I: Foo>(x: &<I as Foo<A=Bar>>::A) {} diff --git a/src/test/compile-fail/associated-types-eq-3.rs b/src/test/compile-fail/associated-types-eq-3.rs index b56f971db74..ed81c0fccbc 100644 --- a/src/test/compile-fail/associated-types-eq-3.rs +++ b/src/test/compile-fail/associated-types-eq-3.rs @@ -18,9 +18,9 @@ pub trait Foo { struct Bar; -impl Foo for int { - type A = uint; - fn boo(&self) -> uint { +impl Foo for isize { + type A = usize; + fn boo(&self) -> usize { 42 } } @@ -40,7 +40,7 @@ pub fn baz(x: &Foo<A=Bar>) { pub fn main() { - let a = 42i; + let a = 42is; foo1(a); //~ERROR expected usize, found struct Bar baz(&a); //~ERROR expected usize, found struct Bar } diff --git a/src/test/compile-fail/associated-types-eq-expr-path.rs b/src/test/compile-fail/associated-types-eq-expr-path.rs index ef56fdeb051..9baa7f1ad5a 100644 --- a/src/test/compile-fail/associated-types-eq-expr-path.rs +++ b/src/test/compile-fail/associated-types-eq-expr-path.rs @@ -12,15 +12,15 @@ trait Foo { type A; - fn bar() -> int; + fn bar() -> isize; } -impl Foo for int { - type A = uint; - fn bar() -> int { 42 } +impl Foo for isize { + type A = usize; + fn bar() -> isize { 42 } } pub fn main() { - let x: int = Foo::<A=uint>::bar(); + let x: isize = Foo::<A=usize>::bar(); //~^ERROR unexpected binding of associated item in expression path } diff --git a/src/test/compile-fail/associated-types-eq-hr.rs b/src/test/compile-fail/associated-types-eq-hr.rs index 2532977b1ca..d5678c155fd 100644 --- a/src/test/compile-fail/associated-types-eq-hr.rs +++ b/src/test/compile-fail/associated-types-eq-hr.rs @@ -17,43 +17,43 @@ pub trait TheTrait<T> { } struct IntStruct { - x: int + x: isize } -impl<'a> TheTrait<&'a int> for IntStruct { - type A = &'a int; +impl<'a> TheTrait<&'a isize> for IntStruct { + type A = &'a isize; - fn get(&self, t: &'a int) -> &'a int { + fn get(&self, t: &'a isize) -> &'a isize { t } } struct UintStruct { - x: int + x: isize } -impl<'a> TheTrait<&'a int> for UintStruct { - type A = &'a uint; +impl<'a> TheTrait<&'a isize> for UintStruct { + type A = &'a usize; - fn get(&self, t: &'a int) -> &'a uint { + fn get(&self, t: &'a isize) -> &'a usize { panic!() } } fn foo<T>() - where T : for<'x> TheTrait<&'x int, A = &'x int> + where T : for<'x> TheTrait<&'x isize, A = &'x isize> { // ok for IntStruct, but not UintStruct } fn bar<T>() - where T : for<'x> TheTrait<&'x int, A = &'x uint> + where T : for<'x> TheTrait<&'x isize, A = &'x usize> { // ok for UintStruct, but not IntStruct } fn baz<T>() - where T : for<'x,'y> TheTrait<&'x int, A = &'y int> + where T : for<'x,'y> TheTrait<&'x isize, A = &'y isize> { // not ok for either struct, due to the use of two lifetimes } diff --git a/src/test/compile-fail/associated-types-incomplete-object.rs b/src/test/compile-fail/associated-types-incomplete-object.rs index 371f97e867a..31492406fed 100644 --- a/src/test/compile-fail/associated-types-incomplete-object.rs +++ b/src/test/compile-fail/associated-types-incomplete-object.rs @@ -19,24 +19,24 @@ pub trait Foo { struct Bar; -impl Foo for int { - type A = uint; +impl Foo for isize { + type A = usize; type B = char; - fn boo(&self) -> uint { + fn boo(&self) -> usize { 42 } } pub fn main() { - let a = &42i as &Foo<A=uint, B=char>; + let a = &42is as &Foo<A=usize, B=char>; - let b = &42i as &Foo<A=uint>; + let b = &42is as &Foo<A=usize>; //~^ ERROR the value of the associated type `B` (from the trait `Foo`) must be specified - let c = &42i as &Foo<B=char>; + let c = &42is as &Foo<B=char>; //~^ ERROR the value of the associated type `A` (from the trait `Foo`) must be specified - let d = &42i as &Foo; + let d = &42is as &Foo; //~^ ERROR the value of the associated type `A` (from the trait `Foo`) must be specified //~| ERROR the value of the associated type `B` (from the trait `Foo`) must be specified } diff --git a/src/test/compile-fail/associated-types-invalid-trait-ref-issue-18865.rs b/src/test/compile-fail/associated-types-invalid-trait-ref-issue-18865.rs index 13f6dcc9fde..b6c4d59c848 100644 --- a/src/test/compile-fail/associated-types-invalid-trait-ref-issue-18865.rs +++ b/src/test/compile-fail/associated-types-invalid-trait-ref-issue-18865.rs @@ -16,7 +16,7 @@ trait Foo<T> { fn get_bar(&self) -> Self::Bar; } -fn f<T:Foo<int>>(t: &T) { +fn f<T:Foo<isize>>(t: &T) { let u: <T as Foo<usize>>::Bar = t.get_bar(); //~^ ERROR the trait `Foo<usize>` is not implemented for the type `T` } diff --git a/src/test/compile-fail/associated-types-issue-17359.rs b/src/test/compile-fail/associated-types-issue-17359.rs index 6c79105abee..fa09ae793bf 100644 --- a/src/test/compile-fail/associated-types-issue-17359.rs +++ b/src/test/compile-fail/associated-types-issue-17359.rs @@ -15,7 +15,7 @@ trait Trait { type Type; } -impl Trait for int {} //~ ERROR missing: `Type` +impl Trait for isize {} //~ ERROR missing: `Type` fn main() {} diff --git a/src/test/compile-fail/associated-types-multiple-types-one-trait.rs b/src/test/compile-fail/associated-types-multiple-types-one-trait.rs new file mode 100644 index 00000000000..9436f825de8 --- /dev/null +++ b/src/test/compile-fail/associated-types-multiple-types-one-trait.rs @@ -0,0 +1,56 @@ +// 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. + +trait Foo { + type X; + type Y; +} + +fn have_x_want_x<T:Foo<X=u32>>(t: &T) +{ + want_x(t); +} + +fn have_x_want_y<T:Foo<X=u32>>(t: &T) +{ + want_y(t); //~ ERROR type mismatch +} + +fn have_y_want_x<T:Foo<Y=i32>>(t: &T) +{ + want_x(t); //~ ERROR type mismatch +} + +fn have_y_want_y<T:Foo<Y=i32>>(t: &T) +{ + want_y(t); +} + +fn have_xy_want_x<T:Foo<X=u32,Y=i32>>(t: &T) +{ + want_x(t); +} + +fn have_xy_want_y<T:Foo<X=u32,Y=i32>>(t: &T) +{ + want_y(t); +} + +fn have_xy_want_xy<T:Foo<X=u32,Y=i32>>(t: &T) +{ + want_x(t); + want_y(t); +} + +fn want_x<T:Foo<X=u32>>(t: &T) { } + +fn want_y<T:Foo<Y=i32>>(t: &T) { } + +fn main() { } diff --git a/src/test/compile-fail/associated-types-no-suitable-bound.rs b/src/test/compile-fail/associated-types-no-suitable-bound.rs index 98f2355f9be..fd60896c298 100644 --- a/src/test/compile-fail/associated-types-no-suitable-bound.rs +++ b/src/test/compile-fail/associated-types-no-suitable-bound.rs @@ -14,7 +14,7 @@ trait Get { } struct Struct { - x: int, + x: isize, } impl Struct { diff --git a/src/test/compile-fail/associated-types-path-2.rs b/src/test/compile-fail/associated-types-path-2.rs index 9994a0c465f..74c8dffced5 100644 --- a/src/test/compile-fail/associated-types-path-2.rs +++ b/src/test/compile-fail/associated-types-path-2.rs @@ -14,8 +14,8 @@ pub trait Foo { type A; } -impl Foo for int { - type A = uint; +impl Foo for isize { + type A = usize; } pub fn f1<T: Foo>(a: T, x: T::A) {} @@ -45,7 +45,7 @@ pub fn f1_uint_int() { } pub fn f2_int() { - let _: int = f2(2is); + let _: isize = f2(2is); //~^ ERROR expected `isize`, found `usize` } diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs b/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs index c5245840c42..917c03fbf4b 100644 --- a/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs +++ b/src/test/compile-fail/associated-types-project-from-hrtb-explicit.rs @@ -17,7 +17,7 @@ pub trait Foo<T> { fn get(&self, t: T) -> Self::A; } -fn foo2<I>(x: <I as for<'x> Foo<&'x int>>::A) +fn foo2<I>(x: <I as for<'x> Foo<&'x isize>>::A) //~^ ERROR expected identifier, found keyword `for` //~| ERROR expected one of `::` or `>` { diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-in-fn-body.rs b/src/test/compile-fail/associated-types-project-from-hrtb-in-fn-body.rs index 1f1ab4ca4b6..285a77d6b65 100644 --- a/src/test/compile-fail/associated-types-project-from-hrtb-in-fn-body.rs +++ b/src/test/compile-fail/associated-types-project-from-hrtb-in-fn-body.rs @@ -17,15 +17,15 @@ pub trait Foo<T> { fn get(&self, t: T) -> Self::A; } -fn foo<'a, I : for<'x> Foo<&'x int>>( - x: <I as Foo<&'a int>>::A) +fn foo<'a, I : for<'x> Foo<&'x isize>>( + x: <I as Foo<&'a isize>>::A) { let y: I::A = x; } -fn bar<'a, 'b, I : for<'x> Foo<&'x int>>( - x: <I as Foo<&'a int>>::A, - y: <I as Foo<&'b int>>::A, +fn bar<'a, 'b, I : for<'x> Foo<&'x isize>>( + x: <I as Foo<&'a isize>>::A, + y: <I as Foo<&'b isize>>::A, cond: bool) { // x and y here have two distinct lifetimes: diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-in-fn.rs b/src/test/compile-fail/associated-types-project-from-hrtb-in-fn.rs index 0920bfab32b..a79d5c4649a 100644 --- a/src/test/compile-fail/associated-types-project-from-hrtb-in-fn.rs +++ b/src/test/compile-fail/associated-types-project-from-hrtb-in-fn.rs @@ -17,7 +17,7 @@ pub trait Foo<T> { fn get(&self, t: T) -> Self::A; } -fn foo2<I : for<'x> Foo<&'x int>>( +fn foo2<I : for<'x> Foo<&'x isize>>( x: I::A) //~^ ERROR cannot extract an associated type from a higher-ranked trait bound in this context { @@ -28,15 +28,15 @@ fn foo2<I : for<'x> Foo<&'x int>>( // specifically for fn signatures. } -fn foo3<I : for<'x> Foo<&'x int>>( - x: <I as Foo<&int>>::A) +fn foo3<I : for<'x> Foo<&'x isize>>( + x: <I as Foo<&isize>>::A) { // OK, in this case we spelled out the precise regions involved, though we left one of // them anonymous. } -fn foo4<'a, I : for<'x> Foo<&'x int>>( - x: <I as Foo<&'a int>>::A) +fn foo4<'a, I : for<'x> Foo<&'x isize>>( + x: <I as Foo<&'a isize>>::A) { // OK, in this case we spelled out the precise regions involved. } diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-in-struct.rs b/src/test/compile-fail/associated-types-project-from-hrtb-in-struct.rs index 0acb0f4853b..44ad0bb0113 100644 --- a/src/test/compile-fail/associated-types-project-from-hrtb-in-struct.rs +++ b/src/test/compile-fail/associated-types-project-from-hrtb-in-struct.rs @@ -17,18 +17,18 @@ pub trait Foo<T> { fn get(&self, t: T) -> Self::A; } -struct SomeStruct<I : for<'x> Foo<&'x int>> { +struct SomeStruct<I : for<'x> Foo<&'x isize>> { field: I::A //~^ ERROR cannot extract an associated type from a higher-ranked trait bound in this context } -struct AnotherStruct<I : for<'x> Foo<&'x int>> { - field: <I as Foo<&int>>::A +struct AnotherStruct<I : for<'x> Foo<&'x isize>> { + field: <I as Foo<&isize>>::A //~^ ERROR missing lifetime specifier } -struct YetAnotherStruct<'a, I : for<'x> Foo<&'x int>> { - field: <I as Foo<&'a int>>::A +struct YetAnotherStruct<'a, I : for<'x> Foo<&'x isize>> { + field: <I as Foo<&'a isize>>::A } pub fn main() {} diff --git a/src/test/compile-fail/associated-types-project-from-hrtb-in-trait-method.rs b/src/test/compile-fail/associated-types-project-from-hrtb-in-trait-method.rs index 21e92c53058..af46a1b42d0 100644 --- a/src/test/compile-fail/associated-types-project-from-hrtb-in-trait-method.rs +++ b/src/test/compile-fail/associated-types-project-from-hrtb-in-trait-method.rs @@ -17,17 +17,17 @@ pub trait Foo<T> { fn get(&self, t: T) -> Self::A; } -trait SomeTrait<I : for<'x> Foo<&'x int>> { +trait SomeTrait<I : for<'x> Foo<&'x isize>> { fn some_method(&self, arg: I::A); //~^ ERROR cannot extract an associated type from a higher-ranked trait bound in this context } -trait AnotherTrait<I : for<'x> Foo<&'x int>> { - fn some_method(&self, arg: <I as Foo<&int>>::A); +trait AnotherTrait<I : for<'x> Foo<&'x isize>> { + fn some_method(&self, arg: <I as Foo<&isize>>::A); } -trait YetAnotherTrait<I : for<'x> Foo<&'x int>> { - fn some_method<'a>(&self, arg: <I as Foo<&'a int>>::A); +trait YetAnotherTrait<I : for<'x> Foo<&'x isize>> { + fn some_method<'a>(&self, arg: <I as Foo<&'a isize>>::A); } pub fn main() {} diff --git a/src/test/compile-fail/associated-types-unconstrained.rs b/src/test/compile-fail/associated-types-unconstrained.rs index 96863466944..aecbf217a5b 100644 --- a/src/test/compile-fail/associated-types-unconstrained.rs +++ b/src/test/compile-fail/associated-types-unconstrained.rs @@ -12,15 +12,15 @@ trait Foo { type A; - fn bar() -> int; + fn bar() -> isize; } -impl Foo for int { - type A = uint; - fn bar() -> int { 42 } +impl Foo for isize { + type A = usize; + fn bar() -> isize { 42 } } pub fn main() { - let x: int = Foo::bar(); + let x: isize = Foo::bar(); //~^ ERROR type annotations required } diff --git a/src/test/compile-fail/auto-ref-slice-plus-ref.rs b/src/test/compile-fail/auto-ref-slice-plus-ref.rs index fb935cf1030..ad3f467a454 100644 --- a/src/test/compile-fail/auto-ref-slice-plus-ref.rs +++ b/src/test/compile-fail/auto-ref-slice-plus-ref.rs @@ -27,7 +27,7 @@ trait MyIter { fn test(&self); } -impl<'a> MyIter for &'a [int] { +impl<'a> MyIter for &'a [isize] { fn test_mut(&mut self) { } fn test(&self) { } } diff --git a/src/test/compile-fail/autoderef-full-lval.rs b/src/test/compile-fail/autoderef-full-lval.rs index bbe5af1b516..2c5749e0d5d 100644 --- a/src/test/compile-fail/autoderef-full-lval.rs +++ b/src/test/compile-fail/autoderef-full-lval.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct clam { x: Box<isize>, y: Box<isize>, @@ -25,7 +28,7 @@ fn main() { assert_eq!(z, 21); let forty: fish = fish{a: box 40}; let two: fish = fish{a: box 2}; - let answer: int = forty.a + two.a; + let answer: isize = forty.a + two.a; //~^ ERROR binary operation `+` cannot be applied to type `Box<isize>` println!("{}", answer); assert_eq!(answer, 42); diff --git a/src/test/compile-fail/bad-bang-ann-3.rs b/src/test/compile-fail/bad-bang-ann-3.rs index d204c8c750a..e5dbdbd237d 100644 --- a/src/test/compile-fail/bad-bang-ann-3.rs +++ b/src/test/compile-fail/bad-bang-ann-3.rs @@ -10,8 +10,8 @@ // Tests that a function with a ! annotation always actually fails -fn bad_bang(i: uint) -> ! { - return 7u; //~ ERROR `return` in a function declared as diverging [E0166] +fn bad_bang(i: usize) -> ! { + return 7us; //~ ERROR `return` in a function declared as diverging [E0166] } -fn main() { bad_bang(5u); } +fn main() { bad_bang(5us); } diff --git a/src/test/compile-fail/bad-bang-ann.rs b/src/test/compile-fail/bad-bang-ann.rs index 7e8142dbb29..414421c8b77 100644 --- a/src/test/compile-fail/bad-bang-ann.rs +++ b/src/test/compile-fail/bad-bang-ann.rs @@ -10,8 +10,8 @@ // Tests that a function with a ! annotation always actually fails -fn bad_bang(i: uint) -> ! { //~ ERROR computation may converge in a function marked as diverging - if i < 0u { } else { panic!(); } +fn bad_bang(i: usize) -> ! { //~ ERROR computation may converge in a function marked as diverging + if i < 0us { } else { panic!(); } } -fn main() { bad_bang(5u); } +fn main() { bad_bang(5us); } diff --git a/src/test/compile-fail/bad-env-capture.rs b/src/test/compile-fail/bad-env-capture.rs index ac5a4c220a4..93866488732 100644 --- a/src/test/compile-fail/bad-env-capture.rs +++ b/src/test/compile-fail/bad-env-capture.rs @@ -10,7 +10,7 @@ // error-pattern: can't capture dynamic environment in a fn item; fn foo() { - let x: int; + let x: isize; fn bar() { log(debug, x); } } fn main() { foo(); } diff --git a/src/test/compile-fail/bad-env-capture2.rs b/src/test/compile-fail/bad-env-capture2.rs index c97069acd9a..39a6922cfd0 100644 --- a/src/test/compile-fail/bad-env-capture2.rs +++ b/src/test/compile-fail/bad-env-capture2.rs @@ -9,7 +9,7 @@ // except according to those terms. // error-pattern: can't capture dynamic environment in a fn item; -fn foo(x: int) { +fn foo(x: isize) { fn bar() { log(debug, x); } } fn main() { foo(2); } diff --git a/src/test/compile-fail/bad-env-capture3.rs b/src/test/compile-fail/bad-env-capture3.rs index e3a6ac2cdfc..8857b94ddce 100644 --- a/src/test/compile-fail/bad-env-capture3.rs +++ b/src/test/compile-fail/bad-env-capture3.rs @@ -9,7 +9,7 @@ // except according to those terms. // error-pattern: can't capture dynamic environment in a fn item; -fn foo(x: int) { +fn foo(x: isize) { fn mth() { fn bar() { log(debug, x); } } diff --git a/src/test/compile-fail/bad-main.rs b/src/test/compile-fail/bad-main.rs index da8596fa25b..321dca89891 100644 --- a/src/test/compile-fail/bad-main.rs +++ b/src/test/compile-fail/bad-main.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main(x: int) { } //~ ERROR: main function expects type +fn main(x: isize) { } //~ ERROR: main function expects type diff --git a/src/test/compile-fail/bad-match.rs b/src/test/compile-fail/bad-match.rs index 728b577df1d..33043ff5524 100644 --- a/src/test/compile-fail/bad-match.rs +++ b/src/test/compile-fail/bad-match.rs @@ -11,7 +11,7 @@ // error-pattern: expected fn main() { - let int x = 5; + let isize x = 5; match x; } diff --git a/src/test/compile-fail/bad-method-typaram-kind.rs b/src/test/compile-fail/bad-method-typaram-kind.rs index 349c33a30a5..8e5a6054b89 100644 --- a/src/test/compile-fail/bad-method-typaram-kind.rs +++ b/src/test/compile-fail/bad-method-typaram-kind.rs @@ -9,14 +9,14 @@ // except according to those terms. fn foo<T:'static>() { - 1u.bar::<T>(); //~ ERROR `core::marker::Send` is not implemented + 1us.bar::<T>(); //~ ERROR `core::marker::Send` is not implemented } trait bar { fn bar<T:Send>(&self); } -impl bar for uint { +impl bar for usize { fn bar<T:Send>(&self) { } } diff --git a/src/test/compile-fail/bad-mid-path-type-params.rs b/src/test/compile-fail/bad-mid-path-type-params.rs index 3a2a7558657..79fe4e7165e 100644 --- a/src/test/compile-fail/bad-mid-path-type-params.rs +++ b/src/test/compile-fail/bad-mid-path-type-params.rs @@ -33,11 +33,11 @@ trait Trait<T> { } struct S2 { - contents: int, + contents: isize, } -impl Trait<int> for S2 { - fn new<U>(x: int, _: U) -> S2 { +impl Trait<isize> for S2 { + fn new<U>(x: isize, _: U) -> S2 { S2 { contents: x, } @@ -45,16 +45,16 @@ impl Trait<int> for S2 { } fn foo<'a>() { - let _ = S::new::<int,f64>(1, 1.0); + let _ = S::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided - let _ = S::<'a,int>::new::<f64>(1, 1.0); + let _ = S::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR too many lifetime parameters provided - let _: S2 = Trait::new::<int,f64>(1, 1.0); + let _: S2 = Trait::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided - let _: S2 = Trait::<'a,int>::new::<f64>(1, 1.0); + let _: S2 = Trait::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR too many lifetime parameters provided } diff --git a/src/test/compile-fail/bad-name.rs b/src/test/compile-fail/bad-name.rs index e320d5918b6..b208c6f4244 100644 --- a/src/test/compile-fail/bad-name.rs +++ b/src/test/compile-fail/bad-name.rs @@ -11,5 +11,5 @@ // error-pattern: expected fn main() { - let x.y::<int>.z foo; + let x.y::<isize>.z foo; } diff --git a/src/test/compile-fail/bang-tailexpr.rs b/src/test/compile-fail/bang-tailexpr.rs index ec576ff4bd8..d17fa68b47c 100644 --- a/src/test/compile-fail/bang-tailexpr.rs +++ b/src/test/compile-fail/bang-tailexpr.rs @@ -9,6 +9,6 @@ // except according to those terms. fn f() -> ! { //~ ERROR computation may converge in a function marked as diverging - 3i + 3is } fn main() { } diff --git a/src/test/compile-fail/better-expected.rs b/src/test/compile-fail/better-expected.rs index 672d8a30fc5..0d84a5e7d02 100644 --- a/src/test/compile-fail/better-expected.rs +++ b/src/test/compile-fail/better-expected.rs @@ -9,5 +9,5 @@ // except according to those terms. fn main() { - let x: [int 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `3` + let x: [isize 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `3` } diff --git a/src/test/compile-fail/bind-struct-early-modifiers.rs b/src/test/compile-fail/bind-struct-early-modifiers.rs index 3671cf110d8..375f6c5d047 100644 --- a/src/test/compile-fail/bind-struct-early-modifiers.rs +++ b/src/test/compile-fail/bind-struct-early-modifiers.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - struct Foo { x: int } + struct Foo { x: isize } match (Foo { x: 10 }) { Foo { ref x: ref x } => {}, //~ ERROR unexpected `:` _ => {} diff --git a/src/test/compile-fail/binop-move-semantics.rs b/src/test/compile-fail/binop-move-semantics.rs index ffc38cc0a60..cff0064497a 100644 --- a/src/test/compile-fail/binop-move-semantics.rs +++ b/src/test/compile-fail/binop-move-semantics.rs @@ -37,9 +37,9 @@ fn illegal_dereference<T: Add<Output=()>>(mut x: T, y: T) { let m = &mut x; let n = &y; - *m //~ ERROR: cannot move out of dereference of `&mut`-pointer + *m //~ ERROR: cannot move out of borrowed content + - *n; //~ ERROR: cannot move out of dereference of `&`-pointer + *n; //~ ERROR: cannot move out of borrowed content } struct Foo; diff --git a/src/test/compile-fail/bogus-tag.rs b/src/test/compile-fail/bogus-tag.rs index cc0ed214103..704d856f106 100644 --- a/src/test/compile-fail/bogus-tag.rs +++ b/src/test/compile-fail/bogus-tag.rs @@ -11,7 +11,7 @@ // error-pattern: unresolved -enum color { rgb(int, int, int), rgba(int, int, int, int), } +enum color { rgb(isize, isize, isize), rgba(isize, isize, isize, isize), } fn main() { let red: color = rgb(255, 0, 0); diff --git a/src/test/compile-fail/borrow-immutable-upvar-mutation.rs b/src/test/compile-fail/borrow-immutable-upvar-mutation.rs index f748c400654..12555c55072 100644 --- a/src/test/compile-fail/borrow-immutable-upvar-mutation.rs +++ b/src/test/compile-fail/borrow-immutable-upvar-mutation.rs @@ -13,29 +13,29 @@ // Tests that we can't assign to or mutably borrow upvars from `Fn` // closures (issue #17780) -fn set(x: &mut uint) { *x = 5; } +fn set(x: &mut usize) { *x = 5; } fn main() { // By-ref captures { - let mut x = 0u; + let mut x = 0us; let _f = |&:| x = 42; //~ ERROR cannot assign - let mut y = 0u; + let mut y = 0us; let _g = |&:| set(&mut y); //~ ERROR cannot borrow - let mut z = 0u; + let mut z = 0us; let _h = |&mut:| { set(&mut z); |&:| z = 42; }; //~ ERROR cannot assign } // By-value captures { - let mut x = 0u; + let mut x = 0us; let _f = move |&:| x = 42; //~ ERROR cannot assign - let mut y = 0u; + let mut y = 0us; let _g = move |&:| set(&mut y); //~ ERROR cannot borrow - let mut z = 0u; + let mut z = 0us; let _h = move |&mut:| { set(&mut z); move |&:| z = 42; }; //~ ERROR cannot assign } } diff --git a/src/test/compile-fail/borrow-tuple-fields.rs b/src/test/compile-fail/borrow-tuple-fields.rs index 1d09143c24d..e6fe60a9004 100644 --- a/src/test/compile-fail/borrow-tuple-fields.rs +++ b/src/test/compile-fail/borrow-tuple-fields.rs @@ -8,33 +8,36 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo(Box<int>, int); +#![allow(unknown_features)] +#![feature(box_syntax)] -struct Bar(int, int); +struct Foo(Box<isize>, isize); + +struct Bar(isize, isize); fn main() { - let x = (box 1i, 2i); + let x = (box 1is, 2is); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed - let mut x = (1i, 2i); + let mut x = (1is, 2is); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as - let mut x = (1i, 2i); + let mut x = (1is, 2is); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time - let x = Foo(box 1i, 2i); + let x = Foo(box 1is, 2is); let r = &x.0; let y = x; //~ ERROR cannot move out of `x` because it is borrowed - let mut x = Bar(1i, 2i); + let mut x = Bar(1is, 2is); let a = &x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as - let mut x = Bar(1i, 2i); + let mut x = Bar(1is, 2is); let a = &mut x.0; let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time } diff --git a/src/test/compile-fail/borrowck-and-init.rs b/src/test/compile-fail/borrowck-and-init.rs index 0f07cab3acc..92f16d8ffce 100644 --- a/src/test/compile-fail/borrowck-and-init.rs +++ b/src/test/compile-fail/borrowck-and-init.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let i: int; + let i: isize; println!("{}", false && { i = 5; true }); println!("{}", i); //~ ERROR use of possibly uninitialized variable: `i` diff --git a/src/test/compile-fail/borrowck-anon-fields-struct.rs b/src/test/compile-fail/borrowck-anon-fields-struct.rs index 514dd584c6a..5ee2b89dd98 100644 --- a/src/test/compile-fail/borrowck-anon-fields-struct.rs +++ b/src/test/compile-fail/borrowck-anon-fields-struct.rs @@ -11,7 +11,7 @@ // Tests that we are able to distinguish when loans borrow different // anonymous fields of a tuple vs the same anonymous field. -struct Y(uint, uint); +struct Y(usize, usize); fn distinct_variant() { let mut y = Y(1, 2); diff --git a/src/test/compile-fail/borrowck-anon-fields-tuple.rs b/src/test/compile-fail/borrowck-anon-fields-tuple.rs index 9a452ed18f6..88486756b66 100644 --- a/src/test/compile-fail/borrowck-anon-fields-tuple.rs +++ b/src/test/compile-fail/borrowck-anon-fields-tuple.rs @@ -12,7 +12,7 @@ // anonymous fields of a tuple vs the same anonymous field. fn distinct_variant() { - let mut y = (1i, 2i); + let mut y = (1is, 2is); let a = match y { (ref mut a, _) => a @@ -27,7 +27,7 @@ fn distinct_variant() { } fn same_variant() { - let mut y = (1i, 2i); + let mut y = (1is, 2is); let a = match y { (ref mut a, _) => a diff --git a/src/test/compile-fail/borrowck-anon-fields-variant.rs b/src/test/compile-fail/borrowck-anon-fields-variant.rs index 8b54f146d04..4e1b85283a6 100644 --- a/src/test/compile-fail/borrowck-anon-fields-variant.rs +++ b/src/test/compile-fail/borrowck-anon-fields-variant.rs @@ -12,7 +12,7 @@ // anonymous fields of an enum variant vs the same anonymous field. enum Foo { - X, Y(uint, uint) + X, Y(usize, usize) } fn distinct_variant() { diff --git a/src/test/compile-fail/borrowck-array-double-move.rs b/src/test/compile-fail/borrowck-array-double-move.rs index c872d0dc4b9..ac9ddc2ce65 100644 --- a/src/test/compile-fail/borrowck-array-double-move.rs +++ b/src/test/compile-fail/borrowck-array-double-move.rs @@ -8,10 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f() { - let mut a = [box 0i, box 1i]; + let mut a = [box 0is, box 1is]; drop(a[0]); - a[1] = box 2i; + a[1] = box 2is; drop(a[0]); //~ ERROR use of moved value: `a[..]` } diff --git a/src/test/compile-fail/borrowck-assign-comp-idx.rs b/src/test/compile-fail/borrowck-assign-comp-idx.rs index a6801a6a51a..3a2c6f03851 100644 --- a/src/test/compile-fail/borrowck-assign-comp-idx.rs +++ b/src/test/compile-fail/borrowck-assign-comp-idx.rs @@ -9,22 +9,22 @@ // except according to those terms. struct Point { - x: int, - y: int, + x: isize, + y: isize, } fn a() { let mut p = vec!(1); // Create an immutable pointer into p's contents: - let q: &int = &p[0]; + let q: &isize = &p[0]; p[0] = 5; //~ ERROR cannot borrow println!("{}", *q); } -fn borrow<F>(_x: &[int], _f: F) where F: FnOnce() {} +fn borrow<F>(_x: &[isize], _f: F) where F: FnOnce() {} fn b() { // here we alias the mutable vector into an imm slice and try to diff --git a/src/test/compile-fail/borrowck-assign-comp.rs b/src/test/compile-fail/borrowck-assign-comp.rs index ccd0542ca7f..802b83119b7 100644 --- a/src/test/compile-fail/borrowck-assign-comp.rs +++ b/src/test/compile-fail/borrowck-assign-comp.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct point { x: int, y: int } +struct point { x: isize, y: isize } fn a() { let mut p = point {x: 3, y: 4}; @@ -16,7 +16,7 @@ fn a() { // This assignment is illegal because the field x is not // inherently mutable; since `p` was made immutable, `p.x` is now - // immutable. Otherwise the type of &_q.x (&int) would be wrong. + // immutable. Otherwise the type of &_q.x (&isize) would be wrong. p.x = 5; //~ ERROR cannot assign to `p.x` q.x; } diff --git a/src/test/compile-fail/borrowck-assign-to-andmut-in-aliasable-loc.rs b/src/test/compile-fail/borrowck-assign-to-andmut-in-aliasable-loc.rs index 3fa840f6a4e..d66cdb99a74 100644 --- a/src/test/compile-fail/borrowck-assign-to-andmut-in-aliasable-loc.rs +++ b/src/test/compile-fail/borrowck-assign-to-andmut-in-aliasable-loc.rs @@ -12,7 +12,7 @@ // borrowed (but otherwise non-aliasable) location is illegal. struct S<'a> { - pointer: &'a mut int + pointer: &'a mut isize } fn a(s: &S) { diff --git a/src/test/compile-fail/borrowck-assign-to-andmut-in-borrowed-loc.rs b/src/test/compile-fail/borrowck-assign-to-andmut-in-borrowed-loc.rs index ccbbc2ea6c3..77aa57ef1b5 100644 --- a/src/test/compile-fail/borrowck-assign-to-andmut-in-borrowed-loc.rs +++ b/src/test/compile-fail/borrowck-assign-to-andmut-in-borrowed-loc.rs @@ -12,7 +12,7 @@ // borrowed (but otherwise non-aliasable) location is illegal. struct S<'a> { - pointer: &'a mut int + pointer: &'a mut isize } fn copy_borrowed_ptr<'a>(p: &'a mut S<'a>) -> S<'a> { diff --git a/src/test/compile-fail/borrowck-assign-to-constants.rs b/src/test/compile-fail/borrowck-assign-to-constants.rs index c0fb24c83e3..1b5b1899e0d 100644 --- a/src/test/compile-fail/borrowck-assign-to-constants.rs +++ b/src/test/compile-fail/borrowck-assign-to-constants.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static foo: int = 5; +static foo: isize = 5; fn main() { // assigning to various global constants diff --git a/src/test/compile-fail/borrowck-auto-mut-ref-to-immut-var.rs b/src/test/compile-fail/borrowck-auto-mut-ref-to-immut-var.rs index dcfef4e1d9c..ea020dc0685 100644 --- a/src/test/compile-fail/borrowck-auto-mut-ref-to-immut-var.rs +++ b/src/test/compile-fail/borrowck-auto-mut-ref-to-immut-var.rs @@ -11,7 +11,7 @@ // Tests that auto-ref can't create mutable aliases to immutable memory. struct Foo { - x: int + x: isize } impl Foo { diff --git a/src/test/compile-fail/borrowck-autoref-3261.rs b/src/test/compile-fail/borrowck-autoref-3261.rs index 2804b8c48a7..d5f09305808 100644 --- a/src/test/compile-fail/borrowck-autoref-3261.rs +++ b/src/test/compile-fail/borrowck-autoref-3261.rs @@ -10,10 +10,10 @@ enum Either<T, U> { Left(T), Right(U) } -struct X(Either<(uint,uint), fn()>); +struct X(Either<(usize,usize), fn()>); impl X { - pub fn with<F>(&self, blk: F) where F: FnOnce(&Either<(uint, uint), fn()>) { + pub fn with<F>(&self, blk: F) where F: FnOnce(&Either<(usize, usize), fn()>) { let X(ref e) = *self; blk(e) } diff --git a/src/test/compile-fail/borrowck-bad-nested-calls-free.rs b/src/test/compile-fail/borrowck-bad-nested-calls-free.rs index ab2fc6c67b4..4d1939be5b9 100644 --- a/src/test/compile-fail/borrowck-bad-nested-calls-free.rs +++ b/src/test/compile-fail/borrowck-bad-nested-calls-free.rs @@ -11,13 +11,14 @@ // Test that we detect nested calls that could free pointers evaluated // for earlier arguments. +#![feature(box_syntax)] -fn rewrite(v: &mut Box<uint>) -> uint { +fn rewrite(v: &mut Box<usize>) -> usize { *v = box 22; **v } -fn add(v: &uint, w: uint) -> uint { +fn add(v: &usize, w: usize) -> usize { *v + w } diff --git a/src/test/compile-fail/borrowck-bad-nested-calls-move.rs b/src/test/compile-fail/borrowck-bad-nested-calls-move.rs index 708eed0d113..9eda3689334 100644 --- a/src/test/compile-fail/borrowck-bad-nested-calls-move.rs +++ b/src/test/compile-fail/borrowck-bad-nested-calls-move.rs @@ -11,13 +11,14 @@ // Test that we detect nested calls that could free pointers evaluated // for earlier arguments. +#![feature(box_syntax)] -fn rewrite(v: &mut Box<uint>) -> uint { +fn rewrite(v: &mut Box<usize>) -> usize { *v = box 22; **v } -fn add(v: &uint, w: Box<uint>) -> uint { +fn add(v: &usize, w: Box<usize>) -> usize { *v + *w } diff --git a/src/test/compile-fail/borrowck-block-unint.rs b/src/test/compile-fail/borrowck-block-unint.rs index e519e57d178..a09ee439245 100644 --- a/src/test/compile-fail/borrowck-block-unint.rs +++ b/src/test/compile-fail/borrowck-block-unint.rs @@ -10,7 +10,7 @@ fn force<F>(f: F) where F: FnOnce() { f(); } fn main() { - let x: int; + let x: isize; force(|| { //~ ERROR capture of possibly uninitialized variable: `x` println!("{}", x); }); diff --git a/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs b/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs index d5998c8ca99..397c55a502a 100644 --- a/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs +++ b/src/test/compile-fail/borrowck-borrow-from-owned-ptr.rs @@ -17,8 +17,8 @@ struct Foo { impl Copy for Foo {} struct Bar { - int1: int, - int2: int, + int1: isize, + int2: isize, } impl Copy for Bar {} diff --git a/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs b/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs index d252d442297..ae4c09c59d7 100644 --- a/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs +++ b/src/test/compile-fail/borrowck-borrow-from-stack-variable.rs @@ -16,8 +16,8 @@ struct Foo { impl Copy for Foo {} struct Bar { - int1: int, - int2: int, + int1: isize, + int2: isize, } impl Copy for Bar {} diff --git a/src/test/compile-fail/borrowck-borrow-from-temporary.rs b/src/test/compile-fail/borrowck-borrow-from-temporary.rs index 784bd1e8ae4..fbb3824cd40 100644 --- a/src/test/compile-fail/borrowck-borrow-from-temporary.rs +++ b/src/test/compile-fail/borrowck-borrow-from-temporary.rs @@ -11,9 +11,9 @@ // Test lifetimes are linked properly when we take reference // to interior. -struct Foo(int); +struct Foo(isize); -fn foo<'a>() -> &'a int { +fn foo<'a>() -> &'a isize { let &Foo(ref x) = &Foo(3); //~ ERROR borrowed value does not live long enough x } diff --git a/src/test/compile-fail/borrowck-borrow-immut-deref-of-box-as-mut.rs b/src/test/compile-fail/borrowck-borrow-immut-deref-of-box-as-mut.rs index 7e3c4658fc8..794e0fc6e3a 100644 --- a/src/test/compile-fail/borrowck-borrow-immut-deref-of-box-as-mut.rs +++ b/src/test/compile-fail/borrowck-borrow-immut-deref-of-box-as-mut.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct A; impl A { @@ -18,5 +20,5 @@ impl A { pub fn main() { let a = box A; a.foo(); - //~^ ERROR cannot borrow immutable dereference of `Box` `*a` as mutable + //~^ ERROR cannot borrow immutable `Box` content `*a` as mutable } diff --git a/src/test/compile-fail/borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs b/src/test/compile-fail/borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs index 7bee06b7804..9126058a4e6 100644 --- a/src/test/compile-fail/borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs +++ b/src/test/compile-fail/borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs @@ -13,20 +13,20 @@ // // Example from src/middle/borrowck/doc.rs -fn foo(t0: & &mut int) { +fn foo(t0: & &mut isize) { let t1 = t0; - let p: &int = &**t0; + let p: &isize = &**t0; **t1 = 22; //~ ERROR cannot assign } -fn foo3(t0: &mut &mut int) { +fn foo3(t0: &mut &mut isize) { let t1 = &mut *t0; - let p: &int = &**t0; //~ ERROR cannot borrow + let p: &isize = &**t0; //~ ERROR cannot borrow **t1 = 22; } -fn foo4(t0: & &mut int) { - let x: &mut int = &mut **t0; //~ ERROR cannot borrow +fn foo4(t0: & &mut isize) { + let x: &mut isize = &mut **t0; //~ ERROR cannot borrow *x += 1; } diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref-mut.rs b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref-mut.rs index 66bcfc23808..5db9ad2e3a4 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref-mut.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref-mut.rs @@ -32,25 +32,25 @@ impl<T> DerefMut for Own<T> { } struct Point { - x: int, - y: int + x: isize, + y: isize } impl Point { - fn get(&self) -> (int, int) { + fn get(&self) -> (isize, isize) { (self.x, self.y) } - fn set(&mut self, x: int, y: int) { + fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } - fn x_ref(&self) -> &int { + fn x_ref(&self) -> &isize { &self.x } - fn y_mut(&mut self) -> &mut int { + fn y_mut(&mut self) -> &mut isize { &mut self.y } } @@ -67,15 +67,15 @@ fn deref_mut_field2(mut x: Own<Point>) { let _i = &mut x.y; } -fn deref_extend_field(x: &Own<Point>) -> &int { +fn deref_extend_field(x: &Own<Point>) -> &isize { &x.y } -fn deref_extend_mut_field1(x: &Own<Point>) -> &mut int { +fn deref_extend_mut_field1(x: &Own<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } -fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut int { +fn deref_extend_mut_field2(x: &mut Own<Point>) -> &mut isize { &mut x.y } @@ -126,15 +126,15 @@ fn deref_mut_method2(mut x: Own<Point>) { x.set(0, 0); } -fn deref_extend_method(x: &Own<Point>) -> &int { +fn deref_extend_method(x: &Own<Point>) -> &isize { x.x_ref() } -fn deref_extend_mut_method1(x: &Own<Point>) -> &mut int { +fn deref_extend_mut_method1(x: &Own<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } -fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut int { +fn deref_extend_mut_method2(x: &mut Own<Point>) -> &mut isize { x.y_mut() } diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs index abab9e57ffe..75680de9c9e 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-auto-deref.rs @@ -26,25 +26,25 @@ impl<T> Deref for Rc<T> { } struct Point { - x: int, - y: int + x: isize, + y: isize } impl Point { - fn get(&self) -> (int, int) { + fn get(&self) -> (isize, isize) { (self.x, self.y) } - fn set(&mut self, x: int, y: int) { + fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } - fn x_ref(&self) -> &int { + fn x_ref(&self) -> &isize { &self.x } - fn y_mut(&mut self) -> &mut int { + fn y_mut(&mut self) -> &mut isize { &mut self.y } } @@ -61,15 +61,15 @@ fn deref_mut_field2(mut x: Rc<Point>) { let _i = &mut x.y; //~ ERROR cannot borrow } -fn deref_extend_field(x: &Rc<Point>) -> &int { +fn deref_extend_field(x: &Rc<Point>) -> &isize { &x.y } -fn deref_extend_mut_field1(x: &Rc<Point>) -> &mut int { +fn deref_extend_mut_field1(x: &Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } -fn deref_extend_mut_field2(x: &mut Rc<Point>) -> &mut int { +fn deref_extend_mut_field2(x: &mut Rc<Point>) -> &mut isize { &mut x.y //~ ERROR cannot borrow } @@ -97,15 +97,15 @@ fn deref_mut_method2(mut x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } -fn deref_extend_method(x: &Rc<Point>) -> &int { +fn deref_extend_method(x: &Rc<Point>) -> &isize { x.x_ref() } -fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut int { +fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } -fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut int { +fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-deref-mut.rs b/src/test/compile-fail/borrowck-borrow-overloaded-deref-mut.rs index dda7e4d1047..bfe53b739f4 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-deref-mut.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-deref-mut.rs @@ -31,39 +31,39 @@ impl<T> DerefMut for Own<T> { } } -fn deref_imm(x: Own<int>) { +fn deref_imm(x: Own<isize>) { let _i = &*x; } -fn deref_mut1(x: Own<int>) { +fn deref_mut1(x: Own<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } -fn deref_mut2(mut x: Own<int>) { +fn deref_mut2(mut x: Own<isize>) { let _i = &mut *x; } -fn deref_extend<'a>(x: &'a Own<int>) -> &'a int { +fn deref_extend<'a>(x: &'a Own<isize>) -> &'a isize { &**x } -fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int { +fn deref_extend_mut1<'a>(x: &'a Own<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } -fn deref_extend_mut2<'a>(x: &'a mut Own<int>) -> &'a mut int { +fn deref_extend_mut2<'a>(x: &'a mut Own<isize>) -> &'a mut isize { &mut **x } -fn assign1<'a>(x: Own<int>) { +fn assign1<'a>(x: Own<isize>) { *x = 3; //~ ERROR cannot borrow } -fn assign2<'a>(x: &'a Own<int>) { +fn assign2<'a>(x: &'a Own<isize>) { **x = 3; //~ ERROR cannot borrow } -fn assign3<'a>(x: &'a mut Own<int>) { +fn assign3<'a>(x: &'a mut Own<isize>) { **x = 3; } diff --git a/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs b/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs index 001a5232b12..153368f4894 100644 --- a/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs +++ b/src/test/compile-fail/borrowck-borrow-overloaded-deref.rs @@ -25,39 +25,39 @@ impl<T> Deref for Rc<T> { } } -fn deref_imm(x: Rc<int>) { +fn deref_imm(x: Rc<isize>) { let _i = &*x; } -fn deref_mut1(x: Rc<int>) { +fn deref_mut1(x: Rc<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } -fn deref_mut2(mut x: Rc<int>) { +fn deref_mut2(mut x: Rc<isize>) { let _i = &mut *x; //~ ERROR cannot borrow } -fn deref_extend<'a>(x: &'a Rc<int>) -> &'a int { +fn deref_extend<'a>(x: &'a Rc<isize>) -> &'a isize { &**x } -fn deref_extend_mut1<'a>(x: &'a Rc<int>) -> &'a mut int { +fn deref_extend_mut1<'a>(x: &'a Rc<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } -fn deref_extend_mut2<'a>(x: &'a mut Rc<int>) -> &'a mut int { +fn deref_extend_mut2<'a>(x: &'a mut Rc<isize>) -> &'a mut isize { &mut **x //~ ERROR cannot borrow } -fn assign1<'a>(x: Rc<int>) { +fn assign1<'a>(x: Rc<isize>) { *x = 3; //~ ERROR cannot assign } -fn assign2<'a>(x: &'a Rc<int>) { +fn assign2<'a>(x: &'a Rc<isize>) { **x = 3; //~ ERROR cannot assign } -fn assign3<'a>(x: &'a mut Rc<int>) { +fn assign3<'a>(x: &'a mut Rc<isize>) { **x = 3; //~ ERROR cannot assign } diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue-2.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue-2.rs index 10c63965a7b..d983c5d5087 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue-2.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue-2.rs @@ -18,7 +18,7 @@ struct defer<'a> { impl<'a> Drop for defer<'a> { fn drop(&mut self) { unsafe { - println!("{}", self.x); + println!("{:?}", self.x); } } } diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs index f2ff5f86f63..98d1905ed90 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs @@ -10,11 +10,13 @@ //buggy.rs +#![feature(box_syntax)] + extern crate collections; use std::collections::HashMap; fn main() { - let mut buggy_map: HashMap<uint, &uint> = HashMap::new(); + let mut buggy_map: HashMap<usize, &usize> = HashMap::new(); buggy_map.insert(42, &*box 1); //~ ERROR borrowed value does not live long enough // but it is ok if we use a temporary diff --git a/src/test/compile-fail/borrowck-box-insensitivity.rs b/src/test/compile-fail/borrowck-box-insensitivity.rs index d05c03547ac..648d0d81ffb 100644 --- a/src/test/compile-fail/borrowck-box-insensitivity.rs +++ b/src/test/compile-fail/borrowck-box-insensitivity.rs @@ -8,24 +8,26 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct A { - x: Box<int>, - y: int, + x: Box<isize>, + y: isize, } struct B { - x: Box<int>, - y: Box<int>, + x: Box<isize>, + y: Box<isize>, } struct C { x: Box<A>, - y: int, + y: isize, } struct D { x: Box<A>, - y: Box<int>, + y: Box<isize>, } fn copy_after_move() { diff --git a/src/test/compile-fail/borrowck-break-uninit-2.rs b/src/test/compile-fail/borrowck-break-uninit-2.rs index 0b10ccfdca1..a52eaeeb9c3 100644 --- a/src/test/compile-fail/borrowck-break-uninit-2.rs +++ b/src/test/compile-fail/borrowck-break-uninit-2.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo() -> int { - let x: int; +fn foo() -> isize { + let x: isize; - while 1i != 2 { + while 1is != 2 { break; x = 0; } println!("{}", x); //~ ERROR use of possibly uninitialized variable: `x` - return 17i; + return 17is; } fn main() { println!("{}", foo()); } diff --git a/src/test/compile-fail/borrowck-break-uninit.rs b/src/test/compile-fail/borrowck-break-uninit.rs index aa7ce4fa347..8a6a036945b 100644 --- a/src/test/compile-fail/borrowck-break-uninit.rs +++ b/src/test/compile-fail/borrowck-break-uninit.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo() -> int { - let x: int; +fn foo() -> isize { + let x: isize; loop { break; diff --git a/src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs b/src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs index 6dbdff9441d..010ddb792cc 100644 --- a/src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs +++ b/src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs @@ -11,6 +11,7 @@ // Ensure that invoking a closure counts as a unique immutable borrow #![feature(unboxed_closures)] +#![feature(box_syntax)] type Fn<'a> = Box<FnMut() + 'a>; @@ -32,7 +33,7 @@ fn test1() { } fn test2<F>(f: &F) where F: FnMut() { - (*f)(); //~ ERROR: cannot borrow immutable dereference of `&`-pointer `*f` as mutable + (*f)(); //~ ERROR: cannot borrow immutable borrowed content `*f` as mutable } fn test3<F>(f: &mut F) where F: FnMut() { @@ -40,7 +41,7 @@ fn test3<F>(f: &mut F) where F: FnMut() { } fn test4(f: &Test) { - f.f.call_mut(()) //~ ERROR: cannot borrow immutable dereference of `Box` `*f.f` as mutable + f.f.call_mut(()) //~ ERROR: cannot borrow immutable `Box` content `*f.f` as mutable } fn test5(f: &mut Test) { @@ -55,8 +56,8 @@ fn test6() { } fn test7() { - fn foo<F>(_: F) where F: FnMut(Box<FnMut(int)>, int) {} - let mut f = |&mut: g: Box<FnMut(int)>, b: int| {}; + fn foo<F>(_: F) where F: FnMut(Box<FnMut(isize)>, isize) {} + let mut f = |&mut: g: Box<FnMut(isize)>, b: isize| {}; f(box |a| { //~ ERROR: cannot borrow `f` as immutable because it is also borrowed as mutable foo(f); //~ ERROR: cannot move out of captured outer variable }, 3); diff --git a/src/test/compile-fail/borrowck-call-method-from-mut-aliasable.rs b/src/test/compile-fail/borrowck-call-method-from-mut-aliasable.rs index 537e52120d9..bc0b667e895 100644 --- a/src/test/compile-fail/borrowck-call-method-from-mut-aliasable.rs +++ b/src/test/compile-fail/borrowck-call-method-from-mut-aliasable.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } impl Foo { diff --git a/src/test/compile-fail/borrowck-closures-mut-and-imm.rs b/src/test/compile-fail/borrowck-closures-mut-and-imm.rs index 47a47d04432..29c7d6920bd 100644 --- a/src/test/compile-fail/borrowck-closures-mut-and-imm.rs +++ b/src/test/compile-fail/borrowck-closures-mut-and-imm.rs @@ -11,54 +11,55 @@ // Tests that two closures cannot simultaneously have mutable // and immutable access to the variable. Issue #6801. +#![feature(box_syntax)] -fn get(x: &int) -> int { +fn get(x: &isize) -> isize { *x } -fn set(x: &mut int) { +fn set(x: &mut isize) { *x = 4; } fn a() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| x = 4; let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x` } fn b() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| set(&mut x); let c2 = |&mut:| get(&x); //~ ERROR cannot borrow `x` } fn c() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| set(&mut x); let c2 = |&mut:| x * 5; //~ ERROR cannot borrow `x` } fn d() { - let mut x = 3i; + let mut x = 3is; let c2 = |&mut:| x * 5; x = 5; //~ ERROR cannot assign } fn e() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| get(&x); x = 5; //~ ERROR cannot assign } fn f() { - let mut x = box 3i; + let mut x = box 3is; let c1 = |&mut:| get(&*x); *x = 5; //~ ERROR cannot assign } fn g() { struct Foo { - f: Box<int> + f: Box<isize> } let mut x = box Foo { f: box 3 }; @@ -68,7 +69,7 @@ fn g() { fn h() { struct Foo { - f: Box<int> + f: Box<isize> } let mut x = box Foo { f: box 3 }; diff --git a/src/test/compile-fail/borrowck-closures-mut-of-imm.rs b/src/test/compile-fail/borrowck-closures-mut-of-imm.rs index 30e1421ba26..82607741909 100644 --- a/src/test/compile-fail/borrowck-closures-mut-of-imm.rs +++ b/src/test/compile-fail/borrowck-closures-mut-of-imm.rs @@ -11,15 +11,15 @@ // Tests that two closures cannot simultaneously have mutable // and immutable access to the variable. Issue #6801. -fn get(x: &int) -> int { +fn get(x: &isize) -> isize { *x } -fn set(x: &mut int) { +fn set(x: &mut isize) { *x = 4; } -fn a(x: &int) { +fn a(x: &isize) { let c1 = |&mut:| set(&mut *x); //~^ ERROR cannot borrow let c2 = |&mut:| set(&mut *x); diff --git a/src/test/compile-fail/borrowck-closures-two-mut.rs b/src/test/compile-fail/borrowck-closures-two-mut.rs index 0f284b53849..5cb49ab7711 100644 --- a/src/test/compile-fail/borrowck-closures-two-mut.rs +++ b/src/test/compile-fail/borrowck-closures-two-mut.rs @@ -12,31 +12,32 @@ // access to the variable, whether that mutable access be used // for direct assignment or for taking mutable ref. Issue #6801. +#![feature(box_syntax)] fn a() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| x = 4; let c2 = |&mut:| x = 5; //~ ERROR cannot borrow `x` as mutable more than once } -fn set(x: &mut int) { +fn set(x: &mut isize) { *x = 4; } fn b() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| set(&mut x); let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once } fn c() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| x = 5; let c2 = |&mut:| set(&mut x); //~ ERROR cannot borrow `x` as mutable more than once } fn d() { - let mut x = 3i; + let mut x = 3is; let c1 = |&mut:| x = 5; let c2 = |&mut:| { let _y = |&mut:| set(&mut x); }; // (nested closure) //~^ ERROR cannot borrow `x` as mutable more than once @@ -44,7 +45,7 @@ fn d() { fn g() { struct Foo { - f: Box<int> + f: Box<isize> } let mut x = box Foo { f: box 3 }; diff --git a/src/test/compile-fail/borrowck-closures-unique-imm.rs b/src/test/compile-fail/borrowck-closures-unique-imm.rs index a9cc9e967f6..cf86602af0b 100644 --- a/src/test/compile-fail/borrowck-closures-unique-imm.rs +++ b/src/test/compile-fail/borrowck-closures-unique-imm.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } pub fn main() { diff --git a/src/test/compile-fail/borrowck-closures-unique.rs b/src/test/compile-fail/borrowck-closures-unique.rs index 9a772cc49b8..f9a6d5ac845 100644 --- a/src/test/compile-fail/borrowck-closures-unique.rs +++ b/src/test/compile-fail/borrowck-closures-unique.rs @@ -14,35 +14,35 @@ // may be *immutable*, but we cannot allow // multiple borrows. -fn get(x: &int) -> int { +fn get(x: &isize) -> isize { *x } -fn set(x: &mut int) -> int { +fn set(x: &mut isize) -> isize { *x } -fn a(x: &mut int) { +fn a(x: &mut isize) { let c1 = |&mut:| get(x); let c2 = |&mut:| get(x); } -fn b(x: &mut int) { +fn b(x: &mut isize) { let c1 = |&mut:| get(x); let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x` } -fn c(x: &mut int) { +fn c(x: &mut isize) { let c1 = |&mut:| get(x); let c2 = |&mut:| { get(x); set(x); }; //~ ERROR closure requires unique access to `x` } -fn d(x: &mut int) { +fn d(x: &mut isize) { let c1 = |&mut:| set(x); let c2 = |&mut:| set(x); //~ ERROR closure requires unique access to `x` } -fn e(x: &mut int) { +fn e(x: &mut isize) { let c1 = |&mut:| x = panic!(); //~ ERROR closure cannot assign to immutable local variable } diff --git a/src/test/compile-fail/borrowck-closures-use-after-free.rs b/src/test/compile-fail/borrowck-closures-use-after-free.rs index 23c90fcf574..b6529da1883 100644 --- a/src/test/compile-fail/borrowck-closures-use-after-free.rs +++ b/src/test/compile-fail/borrowck-closures-use-after-free.rs @@ -12,9 +12,10 @@ // cannot also be supplied a borrowed version of that // variable's contents. Issue #11192. +#![feature(box_syntax)] struct Foo { - x: int + x: isize } impl Drop for Foo { diff --git a/src/test/compile-fail/borrowck-field-sensitivity.rs b/src/test/compile-fail/borrowck-field-sensitivity.rs index 49c93e3aa9e..fe5142a7734 100644 --- a/src/test/compile-fail/borrowck-field-sensitivity.rs +++ b/src/test/compile-fail/borrowck-field-sensitivity.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { a: int, b: Box<int> } +#![feature(box_syntax)] + +struct A { a: isize, b: Box<isize> } fn deref_after_move() { let x = A { a: 1, b: box 2 }; diff --git a/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs b/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs index f0d42bb9ac1..6884ac153a1 100644 --- a/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs +++ b/src/test/compile-fail/borrowck-for-loop-correct-cmt-for-pattern.rs @@ -10,12 +10,14 @@ // Issue #16205. +#![feature(box_syntax)] + struct Foo { - a: [Box<int>; 3], + a: [Box<isize>; 3], } fn main() { - let mut y = 1i; + let mut y = 1is; let x = Some(&mut y); for &a in x.iter() { //~ ERROR cannot move out } @@ -26,7 +28,7 @@ fn main() { for &a in f.a.iter() { //~ ERROR cannot move out } - let x = Some(box 1i); + let x = Some(box 1is); for &a in x.iter() { //~ ERROR cannot move out } } diff --git a/src/test/compile-fail/borrowck-for-loop-head-linkage.rs b/src/test/compile-fail/borrowck-for-loop-head-linkage.rs index cb673f9be34..d2f99ea696a 100644 --- a/src/test/compile-fail/borrowck-for-loop-head-linkage.rs +++ b/src/test/compile-fail/borrowck-for-loop-head-linkage.rs @@ -11,11 +11,11 @@ use std::iter::repeat; fn main() { - let mut vector = vec![1u, 2]; + let mut vector = vec![1us, 2]; for &x in vector.iter() { let cap = vector.capacity(); vector.extend(repeat(0)); //~ ERROR cannot borrow - vector[1u] = 5u; //~ ERROR cannot borrow + vector[1us] = 5us; //~ ERROR cannot borrow } } diff --git a/src/test/compile-fail/borrowck-if-no-else.rs b/src/test/compile-fail/borrowck-if-no-else.rs index 854d42219ea..b98833776fb 100644 --- a/src/test/compile-fail/borrowck-if-no-else.rs +++ b/src/test/compile-fail/borrowck-if-no-else.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } fn main() { - let x: int; if 1i > 2 { x = 10; } + let x: isize; if 1is > 2 { x = 10; } foo(x); //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/borrowck-if-with-else.rs b/src/test/compile-fail/borrowck-if-with-else.rs index e6d59062af2..c74edfd8d07 100644 --- a/src/test/compile-fail/borrowck-if-with-else.rs +++ b/src/test/compile-fail/borrowck-if-with-else.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } fn main() { - let x: int; - if 1i > 2 { + let x: isize; + if 1is > 2 { println!("whoops"); } else { x = 10; diff --git a/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs b/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs index d127e9345cd..fabfce6ffb3 100644 --- a/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs +++ b/src/test/compile-fail/borrowck-imm-ref-to-mut-rec-field-issue-3162-c.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut _a = 3i; + let mut _a = 3is; let _b = &mut _a; { let _c = &*_b; diff --git a/src/test/compile-fail/borrowck-init-in-called-fn-expr.rs b/src/test/compile-fail/borrowck-init-in-called-fn-expr.rs index 5496a9dd4b3..3c20abab8bd 100644 --- a/src/test/compile-fail/borrowck-init-in-called-fn-expr.rs +++ b/src/test/compile-fail/borrowck-init-in-called-fn-expr.rs @@ -9,8 +9,8 @@ // except according to those terms. fn main() { - let j = |&:| -> int { - let i: int; + let j = |&:| -> isize { + let i: isize; i //~ ERROR use of possibly uninitialized variable: `i` }; j(); diff --git a/src/test/compile-fail/borrowck-init-in-fn-expr.rs b/src/test/compile-fail/borrowck-init-in-fn-expr.rs index 33c284c71b3..31ca39c3f9b 100644 --- a/src/test/compile-fail/borrowck-init-in-fn-expr.rs +++ b/src/test/compile-fail/borrowck-init-in-fn-expr.rs @@ -9,8 +9,8 @@ // except according to those terms. fn main() { - let f = |&:| -> int { - let i: int; + let f = |&:| -> isize { + let i: isize; i //~ ERROR use of possibly uninitialized variable: `i` }; println!("{}", f()); diff --git a/src/test/compile-fail/borrowck-init-in-fru.rs b/src/test/compile-fail/borrowck-init-in-fru.rs index ac90b7cb432..569ddb80c2f 100644 --- a/src/test/compile-fail/borrowck-init-in-fru.rs +++ b/src/test/compile-fail/borrowck-init-in-fru.rs @@ -10,8 +10,8 @@ #[derive(Clone)] struct point { - x: int, - y: int, + x: isize, + y: isize, } fn main() { diff --git a/src/test/compile-fail/borrowck-init-op-equal.rs b/src/test/compile-fail/borrowck-init-op-equal.rs index d6065c81a2d..e0d93fd1d47 100644 --- a/src/test/compile-fail/borrowck-init-op-equal.rs +++ b/src/test/compile-fail/borrowck-init-op-equal.rs @@ -10,7 +10,7 @@ fn test() { - let v: int; + let v: isize; v += 1; //~ ERROR use of possibly uninitialized variable: `v` v.clone(); } diff --git a/src/test/compile-fail/borrowck-init-plus-equal.rs b/src/test/compile-fail/borrowck-init-plus-equal.rs index 6e813809f03..a036286f363 100644 --- a/src/test/compile-fail/borrowck-init-plus-equal.rs +++ b/src/test/compile-fail/borrowck-init-plus-equal.rs @@ -9,7 +9,7 @@ // except according to those terms. fn test() { - let mut v: int; + let mut v: isize; v = v + 1; //~ ERROR use of possibly uninitialized variable: `v` v.clone(); } diff --git a/src/test/compile-fail/borrowck-insert-during-each.rs b/src/test/compile-fail/borrowck-insert-during-each.rs index 0428ee83065..d729af844cb 100644 --- a/src/test/compile-fail/borrowck-insert-during-each.rs +++ b/src/test/compile-fail/borrowck-insert-during-each.rs @@ -12,11 +12,11 @@ extern crate collections; use std::collections::HashSet; struct Foo { - n: HashSet<int>, + n: HashSet<isize>, } impl Foo { - pub fn foo<F>(&mut self, mut fun: F) where F: FnMut(&int) { + pub fn foo<F>(&mut self, mut fun: F) where F: FnMut(&isize) { for f in self.n.iter() { fun(f); } diff --git a/src/test/compile-fail/borrowck-issue-14498.rs b/src/test/compile-fail/borrowck-issue-14498.rs index 45dda5fee5a..cc562afa9f8 100644 --- a/src/test/compile-fail/borrowck-issue-14498.rs +++ b/src/test/compile-fail/borrowck-issue-14498.rs @@ -11,11 +11,13 @@ // This tests that we can't modify Box<&mut T> contents while they // are borrowed. -struct A { a: int } -struct B<'a> { a: Box<&'a mut int> } +#![feature(box_syntax)] + +struct A { a: isize } +struct B<'a> { a: Box<&'a mut isize> } fn borrow_in_var_from_var() { - let mut x: int = 1; + let mut x: isize = 1; let y = box &mut x; let p = &y; let q = &***p; @@ -35,7 +37,7 @@ fn borrow_in_var_from_field() { } fn borrow_in_field_from_var() { - let mut x: int = 1; + let mut x: isize = 1; let y = B { a: box &mut x }; let p = &y.a; let q = &***p; diff --git a/src/test/compile-fail/borrowck-issue-2657-1.rs b/src/test/compile-fail/borrowck-issue-2657-1.rs index 9d28b2a436f..dc1c73efc40 100644 --- a/src/test/compile-fail/borrowck-issue-2657-1.rs +++ b/src/test/compile-fail/borrowck-issue-2657-1.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let x = Some(box 1i); + let x = Some(box 1is); match x { Some(ref _y) => { let _a = x; //~ ERROR cannot move diff --git a/src/test/compile-fail/borrowck-issue-2657-2.rs b/src/test/compile-fail/borrowck-issue-2657-2.rs index 973cf3bf8c8..0b76044f8d6 100644 --- a/src/test/compile-fail/borrowck-issue-2657-2.rs +++ b/src/test/compile-fail/borrowck-issue-2657-2.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let x = Some(box 1i); + let x = Some(box 1is); match x { Some(ref y) => { let _b = *y; //~ ERROR cannot move out diff --git a/src/test/compile-fail/borrowck-lend-flow-if.rs b/src/test/compile-fail/borrowck-lend-flow-if.rs index f798d170f96..ca8efb5dc96 100644 --- a/src/test/compile-fail/borrowck-lend-flow-if.rs +++ b/src/test/compile-fail/borrowck-lend-flow-if.rs @@ -14,14 +14,15 @@ // either genuine or would require more advanced changes. The latter // cases are noted. +#![feature(box_syntax)] -fn borrow(_v: &int) {} -fn borrow_mut(_v: &mut int) {} +fn borrow(_v: &isize) {} +fn borrow_mut(_v: &mut isize) {} fn cond() -> bool { panic!() } fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() } fn produce<T>() -> T { panic!(); } -fn inc(v: &mut Box<int>) { +fn inc(v: &mut Box<isize>) { *v = box() (**v + 1); } diff --git a/src/test/compile-fail/borrowck-lend-flow-loop.rs b/src/test/compile-fail/borrowck-lend-flow-loop.rs index ff038b545d5..491a0d40bec 100644 --- a/src/test/compile-fail/borrowck-lend-flow-loop.rs +++ b/src/test/compile-fail/borrowck-lend-flow-loop.rs @@ -14,13 +14,14 @@ // either genuine or would require more advanced changes. The latter // cases are noted. +#![feature(box_syntax)] -fn borrow(_v: &int) {} -fn borrow_mut(_v: &mut int) {} +fn borrow(_v: &isize) {} +fn borrow_mut(_v: &mut isize) {} fn cond() -> bool { panic!() } fn produce<T>() -> T { panic!(); } -fn inc(v: &mut Box<int>) { +fn inc(v: &mut Box<isize>) { *v = box() (**v + 1); } @@ -40,7 +41,7 @@ fn block_overarching_alias_mut() { let mut v = box 3; let mut x = &mut v; - for _ in range(0i, 3) { + for _ in range(0is, 3) { borrow(&*v); //~ ERROR cannot borrow } *x = box 5; @@ -112,8 +113,8 @@ fn while_aliased_mut_cond(cond: bool, cond2: bool) { } } -fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where - F: FnMut(&'r mut uint) -> bool, +fn loop_break_pops_scopes<'r, F>(_v: &'r mut [usize], mut f: F) where + F: FnMut(&'r mut usize) -> bool, { // Here we check that when you break out of an inner loop, the // borrows that go out of scope as you exit the inner loop are @@ -122,7 +123,7 @@ fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where while cond() { while cond() { // this borrow is limited to the scope of `r`... - let r: &'r mut uint = produce(); + let r: &'r mut usize = produce(); if !f(&mut *r) { break; // ...so it is not live as exit the `while` loop here } @@ -130,13 +131,15 @@ fn loop_break_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where } } -fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool { +fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [usize], mut f: F) + where F: FnMut(&'r mut usize) -> bool +{ // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... - let r: &'r mut uint = produce(); + let r: &'r mut usize = produce(); if !f(&mut *r) { continue; // ...so it is not live as exit (and re-enter) the `while` loop here } diff --git a/src/test/compile-fail/borrowck-lend-flow-match.rs b/src/test/compile-fail/borrowck-lend-flow-match.rs index 0b40a78425f..f501682847f 100644 --- a/src/test/compile-fail/borrowck-lend-flow-match.rs +++ b/src/test/compile-fail/borrowck-lend-flow-match.rs @@ -19,10 +19,10 @@ fn separate_arms() { None => { // It is ok to reassign x here, because there is in // fact no outstanding loan of x! - x = Some(0i); + x = Some(0is); } Some(ref _i) => { - x = Some(1i); //~ ERROR cannot assign + x = Some(1is); //~ ERROR cannot assign } } x.clone(); // just to prevent liveness warnings diff --git a/src/test/compile-fail/borrowck-lend-flow.rs b/src/test/compile-fail/borrowck-lend-flow.rs index 85fc7fb87b3..177976c15f0 100644 --- a/src/test/compile-fail/borrowck-lend-flow.rs +++ b/src/test/compile-fail/borrowck-lend-flow.rs @@ -14,14 +14,15 @@ // either genuine or would require more advanced changes. The latter // cases are noted. +#![feature(box_syntax)] -fn borrow(_v: &int) {} -fn borrow_mut(_v: &mut int) {} +fn borrow(_v: &isize) {} +fn borrow_mut(_v: &mut isize) {} fn cond() -> bool { panic!() } fn for_func<F>(_f: F) where F: FnOnce() -> bool { panic!() } fn produce<T>() -> T { panic!(); } -fn inc(v: &mut Box<int>) { +fn inc(v: &mut Box<isize>) { *v = box() (**v + 1); } diff --git a/src/test/compile-fail/borrowck-let-suggestion.rs b/src/test/compile-fail/borrowck-let-suggestion.rs index cd1101c05d1..5f5ff4014e1 100644 --- a/src/test/compile-fail/borrowck-let-suggestion.rs +++ b/src/test/compile-fail/borrowck-let-suggestion.rs @@ -9,7 +9,7 @@ // except according to those terms. fn f() { - let x = [1i].iter(); //~ ERROR borrowed value does not live long enough + let x = [1is].iter(); //~ ERROR borrowed value does not live long enough //~^^ NOTE reference must be valid for the block //~^^ HELP consider using a `let` binding to increase its lifetime } diff --git a/src/test/compile-fail/borrowck-loan-blocks-move-cc.rs b/src/test/compile-fail/borrowck-loan-blocks-move-cc.rs index 5c282495cc2..bff22257760 100644 --- a/src/test/compile-fail/borrowck-loan-blocks-move-cc.rs +++ b/src/test/compile-fail/borrowck-loan-blocks-move-cc.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::thread::Thread; -fn borrow<F>(v: &int, f: F) where F: FnOnce(&int) { +fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { - let v = box 3i; + let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); @@ -24,7 +26,7 @@ fn box_imm() { } fn box_imm_explicit() { - let v = box 3i; + let v = box 3is; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); diff --git a/src/test/compile-fail/borrowck-loan-blocks-move.rs b/src/test/compile-fail/borrowck-loan-blocks-move.rs index 3c284ede0c8..f3f18807314 100644 --- a/src/test/compile-fail/borrowck-loan-blocks-move.rs +++ b/src/test/compile-fail/borrowck-loan-blocks-move.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -fn take(_v: Box<int>) { +fn take(_v: Box<isize>) { } fn box_imm() { diff --git a/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs b/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs index b6a71fcd446..a52a4484b20 100644 --- a/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs +++ b/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn borrow<F>(v: &int, f: F) where F: FnOnce(&int) { +#![feature(box_syntax)] + +fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } diff --git a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs index 924d70e9f46..902762f687e 100644 --- a/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs +++ b/src/test/compile-fail/borrowck-loan-in-overloaded-op.rs @@ -8,10 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::ops::Add; #[derive(Clone)] -struct foo(Box<uint>); +struct foo(Box<usize>); impl Add for foo { type Output = foo; diff --git a/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs b/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs index 5aa2deb44f1..b1eb06d16b1 100644 --- a/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs +++ b/src/test/compile-fail/borrowck-loan-rcvr-overloaded-op.rs @@ -12,20 +12,20 @@ use std::ops::Add; #[derive(Copy)] struct Point { - x: int, - y: int, + x: isize, + y: isize, } -impl Add<int> for Point { - type Output = int; +impl Add<isize> for Point { + type Output = isize; - fn add(self, z: int) -> int { + fn add(self, z: isize) -> isize { self.x + self.y + z } } impl Point { - pub fn times(&self, z: int) -> int { + pub fn times(&self, z: isize) -> isize { self.x * self.y * z } } diff --git a/src/test/compile-fail/borrowck-loan-rcvr.rs b/src/test/compile-fail/borrowck-loan-rcvr.rs index 0ada3db47a4..014b27f9659 100644 --- a/src/test/compile-fail/borrowck-loan-rcvr.rs +++ b/src/test/compile-fail/borrowck-loan-rcvr.rs @@ -9,7 +9,7 @@ // except according to those terms. -struct point { x: int, y: int } +struct point { x: isize, y: isize } trait methods { fn impurem(&self); diff --git a/src/test/compile-fail/borrowck-loan-vec-content.rs b/src/test/compile-fail/borrowck-loan-vec-content.rs index efb7a5253ed..21d9dea77b2 100644 --- a/src/test/compile-fail/borrowck-loan-vec-content.rs +++ b/src/test/compile-fail/borrowck-loan-vec-content.rs @@ -12,17 +12,17 @@ // (locally rooted) mutable, unique vector, and that we then prevent // modifications to the contents. -fn takes_imm_elt<F>(_v: &int, f: F) where F: FnOnce() { +fn takes_imm_elt<F>(_v: &isize, f: F) where F: FnOnce() { f(); } fn has_mut_vec_and_does_not_try_to_change_it() { - let mut v: Vec<int> = vec!(1, 2, 3); + let mut v: Vec<isize> = vec!(1, 2, 3); takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { - let mut v: Vec<int> = vec!(1, 2, 3); + let mut v: Vec<isize> = vec!(1, 2, 3); takes_imm_elt( &v[0], || { //~ ERROR cannot borrow `v` as mutable diff --git a/src/test/compile-fail/borrowck-match-binding-is-assignment.rs b/src/test/compile-fail/borrowck-match-binding-is-assignment.rs index fe0519b8198..575d67c0b83 100644 --- a/src/test/compile-fail/borrowck-match-binding-is-assignment.rs +++ b/src/test/compile-fail/borrowck-match-binding-is-assignment.rs @@ -11,15 +11,15 @@ // Test that immutable pattern bindings cannot be reassigned. enum E { - Foo(int) + Foo(isize) } struct S { - bar: int, + bar: isize, } pub fn main() { - match 1i { + match 1is { x => { x += 1; //~ ERROR re-assignment of immutable variable `x` } @@ -37,13 +37,13 @@ pub fn main() { } } - match (1i,) { + match (1is,) { (x,) => { x += 1; //~ ERROR re-assignment of immutable variable `x` } } - match [1i,2,3] { + match [1is,2,3] { [x,_,_] => { x += 1; //~ ERROR re-assignment of immutable variable `x` } diff --git a/src/test/compile-fail/borrowck-move-by-capture.rs b/src/test/compile-fail/borrowck-move-by-capture.rs index 35f0751aa78..b0d546cd5c8 100644 --- a/src/test/compile-fail/borrowck-move-by-capture.rs +++ b/src/test/compile-fail/borrowck-move-by-capture.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + pub fn main() { let bar = box 3; let _g = |&mut:| { - let _h = move |:| -> int { *bar }; //~ ERROR cannot move out of captured outer variable + let _h = move |:| -> isize { *bar }; //~ ERROR cannot move out of captured outer variable }; } diff --git a/src/test/compile-fail/borrowck-move-error-with-note.rs b/src/test/compile-fail/borrowck-move-error-with-note.rs index c61ec39ec50..2d82c8be519 100644 --- a/src/test/compile-fail/borrowck-move-error-with-note.rs +++ b/src/test/compile-fail/borrowck-move-error-with-note.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] enum Foo { Foo1(Box<u32>, Box<u32>), @@ -44,7 +45,7 @@ fn move_in_match() { // from issue-8064 struct A { - a: Box<int>, + a: Box<isize>, } fn free<T>(_: T) {} diff --git a/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs b/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs index 63409f5afb0..0d1a51bbf35 100644 --- a/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs +++ b/src/test/compile-fail/borrowck-move-from-subpath-of-borrowed-path.rs @@ -11,8 +11,10 @@ // verify that an error is raised when trying to move out of a // borrowed path. +#![feature(box_syntax)] + fn main() { - let a = box box 2i; + let a = box box 2is; let b = &a; let z = *a; //~ ERROR: cannot move out of `*a` because it is borrowed diff --git a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs index 87bb8ef7a58..8310d4ba144 100644 --- a/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs +++ b/src/test/compile-fail/borrowck-move-from-unsafe-ptr.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn foo(x: *const Box<int>) -> Box<int> { +fn foo(x: *const Box<isize>) -> Box<isize> { let y = *x; //~ ERROR dereference of unsafe pointer requires unsafe function or block return y; } diff --git a/src/test/compile-fail/borrowck-move-in-irrefut-pat.rs b/src/test/compile-fail/borrowck-move-in-irrefut-pat.rs index c5d23925a89..ec505faf885 100644 --- a/src/test/compile-fail/borrowck-move-in-irrefut-pat.rs +++ b/src/test/compile-fail/borrowck-move-in-irrefut-pat.rs @@ -11,16 +11,16 @@ fn with<F>(f: F) where F: FnOnce(&String) {} fn arg_item(&_x: &String) {} - //~^ ERROR cannot move out of dereference of `&`-pointer + //~^ ERROR cannot move out of borrowed content fn arg_closure() { with(|&_x| ()) - //~^ ERROR cannot move out of dereference of `&`-pointer + //~^ ERROR cannot move out of borrowed content } fn let_pat() { let &_x = &"hi".to_string(); - //~^ ERROR cannot move out of dereference of `&`-pointer + //~^ ERROR cannot move out of borrowed content } pub fn main() {} diff --git a/src/test/compile-fail/borrowck-move-moved-value-into-closure.rs b/src/test/compile-fail/borrowck-move-moved-value-into-closure.rs index ca484738cb6..43bf3f25d1a 100644 --- a/src/test/compile-fail/borrowck-move-moved-value-into-closure.rs +++ b/src/test/compile-fail/borrowck-move-moved-value-into-closure.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn call_f<F:FnOnce() -> int>(f: F) -> int { +#![feature(box_syntax)] + +fn call_f<F:FnOnce() -> isize>(f: F) -> isize { f() } diff --git a/src/test/compile-fail/borrowck-move-mut-base-ptr.rs b/src/test/compile-fail/borrowck-move-mut-base-ptr.rs index ce2755dbc0f..5bdea6a2bd9 100644 --- a/src/test/compile-fail/borrowck-move-mut-base-ptr.rs +++ b/src/test/compile-fail/borrowck-move-mut-base-ptr.rs @@ -13,8 +13,8 @@ // // Example from src/middle/borrowck/doc.rs -fn foo(t0: &mut int) { - let p: &int = &*t0; // Freezes `*t0` +fn foo(t0: &mut isize) { + let p: &isize = &*t0; // Freezes `*t0` let t1 = t0; //~ ERROR cannot move out of `t0` *t1 = 22; } diff --git a/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs b/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs index a6723a04611..507f073adb2 100644 --- a/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs +++ b/src/test/compile-fail/borrowck-move-out-of-overloaded-auto-deref.rs @@ -11,6 +11,6 @@ use std::rc::Rc; pub fn main() { - let _x = Rc::new(vec!(1i, 2)).into_iter(); - //~^ ERROR cannot move out of dereference of `&`-pointer + let _x = Rc::new(vec!(1is, 2)).into_iter(); + //~^ ERROR cannot move out of borrowed content } diff --git a/src/test/compile-fail/borrowck-move-out-of-overloaded-deref.rs b/src/test/compile-fail/borrowck-move-out-of-overloaded-deref.rs index 8a93790d5a2..fffcf575ab0 100644 --- a/src/test/compile-fail/borrowck-move-out-of-overloaded-deref.rs +++ b/src/test/compile-fail/borrowck-move-out-of-overloaded-deref.rs @@ -12,5 +12,5 @@ use std::rc::Rc; pub fn main() { let _x = *Rc::new("hi".to_string()); - //~^ ERROR cannot move out of dereference of `&`-pointer + //~^ ERROR cannot move out of borrowed content } diff --git a/src/test/compile-fail/borrowck-move-out-of-static-item.rs b/src/test/compile-fail/borrowck-move-out-of-static-item.rs index 730a0c3e235..2f81aa8f381 100644 --- a/src/test/compile-fail/borrowck-move-out-of-static-item.rs +++ b/src/test/compile-fail/borrowck-move-out-of-static-item.rs @@ -13,7 +13,7 @@ use std::marker; struct Foo { - foo: int, + foo: isize, nocopy: marker::NoCopy } diff --git a/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs b/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs index 23ef5331b49..75596af10d7 100644 --- a/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs +++ b/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs @@ -25,7 +25,7 @@ pub fn main() { match x { [_, tail..] => { match tail { - [Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer + [Foo { string: a }, //~ ERROR cannot move out of borrowed content Foo { string: b }] => { //~^^ NOTE attempting to move value to here //~^^ NOTE and here diff --git a/src/test/compile-fail/borrowck-move-subcomponent.rs b/src/test/compile-fail/borrowck-move-subcomponent.rs index a29a171e935..88871dda659 100644 --- a/src/test/compile-fail/borrowck-move-subcomponent.rs +++ b/src/test/compile-fail/borrowck-move-subcomponent.rs @@ -11,9 +11,10 @@ // Tests that the borrow checker checks all components of a path when moving // out. +#![feature(box_syntax)] struct S { - x : Box<int> + x : Box<isize> } fn f<T>(_: T) {} diff --git a/src/test/compile-fail/borrowck-multiple-captures.rs b/src/test/compile-fail/borrowck-multiple-captures.rs index 2a26ff7d4a1..33ac5d7fceb 100644 --- a/src/test/compile-fail/borrowck-multiple-captures.rs +++ b/src/test/compile-fail/borrowck-multiple-captures.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::thread::Thread; fn borrow<T>(_: &T) { } fn different_vars_after_borrows() { - let x1 = box 1i; + let x1 = box 1is; let p1 = &x1; - let x2 = box 2i; + let x2 = box 2is; let p2 = &x2; Thread::spawn(move|| { drop(x1); //~ ERROR cannot move `x1` into closure because it is borrowed @@ -26,9 +28,9 @@ fn different_vars_after_borrows() { } fn different_vars_after_moves() { - let x1 = box 1i; + let x1 = box 1is; drop(x1); - let x2 = box 2i; + let x2 = box 2is; drop(x2); Thread::spawn(move|| { drop(x1); //~ ERROR capture of moved value: `x1` @@ -37,7 +39,7 @@ fn different_vars_after_moves() { } fn same_var_after_borrow() { - let x = box 1i; + let x = box 1is; let p = &x; Thread::spawn(move|| { drop(x); //~ ERROR cannot move `x` into closure because it is borrowed @@ -47,7 +49,7 @@ fn same_var_after_borrow() { } fn same_var_after_move() { - let x = box 1i; + let x = box 1is; drop(x); Thread::spawn(move|| { drop(x); //~ ERROR capture of moved value: `x` diff --git a/src/test/compile-fail/borrowck-mut-addr-of-imm-var.rs b/src/test/compile-fail/borrowck-mut-addr-of-imm-var.rs index 0c0377e7411..b6626a835e4 100644 --- a/src/test/compile-fail/borrowck-mut-addr-of-imm-var.rs +++ b/src/test/compile-fail/borrowck-mut-addr-of-imm-var.rs @@ -9,8 +9,8 @@ // except according to those terms. fn main() { - let x: int = 3; - let y: &mut int = &mut x; //~ ERROR cannot borrow + let x: isize = 3; + let y: &mut isize = &mut x; //~ ERROR cannot borrow *y = 5; println!("{}", *y); } diff --git a/src/test/compile-fail/borrowck-mut-borrow-of-mut-base-ptr.rs b/src/test/compile-fail/borrowck-mut-borrow-of-mut-base-ptr.rs index fb018f3d4bc..71dc61abb64 100644 --- a/src/test/compile-fail/borrowck-mut-borrow-of-mut-base-ptr.rs +++ b/src/test/compile-fail/borrowck-mut-borrow-of-mut-base-ptr.rs @@ -13,16 +13,16 @@ // // Example from src/middle/borrowck/doc.rs -fn foo<'a>(mut t0: &'a mut int, - mut t1: &'a mut int) { - let p: &int = &*t0; // Freezes `*t0` +fn foo<'a>(mut t0: &'a mut isize, + mut t1: &'a mut isize) { + let p: &isize = &*t0; // Freezes `*t0` let mut t2 = &mut t0; //~ ERROR cannot borrow `t0` **t2 += 1; // Mutates `*t0` } -fn bar<'a>(mut t0: &'a mut int, - mut t1: &'a mut int) { - let p: &mut int = &mut *t0; // Claims `*t0` +fn bar<'a>(mut t0: &'a mut isize, + mut t1: &'a mut isize) { + let p: &mut isize = &mut *t0; // Claims `*t0` let mut t2 = &mut t0; //~ ERROR cannot borrow `t0` **t2 += 1; // Mutates `*t0` but not through `*p` } diff --git a/src/test/compile-fail/borrowck-mut-slice-of-imm-vec.rs b/src/test/compile-fail/borrowck-mut-slice-of-imm-vec.rs index 283d6398e9a..b8a92db4e42 100644 --- a/src/test/compile-fail/borrowck-mut-slice-of-imm-vec.rs +++ b/src/test/compile-fail/borrowck-mut-slice-of-imm-vec.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn write(v: &mut [int]) { +fn write(v: &mut [isize]) { v[0] += 1; } diff --git a/src/test/compile-fail/borrowck-mutate-in-guard.rs b/src/test/compile-fail/borrowck-mutate-in-guard.rs index 464e42df8aa..44353ab5d96 100644 --- a/src/test/compile-fail/borrowck-mutate-in-guard.rs +++ b/src/test/compile-fail/borrowck-mutate-in-guard.rs @@ -9,11 +9,11 @@ // except according to those terms. enum Enum<'a> { - A(&'a int), + A(&'a isize), B(bool), } -fn foo() -> int { +fn foo() -> isize { let mut n = 42; let mut x = Enum::A(&mut n); match x { diff --git a/src/test/compile-fail/borrowck-no-cycle-in-exchange-heap.rs b/src/test/compile-fail/borrowck-no-cycle-in-exchange-heap.rs index db3fa6247db..6985d203fb1 100644 --- a/src/test/compile-fail/borrowck-no-cycle-in-exchange-heap.rs +++ b/src/test/compile-fail/borrowck-no-cycle-in-exchange-heap.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct node_ { a: Box<cycle> diff --git a/src/test/compile-fail/borrowck-or-init.rs b/src/test/compile-fail/borrowck-or-init.rs index 270eeca4c4b..27871a6ab16 100644 --- a/src/test/compile-fail/borrowck-or-init.rs +++ b/src/test/compile-fail/borrowck-or-init.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let i: int; + let i: isize; println!("{}", false || { i = 5; true }); println!("{}", i); //~ ERROR use of possibly uninitialized variable: `i` diff --git a/src/test/compile-fail/borrowck-overloaded-call.rs b/src/test/compile-fail/borrowck-overloaded-call.rs index 938fc53d610..7d35a27c0ae 100644 --- a/src/test/compile-fail/borrowck-overloaded-call.rs +++ b/src/test/compile-fail/borrowck-overloaded-call.rs @@ -13,23 +13,23 @@ use std::ops::{Fn, FnMut, FnOnce}; struct SFn { - x: int, - y: int, + x: isize, + y: isize, } -impl Fn<(int,),int> for SFn { - extern "rust-call" fn call(&self, (z,): (int,)) -> int { +impl Fn<(isize,),isize> for SFn { + extern "rust-call" fn call(&self, (z,): (isize,)) -> isize { self.x * self.y * z } } struct SFnMut { - x: int, - y: int, + x: isize, + y: isize, } -impl FnMut<(int,),int> for SFnMut { - extern "rust-call" fn call_mut(&mut self, (z,): (int,)) -> int { +impl FnMut<(isize,),isize> for SFnMut { + extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize { self.x * self.y * z } } @@ -38,8 +38,8 @@ struct SFnOnce { x: String, } -impl FnOnce<(String,),uint> for SFnOnce { - extern "rust-call" fn call_once(self, (z,): (String,)) -> uint { +impl FnOnce<(String,),usize> for SFnOnce { + extern "rust-call" fn call_once(self, (z,): (String,)) -> usize { self.x.len() + z.len() } } diff --git a/src/test/compile-fail/borrowck-overloaded-index-2.rs b/src/test/compile-fail/borrowck-overloaded-index-2.rs index 53fb935755c..da3da47fa90 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-2.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-2.rs @@ -8,23 +8,25 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::ops::Index; struct MyVec<T> { data: Vec<T>, } -impl<T> Index<uint> for MyVec<T> { +impl<T> Index<usize> for MyVec<T> { type Output = T; - fn index(&self, &i: &uint) -> &T { + fn index(&self, &i: &usize) -> &T { &self.data[i] } } fn main() { - let v = MyVec { data: vec!(box 1i, box 2, box 3) }; + let v = MyVec { data: vec!(box 1is, box 2, box 3) }; let good = &v[0]; // Shouldn't fail here let bad = v[0]; - //~^ ERROR cannot move out of dereference (dereference is implicit, due to indexing) + //~^ ERROR cannot move out of indexed content } diff --git a/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs b/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs new file mode 100644 index 00000000000..4188cf00142 --- /dev/null +++ b/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs @@ -0,0 +1,47 @@ +// 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. + +// Check that we properly record borrows when we are doing an +// overloaded, autoderef of a value obtained via an overloaded index +// operator. The accounting of the all the implicit things going on +// here is rather subtle. Issue #20232. + +use std::ops::{Deref, Index}; + +struct MyVec<T> { x: T } + +impl<T> Index<usize> for MyVec<T> { + type Output = T; + fn index(&self, _: &usize) -> &T { + &self.x + } +} + +struct MyPtr<T> { x: T } + +impl<T> Deref for MyPtr<T> { + type Target = T; + fn deref(&self) -> &T { + &self.x + } +} + +struct Foo { f: usize } + +fn main() { + let mut v = MyVec { x: MyPtr { x: Foo { f: 22 } } }; + let i = &v[0].f; + v = MyVec { x: MyPtr { x: Foo { f: 23 } } }; + //~^ ERROR cannot assign to `v` + read(*i); +} + +fn read(_: usize) { } + diff --git a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs index 416e67dac0c..9193a28511e 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs @@ -14,14 +14,14 @@ use std::ops::{Index, IndexMut}; struct Foo { - x: int, - y: int, + x: isize, + y: isize, } impl Index<String> for Foo { - type Output = int; + type Output = isize; - fn index<'a>(&'a self, z: &String) -> &'a int { + fn index<'a>(&'a self, z: &String) -> &'a isize { if z.as_slice() == "x" { &self.x } else { @@ -31,9 +31,9 @@ impl Index<String> for Foo { } impl IndexMut<String> for Foo { - type Output = int; + type Output = isize; - fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut int { + fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize { if z.as_slice() == "x" { &mut self.x } else { diff --git a/src/test/compile-fail/borrowck-overloaded-index.rs b/src/test/compile-fail/borrowck-overloaded-index.rs index 80b68dbf519..7259ca8971d 100644 --- a/src/test/compile-fail/borrowck-overloaded-index.rs +++ b/src/test/compile-fail/borrowck-overloaded-index.rs @@ -11,14 +11,14 @@ use std::ops::{Index, IndexMut}; struct Foo { - x: int, - y: int, + x: isize, + y: isize, } impl Index<String> for Foo { - type Output = int; + type Output = isize; - fn index<'a>(&'a self, z: &String) -> &'a int { + fn index<'a>(&'a self, z: &String) -> &'a isize { if z.as_slice() == "x" { &self.x } else { @@ -28,9 +28,9 @@ impl Index<String> for Foo { } impl IndexMut<String> for Foo { - type Output = int; + type Output = isize; - fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut int { + fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize { if z.as_slice() == "x" { &mut self.x } else { @@ -40,13 +40,13 @@ impl IndexMut<String> for Foo { } struct Bar { - x: int, + x: isize, } -impl Index<int> for Bar { - type Output = int; +impl Index<isize> for Bar { + type Output = isize; - fn index<'a>(&'a self, z: &int) -> &'a int { + fn index<'a>(&'a self, z: &isize) -> &'a isize { &self.x } } @@ -66,5 +66,5 @@ fn main() { x: 1, }; s[2] = 20; - //~^ ERROR cannot assign to immutable dereference (dereference is implicit, due to indexing) + //~^ ERROR cannot assign to immutable indexed content } diff --git a/src/test/compile-fail/borrowck-pat-reassign-binding.rs b/src/test/compile-fail/borrowck-pat-reassign-binding.rs index f33e5e9b02d..d176245823e 100644 --- a/src/test/compile-fail/borrowck-pat-reassign-binding.rs +++ b/src/test/compile-fail/borrowck-pat-reassign-binding.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut x: Option<int> = None; + let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. diff --git a/src/test/compile-fail/borrowck-reborrow-from-mut.rs b/src/test/compile-fail/borrowck-reborrow-from-mut.rs index b4bd64f2135..6f5dfa67be5 100644 --- a/src/test/compile-fail/borrowck-reborrow-from-mut.rs +++ b/src/test/compile-fail/borrowck-reborrow-from-mut.rs @@ -14,8 +14,8 @@ struct Foo { } struct Bar { - int1: int, - int2: int, + int1: isize, + int2: isize, } fn borrow_same_field_twice_mut_mut(foo: &mut Foo) { diff --git a/src/test/compile-fail/borrowck-reborrow-from-shorter-lived-andmut.rs b/src/test/compile-fail/borrowck-reborrow-from-shorter-lived-andmut.rs index 05cadfd5365..eee407472bf 100644 --- a/src/test/compile-fail/borrowck-reborrow-from-shorter-lived-andmut.rs +++ b/src/test/compile-fail/borrowck-reborrow-from-shorter-lived-andmut.rs @@ -12,7 +12,7 @@ // borrowed (but otherwise non-aliasable) location is illegal. struct S<'a> { - pointer: &'a mut int + pointer: &'a mut isize } fn copy_borrowed_ptr<'a,'b>(p: &'a mut S<'b>) -> S<'b> { diff --git a/src/test/compile-fail/borrowck-ref-mut-of-imm.rs b/src/test/compile-fail/borrowck-ref-mut-of-imm.rs index 4a34b85c3ed..1784b72a699 100644 --- a/src/test/compile-fail/borrowck-ref-mut-of-imm.rs +++ b/src/test/compile-fail/borrowck-ref-mut-of-imm.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn destructure(x: Option<int>) -> int { +fn destructure(x: Option<isize>) -> isize { match x { None => 0, Some(ref mut v) => *v //~ ERROR cannot borrow diff --git a/src/test/compile-fail/borrowck-report-with-custom-diagnostic.rs b/src/test/compile-fail/borrowck-report-with-custom-diagnostic.rs index 0a47353683c..c3a1e808e37 100644 --- a/src/test/compile-fail/borrowck-report-with-custom-diagnostic.rs +++ b/src/test/compile-fail/borrowck-report-with-custom-diagnostic.rs @@ -11,7 +11,7 @@ #![allow(dead_code)] fn main() { // Original borrow ends at end of function - let mut x = 1u; + let mut x = 1us; let y = &mut x; let z = &x; //~ ERROR cannot borrow } @@ -21,7 +21,7 @@ fn foo() { match true { true => { // Original borrow ends at end of match arm - let mut x = 1u; + let mut x = 1us; let y = &x; let z = &mut x; //~ ERROR cannot borrow } @@ -33,7 +33,7 @@ fn foo() { fn bar() { // Original borrow ends at end of closure |&:| { - let mut x = 1u; + let mut x = 1us; let y = &mut x; let z = &mut x; //~ ERROR cannot borrow }; diff --git a/src/test/compile-fail/borrowck-return.rs b/src/test/compile-fail/borrowck-return.rs index 6558bc57968..74d435b35e7 100644 --- a/src/test/compile-fail/borrowck-return.rs +++ b/src/test/compile-fail/borrowck-return.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f() -> int { - let x: int; +fn f() -> isize { + let x: isize; return x; //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/borrowck-struct-update-with-dtor.rs b/src/test/compile-fail/borrowck-struct-update-with-dtor.rs index 98a29f01faf..bbfc5f89a8d 100644 --- a/src/test/compile-fail/borrowck-struct-update-with-dtor.rs +++ b/src/test/compile-fail/borrowck-struct-update-with-dtor.rs @@ -15,10 +15,10 @@ use std::marker::NoCopy as NP; -struct S { a: int, np: NP } +struct S { a: isize, np: NP } impl Drop for S { fn drop(&mut self) { } } -struct T { a: int, mv: Box<int> } +struct T { a: isize, mv: Box<isize> } impl Drop for T { fn drop(&mut self) { } } fn f(s0:S) { diff --git a/src/test/compile-fail/borrowck-swap-mut-base-ptr.rs b/src/test/compile-fail/borrowck-swap-mut-base-ptr.rs index 3e8a0f87659..0102a909188 100644 --- a/src/test/compile-fail/borrowck-swap-mut-base-ptr.rs +++ b/src/test/compile-fail/borrowck-swap-mut-base-ptr.rs @@ -15,9 +15,9 @@ use std::mem::swap; -fn foo<'a>(mut t0: &'a mut int, - mut t1: &'a mut int) { - let p: &int = &*t0; // Freezes `*t0` +fn foo<'a>(mut t0: &'a mut isize, + mut t1: &'a mut isize) { + let p: &isize = &*t0; // Freezes `*t0` swap(&mut t0, &mut t1); //~ ERROR cannot borrow `t0` *t1 = 22; } diff --git a/src/test/compile-fail/borrowck-unary-move.rs b/src/test/compile-fail/borrowck-unary-move.rs index 72941f77210..5b5c5f4da91 100644 --- a/src/test/compile-fail/borrowck-unary-move.rs +++ b/src/test/compile-fail/borrowck-unary-move.rs @@ -9,13 +9,13 @@ // except according to those terms. -fn foo(x: Box<int>) -> int { +fn foo(x: Box<isize>) -> isize { let y = &*x; free(x); //~ ERROR cannot move out of `x` because it is borrowed *y } -fn free(_x: Box<int>) { +fn free(_x: Box<isize>) { } fn main() { diff --git a/src/test/compile-fail/borrowck-unboxed-closures.rs b/src/test/compile-fail/borrowck-unboxed-closures.rs index cca3dcb8b34..8e7e2e3e777 100644 --- a/src/test/compile-fail/borrowck-unboxed-closures.rs +++ b/src/test/compile-fail/borrowck-unboxed-closures.rs @@ -10,17 +10,17 @@ #![feature(overloaded_calls, unboxed_closures)] -fn a<F:Fn(int, int) -> int>(mut f: F) { +fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } -fn b<F:FnMut(int, int) -> int>(f: F) { +fn b<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } -fn c<F:FnOnce(int, int) -> int>(f: F) { +fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } diff --git a/src/test/compile-fail/borrowck-uninit-after-item.rs b/src/test/compile-fail/borrowck-uninit-after-item.rs index a828b1d6b9f..acd827d6c62 100644 --- a/src/test/compile-fail/borrowck-uninit-after-item.rs +++ b/src/test/compile-fail/borrowck-uninit-after-item.rs @@ -10,6 +10,6 @@ fn main() { let bar; - fn baz(_x: int) { } + fn baz(_x: isize) { } baz(bar); //~ ERROR use of possibly uninitialized variable: `bar` } diff --git a/src/test/compile-fail/borrowck-uninit-in-assignop.rs b/src/test/compile-fail/borrowck-uninit-in-assignop.rs index b5e462e592a..e253ecc74b9 100644 --- a/src/test/compile-fail/borrowck-uninit-in-assignop.rs +++ b/src/test/compile-fail/borrowck-uninit-in-assignop.rs @@ -12,33 +12,33 @@ // expression is detected. pub fn main() { - let x: int; + let x: isize; x += 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x -= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x *= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x /= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x %= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x ^= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x &= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x |= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x <<= 1; //~ ERROR use of possibly uninitialized variable: `x` - let x: int; + let x: isize; x >>= 1; //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/borrowck-uninit.rs b/src/test/compile-fail/borrowck-uninit.rs index a64216df6c7..f4b73bc889f 100644 --- a/src/test/compile-fail/borrowck-uninit.rs +++ b/src/test/compile-fail/borrowck-uninit.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(x: int) { println!("{}", x); } +fn foo(x: isize) { println!("{}", x); } fn main() { - let x: int; + let x: isize; foo(x); //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/borrowck-uniq-via-lend.rs b/src/test/compile-fail/borrowck-uniq-via-lend.rs index 9785b6a8f69..7fadf6d4660 100644 --- a/src/test/compile-fail/borrowck-uniq-via-lend.rs +++ b/src/test/compile-fail/borrowck-uniq-via-lend.rs @@ -8,16 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -fn borrow(_v: &int) {} +fn borrow(_v: &isize) {} fn local() { - let mut v = box 3i; + let mut v = box 3is; borrow(&*v); } fn local_rec() { - struct F { f: Box<int> } + struct F { f: Box<isize> } let mut v = F {f: box 3}; borrow(&*v.f); } @@ -25,33 +26,33 @@ fn local_rec() { fn local_recs() { struct F { f: G } struct G { g: H } - struct H { h: Box<int> } + struct H { h: Box<isize> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(&*v.f.g.h); } fn aliased_imm() { - let mut v = box 3i; + let mut v = box 3is; let _w = &v; borrow(&*v); } fn aliased_mut() { - let mut v = box 3i; + let mut v = box 3is; let _w = &mut v; borrow(&*v); //~ ERROR cannot borrow `*v` } fn aliased_other() { - let mut v = box 3i; - let mut w = box 4i; + let mut v = box 3is; + let mut w = box 4is; let _x = &mut w; borrow(&*v); } fn aliased_other_reassign() { - let mut v = box 3i; - let mut w = box 4i; + let mut v = box 3is; + let mut w = box 4is; let mut _x = &mut w; _x = &mut v; borrow(&*v); //~ ERROR cannot borrow `*v` diff --git a/src/test/compile-fail/borrowck-use-in-index-lvalue.rs b/src/test/compile-fail/borrowck-use-in-index-lvalue.rs index 3cd582ca0b8..94c1d3a6a45 100644 --- a/src/test/compile-fail/borrowck-use-in-index-lvalue.rs +++ b/src/test/compile-fail/borrowck-use-in-index-lvalue.rs @@ -9,10 +9,10 @@ // except according to those terms. fn test() { - let w: &mut [int]; + let w: &mut [isize]; w[5] = 0; //~ ERROR use of possibly uninitialized variable: `w` - let mut w: &mut [int]; + let mut w: &mut [isize]; w[5] = 0; //~ ERROR use of possibly uninitialized variable: `w` } diff --git a/src/test/compile-fail/borrowck-use-mut-borrow.rs b/src/test/compile-fail/borrowck-use-mut-borrow.rs index 0d27473cb2d..42e12622b69 100644 --- a/src/test/compile-fail/borrowck-use-mut-borrow.rs +++ b/src/test/compile-fail/borrowck-use-mut-borrow.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { a: int, b: int } +#![feature(box_syntax)] + +struct A { a: isize, b: isize } impl Copy for A {} -struct B { a: int, b: Box<int> } +struct B { a: isize, b: Box<isize> } fn var_copy_after_var_borrow() { - let mut x: int = 1; + let mut x: isize = 1; let p = &mut x; drop(x); //~ ERROR cannot use `x` because it was mutably borrowed *p = 2; @@ -59,7 +61,7 @@ fn fu_field_copy_after_field_borrow() { } fn var_deref_after_var_borrow() { - let mut x: Box<int> = box 1; + let mut x: Box<isize> = box 1; let p = &mut x; drop(*x); //~ ERROR cannot use `*x` because it was mutably borrowed **p = 2; diff --git a/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs b/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs index 4a5418a4f20..577334cce95 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-element-loan.rs @@ -10,9 +10,9 @@ #![feature(advanced_slice_patterns)] -fn a<'a>() -> &'a [int] { +fn a<'a>() -> &'a [isize] { let vec = vec!(1, 2, 3, 4); - let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough + let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough let tail = match vec { [_, tail..] => tail, _ => panic!("a") @@ -20,9 +20,9 @@ fn a<'a>() -> &'a [int] { tail } -fn b<'a>() -> &'a [int] { +fn b<'a>() -> &'a [isize] { let vec = vec!(1, 2, 3, 4); - let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough + let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough let init = match vec { [init.., _] => init, _ => panic!("b") @@ -30,9 +30,9 @@ fn b<'a>() -> &'a [int] { init } -fn c<'a>() -> &'a [int] { +fn c<'a>() -> &'a [isize] { let vec = vec!(1, 2, 3, 4); - let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough + let vec: &[isize] = vec.as_slice(); //~ ERROR does not live long enough let slice = match vec { [_, slice.., _] => slice, _ => panic!("c") diff --git a/src/test/compile-fail/borrowck-vec-pattern-loan-from-mut.rs b/src/test/compile-fail/borrowck-vec-pattern-loan-from-mut.rs index cc1dbc81955..565b8ca2f68 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-loan-from-mut.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-loan-from-mut.rs @@ -10,7 +10,7 @@ fn a() { let mut v = vec!(1, 2, 3); - let vb: &mut [int] = v.as_mut_slice(); + let vb: &mut [isize] = v.as_mut_slice(); match vb { [_a, tail..] => { v.push(tail[0] + tail[1]); //~ ERROR cannot borrow diff --git a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs index cb8762f44fb..8869e99efd5 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let mut a = [1i, 2, 3, 4]; + let mut a = [1is, 2, 3, 4]; let t = match a { [1, 2, tail..] => tail, _ => unreachable!() diff --git a/src/test/compile-fail/borrowck-vec-pattern-nesting.rs b/src/test/compile-fail/borrowck-vec-pattern-nesting.rs index 2eec7887856..49994ebdbba 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-nesting.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-nesting.rs @@ -9,9 +9,10 @@ // except according to those terms. #![feature(advanced_slice_patterns)] +#![feature(box_syntax)] fn a() { - let mut vec = [box 1i, box 2, box 3]; + let mut vec = [box 1is, box 2, box 3]; match vec { [box ref _a, _, _] => { vec[0] = box 4; //~ ERROR cannot assign @@ -20,8 +21,8 @@ fn a() { } fn b() { - let mut vec = vec!(box 1i, box 2, box 3); - let vec: &mut [Box<int>] = vec.as_mut_slice(); + let mut vec = vec!(box 1is, box 2, box 3); + let vec: &mut [Box<isize>] = vec.as_mut_slice(); match vec { [_b..] => { vec[0] = box 4; //~ ERROR cannot assign @@ -30,8 +31,8 @@ fn b() { } fn c() { - let mut vec = vec!(box 1i, box 2, box 3); - let vec: &mut [Box<int>] = vec.as_mut_slice(); + let mut vec = vec!(box 1is, box 2, box 3); + let vec: &mut [Box<isize>] = vec.as_mut_slice(); match vec { [_a, //~ ERROR cannot move out _b..] => { //~^ NOTE attempting to move value to here @@ -48,8 +49,8 @@ fn c() { } fn d() { - let mut vec = vec!(box 1i, box 2, box 3); - let vec: &mut [Box<int>] = vec.as_mut_slice(); + let mut vec = vec!(box 1is, box 2, box 3); + let vec: &mut [Box<isize>] = vec.as_mut_slice(); match vec { [_a.., //~ ERROR cannot move out _b] => {} //~ NOTE attempting to move value to here @@ -59,8 +60,8 @@ fn d() { } fn e() { - let mut vec = vec!(box 1i, box 2, box 3); - let vec: &mut [Box<int>] = vec.as_mut_slice(); + let mut vec = vec!(box 1is, box 2, box 3); + let vec: &mut [Box<isize>] = vec.as_mut_slice(); match vec { [_a, _b, _c] => {} //~ ERROR cannot move out //~^ NOTE attempting to move value to here diff --git a/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs b/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs index 852eb172c59..bcd1aa81d4c 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-tail-element-loan.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn a<'a>() -> &'a int { +fn a<'a>() -> &'a isize { let vec = vec!(1, 2, 3, 4); - let vec: &[int] = vec.as_slice(); //~ ERROR `vec` does not live long enough + let vec: &[isize] = vec.as_slice(); //~ ERROR `vec` does not live long enough let tail = match vec { [_a, tail..] => &tail[0], _ => panic!("foo") diff --git a/src/test/compile-fail/borrowck-while-break.rs b/src/test/compile-fail/borrowck-while-break.rs index 15a70b2444d..4752120d691 100644 --- a/src/test/compile-fail/borrowck-while-break.rs +++ b/src/test/compile-fail/borrowck-while-break.rs @@ -11,7 +11,7 @@ fn test(cond: bool) { let v; while cond { - v = 3i; + v = 3is; break; } println!("{}", v); //~ ERROR use of possibly uninitialized variable: `v` diff --git a/src/test/compile-fail/borrowck-while.rs b/src/test/compile-fail/borrowck-while.rs index b5703e56642..f163cf602bf 100644 --- a/src/test/compile-fail/borrowck-while.rs +++ b/src/test/compile-fail/borrowck-while.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f() -> int { - let mut x: int; - while 1i == 1 { x = 10; } +fn f() -> isize { + let mut x: isize; + while 1is == 1 { x = 10; } return x; //~ ERROR use of possibly uninitialized variable: `x` } diff --git a/src/test/compile-fail/builtin-superkinds-self-type.rs b/src/test/compile-fail/builtin-superkinds-self-type.rs index 9826a5a0126..0ec4f3dce11 100644 --- a/src/test/compile-fail/builtin-superkinds-self-type.rs +++ b/src/test/compile-fail/builtin-superkinds-self-type.rs @@ -22,6 +22,6 @@ impl <T: Sync> Foo for T { } fn main() { let (tx, rx) = channel(); - 1193182i.foo(tx); - assert!(rx.recv() == 1193182i); + 1193182is.foo(tx); + assert!(rx.recv() == 1193182is); } diff --git a/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs index 143e78e5d9f..9148f13c4dd 100644 --- a/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs +++ b/src/test/compile-fail/cannot-mutate-captured-non-mut-var.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = 1i; + let x = 1is; move|:| { x = 2; }; //~^ ERROR: cannot assign to immutable captured outer variable diff --git a/src/test/compile-fail/capture1.rs b/src/test/compile-fail/capture1.rs index 7d590ca49dd..fd50918a313 100644 --- a/src/test/compile-fail/capture1.rs +++ b/src/test/compile-fail/capture1.rs @@ -12,6 +12,6 @@ // error-pattern: can't capture dynamic environment in a fn item; fn main() { - let bar: int = 5; - fn foo() -> int { return bar; } + let bar: isize = 5; + fn foo() -> isize { return bar; } } diff --git a/src/test/compile-fail/cast-to-bare-fn.rs b/src/test/compile-fail/cast-to-bare-fn.rs index 1db813292b0..a7f0917ed86 100644 --- a/src/test/compile-fail/cast-to-bare-fn.rs +++ b/src/test/compile-fail/cast-to-bare-fn.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(_x: int) { } +fn foo(_x: isize) { } fn main() { let v: u64 = 5; - let x = foo as extern "C" fn() -> int; + let x = foo as extern "C" fn() -> isize; //~^ ERROR mismatched types - let y = v as extern "Rust" fn(int) -> (int, int); + let y = v as extern "Rust" fn(isize) -> (isize, isize); //~^ ERROR non-scalar cast y(x()); } diff --git a/src/test/compile-fail/check-static-immutable-mut-slices.rs b/src/test/compile-fail/check-static-immutable-mut-slices.rs index 2945a050247..d1e3fe25253 100644 --- a/src/test/compile-fail/check-static-immutable-mut-slices.rs +++ b/src/test/compile-fail/check-static-immutable-mut-slices.rs @@ -10,7 +10,7 @@ // Checks that immutable static items can't have mutable slices -static TEST: &'static mut [int] = &mut []; +static TEST: &'static mut [isize] = &mut []; //~^ ERROR statics are not allowed to have mutable references pub fn main() { } diff --git a/src/test/compile-fail/check-static-values-constraints.rs b/src/test/compile-fail/check-static-values-constraints.rs index 1c7ae05961e..7c4f9ada2d3 100644 --- a/src/test/compile-fail/check-static-values-constraints.rs +++ b/src/test/compile-fail/check-static-values-constraints.rs @@ -10,6 +10,8 @@ // Verifies all possible restrictions for statics values. +#![feature(box_syntax)] + use std::marker; struct WithDtor; @@ -24,7 +26,7 @@ impl Drop for WithDtor { // 3. Expr calls with unsafe arguments for statics are rejected enum SafeEnum { Variant1, - Variant2(int), + Variant2(isize), Variant3(WithDtor), Variant4(String) } @@ -43,7 +45,7 @@ static STATIC3: SafeEnum = SafeEnum::Variant3(WithDtor); // a destructor. enum UnsafeEnum { Variant5, - Variant6(int) + Variant6(isize) } impl Drop for UnsafeEnum { @@ -130,11 +132,11 @@ static STATIC16: (&'static Box<MyOwned>, &'static Box<MyOwned>) = ( static mut STATIC17: SafeEnum = SafeEnum::Variant1; //~^ ERROR mutable statics are not allowed to have destructors -static STATIC19: Box<int> = +static STATIC19: Box<isize> = box 3; //~^ ERROR statics are not allowed to have custom pointers pub fn main() { - let y = { static x: Box<int> = box 3; x }; + let y = { static x: Box<isize> = box 3; x }; //~^ ERROR statics are not allowed to have custom pointers } diff --git a/src/test/compile-fail/class-cast-to-trait.rs b/src/test/compile-fail/class-cast-to-trait.rs index ae0f377ba87..31e09e877c7 100644 --- a/src/test/compile-fail/class-cast-to-trait.rs +++ b/src/test/compile-fail/class-cast-to-trait.rs @@ -8,15 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait noisy { fn speak(&self); } struct cat { - meows : uint, + meows : usize, - how_hungry : int, + how_hungry : isize, name : String, } @@ -49,7 +50,7 @@ impl cat { } } -fn cat(in_x : uint, in_y : int, in_name: String) -> cat { +fn cat(in_x : usize, in_y : isize, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, diff --git a/src/test/compile-fail/class-implements-bad-trait.rs b/src/test/compile-fail/class-implements-bad-trait.rs index 9e7366a643d..d709ffdc3fc 100644 --- a/src/test/compile-fail/class-implements-bad-trait.rs +++ b/src/test/compile-fail/class-implements-bad-trait.rs @@ -10,10 +10,10 @@ // error-pattern:nonexistent class cat : nonexistent { - let meows: uint; - new(in_x : uint) { self.meows = in_x; } + let meows: usize; + new(in_x : usize) { self.meows = in_x; } } fn main() { - let nyan = cat(0u); + let nyan = cat(0us); } diff --git a/src/test/compile-fail/class-method-missing.rs b/src/test/compile-fail/class-method-missing.rs index 17cf36b73f6..3b921e07279 100644 --- a/src/test/compile-fail/class-method-missing.rs +++ b/src/test/compile-fail/class-method-missing.rs @@ -13,19 +13,19 @@ trait animal { } struct cat { - meows: uint, + meows: usize, } impl animal for cat { //~^ ERROR not all trait items implemented, missing: `eat` } -fn cat(in_x : uint) -> cat { +fn cat(in_x : usize) -> cat { cat { meows: in_x } } fn main() { - let nyan = cat(0u); + let nyan = cat(0us); } diff --git a/src/test/compile-fail/class-missing-self.rs b/src/test/compile-fail/class-missing-self.rs index 0e75e702277..4d8e4bca784 100644 --- a/src/test/compile-fail/class-missing-self.rs +++ b/src/test/compile-fail/class-missing-self.rs @@ -9,14 +9,14 @@ // except according to those terms. struct cat { - meows : uint, + meows : usize, } impl cat { fn sleep(&self) { loop{} } fn meow(&self) { println!("Meow"); - meows += 1u; //~ ERROR unresolved name + meows += 1us; //~ ERROR unresolved name sleep(); //~ ERROR unresolved name } diff --git a/src/test/compile-fail/coherence-all-remote.rs b/src/test/compile-fail/coherence-all-remote.rs index d86256a7776..f8ddf83c9c6 100644 --- a/src/test/compile-fail/coherence-all-remote.rs +++ b/src/test/compile-fail/coherence-all-remote.rs @@ -13,7 +13,7 @@ extern crate "coherence-lib" as lib; use lib::Remote1; -impl<T> Remote1<T> for int { } +impl<T> Remote1<T> for isize { } //~^ ERROR E0117 fn main() { } diff --git a/src/test/compile-fail/coherence-bigint-int.rs b/src/test/compile-fail/coherence-bigint-int.rs index b4917d0c29f..684773098cd 100644 --- a/src/test/compile-fail/coherence-bigint-int.rs +++ b/src/test/compile-fail/coherence-bigint-int.rs @@ -15,6 +15,6 @@ use lib::Remote1; pub struct BigInt; -impl Remote1<BigInt> for int { } //~ ERROR E0117 +impl Remote1<BigInt> for isize { } //~ ERROR E0117 fn main() { } diff --git a/src/test/compile-fail/coherence-bigint-vecint.rs b/src/test/compile-fail/coherence-bigint-vecint.rs index de4e656110f..28747674b8b 100644 --- a/src/test/compile-fail/coherence-bigint-vecint.rs +++ b/src/test/compile-fail/coherence-bigint-vecint.rs @@ -15,6 +15,6 @@ use lib::Remote1; pub struct BigInt; -impl Remote1<BigInt> for Vec<int> { } //~ ERROR E0117 +impl Remote1<BigInt> for Vec<isize> { } //~ ERROR E0117 fn main() { } diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-implemented.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-implemented.rs index c0d82d35e30..27d97d18c94 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-implemented.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-implemented.rs @@ -16,23 +16,23 @@ use std::default::Default; // for the same type (though this crate doesn't). trait MyTrait { - fn get(&self) -> uint; + fn get(&self) -> usize; } trait Even { } trait Odd { } -impl Even for int { } +impl Even for isize { } -impl Odd for uint { } +impl Odd for usize { } impl<T:Even> MyTrait for T { //~ ERROR E0119 - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } impl<T:Odd> MyTrait for T { - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } fn main() { } diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-unimplemented.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-unimplemented.rs index c44844bcf0b..0f233b78c72 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-unimplemented.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-blanket-unimplemented.rs @@ -16,7 +16,7 @@ use std::default::Default; // for the same type (though this crate doesn't implement them at all). trait MyTrait { - fn get(&self) -> uint; + fn get(&self) -> usize; } trait Even { } @@ -24,11 +24,11 @@ trait Even { } trait Odd { } impl<T:Even> MyTrait for T { //~ ERROR E0119 - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } impl<T:Odd> MyTrait for T { - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } fn main() { } diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-cross-crate.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-cross-crate.rs index 2e163bc11a8..1f6bb08871c 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-cross-crate.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-cross-crate.rs @@ -19,11 +19,11 @@ use std::default::Default; struct MyThingy; impl Go for MyThingy { - fn go(&self, arg: int) { } + fn go(&self, arg: isize) { } } impl GoMut for MyThingy { //~ ERROR conflicting implementations - fn go_mut(&mut self, arg: int) { } + fn go_mut(&mut self, arg: isize) { } } fn main() { } diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-multidispatch.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-multidispatch.rs index f3efca369b3..c3563792ce3 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-multidispatch.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-multidispatch.rs @@ -26,11 +26,11 @@ impl<T> MyTrait<T> for T { //~ ERROR E0119 #[derive(Clone)] struct MyType { - dummy: uint + dummy: usize } impl MyTrait<MyType> for MyType { - fn get(&self) -> uint { (*self).clone() } + fn get(&self) -> usize { (*self).clone() } } fn main() { } diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-trait.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-trait.rs index 9db322a5517..eeaa68677eb 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-specific-trait.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-specific-trait.rs @@ -16,19 +16,19 @@ trait OtherTrait { } trait MyTrait { - fn get(&self) -> uint; + fn get(&self) -> usize; } impl<T:OtherTrait> MyTrait for T { //~ ERROR E0119 - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } struct MyType { - dummy: uint + dummy: usize } impl MyTrait for MyType { - fn get(&self) -> uint { self.dummy } + fn get(&self) -> usize { self.dummy } } impl OtherTrait for MyType { diff --git a/src/test/compile-fail/coherence-blanket-conflicts-with-specific.rs b/src/test/compile-fail/coherence-blanket-conflicts-with-specific.rs index 936025385bb..980e4256d2b 100644 --- a/src/test/compile-fail/coherence-blanket-conflicts-with-specific.rs +++ b/src/test/compile-fail/coherence-blanket-conflicts-with-specific.rs @@ -15,19 +15,19 @@ use std::default::Default; // specific T. trait MyTrait { - fn get(&self) -> uint; + fn get(&self) -> usize; } impl<T> MyTrait for T { //~ ERROR E0119 - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } struct MyType { - dummy: uint + dummy: usize } impl MyTrait for MyType { - fn get(&self) -> uint { self.dummy } + fn get(&self) -> usize { self.dummy } } fn main() { } diff --git a/src/test/compile-fail/coherence-orphan.rs b/src/test/compile-fail/coherence-orphan.rs index 30a382c143d..0bd0224b246 100644 --- a/src/test/compile-fail/coherence-orphan.rs +++ b/src/test/compile-fail/coherence-orphan.rs @@ -16,10 +16,10 @@ use lib::TheTrait; struct TheType; -impl TheTrait<uint> for int { } //~ ERROR E0117 +impl TheTrait<usize> for isize { } //~ ERROR E0117 -impl TheTrait<TheType> for int { } //~ ERROR E0117 +impl TheTrait<TheType> for isize { } //~ ERROR E0117 -impl TheTrait<int> for TheType { } +impl TheTrait<isize> for TheType { } fn main() { } diff --git a/src/test/compile-fail/coherence-tuple-conflict.rs b/src/test/compile-fail/coherence-tuple-conflict.rs index 92fa725cb1e..9673fb6a213 100644 --- a/src/test/compile-fail/coherence-tuple-conflict.rs +++ b/src/test/compile-fail/coherence-tuple-conflict.rs @@ -15,15 +15,15 @@ use std::default::Default; // specific T. trait MyTrait { - fn get(&self) -> uint; + fn get(&self) -> usize; } impl<T> MyTrait for (T,T) { //~ ERROR E0119 - fn get(&self) -> uint { 0 } + fn get(&self) -> usize { 0 } } impl<A,B> MyTrait for (A,B) { - fn get(&self) -> uint { self.dummy } + fn get(&self) -> usize { self.dummy } } fn main() { } diff --git a/src/test/compile-fail/comm-not-freeze-receiver.rs b/src/test/compile-fail/comm-not-freeze-receiver.rs index a7962c09fb3..305acfec401 100644 --- a/src/test/compile-fail/comm-not-freeze-receiver.rs +++ b/src/test/compile-fail/comm-not-freeze-receiver.rs @@ -13,5 +13,5 @@ use std::sync::mpsc::Receiver; fn test<T: Sync>() {} fn main() { - test::<Receiver<int>>(); //~ ERROR: `core::marker::Sync` is not implemented + test::<Receiver<isize>>(); //~ ERROR: `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/comm-not-freeze.rs b/src/test/compile-fail/comm-not-freeze.rs index 1977438d423..de2c96920c3 100644 --- a/src/test/compile-fail/comm-not-freeze.rs +++ b/src/test/compile-fail/comm-not-freeze.rs @@ -13,5 +13,5 @@ use std::sync::mpsc::Sender; fn test<T: Sync>() {} fn main() { - test::<Sender<int>>(); //~ ERROR: `core::marker::Sync` is not implemented + test::<Sender<isize>>(); //~ ERROR: `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/const-block-non-item-statement.rs b/src/test/compile-fail/const-block-non-item-statement.rs index 1814b1cd544..62e8fccbda0 100644 --- a/src/test/compile-fail/const-block-non-item-statement.rs +++ b/src/test/compile-fail/const-block-non-item-statement.rs @@ -8,18 +8,18 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static A: uint = { 1u; 2 }; +static A: usize = { 1us; 2 }; //~^ ERROR: blocks in constants are limited to items and tail expressions -static B: uint = { { } 2 }; +static B: usize = { { } 2 }; //~^ ERROR: blocks in constants are limited to items and tail expressions macro_rules! foo { () => (()) //~ ERROR: blocks in constants are limited to items and tail expressions } -static C: uint = { foo!(); 2 }; +static C: usize = { foo!(); 2 }; -static D: uint = { let x = 4u; 2 }; +static D: usize = { let x = 4us; 2 }; //~^ ERROR: blocks in constants are limited to items and tail expressions pub fn main() { diff --git a/src/test/compile-fail/const-recursive.rs b/src/test/compile-fail/const-recursive.rs index 9c633e082b1..ad05c7c423f 100644 --- a/src/test/compile-fail/const-recursive.rs +++ b/src/test/compile-fail/const-recursive.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: recursive constant -static a: int = b; -static b: int = a; +static a: isize = b; +static b: isize = a; fn main() { } diff --git a/src/test/compile-fail/copy-a-resource.rs b/src/test/compile-fail/copy-a-resource.rs index 01c6970506c..1201db437b9 100644 --- a/src/test/compile-fail/copy-a-resource.rs +++ b/src/test/compile-fail/copy-a-resource.rs @@ -10,14 +10,14 @@ #[derive(Show)] struct foo { - i: int, + i: isize, } impl Drop for foo { fn drop(&mut self) {} } -fn foo(i:int) -> foo { +fn foo(i:isize) -> foo { foo { i: i } diff --git a/src/test/compile-fail/cross-borrow-trait.rs b/src/test/compile-fail/cross-borrow-trait.rs index 1ccd5290fef..ff96ea93184 100644 --- a/src/test/compile-fail/cross-borrow-trait.rs +++ b/src/test/compile-fail/cross-borrow-trait.rs @@ -11,6 +11,8 @@ // Test that cross-borrowing (implicitly converting from `Box<T>` to `&T`) is // forbidden when `T` is a trait. +#![feature(box_syntax)] + struct Foo; trait Trait {} impl Trait for Foo {} diff --git a/src/test/compile-fail/deriving-non-type.rs b/src/test/compile-fail/deriving-non-type.rs index 717ce6e11ef..6015652668e 100644 --- a/src/test/compile-fail/deriving-non-type.rs +++ b/src/test/compile-fail/deriving-non-type.rs @@ -22,10 +22,10 @@ impl S { } impl T for S { } #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums -static s: uint = 0u; +static s: usize = 0us; #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums -const c: uint = 0u; +const c: usize = 0us; #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums mod m { } @@ -34,7 +34,7 @@ mod m { } extern "C" { } #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums -type A = uint; +type A = usize; #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums fn main() { } diff --git a/src/test/compile-fail/deriving-primitive.rs b/src/test/compile-fail/deriving-primitive.rs index a3c6c8672c8..6e9b120aa69 100644 --- a/src/test/compile-fail/deriving-primitive.rs +++ b/src/test/compile-fail/deriving-primitive.rs @@ -9,25 +9,25 @@ // except according to those terms. use std::num::FromPrimitive; -use std::int; +use std::isize; #[derive(FromPrimitive)] -struct A { x: int } +struct A { x: isize } //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] -struct B(int); +struct B(isize); //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] -enum C { Foo(int), Bar(uint) } +enum C { Foo(isize), Bar(usize) } //~^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments //~^^^ ERROR `FromPrimitive` cannot be derived for enum variants with arguments #[derive(FromPrimitive)] -enum D { Baz { x: int } } +enum D { Baz { x: isize } } //~^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants //~^^^ ERROR `FromPrimitive` cannot be derived for enums with struct variants diff --git a/src/test/compile-fail/destructure-trait-ref.rs b/src/test/compile-fail/destructure-trait-ref.rs index a2a5a3e257f..5166ef8f72f 100644 --- a/src/test/compile-fail/destructure-trait-ref.rs +++ b/src/test/compile-fail/destructure-trait-ref.rs @@ -11,8 +11,10 @@ // The regression test for #15031 to make sure destructuring trait // reference work properly. +#![feature(box_syntax)] + trait T {} -impl T for int {} +impl T for isize {} fn main() { // For an expression of the form: @@ -25,17 +27,17 @@ fn main() { // if n > m, it's a type mismatch error. // n < m - let &x = &(&1i as &T); - let &x = &&(&1i as &T); - let &&x = &&(&1i as &T); + let &x = &(&1is as &T); + let &x = &&(&1is as &T); + let &&x = &&(&1is as &T); // n == m - let &x = &1i as &T; //~ ERROR type `&T` cannot be dereferenced - let &&x = &(&1i as &T); //~ ERROR type `&T` cannot be dereferenced - let box x = box 1i as Box<T>; //~ ERROR type `Box<T>` cannot be dereferenced + let &x = &1is as &T; //~ ERROR type `&T` cannot be dereferenced + let &&x = &(&1is as &T); //~ ERROR type `&T` cannot be dereferenced + let box x = box 1is as Box<T>; //~ ERROR type `Box<T>` cannot be dereferenced // n > m - let &&x = &1i as &T; //~ ERROR found &-ptr - let &&&x = &(&1i as &T); //~ ERROR found &-ptr - let box box x = box 1i as Box<T>; //~ ERROR found box + let &&x = &1is as &T; //~ ERROR found &-ptr + let &&&x = &(&1is as &T); //~ ERROR found &-ptr + let box box x = box 1is as Box<T>; //~ ERROR found box } diff --git a/src/test/compile-fail/drop-on-non-struct.rs b/src/test/compile-fail/drop-on-non-struct.rs index 238700254b8..26b247d0d0f 100644 --- a/src/test/compile-fail/drop-on-non-struct.rs +++ b/src/test/compile-fail/drop-on-non-struct.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -impl Drop for int { +impl<'a> Drop for &'a mut isize { //~^ ERROR the Drop trait may only be implemented on structures //~^^ ERROR E0117 fn drop(&mut self) { diff --git a/src/test/compile-fail/drop-with-active-borrows-2.rs b/src/test/compile-fail/drop-with-active-borrows-2.rs index 1cbd6292e99..d9d3d79b5af 100644 --- a/src/test/compile-fail/drop-with-active-borrows-2.rs +++ b/src/test/compile-fail/drop-with-active-borrows-2.rs @@ -15,5 +15,5 @@ fn read_lines_borrowed<'a>() -> Vec<&'a str> { } fn main() { - println!("{}", read_lines_borrowed()); + println!("{:?}", read_lines_borrowed()); } diff --git a/src/test/compile-fail/dst-bad-assign-2.rs b/src/test/compile-fail/dst-bad-assign-2.rs index ebd0ee97efe..7dbb8fc92e3 100644 --- a/src/test/compile-fail/dst-bad-assign-2.rs +++ b/src/test/compile-fail/dst-bad-assign-2.rs @@ -10,8 +10,10 @@ // Forbid assignment into a dynamically sized type. +#![feature(box_syntax)] + struct Fat<T: ?Sized> { - f1: int, + f1: isize, f2: &'static str, ptr: T } @@ -21,19 +23,19 @@ struct Bar; #[derive(PartialEq,Eq)] struct Bar1 { - f: int + f: isize } trait ToBar { fn to_bar(&self) -> Bar; - fn to_val(&self) -> int; + fn to_val(&self) -> isize; } impl ToBar for Bar1 { fn to_bar(&self) -> Bar { Bar } - fn to_val(&self) -> int { + fn to_val(&self) -> isize { self.f } } diff --git a/src/test/compile-fail/dst-bad-assign.rs b/src/test/compile-fail/dst-bad-assign.rs index f52c990ca52..634b5999e9e 100644 --- a/src/test/compile-fail/dst-bad-assign.rs +++ b/src/test/compile-fail/dst-bad-assign.rs @@ -10,8 +10,10 @@ // Forbid assignment into a dynamically sized type. +#![feature(box_syntax)] + struct Fat<T: ?Sized> { - f1: int, + f1: isize, f2: &'static str, ptr: T } @@ -21,19 +23,19 @@ struct Bar; #[derive(PartialEq,Eq)] struct Bar1 { - f: int + f: isize } trait ToBar { fn to_bar(&self) -> Bar; - fn to_val(&self) -> int; + fn to_val(&self) -> isize; } impl ToBar for Bar1 { fn to_bar(&self) -> Bar { Bar } - fn to_val(&self) -> int { + fn to_val(&self) -> isize { self.f } } diff --git a/src/test/compile-fail/dst-bad-coerce2.rs b/src/test/compile-fail/dst-bad-coerce2.rs index 54c625221ba..160197368d6 100644 --- a/src/test/compile-fail/dst-bad-coerce2.rs +++ b/src/test/compile-fail/dst-bad-coerce2.rs @@ -21,8 +21,8 @@ impl Bar for Foo {} pub fn main() { // With a vec of ints. let f1 = Fat { ptr: [1, 2, 3] }; - let f2: &Fat<[int; 3]> = &f1; - let f3: &mut Fat<[int]> = f2; //~ ERROR mismatched types + let f2: &Fat<[isize; 3]> = &f1; + let f3: &mut Fat<[isize]> = f2; //~ ERROR mismatched types // With a trait. let f1 = Fat { ptr: Foo }; diff --git a/src/test/compile-fail/dst-bad-coerce3.rs b/src/test/compile-fail/dst-bad-coerce3.rs index 192d43e32fd..347a2d2ecbe 100644 --- a/src/test/compile-fail/dst-bad-coerce3.rs +++ b/src/test/compile-fail/dst-bad-coerce3.rs @@ -21,8 +21,8 @@ impl Bar for Foo {} fn baz<'a>() { // With a vec of ints. let f1 = Fat { ptr: [1, 2, 3] }; - let f2: &Fat<[int; 3]> = &f1; //~ ERROR `f1` does not live long enough - let f3: &'a Fat<[int]> = f2; + let f2: &Fat<[isize; 3]> = &f1; //~ ERROR `f1` does not live long enough + let f3: &'a Fat<[isize]> = f2; // With a trait. let f1 = Fat { ptr: Foo }; diff --git a/src/test/compile-fail/dst-bad-deep.rs b/src/test/compile-fail/dst-bad-deep.rs index 0276e2e418d..032835d9460 100644 --- a/src/test/compile-fail/dst-bad-deep.rs +++ b/src/test/compile-fail/dst-bad-deep.rs @@ -18,8 +18,8 @@ struct Fat<T: ?Sized> { } pub fn main() { - let f: Fat<[int; 3]> = Fat { ptr: [5i, 6, 7] }; - let g: &Fat<[int]> = &f; - let h: &Fat<Fat<[int]>> = &Fat { ptr: *g }; + let f: Fat<[isize; 3]> = Fat { ptr: [5is, 6, 7] }; + let g: &Fat<[isize]> = &f; + let h: &Fat<Fat<[isize]>> = &Fat { ptr: *g }; //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/dst-index.rs b/src/test/compile-fail/dst-index.rs index e297ecaac23..2a66b87fece 100644 --- a/src/test/compile-fail/dst-index.rs +++ b/src/test/compile-fail/dst-index.rs @@ -18,10 +18,10 @@ struct S; impl Copy for S {} -impl Index<uint> for S { +impl Index<usize> for S { type Output = str; - fn index<'a>(&'a self, _: &uint) -> &'a str { + fn index<'a>(&'a self, _: &usize) -> &'a str { "hello" } } @@ -30,20 +30,20 @@ struct T; impl Copy for T {} -impl Index<uint> for T { +impl Index<usize> for T { type Output = Show + 'static; - fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) { - static x: uint = 42; + fn index<'a>(&'a self, idx: &usize) -> &'a (Show + 'static) { + static x: usize = 42; &x } } fn main() { S[0]; - //~^ ERROR cannot move out of dereference + //~^ ERROR cannot move out of indexed content //~^^ ERROR E0161 T[0]; - //~^ ERROR cannot move out of dereference + //~^ ERROR cannot move out of indexed content //~^^ ERROR E0161 } diff --git a/src/test/compile-fail/dst-rvalue.rs b/src/test/compile-fail/dst-rvalue.rs index 4c1dafd8c1a..69bda8c1671 100644 --- a/src/test/compile-fail/dst-rvalue.rs +++ b/src/test/compile-fail/dst-rvalue.rs @@ -10,13 +10,15 @@ // Check that dynamically sized rvalues are forbidden +#![feature(box_syntax)] + pub fn main() { let _x: Box<str> = box *"hello world"; //~^ ERROR E0161 - //~^^ ERROR cannot move out of dereference + //~^^ ERROR cannot move out of borrowed content - let array: &[int] = &[1, 2, 3]; - let _x: Box<[int]> = box *array; + let array: &[isize] = &[1, 2, 3]; + let _x: Box<[isize]> = box *array; //~^ ERROR E0161 - //~^^ ERROR cannot move out of dereference + //~^^ ERROR cannot move out of borrowed content } diff --git a/src/test/compile-fail/duplicate-parameter.rs b/src/test/compile-fail/duplicate-parameter.rs index c1c0f974de9..18ec55e10bb 100644 --- a/src/test/compile-fail/duplicate-parameter.rs +++ b/src/test/compile-fail/duplicate-parameter.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(a: int, a: int) {} +fn f(a: isize, a: isize) {} //~^ ERROR identifier `a` is bound more than once in this parameter list fn main() { diff --git a/src/test/compile-fail/enum-and-module-in-same-scope.rs b/src/test/compile-fail/enum-and-module-in-same-scope.rs index 7526c6753e6..f3d8fcf31d7 100644 --- a/src/test/compile-fail/enum-and-module-in-same-scope.rs +++ b/src/test/compile-fail/enum-and-module-in-same-scope.rs @@ -9,7 +9,7 @@ // except according to those terms. mod Foo { - pub static X: int = 42; + pub static X: isize = 42; } enum Foo { //~ ERROR duplicate definition of type or module `Foo` diff --git a/src/test/compile-fail/enum-discrim-too-small.rs b/src/test/compile-fail/enum-discrim-too-small.rs index 2de50ad1d1d..1d7794336a0 100644 --- a/src/test/compile-fail/enum-discrim-too-small.rs +++ b/src/test/compile-fail/enum-discrim-too-small.rs @@ -53,6 +53,6 @@ enum Ei32 { // u64 currently allows negative numbers, and i64 allows numbers greater than `1<<63`. This is a // little counterintuitive, but since the discriminant can store all the bits, and extracting it // with a cast requires specifying the signedness, there is no loss of information in those cases. -// This also applies to int and uint on 64-bit targets. +// This also applies to isize and usize on 64-bit targets. pub fn main() { } diff --git a/src/test/compile-fail/enum-in-scope.rs b/src/test/compile-fail/enum-in-scope.rs index cccf66ef2d5..7be06ec7de8 100644 --- a/src/test/compile-fail/enum-in-scope.rs +++ b/src/test/compile-fail/enum-in-scope.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct hello(int); +struct hello(isize); fn main() { let hello = 0; //~ERROR declaration of `hello` shadows diff --git a/src/test/compile-fail/exclusive-drop-and-copy.rs b/src/test/compile-fail/exclusive-drop-and-copy.rs new file mode 100644 index 00000000000..17453bc677f --- /dev/null +++ b/src/test/compile-fail/exclusive-drop-and-copy.rs @@ -0,0 +1,30 @@ +// 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. + +#![feature(unsafe_destructor)] + +// issue #20126 + +#[derive(Copy)] //~ ERROR the trait `Copy` may not be implemented +struct Foo; + +impl Drop for Foo { + fn drop(&mut self) {} +} + +#[derive(Copy)] //~ ERROR the trait `Copy` may not be implemented +struct Bar<T>; + +#[unsafe_destructor] +impl<T> Drop for Bar<T> { + fn drop(&mut self) {} +} + +fn main() {} diff --git a/src/test/compile-fail/explicit-call-to-dtor.rs b/src/test/compile-fail/explicit-call-to-dtor.rs index 6b334dd6ecd..90030488dd6 100644 --- a/src/test/compile-fail/explicit-call-to-dtor.rs +++ b/src/test/compile-fail/explicit-call-to-dtor.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int + x: isize } impl Drop for Foo { diff --git a/src/test/compile-fail/explicit-call-to-supertrait-dtor.rs b/src/test/compile-fail/explicit-call-to-supertrait-dtor.rs index d0dd0e68da6..63ed74dfa49 100644 --- a/src/test/compile-fail/explicit-call-to-supertrait-dtor.rs +++ b/src/test/compile-fail/explicit-call-to-supertrait-dtor.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int + x: isize } trait Bar : Drop { diff --git a/src/test/compile-fail/explicit-self-lifetime-mismatch.rs b/src/test/compile-fail/explicit-self-lifetime-mismatch.rs index 9b2264b8902..fbc5263d82d 100644 --- a/src/test/compile-fail/explicit-self-lifetime-mismatch.rs +++ b/src/test/compile-fail/explicit-self-lifetime-mismatch.rs @@ -9,8 +9,8 @@ // except according to those terms. struct Foo<'a,'b> { - x: &'a int, - y: &'b int, + x: &'a isize, + y: &'b isize, } impl<'a,'b> Foo<'a,'b> { diff --git a/src/test/compile-fail/export.rs b/src/test/compile-fail/export.rs index dec65d4b4f8..3a391e7c609 100644 --- a/src/test/compile-fail/export.rs +++ b/src/test/compile-fail/export.rs @@ -10,8 +10,8 @@ // error-pattern: unresolved name mod foo { - pub fn x(y: int) { log(debug, y); } - fn z(y: int) { log(debug, y); } + pub fn x(y: isize) { log(debug, y); } + fn z(y: isize) { log(debug, y); } } fn main() { foo::z(10); } diff --git a/src/test/compile-fail/extern-with-type-bounds.rs b/src/test/compile-fail/extern-with-type-bounds.rs new file mode 100644 index 00000000000..d2c88865d54 --- /dev/null +++ b/src/test/compile-fail/extern-with-type-bounds.rs @@ -0,0 +1,33 @@ +// 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. + +#![feature(intrinsics)] + +use std::intrinsics::TypeId; + +extern "rust-intrinsic" { + // Real example from libcore + fn type_id<T: ?Sized + 'static>() -> TypeId; + + // Silent bounds made explicit to make sure they are actually + // resolved. + fn transmute<T: Sized, U: Sized>(val: T) -> U; + + // Bounds aren't checked right now, so this should work + // even though it's incorrect. + fn size_of<T: Clone>() -> usize; + + // Unresolved bounds should still error. + fn align_of<T: NoSuchTrait>() -> usize; + //~^ ERROR attempt to bound type parameter with a nonexistent trait `NoSuchTrait` +} + +fn main() {} + diff --git a/src/test/compile-fail/feature-gate-advanced-slice-features.rs b/src/test/compile-fail/feature-gate-advanced-slice-features.rs index 97d593d310e..a37a8a326a6 100644 --- a/src/test/compile-fail/feature-gate-advanced-slice-features.rs +++ b/src/test/compile-fail/feature-gate-advanced-slice-features.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = [ 1i, 2, 3, 4, 5 ]; + let x = [ 1is, 2, 3, 4, 5 ]; match x { [ xs.., 4, 5 ] => {} //~ ERROR multiple-element slice matches [ 1, xs.., 5 ] => {} //~ ERROR multiple-element slice matches diff --git a/src/test/compile-fail/feature-gate-box-expr.rs b/src/test/compile-fail/feature-gate-box-expr.rs new file mode 100644 index 00000000000..bc7a70471cd --- /dev/null +++ b/src/test/compile-fail/feature-gate-box-expr.rs @@ -0,0 +1,23 @@ +// 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. + +fn main() { + use std::boxed::HEAP; + + let x = box 'c'; //~ ERROR box expression syntax is experimental in alpha release + println!("x: {}", x); + + let x = box () 'c'; //~ ERROR box expression syntax is experimental in alpha release + println!("x: {}", x); + + let x = box (HEAP) 'c'; //~ ERROR box expression syntax is experimental in alpha release + println!("x: {}", x); +} + diff --git a/src/test/compile-fail/syntax-extension-bytes-too-large-u8-literal.rs b/src/test/compile-fail/feature-gate-box-pat.rs index 1a9aa3753ee..b36bc22b9dc 100644 --- a/src/test/compile-fail/syntax-extension-bytes-too-large-u8-literal.rs +++ b/src/test/compile-fail/feature-gate-box-pat.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// 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. // @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - let vec = bytes!(1024u8); //~ ERROR too large u8 literal in bytes! - //~^ WARN `bytes!` is deprecated + let box x = Box::new('c'); //~ ERROR box pattern syntax is experimental in alpha release + println!("x: {}", x); } diff --git a/src/test/compile-fail/syntax-extension-bytes-too-small-integer-literal.rs b/src/test/compile-fail/feature-gate-feature-gate.rs index c2d49735943..b903b29658b 100644 --- a/src/test/compile-fail/syntax-extension-bytes-too-small-integer-literal.rs +++ b/src/test/compile-fail/feature-gate-feature-gate.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main() { - let vec = bytes!(-1024); //~ ERROR non-literal in bytes - //~^ WARN `bytes!` is deprecated -} +#![forbid(unstable_features)] +#![feature(intrinsics)] //~ ERROR unstable feature + +fn main() { } diff --git a/src/test/compile-fail/feature-gate-int-uint.rs b/src/test/compile-fail/feature-gate-int-uint.rs new file mode 100644 index 00000000000..016a0394289 --- /dev/null +++ b/src/test/compile-fail/feature-gate-int-uint.rs @@ -0,0 +1,35 @@ +// 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. + +#![allow(dead_code)] + +mod u { + type X = uint; //~ WARN the `uint` type is deprecated + struct Foo { + x: uint //~ WARN the `uint` type is deprecated + } + fn bar(x: uint) { //~ WARN the `uint` type is deprecated + 1u; //~ WARN the `u` suffix on integers is deprecated + } +} +mod i { + type X = int; //~ WARN the `int` type is deprecated + struct Foo { + x: int //~ WARN the `int` type is deprecated + } + fn bar(x: int) { //~ WARN the `int` type is deprecated + 1i; //~ WARN the `i` suffix on integers is deprecated + } +} + +fn main() { + // make compilation fail, after feature gating + let () = 1u8; //~ ERROR +} diff --git a/src/test/compile-fail/feature-gated-feature-in-macro-arg.rs b/src/test/compile-fail/feature-gated-feature-in-macro-arg.rs index cd49c7c016e..1e15e67876e 100644 --- a/src/test/compile-fail/feature-gated-feature-in-macro-arg.rs +++ b/src/test/compile-fail/feature-gated-feature-in-macro-arg.rs @@ -8,6 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// FIXME #20661: format_args! emits calls to the unstable std::fmt::rt +// module, so the compiler has some hacks to make that possible +// (in span_is_internal). Unnfortunately those hacks defeat this +// particular scenario of checking feature gates in arguments to +// println!(). + +// ignore-test + // tests that input to a macro is checked for use of gated features. If this // test succeeds due to the acceptance of a feature, pick a new feature to // test. Not ideal, but oh well :( diff --git a/src/test/compile-fail/fn-bad-block-type.rs b/src/test/compile-fail/fn-bad-block-type.rs index ba568ef5f84..c5c355cfbce 100644 --- a/src/test/compile-fail/fn-bad-block-type.rs +++ b/src/test/compile-fail/fn-bad-block-type.rs @@ -10,6 +10,6 @@ // error-pattern:mismatched types -fn f() -> int { true } +fn f() -> isize { true } fn main() { } diff --git a/src/test/compile-fail/fn-item-type.rs b/src/test/compile-fail/fn-item-type.rs index dd4a24bfb2f..b2394a29899 100644 --- a/src/test/compile-fail/fn-item-type.rs +++ b/src/test/compile-fail/fn-item-type.rs @@ -11,8 +11,8 @@ // Test that the types of distinct fn items are not compatible by // default. See also `run-pass/fn-item-type-*.rs`. -fn foo(x: int) -> int { x * 2 } -fn bar(x: int) -> int { x * 4 } +fn foo(x: isize) -> isize { x * 2 } +fn bar(x: isize) -> isize { x * 4 } fn eq<T>(x: T, y: T) { } diff --git a/src/test/compile-fail/fn-trait-formatting.rs b/src/test/compile-fail/fn-trait-formatting.rs index 06e8412ddaa..3f5a92605b7 100644 --- a/src/test/compile-fail/fn-trait-formatting.rs +++ b/src/test/compile-fail/fn-trait-formatting.rs @@ -9,6 +9,7 @@ // except according to those terms. #![feature(unboxed_closures)] +#![feature(box_syntax)] fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {} @@ -20,5 +21,5 @@ fn main() { let _: () = (box |&mut:| -> isize unimplemented!()) as Box<FnMut() -> isize>; //~^ ERROR Box<core::ops::FnMut() -> isize> - needs_fn(1i); //~ ERROR `core::ops::Fn(isize) -> isize` + needs_fn(1is); //~ ERROR `core::ops::Fn(isize) -> isize` } diff --git a/src/test/compile-fail/fn-variance-1.rs b/src/test/compile-fail/fn-variance-1.rs index 039628b6752..838e65e1d05 100644 --- a/src/test/compile-fail/fn-variance-1.rs +++ b/src/test/compile-fail/fn-variance-1.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn takes_imm(x: &int) { } +fn takes_imm(x: &isize) { } -fn takes_mut(x: &mut int) { } +fn takes_mut(x: &mut isize) { } fn apply<T, F>(t: T, f: F) where F: FnOnce(T) { f(t) diff --git a/src/test/compile-fail/for-loop-bogosity.rs b/src/test/compile-fail/for-loop-bogosity.rs index 67d07ca4bd1..fd920f92394 100644 --- a/src/test/compile-fail/for-loop-bogosity.rs +++ b/src/test/compile-fail/for-loop-bogosity.rs @@ -9,12 +9,12 @@ // except according to those terms. struct MyStruct { - x: int, - y: int, + x: isize, + y: isize, } impl MyStruct { - fn next(&mut self) -> Option<int> { + fn next(&mut self) -> Option<isize> { Some(self.x) } } diff --git a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs index 8de613ac03d..c381fcf3efb 100644 --- a/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs +++ b/src/test/compile-fail/for-loop-refutable-pattern-error-message.rs @@ -11,6 +11,6 @@ fn main() { for - &1i //~ ERROR refutable pattern in `for` loop binding - in [1i].iter() {} + &1is //~ ERROR refutable pattern in `for` loop binding + in [1is].iter() {} } diff --git a/src/test/compile-fail/forget-init-unsafe.rs b/src/test/compile-fail/forget-init-unsafe.rs index 12df0c71cc5..46a18c98183 100644 --- a/src/test/compile-fail/forget-init-unsafe.rs +++ b/src/test/compile-fail/forget-init-unsafe.rs @@ -12,6 +12,6 @@ use std::intrinsics::{init, forget}; // Test that the `forget` and `init` intrinsics are really unsafe pub fn main() { - let stuff = init::<int>(); //~ ERROR call to unsafe function requires unsafe + let stuff = init::<isize>(); //~ ERROR call to unsafe function requires unsafe forget(stuff); //~ ERROR call to unsafe function requires unsafe } diff --git a/src/test/compile-fail/fully-qualified-type-name3.rs b/src/test/compile-fail/fully-qualified-type-name3.rs index 0a5a54b9a27..dc0c9a093ff 100644 --- a/src/test/compile-fail/fully-qualified-type-name3.rs +++ b/src/test/compile-fail/fully-qualified-type-name3.rs @@ -12,8 +12,8 @@ // ignore-test -type T1 = uint; -type T2 = int; +type T1 = usize; +type T2 = isize; fn bar(x: T1) -> T2 { return x; diff --git a/src/test/compile-fail/functional-struct-update-noncopyable.rs b/src/test/compile-fail/functional-struct-update-noncopyable.rs index da246f85c43..7ce32bbc975 100644 --- a/src/test/compile-fail/functional-struct-update-noncopyable.rs +++ b/src/test/compile-fail/functional-struct-update-noncopyable.rs @@ -12,7 +12,7 @@ use std::sync::Arc; -struct A { y: Arc<int>, x: Arc<int> } +struct A { y: Arc<isize>, x: Arc<isize> } impl Drop for A { fn drop(&mut self) { println!("x={}", *self.x); } diff --git a/src/test/compile-fail/gated-non-ascii-idents.rs b/src/test/compile-fail/gated-non-ascii-idents.rs index 4cbb61d9853..f4b9830d579 100644 --- a/src/test/compile-fail/gated-non-ascii-idents.rs +++ b/src/test/compile-fail/gated-non-ascii-idents.rs @@ -17,9 +17,9 @@ mod föö { //~ ERROR non-ascii idents } fn bär( //~ ERROR non-ascii idents - bäz: int //~ ERROR non-ascii idents + bäz: isize //~ ERROR non-ascii idents ) { - let _ö: int; //~ ERROR non-ascii idents + let _ö: isize; //~ ERROR non-ascii idents match (1, 2) { (_ä, _) => {} //~ ERROR non-ascii idents @@ -27,12 +27,12 @@ fn bär( //~ ERROR non-ascii idents } struct Föö { //~ ERROR non-ascii idents - föö: int //~ ERROR non-ascii idents + föö: isize //~ ERROR non-ascii idents } enum Bär { //~ ERROR non-ascii idents Bäz { //~ ERROR non-ascii idents - qüx: int //~ ERROR non-ascii idents + qüx: isize //~ ERROR non-ascii idents } } diff --git a/src/test/compile-fail/generic-impl-less-params-with-defaults.rs b/src/test/compile-fail/generic-impl-less-params-with-defaults.rs index a8b1911426c..02f09749d61 100644 --- a/src/test/compile-fail/generic-impl-less-params-with-defaults.rs +++ b/src/test/compile-fail/generic-impl-less-params-with-defaults.rs @@ -15,6 +15,6 @@ impl<A, B, C = (A, B)> Foo<A, B, C> { } fn main() { - Foo::<int>::new(); + Foo::<isize>::new(); //~^ ERROR too few type parameters provided } diff --git a/src/test/compile-fail/generic-impl-more-params-with-defaults.rs b/src/test/compile-fail/generic-impl-more-params-with-defaults.rs index 696235333a1..d88da2625c1 100644 --- a/src/test/compile-fail/generic-impl-more-params-with-defaults.rs +++ b/src/test/compile-fail/generic-impl-more-params-with-defaults.rs @@ -17,6 +17,6 @@ impl<T, A = Heap> Vec<T, A> { } fn main() { - Vec::<int, Heap, bool>::new(); + Vec::<isize, Heap, bool>::new(); //~^ ERROR too many type parameters provided } diff --git a/src/test/compile-fail/generic-type-more-params-with-defaults.rs b/src/test/compile-fail/generic-type-more-params-with-defaults.rs index ee3e1818779..19d303488ac 100644 --- a/src/test/compile-fail/generic-type-more-params-with-defaults.rs +++ b/src/test/compile-fail/generic-type-more-params-with-defaults.rs @@ -13,6 +13,6 @@ struct Heap; struct Vec<T, A = Heap>; fn main() { - let _: Vec<int, Heap, bool>; + let _: Vec<isize, Heap, bool>; //~^ ERROR wrong number of type arguments: expected at most 2, found 3 } diff --git a/src/test/compile-fail/glob-resolve1.rs b/src/test/compile-fail/glob-resolve1.rs index d8258a72ce3..fce8a07d727 100644 --- a/src/test/compile-fail/glob-resolve1.rs +++ b/src/test/compile-fail/glob-resolve1.rs @@ -23,7 +23,7 @@ mod bar { struct C; - type D = int; + type D = isize; } fn foo<T>() {} diff --git a/src/test/compile-fail/hashmap-iter-value-lifetime.rs b/src/test/compile-fail/hashmap-iter-value-lifetime.rs index d9d7705fef6..db1e1e8efe4 100644 --- a/src/test/compile-fail/hashmap-iter-value-lifetime.rs +++ b/src/test/compile-fail/hashmap-iter-value-lifetime.rs @@ -10,7 +10,7 @@ fn main() { let mut my_stuff = std::collections::HashMap::new(); - my_stuff.insert(0i, 42i); + my_stuff.insert(0is, 42is); let (_, thing) = my_stuff.iter().next().unwrap(); diff --git a/src/test/compile-fail/hashmap-lifetimes.rs b/src/test/compile-fail/hashmap-lifetimes.rs index edd57477d76..40673dd92b8 100644 --- a/src/test/compile-fail/hashmap-lifetimes.rs +++ b/src/test/compile-fail/hashmap-lifetimes.rs @@ -10,7 +10,7 @@ fn main() { let mut my_stuff = std::collections::HashMap::new(); - my_stuff.insert(0i, 42i); + my_stuff.insert(0is, 42is); let mut it = my_stuff.iter(); my_stuff.insert(1, 43); //~ ERROR cannot borrow diff --git a/src/test/compile-fail/hrtb-conflate-regions.rs b/src/test/compile-fail/hrtb-conflate-regions.rs index 5eb8fd69312..3efe0501267 100644 --- a/src/test/compile-fail/hrtb-conflate-regions.rs +++ b/src/test/compile-fail/hrtb-conflate-regions.rs @@ -16,12 +16,12 @@ trait Foo<X> { } fn want_foo2<T>() - where T : for<'a,'b> Foo<(&'a int, &'b int)> + where T : for<'a,'b> Foo<(&'a isize, &'b isize)> { } fn want_foo1<T>() - where T : for<'z> Foo<(&'z int, &'z int)> + where T : for<'z> Foo<(&'z isize, &'z isize)> { } @@ -30,7 +30,7 @@ fn want_foo1<T>() struct SomeStruct; -impl<'a> Foo<(&'a int, &'a int)> for SomeStruct +impl<'a> Foo<(&'a isize, &'a isize)> for SomeStruct { } diff --git a/src/test/compile-fail/hrtb-debruijn-in-receiver.rs b/src/test/compile-fail/hrtb-debruijn-in-receiver.rs index 2dbd16107b0..2365f494075 100644 --- a/src/test/compile-fail/hrtb-debruijn-in-receiver.rs +++ b/src/test/compile-fail/hrtb-debruijn-in-receiver.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; struct Foo<'a> { - map: HashMap<uint, &'a str> + map: HashMap<usize, &'a str> } impl<'a> Foo<'a> { diff --git a/src/test/compile-fail/hrtb-higher-ranker-supertraits-transitive.rs b/src/test/compile-fail/hrtb-higher-ranker-supertraits-transitive.rs index 4199deee7b8..249256f8e01 100644 --- a/src/test/compile-fail/hrtb-higher-ranker-supertraits-transitive.rs +++ b/src/test/compile-fail/hrtb-higher-ranker-supertraits-transitive.rs @@ -12,13 +12,13 @@ trait Foo<'tcx> { - fn foo(&'tcx self) -> &'tcx int; + fn foo(&'tcx self) -> &'tcx isize; } trait Bar<'ccx> : for<'tcx> Foo<'tcx> { - fn bar(&'ccx self) -> &'ccx int; + fn bar(&'ccx self) -> &'ccx isize; } trait Baz diff --git a/src/test/compile-fail/hrtb-higher-ranker-supertraits.rs b/src/test/compile-fail/hrtb-higher-ranker-supertraits.rs index 108ca1b82e0..441ad76b602 100644 --- a/src/test/compile-fail/hrtb-higher-ranker-supertraits.rs +++ b/src/test/compile-fail/hrtb-higher-ranker-supertraits.rs @@ -12,13 +12,13 @@ trait Foo<'tcx> { - fn foo(&'tcx self) -> &'tcx int; + fn foo(&'tcx self) -> &'tcx isize; } trait Bar<'ccx> : for<'tcx> Foo<'tcx> { - fn bar(&'ccx self) -> &'ccx int; + fn bar(&'ccx self) -> &'ccx isize; } fn want_foo_for_some_tcx<'x,F>(f: &'x F) diff --git a/src/test/compile-fail/hrtb-identity-fn-borrows.rs b/src/test/compile-fail/hrtb-identity-fn-borrows.rs index 733a5b2a85a..17939cf9fe0 100644 --- a/src/test/compile-fail/hrtb-identity-fn-borrows.rs +++ b/src/test/compile-fail/hrtb-identity-fn-borrows.rs @@ -16,7 +16,7 @@ trait FnLike<A,R> { } fn call_repeatedly<F>(f: F) - where F : for<'a> FnLike<&'a int, &'a int> + where F : for<'a> FnLike<&'a isize, &'a isize> { // Result is stored: cannot re-assign `x` let mut x = 3; diff --git a/src/test/compile-fail/huge-array-simple.rs b/src/test/compile-fail/huge-array-simple.rs index a9dda771b7f..1e04e685e41 100644 --- a/src/test/compile-fail/huge-array-simple.rs +++ b/src/test/compile-fail/huge-array-simple.rs @@ -11,5 +11,5 @@ // error-pattern: too big for the current fn main() { - let fat : [u8; (1<<61)+(1<<31)] = [0; (1u64<<61) as uint +(1u64<<31) as uint]; + let fat : [u8; (1<<61)+(1<<31)] = [0; (1u64<<61) as usize +(1u64<<31) as usize]; } diff --git a/src/test/compile-fail/huge-enum.rs b/src/test/compile-fail/huge-enum.rs index 7c7a75abf3f..aef1fa85e0d 100644 --- a/src/test/compile-fail/huge-enum.rs +++ b/src/test/compile-fail/huge-enum.rs @@ -12,12 +12,12 @@ // FIXME: work properly with higher limits -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] fn main() { let big: Option<[u32; (1<<29)-1]> = None; } -#[cfg(target_word_size = "64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] fn main() { let big: Option<[u32; (1<<45)-1]> = None; } diff --git a/src/test/compile-fail/if-let.rs b/src/test/compile-fail/if-let.rs index 971f643c0fe..d83779c4f0f 100644 --- a/src/test/compile-fail/if-let.rs +++ b/src/test/compile-fail/if-let.rs @@ -20,20 +20,20 @@ fn macros() { }} } - foo!(a, 1i, { //~ ERROR irrefutable if-let + foo!(a, 1is, { //~ ERROR irrefutable if-let println!("irrefutable pattern"); }); - bar!(a, 1i, { //~ ERROR irrefutable if-let + bar!(a, 1is, { //~ ERROR irrefutable if-let println!("irrefutable pattern"); }); } pub fn main() { - if let a = 1i { //~ ERROR irrefutable if-let + if let a = 1is { //~ ERROR irrefutable if-let println!("irrefutable pattern"); } - if let a = 1i { //~ ERROR irrefutable if-let + if let a = 1is { //~ ERROR irrefutable if-let println!("irrefutable pattern"); } else if true { println!("else-if in irrefutable if-let"); @@ -41,15 +41,15 @@ pub fn main() { println!("else in irrefutable if-let"); } - if let 1i = 2i { + if let 1is = 2is { println!("refutable pattern"); - } else if let a = 1i { //~ ERROR irrefutable if-let + } else if let a = 1is { //~ ERROR irrefutable if-let println!("irrefutable pattern"); } if true { println!("if"); - } else if let a = 1i { //~ ERROR irrefutable if-let + } else if let a = 1is { //~ ERROR irrefutable if-let println!("irrefutable pattern"); } } diff --git a/src/test/compile-fail/immut-function-arguments.rs b/src/test/compile-fail/immut-function-arguments.rs index 827e648cca8..99927d8b9bf 100644 --- a/src/test/compile-fail/immut-function-arguments.rs +++ b/src/test/compile-fail/immut-function-arguments.rs @@ -9,12 +9,12 @@ // except according to those terms. -fn f(y: Box<int>) { +fn f(y: Box<isize>) { *y = 5; //~ ERROR cannot assign } fn g() { - let _frob = |&: q: Box<int>| { *q = 2; }; //~ ERROR cannot assign + let _frob = |&: q: Box<isize>| { *q = 2; }; //~ ERROR cannot assign } diff --git a/src/test/compile-fail/impl-bounds-checking.rs b/src/test/compile-fail/impl-bounds-checking.rs index 69a35bcbd7b..8c8f67e40ab 100644 --- a/src/test/compile-fail/impl-bounds-checking.rs +++ b/src/test/compile-fail/impl-bounds-checking.rs @@ -17,8 +17,8 @@ trait Getter<T: Clone2> { fn get(&self) -> T; } -impl Getter<int> for int { //~ ERROR the trait `Clone2` is not implemented - fn get(&self) -> int { *self } +impl Getter<isize> for isize { //~ ERROR the trait `Clone2` is not implemented + fn get(&self) -> isize { *self } } fn main() { } diff --git a/src/test/compile-fail/impl-not-adjacent-to-type.rs b/src/test/compile-fail/impl-not-adjacent-to-type.rs index 7a5428d63e8..7a7673d871d 100644 --- a/src/test/compile-fail/impl-not-adjacent-to-type.rs +++ b/src/test/compile-fail/impl-not-adjacent-to-type.rs @@ -10,8 +10,8 @@ mod foo { pub struct Foo { - x: int, - y: int, + x: isize, + y: isize, } } diff --git a/src/test/compile-fail/impl-unused-tps.rs b/src/test/compile-fail/impl-unused-tps.rs index 99c6c6b8985..c9399afbb93 100644 --- a/src/test/compile-fail/impl-unused-tps.rs +++ b/src/test/compile-fail/impl-unused-tps.rs @@ -16,19 +16,19 @@ trait Bar { type Out; } -impl<T> Foo<T> for [int;0] { +impl<T> Foo<T> for [isize;0] { // OK, T is used in `Foo<T>`. } -impl<T,U> Foo<T> for [int;1] { +impl<T,U> Foo<T> for [isize;1] { //~^ ERROR the type parameter `U` is not constrained } -impl<T,U> Foo<T> for [int;2] where T : Bar<Out=U> { +impl<T,U> Foo<T> for [isize;2] where T : Bar<Out=U> { // OK, `U` is now constrained by the output type parameter. } -impl<T:Bar<Out=U>,U> Foo<T> for [int;3] { +impl<T:Bar<Out=U>,U> Foo<T> for [isize;3] { // OK, same as above but written differently. } diff --git a/src/test/compile-fail/implicit-method-bind.rs b/src/test/compile-fail/implicit-method-bind.rs index 34367f06793..d329f72f788 100644 --- a/src/test/compile-fail/implicit-method-bind.rs +++ b/src/test/compile-fail/implicit-method-bind.rs @@ -11,5 +11,5 @@ use std::num::SignedInt; fn main() { - let _f = 10i.abs; //~ ERROR attempted to take value of method + let _f = 10is.abs; //~ ERROR attempted to take value of method } diff --git a/src/test/compile-fail/import-glob-circular.rs b/src/test/compile-fail/import-glob-circular.rs index fda7b190d72..0f6e3dc134d 100644 --- a/src/test/compile-fail/import-glob-circular.rs +++ b/src/test/compile-fail/import-glob-circular.rs @@ -13,13 +13,13 @@ mod circ1 { pub use circ2::f2; pub fn f1() { println!("f1"); } - pub fn common() -> uint { return 0u; } + pub fn common() -> usize { return 0us; } } mod circ2 { pub use circ1::f1; pub fn f2() { println!("f2"); } - pub fn common() -> uint { return 1u; } + pub fn common() -> usize { return 1us; } } mod test { diff --git a/src/test/compile-fail/import-shadow-1.rs b/src/test/compile-fail/import-shadow-1.rs index eac5a98140f..503fa4eca52 100644 --- a/src/test/compile-fail/import-shadow-1.rs +++ b/src/test/compile-fail/import-shadow-1.rs @@ -16,11 +16,11 @@ use foo::*; use bar::*; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-2.rs b/src/test/compile-fail/import-shadow-2.rs index 8b0809fd55a..0c107cf27f5 100644 --- a/src/test/compile-fail/import-shadow-2.rs +++ b/src/test/compile-fail/import-shadow-2.rs @@ -16,11 +16,11 @@ use foo::*; use foo::*; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-3.rs b/src/test/compile-fail/import-shadow-3.rs index cef481af6ba..bf90973c285 100644 --- a/src/test/compile-fail/import-shadow-3.rs +++ b/src/test/compile-fail/import-shadow-3.rs @@ -16,11 +16,11 @@ use foo::Baz; use bar::*; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-4.rs b/src/test/compile-fail/import-shadow-4.rs index 919eea0e046..f21fdaae47b 100644 --- a/src/test/compile-fail/import-shadow-4.rs +++ b/src/test/compile-fail/import-shadow-4.rs @@ -16,11 +16,11 @@ use foo::*; use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-5.rs b/src/test/compile-fail/import-shadow-5.rs index df17b7f0a20..dc300bc7baa 100644 --- a/src/test/compile-fail/import-shadow-5.rs +++ b/src/test/compile-fail/import-shadow-5.rs @@ -16,11 +16,11 @@ use foo::Baz; use bar::Baz; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-6.rs b/src/test/compile-fail/import-shadow-6.rs index 94269043b02..fa3b75c70f0 100644 --- a/src/test/compile-fail/import-shadow-6.rs +++ b/src/test/compile-fail/import-shadow-6.rs @@ -16,11 +16,11 @@ use qux::*; use foo::*; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/import-shadow-7.rs b/src/test/compile-fail/import-shadow-7.rs index b3bac380710..34aba15b392 100644 --- a/src/test/compile-fail/import-shadow-7.rs +++ b/src/test/compile-fail/import-shadow-7.rs @@ -16,11 +16,11 @@ use foo::*; use qux::*; //~ERROR a type named `Baz` has already been imported in this module mod foo { - pub type Baz = int; + pub type Baz = isize; } mod bar { - pub type Baz = int; + pub type Baz = isize; } mod qux { diff --git a/src/test/compile-fail/index-bot.rs b/src/test/compile-fail/index-bot.rs index bd01d45fd44..876c1e481f6 100644 --- a/src/test/compile-fail/index-bot.rs +++ b/src/test/compile-fail/index-bot.rs @@ -9,5 +9,5 @@ // except according to those terms. fn main() { - (return)[0u]; //~ ERROR the type of this value must be known in this context + (return)[0us]; //~ ERROR the type of this value must be known in this context } diff --git a/src/test/compile-fail/indexing-requires-a-uint.rs b/src/test/compile-fail/indexing-requires-a-uint.rs index e5edb2358f8..901d8783d02 100644 --- a/src/test/compile-fail/indexing-requires-a-uint.rs +++ b/src/test/compile-fail/indexing-requires-a-uint.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Make sure that indexing an array is only valid with a `uint`, not any other +// Make sure that indexing an array is only valid with a `usize`, not any other // integral type. fn main() { @@ -16,11 +16,11 @@ fn main() { [0][0u8]; //~ ERROR: the trait `core::ops::Index<u8>` is not implemented //~^ ERROR: the trait `core::ops::Index<u8>` is not implemented - [0][0]; // should infer to be a uint + [0][0]; // should infer to be a usize let i = 0; // i is an IntVar - [0][i]; // i should be locked to uint - bar::<int>(i); // i should not be re-coerced back to an int + [0][i]; // i should be locked to usize + bar::<isize>(i); // i should not be re-coerced back to an isize //~^ ERROR: mismatched types } diff --git a/src/test/compile-fail/infinite-autoderef.rs b/src/test/compile-fail/infinite-autoderef.rs index f0b9e796ae6..3635c4dbb02 100644 --- a/src/test/compile-fail/infinite-autoderef.rs +++ b/src/test/compile-fail/infinite-autoderef.rs @@ -10,6 +10,8 @@ // error-pattern: reached the recursion limit while auto-dereferencing +#![feature(box_syntax)] + use std::ops::Deref; struct Foo; diff --git a/src/test/compile-fail/infinite-instantiation.rs b/src/test/compile-fail/infinite-instantiation.rs index b8fa6285d99..a922f5fe452 100644 --- a/src/test/compile-fail/infinite-instantiation.rs +++ b/src/test/compile-fail/infinite-instantiation.rs @@ -15,8 +15,8 @@ trait to_opt { fn to_option(&self) -> Option<Self>; } -impl to_opt for uint { - fn to_option(&self) -> Option<uint> { +impl to_opt for usize { + fn to_option(&self) -> Option<usize> { Some(*self) } } @@ -27,12 +27,12 @@ impl<T:Clone> to_opt for Option<T> { } } -fn function<T:to_opt + Clone>(counter: uint, t: T) { - if counter > 0u { - function(counter - 1u, t.to_option()); +fn function<T:to_opt + Clone>(counter: usize, t: T) { + if counter > 0us { + function(counter - 1us, t.to_option()); } } fn main() { - function(22u, 22u); + function(22us, 22us); } diff --git a/src/test/compile-fail/infinite-tag-type-recursion.rs b/src/test/compile-fail/infinite-tag-type-recursion.rs index f8d89a8269d..a57c015d684 100644 --- a/src/test/compile-fail/infinite-tag-type-recursion.rs +++ b/src/test/compile-fail/infinite-tag-type-recursion.rs @@ -11,6 +11,6 @@ // error-pattern: illegal recursive enum type; wrap the inner value in a box -enum mlist { cons(int, mlist), nil, } +enum mlist { cons(isize, mlist), nil, } fn main() { let a = mlist::cons(10, mlist::cons(11, mlist::nil)); } diff --git a/src/test/compile-fail/int-literal-too-large-span.rs b/src/test/compile-fail/int-literal-too-large-span.rs index 8a496c934b9..2aeaf6efaa4 100644 --- a/src/test/compile-fail/int-literal-too-large-span.rs +++ b/src/test/compile-fail/int-literal-too-large-span.rs @@ -11,7 +11,7 @@ // issue #17123 fn main() { - 100000000000000000000000000000000 //~ ERROR int literal is too large + 100000000000000000000000000000000is //~ ERROR int literal is too large ; // the span shouldn't point to this. } diff --git a/src/test/compile-fail/integral-indexing.rs b/src/test/compile-fail/integral-indexing.rs index bbceb00abd3..ef651dd9ce7 100644 --- a/src/test/compile-fail/integral-indexing.rs +++ b/src/test/compile-fail/integral-indexing.rs @@ -9,9 +9,9 @@ // except according to those terms. pub fn main() { - let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5); + let v: Vec<isize> = vec!(0, 1, 2, 3, 4, 5); let s: String = "abcdef".to_string(); - v.as_slice()[3u]; + v.as_slice()[3us]; v.as_slice()[3]; v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented //~^ ERROR the trait `core::ops::Index<u8>` is not implemented @@ -21,7 +21,7 @@ pub fn main() { //~^ ERROR the trait `core::ops::Index<u32>` is not implemented v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented //~^ ERROR the trait `core::ops::Index<i32>` is not implemented - s.as_bytes()[3u]; + s.as_bytes()[3us]; s.as_bytes()[3]; s.as_bytes()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented //~^ERROR the trait `core::ops::Index<u8>` is not implemented diff --git a/src/test/compile-fail/intrinsic-return-address.rs b/src/test/compile-fail/intrinsic-return-address.rs index 9c1db4057c6..a80d3931555 100644 --- a/src/test/compile-fail/intrinsic-return-address.rs +++ b/src/test/compile-fail/intrinsic-return-address.rs @@ -20,7 +20,7 @@ unsafe fn f() { //~^ ERROR invalid use of `return_address` intrinsic: function does not use out pointer } -unsafe fn g() -> int { +unsafe fn g() -> isize { let _ = return_address(); //~^ ERROR invalid use of `return_address` intrinsic: function does not use out pointer 0 diff --git a/src/test/compile-fail/issue-10200.rs b/src/test/compile-fail/issue-10200.rs index 2b9ac705f32..03d4e9b81eb 100644 --- a/src/test/compile-fail/issue-10200.rs +++ b/src/test/compile-fail/issue-10200.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo(bool); -fn foo(_: uint) -> Foo { Foo(false) } +fn foo(_: usize) -> Foo { Foo(false) } fn main() { match Foo(true) { diff --git a/src/test/compile-fail/issue-10291.rs b/src/test/compile-fail/issue-10291.rs index dec4fc3b8f5..45f6e55914a 100644 --- a/src/test/compile-fail/issue-10291.rs +++ b/src/test/compile-fail/issue-10291.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn test<'x>(x: &'x int) { - drop::<Box<for<'z> FnMut(&'z int) -> &'z int>>(box |z| { +#![feature(box_syntax)] + +fn test<'x>(x: &'x isize) { + drop::<Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| { x //~^ ERROR cannot infer an appropriate lifetime }); diff --git a/src/test/compile-fail/issue-10392-2.rs b/src/test/compile-fail/issue-10392-2.rs index 2cbb59cc15a..b077081c5b0 100644 --- a/src/test/compile-fail/issue-10392-2.rs +++ b/src/test/compile-fail/issue-10392-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { foo: int } +struct A { foo: isize } fn a() -> A { panic!() } diff --git a/src/test/compile-fail/issue-10392.rs b/src/test/compile-fail/issue-10392.rs index 4d0e02c6310..3f8d26bfec0 100644 --- a/src/test/compile-fail/issue-10392.rs +++ b/src/test/compile-fail/issue-10392.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { foo: int } +struct A { foo: isize } fn a() -> A { panic!() } diff --git a/src/test/compile-fail/issue-10398.rs b/src/test/compile-fail/issue-10398.rs index c90f064bf90..c1102bc84ab 100644 --- a/src/test/compile-fail/issue-10398.rs +++ b/src/test/compile-fail/issue-10398.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let x = box 1i; + let x = box 1is; let f = move|:| { let _a = x; drop(x); diff --git a/src/test/compile-fail/issue-10636-1.rs b/src/test/compile-fail/issue-10636-1.rs index 710c5a306f3..bb020d55bdb 100644 --- a/src/test/compile-fail/issue-10636-1.rs +++ b/src/test/compile-fail/issue-10636-1.rs @@ -9,5 +9,5 @@ // except according to those terms. struct Obj { //~ NOTE: unclosed delimiter - member: uint + member: usize ) //~ ERROR: incorrect close delimiter diff --git a/src/test/compile-fail/issue-10636-2.rs b/src/test/compile-fail/issue-10636-2.rs index 2303f858fcc..a92ef248924 100644 --- a/src/test/compile-fail/issue-10636-2.rs +++ b/src/test/compile-fail/issue-10636-2.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn trace_option(option: Option<int>) { +pub fn trace_option(option: Option<isize>) { option.map(|some| 42; //~ NOTE: unclosed delimiter } //~ ERROR: incorrect close delimiter diff --git a/src/test/compile-fail/issue-10877.rs b/src/test/compile-fail/issue-10877.rs index 2a9cadf1f33..39f25b837cd 100644 --- a/src/test/compile-fail/issue-10877.rs +++ b/src/test/compile-fail/issue-10877.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo { x: int } +struct Foo { x: isize } extern { fn foo(1: ()); //~^ ERROR: patterns aren't allowed in foreign function declarations - fn bar((): int); + fn bar((): isize); //~^ ERROR: patterns aren't allowed in foreign function declarations - fn baz(Foo { x }: int); + fn baz(Foo { x }: isize); //~^ ERROR: patterns aren't allowed in foreign function declarations fn qux((x,y): ()); //~^ ERROR: patterns aren't allowed in foreign function declarations - fn this_is_actually_ok(a: uint); - fn and_so_is_this(_: uint); + fn this_is_actually_ok(a: usize); + fn and_so_is_this(_: usize); } fn main() {} diff --git a/src/test/compile-fail/issue-11192.rs b/src/test/compile-fail/issue-11192.rs index f496c1e1227..0d7a846bff6 100644 --- a/src/test/compile-fail/issue-11192.rs +++ b/src/test/compile-fail/issue-11192.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct Foo { - x: int + x: isize } impl Drop for Foo { diff --git a/src/test/compile-fail/issue-11493.rs b/src/test/compile-fail/issue-11493.rs index 7856a5dcf7f..895eb4cf96f 100644 --- a/src/test/compile-fail/issue-11493.rs +++ b/src/test/compile-fail/issue-11493.rs @@ -11,6 +11,6 @@ // This file must never have a trailing newline fn main() { - let x = Some(3i); - let y = x.as_ref().unwrap_or(&5i); //~ ERROR: borrowed value does not live long enough + let x = Some(3is); + let y = x.as_ref().unwrap_or(&5is); //~ ERROR: borrowed value does not live long enough } diff --git a/src/test/compile-fail/issue-11515.rs b/src/test/compile-fail/issue-11515.rs index 46fcb2ec340..f0089b0ae5b 100644 --- a/src/test/compile-fail/issue-11515.rs +++ b/src/test/compile-fail/issue-11515.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct Test<'s> { func: Box<FnMut()+'static> } diff --git a/src/test/compile-fail/issue-11714.rs b/src/test/compile-fail/issue-11714.rs index ed00d4131db..eef035d3d94 100644 --- a/src/test/compile-fail/issue-11714.rs +++ b/src/test/compile-fail/issue-11714.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn blah() -> int { //~ ERROR not all control paths return a value - 1i +fn blah() -> isize { //~ ERROR not all control paths return a value + 1is ; //~ HELP consider removing this semicolon: } diff --git a/src/test/compile-fail/issue-11844.rs b/src/test/compile-fail/issue-11844.rs index 55c12b051b9..560cbe1b8a8 100644 --- a/src/test/compile-fail/issue-11844.rs +++ b/src/test/compile-fail/issue-11844.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { let a = Some(box 1); match a { diff --git a/src/test/compile-fail/issue-11873.rs b/src/test/compile-fail/issue-11873.rs index 89667937531..67578de8922 100644 --- a/src/test/compile-fail/issue-11873.rs +++ b/src/test/compile-fail/issue-11873.rs @@ -9,8 +9,8 @@ // except according to those terms. fn main() { - let mut v = vec!(1i); - let mut f = |&mut:| v.push(2i); + let mut v = vec!(1is); + let mut f = |&mut:| v.push(2is); let _w = v; //~ ERROR: cannot move out of `v` f(); diff --git a/src/test/compile-fail/issue-11925.rs b/src/test/compile-fail/issue-11925.rs index c561f0a696a..e5f3b7d62d3 100644 --- a/src/test/compile-fail/issue-11925.rs +++ b/src/test/compile-fail/issue-11925.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { let r = { - let x = box 42i; + let x = box 42is; let f = move|:| &x; //~ ERROR: `x` does not live long enough f() }; diff --git a/src/test/compile-fail/issue-12041.rs b/src/test/compile-fail/issue-12041.rs index 094f6d64edc..02c19204f79 100644 --- a/src/test/compile-fail/issue-12041.rs +++ b/src/test/compile-fail/issue-12041.rs @@ -17,7 +17,7 @@ fn main() { loop { let tx = tx; //~^ ERROR: use of moved value: `tx` - tx.send(1i); + tx.send(1is); } }); } diff --git a/src/test/compile-fail/issue-12116.rs b/src/test/compile-fail/issue-12116.rs index 47907ac2be9..6f75909fada 100644 --- a/src/test/compile-fail/issue-12116.rs +++ b/src/test/compile-fail/issue-12116.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + enum IntList { - Cons(int, Box<IntList>), + Cons(isize, Box<IntList>), Nil } diff --git a/src/test/compile-fail/issue-12127.rs b/src/test/compile-fail/issue-12127.rs index 5f2837d2875..c06082de3cd 100644 --- a/src/test/compile-fail/issue-12127.rs +++ b/src/test/compile-fail/issue-12127.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn do_it(x: &int) { } +#![feature(box_syntax)] + +fn do_it(x: &isize) { } fn main() { let x = box 22; diff --git a/src/test/compile-fail/issue-12369.rs b/src/test/compile-fail/issue-12369.rs index 4522b536ffd..0587bdf6136 100644 --- a/src/test/compile-fail/issue-12369.rs +++ b/src/test/compile-fail/issue-12369.rs @@ -10,7 +10,7 @@ fn main() { let sl = vec![1,2,3]; - let v: int = match sl.as_slice() { + let v: isize = match sl.as_slice() { [] => 0, [a,b,c] => 3, [a, rest..] => a, diff --git a/src/test/compile-fail/issue-12470.rs b/src/test/compile-fail/issue-12470.rs index 0202d538cf6..93785817e14 100644 --- a/src/test/compile-fail/issue-12470.rs +++ b/src/test/compile-fail/issue-12470.rs @@ -8,17 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + trait X { - fn get_i(&self) -> int; + fn get_i(&self) -> isize; } struct B { - i: int + i: isize } impl X for B { - fn get_i(&self) -> int { + fn get_i(&self) -> isize { self.i } } diff --git a/src/test/compile-fail/issue-12567.rs b/src/test/compile-fail/issue-12567.rs index 26866cbbc60..d186a83676a 100644 --- a/src/test/compile-fail/issue-12567.rs +++ b/src/test/compile-fail/issue-12567.rs @@ -12,11 +12,11 @@ fn match_vecs<'a, T>(l1: &'a [T], l2: &'a [T]) { match (l1, l2) { ([], []) => println!("both empty"), ([], [hd, tl..]) | ([hd, tl..], []) => println!("one empty"), - //~^ ERROR: cannot move out of dereference - //~^^ ERROR: cannot move out of dereference + //~^ ERROR: cannot move out of borrowed content + //~^^ ERROR: cannot move out of borrowed content ([hd1, tl1..], [hd2, tl2..]) => println!("both nonempty"), - //~^ ERROR: cannot move out of dereference - //~^^ ERROR: cannot move out of dereference + //~^ ERROR: cannot move out of borrowed content + //~^^ ERROR: cannot move out of borrowed content } } diff --git a/src/test/compile-fail/issue-12997-1.rs b/src/test/compile-fail/issue-12997-1.rs index 193cbcb25b7..2d8d7857c99 100644 --- a/src/test/compile-fail/issue-12997-1.rs +++ b/src/test/compile-fail/issue-12997-1.rs @@ -16,4 +16,4 @@ fn foo() { } //~ ERROR functions used as benches #[bench] -fn bar(x: int, y: int) { } //~ ERROR functions used as benches +fn bar(x: isize, y: isize) { } //~ ERROR functions used as benches diff --git a/src/test/compile-fail/issue-13058.rs b/src/test/compile-fail/issue-13058.rs index 8f507864052..eee82483cae 100644 --- a/src/test/compile-fail/issue-13058.rs +++ b/src/test/compile-fail/issue-13058.rs @@ -34,6 +34,6 @@ fn check<'r, I: Iterator<Item=usize>, T: Itble<'r, usize, I>>(cont: &T) -> bool } fn main() { - check((3u, 5u)); + check((3us, 5us)); //~^ ERROR mismatched types: expected `&_`, found `(usize, usize)` (expected &-ptr, found tuple) } diff --git a/src/test/compile-fail/issue-13359.rs b/src/test/compile-fail/issue-13359.rs index 25e64e070f4..2e338860377 100644 --- a/src/test/compile-fail/issue-13359.rs +++ b/src/test/compile-fail/issue-13359.rs @@ -13,9 +13,9 @@ fn foo(_s: i16) { } fn bar(_s: u32) { } fn main() { - foo(1*(1 as int)); + foo(1*(1 as isize)); //~^ ERROR: mismatched types: expected `i16`, found `isize` (expected i16, found isize) - bar(1*(1 as uint)); + bar(1*(1 as usize)); //~^ ERROR: mismatched types: expected `u32`, found `usize` (expected u32, found usize) } diff --git a/src/test/compile-fail/issue-1362.rs b/src/test/compile-fail/issue-1362.rs index bfbbc9d8aed..28d16f9c0b7 100644 --- a/src/test/compile-fail/issue-1362.rs +++ b/src/test/compile-fail/issue-1362.rs @@ -11,7 +11,7 @@ // Regression test for issue #1362 - without that fix the span will be bogus // no-reformat fn main() { - let x: uint = 20i; //~ ERROR mismatched types + let x: usize = 20is; //~ ERROR mismatched types } // NOTE: Do not add any extra lines as the line number the error is // on is significant; an error later in the source file might not diff --git a/src/test/compile-fail/issue-13853-4.rs b/src/test/compile-fail/issue-13853-4.rs index 7d653f5ab9e..b0db9e58dba 100644 --- a/src/test/compile-fail/issue-13853-4.rs +++ b/src/test/compile-fail/issue-13853-4.rs @@ -9,7 +9,7 @@ // except according to those terms. struct AutoBuilder<'a> { - context: &'a int + context: &'a isize } impl<'a> Drop for AutoBuilder<'a> { diff --git a/src/test/compile-fail/issue-14084.rs b/src/test/compile-fail/issue-14084.rs index d247bf0913c..92e0dd3ad0e 100644 --- a/src/test/compile-fail/issue-14084.rs +++ b/src/test/compile-fail/issue-14084.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { box ( () ) 0; //~^ ERROR: only the managed heap and exchange heap are currently supported diff --git a/src/test/compile-fail/issue-14182.rs b/src/test/compile-fail/issue-14182.rs index 5033576a234..364951a4fea 100644 --- a/src/test/compile-fail/issue-14182.rs +++ b/src/test/compile-fail/issue-14182.rs @@ -11,8 +11,8 @@ // ignore-test FIXME(japari) remove test struct Foo { - f: for <'b> |&'b int|: - 'b -> &'b int //~ ERROR use of undeclared lifetime name `'b` + f: for <'b> |&'b isize|: + 'b -> &'b isize //~ ERROR use of undeclared lifetime name `'b` } fn main() { diff --git a/src/test/compile-fail/issue-14254.rs b/src/test/compile-fail/issue-14254.rs index dc19b9d51c8..74eea0c57a0 100644 --- a/src/test/compile-fail/issue-14254.rs +++ b/src/test/compile-fail/issue-14254.rs @@ -15,7 +15,7 @@ trait Foo { } struct BarTy { - x : int, + x : isize, y : f64, } @@ -76,7 +76,7 @@ impl Foo for Box<BarTy> { } } -impl Foo for *const int { +impl Foo for *const isize { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? @@ -85,7 +85,7 @@ impl Foo for *const int { } } -impl<'a> Foo for &'a int { +impl<'a> Foo for &'a isize { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? @@ -94,7 +94,7 @@ impl<'a> Foo for &'a int { } } -impl<'a> Foo for &'a mut int { +impl<'a> Foo for &'a mut isize { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? @@ -103,7 +103,7 @@ impl<'a> Foo for &'a mut int { } } -impl Foo for Box<int> { +impl Foo for Box<isize> { fn bar(&self) { baz(); //~^ ERROR: unresolved name `baz`. Did you mean to call `self.baz`? diff --git a/src/test/compile-fail/issue-14303-fncall.rs b/src/test/compile-fail/issue-14303-fncall.rs index 3a5c8bbc546..0ec64ba6a3f 100644 --- a/src/test/compile-fail/issue-14303-fncall.rs +++ b/src/test/compile-fail/issue-14303-fncall.rs @@ -11,6 +11,6 @@ fn main() { range(0, 4) .map(|x| x * 2) - .collect::<Vec<'a, uint, 'b>>() + .collect::<Vec<'a, usize, 'b>>() //~^ ERROR lifetime parameters must be declared prior to type parameters } diff --git a/src/test/compile-fail/issue-14303-impl.rs b/src/test/compile-fail/issue-14303-impl.rs index 46d0219da81..c4a00581274 100644 --- a/src/test/compile-fail/issue-14303-impl.rs +++ b/src/test/compile-fail/issue-14303-impl.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct X { x: int } +struct X { x: isize } impl<'a, T, 'b> X {} //~^ ERROR lifetime parameters must be declared prior to type parameters diff --git a/src/test/compile-fail/issue-1448-2.rs b/src/test/compile-fail/issue-1448-2.rs index 234fa85c89a..371adf931b0 100644 --- a/src/test/compile-fail/issue-1448-2.rs +++ b/src/test/compile-fail/issue-1448-2.rs @@ -10,8 +10,8 @@ // Regression test for issue #1448 and #1386 -fn foo(a: uint) -> uint { a } +fn foo(a: usize) -> usize { a } fn main() { - println!("{}", foo(10i)); //~ ERROR mismatched types + println!("{}", foo(10is)); //~ ERROR mismatched types } diff --git a/src/test/compile-fail/issue-14915.rs b/src/test/compile-fail/issue-14915.rs index 142fecc31fe..18e4ccc3311 100644 --- a/src/test/compile-fail/issue-14915.rs +++ b/src/test/compile-fail/issue-14915.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { let x: Box<isize> = box 0; diff --git a/src/test/compile-fail/issue-15094.rs b/src/test/compile-fail/issue-15094.rs index 5292848f8ee..5b33069b595 100644 --- a/src/test/compile-fail/issue-15094.rs +++ b/src/test/compile-fail/issue-15094.rs @@ -28,6 +28,6 @@ fn make_shower<T>(x: T) -> Shower<T> { } pub fn main() { - let show3 = make_shower(3i); + let show3 = make_shower(3is); show3(); } diff --git a/src/test/compile-fail/issue-15129.rs b/src/test/compile-fail/issue-15129.rs index f56430f4228..7a7ba46de74 100644 --- a/src/test/compile-fail/issue-15129.rs +++ b/src/test/compile-fail/issue-15129.rs @@ -14,7 +14,7 @@ pub enum T { } pub enum V { - V1(int), + V1(isize), V2(bool) } diff --git a/src/test/compile-fail/issue-15167.rs b/src/test/compile-fail/issue-15167.rs index d4de4e177f0..630c35d6a4f 100644 --- a/src/test/compile-fail/issue-15167.rs +++ b/src/test/compile-fail/issue-15167.rs @@ -18,7 +18,7 @@ macro_rules! f { () => (n) } fn main() -> (){ - for n in range(0i, 1) { + for n in range(0is, 1) { println!("{}", f!()); //~ ERROR unresolved name `n` } } diff --git a/src/test/compile-fail/issue-15260.rs b/src/test/compile-fail/issue-15260.rs index e3d19729710..2228b6d3779 100644 --- a/src/test/compile-fail/issue-15260.rs +++ b/src/test/compile-fail/issue-15260.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - a: uint, + a: usize, } fn main() { diff --git a/src/test/compile-fail/issue-15480.rs b/src/test/compile-fail/issue-15480.rs index abcc2eb1f98..59d87b5277a 100644 --- a/src/test/compile-fail/issue-15480.rs +++ b/src/test/compile-fail/issue-15480.rs @@ -10,7 +10,7 @@ fn main() { let v = vec![ - &3i + &3is //~^ ERROR borrowed value does not live long enough ]; diff --git a/src/test/compile-fail/issue-15524.rs b/src/test/compile-fail/issue-15524.rs index 6d9657ab289..b378d2f885e 100644 --- a/src/test/compile-fail/issue-15524.rs +++ b/src/test/compile-fail/issue-15524.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -const N: int = 1; +const N: isize = 1; enum Foo { A = 1, diff --git a/src/test/compile-fail/issue-15756.rs b/src/test/compile-fail/issue-15756.rs index c2d30224dc8..02ccf9c0e08 100644 --- a/src/test/compile-fail/issue-15756.rs +++ b/src/test/compile-fail/issue-15756.rs @@ -14,7 +14,7 @@ use std::slice::ChunksMut; fn dft_iter<'a, T>(arg1: Chunks<'a,T>, arg2: ChunksMut<'a,T>) { for - &something + &mut something //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[T]` in arg2 { diff --git a/src/test/compile-fail/issue-15783.rs b/src/test/compile-fail/issue-15783.rs index f3e7a65db48..1b1b0302383 100644 --- a/src/test/compile-fail/issue-15783.rs +++ b/src/test/compile-fail/issue-15783.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub fn foo(params: Option<&[&str]>) -> uint { +pub fn foo(params: Option<&[&str]>) -> usize { params.unwrap().first().unwrap().len() } diff --git a/src/test/compile-fail/issue-15896.rs b/src/test/compile-fail/issue-15896.rs index 7b91063e2f9..c4373ba3351 100644 --- a/src/test/compile-fail/issue-15896.rs +++ b/src/test/compile-fail/issue-15896.rs @@ -12,7 +12,7 @@ fn main() { enum R { REB(()) } - struct Tau { t: uint } + struct Tau { t: usize } enum E { B(R, Tau) } let e = E::B(R::REB(()), Tau { t: 3 }); diff --git a/src/test/compile-fail/issue-16149.rs b/src/test/compile-fail/issue-16149.rs index aa586e58f70..a924cc9f9bb 100644 --- a/src/test/compile-fail/issue-16149.rs +++ b/src/test/compile-fail/issue-16149.rs @@ -9,7 +9,7 @@ // except according to those terms. extern { - static externalValue: int; + static externalValue: isize; } fn main() { diff --git a/src/test/compile-fail/issue-16465.rs b/src/test/compile-fail/issue-16465.rs index 280f19cfe9c..825b40cb322 100644 --- a/src/test/compile-fail/issue-16465.rs +++ b/src/test/compile-fail/issue-16465.rs @@ -14,7 +14,7 @@ struct Foo<T>{ x : T } -type FooInt = Foo<int>; +type FooInt = Foo<isize>; impl Drop for FooInt { //~^ ERROR cannot implement a destructor on a structure with type parameters diff --git a/src/test/compile-fail/issue-16538.rs b/src/test/compile-fail/issue-16538.rs index af686b86813..a6b73dcc19c 100644 --- a/src/test/compile-fail/issue-16538.rs +++ b/src/test/compile-fail/issue-16538.rs @@ -9,9 +9,9 @@ // except according to those terms. mod Y { - type X = uint; + type X = usize; extern { - static x: *const uint; + static x: *const usize; } fn foo(value: *const X) -> *const X { value diff --git a/src/test/compile-fail/issue-16562.rs b/src/test/compile-fail/issue-16562.rs index 626a442a2c3..a400263a243 100644 --- a/src/test/compile-fail/issue-16562.rs +++ b/src/test/compile-fail/issue-16562.rs @@ -15,11 +15,11 @@ struct Col<D, C> { col: C, } -trait Collection { fn len(&self) -> uint; } +trait Collection { fn len(&self) -> usize; } -impl<T, M: MatrixShape> Collection for Col<M, uint> { +impl<T, M: MatrixShape> Collection for Col<M, usize> { //~^ ERROR type parameter `T` is not constrained - fn len(&self) -> uint { + fn len(&self) -> usize { unimplemented!() } } diff --git a/src/test/compile-fail/issue-16747.rs b/src/test/compile-fail/issue-16747.rs index 22e3e9ed09e..814b885e3aa 100644 --- a/src/test/compile-fail/issue-16747.rs +++ b/src/test/compile-fail/issue-16747.rs @@ -12,7 +12,7 @@ trait ListItem<'a> { fn list_name() -> &'a str; } -trait Collection { fn len(&self) -> uint; } +trait Collection { fn len(&self) -> usize; } struct List<'a, T: ListItem<'a>> { //~^ ERROR the parameter type `T` may not live long enough @@ -22,7 +22,7 @@ struct List<'a, T: ListItem<'a>> { } impl<'a, T: ListItem<'a>> Collection for List<'a, T> { - fn len(&self) -> uint { + fn len(&self) -> usize { 0 } } diff --git a/src/test/compile-fail/issue-17252.rs b/src/test/compile-fail/issue-17252.rs index 4adb3f041a3..2e9ef8d6077 100644 --- a/src/test/compile-fail/issue-17252.rs +++ b/src/test/compile-fail/issue-17252.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static FOO: uint = FOO; //~ ERROR recursive constant +static FOO: usize = FOO; //~ ERROR recursive constant fn main() { let _x: [u8; FOO]; // caused stack overflow prior to fix - let _y: uint = 1 + { - static BAR: uint = BAR; //~ ERROR recursive constant + let _y: usize = 1 + { + static BAR: usize = BAR; //~ ERROR recursive constant let _z: [u8; BAR]; // caused stack overflow prior to fix 1 }; diff --git a/src/test/compile-fail/issue-17263.rs b/src/test/compile-fail/issue-17263.rs index b610a2b0c91..543063b3fc9 100644 --- a/src/test/compile-fail/issue-17263.rs +++ b/src/test/compile-fail/issue-17263.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo { a: int, b: int } +#![feature(box_syntax)] + +struct Foo { a: isize, b: isize } fn main() { let mut x = box Foo { a: 1, b: 2 }; diff --git a/src/test/compile-fail/issue-17283.rs b/src/test/compile-fail/issue-17283.rs index 122c1f08395..0c9fd9d9486 100644 --- a/src/test/compile-fail/issue-17283.rs +++ b/src/test/compile-fail/issue-17283.rs @@ -12,11 +12,11 @@ // within assignments in if expressions. struct Foo { - foo: uint + foo: usize } fn main() { - let x = 1u; + let x = 1us; let y: Foo; // `x { ... }` should not be interpreted as a struct literal here diff --git a/src/test/compile-fail/issue-17337.rs b/src/test/compile-fail/issue-17337.rs index e0f655084ff..24425e5eeec 100644 --- a/src/test/compile-fail/issue-17337.rs +++ b/src/test/compile-fail/issue-17337.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![staged_api] #![deny(deprecated)] struct Foo; diff --git a/src/test/compile-fail/issue-17383.rs b/src/test/compile-fail/issue-17383.rs index 24007364550..c71e0ecd494 100644 --- a/src/test/compile-fail/issue-17383.rs +++ b/src/test/compile-fail/issue-17383.rs @@ -12,7 +12,7 @@ enum X { A = b'a' //~ ERROR discriminator values can only be used with a c-like enum , - B(int) + B(isize) } fn main() {} diff --git a/src/test/compile-fail/issue-17385.rs b/src/test/compile-fail/issue-17385.rs index 62a5c7318b9..38278c524c8 100644 --- a/src/test/compile-fail/issue-17385.rs +++ b/src/test/compile-fail/issue-17385.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct X(int); +struct X(isize); enum Enum { Variant1, @@ -23,10 +23,10 @@ impl Drop for Enum { } fn main() { - let foo = X(1i); + let foo = X(1is); drop(foo); match foo { //~ ERROR use of moved value - X(1i) => (), + X(1is) => (), _ => unreachable!() } diff --git a/src/test/compile-fail/issue-17405.rs b/src/test/compile-fail/issue-17405.rs index c956f00c8e7..63120e85b09 100644 --- a/src/test/compile-fail/issue-17405.rs +++ b/src/test/compile-fail/issue-17405.rs @@ -9,11 +9,11 @@ // except according to those terms. enum Foo { - Bar(int) + Bar(isize) } fn main() { - match Foo::Bar(1i) { + match Foo::Bar(1is) { Foo { i } => () //~ ERROR `Foo` does not name a struct or a struct variant } } diff --git a/src/test/compile-fail/issue-17441.rs b/src/test/compile-fail/issue-17441.rs index 6ae4fbca8b0..e9e69dadd3b 100644 --- a/src/test/compile-fail/issue-17441.rs +++ b/src/test/compile-fail/issue-17441.rs @@ -8,17 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let _foo = &[1u, 2] as [usize]; + let _foo = &[1us, 2] as [usize]; //~^ ERROR cast to unsized type: `&[usize; 2]` as `[usize]` //~^^ HELP consider using an implicit coercion to `&[usize]` instead - let _bar = box 1u as std::fmt::Show; + let _bar = box 1us as std::fmt::Show; //~^ ERROR cast to unsized type: `Box<usize>` as `core::fmt::Show` //~^^ HELP did you mean `Box<core::fmt::Show>`? - let _baz = 1u as std::fmt::Show; + let _baz = 1us as std::fmt::Show; //~^ ERROR cast to unsized type: `usize` as `core::fmt::Show` //~^^ HELP consider using a box or reference as appropriate - let _quux = [1u, 2] as [usize]; + let _quux = [1us, 2] as [usize]; //~^ ERROR cast to unsized type: `[usize; 2]` as `[usize]` //~^^ HELP consider using a box or reference as appropriate } diff --git a/src/test/compile-fail/issue-17450.rs b/src/test/compile-fail/issue-17450.rs index ca611c62577..5471d8522df 100644 --- a/src/test/compile-fail/issue-17450.rs +++ b/src/test/compile-fail/issue-17450.rs @@ -10,8 +10,8 @@ #![allow(dead_code)] -static mut x: int = 3; -static mut y: int = unsafe { +static mut x: isize = 3; +static mut y: isize = unsafe { x //~^ ERROR cannot refer to other statics by value, use the address-of operator or a constant instea }; diff --git a/src/test/compile-fail/issue-17458.rs b/src/test/compile-fail/issue-17458.rs index b1fbe6f5549..d9fd67f9197 100644 --- a/src/test/compile-fail/issue-17458.rs +++ b/src/test/compile-fail/issue-17458.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static X: uint = 0 as *const uint as uint; +static X: usize = 0 as *const usize as usize; //~^ ERROR: can not cast a pointer to an integer in a constant expression fn main() { diff --git a/src/test/compile-fail/issue-17651.rs b/src/test/compile-fail/issue-17651.rs index 589f1cf44bf..fbecd0487bf 100644 --- a/src/test/compile-fail/issue-17651.rs +++ b/src/test/compile-fail/issue-17651.rs @@ -11,8 +11,10 @@ // Test that moves of unsized values within closures are caught // and rejected. +#![feature(box_syntax)] + fn main() { (|&:| box *[0us].as_slice())(); - //~^ ERROR cannot move out of dereference + //~^ ERROR cannot move out of borrowed content //~^^ ERROR cannot move a value of type [usize] } diff --git a/src/test/compile-fail/issue-17718-borrow-interior.rs b/src/test/compile-fail/issue-17718-borrow-interior.rs index 8aa5fdf1c4d..d33c12668f2 100644 --- a/src/test/compile-fail/issue-17718-borrow-interior.rs +++ b/src/test/compile-fail/issue-17718-borrow-interior.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct S { a: uint } +struct S { a: usize } static A: S = S { a: 3 }; -static B: &'static uint = &A.a; +static B: &'static usize = &A.a; //~^ ERROR: cannot refer to the interior of another static -static C: &'static uint = &(A.a); +static C: &'static usize = &(A.a); //~^ ERROR: cannot refer to the interior of another static -static D: [uint; 1] = [1]; -static E: uint = D[0]; +static D: [usize; 1] = [1]; +static E: usize = D[0]; //~^ ERROR: cannot refer to other statics by value -static F: &'static uint = &D[0]; +static F: &'static usize = &D[0]; //~^ ERROR: cannot refer to the interior of another static fn main() {} diff --git a/src/test/compile-fail/issue-17718-const-bad-values.rs b/src/test/compile-fail/issue-17718-const-bad-values.rs index 6425dbda5c6..daa250d12f5 100644 --- a/src/test/compile-fail/issue-17718-const-bad-values.rs +++ b/src/test/compile-fail/issue-17718-const-bad-values.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -const C1: &'static mut [uint] = &mut []; +const C1: &'static mut [usize] = &mut []; //~^ ERROR: constants are not allowed to have mutable references -static mut S: uint = 3; -const C2: &'static mut uint = &mut S; +static mut S: usize = 3; +const C2: &'static mut usize = &mut S; //~^ ERROR: constants cannot refer to other statics //~^^ ERROR: are not allowed to have mutable references diff --git a/src/test/compile-fail/issue-17718-const-borrow.rs b/src/test/compile-fail/issue-17718-const-borrow.rs index 21cc9a757cf..dfa5bca8ccd 100644 --- a/src/test/compile-fail/issue-17718-const-borrow.rs +++ b/src/test/compile-fail/issue-17718-const-borrow.rs @@ -10,13 +10,13 @@ use std::cell::UnsafeCell; -const A: UnsafeCell<uint> = UnsafeCell { value: 1 }; -const B: &'static UnsafeCell<uint> = &A; +const A: UnsafeCell<usize> = UnsafeCell { value: 1 }; +const B: &'static UnsafeCell<usize> = &A; //~^ ERROR: cannot borrow a constant which contains interior mutability -struct C { a: UnsafeCell<uint> } +struct C { a: UnsafeCell<usize> } const D: C = C { a: UnsafeCell { value: 1 } }; -const E: &'static UnsafeCell<uint> = &D.a; +const E: &'static UnsafeCell<usize> = &D.a; //~^ ERROR: cannot borrow a constant which contains interior mutability const F: &'static C = &D; //~^ ERROR: cannot borrow a constant which contains interior mutability diff --git a/src/test/compile-fail/issue-17718-const-mut.rs b/src/test/compile-fail/issue-17718-const-mut.rs index 12b9cf4ba8c..5177ebbc188 100644 --- a/src/test/compile-fail/issue-17718-const-mut.rs +++ b/src/test/compile-fail/issue-17718-const-mut.rs @@ -11,7 +11,7 @@ const mut //~ ERROR: const globals cannot be mutable //~^ HELP did you mean to declare a static? -FOO: uint = 3; +FOO: usize = 3; fn main() { } diff --git a/src/test/compile-fail/issue-17718-const-naming.rs b/src/test/compile-fail/issue-17718-const-naming.rs index 0cfee6daf3f..15f66493f88 100644 --- a/src/test/compile-fail/issue-17718-const-naming.rs +++ b/src/test/compile-fail/issue-17718-const-naming.rs @@ -10,7 +10,7 @@ #[deny(warnings)] -const foo: int = 3; +const foo: isize = 3; //~^ ERROR: should have an uppercase name such as //~^^ ERROR: constant item is never used diff --git a/src/test/compile-fail/issue-17718-const-privacy.rs b/src/test/compile-fail/issue-17718-const-privacy.rs index d3be9f3dd3f..a9af30a3ff0 100644 --- a/src/test/compile-fail/issue-17718-const-privacy.rs +++ b/src/test/compile-fail/issue-17718-const-privacy.rs @@ -20,7 +20,7 @@ use other::{ }; mod a { - const B: uint = 3; + const B: usize = 3; } fn main() {} diff --git a/src/test/compile-fail/issue-17718-constants-not-static.rs b/src/test/compile-fail/issue-17718-constants-not-static.rs index 8c51b592054..db56d2c6cf3 100644 --- a/src/test/compile-fail/issue-17718-constants-not-static.rs +++ b/src/test/compile-fail/issue-17718-constants-not-static.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -const FOO: uint = 3; +const FOO: usize = 3; -fn foo() -> &'static uint { &FOO } +fn foo() -> &'static usize { &FOO } //~^ ERROR: borrowed value does not live long enough fn main() { diff --git a/src/test/compile-fail/issue-17718-patterns.rs b/src/test/compile-fail/issue-17718-patterns.rs index 01dfb1b4af9..6c4d0874703 100644 --- a/src/test/compile-fail/issue-17718-patterns.rs +++ b/src/test/compile-fail/issue-17718-patterns.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static A1: uint = 1; -static mut A2: uint = 1; -const A3: uint = 1; +static A1: usize = 1; +static mut A2: usize = 1; +const A3: usize = 1; fn main() { - match 1u { + match 1us { A1 => {} //~ ERROR: static variables cannot be referenced in a pattern A2 => {} //~ ERROR: static variables cannot be referenced in a pattern A3 => {} diff --git a/src/test/compile-fail/issue-17718-recursive.rs b/src/test/compile-fail/issue-17718-recursive.rs index a13dfe639c1..9959b0c6fc5 100644 --- a/src/test/compile-fail/issue-17718-recursive.rs +++ b/src/test/compile-fail/issue-17718-recursive.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -const A: uint = B; //~ ERROR: recursive constant -const B: uint = A; //~ ERROR: recursive constant +const A: usize = B; //~ ERROR: recursive constant +const B: usize = A; //~ ERROR: recursive constant fn main() {} diff --git a/src/test/compile-fail/issue-17718-references.rs b/src/test/compile-fail/issue-17718-references.rs index 7b272e1610c..9d8b116f569 100644 --- a/src/test/compile-fail/issue-17718-references.rs +++ b/src/test/compile-fail/issue-17718-references.rs @@ -8,21 +8,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Struct { a: uint } +struct Struct { a: usize } -const C: uint = 1; -static S: uint = 1; +const C: usize = 1; +static S: usize = 1; -const T1: &'static uint = &C; -const T2: &'static uint = &S; //~ ERROR: constants cannot refer to other statics -static T3: &'static uint = &C; -static T4: &'static uint = &S; +const T1: &'static usize = &C; +const T2: &'static usize = &S; //~ ERROR: constants cannot refer to other statics +static T3: &'static usize = &C; +static T4: &'static usize = &S; -const T5: uint = C; -const T6: uint = S; //~ ERROR: constants cannot refer to other statics +const T5: usize = C; +const T6: usize = S; //~ ERROR: constants cannot refer to other statics //~^ cannot refer to other statics -static T7: uint = C; -static T8: uint = S; //~ ERROR: cannot refer to other statics by value +static T7: usize = C; +static T8: usize = S; //~ ERROR: cannot refer to other statics by value const T9: Struct = Struct { a: C }; const T10: Struct = Struct { a: S }; //~ ERROR: cannot refer to other statics by value diff --git a/src/test/compile-fail/issue-17718-static-sync.rs b/src/test/compile-fail/issue-17718-static-sync.rs index 147bff2e977..394a9cc69be 100644 --- a/src/test/compile-fail/issue-17718-static-sync.rs +++ b/src/test/compile-fail/issue-17718-static-sync.rs @@ -12,7 +12,7 @@ use std::marker; struct Foo { marker: marker::NoSync } -static FOO: uint = 3; +static FOO: usize = 3; static BAR: Foo = Foo { marker: marker::NoSync }; //~^ ERROR: the trait `core::marker::Sync` is not implemented diff --git a/src/test/compile-fail/issue-17800.rs b/src/test/compile-fail/issue-17800.rs index 9590ef3dab4..89611e4f3fe 100644 --- a/src/test/compile-fail/issue-17800.rs +++ b/src/test/compile-fail/issue-17800.rs @@ -14,8 +14,8 @@ enum MyOption<T> { } fn main() { - match MyOption::MySome(42i) { - MyOption::MySome { x: 42i } => (), + match MyOption::MySome(42is) { + MyOption::MySome { x: 42is } => (), //~^ ERROR `MyOption::MySome` does not name a struct or a struct variant _ => (), } diff --git a/src/test/compile-fail/issue-17913.rs b/src/test/compile-fail/issue-17913.rs index 3224edb381c..56cd544b3c6 100644 --- a/src/test/compile-fail/issue-17913.rs +++ b/src/test/compile-fail/issue-17913.rs @@ -8,18 +8,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. + // error-pattern: too big for the current architecture -#[cfg(target_word_size = "64")] +#![feature(box_syntax)] + +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] fn main() { - let n = 0u; - let a = box [&n; 0xF000000000000000u]; + let n = 0us; + let a = box [&n; 0xF000000000000000us]; println!("{}", a[0xFFFFFFu]); } -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] fn main() { - let n = 0u; + let n = 0us; let a = box [&n; 0xFFFFFFFFu]; println!("{}", a[0xFFFFFFu]); } diff --git a/src/test/compile-fail/issue-17933.rs b/src/test/compile-fail/issue-17933.rs index de5a38507bc..47f8d75250d 100644 --- a/src/test/compile-fail/issue-17933.rs +++ b/src/test/compile-fail/issue-17933.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -pub static X: uint = 1u; +pub static X: usize = 1us; fn main() { - match 1u { + match 1us { self::X => { }, //~^ ERROR static variables cannot be referenced in a pattern, use a `const` instead _ => { }, diff --git a/src/test/compile-fail/issue-17999.rs b/src/test/compile-fail/issue-17999.rs index e3ad2dd1b06..5726960f66a 100644 --- a/src/test/compile-fail/issue-17999.rs +++ b/src/test/compile-fail/issue-17999.rs @@ -11,7 +11,7 @@ #![deny(unused_variables)] fn main() { - for _ in range(1i, 101) { + for _ in range(1is, 101) { let x = (); //~ ERROR: unused variable: `x` match () { a => {} //~ ERROR: unused variable: `a` diff --git a/src/test/compile-fail/issue-18107.rs b/src/test/compile-fail/issue-18107.rs index b8249ebd479..83427e8aa67 100644 --- a/src/test/compile-fail/issue-18107.rs +++ b/src/test/compile-fail/issue-18107.rs @@ -16,7 +16,7 @@ fn _create_render(_: &()) -> AbstractRenderer //~^ ERROR: the trait `core::marker::Sized` is not implemented { - match 0u { + match 0us { _ => unimplemented!() } } diff --git a/src/test/compile-fail/issue-18118.rs b/src/test/compile-fail/issue-18118.rs index 4497c8088c3..129f28f1d89 100644 --- a/src/test/compile-fail/issue-18118.rs +++ b/src/test/compile-fail/issue-18118.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - static z: &'static int = { + static z: &'static isize = { let p = 3; &p //~^ ERROR cannot borrow a local variable inside a static block, define a separate static instead diff --git a/src/test/compile-fail/issue-18252.rs b/src/test/compile-fail/issue-18252.rs index 02493b96dc8..822c86d1d3e 100644 --- a/src/test/compile-fail/issue-18252.rs +++ b/src/test/compile-fail/issue-18252.rs @@ -9,9 +9,9 @@ // except according to those terms. enum Foo { - Variant { x: uint } + Variant { x: usize } } fn main() { - let f = Foo::Variant(42u); //~ ERROR uses it like a function + let f = Foo::Variant(42us); //~ ERROR uses it like a function } diff --git a/src/test/compile-fail/issue-18294.rs b/src/test/compile-fail/issue-18294.rs index ca4cf526f07..efc1ba1635c 100644 --- a/src/test/compile-fail/issue-18294.rs +++ b/src/test/compile-fail/issue-18294.rs @@ -10,6 +10,6 @@ fn main() { const X: u32 = 1; - const Y: uint = &X as *const u32 as uint; //~ ERROR E0018 + const Y: usize = &X as *const u32 as usize; //~ ERROR E0018 println!("{}", Y); } diff --git a/src/test/compile-fail/issue-18423.rs b/src/test/compile-fail/issue-18423.rs index 63b110b5579..5945a7a1c9a 100644 --- a/src/test/compile-fail/issue-18423.rs +++ b/src/test/compile-fail/issue-18423.rs @@ -11,7 +11,7 @@ // Test that `Box` cannot be used with a lifetime parameter. struct Foo<'a> { - x: Box<'a, int> //~ ERROR wrong number of lifetime parameters + x: Box<'a, isize> //~ ERROR wrong number of lifetime parameters } pub fn main() { diff --git a/src/test/compile-fail/issue-18566.rs b/src/test/compile-fail/issue-18566.rs index 0d1a1f16c2c..85dda340d19 100644 --- a/src/test/compile-fail/issue-18566.rs +++ b/src/test/compile-fail/issue-18566.rs @@ -10,25 +10,25 @@ use std::ops::Deref; -struct MyPtr<'a>(&'a mut uint); +struct MyPtr<'a>(&'a mut usize); impl<'a> Deref for MyPtr<'a> { - type Target = uint; + type Target = usize; - fn deref<'b>(&'b self) -> &'b uint { self.0 } + fn deref<'b>(&'b self) -> &'b usize { self.0 } } trait Tr { - fn poke(&self, s: &mut uint); + fn poke(&self, s: &mut usize); } -impl Tr for uint { - fn poke(&self, s: &mut uint) { +impl Tr for usize { + fn poke(&self, s: &mut usize) { *s = 2; } } fn main() { - let s = &mut 1u; + let s = &mut 1us; MyPtr(s).poke(s); //~^ ERROR cannot borrow `*s` as mutable more than once at a time diff --git a/src/test/compile-fail/issue-18783.rs b/src/test/compile-fail/issue-18783.rs index 3a0fbddf818..bed835d9bde 100644 --- a/src/test/compile-fail/issue-18783.rs +++ b/src/test/compile-fail/issue-18783.rs @@ -8,11 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::cell::RefCell; fn main() { let c = RefCell::new(vec![]); - let mut y = 1u; + let mut y = 1us; c.push(box || y = 0); c.push(box || y = 0); //~^ ERROR cannot borrow `y` as mutable more than once at a time @@ -20,7 +22,7 @@ fn main() { fn ufcs() { let c = RefCell::new(vec![]); - let mut y = 1u; + let mut y = 1us; Push::push(&c, box || y = 0); Push::push(&c, box || y = 0); diff --git a/src/test/compile-fail/issue-18959.rs b/src/test/compile-fail/issue-18959.rs index 7aba1bc8e65..e174fb9b7ad 100644 --- a/src/test/compile-fail/issue-18959.rs +++ b/src/test/compile-fail/issue-18959.rs @@ -17,7 +17,7 @@ impl Foo for Thing { fn foo<T>(&self, _: &T) {} } -#[inline(never)] fn foo(b: &Bar) { b.foo(&0u) } +#[inline(never)] fn foo(b: &Bar) { b.foo(&0us) } fn main() { let mut thing = Thing; diff --git a/src/test/compile-fail/issue-19096.rs b/src/test/compile-fail/issue-19096.rs index 5d915d6a59b..7bc79463d3a 100644 --- a/src/test/compile-fail/issue-19096.rs +++ b/src/test/compile-fail/issue-19096.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - let t = (42i, 42i); - t.0::<int>; //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `::` + let t = (42is, 42is); + t.0::<isize>; //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `::` } diff --git a/src/test/compile-fail/issue-19244-1.rs b/src/test/compile-fail/issue-19244-1.rs index fafe6377397..0850705aee6 100644 --- a/src/test/compile-fail/issue-19244-1.rs +++ b/src/test/compile-fail/issue-19244-1.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -const TUP: (uint,) = (42,); +const TUP: (usize,) = (42,); fn main() { - let a: [int; TUP.1]; + let a: [isize; TUP.1]; //~^ ERROR expected constant expr for array length: tuple index out of bounds } diff --git a/src/test/compile-fail/issue-19244-2.rs b/src/test/compile-fail/issue-19244-2.rs index 95965ca35f9..93a3fc87eb0 100644 --- a/src/test/compile-fail/issue-19244-2.rs +++ b/src/test/compile-fail/issue-19244-2.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct MyStruct { field: uint } +struct MyStruct { field: usize } const STRUCT: MyStruct = MyStruct { field: 42 }; fn main() { - let a: [int; STRUCT.nonexistent_field]; + let a: [isize; STRUCT.nonexistent_field]; //~^ ERROR expected constant expr for array length: nonexistent struct field } diff --git a/src/test/compile-fail/issue-1962.rs b/src/test/compile-fail/issue-1962.rs index c59ee328eff..44abfca1653 100644 --- a/src/test/compile-fail/issue-1962.rs +++ b/src/test/compile-fail/issue-1962.rs @@ -10,9 +10,9 @@ // compile-flags: -D while-true fn main() { - let mut i = 0i; + let mut i = 0is; while true { //~ ERROR denote infinite loops with loop - i += 1i; - if i == 5i { break; } + i += 1is; + if i == 5is { break; } } } diff --git a/src/test/compile-fail/issue-2111.rs b/src/test/compile-fail/issue-2111.rs index 3d9c7401ded..8180ce52bdb 100644 --- a/src/test/compile-fail/issue-2111.rs +++ b/src/test/compile-fail/issue-2111.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(a: Option<uint>, b: Option<uint>) { +fn foo(a: Option<usize>, b: Option<usize>) { match (a,b) { //~^ ERROR: non-exhaustive patterns: `(None, None)` not covered (Some(a), Some(b)) if a == b => { } diff --git a/src/test/compile-fail/issue-2150.rs b/src/test/compile-fail/issue-2150.rs index 455cde63f27..f18db94acf3 100644 --- a/src/test/compile-fail/issue-2150.rs +++ b/src/test/compile-fail/issue-2150.rs @@ -12,10 +12,10 @@ #![allow(unused_variables)] #![allow(dead_code)] -fn fail_len(v: Vec<int> ) -> uint { +fn fail_len(v: Vec<isize> ) -> usize { let mut i = 3; panic!(); - for x in v.iter() { i += 1u; } + for x in v.iter() { i += 1us; } //~^ ERROR: unreachable statement return i; } diff --git a/src/test/compile-fail/issue-2330.rs b/src/test/compile-fail/issue-2330.rs index 6291b024053..63f146a21d9 100644 --- a/src/test/compile-fail/issue-2330.rs +++ b/src/test/compile-fail/issue-2330.rs @@ -15,8 +15,8 @@ trait channel<T> { } // `chan` is not a trait, it's an enum -impl chan for int { //~ ERROR `chan` is not a trait - fn send(&self, v: int) { panic!() } +impl chan for isize { //~ ERROR `chan` is not a trait + fn send(&self, v: isize) { panic!() } } fn main() { diff --git a/src/test/compile-fail/issue-2354-1.rs b/src/test/compile-fail/issue-2354-1.rs index 67b5c6becc7..d37837b9714 100644 --- a/src/test/compile-fail/issue-2354-1.rs +++ b/src/test/compile-fail/issue-2354-1.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static foo: int = 2; } //~ ERROR incorrect close delimiter: +static foo: isize = 2; } //~ ERROR incorrect close delimiter: diff --git a/src/test/compile-fail/issue-2356.rs b/src/test/compile-fail/issue-2356.rs index 850edd05781..f0ae0eb59f5 100644 --- a/src/test/compile-fail/issue-2356.rs +++ b/src/test/compile-fail/issue-2356.rs @@ -13,7 +13,7 @@ trait Groom { } pub struct cat { - whiskers: int, + whiskers: isize, } pub enum MaybeDog { @@ -30,7 +30,7 @@ impl MaybeDog { } impl Groom for cat { - fn shave(&self, other: uint) { + fn shave(&self, other: usize) { whiskers -= other; //~^ ERROR: unresolved name `whiskers`. Did you mean `self.whiskers`? shave(4); @@ -75,7 +75,7 @@ impl cat { //~^ ERROR: unresolved name `whiskers`. Did you mean `self.whiskers`? } - pub fn grow_older(other:uint) { + pub fn grow_older(other:usize) { whiskers = 4; //~^ ERROR: unresolved name `whiskers`. Did you mean `self.whiskers`? purr_louder(); diff --git a/src/test/compile-fail/issue-2478.rs b/src/test/compile-fail/issue-2478.rs index 860192ba3e5..3aea9c32e3a 100644 --- a/src/test/compile-fail/issue-2478.rs +++ b/src/test/compile-fail/issue-2478.rs @@ -10,8 +10,8 @@ // ignore-test -fn foo<'a>() -> &'a int { //~ ERROR unconstrained region +fn foo<'a>() -> &'a isize { //~ ERROR unconstrained region return &x; } -static x: int = 5; +static x: isize = 5; fn main() {} diff --git a/src/test/compile-fail/issue-2590.rs b/src/test/compile-fail/issue-2590.rs index 79a66e30fdb..d7e438d1049 100644 --- a/src/test/compile-fail/issue-2590.rs +++ b/src/test/compile-fail/issue-2590.rs @@ -10,16 +10,16 @@ struct parser { - tokens: Vec<int> , + tokens: Vec<isize> , } trait parse { - fn parse(&self) -> Vec<int> ; + fn parse(&self) -> Vec<isize> ; } impl parse for parser { - fn parse(&self) -> Vec<int> { - self.tokens //~ ERROR cannot move out of dereference of `&`-pointer + fn parse(&self) -> Vec<isize> { + self.tokens //~ ERROR cannot move out of borrowed content } } diff --git a/src/test/compile-fail/issue-2611-4.rs b/src/test/compile-fail/issue-2611-4.rs index 70ffa86359d..b141c1f441a 100644 --- a/src/test/compile-fail/issue-2611-4.rs +++ b/src/test/compile-fail/issue-2611-4.rs @@ -16,7 +16,7 @@ trait A { } struct E { - f: int + f: isize } impl A for E { diff --git a/src/test/compile-fail/issue-2611-5.rs b/src/test/compile-fail/issue-2611-5.rs index 2eda5d67edd..440294f38ae 100644 --- a/src/test/compile-fail/issue-2611-5.rs +++ b/src/test/compile-fail/issue-2611-5.rs @@ -16,7 +16,7 @@ trait A { } struct E { - f: int + f: isize } impl A for E { diff --git a/src/test/compile-fail/issue-2823.rs b/src/test/compile-fail/issue-2823.rs index b6820a1d8e4..1996cb737fc 100644 --- a/src/test/compile-fail/issue-2823.rs +++ b/src/test/compile-fail/issue-2823.rs @@ -9,7 +9,7 @@ // except according to those terms. struct C { - x: int, + x: isize, } impl Drop for C { diff --git a/src/test/compile-fail/issue-2849.rs b/src/test/compile-fail/issue-2849.rs index 5aaeb7e8c6d..48f4cac9711 100644 --- a/src/test/compile-fail/issue-2849.rs +++ b/src/test/compile-fail/issue-2849.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum foo { alpha, beta(int) } +enum foo { alpha, beta(isize) } fn main() { match foo::alpha { diff --git a/src/test/compile-fail/issue-2995.rs b/src/test/compile-fail/issue-2995.rs index 920897e6828..8fbf97411cc 100644 --- a/src/test/compile-fail/issue-2995.rs +++ b/src/test/compile-fail/issue-2995.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn bad (p: *const int) { - let _q: &int = p as ∫ //~ ERROR non-scalar cast +fn bad (p: *const isize) { + let _q: &isize = p as &isize; //~ ERROR non-scalar cast } fn main() { } diff --git a/src/test/compile-fail/issue-3038.rs b/src/test/compile-fail/issue-3038.rs index d9fe3550c9e..1eec62df788 100644 --- a/src/test/compile-fail/issue-3038.rs +++ b/src/test/compile-fail/issue-3038.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum f { g(int, int) } +enum f { g(isize, isize) } enum h { i(j, k) } -enum j { l(int, int) } -enum k { m(int, int) } +enum j { l(isize, isize) } +enum k { m(isize, isize) } fn main() { diff --git a/src/test/compile-fail/issue-3344.rs b/src/test/compile-fail/issue-3344.rs index 27a91f891a2..73532cb768a 100644 --- a/src/test/compile-fail/issue-3344.rs +++ b/src/test/compile-fail/issue-3344.rs @@ -9,7 +9,7 @@ // except according to those terms. #[derive(PartialEq)] -struct thing(uint); +struct thing(usize); impl PartialOrd for thing { //~ ERROR not all trait items implemented, missing: `partial_cmp` fn le(&self, other: &thing) -> bool { true } fn ge(&self, other: &thing) -> bool { true } diff --git a/src/test/compile-fail/issue-3521-2.rs b/src/test/compile-fail/issue-3521-2.rs index cdfc9906776..678618d7216 100644 --- a/src/test/compile-fail/issue-3521-2.rs +++ b/src/test/compile-fail/issue-3521-2.rs @@ -11,7 +11,7 @@ fn main() { let foo = 100; - static y: int = foo + 1; //~ ERROR: attempt to use a non-constant value in a constant + static y: isize = foo + 1; //~ ERROR: attempt to use a non-constant value in a constant println!("{}", y); } diff --git a/src/test/compile-fail/issue-3601.rs b/src/test/compile-fail/issue-3601.rs index f10305d017d..15b3ec0bfe7 100644 --- a/src/test/compile-fail/issue-3601.rs +++ b/src/test/compile-fail/issue-3601.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct HTMLImageData { image: Option<String> diff --git a/src/test/compile-fail/issue-3668-2.rs b/src/test/compile-fail/issue-3668-2.rs index f7637f684be..0577b152723 100644 --- a/src/test/compile-fail/issue-3668-2.rs +++ b/src/test/compile-fail/issue-3668-2.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(x:int) { - static child: int = x + 1; //~ ERROR attempt to use a non-constant value in a constant +fn f(x:isize) { + static child: isize = x + 1; //~ ERROR attempt to use a non-constant value in a constant } fn main() {} diff --git a/src/test/compile-fail/issue-3702-2.rs b/src/test/compile-fail/issue-3702-2.rs index 1e80fd7a7e9..2b732899ea4 100644 --- a/src/test/compile-fail/issue-3702-2.rs +++ b/src/test/compile-fail/issue-3702-2.rs @@ -11,13 +11,13 @@ use std::num::ToPrimitive; trait Add { - fn to_int(&self) -> int; - fn add_dynamic(&self, other: &Add) -> int; + fn to_int(&self) -> isize; + fn add_dynamic(&self, other: &Add) -> isize; } -impl Add for int { - fn to_int(&self) -> int { *self } - fn add_dynamic(&self, other: &Add) -> int { +impl Add for isize { + fn to_int(&self) -> isize { *self } + fn add_dynamic(&self, other: &Add) -> isize { self.to_int() + other.to_int() //~ ERROR multiple applicable methods in scope } } diff --git a/src/test/compile-fail/issue-3707.rs b/src/test/compile-fail/issue-3707.rs index 2445638d62e..0aa357f2398 100644 --- a/src/test/compile-fail/issue-3707.rs +++ b/src/test/compile-fail/issue-3707.rs @@ -9,12 +9,12 @@ // except according to those terms. struct Obj { - member: uint + member: usize } impl Obj { pub fn boom() -> bool { - return 1i+1 == 2 + return 1is+1 == 2 } pub fn chirp(&self) { self.boom(); //~ ERROR `&Obj` does not implement any method in scope named `boom` @@ -24,5 +24,5 @@ impl Obj { fn main() { let o = Obj { member: 0 }; o.chirp(); - 1i + 1; + 1is + 1; } diff --git a/src/test/compile-fail/issue-3763.rs b/src/test/compile-fail/issue-3763.rs index 73d42aa0de1..6e6c19a5bf6 100644 --- a/src/test/compile-fail/issue-3763.rs +++ b/src/test/compile-fail/issue-3763.rs @@ -8,10 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] mod my_mod { pub struct MyStruct { - priv_field: int + priv_field: isize } pub fn MyStruct () -> MyStruct { MyStruct {priv_field: 4} diff --git a/src/test/compile-fail/issue-3820.rs b/src/test/compile-fail/issue-3820.rs index 06577afa6dd..28de76f18da 100644 --- a/src/test/compile-fail/issue-3820.rs +++ b/src/test/compile-fail/issue-3820.rs @@ -9,11 +9,11 @@ // except according to those terms. struct Thing { - x: int + x: isize } impl Thing { - fn mul(&self, c: &int) -> Thing { + fn mul(&self, c: &isize) -> Thing { Thing {x: self.x * *c} } } diff --git a/src/test/compile-fail/issue-3907-2.rs b/src/test/compile-fail/issue-3907-2.rs index 546b808a38f..9a166a6752b 100644 --- a/src/test/compile-fail/issue-3907-2.rs +++ b/src/test/compile-fail/issue-3907-2.rs @@ -14,7 +14,7 @@ extern crate issue_3907; type Foo = issue_3907::Foo+'static; struct S { - name: int + name: isize } fn bar(_x: Foo) {} //~ ERROR the trait `core::marker::Sized` is not implemented diff --git a/src/test/compile-fail/issue-3907.rs b/src/test/compile-fail/issue-3907.rs index a2faef59fd8..001de796b4a 100644 --- a/src/test/compile-fail/issue-3907.rs +++ b/src/test/compile-fail/issue-3907.rs @@ -14,7 +14,7 @@ extern crate issue_3907; type Foo = issue_3907::Foo; struct S { - name: int + name: isize } impl Foo for S { //~ ERROR: `Foo` is not a trait diff --git a/src/test/compile-fail/issue-3953.rs b/src/test/compile-fail/issue-3953.rs index ab2018af999..0f1dd2d7fd6 100644 --- a/src/test/compile-fail/issue-3953.rs +++ b/src/test/compile-fail/issue-3953.rs @@ -16,7 +16,7 @@ trait Hahaha: PartialEq + PartialEq { //~^ ERROR trait `PartialEq` already appears in the list of bounds } -struct Lol(int); +struct Lol(isize); impl Hahaha for Lol { } diff --git a/src/test/compile-fail/issue-4265.rs b/src/test/compile-fail/issue-4265.rs index a1a77092b12..b4bc7ecdc5f 100644 --- a/src/test/compile-fail/issue-4265.rs +++ b/src/test/compile-fail/issue-4265.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - baz: uint + baz: usize } impl Foo { diff --git a/src/test/compile-fail/issue-4335.rs b/src/test/compile-fail/issue-4335.rs index d4f9ea5b276..292d1d9616a 100644 --- a/src/test/compile-fail/issue-4335.rs +++ b/src/test/compile-fail/issue-4335.rs @@ -9,6 +9,7 @@ // except according to those terms. #![feature(unboxed_closures)] +#![feature(box_syntax)] fn id<T>(t: T) -> T { t } @@ -17,6 +18,6 @@ fn f<'r, T>(v: &'r T) -> Box<FnMut() -> T + 'r> { } fn main() { - let v = &5i; + let v = &5is; println!("{}", f(v).call_mut(())); } diff --git a/src/test/compile-fail/issue-4366-2.rs b/src/test/compile-fail/issue-4366-2.rs index 289e9855525..e8dfac45447 100644 --- a/src/test/compile-fail/issue-4366-2.rs +++ b/src/test/compile-fail/issue-4366-2.rs @@ -18,7 +18,7 @@ mod foo { mod a { pub mod b { use foo::foo; - type bar = int; + type bar = isize; } pub mod sub { use a::b::*; diff --git a/src/test/compile-fail/issue-4366.rs b/src/test/compile-fail/issue-4366.rs index 289aa21e1cb..5625ac00c85 100644 --- a/src/test/compile-fail/issue-4366.rs +++ b/src/test/compile-fail/issue-4366.rs @@ -21,11 +21,11 @@ mod foo { mod a { pub mod b { use foo::foo; - type bar = int; + type bar = isize; } pub mod sub { use a::b::*; - fn sub() -> int { foo(); 1 } //~ ERROR: unresolved name `foo` + fn sub() -> isize { foo(); 1 } //~ ERROR: unresolved name `foo` } } diff --git a/src/test/compile-fail/issue-4935.rs b/src/test/compile-fail/issue-4935.rs index 3a0db4246be..b37b8e237ed 100644 --- a/src/test/compile-fail/issue-4935.rs +++ b/src/test/compile-fail/issue-4935.rs @@ -10,5 +10,5 @@ // Regression test for issue #4935 -fn foo(a: uint) {} +fn foo(a: usize) {} fn main() { foo(5, 6) } //~ ERROR this function takes 1 parameter but 2 parameters were supplied diff --git a/src/test/compile-fail/issue-4972.rs b/src/test/compile-fail/issue-4972.rs index 765aec35fc6..b2b9dfce092 100644 --- a/src/test/compile-fail/issue-4972.rs +++ b/src/test/compile-fail/issue-4972.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait MyTrait { } diff --git a/src/test/compile-fail/issue-5035.rs b/src/test/compile-fail/issue-5035.rs index 8ffe308a669..cdf9d3bd36e 100644 --- a/src/test/compile-fail/issue-5035.rs +++ b/src/test/compile-fail/issue-5035.rs @@ -10,6 +10,6 @@ trait I {} type K = I; -impl K for int {} //~ ERROR: `K` is not a trait +impl K for isize {} //~ ERROR: `K` is not a trait //~^ NOTE: `type` aliases cannot be used for traits fn main() {} diff --git a/src/test/compile-fail/issue-5100.rs b/src/test/compile-fail/issue-5100.rs index df3748ac934..ca7f87ff61a 100644 --- a/src/test/compile-fail/issue-5100.rs +++ b/src/test/compile-fail/issue-5100.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + enum A { B, C } fn main() { diff --git a/src/test/compile-fail/issue-5153.rs b/src/test/compile-fail/issue-5153.rs index 57a158d2438..c10c7cba455 100644 --- a/src/test/compile-fail/issue-5153.rs +++ b/src/test/compile-fail/issue-5153.rs @@ -14,8 +14,8 @@ trait Foo { fn foo(self: Box<Self>); } -impl Foo for int { - fn foo(self: Box<int>) { } +impl Foo for isize { + fn foo(self: Box<isize>) { } } fn main() { diff --git a/src/test/compile-fail/issue-5358-1.rs b/src/test/compile-fail/issue-5358-1.rs index 576dfe8b67b..96bad3a6a44 100644 --- a/src/test/compile-fail/issue-5358-1.rs +++ b/src/test/compile-fail/issue-5358-1.rs @@ -9,7 +9,7 @@ // except according to those terms. enum Either<T, U> { Left(T), Right(U) } -struct S(Either<uint, uint>); +struct S(Either<usize, usize>); fn main() { match S(Either::Left(5)) { diff --git a/src/test/compile-fail/issue-5439.rs b/src/test/compile-fail/issue-5439.rs index 55e3459a589..4e618f3d858 100644 --- a/src/test/compile-fail/issue-5439.rs +++ b/src/test/compile-fail/issue-5439.rs @@ -8,17 +8,18 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct Foo { - foo: int, + foo: isize, } struct Bar { - bar: int, + bar: isize, } impl Bar { - fn make_foo (&self, i: int) -> Box<Foo> { + fn make_foo (&self, i: isize) -> Box<Foo> { return box Foo { nonexistent: self, foo: i }; //~ ERROR: no field named } } diff --git a/src/test/compile-fail/issue-5500-1.rs b/src/test/compile-fail/issue-5500-1.rs index 0edcfa8a547..7e5809cdee0 100644 --- a/src/test/compile-fail/issue-5500-1.rs +++ b/src/test/compile-fail/issue-5500-1.rs @@ -9,7 +9,7 @@ // except according to those terms. struct TrieMapIterator<'a> { - node: &'a uint + node: &'a usize } fn main() { diff --git a/src/test/compile-fail/issue-5543.rs b/src/test/compile-fail/issue-5543.rs index 2d64013dc27..cf98f1572e5 100644 --- a/src/test/compile-fail/issue-5543.rs +++ b/src/test/compile-fail/issue-5543.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + trait Foo {} impl Foo for u8 {} diff --git a/src/test/compile-fail/issue-5544-b.rs b/src/test/compile-fail/issue-5544-b.rs index bbe43e652a8..1f166ec0d1c 100644 --- a/src/test/compile-fail/issue-5544-b.rs +++ b/src/test/compile-fail/issue-5544-b.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - let _i = 0xff_ffff_ffff_ffff_ffff; + let _i = 0xff_ffff_ffff_ffff_ffff_is; //~^ ERROR int literal is too large } diff --git a/src/test/compile-fail/issue-5997-enum.rs b/src/test/compile-fail/issue-5997-enum.rs index 39e1e117cd0..ad485f2d330 100644 --- a/src/test/compile-fail/issue-5997-enum.rs +++ b/src/test/compile-fail/issue-5997-enum.rs @@ -16,6 +16,6 @@ fn f<Z>() -> bool { } fn main() { - let b = f::<int>(); + let b = f::<isize>(); assert!(b); } diff --git a/src/test/compile-fail/issue-5997-struct.rs b/src/test/compile-fail/issue-5997-struct.rs index b2a63ed1c7b..587c7c63f4c 100644 --- a/src/test/compile-fail/issue-5997-struct.rs +++ b/src/test/compile-fail/issue-5997-struct.rs @@ -16,6 +16,6 @@ fn f<T>() -> bool { } fn main() { - let b = f::<int>(); + let b = f::<isize>(); assert!(b); } diff --git a/src/test/compile-fail/issue-6702.rs b/src/test/compile-fail/issue-6702.rs index 3e35e4a659d..d035c615ec3 100644 --- a/src/test/compile-fail/issue-6702.rs +++ b/src/test/compile-fail/issue-6702.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Monster { - damage: int + damage: isize } diff --git a/src/test/compile-fail/issue-6801.rs b/src/test/compile-fail/issue-6801.rs index 433ae3bf89e..9424ff22dc7 100644 --- a/src/test/compile-fail/issue-6801.rs +++ b/src/test/compile-fail/issue-6801.rs @@ -12,17 +12,18 @@ // transferring ownership of the owned box before invoking the stack // closure results in a crash. +#![feature(box_syntax)] -fn twice(x: Box<uint>) -> uint { +fn twice(x: Box<usize>) -> usize { *x * 2 } -fn invoke<F>(f: F) where F: FnOnce() -> uint { +fn invoke<F>(f: F) where F: FnOnce() -> usize { f(); } fn main() { - let x : Box<uint> = box 9; + let x : Box<usize> = box 9; let sq = |:| { *x * *x }; twice(x); //~ ERROR: cannot move out of diff --git a/src/test/compile-fail/issue-6991.rs b/src/test/compile-fail/issue-6991.rs index a5d23c70bd5..0cc5898adfc 100644 --- a/src/test/compile-fail/issue-6991.rs +++ b/src/test/compile-fail/issue-6991.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static x: &'static uint = &1; -static y: uint = *x; +static x: &'static usize = &1; +static y: usize = *x; //~^ ERROR cannot refer to other statics by value, // use the address-of operator or a constant instead fn main() {} diff --git a/src/test/compile-fail/issue-7013.rs b/src/test/compile-fail/issue-7013.rs index d2f9ee47603..d246e4e54d0 100644 --- a/src/test/compile-fail/issue-7013.rs +++ b/src/test/compile-fail/issue-7013.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + use std::cell::RefCell; use std::rc::Rc; diff --git a/src/test/compile-fail/issue-7044.rs b/src/test/compile-fail/issue-7044.rs index ee332789b0e..6f9fb2e61f2 100644 --- a/src/test/compile-fail/issue-7044.rs +++ b/src/test/compile-fail/issue-7044.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static X: int = 0; +static X: isize = 0; struct X; //~ ERROR error: duplicate definition of value `X` fn main() {} diff --git a/src/test/compile-fail/issue-7364.rs b/src/test/compile-fail/issue-7364.rs index c8c7ef4ed89..2e644b65402 100644 --- a/src/test/compile-fail/issue-7364.rs +++ b/src/test/compile-fail/issue-7364.rs @@ -8,11 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] use std::cell::RefCell; // Regresion test for issue 7364 -static boxed: Box<RefCell<int>> = box RefCell::new(0); +static boxed: Box<RefCell<isize>> = box RefCell::new(0); //~^ ERROR statics are not allowed to have custom pointers //~| ERROR: the trait `core::marker::Sync` is not implemented for the type //~| ERROR: the trait `core::marker::Sync` is not implemented for the type diff --git a/src/test/compile-fail/issue-7575.rs b/src/test/compile-fail/issue-7575.rs index 0d5156956e5..49e54f25bf6 100644 --- a/src/test/compile-fail/issue-7575.rs +++ b/src/test/compile-fail/issue-7575.rs @@ -30,17 +30,17 @@ trait UnusedTrait { impl CtxtFn for usize { fn f8(self, i: usize) -> usize { - i * 4u + i * 4us } fn f9(i: usize) -> usize { - i * 4u + i * 4us } } impl OtherTrait for usize { fn f9(i: usize) -> usize { - i * 8u + i * 8us } } diff --git a/src/test/compile-fail/issue-7607-1.rs b/src/test/compile-fail/issue-7607-1.rs index 9bf1bd2e011..48fc393d0da 100644 --- a/src/test/compile-fail/issue-7607-1.rs +++ b/src/test/compile-fail/issue-7607-1.rs @@ -11,7 +11,7 @@ // ignore-tidy-linelength struct Foo { - x: int + x: isize } impl Fo { //~ERROR inherent implementations are not allowed for types not defined in the current module diff --git a/src/test/compile-fail/issue-7607-2.rs b/src/test/compile-fail/issue-7607-2.rs index 8a7022a9a32..9541899b469 100644 --- a/src/test/compile-fail/issue-7607-2.rs +++ b/src/test/compile-fail/issue-7607-2.rs @@ -11,7 +11,7 @@ // ignore-tidy-linelength pub mod a { - pub struct Foo { a: uint } + pub struct Foo { a: usize } } pub mod b { diff --git a/src/test/compile-fail/issue-8153.rs b/src/test/compile-fail/issue-8153.rs index 2af531135ec..ea7224939ce 100644 --- a/src/test/compile-fail/issue-8153.rs +++ b/src/test/compile-fail/issue-8153.rs @@ -13,12 +13,12 @@ struct Foo; trait Bar { - fn bar(&self) -> int; + fn bar(&self) -> isize; } impl Bar for Foo { - fn bar(&self) -> int {1} - fn bar(&self) -> int {2} //~ ERROR duplicate method + fn bar(&self) -> isize {1} + fn bar(&self) -> isize {2} //~ ERROR duplicate method } fn main() { diff --git a/src/test/compile-fail/issue-9243.rs b/src/test/compile-fail/issue-9243.rs index eb3618c9f04..808aa098c5a 100644 --- a/src/test/compile-fail/issue-9243.rs +++ b/src/test/compile-fail/issue-9243.rs @@ -11,7 +11,7 @@ // Regresion test for issue 9243 struct Test { - mem: int, + mem: isize, } pub static g_test: Test = Test {mem: 0}; //~ ERROR statics are not allowed to have destructors diff --git a/src/test/compile-fail/issue-9725.rs b/src/test/compile-fail/issue-9725.rs index 9545ad43ff8..1a3c926ba38 100644 --- a/src/test/compile-fail/issue-9725.rs +++ b/src/test/compile-fail/issue-9725.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { foo: int } +struct A { foo: isize } fn main() { let A { foo, foo } = A { foo: 3 }; diff --git a/src/test/compile-fail/issue-9814.rs b/src/test/compile-fail/issue-9814.rs index d6cc493e936..8aefc5919d1 100644 --- a/src/test/compile-fail/issue-9814.rs +++ b/src/test/compile-fail/issue-9814.rs @@ -11,7 +11,7 @@ // Verify that single-variant enums cant be de-referenced // Regression test for issue #9814 -enum Foo { Bar(int) } +enum Foo { Bar(isize) } fn main() { let _ = *Foo::Bar(2); //~ ERROR type `Foo` cannot be dereferenced diff --git a/src/test/compile-fail/issue-9957.rs b/src/test/compile-fail/issue-9957.rs index 573d847cbe3..b1204e82890 100644 --- a/src/test/compile-fail/issue-9957.rs +++ b/src/test/compile-fail/issue-9957.rs @@ -11,5 +11,5 @@ pub extern crate core; //~ ERROR: `pub` visibility is not allowed fn main() { - pub use std::uint; //~ ERROR: imports in functions are never reachable + pub use std::usize; //~ ERROR: imports in functions are never reachable } diff --git a/src/test/compile-fail/keyword-super.rs b/src/test/compile-fail/keyword-super.rs index 6cbc8aa1ea6..0c94f76f1f6 100644 --- a/src/test/compile-fail/keyword-super.rs +++ b/src/test/compile-fail/keyword-super.rs @@ -9,5 +9,5 @@ // except according to those terms. fn main() { - let super: int; //~ ERROR expected identifier, found keyword `super` + let super: isize; //~ ERROR expected identifier, found keyword `super` } diff --git a/src/test/compile-fail/kindck-copy.rs b/src/test/compile-fail/kindck-copy.rs index ac088e69a28..4398be4b212 100644 --- a/src/test/compile-fail/kindck-copy.rs +++ b/src/test/compile-fail/kindck-copy.rs @@ -18,8 +18,8 @@ fn assert_copy<T:Copy>() { } trait Dummy { } struct MyStruct { - x: int, - y: int, + x: isize, + y: isize, } impl Copy for MyStruct {} @@ -28,22 +28,22 @@ struct MyNoncopyStruct { x: Box<char>, } -fn test<'a,T,U:Copy>(_: &'a int) { +fn test<'a,T,U:Copy>(_: &'a isize) { // lifetime pointers are ok... - assert_copy::<&'static int>(); - assert_copy::<&'a int>(); + assert_copy::<&'static isize>(); + assert_copy::<&'a isize>(); assert_copy::<&'a str>(); - assert_copy::<&'a [int]>(); + assert_copy::<&'a [isize]>(); // ...unless they are mutable - assert_copy::<&'static mut int>(); //~ ERROR `core::marker::Copy` is not implemented - assert_copy::<&'a mut int>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<&'static mut isize>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<&'a mut isize>(); //~ ERROR `core::marker::Copy` is not implemented // ~ pointers are not ok - assert_copy::<Box<int>>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<Box<isize>>(); //~ ERROR `core::marker::Copy` is not implemented assert_copy::<String>(); //~ ERROR `core::marker::Copy` is not implemented - assert_copy::<Vec<int> >(); //~ ERROR `core::marker::Copy` is not implemented - assert_copy::<Box<&'a mut int>>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<Vec<isize> >(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<Box<&'a mut isize>>(); //~ ERROR `core::marker::Copy` is not implemented // borrowed object types are generally ok assert_copy::<&'a Dummy>(); @@ -58,16 +58,16 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::marker::Copy` is not implemented // unsafe ptrs are ok - assert_copy::<*const int>(); - assert_copy::<*const &'a mut int>(); + assert_copy::<*const isize>(); + assert_copy::<*const &'a mut isize>(); // regular old ints and such are ok - assert_copy::<int>(); + assert_copy::<isize>(); assert_copy::<bool>(); assert_copy::<()>(); // tuples are ok - assert_copy::<(int,int)>(); + assert_copy::<(isize,isize)>(); // structs of POD are ok assert_copy::<MyStruct>(); @@ -76,7 +76,7 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::<MyNoncopyStruct>(); //~ ERROR `core::marker::Copy` is not implemented // ref counted types are not ok - assert_copy::<Rc<int>>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<Rc<isize>>(); //~ ERROR `core::marker::Copy` is not implemented } pub fn main() { diff --git a/src/test/compile-fail/kindck-destructor-owned.rs b/src/test/compile-fail/kindck-destructor-owned.rs index 803da617abd..7f3704144be 100644 --- a/src/test/compile-fail/kindck-destructor-owned.rs +++ b/src/test/compile-fail/kindck-destructor-owned.rs @@ -10,7 +10,7 @@ struct Bar<'a> { - f: &'a int, + f: &'a isize, } impl<'a> Drop for Bar<'a> { @@ -20,7 +20,7 @@ impl<'a> Drop for Bar<'a> { } struct Baz { - f: &'static int, + f: &'static isize, } impl Drop for Baz { diff --git a/src/test/compile-fail/kindck-impl-type-params-2.rs b/src/test/compile-fail/kindck-impl-type-params-2.rs index 9e7c983195a..cd47bd721fc 100644 --- a/src/test/compile-fail/kindck-impl-type-params-2.rs +++ b/src/test/compile-fail/kindck-impl-type-params-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + trait Foo { } @@ -17,7 +19,7 @@ impl<T:Copy> Foo for T { fn take_param<T:Foo>(foo: &T) { } fn main() { - let x = box 3i; + let x = box 3is; take_param(&x); //~^ ERROR the trait `core::marker::Copy` is not implemented } diff --git a/src/test/compile-fail/kindck-impl-type-params.rs b/src/test/compile-fail/kindck-impl-type-params.rs index 6ecf2593d00..5d090689415 100644 --- a/src/test/compile-fail/kindck-impl-type-params.rs +++ b/src/test/compile-fail/kindck-impl-type-params.rs @@ -11,6 +11,8 @@ // Issue #14061: tests the interaction between generic implementation // parameter bounds and trait objects. +#![feature(box_syntax)] + struct S<T>; trait Gettable<T> {} @@ -32,8 +34,8 @@ fn g<T>(val: T) { } fn foo<'a>() { - let t: S<&'a int> = S; - let a = &t as &Gettable<&'a int>; + let t: S<&'a isize> = S; + let a = &t as &Gettable<&'a isize>; //~^ ERROR declared lifetime bound not satisfied } diff --git a/src/test/compile-fail/kindck-inherited-copy-bound.rs b/src/test/compile-fail/kindck-inherited-copy-bound.rs index 7f610176b65..4ccb240071d 100644 --- a/src/test/compile-fail/kindck-inherited-copy-bound.rs +++ b/src/test/compile-fail/kindck-inherited-copy-bound.rs @@ -10,6 +10,8 @@ // Test that Copy bounds inherited by trait are checked. +#![feature(box_syntax)] + use std::any::Any; trait Foo : Copy { @@ -21,12 +23,12 @@ impl<T:Copy> Foo for T { fn take_param<T:Foo>(foo: &T) { } fn a() { - let x = box 3i; + let x = box 3is; take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { - let x = box 3i; + let x = box 3is; let y = &x; let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } diff --git a/src/test/compile-fail/kindck-nonsendable-1.rs b/src/test/compile-fail/kindck-nonsendable-1.rs index a13a3f7c4ab..79aec386d9a 100644 --- a/src/test/compile-fail/kindck-nonsendable-1.rs +++ b/src/test/compile-fail/kindck-nonsendable-1.rs @@ -11,12 +11,12 @@ use std::rc::Rc; -fn foo(_x: Rc<uint>) {} +fn foo(_x: Rc<usize>) {} fn bar<F:FnOnce() + Send>(_: F) { } fn main() { - let x = Rc::new(3u); + let x = Rc::new(3us); bar(move|| foo(x)); //~^ ERROR `core::marker::Send` is not implemented //~^^ ERROR `core::marker::Send` is not implemented diff --git a/src/test/compile-fail/kindck-send-owned.rs b/src/test/compile-fail/kindck-send-owned.rs index 11148d2846c..7025249fafb 100644 --- a/src/test/compile-fail/kindck-send-owned.rs +++ b/src/test/compile-fail/kindck-send-owned.rs @@ -13,13 +13,13 @@ fn assert_send<T:Send>() { } // owned content are ok -fn test30() { assert_send::<Box<int>>(); } +fn test30() { assert_send::<Box<isize>>(); } fn test31() { assert_send::<String>(); } -fn test32() { assert_send::<Vec<int> >(); } +fn test32() { assert_send::<Vec<isize> >(); } // but not if they own a bad thing -fn test40<'a>(_: &'a int) { - assert_send::<Box<&'a int>>(); //~ ERROR declared lifetime bound not satisfied +fn test40<'a>(_: &'a isize) { + assert_send::<Box<&'a isize>>(); //~ ERROR declared lifetime bound not satisfied } fn main() { } diff --git a/src/test/compile-fail/kindck-send-region-pointers.rs b/src/test/compile-fail/kindck-send-region-pointers.rs index 04172932cfe..c6987e89e3a 100644 --- a/src/test/compile-fail/kindck-send-region-pointers.rs +++ b/src/test/compile-fail/kindck-send-region-pointers.rs @@ -13,22 +13,22 @@ fn assert_send<T:Send>() { } // lifetime pointers with 'static lifetime are ok -fn test01() { assert_send::<&'static int>(); } +fn test01() { assert_send::<&'static isize>(); } fn test02() { assert_send::<&'static str>(); } -fn test03() { assert_send::<&'static [int]>(); } +fn test03() { assert_send::<&'static [isize]>(); } // whether or not they are mutable -fn test10() { assert_send::<&'static mut int>(); } +fn test10() { assert_send::<&'static mut isize>(); } // otherwise lifetime pointers are not ok -fn test20<'a>(_: &'a int) { - assert_send::<&'a int>(); //~ ERROR declared lifetime bound not satisfied +fn test20<'a>(_: &'a isize) { + assert_send::<&'a isize>(); //~ ERROR declared lifetime bound not satisfied } -fn test21<'a>(_: &'a int) { +fn test21<'a>(_: &'a isize) { assert_send::<&'a str>(); //~ ERROR declared lifetime bound not satisfied } -fn test22<'a>(_: &'a int) { - assert_send::<&'a [int]>(); //~ ERROR declared lifetime bound not satisfied +fn test22<'a>(_: &'a isize) { + assert_send::<&'a [isize]>(); //~ ERROR declared lifetime bound not satisfied } fn main() { } diff --git a/src/test/compile-fail/kindck-send-unsafe.rs b/src/test/compile-fail/kindck-send-unsafe.rs index 1bfd0d4a11f..bce765a986a 100644 --- a/src/test/compile-fail/kindck-send-unsafe.rs +++ b/src/test/compile-fail/kindck-send-unsafe.rs @@ -13,7 +13,7 @@ extern crate core; fn assert_send<T:Send>() { } fn test71<'a>() { - assert_send::<*mut &'a int>(); + assert_send::<*mut &'a isize>(); //~^ ERROR the trait `core::marker::Send` is not implemented for the type } diff --git a/src/test/compile-fail/lang-item-missing.rs b/src/test/compile-fail/lang-item-missing.rs index bcde10a0b22..793d9c77c3b 100644 --- a/src/test/compile-fail/lang-item-missing.rs +++ b/src/test/compile-fail/lang-item-missing.rs @@ -16,6 +16,6 @@ #![no_std] #[start] -fn start(argc: int, argv: *const *const u8) -> int { +fn start(argc: isize, argv: *const *const u8) -> isize { 0 } diff --git a/src/test/compile-fail/lifetime-elision-return-type-requires-explicit-lifetime.rs b/src/test/compile-fail/lifetime-elision-return-type-requires-explicit-lifetime.rs index 817582a877f..55cce016335 100644 --- a/src/test/compile-fail/lifetime-elision-return-type-requires-explicit-lifetime.rs +++ b/src/test/compile-fail/lifetime-elision-return-type-requires-explicit-lifetime.rs @@ -9,29 +9,29 @@ // except according to those terms. // Lifetime annotation needed because we have no arguments. -fn f() -> &int { //~ ERROR missing lifetime specifier +fn f() -> &isize { //~ ERROR missing lifetime specifier //~^ HELP there is no value for it to be borrowed from panic!() } // Lifetime annotation needed because we have two by-reference parameters. -fn g(_x: &int, _y: &int) -> &int { //~ ERROR missing lifetime specifier +fn g(_x: &isize, _y: &isize) -> &isize { //~ ERROR missing lifetime specifier //~^ HELP the signature does not say whether it is borrowed from `_x` or `_y` panic!() } struct Foo<'a> { - x: &'a int, + x: &'a isize, } // Lifetime annotation needed because we have two lifetimes: one as a parameter // and one on the reference. -fn h(_x: &Foo) -> &int { //~ ERROR missing lifetime specifier +fn h(_x: &Foo) -> &isize { //~ ERROR missing lifetime specifier //~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from panic!() } -fn i(_x: int) -> &int { //~ ERROR missing lifetime specifier +fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier //~^ HELP this function's return type contains a borrowed value panic!() } diff --git a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-2.rs b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-2.rs index 7d91b1998bf..fac518c7635 100644 --- a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-2.rs +++ b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-2.rs @@ -14,15 +14,15 @@ use std::iter::{Range,range}; trait Itble<'r, T, I: Iterator<Item=T>> { fn iter(&'r self) -> I; } -impl<'r> Itble<'r, uint, Range<uint>> for (uint, uint) { - fn iter(&'r self) -> Range<uint> { +impl<'r> Itble<'r, usize, Range<usize>> for (usize, usize) { + fn iter(&'r self) -> Range<usize> { let &(min, max) = self; range(min, max) } } -fn check<'r, I: Iterator<Item=uint>, T: Itble<'r, uint, I>>(cont: &T) -> bool { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn check<'r, I: Iterator<Item = uint>, T: Itble<'r, uint, I>>(cont: &'r T) +fn check<'r, I: Iterator<Item=usize>, T: Itble<'r, usize, I>>(cont: &T) -> bool { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn check<'r, I: Iterator<Item = usize>, T: Itble<'r, usize, I>>(cont: &'r T) let cont_iter = cont.iter(); //~ ERROR: cannot infer let result = cont_iter.fold(Some(0u16), |state, val| { state.map_or(None, |mask| { diff --git a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-3.rs b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-3.rs index 29265b8750c..04c5b223cb8 100644 --- a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-3.rs +++ b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param-3.rs @@ -10,17 +10,17 @@ // ignore-tidy-linelength -struct Bar<'x, 'y, 'z> { bar: &'y int, baz: int } -fn bar1<'a>(x: &Bar) -> (&'a int, &'a int, &'a int) { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn bar1<'b, 'c, 'a>(x: &'a Bar<'b, 'a, 'c>) -> (&'a int, &'a int, &'a int) +struct Bar<'x, 'y, 'z> { bar: &'y i32, baz: i32 } +fn bar1<'a>(x: &Bar) -> (&'a i32, &'a i32, &'a i32) { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn bar1<'b, 'c, 'a>(x: &'a Bar<'b, 'a, 'c>) -> (&'a i32, &'a i32, &'a i32) (x.bar, &x.baz, &x.baz) //~^ ERROR: cannot infer //~^^ ERROR: cannot infer //~^^^ ERROR: cannot infer } -fn bar2<'a, 'b, 'c>(x: &Bar<'a, 'b, 'c>) -> (&'a int, &'a int, &'a int) { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn bar2<'a, 'c>(x: &'a Bar<'a, 'a, 'c>) -> (&'a int, &'a int, &'a int) +fn bar2<'a, 'b, 'c>(x: &Bar<'a, 'b, 'c>) -> (&'a i32, &'a i32, &'a i32) { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn bar2<'a, 'c>(x: &'a Bar<'a, 'a, 'c>) -> (&'a i32, &'a i32, &'a i32) (x.bar, &x.baz, &x.baz) //~^ ERROR: cannot infer //~^^ ERROR: cannot infer diff --git a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param.rs b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param.rs index 4abf045501c..c60e321219b 100644 --- a/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param.rs +++ b/src/test/compile-fail/lifetime-inference-give-expl-lifetime-param.rs @@ -10,43 +10,43 @@ // ignore-tidy-linelength -struct Foo<'x> { bar: int } -fn foo1<'a>(x: &Foo) -> &'a int { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo1<'a>(x: &'a Foo) -> &'a int +struct Foo<'x> { bar: isize } +fn foo1<'a>(x: &Foo) -> &'a isize { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo1<'a>(x: &'a Foo) -> &'a isize &x.bar //~ ERROR: cannot infer } -fn foo2<'a, 'b>(x: &'a Foo) -> &'b int { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo2<'a>(x: &'a Foo) -> &'a int +fn foo2<'a, 'b>(x: &'a Foo) -> &'b isize { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo2<'a>(x: &'a Foo) -> &'a isize &x.bar //~ ERROR: cannot infer } -fn foo3<'a>(x: &Foo) -> (&'a int, &'a int) { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo3<'a>(x: &'a Foo) -> (&'a int, &'a int) +fn foo3<'a>(x: &Foo) -> (&'a isize, &'a isize) { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo3<'a>(x: &'a Foo) -> (&'a isize, &'a isize) (&x.bar, &x.bar) //~ ERROR: cannot infer //~^ ERROR: cannot infer } -fn foo4<'a, 'b>(x: &'a Foo) -> (&'b int, &'a int, &'b int) { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo4<'a>(x: &'a Foo) -> (&'a int, &'a int, &'a int) +fn foo4<'a, 'b>(x: &'a Foo) -> (&'b isize, &'a isize, &'b isize) { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo4<'a>(x: &'a Foo) -> (&'a isize, &'a isize, &'a isize) (&x.bar, &x.bar, &x.bar) //~ ERROR: cannot infer //~^ ERROR: cannot infer } -struct Cat<'x, T> { cat: &'x int, t: T } -struct Dog<'y> { dog: &'y int } +struct Cat<'x, T> { cat: &'x isize, t: T } +struct Dog<'y> { dog: &'y isize } -fn cat2<'x, 'y>(x: Cat<'x, Dog<'y>>) -> &'x int { -//~^ HELP: consider using an explicit lifetime parameter as shown: fn cat2<'x>(x: Cat<'x, Dog<'x>>) -> &'x int +fn cat2<'x, 'y>(x: Cat<'x, Dog<'y>>) -> &'x isize { +//~^ HELP: consider using an explicit lifetime parameter as shown: fn cat2<'x>(x: Cat<'x, Dog<'x>>) -> &'x isize x.t.dog //~ ERROR: cannot infer } struct Baz<'x> { - bar: &'x int + bar: &'x isize } impl<'a> Baz<'a> { - fn baz2<'b>(&self, x: &int) -> (&'b int, &'b int) { + fn baz2<'b>(&self, x: &isize) -> (&'b isize, &'b isize) { // The lifetime that gets assigned to `x` seems somewhat random. // I have disabled this test for the time being. --pcwalton (self.bar, x) //~ ERROR: cannot infer diff --git a/src/test/compile-fail/lifetime-no-keyword.rs b/src/test/compile-fail/lifetime-no-keyword.rs index 0ef13d73fab..8ffbcd90df8 100644 --- a/src/test/compile-fail/lifetime-no-keyword.rs +++ b/src/test/compile-fail/lifetime-no-keyword.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo<'a>(a: &'a int) { } -fn bar(a: &'static int) { } -fn baz(a: &'let int) { } //~ ERROR invalid lifetime name +fn foo<'a>(a: &'a isize) { } +fn bar(a: &'static isize) { } +fn baz(a: &'let isize) { } //~ ERROR invalid lifetime name fn main() { } diff --git a/src/test/compile-fail/lifetime-obsoleted-self.rs b/src/test/compile-fail/lifetime-obsoleted-self.rs index a99daaab249..766922f2f88 100644 --- a/src/test/compile-fail/lifetime-obsoleted-self.rs +++ b/src/test/compile-fail/lifetime-obsoleted-self.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn baz(a: &'self int) { } //~ ERROR invalid lifetime name: 'self is no longer a special lifetime +fn baz(a: &'self isize) { } //~ ERROR invalid lifetime name: 'self is no longer a special lifetime fn main() { } diff --git a/src/test/compile-fail/linkage1.rs b/src/test/compile-fail/linkage1.rs index a045b838d51..555cc2b9a7a 100644 --- a/src/test/compile-fail/linkage1.rs +++ b/src/test/compile-fail/linkage1.rs @@ -9,6 +9,6 @@ // except according to those terms. extern { - #[linkage = "extern_weak"] static foo: int; + #[linkage = "extern_weak"] static foo: isize; //~^ ERROR: the `linkage` attribute is experimental and not portable } diff --git a/src/test/compile-fail/linkage4.rs b/src/test/compile-fail/linkage4.rs index 8f68f3e553c..635d58e04c7 100644 --- a/src/test/compile-fail/linkage4.rs +++ b/src/test/compile-fail/linkage4.rs @@ -9,7 +9,7 @@ // except according to those terms. #[linkage = "external"] -static foo: int = 0; +static foo: isize = 0; //~^ ERROR: the `linkage` attribute is experimental and not portable fn main() {} diff --git a/src/test/compile-fail/lint-ctypes.rs b/src/test/compile-fail/lint-ctypes.rs index 1755a9a2481..801f9dfd1cf 100644 --- a/src/test/compile-fail/lint-ctypes.rs +++ b/src/test/compile-fail/lint-ctypes.rs @@ -13,10 +13,10 @@ extern crate libc; extern { - pub fn bare_type1(size: int); //~ ERROR: found rust type - pub fn bare_type2(size: uint); //~ ERROR: found rust type - pub fn ptr_type1(size: *const int); //~ ERROR: found rust type - pub fn ptr_type2(size: *const uint); //~ ERROR: found rust type + pub fn bare_type1(size: isize); //~ ERROR: found rust type + pub fn bare_type2(size: usize); //~ ERROR: found rust type + pub fn ptr_type1(size: *const isize); //~ ERROR: found rust type + pub fn ptr_type2(size: *const usize); //~ ERROR: found rust type pub fn good1(size: *const libc::c_int); pub fn good2(size: *const libc::c_uint); diff --git a/src/test/compile-fail/lint-dead-code-1.rs b/src/test/compile-fail/lint-dead-code-1.rs index 9e5f15c2721..34c79be7118 100644 --- a/src/test/compile-fail/lint-dead-code-1.rs +++ b/src/test/compile-fail/lint-dead-code-1.rs @@ -29,28 +29,28 @@ mod foo2 { pub struct Bar2; } -pub static pub_static: int = 0; -static priv_static: int = 0; //~ ERROR: static item is never used -const used_static: int = 0; -pub static used_static2: int = used_static; -const USED_STATIC: int = 0; -const STATIC_USED_IN_ENUM_DISCRIMINANT: int = 10; - -pub const pub_const: int = 0; -const priv_const: int = 0; //~ ERROR: constant item is never used -const used_const: int = 0; -pub const used_const2: int = used_const; -const USED_CONST: int = 1; -const CONST_USED_IN_ENUM_DISCRIMINANT: int = 11; +pub static pub_static: isize = 0; +static priv_static: isize = 0; //~ ERROR: static item is never used +const used_static: isize = 0; +pub static used_static2: isize = used_static; +const USED_STATIC: isize = 0; +const STATIC_USED_IN_ENUM_DISCRIMINANT: isize = 10; + +pub const pub_const: isize = 0; +const priv_const: isize = 0; //~ ERROR: constant item is never used +const used_const: isize = 0; +pub const used_const2: isize = used_const; +const USED_CONST: isize = 1; +const CONST_USED_IN_ENUM_DISCRIMINANT: isize = 11; pub type typ = *const UsedStruct4; pub struct PubStruct; struct PrivStruct; //~ ERROR: struct is never used struct UsedStruct1 { #[allow(dead_code)] - x: int + x: isize } -struct UsedStruct2(int); +struct UsedStruct2(isize); struct UsedStruct3; struct UsedStruct4; // this struct is never used directly, but its method is, so we don't want @@ -90,7 +90,7 @@ pub fn pub_fn() { let e = used_enum::foo3; SemiUsedStruct::la_la_la(); - let i = 1i; + let i = 1is; match i { USED_STATIC => (), USED_CONST => (), diff --git a/src/test/compile-fail/lint-dead-code-2.rs b/src/test/compile-fail/lint-dead-code-2.rs index c7199eec8a3..e8b85ffd69a 100644 --- a/src/test/compile-fail/lint-dead-code-2.rs +++ b/src/test/compile-fail/lint-dead-code-2.rs @@ -36,7 +36,7 @@ fn dead_fn2() {} //~ ERROR: function is never used fn used_fn() {} #[start] -fn start(_: int, _: *const *const u8) -> int { +fn start(_: isize, _: *const *const u8) -> isize { used_fn(); let foo = Foo; foo.bar2(); diff --git a/src/test/compile-fail/lint-dead-code-3.rs b/src/test/compile-fail/lint-dead-code-3.rs index 4ef76030bcc..03b89c522ce 100644 --- a/src/test/compile-fail/lint-dead-code-3.rs +++ b/src/test/compile-fail/lint-dead-code-3.rs @@ -79,12 +79,12 @@ mod inner { fn f(&self) { f(); } } - impl Trait for int {} + impl Trait for isize {} fn f() {} } pub fn foo() { - let a = &1i as &inner::Trait; + let a = &1is as &inner::Trait; a.f(); } diff --git a/src/test/compile-fail/lint-dead-code-4.rs b/src/test/compile-fail/lint-dead-code-4.rs index 21e1ab4c33e..ac8f158f8fb 100644 --- a/src/test/compile-fail/lint-dead-code-4.rs +++ b/src/test/compile-fail/lint-dead-code-4.rs @@ -17,12 +17,12 @@ extern crate libc; use std::num::Int; struct Foo { - x: uint, + x: usize, b: bool, //~ ERROR: struct field is never used marker: std::marker::NoCopy } -fn field_read(f: Foo) -> uint { +fn field_read(f: Foo) -> usize { f.x.pow(2) } @@ -30,7 +30,7 @@ enum XYZ { X, //~ ERROR variant is never used Y { //~ ERROR variant is never used a: String, - b: int //~ ERROR: struct field is never used + b: isize //~ ERROR: struct field is never used }, Z } @@ -43,7 +43,7 @@ fn field_match_in_patterns(b: XYZ) -> String { } struct Bar { - x: uint, //~ ERROR: struct field is never used + x: usize, //~ ERROR: struct field is never used b: bool, _guard: () } @@ -61,6 +61,6 @@ fn field_match_in_let(f: Bar) -> bool { fn main() { field_read(Foo { x: 1, b: false, marker: std::marker::NoCopy }); field_match_in_patterns(XYZ::Z); - field_match_in_let(Bar { x: 42u, b: true, _guard: () }); + field_match_in_let(Bar { x: 42us, b: true, _guard: () }); let _ = Baz { x: 0 }; } diff --git a/src/test/compile-fail/lint-dead-code-5.rs b/src/test/compile-fail/lint-dead-code-5.rs index d6a31c96100..04d6547d938 100644 --- a/src/test/compile-fail/lint-dead-code-5.rs +++ b/src/test/compile-fail/lint-dead-code-5.rs @@ -12,16 +12,16 @@ #![deny(dead_code)] enum Enum1 { - Variant1(int), + Variant1(isize), Variant2 //~ ERROR: variant is never used } enum Enum2 { Variant3(bool), #[allow(dead_code)] - Variant4(int), - Variant5 { _x: int }, //~ ERROR: variant is never used: `Variant5` - Variant6(int), //~ ERROR: variant is never used: `Variant6` + Variant4(isize), + Variant5 { _x: isize }, //~ ERROR: variant is never used: `Variant5` + Variant6(isize), //~ ERROR: variant is never used: `Variant6` _Variant7, } diff --git a/src/test/compile-fail/lint-directives-on-use-items-issue-10534.rs b/src/test/compile-fail/lint-directives-on-use-items-issue-10534.rs index efb28449564..18159aec708 100644 --- a/src/test/compile-fail/lint-directives-on-use-items-issue-10534.rs +++ b/src/test/compile-fail/lint-directives-on-use-items-issue-10534.rs @@ -16,7 +16,7 @@ // ignored. #[allow(dead_code)] -mod a { pub static x: int = 3; pub static y: int = 4; } +mod a { pub static x: isize = 3; pub static y: isize = 4; } mod b { use a::x; //~ ERROR: unused import diff --git a/src/test/compile-fail/lint-exceeding-bitshifts.rs b/src/test/compile-fail/lint-exceeding-bitshifts.rs index dbb65d8b7ce..91a4d0fea0a 100644 --- a/src/test/compile-fail/lint-exceeding-bitshifts.rs +++ b/src/test/compile-fail/lint-exceeding-bitshifts.rs @@ -56,7 +56,7 @@ fn main() { let n = 1u8 << (4+3); let n = 1u8 << (4+4); //~ ERROR: bitshift exceeds the type's number of bits - let n = 1i << std::int::BITS; //~ ERROR: bitshift exceeds the type's number of bits - let n = 1u << std::uint::BITS; //~ ERROR: bitshift exceeds the type's number of bits + let n = 1is << std::isize::BITS; //~ ERROR: bitshift exceeds the type's number of bits + let n = 1us << std::usize::BITS; //~ ERROR: bitshift exceeds the type's number of bits } diff --git a/src/test/compile-fail/lint-forbid-attr.rs b/src/test/compile-fail/lint-forbid-attr.rs index 92fabd6050b..d1fcf62115b 100644 --- a/src/test/compile-fail/lint-forbid-attr.rs +++ b/src/test/compile-fail/lint-forbid-attr.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![forbid(experimental)] +#![forbid(unstable)] -#[allow(experimental)] //~ ERROR allow(experimental) overruled by outer forbid(experimental) +#[allow(unstable)] //~ ERROR allow(unstable) overruled by outer forbid(unstable) fn main() { } diff --git a/src/test/compile-fail/lint-forbid-cmdline.rs b/src/test/compile-fail/lint-forbid-cmdline.rs index 4de84825ada..e3be0d06a35 100644 --- a/src/test/compile-fail/lint-forbid-cmdline.rs +++ b/src/test/compile-fail/lint-forbid-cmdline.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags: -F experimental +// compile-flags: -F unstable -#[allow(experimental)] //~ ERROR allow(experimental) overruled by outer forbid(experimental) +#![staged_api] +#[allow(unstable)] //~ ERROR allow(unstable) overruled by outer forbid(unstable) fn main() { } diff --git a/src/test/compile-fail/lint-group-style.rs b/src/test/compile-fail/lint-group-style.rs index 63d65fc06aa..24d16bcaafc 100644 --- a/src/test/compile-fail/lint-group-style.rs +++ b/src/test/compile-fail/lint-group-style.rs @@ -24,7 +24,7 @@ mod test { mod bad { fn CamelCase() {} //~ ERROR function `CamelCase` should have a snake case name - static bad: int = 1; //~ ERROR static constant `bad` should have an uppercase name + static bad: isize = 1; //~ ERROR static constant `bad` should have an uppercase name } mod warn { diff --git a/src/test/compile-fail/lint-impl-fn.rs b/src/test/compile-fail/lint-impl-fn.rs index eaef43a9083..608aec327b6 100644 --- a/src/test/compile-fail/lint-impl-fn.rs +++ b/src/test/compile-fail/lint-impl-fn.rs @@ -11,7 +11,7 @@ #![allow(while_true)] #![allow(dead_code)] -struct A(int); +struct A(isize); impl A { fn foo(&self) { while true {} } @@ -22,7 +22,7 @@ impl A { #[deny(while_true)] mod foo { - struct B(int); + struct B(isize); impl B { fn foo(&self) { while true {} } //~ ERROR: infinite loops diff --git a/src/test/compile-fail/lint-missing-doc.rs b/src/test/compile-fail/lint-missing-doc.rs index e50f636050c..55103f10f2c 100644 --- a/src/test/compile-fail/lint-missing-doc.rs +++ b/src/test/compile-fail/lint-missing-doc.rs @@ -21,19 +21,19 @@ type Typedef = String; pub type PubTypedef = String; //~ ERROR: missing documentation struct Foo { - a: int, - b: int, + a: isize, + b: isize, } pub struct PubFoo { //~ ERROR: missing documentation - pub a: int, //~ ERROR: missing documentation - b: int, + pub a: isize, //~ ERROR: missing documentation + b: isize, } #[allow(missing_docs)] pub struct PubFoo2 { - pub a: int, - pub c: int, + pub a: isize, + pub c: isize, } mod module_no_dox {} @@ -100,15 +100,15 @@ mod a { enum Baz { BazA { - a: int, - b: int + a: isize, + b: isize }, BarB } pub enum PubBaz { //~ ERROR: missing documentation PubBazA { //~ ERROR: missing documentation - a: int, //~ ERROR: missing documentation + a: isize, //~ ERROR: missing documentation }, } @@ -117,14 +117,14 @@ pub enum PubBaz2 { /// dox PubBaz2A { /// dox - a: int, + a: isize, }, } #[allow(missing_docs)] pub enum PubBaz3 { PubBaz3A { - b: int + b: isize }, } diff --git a/src/test/compile-fail/lint-non-camel-case-types.rs b/src/test/compile-fail/lint-non-camel-case-types.rs index 6ce63e2ecdb..70d6b240985 100644 --- a/src/test/compile-fail/lint-non-camel-case-types.rs +++ b/src/test/compile-fail/lint-non-camel-case-types.rs @@ -12,7 +12,7 @@ #![allow(dead_code)] struct foo { //~ ERROR type `foo` should have a camel case name such as `Foo` - bar: int, + bar: isize, } enum foo2 { //~ ERROR type `foo2` should have a camel case name such as `Foo2` @@ -20,10 +20,10 @@ enum foo2 { //~ ERROR type `foo2` should have a camel case name such as `Foo2` } struct foo3 { //~ ERROR type `foo3` should have a camel case name such as `Foo3` - bar: int + bar: isize } -type foo4 = int; //~ ERROR type `foo4` should have a camel case name such as `Foo4` +type foo4 = isize; //~ ERROR type `foo4` should have a camel case name such as `Foo4` enum Foo5 { bar //~ ERROR variant `bar` should have a camel case name such as `Bar` @@ -36,9 +36,9 @@ fn f<ty>(_: ty) {} //~ ERROR type parameter `ty` should have a camel case name s #[repr(C)] struct foo7 { - bar: int, + bar: isize, } -type __ = int; //~ ERROR type `__` should have a camel case name such as `CamelCase` +type __ = isize; //~ ERROR type `__` should have a camel case name such as `CamelCase` fn main() { } diff --git a/src/test/compile-fail/lint-non-uppercase-statics.rs b/src/test/compile-fail/lint-non-uppercase-statics.rs index 7ff5cafd097..10475f967d7 100644 --- a/src/test/compile-fail/lint-non-uppercase-statics.rs +++ b/src/test/compile-fail/lint-non-uppercase-statics.rs @@ -11,6 +11,6 @@ #![forbid(non_upper_case_globals)] #![allow(dead_code)] -static foo: int = 1; //~ ERROR static constant `foo` should have an uppercase name such as `FOO` +static foo: isize = 1; //~ ERROR static constant `foo` should have an uppercase name such as `FOO` fn main() { } diff --git a/src/test/compile-fail/lint-output-format.rs b/src/test/compile-fail/lint-output-format.rs index 35721ee5b14..10217481bf3 100644 --- a/src/test/compile-fail/lint-output-format.rs +++ b/src/test/compile-fail/lint-output-format.rs @@ -8,14 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags:-F experimental -D unstable +// compile-flags:-F unstable // aux-build:lint_output_format.rs extern crate lint_output_format; //~ ERROR: use of unmarked item -use lint_output_format::{foo, bar, baz}; +use lint_output_format::{foo, bar}; fn main() { let _x = foo(); //~ WARNING #[warn(deprecated)] on by default - let _y = bar(); //~ ERROR [-F experimental] - let _z = baz(); //~ ERROR [-D unstable] + let _y = bar(); //~ ERROR [-F unstable] } diff --git a/src/test/compile-fail/lint-owned-heap-memory.rs b/src/test/compile-fail/lint-owned-heap-memory.rs index 5ee16f0aa26..9c68da8beaf 100644 --- a/src/test/compile-fail/lint-owned-heap-memory.rs +++ b/src/test/compile-fail/lint-owned-heap-memory.rs @@ -10,10 +10,10 @@ #![allow(dead_code)] #![forbid(box_pointers)] - +#![feature(box_syntax)] struct Foo { - x: Box<int> //~ ERROR type uses owned + x: Box<isize> //~ ERROR type uses owned } fn main() { diff --git a/src/test/compile-fail/lint-raw-ptr-derive.rs b/src/test/compile-fail/lint-raw-ptr-derive.rs index 3198e782df8..4320b3e7441 100644 --- a/src/test/compile-fail/lint-raw-ptr-derive.rs +++ b/src/test/compile-fail/lint-raw-ptr-derive.rs @@ -13,22 +13,22 @@ #[derive(Clone)] struct Foo { - x: *const int //~ ERROR use of `#[derive]` with a raw pointer + x: *const isize //~ ERROR use of `#[derive]` with a raw pointer } #[derive(Clone)] -struct Bar(*mut int); //~ ERROR use of `#[derive]` with a raw pointer +struct Bar(*mut isize); //~ ERROR use of `#[derive]` with a raw pointer #[derive(Clone)] enum Baz { - A(*const int), //~ ERROR use of `#[derive]` with a raw pointer - B { x: *mut int } //~ ERROR use of `#[derive]` with a raw pointer + A(*const isize), //~ ERROR use of `#[derive]` with a raw pointer + B { x: *mut isize } //~ ERROR use of `#[derive]` with a raw pointer } #[derive(Clone)] struct Buzz { - x: (*const int, //~ ERROR use of `#[derive]` with a raw pointer - *const uint) //~ ERROR use of `#[derive]` with a raw pointer + x: (*const isize, //~ ERROR use of `#[derive]` with a raw pointer + *const usize) //~ ERROR use of `#[derive]` with a raw pointer } fn main() {} diff --git a/src/test/compile-fail/lint-shorthand-field.rs b/src/test/compile-fail/lint-shorthand-field.rs index eb4da4d66f3..97a976a493f 100644 --- a/src/test/compile-fail/lint-shorthand-field.rs +++ b/src/test/compile-fail/lint-shorthand-field.rs @@ -12,8 +12,8 @@ #![deny(non_shorthand_field_patterns)] struct Foo { - x: int, - y: int, + x: isize, + y: isize, } fn main() { @@ -30,7 +30,7 @@ fn main() { } { - const x: int = 1; + const x: isize = 1; match (Foo { x: 1, y: 1 }) { Foo { x: x, ..} => {}, diff --git a/src/test/compile-fail/lint-stability.rs b/src/test/compile-fail/lint-stability.rs index 0e24269ec44..eab5e98d68f 100644 --- a/src/test/compile-fail/lint-stability.rs +++ b/src/test/compile-fail/lint-stability.rs @@ -15,15 +15,16 @@ #![deny(unstable)] #![deny(deprecated)] -#![deny(experimental)] +#![deny(unstable)] #![allow(dead_code)] +#![staged_api] #[macro_use] extern crate lint_stability; //~ ERROR: use of unmarked item mod cross_crate { extern crate stability_cfg1; - extern crate stability_cfg2; //~ ERROR: use of experimental item + extern crate stability_cfg2; //~ ERROR: use of unstable item use lint_stability::*; @@ -38,13 +39,13 @@ mod cross_crate { foo.method_deprecated_text(); //~ ERROR use of deprecated item: text foo.trait_deprecated_text(); //~ ERROR use of deprecated item: text - experimental(); //~ ERROR use of experimental item - foo.method_experimental(); //~ ERROR use of experimental item - foo.trait_experimental(); //~ ERROR use of experimental item + experimental(); //~ ERROR use of unstable item + foo.method_experimental(); //~ ERROR use of unstable item + foo.trait_experimental(); //~ ERROR use of unstable item - experimental_text(); //~ ERROR use of experimental item: text - foo.method_experimental_text(); //~ ERROR use of experimental item: text - foo.trait_experimental_text(); //~ ERROR use of experimental item: text + experimental_text(); //~ ERROR use of unstable item: text + foo.method_experimental_text(); //~ ERROR use of unstable item: text + foo.trait_experimental_text(); //~ ERROR use of unstable item: text unstable(); //~ ERROR use of unstable item foo.method_unstable(); //~ ERROR use of unstable item @@ -83,7 +84,7 @@ mod cross_crate { foo.trait_locked_text(); let _ = DeprecatedStruct { i: 0 }; //~ ERROR use of deprecated item - let _ = ExperimentalStruct { i: 0 }; //~ ERROR use of experimental item + let _ = ExperimentalStruct { i: 0 }; //~ ERROR use of unstable item let _ = UnstableStruct { i: 0 }; //~ ERROR use of unstable item let _ = UnmarkedStruct { i: 0 }; //~ ERROR use of unmarked item let _ = StableStruct { i: 0 }; @@ -91,7 +92,7 @@ mod cross_crate { let _ = LockedStruct { i: 0 }; let _ = DeprecatedUnitStruct; //~ ERROR use of deprecated item - let _ = ExperimentalUnitStruct; //~ ERROR use of experimental item + let _ = ExperimentalUnitStruct; //~ ERROR use of unstable item let _ = UnstableUnitStruct; //~ ERROR use of unstable item let _ = UnmarkedUnitStruct; //~ ERROR use of unmarked item let _ = StableUnitStruct; @@ -99,7 +100,7 @@ mod cross_crate { let _ = LockedUnitStruct; let _ = Enum::DeprecatedVariant; //~ ERROR use of deprecated item - let _ = Enum::ExperimentalVariant; //~ ERROR use of experimental item + let _ = Enum::ExperimentalVariant; //~ ERROR use of unstable item let _ = Enum::UnstableVariant; //~ ERROR use of unstable item let _ = Enum::UnmarkedVariant; //~ ERROR use of unmarked item let _ = Enum::StableVariant; @@ -107,7 +108,7 @@ mod cross_crate { let _ = Enum::LockedVariant; let _ = DeprecatedTupleStruct (1); //~ ERROR use of deprecated item - let _ = ExperimentalTupleStruct (1); //~ ERROR use of experimental item + let _ = ExperimentalTupleStruct (1); //~ ERROR use of unstable item let _ = UnstableTupleStruct (1); //~ ERROR use of unstable item let _ = UnmarkedTupleStruct (1); //~ ERROR use of unmarked item let _ = StableTupleStruct (1); @@ -128,8 +129,8 @@ mod cross_crate { fn test_method_param<F: Trait>(foo: F) { foo.trait_deprecated(); //~ ERROR use of deprecated item foo.trait_deprecated_text(); //~ ERROR use of deprecated item: text - foo.trait_experimental(); //~ ERROR use of experimental item - foo.trait_experimental_text(); //~ ERROR use of experimental item: text + foo.trait_experimental(); //~ ERROR use of unstable item + foo.trait_experimental_text(); //~ ERROR use of unstable item: text foo.trait_unstable(); //~ ERROR use of unstable item foo.trait_unstable_text(); //~ ERROR use of unstable item: text foo.trait_unmarked(); //~ ERROR use of unmarked item @@ -139,8 +140,8 @@ mod cross_crate { fn test_method_object(foo: &Trait) { foo.trait_deprecated(); //~ ERROR use of deprecated item foo.trait_deprecated_text(); //~ ERROR use of deprecated item: text - foo.trait_experimental(); //~ ERROR use of experimental item - foo.trait_experimental_text(); //~ ERROR use of experimental item: text + foo.trait_experimental(); //~ ERROR use of unstable item + foo.trait_experimental_text(); //~ ERROR use of unstable item: text foo.trait_unstable(); //~ ERROR use of unstable item foo.trait_unstable_text(); //~ ERROR use of unstable item: text foo.trait_unmarked(); //~ ERROR use of unmarked item @@ -149,33 +150,33 @@ mod cross_crate { struct S; - impl ExperimentalTrait for S { } //~ ERROR use of experimental item + impl ExperimentalTrait for S { } //~ ERROR use of unstable item - trait LocalTrait : ExperimentalTrait { } //~ ERROR use of experimental item + trait LocalTrait : ExperimentalTrait { } //~ ERROR use of unstable item } mod inheritance { - extern crate inherited_stability; //~ ERROR: use of experimental item + extern crate inherited_stability; //~ ERROR: use of unstable item use self::inherited_stability::*; fn test_inheritance() { - experimental(); //~ ERROR use of experimental item + experimental(); //~ ERROR use of unstable item stable(); - stable_mod::experimental(); //~ ERROR use of experimental item + stable_mod::experimental(); //~ ERROR use of unstable item stable_mod::stable(); - unstable_mod::experimental(); //~ ERROR use of experimental item + unstable_mod::experimental(); //~ ERROR use of unstable item unstable_mod::unstable(); //~ ERROR use of unstable item - experimental_mod::experimental(); //~ ERROR use of experimental item + experimental_mod::experimental(); //~ ERROR use of unstable item experimental_mod::stable(); - let _ = Experimental::ExperimentalVariant; //~ ERROR use of experimental item + let _ = Experimental::ExperimentalVariant; //~ ERROR use of unstable item let _ = Experimental::StableVariant; - let x: uint = 0; - x.experimental(); //~ ERROR use of experimental item + let x: usize = 0; + x.experimental(); //~ ERROR use of unstable item x.stable(); } } @@ -186,9 +187,9 @@ mod this_crate { #[deprecated="text"] pub fn deprecated_text() {} - #[experimental] + #[unstable] pub fn experimental() {} - #[experimental="text"] + #[unstable="text"] pub fn experimental_text() {} #[unstable] @@ -222,9 +223,9 @@ mod this_crate { #[deprecated="text"] pub fn method_deprecated_text(&self) {} - #[experimental] + #[unstable] pub fn method_experimental(&self) {} - #[experimental="text"] + #[unstable="text"] pub fn method_experimental_text(&self) {} #[unstable] @@ -256,9 +257,9 @@ mod this_crate { #[deprecated="text"] fn trait_deprecated_text(&self) {} - #[experimental] + #[unstable] fn trait_experimental(&self) {} - #[experimental="text"] + #[unstable="text"] fn trait_experimental_text(&self) {} #[unstable] @@ -287,22 +288,22 @@ mod this_crate { impl Trait for MethodTester {} #[deprecated] - pub struct DeprecatedStruct { i: int } - #[experimental] - pub struct ExperimentalStruct { i: int } + pub struct DeprecatedStruct { i: isize } + #[unstable] + pub struct ExperimentalStruct { i: isize } #[unstable] - pub struct UnstableStruct { i: int } - pub struct UnmarkedStruct { i: int } + pub struct UnstableStruct { i: isize } + pub struct UnmarkedStruct { i: isize } #[stable] - pub struct StableStruct { i: int } + pub struct StableStruct { i: isize } #[frozen] - pub struct FrozenStruct { i: int } + pub struct FrozenStruct { i: isize } #[locked] - pub struct LockedStruct { i: int } + pub struct LockedStruct { i: isize } #[deprecated] pub struct DeprecatedUnitStruct; - #[experimental] + #[unstable] pub struct ExperimentalUnitStruct; #[unstable] pub struct UnstableUnitStruct; @@ -317,7 +318,7 @@ mod this_crate { pub enum Enum { #[deprecated] DeprecatedVariant, - #[experimental] + #[unstable] ExperimentalVariant, #[unstable] UnstableVariant, @@ -332,18 +333,18 @@ mod this_crate { } #[deprecated] - pub struct DeprecatedTupleStruct(int); - #[experimental] - pub struct ExperimentalTupleStruct(int); + pub struct DeprecatedTupleStruct(isize); + #[unstable] + pub struct ExperimentalTupleStruct(isize); #[unstable] - pub struct UnstableTupleStruct(int); - pub struct UnmarkedTupleStruct(int); + pub struct UnstableTupleStruct(isize); + pub struct UnmarkedTupleStruct(isize); #[stable] - pub struct StableTupleStruct(int); + pub struct StableTupleStruct(isize); #[frozen] - pub struct FrozenTupleStruct(int); + pub struct FrozenTupleStruct(isize); #[locked] - pub struct LockedTupleStruct(int); + pub struct LockedTupleStruct(isize); fn test() { // Only the deprecated cases of the following should generate diff --git a/src/test/compile-fail/lint-type-limits.rs b/src/test/compile-fail/lint-type-limits.rs index 67ef9cd0680..a2bc464ac49 100644 --- a/src/test/compile-fail/lint-type-limits.rs +++ b/src/test/compile-fail/lint-type-limits.rs @@ -14,7 +14,7 @@ fn main() { } fn foo() { - let mut i = 100u; + let mut i = 100us; while i >= 0 { //~ ERROR comparison is useless due to type limits i -= 1; } @@ -50,12 +50,12 @@ fn qux() { } fn quy() { - let i = -23u; //~ WARNING negation of unsigned int literal may be unintentional + let i = -23us; //~ WARNING negation of unsigned int literal may be unintentional //~^ WARNING unused variable } fn quz() { - let i = 23u; + let i = 23us; let j = -i; //~ WARNING negation of unsigned int variable may be unintentional //~^ WARNING unused variable } diff --git a/src/test/compile-fail/lint-unnecessary-parens.rs b/src/test/compile-fail/lint-unnecessary-parens.rs index 1c7a2d7e9d5..4ccc3d8b641 100644 --- a/src/test/compile-fail/lint-unnecessary-parens.rs +++ b/src/test/compile-fail/lint-unnecessary-parens.rs @@ -16,8 +16,8 @@ impl X { fn foo(&self) -> bool { self.y } } -fn foo() -> int { - return (1i); //~ ERROR unnecessary parentheses around `return` value +fn foo() -> isize { + return (1is); //~ ERROR unnecessary parentheses around `return` value } fn bar() -> X { return (X { y: true }); //~ ERROR unnecessary parentheses around `return` value @@ -32,8 +32,8 @@ fn main() { match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } - if let 1i = (1i) {} //~ ERROR unnecessary parentheses around `if let` head expression - while let 1i = (2i) {} //~ ERROR unnecessary parentheses around `while let` head expression + if let 1is = (1is) {} //~ ERROR unnecessary parentheses around `if let` head expression + while let 1is = (2is) {} //~ ERROR unnecessary parentheses around `while let` head expression let v = X { y: false }; // struct lits needs parens, so these shouldn't warn. if (v == X { y: true }) {} @@ -47,7 +47,7 @@ fn main() { _ => {} } - let mut _a = (0i); //~ ERROR unnecessary parentheses around assigned value - _a = (0i); //~ ERROR unnecessary parentheses around assigned value - _a += (1i); //~ ERROR unnecessary parentheses around assigned value + let mut _a = (0is); //~ ERROR unnecessary parentheses around assigned value + _a = (0is); //~ ERROR unnecessary parentheses around assigned value + _a += (1is); //~ ERROR unnecessary parentheses around assigned value } diff --git a/src/test/compile-fail/lint-unused-extern-crate.rs b/src/test/compile-fail/lint-unused-extern-crate.rs index a77de551f5d..c9d34d40479 100644 --- a/src/test/compile-fail/lint-unused-extern-crate.rs +++ b/src/test/compile-fail/lint-unused-extern-crate.rs @@ -28,6 +28,6 @@ use rand::isaac::IsaacRng; use other::*; fn main() { - let x: collecs::vec::Vec<uint> = Vec::new(); + let x: collecs::vec::Vec<usize> = Vec::new(); let y = foo(); } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index b5c0dce6e53..84d7200314f 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -43,8 +43,8 @@ mod test { } mod foo { - pub struct Point{pub x: int, pub y: int} - pub struct Square{pub p: Point, pub h: uint, pub w: uint} + pub struct Point{pub x: isize, pub y: isize} + pub struct Square{pub p: Point, pub h: usize, pub w: usize} } mod bar { @@ -54,7 +54,7 @@ mod bar { pub mod c { use foo::Point; use foo::Square; //~ ERROR unused import - pub fn cc(p: Point) -> int { return 2i * (p.x + p.y); } + pub fn cc(p: Point) -> isize { return 2is * (p.x + p.y); } } #[allow(unused_imports)] @@ -65,8 +65,8 @@ mod bar { fn main() { cal(foo::Point{x:3, y:9}); - let mut a = 3i; - let mut b = 4i; + let mut a = 3is; + let mut b = 4is; swap(&mut a, &mut b); test::C.b(); let _a = foo(); diff --git a/src/test/compile-fail/lint-unused-mut-variables.rs b/src/test/compile-fail/lint-unused-mut-variables.rs index 7513e1bc21a..501eea770d8 100644 --- a/src/test/compile-fail/lint-unused-mut-variables.rs +++ b/src/test/compile-fail/lint-unused-mut-variables.rs @@ -18,16 +18,16 @@ fn main() { // negative cases - let mut a = 3i; //~ ERROR: variable does not need to be mutable - let mut a = 2i; //~ ERROR: variable does not need to be mutable - let mut b = 3i; //~ ERROR: variable does not need to be mutable - let mut a = vec!(3i); //~ ERROR: variable does not need to be mutable - let (mut a, b) = (1i, 2i); //~ ERROR: variable does not need to be mutable + let mut a = 3is; //~ ERROR: variable does not need to be mutable + let mut a = 2is; //~ ERROR: variable does not need to be mutable + let mut b = 3is; //~ ERROR: variable does not need to be mutable + let mut a = vec!(3is); //~ ERROR: variable does not need to be mutable + let (mut a, b) = (1is, 2is); //~ ERROR: variable does not need to be mutable - match 30i { + match 30is { mut x => {} //~ ERROR: variable does not need to be mutable } - match (30i, 2i) { + match (30is, 2is) { (mut x, 1) | //~ ERROR: variable does not need to be mutable (mut x, 2) | (mut x, 3) => { @@ -35,28 +35,28 @@ fn main() { _ => {} } - let x = |&: mut y: int| 10i; //~ ERROR: variable does not need to be mutable - fn what(mut foo: int) {} //~ ERROR: variable does not need to be mutable + let x = |&: mut y: isize| 10is; //~ ERROR: variable does not need to be mutable + fn what(mut foo: isize) {} //~ ERROR: variable does not need to be mutable // positive cases - let mut a = 2i; - a = 3i; + let mut a = 2is; + a = 3is; let mut a = Vec::new(); - a.push(3i); + a.push(3is); let mut a = Vec::new(); callback(|| { - a.push(3i); + a.push(3is); }); - let (mut a, b) = (1i, 2i); + let (mut a, b) = (1is, 2is); a = 34; - match 30i { + match 30is { mut x => { - x = 21i; + x = 21is; } } - match (30i, 2i) { + match (30is, 2is) { (mut x, 1) | (mut x, 2) | (mut x, 3) => { @@ -65,19 +65,19 @@ fn main() { _ => {} } - let x = |&mut: mut y: int| y = 32i; - fn nothing(mut foo: int) { foo = 37i; } + let x = |&mut: mut y: isize| y = 32is; + fn nothing(mut foo: isize) { foo = 37is; } // leading underscore should avoid the warning, just like the // unused variable lint. - let mut _allowed = 1i; + let mut _allowed = 1is; } fn callback<F>(f: F) where F: FnOnce() {} // make sure the lint attribute can be turned off #[allow(unused_mut)] -fn foo(mut a: int) { - let mut a = 3i; - let mut b = vec!(2i); +fn foo(mut a: isize) { + let mut a = 3is; + let mut b = vec!(2is); } diff --git a/src/test/compile-fail/lint-uppercase-variables.rs b/src/test/compile-fail/lint-uppercase-variables.rs index b6eda8635c2..9317e465a7a 100644 --- a/src/test/compile-fail/lint-uppercase-variables.rs +++ b/src/test/compile-fail/lint-uppercase-variables.rs @@ -17,15 +17,15 @@ use std::io::File; use std::io::IoError; struct Something { - X: uint //~ ERROR structure field `X` should have a snake case name such as `x` + X: usize //~ ERROR structure field `X` should have a snake case name such as `x` } -fn test(Xx: uint) { //~ ERROR variable `Xx` should have a snake case name such as `xx` +fn test(Xx: usize) { //~ ERROR variable `Xx` should have a snake case name such as `xx` println!("{}", Xx); } fn main() { - let Test: uint = 0; //~ ERROR variable `Test` should have a snake case name such as `test` + let Test: usize = 0; //~ ERROR variable `Test` should have a snake case name such as `test` println!("{}", Test); let mut f = File::open(&Path::new("something.txt")); diff --git a/src/test/compile-fail/lint-visible-private-types.rs b/src/test/compile-fail/lint-visible-private-types.rs index 373bcb1f859..8cf375f80fb 100644 --- a/src/test/compile-fail/lint-visible-private-types.rs +++ b/src/test/compile-fail/lint-visible-private-types.rs @@ -15,108 +15,108 @@ struct Private<T>; pub struct Public<T>; -impl Private<Public<int>> { - pub fn a(&self) -> Private<int> { panic!() } - fn b(&self) -> Private<int> { panic!() } +impl Private<Public<isize>> { + pub fn a(&self) -> Private<isize> { panic!() } + fn b(&self) -> Private<isize> { panic!() } - pub fn c() -> Private<int> { panic!() } - fn d() -> Private<int> { panic!() } + pub fn c() -> Private<isize> { panic!() } + fn d() -> Private<isize> { panic!() } } -impl Private<int> { - pub fn e(&self) -> Private<int> { panic!() } - fn f(&self) -> Private<int> { panic!() } +impl Private<isize> { + pub fn e(&self) -> Private<isize> { panic!() } + fn f(&self) -> Private<isize> { panic!() } } -impl Public<Private<int>> { - pub fn a(&self) -> Private<int> { panic!() } - fn b(&self) -> Private<int> { panic!() } +impl Public<Private<isize>> { + pub fn a(&self) -> Private<isize> { panic!() } + fn b(&self) -> Private<isize> { panic!() } - pub fn c() -> Private<int> { panic!() } //~ ERROR private type in exported type signature - fn d() -> Private<int> { panic!() } + pub fn c() -> Private<isize> { panic!() } //~ ERROR private type in exported type signature + fn d() -> Private<isize> { panic!() } } -impl Public<int> { - pub fn e(&self) -> Private<int> { panic!() } //~ ERROR private type in exported type signature - fn f(&self) -> Private<int> { panic!() } +impl Public<isize> { + pub fn e(&self) -> Private<isize> { panic!() } //~ ERROR private type in exported type signature + fn f(&self) -> Private<isize> { panic!() } } -pub fn x(_: Private<int>) {} //~ ERROR private type in exported type signature +pub fn x(_: Private<isize>) {} //~ ERROR private type in exported type signature -fn y(_: Private<int>) {} +fn y(_: Private<isize>) {} pub struct Foo { - pub x: Private<int>, //~ ERROR private type in exported type signature - y: Private<int> + pub x: Private<isize>, //~ ERROR private type in exported type signature + y: Private<isize> } struct Bar { - x: Private<int>, + x: Private<isize>, } pub enum Baz { - Baz1(Private<int>), //~ ERROR private type in exported type signature + Baz1(Private<isize>), //~ ERROR private type in exported type signature Baz2 { - y: Private<int> //~ ERROR private type in exported type signature + y: Private<isize> //~ ERROR private type in exported type signature }, } enum Qux { - Qux1(Private<int>), + Qux1(Private<isize>), Qux2 { - x: Private<int>, + x: Private<isize>, } } pub trait PubTrait { - fn foo(&self) -> Private<int> { panic!( )} //~ ERROR private type in exported type signature - fn bar(&self) -> Private<int>; //~ ERROR private type in exported type signature - fn baz() -> Private<int>; //~ ERROR private type in exported type signature + fn foo(&self) -> Private<isize> { panic!( )} //~ ERROR private type in exported type signature + fn bar(&self) -> Private<isize>; //~ ERROR private type in exported type signature + fn baz() -> Private<isize>; //~ ERROR private type in exported type signature } -impl PubTrait for Public<int> { - fn bar(&self) -> Private<int> { panic!() } - fn baz() -> Private<int> { panic!() } +impl PubTrait for Public<isize> { + fn bar(&self) -> Private<isize> { panic!() } + fn baz() -> Private<isize> { panic!() } } -impl PubTrait for Public<Private<int>> { - fn bar(&self) -> Private<int> { panic!() } - fn baz() -> Private<int> { panic!() } +impl PubTrait for Public<Private<isize>> { + fn bar(&self) -> Private<isize> { panic!() } + fn baz() -> Private<isize> { panic!() } } -impl PubTrait for Private<int> { - fn bar(&self) -> Private<int> { panic!() } - fn baz() -> Private<int> { panic!() } +impl PubTrait for Private<isize> { + fn bar(&self) -> Private<isize> { panic!() } + fn baz() -> Private<isize> { panic!() } } -impl PubTrait for (Private<int>,) { - fn bar(&self) -> Private<int> { panic!() } - fn baz() -> Private<int> { panic!() } +impl PubTrait for (Private<isize>,) { + fn bar(&self) -> Private<isize> { panic!() } + fn baz() -> Private<isize> { panic!() } } trait PrivTrait { - fn foo(&self) -> Private<int> { panic!( )} - fn bar(&self) -> Private<int>; + fn foo(&self) -> Private<isize> { panic!( )} + fn bar(&self) -> Private<isize>; } -impl PrivTrait for Private<int> { - fn bar(&self) -> Private<int> { panic!() } +impl PrivTrait for Private<isize> { + fn bar(&self) -> Private<isize> { panic!() } } -impl PrivTrait for (Private<int>,) { - fn bar(&self) -> Private<int> { panic!() } +impl PrivTrait for (Private<isize>,) { + fn bar(&self) -> Private<isize> { panic!() } } pub trait ParamTrait<T> { fn foo() -> T; } -impl ParamTrait<Private<int>> //~ ERROR private type in exported type signature - for Public<int> { - fn foo() -> Private<int> { panic!() } +impl ParamTrait<Private<isize>> //~ ERROR private type in exported type signature + for Public<isize> { + fn foo() -> Private<isize> { panic!() } } -impl ParamTrait<Private<int>> for Private<int> { - fn foo() -> Private<int> { panic!( )} +impl ParamTrait<Private<isize>> for Private<isize> { + fn foo() -> Private<isize> { panic!( )} } -impl<T: ParamTrait<Private<int>>> //~ ERROR private type in exported type signature +impl<T: ParamTrait<Private<isize>>> //~ ERROR private type in exported type signature ParamTrait<T> for Public<i8> { fn foo() -> T { panic!() } } diff --git a/src/test/compile-fail/liveness-assign-imm-local-in-loop.rs b/src/test/compile-fail/liveness-assign-imm-local-in-loop.rs index f8afc10c49b..f50a9345106 100644 --- a/src/test/compile-fail/liveness-assign-imm-local-in-loop.rs +++ b/src/test/compile-fail/liveness-assign-imm-local-in-loop.rs @@ -9,7 +9,7 @@ // except according to those terms. fn test() { - let v: int; + let v: isize; loop { v = 1; //~ ERROR re-assignment of immutable variable //~^ NOTE prior assignment occurs here diff --git a/src/test/compile-fail/liveness-assign-imm-local-in-op-eq.rs b/src/test/compile-fail/liveness-assign-imm-local-in-op-eq.rs index 43d7ca83753..df57bb9e441 100644 --- a/src/test/compile-fail/liveness-assign-imm-local-in-op-eq.rs +++ b/src/test/compile-fail/liveness-assign-imm-local-in-op-eq.rs @@ -9,7 +9,7 @@ // except according to those terms. fn test() { - let v: int; + let v: isize; v = 2; //~ NOTE prior assignment occurs here v += 1; //~ ERROR re-assignment of immutable variable v.clone(); diff --git a/src/test/compile-fail/liveness-assign-imm-local-with-init.rs b/src/test/compile-fail/liveness-assign-imm-local-with-init.rs index 8eb84525b83..28218bff60d 100644 --- a/src/test/compile-fail/liveness-assign-imm-local-with-init.rs +++ b/src/test/compile-fail/liveness-assign-imm-local-with-init.rs @@ -9,7 +9,7 @@ // except according to those terms. fn test() { - let v: int = 1; //~ NOTE prior assignment occurs here + let v: isize = 1; //~ NOTE prior assignment occurs here v.clone(); v = 2; //~ ERROR re-assignment of immutable variable v.clone(); diff --git a/src/test/compile-fail/liveness-bad-bang-2.rs b/src/test/compile-fail/liveness-bad-bang-2.rs index 04364e4e010..bb049175594 100644 --- a/src/test/compile-fail/liveness-bad-bang-2.rs +++ b/src/test/compile-fail/liveness-bad-bang-2.rs @@ -10,8 +10,8 @@ // Tests that a function with a ! annotation always actually fails -fn bad_bang(i: uint) -> ! { //~ ERROR computation may converge in a function marked as diverging - println!("{}", 3i); +fn bad_bang(i: usize) -> ! { //~ ERROR computation may converge in a function marked as diverging + println!("{}", 3is); } -fn main() { bad_bang(5u); } +fn main() { bad_bang(5us); } diff --git a/src/test/compile-fail/liveness-closure-require-ret.rs b/src/test/compile-fail/liveness-closure-require-ret.rs index 82de02f0981..17cd8231222 100644 --- a/src/test/compile-fail/liveness-closure-require-ret.rs +++ b/src/test/compile-fail/liveness-closure-require-ret.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn force<F>(f: F) -> int where F: FnOnce() -> int { f() } +fn force<F>(f: F) -> isize where F: FnOnce() -> isize { f() } fn main() { println!("{}", force(|| {})); } //~ ERROR mismatched types diff --git a/src/test/compile-fail/liveness-dead.rs b/src/test/compile-fail/liveness-dead.rs index 18baf7a9c3f..dc7b0fc4fd0 100644 --- a/src/test/compile-fail/liveness-dead.rs +++ b/src/test/compile-fail/liveness-dead.rs @@ -11,18 +11,18 @@ #![allow(dead_code)] #![deny(unused_assignments)] -fn f1(x: &mut int) { +fn f1(x: &mut isize) { *x = 1; // no error } fn f2() { - let mut x: int = 3; //~ ERROR: value assigned to `x` is never read + let mut x: isize = 3; //~ ERROR: value assigned to `x` is never read x = 4; x.clone(); } fn f3() { - let mut x: int = 3; + let mut x: isize = 3; x.clone(); x = 4; //~ ERROR: value assigned to `x` is never read } diff --git a/src/test/compile-fail/liveness-forgot-ret.rs b/src/test/compile-fail/liveness-forgot-ret.rs index 305cbcad738..e08515e40af 100644 --- a/src/test/compile-fail/liveness-forgot-ret.rs +++ b/src/test/compile-fail/liveness-forgot-ret.rs @@ -10,8 +10,8 @@ // error-pattern: not all control paths return a value -fn god_exists(a: int) -> bool { return god_exists(a); } +fn god_exists(a: isize) -> bool { return god_exists(a); } -fn f(a: int) -> int { if god_exists(a) { return 5; }; } +fn f(a: isize) -> isize { if god_exists(a) { return 5; }; } fn main() { f(12); } diff --git a/src/test/compile-fail/liveness-issue-2163.rs b/src/test/compile-fail/liveness-issue-2163.rs index e46d00c4ab9..69bceec8c32 100644 --- a/src/test/compile-fail/liveness-issue-2163.rs +++ b/src/test/compile-fail/liveness-issue-2163.rs @@ -11,7 +11,7 @@ use std::vec::Vec; fn main() { - let a: Vec<int> = Vec::new(); + let a: Vec<isize> = Vec::new(); a.iter().all(|_| -> bool { //~^ ERROR mismatched types }); diff --git a/src/test/compile-fail/liveness-missing-ret2.rs b/src/test/compile-fail/liveness-missing-ret2.rs index 541e8ec97fa..b53bb6159e8 100644 --- a/src/test/compile-fail/liveness-missing-ret2.rs +++ b/src/test/compile-fail/liveness-missing-ret2.rs @@ -10,7 +10,7 @@ // error-pattern: not all control paths return a value -fn f() -> int { +fn f() -> isize { // Make sure typestate doesn't interpret this match expression as // the function result match true { true => { } _ => {} }; diff --git a/src/test/compile-fail/liveness-move-call-arg.rs b/src/test/compile-fail/liveness-move-call-arg.rs index b9ad1c0fb65..9340964c1fb 100644 --- a/src/test/compile-fail/liveness-move-call-arg.rs +++ b/src/test/compile-fail/liveness-move-call-arg.rs @@ -8,12 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -fn take(_x: Box<int>) {} +fn take(_x: Box<isize>) {} fn main() { - let x: Box<int> = box 25; + let x: Box<isize> = box 25; loop { take(x); //~ ERROR use of moved value: `x` } diff --git a/src/test/compile-fail/liveness-move-in-loop.rs b/src/test/compile-fail/liveness-move-in-loop.rs index 127a68bd339..65ccaceac08 100644 --- a/src/test/compile-fail/liveness-move-in-loop.rs +++ b/src/test/compile-fail/liveness-move-in-loop.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let y: Box<int> = box 42; - let mut x: Box<int>; + let y: Box<isize> = box 42; + let mut x: Box<isize>; loop { println!("{}", y); loop { diff --git a/src/test/compile-fail/liveness-move-in-while.rs b/src/test/compile-fail/liveness-move-in-while.rs index 2cebe3f573b..cadfd487121 100644 --- a/src/test/compile-fail/liveness-move-in-while.rs +++ b/src/test/compile-fail/liveness-move-in-while.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let y: Box<int> = box 42; - let mut x: Box<int>; + let y: Box<isize> = box 42; + let mut x: Box<isize>; loop { println!("{}", y); //~ ERROR use of moved value: `y` while true { while true { while true { x = y; x.clone(); } } } diff --git a/src/test/compile-fail/liveness-return-last-stmt-semi.rs b/src/test/compile-fail/liveness-return-last-stmt-semi.rs index 9cfffb5fa6b..4b8f84ae704 100644 --- a/src/test/compile-fail/liveness-return-last-stmt-semi.rs +++ b/src/test/compile-fail/liveness-return-last-stmt-semi.rs @@ -10,11 +10,11 @@ // // regression test for #8005 -macro_rules! test { () => { fn foo() -> int { 1i; } } } +macro_rules! test { () => { fn foo() -> isize { 1is; } } } //~^ ERROR not all control paths return a value //~^^ HELP consider removing this semicolon -fn no_return() -> int {} //~ ERROR not all control paths return a value +fn no_return() -> isize {} //~ ERROR not all control paths return a value fn bar(x: u32) -> u32 { //~ ERROR not all control paths return a value x * 2; //~ HELP consider removing this semicolon diff --git a/src/test/compile-fail/liveness-unused.rs b/src/test/compile-fail/liveness-unused.rs index e93872eba0c..c9f8230b6c5 100644 --- a/src/test/compile-fail/liveness-unused.rs +++ b/src/test/compile-fail/liveness-unused.rs @@ -12,57 +12,57 @@ #![deny(unused_assignments)] #![allow(dead_code, non_camel_case_types)] -fn f1(x: int) { +fn f1(x: isize) { //~^ ERROR unused variable: `x` } -fn f1b(x: &mut int) { +fn f1b(x: &mut isize) { //~^ ERROR unused variable: `x` } #[allow(unused_variables)] -fn f1c(x: int) {} +fn f1c(x: isize) {} fn f1d() { - let x: int; + let x: isize; //~^ ERROR unused variable: `x` } fn f2() { - let x = 3i; + let x = 3is; //~^ ERROR unused variable: `x` } fn f3() { - let mut x = 3i; + let mut x = 3is; //~^ ERROR variable `x` is assigned to, but never used - x += 4i; + x += 4is; //~^ ERROR value assigned to `x` is never read } fn f3b() { - let mut z = 3i; + let mut z = 3is; //~^ ERROR variable `z` is assigned to, but never used loop { - z += 4i; + z += 4is; } } #[allow(unused_variables)] fn f3c() { - let mut z = 3i; - loop { z += 4i; } + let mut z = 3is; + loop { z += 4is; } } #[allow(unused_variables)] #[allow(unused_assignments)] fn f3d() { - let mut x = 3i; - x += 4i; + let mut x = 3is; + x += 4is; } fn f4() { - match Some(3i) { + match Some(3is) { Some(i) => { //~^ ERROR unused variable: `i` } @@ -71,11 +71,11 @@ fn f4() { } enum tri { - a(int), b(int), c(int) + a(isize), b(isize), c(isize) } -fn f4b() -> int { - match tri::a(3i) { +fn f4b() -> isize { + match tri::a(3is) { tri::a(i) | tri::b(i) | tri::c(i) => { i } @@ -83,17 +83,17 @@ fn f4b() -> int { } fn f5a() { - for x in range(1i, 10) { } + for x in range(1is, 10) { } //~^ ERROR unused variable: `x` } fn f5b() { - for (x, _) in [1i, 2, 3].iter().enumerate() { } + for (x, _) in [1is, 2, 3].iter().enumerate() { } //~^ ERROR unused variable: `x` } fn f5c() { - for (_, x) in [1i, 2, 3].iter().enumerate() { + for (_, x) in [1is, 2, 3].iter().enumerate() { //~^ ERROR unused variable: `x` continue; std::os::set_exit_status(*x); //~ WARNING unreachable statement diff --git a/src/test/compile-fail/liveness-use-after-move.rs b/src/test/compile-fail/liveness-use-after-move.rs index a988254141a..21e52f13060 100644 --- a/src/test/compile-fail/liveness-use-after-move.rs +++ b/src/test/compile-fail/liveness-use-after-move.rs @@ -8,8 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn main() { - let x = box 5i; + let x = box 5is; let y = x; println!("{}", *x); //~ ERROR use of moved value: `*x` y.clone(); diff --git a/src/test/compile-fail/liveness-use-after-send.rs b/src/test/compile-fail/liveness-use-after-send.rs index 44d45463f19..4ba24800f5d 100644 --- a/src/test/compile-fail/liveness-use-after-send.rs +++ b/src/test/compile-fail/liveness-use-after-send.rs @@ -15,11 +15,11 @@ fn send<T:Send + std::fmt::Show>(ch: _chan<T>, data: T) { } #[derive(Show)] -struct _chan<T>(int); +struct _chan<T>(isize); // Tests that "log(debug, message);" is flagged as using // message after the send deinitializes it -fn test00_start(ch: _chan<Box<int>>, message: Box<int>, _count: Box<int>) { +fn test00_start(ch: _chan<Box<isize>>, message: Box<isize>, _count: Box<isize>) { send(ch, message); println!("{}", message); //~ ERROR use of moved value: `message` } diff --git a/src/test/compile-fail/loop-does-not-diverge.rs b/src/test/compile-fail/loop-does-not-diverge.rs index 9488e6bf969..e2d3d059ad8 100644 --- a/src/test/compile-fail/loop-does-not-diverge.rs +++ b/src/test/compile-fail/loop-does-not-diverge.rs @@ -14,7 +14,7 @@ fn forever() -> ! { loop { break; } - return 42i; //~ ERROR `return` in a function declared as diverging + return 42is; //~ ERROR `return` in a function declared as diverging } fn main() { diff --git a/src/test/compile-fail/macro-no-implicit-reexport.rs b/src/test/compile-fail/macro-no-implicit-reexport.rs index 4a427f121fc..1e2172f4a7c 100644 --- a/src/test/compile-fail/macro-no-implicit-reexport.rs +++ b/src/test/compile-fail/macro-no-implicit-reexport.rs @@ -16,5 +16,5 @@ extern crate macro_non_reexport_2; fn main() { - assert_eq!(reexported!(), 3u); //~ ERROR macro undefined + assert_eq!(reexported!(), 3us); //~ ERROR macro undefined } diff --git a/src/test/compile-fail/macro-reexport-not-locally-visible.rs b/src/test/compile-fail/macro-reexport-not-locally-visible.rs index c8e59f98d3c..cf0d79e0fef 100644 --- a/src/test/compile-fail/macro-reexport-not-locally-visible.rs +++ b/src/test/compile-fail/macro-reexport-not-locally-visible.rs @@ -16,5 +16,5 @@ extern crate macro_reexport_1; fn main() { - assert_eq!(reexported!(), 3u); //~ ERROR macro undefined + assert_eq!(reexported!(), 3us); //~ ERROR macro undefined } diff --git a/src/test/compile-fail/macros-nonfatal-errors.rs b/src/test/compile-fail/macros-nonfatal-errors.rs index f97cad559a1..ce1b372a4c1 100644 --- a/src/test/compile-fail/macros-nonfatal-errors.rs +++ b/src/test/compile-fail/macros-nonfatal-errors.rs @@ -22,9 +22,6 @@ enum CantDeriveThose {} fn main() { doesnt_exist!(); //~ ERROR - bytes!(invalid); //~ ERROR non-literal in bytes! - //~^ WARN `bytes!` is deprecated - asm!(invalid); //~ ERROR concat_idents!("not", "idents"); //~ ERROR diff --git a/src/test/compile-fail/main-wrong-type.rs b/src/test/compile-fail/main-wrong-type.rs index ae990880523..d9c617a7172 100644 --- a/src/test/compile-fail/main-wrong-type.rs +++ b/src/test/compile-fail/main-wrong-type.rs @@ -9,8 +9,8 @@ // except according to those terms. struct S { - x: int, - y: int, + x: isize, + y: isize, } fn main(foo: S) { diff --git a/src/test/compile-fail/map-types.rs b/src/test/compile-fail/map-types.rs index 7aafeced3a6..ba2205f5868 100644 --- a/src/test/compile-fail/map-types.rs +++ b/src/test/compile-fail/map-types.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + extern crate collections; use std::collections::HashMap; diff --git a/src/test/compile-fail/match-ill-type1.rs b/src/test/compile-fail/match-ill-type1.rs index 2b4c77bf9e8..908d46f398c 100644 --- a/src/test/compile-fail/match-ill-type1.rs +++ b/src/test/compile-fail/match-ill-type1.rs @@ -10,7 +10,7 @@ fn main() { match 1 { - 1...2u => 1, //~ ERROR mismatched types in range + 1...2us => 1, //~ ERROR mismatched types in range _ => 2, }; } diff --git a/src/test/compile-fail/match-ill-type2.rs b/src/test/compile-fail/match-ill-type2.rs index 17f02abc8ec..6b6954101b2 100644 --- a/src/test/compile-fail/match-ill-type2.rs +++ b/src/test/compile-fail/match-ill-type2.rs @@ -9,9 +9,9 @@ // except according to those terms. fn main() { - match 1i { - 1i => 1i, - 2u => 1i, //~ ERROR mismatched types - _ => 2i, + match 1is { + 1is => 1is, + 2us => 1is, //~ ERROR mismatched types + _ => 2is, }; } diff --git a/src/test/compile-fail/match-join.rs b/src/test/compile-fail/match-join.rs index e78561b9fdb..4ec426fd3aa 100644 --- a/src/test/compile-fail/match-join.rs +++ b/src/test/compile-fail/match-join.rs @@ -17,5 +17,5 @@ fn main() { match true { false => { my_panic(); } true => { } } println!("{}", x); //~ ERROR unresolved name `x` - let x: int; + let x: isize; } diff --git a/src/test/compile-fail/match-non-exhaustive.rs b/src/test/compile-fail/match-non-exhaustive.rs index 20adbeebdf1..2aeccacb0f6 100644 --- a/src/test/compile-fail/match-non-exhaustive.rs +++ b/src/test/compile-fail/match-non-exhaustive.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - match 0i { 1i => () } //~ ERROR non-exhaustive patterns - match 0i { 0i if false => () } //~ ERROR non-exhaustive patterns + match 0is { 1is => () } //~ ERROR non-exhaustive patterns + match 0is { 0is if false => () } //~ ERROR non-exhaustive patterns } diff --git a/src/test/compile-fail/match-pattern-field-mismatch-2.rs b/src/test/compile-fail/match-pattern-field-mismatch-2.rs index ab9efdcc8cc..e63ddf6c7fd 100644 --- a/src/test/compile-fail/match-pattern-field-mismatch-2.rs +++ b/src/test/compile-fail/match-pattern-field-mismatch-2.rs @@ -10,8 +10,8 @@ fn main() { enum color { - rgb(uint, uint, uint), - cmyk(uint, uint, uint, uint), + rgb(usize, usize, usize), + cmyk(usize, usize, usize, usize), no_color, } diff --git a/src/test/compile-fail/match-pattern-field-mismatch.rs b/src/test/compile-fail/match-pattern-field-mismatch.rs index 243690bbf31..8426ecdaf99 100644 --- a/src/test/compile-fail/match-pattern-field-mismatch.rs +++ b/src/test/compile-fail/match-pattern-field-mismatch.rs @@ -10,8 +10,8 @@ fn main() { enum color { - rgb(uint, uint, uint), - cmyk(uint, uint, uint, uint), + rgb(usize, usize, usize), + cmyk(usize, usize, usize, usize), no_color, } diff --git a/src/test/compile-fail/match-range-fail-dominate.rs b/src/test/compile-fail/match-range-fail-dominate.rs index 7a4451f99ab..7d33963003f 100644 --- a/src/test/compile-fail/match-range-fail-dominate.rs +++ b/src/test/compile-fail/match-range-fail-dominate.rs @@ -15,21 +15,21 @@ //error-pattern: unreachable fn main() { - match 5u { - 1u ... 10u => { } - 5u ... 6u => { } + match 5us { + 1us ... 10us => { } + 5us ... 6us => { } _ => {} }; - match 5u { - 3u ... 6u => { } - 4u ... 6u => { } + match 5us { + 3us ... 6us => { } + 4us ... 6us => { } _ => {} }; - match 5u { - 4u ... 6u => { } - 4u ... 6u => { } + match 5us { + 4us ... 6us => { } + 4us ... 6us => { } _ => {} }; diff --git a/src/test/compile-fail/match-range-fail.rs b/src/test/compile-fail/match-range-fail.rs index 9fbd1545fcf..1c804b0552c 100644 --- a/src/test/compile-fail/match-range-fail.rs +++ b/src/test/compile-fail/match-range-fail.rs @@ -13,8 +13,8 @@ //error-pattern: mismatched types fn main() { - match 5u { - 6u ... 1u => { } + match 5us { + 6us ... 1us => { } _ => { } }; @@ -22,8 +22,8 @@ fn main() { "bar" ... "foo" => { } }; - match 5u { - 'c' ... 100u => { } + match 5us { + 'c' ... 100us => { } _ => { } }; } diff --git a/src/test/compile-fail/match-static-const-lc.rs b/src/test/compile-fail/match-static-const-lc.rs index 15a832aad89..345c4aa69a7 100644 --- a/src/test/compile-fail/match-static-const-lc.rs +++ b/src/test/compile-fail/match-static-const-lc.rs @@ -14,7 +14,7 @@ #![deny(non_upper_case_globals)] #[allow(non_upper_case_globals)] -pub const a : int = 97; +pub const a : isize = 97; fn f() { let r = match (0,0) { @@ -27,7 +27,7 @@ fn f() { mod m { #[allow(non_upper_case_globals)] - pub const aha : int = 7; + pub const aha : isize = 7; } fn g() { @@ -41,7 +41,7 @@ fn g() { } mod n { - pub const OKAY : int = 8; + pub const OKAY : isize = 8; } fn h() { diff --git a/src/test/compile-fail/match-struct.rs b/src/test/compile-fail/match-struct.rs index 65082f93d35..e3b47372a4f 100644 --- a/src/test/compile-fail/match-struct.rs +++ b/src/test/compile-fail/match-struct.rs @@ -9,8 +9,8 @@ // except according to those terms. -struct S { a: int } -enum E { C(int) } +struct S { a: isize } +enum E { C(isize) } fn main() { match (S { a: 1 }) { diff --git a/src/test/compile-fail/match-tag-unary.rs b/src/test/compile-fail/match-tag-unary.rs index 89012e42bdc..48733fd423d 100644 --- a/src/test/compile-fail/match-tag-unary.rs +++ b/src/test/compile-fail/match-tag-unary.rs @@ -10,7 +10,7 @@ // error-pattern: mismatched types -enum a { A(int), } -enum b { B(int), } +enum a { A(isize), } +enum b { B(isize), } fn main() { let x: a = a::A(0); match x { b::B(y) => { } } } diff --git a/src/test/compile-fail/match-vec-fixed.rs b/src/test/compile-fail/match-vec-fixed.rs index bac9fef2b17..c35dc8d7c86 100644 --- a/src/test/compile-fail/match-vec-fixed.rs +++ b/src/test/compile-fail/match-vec-fixed.rs @@ -9,7 +9,7 @@ // except according to those terms. fn a() { - let v = [1i, 2, 3]; + let v = [1is, 2, 3]; match v { [_, _, _] => {} [_, _, _] => {} //~ ERROR unreachable pattern diff --git a/src/test/compile-fail/match-vec-unreachable.rs b/src/test/compile-fail/match-vec-unreachable.rs index a85ce660e8b..e2671552b43 100644 --- a/src/test/compile-fail/match-vec-unreachable.rs +++ b/src/test/compile-fail/match-vec-unreachable.rs @@ -10,8 +10,8 @@ fn main() { - let x: Vec<(int, int)> = Vec::new(); - let x: &[(int, int)] = x.as_slice(); + let x: Vec<(isize, isize)> = Vec::new(); + let x: &[(isize, isize)] = x.as_slice(); match x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern diff --git a/src/test/compile-fail/method-ambig-one-trait-coerce.rs b/src/test/compile-fail/method-ambig-one-trait-coerce.rs index 5e3206ea516..cb5da4bb547 100644 --- a/src/test/compile-fail/method-ambig-one-trait-coerce.rs +++ b/src/test/compile-fail/method-ambig-one-trait-coerce.rs @@ -15,15 +15,15 @@ trait Object { } trait foo { - fn foo(self) -> int; + fn foo(self) -> isize; } impl foo for Box<Object+'static> { - fn foo(self) -> int {1} + fn foo(self) -> isize {1} } impl foo for Box<Object+Send> { - fn foo(self) -> int {2} + fn foo(self) -> isize {2} } fn test1(x: Box<Object+Send+Sync>) { diff --git a/src/test/compile-fail/method-ambig-one-trait-unknown-int-type.rs b/src/test/compile-fail/method-ambig-one-trait-unknown-int-type.rs index e211db2dcd2..c6d45f1c9db 100644 --- a/src/test/compile-fail/method-ambig-one-trait-unknown-int-type.rs +++ b/src/test/compile-fail/method-ambig-one-trait-unknown-int-type.rs @@ -13,15 +13,15 @@ // of what kind of `Vec` we have, eventually leading to a type error. trait foo { - fn foo(&self) -> int; + fn foo(&self) -> isize; } -impl foo for Vec<uint> { - fn foo(&self) -> int {1} +impl foo for Vec<usize> { + fn foo(&self) -> isize {1} } -impl foo for Vec<int> { - fn foo(&self) -> int {2} +impl foo for Vec<isize> { + fn foo(&self) -> isize {2} } // This is very hokey: we have heuristics to suppress messages about @@ -39,7 +39,7 @@ fn m2() { let mut x = Vec::new(); // ...but we still resolved `foo()` to the trait and hence know the return type. - let y: uint = x.foo(); //~ ERROR mismatched types + let y: usize = x.foo(); //~ ERROR mismatched types } fn main() { } diff --git a/src/test/compile-fail/method-ambig-two-traits-cross-crate.rs b/src/test/compile-fail/method-ambig-two-traits-cross-crate.rs index 30e635149c4..cab6a8610bf 100644 --- a/src/test/compile-fail/method-ambig-two-traits-cross-crate.rs +++ b/src/test/compile-fail/method-ambig-two-traits-cross-crate.rs @@ -15,8 +15,8 @@ extern crate ambig_impl_2_lib; use ambig_impl_2_lib::me; trait me2 { - fn me(&self) -> uint; + fn me(&self) -> usize; } -impl me2 for uint { fn me(&self) -> uint { *self } } -fn main() { 1u.me(); } //~ ERROR E0034 +impl me2 for usize { fn me(&self) -> usize { *self } } +fn main() { 1us.me(); } //~ ERROR E0034 diff --git a/src/test/compile-fail/method-ambig-two-traits-with-default-method.rs b/src/test/compile-fail/method-ambig-two-traits-with-default-method.rs index 87efaed4e3d..87e3655d31e 100644 --- a/src/test/compile-fail/method-ambig-two-traits-with-default-method.rs +++ b/src/test/compile-fail/method-ambig-two-traits-with-default-method.rs @@ -15,9 +15,9 @@ trait Foo { fn method(&self) {} } trait Bar { fn method(&self) {} } -impl Foo for uint {} -impl Bar for uint {} +impl Foo for usize {} +impl Bar for usize {} fn main() { - 1u.method(); //~ ERROR E0034 + 1us.method(); //~ ERROR E0034 } diff --git a/src/test/compile-fail/method-call-err-msg.rs b/src/test/compile-fail/method-call-err-msg.rs index 3610a0e2e9d..2f82441762f 100644 --- a/src/test/compile-fail/method-call-err-msg.rs +++ b/src/test/compile-fail/method-call-err-msg.rs @@ -13,8 +13,8 @@ pub struct Foo; impl Foo { fn zero(self) -> Foo { self } - fn one(self, _: int) -> Foo { self } - fn two(self, _: int, _: int) -> Foo { self } + fn one(self, _: isize) -> Foo { self } + fn two(self, _: isize, _: isize) -> Foo { self } } fn main() { diff --git a/src/test/compile-fail/method-missing-call.rs b/src/test/compile-fail/method-missing-call.rs index ddfa447f60e..899c1ef16a6 100644 --- a/src/test/compile-fail/method-missing-call.rs +++ b/src/test/compile-fail/method-missing-call.rs @@ -14,26 +14,26 @@ struct Point { - x: int, - y: int + x: isize, + y: isize } impl Point { fn new() -> Point { Point{x:0, y:0} } - fn get_x(&self) -> int { + fn get_x(&self) -> isize { self.x } } fn main() { let point: Point = Point::new(); - let px: int = point + let px: isize = point .get_x;//~ ERROR attempted to take value of method `get_x` on type `Point` //~^ HELP maybe a `()` to call it is missing // Ensure the span is useful - let ys = &[1i,2,3,4,5,6,7]; + let ys = &[1is,2,3,4,5,6,7]; let a = ys.iter() .map(|x| x) .filter(|&&x| x == 1) diff --git a/src/test/compile-fail/method-self-arg-2.rs b/src/test/compile-fail/method-self-arg-2.rs index 0ac0851619c..ad255ecd9c0 100644 --- a/src/test/compile-fail/method-self-arg-2.rs +++ b/src/test/compile-fail/method-self-arg-2.rs @@ -23,5 +23,5 @@ fn main() { Foo::bar(&x); //~ERROR cannot borrow `x` let x = Foo; - Foo::baz(&x); //~ERROR cannot borrow immutable dereference of `&`-pointer as mutable + Foo::baz(&x); //~ERROR cannot borrow immutable borrowed content as mutable } diff --git a/src/test/compile-fail/missing-derivable-attr.rs b/src/test/compile-fail/missing-derivable-attr.rs index db960ac3409..7eee51e4076 100644 --- a/src/test/compile-fail/missing-derivable-attr.rs +++ b/src/test/compile-fail/missing-derivable-attr.rs @@ -13,11 +13,11 @@ trait MyEq { } struct A { - x: int + x: isize } -impl MyEq for int { - fn eq(&self, other: &int) -> bool { *self == *other } +impl MyEq for isize { + fn eq(&self, other: &isize) -> bool { *self == *other } } impl MyEq for A {} //~ ERROR not all trait items implemented, missing: `eq` diff --git a/src/test/compile-fail/missing-return.rs b/src/test/compile-fail/missing-return.rs index 1dc817cc6e6..efd0c827a35 100644 --- a/src/test/compile-fail/missing-return.rs +++ b/src/test/compile-fail/missing-return.rs @@ -10,6 +10,6 @@ // error-pattern: return -fn f() -> int { } +fn f() -> isize { } fn main() { f(); } diff --git a/src/test/compile-fail/mod_file_aux.rs b/src/test/compile-fail/mod_file_aux.rs index 4d18decdc13..b7470811f60 100644 --- a/src/test/compile-fail/mod_file_aux.rs +++ b/src/test/compile-fail/mod_file_aux.rs @@ -10,4 +10,4 @@ // ignore-test Not a test. Used by other tests -pub fn foo() -> int { 10 } +pub fn foo() -> isize { 10 } diff --git a/src/test/compile-fail/move-fragments-1.rs b/src/test/compile-fail/move-fragments-1.rs index e45862a7fc6..3f14be2da10 100644 --- a/src/test/compile-fail/move-fragments-1.rs +++ b/src/test/compile-fail/move-fragments-1.rs @@ -18,7 +18,7 @@ // These are all fairly trivial cases: unused variables or direct // drops of substructure. -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } #[rustc_move_fragments] diff --git a/src/test/compile-fail/move-fragments-2.rs b/src/test/compile-fail/move-fragments-2.rs index ceb1d5a0f09..6c0635d6be9 100644 --- a/src/test/compile-fail/move-fragments-2.rs +++ b/src/test/compile-fail/move-fragments-2.rs @@ -20,7 +20,7 @@ use self::Lonely::{Zero, One, Two}; -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) } diff --git a/src/test/compile-fail/move-fragments-3.rs b/src/test/compile-fail/move-fragments-3.rs index 4540b0c5a91..24d73ec2274 100644 --- a/src/test/compile-fail/move-fragments-3.rs +++ b/src/test/compile-fail/move-fragments-3.rs @@ -20,7 +20,7 @@ use self::Lonely::{Zero, One, Two}; -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) } diff --git a/src/test/compile-fail/move-fragments-4.rs b/src/test/compile-fail/move-fragments-4.rs index dc43dcb9b0e..97e8e45ed06 100644 --- a/src/test/compile-fail/move-fragments-4.rs +++ b/src/test/compile-fail/move-fragments-4.rs @@ -19,7 +19,7 @@ // early draft of the code did not properly traverse up through all of // the parents of the leaf fragment.) -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub struct Pair<X,Y> { x: X, y: Y } diff --git a/src/test/compile-fail/move-fragments-5.rs b/src/test/compile-fail/move-fragments-5.rs index bef2f12d642..9f70421fa84 100644 --- a/src/test/compile-fail/move-fragments-5.rs +++ b/src/test/compile-fail/move-fragments-5.rs @@ -17,7 +17,7 @@ // This is the first test that checks moving into local variables. -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub struct Pair<X,Y> { x: X, y: Y } diff --git a/src/test/compile-fail/move-fragments-7.rs b/src/test/compile-fail/move-fragments-7.rs index 6b2c77bcac1..2af2b2957f8 100644 --- a/src/test/compile-fail/move-fragments-7.rs +++ b/src/test/compile-fail/move-fragments-7.rs @@ -19,7 +19,7 @@ // both moving out of the structure (i.e. reading `*p.x`) and writing // into the container (i.e. writing `*p.x`). -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub struct Pair<X,Y> { x: X, y: Y } diff --git a/src/test/compile-fail/move-fragments-8.rs b/src/test/compile-fail/move-fragments-8.rs index 40ab541128c..18bf4066076 100644 --- a/src/test/compile-fail/move-fragments-8.rs +++ b/src/test/compile-fail/move-fragments-8.rs @@ -22,7 +22,7 @@ // also that in this case we cannot do a move out of `&T`, so we only // test writing `*p.x` here. -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } pub struct Pair<X,Y> { x: X, y: Y } diff --git a/src/test/compile-fail/move-fragments-9.rs b/src/test/compile-fail/move-fragments-9.rs index 0b095ff6f82..d0eeebd02f8 100644 --- a/src/test/compile-fail/move-fragments-9.rs +++ b/src/test/compile-fail/move-fragments-9.rs @@ -14,7 +14,7 @@ // Note also that the `test_move_array_then_overwrite` tests represent // cases that we probably should make illegal. -pub struct D { d: int } +pub struct D { d: isize } impl Drop for D { fn drop(&mut self) { } } #[rustc_move_fragments] @@ -34,7 +34,7 @@ pub fn test_move_array_into_recv(a: [D; 3], recv: &mut [D; 3]) { } #[rustc_move_fragments] -pub fn test_extract_array_elem(a: [D; 3], i: uint) -> D { +pub fn test_extract_array_elem(a: [D; 3], i: usize) -> D { //~^ ERROR parent_of_fragments: `$(local a)` //~| ERROR assigned_leaf_path: `$(local i)` //~| ERROR moved_leaf_path: `$(local a).[]` @@ -43,7 +43,7 @@ pub fn test_extract_array_elem(a: [D; 3], i: uint) -> D { } #[rustc_move_fragments] -pub fn test_overwrite_array_elem(mut a: [D; 3], i: uint, d: D) { +pub fn test_overwrite_array_elem(mut a: [D; 3], i: usize, d: D) { //~^ ERROR parent_of_fragments: `$(local mut a)` //~| ERROR assigned_leaf_path: `$(local i)` //~| ERROR assigned_leaf_path: `$(local d)` @@ -59,7 +59,7 @@ pub fn test_overwrite_array_elem(mut a: [D; 3], i: uint, d: D) { // See RFC PR 320 for more discussion. #[rustc_move_fragments] -pub fn test_move_array_then_overwrite_elem1(mut a: [D; 3], i: uint, recv: &mut [D; 3], d: D) { +pub fn test_move_array_then_overwrite_elem1(mut a: [D; 3], i: usize, recv: &mut [D; 3], d: D) { //~^ ERROR parent_of_fragments: `$(local mut a)` //~| ERROR parent_of_fragments: `$(local recv)` //~| ERROR assigned_leaf_path: `$(local recv).*` @@ -76,7 +76,7 @@ pub fn test_move_array_then_overwrite_elem1(mut a: [D; 3], i: uint, recv: &mut [ } #[rustc_move_fragments] -pub fn test_move_array_then_overwrite_elem2(mut a: [D; 3], i: uint, j: uint, +pub fn test_move_array_then_overwrite_elem2(mut a: [D; 3], i: usize, j: usize, recv: &mut [D; 3], d1: D, d2: D) { //~^^ ERROR parent_of_fragments: `$(local mut a)` //~| ERROR parent_of_fragments: `$(local recv)` diff --git a/src/test/compile-fail/move-out-of-tuple-field.rs b/src/test/compile-fail/move-out-of-tuple-field.rs index 7fcb54e0467..ace6c80e3e3 100644 --- a/src/test/compile-fail/move-out-of-tuple-field.rs +++ b/src/test/compile-fail/move-out-of-tuple-field.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo(Box<int>); +#![feature(box_syntax)] + +struct Foo(Box<isize>); fn main() { - let x = (box 1i,); + let x = (box 1is,); let y = x.0; let z = x.0; //~ ERROR use of moved value: `x.0` - let x = Foo(box 1i); + let x = Foo(box 1is); let y = x.0; let z = x.0; //~ ERROR use of moved value: `x.0` } diff --git a/src/test/compile-fail/moves-based-on-type-access-to-field.rs b/src/test/compile-fail/moves-based-on-type-access-to-field.rs index c9efce0d684..b8572fbd215 100644 --- a/src/test/compile-fail/moves-based-on-type-access-to-field.rs +++ b/src/test/compile-fail/moves-based-on-type-access-to-field.rs @@ -11,7 +11,7 @@ // Tests that if you move from `x.f` or `x[0]`, `x` is inaccessible. // Also tests that we give a more specific error message. -struct Foo { f: String, y: int } +struct Foo { f: String, y: isize } fn consume(_s: String) {} fn touch<A>(_a: &A) {} diff --git a/src/test/compile-fail/moves-based-on-type-block-bad.rs b/src/test/compile-fail/moves-based-on-type-block-bad.rs index 14af49dfc49..179c71d3659 100644 --- a/src/test/compile-fail/moves-based-on-type-block-bad.rs +++ b/src/test/compile-fail/moves-based-on-type-block-bad.rs @@ -10,13 +10,15 @@ // ignore-tidy-linelength +#![feature(box_syntax)] + struct S { x: Box<E> } enum E { Foo(Box<S>), - Bar(Box<int>), + Bar(Box<isize>), Baz } diff --git a/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs b/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs index 805c82f03f9..865784c2f1e 100644 --- a/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs +++ b/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs @@ -13,9 +13,9 @@ // See middle::ty::type_contents() for more information. -struct List { key: int, next: Option<Box<List>> } +struct List { key: isize, next: Option<Box<List>> } -fn foo(node: Box<List>) -> int { +fn foo(node: Box<List>) -> isize { let r = match node.next { Some(right) => consume(right), None => 0 @@ -23,7 +23,7 @@ fn foo(node: Box<List>) -> int { consume(node) + r //~ ERROR use of partially moved value: `node` } -fn consume(v: Box<List>) -> int { +fn consume(v: Box<List>) -> isize { v.key } diff --git a/src/test/compile-fail/moves-based-on-type-exprs.rs b/src/test/compile-fail/moves-based-on-type-exprs.rs index d8d84e558a9..58f1f78fa5d 100644 --- a/src/test/compile-fail/moves-based-on-type-exprs.rs +++ b/src/test/compile-fail/moves-based-on-type-exprs.rs @@ -24,13 +24,13 @@ fn f10() { fn f20() { let x = "hi".to_string(); - let _y = (x, 3i); + let _y = (x, 3is); touch(&x); //~ ERROR use of moved value: `x` } fn f21() { - let x = vec!(1i, 2, 3); - let _y = (x[0], 3i); + let x = vec!(1is, 2, 3); + let _y = (x[0], 3is); touch(&x); } @@ -61,9 +61,9 @@ fn f50(cond: bool) { let x = "hi".to_string(); let y = "ho".to_string(); let _y = match cond { - _ if guard(x) => 10i, - true => 10i, - false => 20i, + _ if guard(x) => 10is, + true => 10is, + false => 20is, }; touch(&x); //~ ERROR use of moved value: `x` touch(&y); diff --git a/src/test/compile-fail/moves-based-on-type-move-out-of-closure-env-issue-1965.rs b/src/test/compile-fail/moves-based-on-type-move-out-of-closure-env-issue-1965.rs index ab762332ee4..5dfe7f0c71f 100644 --- a/src/test/compile-fail/moves-based-on-type-move-out-of-closure-env-issue-1965.rs +++ b/src/test/compile-fail/moves-based-on-type-move-out-of-closure-env-issue-1965.rs @@ -8,9 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::uint; +#![feature(box_syntax)] -fn test(_x: Box<uint>) {} +use std::usize; + +fn test(_x: Box<usize>) {} fn main() { let i = box 3; diff --git a/src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs b/src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs index 9053f97e8a7..f410541f0b7 100644 --- a/src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs +++ b/src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs @@ -12,6 +12,7 @@ // bound must be noncopyable. For details see // http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/ +#![feature(box_syntax)] #![feature(unboxed_closures)] struct R<'a> { diff --git a/src/test/compile-fail/moves-based-on-type-tuple.rs b/src/test/compile-fail/moves-based-on-type-tuple.rs index 85c435ef0db..30388f9d2f7 100644 --- a/src/test/compile-fail/moves-based-on-type-tuple.rs +++ b/src/test/compile-fail/moves-based-on-type-tuple.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -fn dup(x: Box<int>) -> Box<(Box<int>,Box<int>)> { box() (x, x) } //~ ERROR use of moved value +fn dup(x: Box<isize>) -> Box<(Box<isize>,Box<isize>)> { box() (x, x) } //~ ERROR use of moved value fn main() { dup(box 3); } diff --git a/src/test/compile-fail/moves-sru-moved-field.rs b/src/test/compile-fail/moves-sru-moved-field.rs index 2cf7618d92d..15977fbeb73 100644 --- a/src/test/compile-fail/moves-sru-moved-field.rs +++ b/src/test/compile-fail/moves-sru-moved-field.rs @@ -8,12 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -type Noncopyable = Box<int>; +type Noncopyable = Box<isize>; struct Foo { - copied: int, - moved: Box<int>, + copied: isize, + moved: Box<isize>, noncopyable: Noncopyable } diff --git a/src/test/compile-fail/multitrait.rs b/src/test/compile-fail/multitrait.rs index 7add747fbfa..a0e210aed40 100644 --- a/src/test/compile-fail/multitrait.rs +++ b/src/test/compile-fail/multitrait.rs @@ -9,7 +9,7 @@ // except according to those terms. struct S { - y: int + y: isize } impl Cmp, ToString for S { //~ ERROR: expected one of `(`, `+`, `::`, or `{`, found `,` diff --git a/src/test/compile-fail/mut-cant-alias.rs b/src/test/compile-fail/mut-cant-alias.rs index ce6e793d55d..847a3eaf8a1 100644 --- a/src/test/compile-fail/mut-cant-alias.rs +++ b/src/test/compile-fail/mut-cant-alias.rs @@ -11,7 +11,7 @@ use std::cell::RefCell; fn main() { - let m = RefCell::new(0i); + let m = RefCell::new(0is); let mut b = m.borrow_mut(); let b1 = &mut *b; let b2 = &mut *b; //~ ERROR cannot borrow diff --git a/src/test/compile-fail/mut-cross-borrowing.rs b/src/test/compile-fail/mut-cross-borrowing.rs index 657c2832c49..7fb5c2ac4a4 100644 --- a/src/test/compile-fail/mut-cross-borrowing.rs +++ b/src/test/compile-fail/mut-cross-borrowing.rs @@ -8,10 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(_: &mut int) {} +#![feature(box_syntax)] + +fn f(_: &mut isize) {} fn main() { - let mut x = box 3i; + let mut x = box 3is; f(x) //~ ERROR mismatched types } diff --git a/src/test/compile-fail/mut-not-freeze.rs b/src/test/compile-fail/mut-not-freeze.rs index d7529c86aa5..8c39320276a 100644 --- a/src/test/compile-fail/mut-not-freeze.rs +++ b/src/test/compile-fail/mut-not-freeze.rs @@ -13,7 +13,7 @@ use std::cell::RefCell; fn f<T: Sync>(_: T) {} fn main() { - let x = RefCell::new(0i); + let x = RefCell::new(0is); f(x); //~^ ERROR `core::marker::Sync` is not implemented //~^^ ERROR `core::marker::Sync` is not implemented diff --git a/src/test/compile-fail/mut-pattern-internal-mutability.rs b/src/test/compile-fail/mut-pattern-internal-mutability.rs index 05c6c4a9655..92f02114a13 100644 --- a/src/test/compile-fail/mut-pattern-internal-mutability.rs +++ b/src/test/compile-fail/mut-pattern-internal-mutability.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let foo = &mut 1i; + let foo = &mut 1is; let &mut x = foo; x += 1; //~ ERROR re-assignment of immutable variable diff --git a/src/test/compile-fail/mut-pattern-mismatched.rs b/src/test/compile-fail/mut-pattern-mismatched.rs index 443be7d7b69..9f1d3d1fb39 100644 --- a/src/test/compile-fail/mut-pattern-mismatched.rs +++ b/src/test/compile-fail/mut-pattern-mismatched.rs @@ -13,10 +13,8 @@ fn main() { // (separate lines to ensure the spans are accurate) - // SNAP 340ac04 uncomment this after the next snapshot - // NOTE(stage0) just in case tidy doesn't check snap's in tests - // let &_ // ~ ERROR expected `&mut isize`, found `&_` - // = foo; + let &_ //~ ERROR expected `&mut isize`, found `&_` + = foo; let &mut _ = foo; let bar = &1is; diff --git a/src/test/compile-fail/mut-patterns.rs b/src/test/compile-fail/mut-patterns.rs index a78e82bb73c..cde05bc1d52 100644 --- a/src/test/compile-fail/mut-patterns.rs +++ b/src/test/compile-fail/mut-patterns.rs @@ -11,6 +11,6 @@ // Can't put mut in non-ident pattern pub fn main() { - struct Foo { x: int } + struct Foo { x: isize } let mut Foo { x: x } = Foo { x: 3 }; //~ ERROR: expected one of `:`, `;`, `=`, or `@`, found `{` } diff --git a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs index e269a736ce2..74b561c37aa 100644 --- a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs +++ b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs @@ -11,7 +11,7 @@ use std::cell::RefCell; fn main() { - let m = RefCell::new(0i); + let m = RefCell::new(0is); let p; { let b = m.borrow(); diff --git a/src/test/compile-fail/mutable-class-fields-2.rs b/src/test/compile-fail/mutable-class-fields-2.rs index 377c745acf3..932c2a9715f 100644 --- a/src/test/compile-fail/mutable-class-fields-2.rs +++ b/src/test/compile-fail/mutable-class-fields-2.rs @@ -9,9 +9,9 @@ // except according to those terms. struct cat { - meows : uint, + meows : usize, - how_hungry : int, + how_hungry : isize, } impl cat { @@ -21,7 +21,7 @@ impl cat { } -fn cat(in_x : uint, in_y : int) -> cat { +fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y @@ -29,6 +29,6 @@ fn cat(in_x : uint, in_y : int) -> cat { } fn main() { - let nyan : cat = cat(52u, 99); + let nyan : cat = cat(52us, 99); nyan.eat(); } diff --git a/src/test/compile-fail/mutable-class-fields.rs b/src/test/compile-fail/mutable-class-fields.rs index 4d77d1824ab..a840ac63dd8 100644 --- a/src/test/compile-fail/mutable-class-fields.rs +++ b/src/test/compile-fail/mutable-class-fields.rs @@ -9,11 +9,11 @@ // except according to those terms. struct cat { - meows : uint, - how_hungry : int, + meows : usize, + how_hungry : isize, } -fn cat(in_x : uint, in_y : int) -> cat { +fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y @@ -21,6 +21,6 @@ fn cat(in_x : uint, in_y : int) -> cat { } fn main() { - let nyan : cat = cat(52u, 99); + let nyan : cat = cat(52us, 99); nyan.how_hungry = 0; //~ ERROR cannot assign } diff --git a/src/test/compile-fail/name-clash-nullary.rs b/src/test/compile-fail/name-clash-nullary.rs index 2f0588b261e..1250318a729 100644 --- a/src/test/compile-fail/name-clash-nullary.rs +++ b/src/test/compile-fail/name-clash-nullary.rs @@ -12,6 +12,6 @@ use std::option::*; fn main() { - let None: int = 42; + let None: isize = 42; log(debug, None); } diff --git a/src/test/compile-fail/namespaced-enum-glob-import-no-impls.rs b/src/test/compile-fail/namespaced-enum-glob-import-no-impls.rs index 602ec9ba762..4437482fb67 100644 --- a/src/test/compile-fail/namespaced-enum-glob-import-no-impls.rs +++ b/src/test/compile-fail/namespaced-enum-glob-import-no-impls.rs @@ -11,8 +11,8 @@ mod m2 { pub enum Foo { A, - B(int), - C { a: int }, + B(isize), + C { a: isize }, } impl Foo { diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index 9a09448ff01..beb0d0ee47e 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use std::thread::Thread; fn main() { - let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let v = vec!(1is, 2, 3, 4, 5, 6, 7, 8, 9, 10); let arc_v = Arc::new(v); Thread::spawn(move|| { @@ -23,5 +23,5 @@ fn main() { assert_eq!((*arc_v)[2], 3); - println!("{}", *arc_v); + println!("{:?}", *arc_v); } diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index de230743685..d8f0fa497a4 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use std::thread::Thread; fn main() { - let v = vec!(1i, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let v = vec!(1is, 2, 3, 4, 5, 6, 7, 8, 9, 10); let arc_v = Arc::new(v); Thread::spawn(move|| { @@ -21,5 +21,5 @@ fn main() { assert_eq!((*arc_v)[2], 3); //~ ERROR use of moved value: `arc_v` - println!("{}", *arc_v); //~ ERROR use of moved value: `arc_v` + println!("{:?}", *arc_v); //~ ERROR use of moved value: `arc_v` } diff --git a/src/test/compile-fail/no_send-rc.rs b/src/test/compile-fail/no_send-rc.rs index 95855ed584b..82cc319466a 100644 --- a/src/test/compile-fail/no_send-rc.rs +++ b/src/test/compile-fail/no_send-rc.rs @@ -13,7 +13,7 @@ use std::rc::Rc; fn bar<T: Send>(_: T) {} fn main() { - let x = Rc::new(5i); + let x = Rc::new(5is); bar(x); //~^ ERROR `core::marker::Send` is not implemented //~^^ ERROR `core::marker::Send` is not implemented diff --git a/src/test/compile-fail/no_send-struct.rs b/src/test/compile-fail/no_send-struct.rs index c2d6f04c7d4..bef70523787 100644 --- a/src/test/compile-fail/no_send-struct.rs +++ b/src/test/compile-fail/no_send-struct.rs @@ -11,7 +11,7 @@ use std::marker; struct Foo { - a: int, + a: isize, ns: marker::NoSend } diff --git a/src/test/compile-fail/no_share-rc.rs b/src/test/compile-fail/no_share-rc.rs index 0f3573e0ad5..0d3e380d4a1 100644 --- a/src/test/compile-fail/no_share-rc.rs +++ b/src/test/compile-fail/no_share-rc.rs @@ -14,7 +14,7 @@ use std::cell::RefCell; fn bar<T: Sync>(_: T) {} fn main() { - let x = Rc::new(RefCell::new(5i)); + let x = Rc::new(RefCell::new(5is)); bar(x); //~^ ERROR the trait `core::marker::Sync` is not implemented //~^^ ERROR the trait `core::marker::Sync` is not implemented diff --git a/src/test/compile-fail/no_share-struct.rs b/src/test/compile-fail/no_share-struct.rs index 59864b63b04..c7028ce9786 100644 --- a/src/test/compile-fail/no_share-struct.rs +++ b/src/test/compile-fail/no_share-struct.rs @@ -10,7 +10,7 @@ use std::marker; -struct Foo { a: int, m: marker::NoSync } +struct Foo { a: isize, m: marker::NoSync } fn bar<T: Sync>(_: T) {} diff --git a/src/test/compile-fail/noexporttypeexe.rs b/src/test/compile-fail/noexporttypeexe.rs index 4081792b654..8fa4e81c889 100644 --- a/src/test/compile-fail/noexporttypeexe.rs +++ b/src/test/compile-fail/noexporttypeexe.rs @@ -17,6 +17,6 @@ fn main() { // This used to cause internal errors when serializing // because the def_id associated with the type was // not convertible to a path. - let x: int = noexporttypelib::foo(); + let x: isize = noexporttypelib::foo(); //~^ ERROR expected `isize`, found `core::option::Option<isize>` } diff --git a/src/test/compile-fail/non-constant-enum-for-vec-repeat.rs b/src/test/compile-fail/non-constant-enum-for-vec-repeat.rs index a1dc2ab2041..0212adff305 100644 --- a/src/test/compile-fail/non-constant-enum-for-vec-repeat.rs +++ b/src/test/compile-fail/non-constant-enum-for-vec-repeat.rs @@ -11,6 +11,6 @@ enum State { ST_NULL, ST_WHITESPACE } fn main() { - [State::ST_NULL; (State::ST_WHITESPACE as uint)]; + [State::ST_NULL; (State::ST_WHITESPACE as usize)]; //~^ ERROR expected constant integer for repeat count, found non-constant expression } diff --git a/src/test/compile-fail/non-constant-expr-for-fixed-len-vec.rs b/src/test/compile-fail/non-constant-expr-for-fixed-len-vec.rs index 85d734ddaf2..14d2c8d0326 100644 --- a/src/test/compile-fail/non-constant-expr-for-fixed-len-vec.rs +++ b/src/test/compile-fail/non-constant-expr-for-fixed-len-vec.rs @@ -11,8 +11,8 @@ // Check that non-constant exprs do fail as count in fixed length vec type fn main() { - fn bar(n: int) { - let _x: [int; n]; + fn bar(n: isize) { + let _x: [isize; n]; //~^ ERROR expected constant expr for array length: non-constant path in constant expr } } diff --git a/src/test/compile-fail/non-constant-expr-for-vec-repeat.rs b/src/test/compile-fail/non-constant-expr-for-vec-repeat.rs index 2e063e5237c..26528543b43 100644 --- a/src/test/compile-fail/non-constant-expr-for-vec-repeat.rs +++ b/src/test/compile-fail/non-constant-expr-for-vec-repeat.rs @@ -11,7 +11,7 @@ // Check that non constant exprs fail for vector repeat syntax fn main() { - fn bar(n: uint) { + fn bar(n: usize) { let _x = [0; n]; //~ ERROR expected constant integer for repeat count, found variable } } diff --git a/src/test/compile-fail/non-copyable-void.rs b/src/test/compile-fail/non-copyable-void.rs index cd134ccf71d..40b641519b0 100644 --- a/src/test/compile-fail/non-copyable-void.rs +++ b/src/test/compile-fail/non-copyable-void.rs @@ -11,7 +11,7 @@ extern crate libc; fn main() { - let x : *const Vec<int> = &vec!(1,2,3); + let x : *const Vec<isize> = &vec!(1,2,3); let y : *const libc::c_void = x as *const libc::c_void; unsafe { let _z = (*y).clone(); diff --git a/src/test/compile-fail/non-exhaustive-match.rs b/src/test/compile-fail/non-exhaustive-match.rs index 8fcf10f1c35..ccf69a4d2c8 100644 --- a/src/test/compile-fail/non-exhaustive-match.rs +++ b/src/test/compile-fail/non-exhaustive-match.rs @@ -16,10 +16,10 @@ fn main() { match true { //~ ERROR non-exhaustive patterns: `false` not covered true => {} } - match Some(10i) { //~ ERROR non-exhaustive patterns: `Some(_)` not covered + match Some(10is) { //~ ERROR non-exhaustive patterns: `Some(_)` not covered None => {} } - match (2i, 3i, 4i) { //~ ERROR non-exhaustive patterns: `(_, _, _)` not covered + match (2is, 3is, 4is) { //~ ERROR non-exhaustive patterns: `(_, _, _)` not covered (_, _, 4) => {} } match (t::a, t::a) { //~ ERROR non-exhaustive patterns: `(a, a)` not covered @@ -35,15 +35,15 @@ fn main() { (_, t::a) => {} (t::b, t::b) => {} } - let vec = vec!(Some(42i), None, Some(21i)); - let vec: &[Option<int>] = vec.as_slice(); + let vec = vec!(Some(42is), None, Some(21is)); + let vec: &[Option<isize>] = vec.as_slice(); match vec { //~ ERROR non-exhaustive patterns: `[]` not covered [Some(..), None, tail..] => {} [Some(..), Some(..), tail..] => {} [None] => {} } - let vec = vec!(1i); - let vec: &[int] = vec.as_slice(); + let vec = vec!(1is); + let vec: &[isize] = vec.as_slice(); match vec { [_, tail..] => (), [] => () @@ -56,8 +56,8 @@ fn main() { [0.1] => (), [] => () } - let vec = vec!(Some(42i), None, Some(21i)); - let vec: &[Option<int>] = vec.as_slice(); + let vec = vec!(Some(42is), None, Some(21is)); + let vec: &[Option<isize>] = vec.as_slice(); match vec { [Some(..), None, tail..] => {} [Some(..), Some(..), tail..] => {} diff --git a/src/test/compile-fail/non-exhaustive-pattern-witness.rs b/src/test/compile-fail/non-exhaustive-pattern-witness.rs index d35e3ad3c55..3bd3a0c653c 100644 --- a/src/test/compile-fail/non-exhaustive-pattern-witness.rs +++ b/src/test/compile-fail/non-exhaustive-pattern-witness.rs @@ -12,7 +12,7 @@ struct Foo { first: bool, - second: Option<[uint; 4]> + second: Option<[usize; 4]> } enum Color { @@ -27,7 +27,7 @@ fn struct_with_a_nested_enum_and_vector() { Foo { first: true, second: None } => (), Foo { first: true, second: Some(_) } => (), Foo { first: false, second: None } => (), - Foo { first: false, second: Some([1u, 2u, 3u, 4u]) } => () + Foo { first: false, second: Some([1us, 2us, 3us, 4us]) } => () } } diff --git a/src/test/compile-fail/noncopyable-class.rs b/src/test/compile-fail/noncopyable-class.rs index ec8369d6736..029b8485993 100644 --- a/src/test/compile-fail/noncopyable-class.rs +++ b/src/test/compile-fail/noncopyable-class.rs @@ -13,14 +13,14 @@ #[derive(Show)] struct bar { - x: int, + x: isize, } impl Drop for bar { fn drop(&mut self) {} } -fn bar(x:int) -> bar { +fn bar(x:isize) -> bar { bar { x: x } @@ -28,11 +28,11 @@ fn bar(x:int) -> bar { #[derive(Show)] struct foo { - i: int, + i: isize, j: bar, } -fn foo(i:int) -> foo { +fn foo(i:isize) -> foo { foo { i: i, j: bar(5) diff --git a/src/test/compile-fail/nonscalar-cast.rs b/src/test/compile-fail/nonscalar-cast.rs index 728f66a6aa7..f32c96b7b64 100644 --- a/src/test/compile-fail/nonscalar-cast.rs +++ b/src/test/compile-fail/nonscalar-cast.rs @@ -12,9 +12,9 @@ #[derive(Show)] struct foo { - x: int + x: isize } fn main() { - println!("{}", foo{ x: 1 } as int); + println!("{}", foo{ x: 1 } as isize); } diff --git a/src/test/compile-fail/not-a-pred.rs b/src/test/compile-fail/not-a-pred.rs index 2e16c58eaad..782c90a6c26 100644 --- a/src/test/compile-fail/not-a-pred.rs +++ b/src/test/compile-fail/not-a-pred.rs @@ -10,8 +10,8 @@ // error-pattern: lt -fn f(a: int, b: int) : lt(a, b) { } +fn f(a: isize, b: isize) : lt(a, b) { } -fn lt(a: int, b: int) { } +fn lt(a: isize, b: isize) { } -fn main() { let a: int = 10; let b: int = 23; check (lt(a, b)); f(a, b); } +fn main() { let a: isize = 10; let b: isize = 23; check (lt(a, b)); f(a, b); } diff --git a/src/test/compile-fail/not-enough-arguments.rs b/src/test/compile-fail/not-enough-arguments.rs index 2deb9591a83..c952906e5e8 100644 --- a/src/test/compile-fail/not-enough-arguments.rs +++ b/src/test/compile-fail/not-enough-arguments.rs @@ -12,7 +12,7 @@ // mismatch between the # of params, and not other // unrelated errors. -fn foo(a: int, b: int, c: int, d:int) { +fn foo(a: isize, b: isize, c: isize, d:isize) { panic!(); } diff --git a/src/test/compile-fail/obsolete-tilde.rs b/src/test/compile-fail/obsolete-tilde.rs index fa59798c1d5..d290d5536a4 100644 --- a/src/test/compile-fail/obsolete-tilde.rs +++ b/src/test/compile-fail/obsolete-tilde.rs @@ -10,12 +10,12 @@ // Test that ~ pointers give an obsolescence message. -fn foo(x: ~int) {} //~ ERROR obsolete syntax: `~` notation for owned pointers +fn foo(x: ~isize) {} //~ ERROR obsolete syntax: `~` notation for owned pointers fn bar(x: ~str) {} //~ ERROR obsolete syntax: `~` notation for owned pointers -fn baz(x: ~[int]) {} //~ ERROR obsolete syntax: `~[T]` is no longer a type +fn baz(x: ~[isize]) {} //~ ERROR obsolete syntax: `~[T]` is no longer a type fn main() { - let x = ~4i; //~ ERROR obsolete syntax: `~` notation for owned pointer allocation + let x = ~4is; //~ ERROR obsolete syntax: `~` notation for owned pointer allocation let y = ~"hello"; //~ ERROR obsolete syntax: `~` notation for owned pointer allocation - let z = ~[1i, 2, 3]; //~ ERROR obsolete syntax: `~[T]` is no longer a type + let z = ~[1is, 2, 3]; //~ ERROR obsolete syntax: `~[T]` is no longer a type } diff --git a/src/test/compile-fail/obsolete-tuple-struct-deref.rs b/src/test/compile-fail/obsolete-tuple-struct-deref.rs index 9ea7d960da9..ad5fac3e21e 100644 --- a/src/test/compile-fail/obsolete-tuple-struct-deref.rs +++ b/src/test/compile-fail/obsolete-tuple-struct-deref.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - struct S(int); + struct S(isize); let s = S(0); let x = *s; //~ ERROR single-field tuple-structs can no longer be dereferenced } diff --git a/src/test/compile-fail/occurs-check-2.rs b/src/test/compile-fail/occurs-check-2.rs index 2765182225f..bfabcff5116 100644 --- a/src/test/compile-fail/occurs-check-2.rs +++ b/src/test/compile-fail/occurs-check-2.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] fn main() { let f; diff --git a/src/test/compile-fail/occurs-check-3.rs b/src/test/compile-fail/occurs-check-3.rs index 4cda97bcb4a..ba7688e8524 100644 --- a/src/test/compile-fail/occurs-check-3.rs +++ b/src/test/compile-fail/occurs-check-3.rs @@ -11,4 +11,4 @@ // error-pattern:mismatched types // From Issue #778 enum clam<T> { a(T), } -fn main() { let c; c = clam::a(c); match c { clam::a::<int>(_) => { } } } +fn main() { let c; c = clam::a(c); match c { clam::a::<isize>(_) => { } } } diff --git a/src/test/compile-fail/occurs-check.rs b/src/test/compile-fail/occurs-check.rs index 44318b36f4b..417bd9b57ee 100644 --- a/src/test/compile-fail/occurs-check.rs +++ b/src/test/compile-fail/occurs-check.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] fn main() { let f; diff --git a/src/test/compile-fail/opt-out-copy-bad.rs b/src/test/compile-fail/opt-out-copy-bad.rs deleted file mode 100644 index 9e425fa8f2e..00000000000 --- a/src/test/compile-fail/opt-out-copy-bad.rs +++ /dev/null @@ -1,44 +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. - -#![feature(opt_out_copy)] -//~^ WARNING feature is deprecated -//~| WARNING feature is deprecated - -// Test that when using the `opt-out-copy` feature we still consider -// destructors to be non-movable - -struct CantCopyThis; - -impl Drop for CantCopyThis { - fn drop(&mut self) { } -} - -struct IWantToCopyThis { - but_i_cant: CantCopyThis, -} - -impl Copy for IWantToCopyThis {} -//~^ ERROR the trait `Copy` may not be implemented for this type - -enum CantCopyThisEither { - A, - B(::std::marker::NoCopy), -} - -enum IWantToCopyThisToo { - ButICant(CantCopyThisEither), -} - -impl Copy for IWantToCopyThisToo {} -//~^ ERROR the trait `Copy` may not be implemented for this type - -fn main() {} - diff --git a/src/test/compile-fail/or-patter-mismatch.rs b/src/test/compile-fail/or-patter-mismatch.rs index e79113ceb89..74f674e64ba 100644 --- a/src/test/compile-fail/or-patter-mismatch.rs +++ b/src/test/compile-fail/or-patter-mismatch.rs @@ -10,6 +10,6 @@ // error-pattern: mismatched types -enum blah { a(int, int, uint), b(int, int), } +enum blah { a(isize, isize, usize), b(isize, isize), } -fn main() { match blah::a(1, 1, 2u) { blah::a(_, x, y) | blah::b(x, y) => { } } } +fn main() { match blah::a(1, 1, 2us) { blah::a(_, x, y) | blah::b(x, y) => { } } } diff --git a/src/test/compile-fail/output-type-mismatch.rs b/src/test/compile-fail/output-type-mismatch.rs index bc77765ebf4..158e99ac200 100644 --- a/src/test/compile-fail/output-type-mismatch.rs +++ b/src/test/compile-fail/output-type-mismatch.rs @@ -12,4 +12,4 @@ fn f() { } -fn main() { let i: int; i = f(); } +fn main() { let i: isize; i = f(); } diff --git a/src/test/compile-fail/overloaded-calls-bad.rs b/src/test/compile-fail/overloaded-calls-bad.rs index b3a4c312589..d784ba2d0d6 100644 --- a/src/test/compile-fail/overloaded-calls-bad.rs +++ b/src/test/compile-fail/overloaded-calls-bad.rs @@ -13,12 +13,12 @@ use std::ops::FnMut; struct S { - x: int, - y: int, + x: isize, + y: isize, } -impl FnMut<(int,),int> for S { - extern "rust-call" fn call_mut(&mut self, (z,): (int,)) -> int { +impl FnMut<(isize,),isize> for S { + extern "rust-call" fn call_mut(&mut self, (z,): (isize,)) -> isize { self.x * self.y * z } } diff --git a/src/test/compile-fail/overloaded-calls-nontuple.rs b/src/test/compile-fail/overloaded-calls-nontuple.rs index 396a809c2e1..c06ab04cd84 100644 --- a/src/test/compile-fail/overloaded-calls-nontuple.rs +++ b/src/test/compile-fail/overloaded-calls-nontuple.rs @@ -13,12 +13,12 @@ use std::ops::FnMut; struct S { - x: int, - y: int, + x: isize, + y: isize, } -impl FnMut<int,int> for S { - extern "rust-call" fn call_mut(&mut self, z: int) -> int { +impl FnMut<isize,isize> for S { + extern "rust-call" fn call_mut(&mut self, z: isize) -> isize { self.x + self.y + z } } diff --git a/src/test/compile-fail/packed-struct-generic-transmute.rs b/src/test/compile-fail/packed-struct-generic-transmute.rs index 38177d07645..6b6ab3f2970 100644 --- a/src/test/compile-fail/packed-struct-generic-transmute.rs +++ b/src/test/compile-fail/packed-struct-generic-transmute.rs @@ -15,8 +15,6 @@ // error-pattern: transmute called on types with different size -#![feature(slicing_syntax)] - use std::mem; #[repr(packed)] @@ -34,6 +32,6 @@ fn main() { let foo = Foo { bar: [1u8, 2, 3, 4, 5], baz: 10i32 }; unsafe { let oof: Oof<[u8; 5], i32> = mem::transmute(foo); - println!("{} {}", &oof.rab[], oof.zab); + println!("{:?} {:?}", &oof.rab[], oof.zab); } } diff --git a/src/test/compile-fail/packed-struct-transmute.rs b/src/test/compile-fail/packed-struct-transmute.rs index 200c8a5137a..b80dd0b36ed 100644 --- a/src/test/compile-fail/packed-struct-transmute.rs +++ b/src/test/compile-fail/packed-struct-transmute.rs @@ -20,13 +20,13 @@ use std::mem; #[repr(packed)] struct Foo { bar: u8, - baz: uint + baz: usize } #[derive(Show)] struct Oof { rab: u8, - zab: uint + zab: usize } fn main() { diff --git a/src/test/compile-fail/pat-range-bad-dots.rs b/src/test/compile-fail/pat-range-bad-dots.rs index 7fe073a4c3d..7f67d7a5fb1 100644 --- a/src/test/compile-fail/pat-range-bad-dots.rs +++ b/src/test/compile-fail/pat-range-bad-dots.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - match 22i { + match 22is { 0 .. 3 => {} //~ ERROR expected one of `...`, `=>`, or `|`, found `..` _ => {} } diff --git a/src/test/compile-fail/pat-ref-enum.rs b/src/test/compile-fail/pat-ref-enum.rs index f1f0637a318..062d3308c3d 100644 --- a/src/test/compile-fail/pat-ref-enum.rs +++ b/src/test/compile-fail/pat-ref-enum.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn matcher(x: Option<int>) { +fn matcher(x: Option<isize>) { match x { ref Some(i) => {} //~ ERROR expected identifier, found enum pattern None => {} diff --git a/src/test/compile-fail/pat-shadow-in-nested-binding.rs b/src/test/compile-fail/pat-shadow-in-nested-binding.rs index 4d89ec14d94..526e4c16187 100644 --- a/src/test/compile-fail/pat-shadow-in-nested-binding.rs +++ b/src/test/compile-fail/pat-shadow-in-nested-binding.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct foo(uint); +struct foo(usize); fn main() { let (foo, _) = (2, 3); //~ ERROR declaration of `foo` shadows diff --git a/src/test/compile-fail/pattern-bindings-after-at.rs b/src/test/compile-fail/pattern-bindings-after-at.rs index 9cd2d0d28b1..70840200aad 100644 --- a/src/test/compile-fail/pattern-bindings-after-at.rs +++ b/src/test/compile-fail/pattern-bindings-after-at.rs @@ -14,8 +14,8 @@ enum Option<T> { } fn main() { - match &mut Some(1i) { - ref mut z @ &Some(ref a) => { + match &mut Some(1is) { + ref mut z @ &mut Some(ref a) => { //~^ ERROR pattern bindings are not allowed after an `@` **z = None; println!("{}", *a); diff --git a/src/test/compile-fail/pattern-error-continue.rs b/src/test/compile-fail/pattern-error-continue.rs index 8b65af00fb1..c288429dcda 100644 --- a/src/test/compile-fail/pattern-error-continue.rs +++ b/src/test/compile-fail/pattern-error-continue.rs @@ -11,13 +11,13 @@ // Test that certain pattern-match type errors are non-fatal enum A { - B(int, int), - C(int, int, int), + B(isize, isize), + C(isize, isize, isize), D } struct S { - a: int + a: isize } fn f(_c: char) {} diff --git a/src/test/compile-fail/pattern-ident-path-generics.rs b/src/test/compile-fail/pattern-ident-path-generics.rs index ab77e376979..58288fa4842 100644 --- a/src/test/compile-fail/pattern-ident-path-generics.rs +++ b/src/test/compile-fail/pattern-ident-path-generics.rs @@ -10,7 +10,7 @@ fn main() { match Some("foo") { - None::<int> => {} //~ ERROR mismatched types + None::<isize> => {} //~ ERROR mismatched types Some(_) => {} } } diff --git a/src/test/compile-fail/pattern-tyvar-2.rs b/src/test/compile-fail/pattern-tyvar-2.rs index ff898ebd16b..cd4a98835c8 100644 --- a/src/test/compile-fail/pattern-tyvar-2.rs +++ b/src/test/compile-fail/pattern-tyvar-2.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum bar { t1((), Option<Vec<int>>), t2, } +enum bar { t1((), Option<Vec<isize>>), t2, } // n.b. my change changes this error message, but I think it's right -- tjc -fn foo(t: bar) -> int { match t { bar::t1(_, Some(x)) => { return x * 3; } _ => { panic!(); } } } +fn foo(t: bar) -> isize { match t { bar::t1(_, Some(x)) => { return x * 3; } _ => { panic!(); } } } //~^ ERROR binary operation `*` cannot be applied to fn main() { } diff --git a/src/test/compile-fail/pattern-tyvar.rs b/src/test/compile-fail/pattern-tyvar.rs index 01b288fdaad..be8d3e027e7 100644 --- a/src/test/compile-fail/pattern-tyvar.rs +++ b/src/test/compile-fail/pattern-tyvar.rs @@ -10,11 +10,11 @@ // error-pattern: mismatched types -enum bar { t1((), Option<Vec<int> >), t2, } +enum bar { t1((), Option<Vec<isize> >), t2, } fn foo(t: bar) { match t { - bar::t1(_, Some::<int>(x)) => { + bar::t1(_, Some::<isize>(x)) => { println!("{}", x); } _ => { panic!(); } diff --git a/src/test/compile-fail/pptypedef.rs b/src/test/compile-fail/pptypedef.rs index b33b89be35d..e3c440d61ce 100644 --- a/src/test/compile-fail/pptypedef.rs +++ b/src/test/compile-fail/pptypedef.rs @@ -11,9 +11,9 @@ fn let_in<T, F>(x: T, f: F) where F: FnOnce(T) {} fn main() { - let_in(3u, |i| { assert!(i == 3is); }); + let_in(3us, |i| { assert!(i == 3is); }); //~^ ERROR expected `usize`, found `isize` - let_in(3i, |i| { assert!(i == 3us); }); + let_in(3is, |i| { assert!(i == 3us); }); //~^ ERROR expected `isize`, found `usize` } diff --git a/src/test/compile-fail/prim-with-args.rs b/src/test/compile-fail/prim-with-args.rs index 0587e033a97..cc0b74dc82a 100644 --- a/src/test/compile-fail/prim-with-args.rs +++ b/src/test/compile-fail/prim-with-args.rs @@ -10,24 +10,24 @@ fn main() { -let x: int<int>; //~ ERROR type parameters are not allowed on this type -let x: i8<int>; //~ ERROR type parameters are not allowed on this type -let x: i16<int>; //~ ERROR type parameters are not allowed on this type -let x: i32<int>; //~ ERROR type parameters are not allowed on this type -let x: i64<int>; //~ ERROR type parameters are not allowed on this type -let x: uint<int>; //~ ERROR type parameters are not allowed on this type -let x: u8<int>; //~ ERROR type parameters are not allowed on this type -let x: u16<int>; //~ ERROR type parameters are not allowed on this type -let x: u32<int>; //~ ERROR type parameters are not allowed on this type -let x: u64<int>; //~ ERROR type parameters are not allowed on this type -let x: char<int>; //~ ERROR type parameters are not allowed on this type +let x: isize<isize>; //~ ERROR type parameters are not allowed on this type +let x: i8<isize>; //~ ERROR type parameters are not allowed on this type +let x: i16<isize>; //~ ERROR type parameters are not allowed on this type +let x: i32<isize>; //~ ERROR type parameters are not allowed on this type +let x: i64<isize>; //~ ERROR type parameters are not allowed on this type +let x: usize<isize>; //~ ERROR type parameters are not allowed on this type +let x: u8<isize>; //~ ERROR type parameters are not allowed on this type +let x: u16<isize>; //~ ERROR type parameters are not allowed on this type +let x: u32<isize>; //~ ERROR type parameters are not allowed on this type +let x: u64<isize>; //~ ERROR type parameters are not allowed on this type +let x: char<isize>; //~ ERROR type parameters are not allowed on this type -let x: int<'static>; //~ ERROR lifetime parameters are not allowed on this type +let x: isize<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: i8<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: i16<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: i32<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: i64<'static>; //~ ERROR lifetime parameters are not allowed on this type -let x: uint<'static>; //~ ERROR lifetime parameters are not allowed on this type +let x: usize<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: u8<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: u16<'static>; //~ ERROR lifetime parameters are not allowed on this type let x: u32<'static>; //~ ERROR lifetime parameters are not allowed on this type diff --git a/src/test/compile-fail/privacy1.rs b/src/test/compile-fail/privacy1.rs index ffee00642ac..9dafae3d87d 100644 --- a/src/test/compile-fail/privacy1.rs +++ b/src/test/compile-fail/privacy1.rs @@ -41,7 +41,7 @@ mod bar { fn foo() -> Self; } - impl B for int { fn foo() -> int { 3 } } + impl B for isize { fn foo() -> isize { 3 } } pub enum Enum { Pub @@ -119,7 +119,7 @@ mod foo { //~^ ERROR: method `bar2` is private //~^^ NOTE: module `baz` is private - let _: int = + let _: isize = ::bar::B::foo(); //~ ERROR: method `foo` is inaccessible //~^ NOTE: trait `B` is private ::lol(); @@ -186,4 +186,4 @@ pub mod mytest { } } -#[start] fn main(_: int, _: *const *const u8) -> int { 3 } +#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 } diff --git a/src/test/compile-fail/privacy2.rs b/src/test/compile-fail/privacy2.rs index b38d7aedf84..b59905776d3 100644 --- a/src/test/compile-fail/privacy2.rs +++ b/src/test/compile-fail/privacy2.rs @@ -32,4 +32,4 @@ fn test2() { //~^ ERROR unresolved import `bar::glob::foo`. There is no `foo` in `bar::glob` } -#[start] fn main(_: int, _: *const *const u8) -> int { 3 } +#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 } diff --git a/src/test/compile-fail/privacy3.rs b/src/test/compile-fail/privacy3.rs index 5ec10d5a4ca..80219b70e07 100644 --- a/src/test/compile-fail/privacy3.rs +++ b/src/test/compile-fail/privacy3.rs @@ -29,4 +29,4 @@ fn test1() { gpriv(); } -#[start] fn main(_: int, _: *const *const u8) -> int { 3 } +#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 } diff --git a/src/test/compile-fail/privacy4.rs b/src/test/compile-fail/privacy4.rs index 92f3a57c69d..3f17d463890 100644 --- a/src/test/compile-fail/privacy4.rs +++ b/src/test/compile-fail/privacy4.rs @@ -32,4 +32,4 @@ fn test2() { gpriv(); } -#[start] fn main(_: int, _: *const *const u8) -> int { 3 } +#[start] fn main(_: isize, _: *const *const u8) -> isize { 3 } diff --git a/src/test/compile-fail/privacy5.rs b/src/test/compile-fail/privacy5.rs index 555969b65ff..df570fd4647 100644 --- a/src/test/compile-fail/privacy5.rs +++ b/src/test/compile-fail/privacy5.rs @@ -15,9 +15,9 @@ extern crate "privacy-tuple-struct" as other; mod a { pub struct A(()); - pub struct B(int); - pub struct C(pub int, int); - pub struct D(pub int); + pub struct B(isize); + pub struct C(pub isize, isize); + pub struct D(pub isize); fn test() { let a = A(()); diff --git a/src/test/compile-fail/private-impl-method.rs b/src/test/compile-fail/private-impl-method.rs index fe5908b40ab..c6e329aab04 100644 --- a/src/test/compile-fail/private-impl-method.rs +++ b/src/test/compile-fail/private-impl-method.rs @@ -10,7 +10,7 @@ mod a { pub struct Foo { - pub x: int + pub x: isize } impl Foo { diff --git a/src/test/compile-fail/private-method.rs b/src/test/compile-fail/private-method.rs index 88ab73e1f9d..e8e26cf8ce3 100644 --- a/src/test/compile-fail/private-method.rs +++ b/src/test/compile-fail/private-method.rs @@ -12,16 +12,16 @@ mod kitties { pub struct cat { - meows : uint, + meows : usize, - how_hungry : int, + how_hungry : isize, } impl cat { fn nap(&self) {} } - pub fn cat(in_x : uint, in_y : int) -> cat { + pub fn cat(in_x : usize, in_y : isize) -> cat { cat { meows: in_x, how_hungry: in_y @@ -30,6 +30,6 @@ mod kitties { } fn main() { - let nyan : kitties::cat = kitties::cat(52u, 99); + let nyan : kitties::cat = kitties::cat(52us, 99); nyan.nap(); } diff --git a/src/test/compile-fail/private-struct-field-cross-crate.rs b/src/test/compile-fail/private-struct-field-cross-crate.rs index 45c4b2b7ae1..36b6000ceeb 100644 --- a/src/test/compile-fail/private-struct-field-cross-crate.rs +++ b/src/test/compile-fail/private-struct-field-cross-crate.rs @@ -13,7 +13,7 @@ extern crate cci_class; use cci_class::kitties::cat; fn main() { - let nyan : cat = cat(52u, 99); - assert!((nyan.meows == 52u)); + let nyan : cat = cat(52us, 99); + assert!((nyan.meows == 52us)); //~^ ERROR field `meows` of struct `cci_class::kitties::cat` is private } diff --git a/src/test/compile-fail/private-struct-field-ctor.rs b/src/test/compile-fail/private-struct-field-ctor.rs index ae19c221496..0a0f2d490a8 100644 --- a/src/test/compile-fail/private-struct-field-ctor.rs +++ b/src/test/compile-fail/private-struct-field-ctor.rs @@ -10,7 +10,7 @@ mod a { pub struct Foo { - x: int + x: isize } } diff --git a/src/test/compile-fail/private-struct-field-pattern.rs b/src/test/compile-fail/private-struct-field-pattern.rs index 991457ef1ce..e9dd6cd1d74 100644 --- a/src/test/compile-fail/private-struct-field-pattern.rs +++ b/src/test/compile-fail/private-struct-field-pattern.rs @@ -12,7 +12,7 @@ use a::Foo; mod a { pub struct Foo { - x: int + x: isize } pub fn make() -> Foo { diff --git a/src/test/compile-fail/private-struct-field.rs b/src/test/compile-fail/private-struct-field.rs index 3f6fa573cc0..b98719e157e 100644 --- a/src/test/compile-fail/private-struct-field.rs +++ b/src/test/compile-fail/private-struct-field.rs @@ -10,7 +10,7 @@ mod cat { pub struct Cat { - meows: uint + meows: usize } pub fn new_cat() -> Cat { diff --git a/src/test/compile-fail/ptr-coercion.rs b/src/test/compile-fail/ptr-coercion.rs index d9b20748a7a..392a803b0dd 100644 --- a/src/test/compile-fail/ptr-coercion.rs +++ b/src/test/compile-fail/ptr-coercion.rs @@ -13,12 +13,12 @@ pub fn main() { // *const -> *mut - let x: *const int = &42i; - let x: *mut int = x; //~ERROR values differ in mutability + let x: *const isize = &42is; + let x: *mut isize = x; //~ERROR values differ in mutability // & -> *mut - let x: *mut int = &42; //~ERROR values differ in mutability + let x: *mut isize = &42; //~ERROR values differ in mutability - let x: *const int = &42; - let x: *mut int = x; //~ERROR values differ in mutability + let x: *const isize = &42; + let x: *mut isize = x; //~ERROR values differ in mutability } diff --git a/src/test/compile-fail/qquote-2.rs b/src/test/compile-fail/qquote-2.rs index 94485dddd13..978287a681e 100644 --- a/src/test/compile-fail/qquote-2.rs +++ b/src/test/compile-fail/qquote-2.rs @@ -52,7 +52,7 @@ fn mk_ctxt() -> fake_ext_ctxt { fn main() { let cx = mk_ctxt(); - let stmt = quote_stmt!(cx, let x int = 20;); //~ ERROR expected end-of-string + let stmt = quote_stmt!(cx, let x isize = 20;); //~ ERROR expected end-of-string check_pp(*stmt, pprust::print_stmt, ""); } diff --git a/src/test/compile-fail/range-1.rs b/src/test/compile-fail/range-1.rs index 0ade2975044..9888c085695 100644 --- a/src/test/compile-fail/range-1.rs +++ b/src/test/compile-fail/range-1.rs @@ -9,11 +9,10 @@ // except according to those terms. // Test range syntax - type errors. -#![feature(slicing_syntax)] pub fn main() { // Mixed types. - let _ = 0u..10i; + let _ = 0us..10is; //~^ ERROR start and end of range have incompatible types // Float => does not implement iterator. @@ -21,7 +20,7 @@ pub fn main() { //~^ ERROR `for` loop expression has type `core::ops::Range<f32>` which does not implement // Unsized type. - let arr: &[_] = &[1u, 2, 3]; + let arr: &[_] = &[1us, 2, 3]; let range = (*arr)..; //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/range-2.rs b/src/test/compile-fail/range-2.rs index 74c304884a0..6d176ca3700 100644 --- a/src/test/compile-fail/range-2.rs +++ b/src/test/compile-fail/range-2.rs @@ -9,11 +9,10 @@ // except according to those terms. // Test range syntax - borrow errors. -#![feature(slicing_syntax)] pub fn main() { let r = { - (&42i)..&42 + (&42is)..&42 //~^ ERROR borrowed value does not live long enough //~^^ ERROR borrowed value does not live long enough }; diff --git a/src/test/compile-fail/recursion.rs b/src/test/compile-fail/recursion.rs index 67177eff9f9..f39c839a0e7 100644 --- a/src/test/compile-fail/recursion.rs +++ b/src/test/compile-fail/recursion.rs @@ -8,18 +8,25 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// ignore-command-line: See https://github.com/rust-lang/rust/issues/20747 +// +// We also get a second error message at the top of file (dummy +// span). This is not helpful, but also kind of annoying to prevent, +// so for now just live with it, since we also get a second message +// that is more helpful. + enum Nil {NilValue} -struct Cons<T> {head:int, tail:T} -trait Dot {fn dot(&self, other:Self) -> int;} +struct Cons<T> {head:isize, tail:T} +trait Dot {fn dot(&self, other:Self) -> isize;} impl Dot for Nil { - fn dot(&self, _:Nil) -> int {0} + fn dot(&self, _:Nil) -> isize {0} } impl<T:Dot> Dot for Cons<T> { - fn dot(&self, other:Cons<T>) -> int { + fn dot(&self, other:Cons<T>) -> isize { self.head * other.head + self.tail.dot(other.tail) } } -fn test<T:Dot> (n:int, i:int, first:T, second:T) ->int { +fn test<T:Dot> (n:isize, i:isize, first:T, second:T) ->isize { match n { 0 => {first.dot(second)} //~^ ERROR: reached the recursion limit during monomorphization // Error message should be here. It should be a type error diff --git a/src/test/compile-fail/recursion_limit.rs b/src/test/compile-fail/recursion_limit.rs index 6e1ecb10e3a..6cd984c071a 100644 --- a/src/test/compile-fail/recursion_limit.rs +++ b/src/test/compile-fail/recursion_limit.rs @@ -35,7 +35,7 @@ link! { K, L } link! { L, M } link! { M, N } -enum N { N(uint) } +enum N { N(usize) } fn is_send<T:Send>() { } diff --git a/src/test/compile-fail/refutable-pattern-errors.rs b/src/test/compile-fail/refutable-pattern-errors.rs index 98d616ee3af..d06c73c4cc0 100644 --- a/src/test/compile-fail/refutable-pattern-errors.rs +++ b/src/test/compile-fail/refutable-pattern-errors.rs @@ -9,10 +9,10 @@ // except according to those terms. -fn func((1, (Some(1), 2...3)): (int, (Option<int>, int))) { } +fn func((1, (Some(1), 2...3)): (isize, (Option<isize>, isize))) { } //~^ ERROR refutable pattern in function argument: `(_, _)` not covered fn main() { - let (1i, (Some(1i), 2i...3i)) = (1i, (None, 2i)); + let (1is, (Some(1is), 2is...3is)) = (1is, (None, 2is)); //~^ ERROR refutable pattern in local binding: `(_, _)` not covered } diff --git a/src/test/compile-fail/refutable-pattern-in-fn-arg.rs b/src/test/compile-fail/refutable-pattern-in-fn-arg.rs index 575e9864a92..53f923e5061 100644 --- a/src/test/compile-fail/refutable-pattern-in-fn-arg.rs +++ b/src/test/compile-fail/refutable-pattern-in-fn-arg.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let f = |&: 3: int| println!("hello"); + let f = |&: 3: isize| println!("hello"); //~^ ERROR refutable pattern in function argument: `_` not covered f(4); } diff --git a/src/test/compile-fail/region-bound-on-closure-outlives-call.rs b/src/test/compile-fail/region-bound-on-closure-outlives-call.rs index 9e8281faf2f..5b04fa3d87c 100644 --- a/src/test/compile-fail/region-bound-on-closure-outlives-call.rs +++ b/src/test/compile-fail/region-bound-on-closure-outlives-call.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn call_rec<F>(mut f: F) -> uint where F: FnMut(uint) -> uint { +fn call_rec<F>(mut f: F) -> usize where F: FnMut(usize) -> usize { (|&mut: x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f` } diff --git a/src/test/compile-fail/region-lifetime-bounds-on-fns-where-clause.rs b/src/test/compile-fail/region-lifetime-bounds-on-fns-where-clause.rs index 3e6a95b04f7..ee05ba676ac 100644 --- a/src/test/compile-fail/region-lifetime-bounds-on-fns-where-clause.rs +++ b/src/test/compile-fail/region-lifetime-bounds-on-fns-where-clause.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn a<'a, 'b>(x: &mut &'a int, y: &mut &'b int) where 'b: 'a { +fn a<'a, 'b>(x: &mut &'a isize, y: &mut &'b isize) where 'b: 'a { // Note: this is legal because of the `'b:'a` declaration. *x = *y; } -fn b<'a, 'b>(x: &mut &'a int, y: &mut &'b int) { +fn b<'a, 'b>(x: &mut &'a isize, y: &mut &'b isize) { // Illegal now because there is no `'b:'a` declaration. *x = *y; //~ ERROR cannot infer } -fn c<'a,'b>(x: &mut &'a int, y: &mut &'b int) { +fn c<'a,'b>(x: &mut &'a isize, y: &mut &'b isize) { // Here we try to call `foo` but do not know that `'a` and `'b` are // related as required. a(x, y); //~ ERROR cannot infer @@ -27,13 +27,13 @@ fn c<'a,'b>(x: &mut &'a int, y: &mut &'b int) { fn d() { // 'a and 'b are early bound in the function `a` because they appear // inconstraints: - let _: fn(&mut &int, &mut &int) = a; //~ ERROR mismatched types + let _: fn(&mut &isize, &mut &isize) = a; //~ ERROR mismatched types } fn e() { // 'a and 'b are late bound in the function `b` because there are // no constraints: - let _: fn(&mut &int, &mut &int) = b; + let _: fn(&mut &isize, &mut &isize) = b; } fn main() { } diff --git a/src/test/compile-fail/region-multiple-lifetime-bounds-on-fns-where-clause.rs b/src/test/compile-fail/region-multiple-lifetime-bounds-on-fns-where-clause.rs index 2d635e9fc27..30e6a4e1277 100644 --- a/src/test/compile-fail/region-multiple-lifetime-bounds-on-fns-where-clause.rs +++ b/src/test/compile-fail/region-multiple-lifetime-bounds-on-fns-where-clause.rs @@ -8,19 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn a<'a, 'b, 'c>(x: &mut &'a int, y: &mut &'b int, z: &mut &'c int) where 'b: 'a + 'c { +fn a<'a, 'b, 'c>(x: &mut &'a isize, y: &mut &'b isize, z: &mut &'c isize) where 'b: 'a + 'c { // Note: this is legal because of the `'b:'a` declaration. *x = *y; *z = *y; } -fn b<'a, 'b, 'c>(x: &mut &'a int, y: &mut &'b int, z: &mut &'c int) { +fn b<'a, 'b, 'c>(x: &mut &'a isize, y: &mut &'b isize, z: &mut &'c isize) { // Illegal now because there is no `'b:'a` declaration. *x = *y; //~ ERROR cannot infer *z = *y; //~ ERROR cannot infer } -fn c<'a,'b, 'c>(x: &mut &'a int, y: &mut &'b int, z: &mut &'c int) { +fn c<'a,'b, 'c>(x: &mut &'a isize, y: &mut &'b isize, z: &mut &'c isize) { // Here we try to call `foo` but do not know that `'a` and `'b` are // related as required. a(x, y, z); //~ ERROR cannot infer @@ -29,13 +29,13 @@ fn c<'a,'b, 'c>(x: &mut &'a int, y: &mut &'b int, z: &mut &'c int) { fn d() { // 'a and 'b are early bound in the function `a` because they appear // inconstraints: - let _: fn(&mut &int, &mut &int, &mut &int) = a; //~ ERROR mismatched types + let _: fn(&mut &isize, &mut &isize, &mut &isize) = a; //~ ERROR mismatched types } fn e() { // 'a and 'b are late bound in the function `b` because there are // no constraints: - let _: fn(&mut &int, &mut &int, &mut &int) = b; + let _: fn(&mut &isize, &mut &isize, &mut &isize) = b; } fn main() { } diff --git a/src/test/compile-fail/region-object-lifetime-in-coercion.rs b/src/test/compile-fail/region-object-lifetime-in-coercion.rs index b2b2d3337c4..e4521873a61 100644 --- a/src/test/compile-fail/region-object-lifetime-in-coercion.rs +++ b/src/test/compile-fail/region-object-lifetime-in-coercion.rs @@ -11,6 +11,8 @@ // Test that attempts to implicitly coerce a value into an // object respect the lifetime bound on the object type. +#![feature(box_syntax)] + trait Foo {} impl<'a> Foo for &'a [u8] {} diff --git a/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs b/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs index 75e9e55138e..cdaa3468a46 100644 --- a/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs +++ b/src/test/compile-fail/regionck-unboxed-closure-lifetimes.rs @@ -17,7 +17,7 @@ fn main() { { let c = 1; let c_ref = &c; //~ ERROR `c` does not live long enough - f = move |&mut: a: int, b: int| { a + b + *c_ref }; + f = move |&mut: a: isize, b: isize| { a + b + *c_ref }; } } diff --git a/src/test/compile-fail/regions-addr-of-arg.rs b/src/test/compile-fail/regions-addr-of-arg.rs index 3e568180b53..c54b4aaace5 100644 --- a/src/test/compile-fail/regions-addr-of-arg.rs +++ b/src/test/compile-fail/regions-addr-of-arg.rs @@ -11,15 +11,15 @@ // Check that taking the address of an argument yields a lifetime // bounded by the current function call. -fn foo(a: int) { - let _p: &'static int = &a; //~ ERROR `a` does not live long enough +fn foo(a: isize) { + let _p: &'static isize = &a; //~ ERROR `a` does not live long enough } -fn bar(a: int) { - let _q: &int = &a; +fn bar(a: isize) { + let _q: &isize = &a; } -fn zed<'a>(a: int) -> &'a int { +fn zed<'a>(a: isize) -> &'a isize { &a //~ ERROR `a` does not live long enough } diff --git a/src/test/compile-fail/regions-addr-of-self.rs b/src/test/compile-fail/regions-addr-of-self.rs index fb2dbacef84..b69224d4499 100644 --- a/src/test/compile-fail/regions-addr-of-self.rs +++ b/src/test/compile-fail/regions-addr-of-self.rs @@ -9,24 +9,24 @@ // except according to those terms. struct dog { - cats_chased: uint, + cats_chased: usize, } impl dog { pub fn chase_cat(&mut self) { - let p: &'static mut uint = &mut self.cats_chased; //~ ERROR cannot infer - *p += 1u; + let p: &'static mut usize = &mut self.cats_chased; //~ ERROR cannot infer + *p += 1us; } pub fn chase_cat_2(&mut self) { - let p: &mut uint = &mut self.cats_chased; - *p += 1u; + let p: &mut usize = &mut self.cats_chased; + *p += 1us; } } fn dog() -> dog { dog { - cats_chased: 0u + cats_chased: 0us } } diff --git a/src/test/compile-fail/regions-addr-of-upvar-self.rs b/src/test/compile-fail/regions-addr-of-upvar-self.rs index fb60d8f7b27..fa76ab758ab 100644 --- a/src/test/compile-fail/regions-addr-of-upvar-self.rs +++ b/src/test/compile-fail/regions-addr-of-upvar-self.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::uint; +use std::usize; struct dog { - food: uint, + food: usize, } impl dog { pub fn chase_cat(&mut self) { let _f = |&:| { - let p: &'static mut uint = &mut self.food; //~ ERROR cannot infer - *p = 3u; + let p: &'static mut usize = &mut self.food; //~ ERROR cannot infer + *p = 3us; }; } } diff --git a/src/test/compile-fail/regions-bound-missing-bound-in-impl.rs b/src/test/compile-fail/regions-bound-missing-bound-in-impl.rs index c6a9f67cfc6..5028ec89972 100644 --- a/src/test/compile-fail/regions-bound-missing-bound-in-impl.rs +++ b/src/test/compile-fail/regions-bound-missing-bound-in-impl.rs @@ -13,7 +13,7 @@ // checked. struct Inv<'a> { // invariant w/r/t 'a - x: &'a mut &'a int + x: &'a mut &'a isize } pub trait Foo<'a> { @@ -24,7 +24,7 @@ pub trait Foo<'a> { } -impl<'a> Foo<'a> for &'a int { +impl<'a> Foo<'a> for &'a isize { fn no_bound<'b:'a>(self, b: Inv<'b>) { //~^ ERROR lifetime parameters or bounds on method `no_bound` do not match } diff --git a/src/test/compile-fail/regions-bounded-by-send.rs b/src/test/compile-fail/regions-bounded-by-send.rs index 0628bbb8bb0..e3f0d3bcdb6 100644 --- a/src/test/compile-fail/regions-bounded-by-send.rs +++ b/src/test/compile-fail/regions-bounded-by-send.rs @@ -20,41 +20,41 @@ trait Dummy:Send { } // lifetime pointers with 'static lifetime are ok -fn static_lifime_ok<'a,T,U:Send>(_: &'a int) { - assert_send::<&'static int>(); +fn static_lifime_ok<'a,T,U:Send>(_: &'a isize) { + assert_send::<&'static isize>(); assert_send::<&'static str>(); - assert_send::<&'static [int]>(); + assert_send::<&'static [isize]>(); // whether or not they are mutable - assert_send::<&'static mut int>(); + assert_send::<&'static mut isize>(); } // otherwise lifetime pointers are not ok -fn param_not_ok<'a>(x: &'a int) { - assert_send::<&'a int>(); //~ ERROR declared lifetime bound not satisfied +fn param_not_ok<'a>(x: &'a isize) { + assert_send::<&'a isize>(); //~ ERROR declared lifetime bound not satisfied } -fn param_not_ok1<'a>(_: &'a int) { +fn param_not_ok1<'a>(_: &'a isize) { assert_send::<&'a str>(); //~ ERROR declared lifetime bound not satisfied } -fn param_not_ok2<'a>(_: &'a int) { - assert_send::<&'a [int]>(); //~ ERROR declared lifetime bound not satisfied +fn param_not_ok2<'a>(_: &'a isize) { + assert_send::<&'a [isize]>(); //~ ERROR declared lifetime bound not satisfied } // boxes are ok fn box_ok() { - assert_send::<Box<int>>(); + assert_send::<Box<isize>>(); assert_send::<String>(); - assert_send::<Vec<int>>(); + assert_send::<Vec<isize>>(); } // but not if they own a bad thing fn box_with_region_not_ok<'a>() { - assert_send::<Box<&'a int>>(); //~ ERROR declared lifetime bound not satisfied + assert_send::<Box<&'a isize>>(); //~ ERROR declared lifetime bound not satisfied } // objects with insufficient bounds no ok @@ -71,11 +71,11 @@ fn object_with_send_bound_not_ok<'a>() { // unsafe pointers are ok unless they point at unsendable things -struct UniqueUnsafePtr(Unique<*const int>); +struct UniqueUnsafePtr(Unique<*const isize>); unsafe impl Send for UniqueUnsafePtr {} -fn unsafe_ok1<'a>(_: &'a int) { +fn unsafe_ok1<'a>(_: &'a isize) { assert_send::<UniqueUnsafePtr>(); } diff --git a/src/test/compile-fail/regions-bounded-by-trait-requiring-static.rs b/src/test/compile-fail/regions-bounded-by-trait-requiring-static.rs index e3939a4e390..8194af25d73 100644 --- a/src/test/compile-fail/regions-bounded-by-trait-requiring-static.rs +++ b/src/test/compile-fail/regions-bounded-by-trait-requiring-static.rs @@ -17,56 +17,56 @@ fn assert_send<T:'static>() { } // lifetime pointers with 'static lifetime are ok -fn static_lifime_ok<'a,T,U:Send>(_: &'a int) { - assert_send::<&'static int>(); +fn static_lifime_ok<'a,T,U:Send>(_: &'a isize) { + assert_send::<&'static isize>(); assert_send::<&'static str>(); - assert_send::<&'static [int]>(); + assert_send::<&'static [isize]>(); // whether or not they are mutable - assert_send::<&'static mut int>(); + assert_send::<&'static mut isize>(); } // otherwise lifetime pointers are not ok -fn param_not_ok<'a>(x: &'a int) { - assert_send::<&'a int>(); //~ ERROR declared lifetime bound not satisfied +fn param_not_ok<'a>(x: &'a isize) { + assert_send::<&'a isize>(); //~ ERROR declared lifetime bound not satisfied } -fn param_not_ok1<'a>(_: &'a int) { +fn param_not_ok1<'a>(_: &'a isize) { assert_send::<&'a str>(); //~ ERROR declared lifetime bound not satisfied } -fn param_not_ok2<'a>(_: &'a int) { - assert_send::<&'a [int]>(); //~ ERROR declared lifetime bound not satisfied +fn param_not_ok2<'a>(_: &'a isize) { + assert_send::<&'a [isize]>(); //~ ERROR declared lifetime bound not satisfied } // boxes are ok fn box_ok() { - assert_send::<Box<int>>(); + assert_send::<Box<isize>>(); assert_send::<String>(); - assert_send::<Vec<int>>(); + assert_send::<Vec<isize>>(); } // but not if they own a bad thing fn box_with_region_not_ok<'a>() { - assert_send::<Box<&'a int>>(); //~ ERROR declared lifetime bound not satisfied + assert_send::<Box<&'a isize>>(); //~ ERROR declared lifetime bound not satisfied } // unsafe pointers are ok unless they point at unsendable things -fn unsafe_ok1<'a>(_: &'a int) { - assert_send::<*const int>(); - assert_send::<*mut int>(); +fn unsafe_ok1<'a>(_: &'a isize) { + assert_send::<*const isize>(); + assert_send::<*mut isize>(); } -fn unsafe_ok2<'a>(_: &'a int) { - assert_send::<*const &'a int>(); //~ ERROR declared lifetime bound not satisfied +fn unsafe_ok2<'a>(_: &'a isize) { + assert_send::<*const &'a isize>(); //~ ERROR declared lifetime bound not satisfied } -fn unsafe_ok3<'a>(_: &'a int) { - assert_send::<*mut &'a int>(); //~ ERROR declared lifetime bound not satisfied +fn unsafe_ok3<'a>(_: &'a isize) { + assert_send::<*mut &'a isize>(); //~ ERROR declared lifetime bound not satisfied } fn main() { diff --git a/src/test/compile-fail/regions-bounded-method-type-parameters-trait-bound.rs b/src/test/compile-fail/regions-bounded-method-type-parameters-trait-bound.rs index e628eb3285a..acc721f26b3 100644 --- a/src/test/compile-fail/regions-bounded-method-type-parameters-trait-bound.rs +++ b/src/test/compile-fail/regions-bounded-method-type-parameters-trait-bound.rs @@ -19,7 +19,7 @@ trait Sized { } struct Inv<'a> { // invariant w/r/t 'a - x: &'a mut &'a int + x: &'a mut &'a isize } trait Foo<'x> { diff --git a/src/test/compile-fail/regions-bounded-method-type-parameters.rs b/src/test/compile-fail/regions-bounded-method-type-parameters.rs index 10484925980..9afacacd662 100644 --- a/src/test/compile-fail/regions-bounded-method-type-parameters.rs +++ b/src/test/compile-fail/regions-bounded-method-type-parameters.rs @@ -18,8 +18,8 @@ impl Foo { fn some_method<A:'static>(self) { } } -fn caller<'a>(x: &int) { - Foo.some_method::<&'a int>(); +fn caller<'a>(x: &isize) { + Foo.some_method::<&'a isize>(); //~^ ERROR declared lifetime bound not satisfied } diff --git a/src/test/compile-fail/regions-bounds.rs b/src/test/compile-fail/regions-bounds.rs index e13a6b211a5..c26740c9598 100644 --- a/src/test/compile-fail/regions-bounds.rs +++ b/src/test/compile-fail/regions-bounds.rs @@ -12,8 +12,8 @@ // nominal types (but not on other types) and that they are type // checked. -struct an_enum<'a>(&'a int); -struct a_class<'a> { x:&'a int } +struct an_enum<'a>(&'a isize); +struct a_class<'a> { x:&'a isize } fn a_fn1<'a,'b>(e: an_enum<'a>) -> an_enum<'b> { return e; //~ ERROR mismatched types: expected `an_enum<'b>`, found `an_enum<'a>` diff --git a/src/test/compile-fail/regions-close-associated-type-into-object.rs b/src/test/compile-fail/regions-close-associated-type-into-object.rs index 816314529b5..8a03f36972d 100644 --- a/src/test/compile-fail/regions-close-associated-type-into-object.rs +++ b/src/test/compile-fail/regions-close-associated-type-into-object.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + trait X {} trait Iter { diff --git a/src/test/compile-fail/regions-close-object-into-object.rs b/src/test/compile-fail/regions-close-object-into-object.rs index 48945868bd3..675f86b58f4 100644 --- a/src/test/compile-fail/regions-close-object-into-object.rs +++ b/src/test/compile-fail/regions-close-object-into-object.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait A<T> {} struct B<'a, T>(&'a (A<T>+'a)); diff --git a/src/test/compile-fail/regions-close-over-borrowed-ref-in-obj.rs b/src/test/compile-fail/regions-close-over-borrowed-ref-in-obj.rs index 037514f45c7..25b8137d29c 100644 --- a/src/test/compile-fail/regions-close-over-borrowed-ref-in-obj.rs +++ b/src/test/compile-fail/regions-close-over-borrowed-ref-in-obj.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + trait Foo { } -impl<'a> Foo for &'a int { } +impl<'a> Foo for &'a isize { } fn main() { let blah; { - let ss: &int = &1; //~ ERROR borrowed value does not live long enough + let ss: &isize = &1; //~ ERROR borrowed value does not live long enough blah = box ss as Box<Foo>; } } diff --git a/src/test/compile-fail/regions-close-over-type-parameter-1.rs b/src/test/compile-fail/regions-close-over-type-parameter-1.rs index 5465f199f40..fc18095fc83 100644 --- a/src/test/compile-fail/regions-close-over-type-parameter-1.rs +++ b/src/test/compile-fail/regions-close-over-type-parameter-1.rs @@ -8,11 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + // Test for what happens when a type parameter `A` is closed over into // an object. This should yield errors unless `A` (and the object) // both have suitable bounds. -trait SomeTrait { fn get(&self) -> int; } +trait SomeTrait { fn get(&self) -> isize; } fn make_object1<A:SomeTrait>(v: A) -> Box<SomeTrait+'static> { box v as Box<SomeTrait+'static> diff --git a/src/test/compile-fail/regions-close-over-type-parameter-2.rs b/src/test/compile-fail/regions-close-over-type-parameter-2.rs index 0ee349aaebf..543d4d1620b 100644 --- a/src/test/compile-fail/regions-close-over-type-parameter-2.rs +++ b/src/test/compile-fail/regions-close-over-type-parameter-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + // Test for what happens when a type parameter `A` is closed over into // an object. This should yield errors unless `A` (and the object) // both have suitable bounds. @@ -24,10 +26,10 @@ fn repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> { fn main() { // Error results because the type of is inferred to be - // ~Repeat<&'blk int> where blk is the lifetime of the block below. + // ~Repeat<&'blk isize> where blk is the lifetime of the block below. let _ = { - let tmp0 = 3i; + let tmp0 = 3is; let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough repeater3(tmp1) }; diff --git a/src/test/compile-fail/regions-close-over-type-parameter-multiple.rs b/src/test/compile-fail/regions-close-over-type-parameter-multiple.rs index cec785c6e96..0f8bc6d684f 100644 --- a/src/test/compile-fail/regions-close-over-type-parameter-multiple.rs +++ b/src/test/compile-fail/regions-close-over-type-parameter-multiple.rs @@ -8,10 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + // Various tests where we over type parameters with multiple lifetime // bounds. -trait SomeTrait { fn get(&self) -> int; } +trait SomeTrait { fn get(&self) -> isize; } fn make_object_good1<'a,'b,A:SomeTrait+'a+'b>(v: A) -> Box<SomeTrait+'a> { // A outlives 'a AND 'b... diff --git a/src/test/compile-fail/regions-close-param-into-object.rs b/src/test/compile-fail/regions-close-param-into-object.rs index 3e91d090c31..74b36958c92 100644 --- a/src/test/compile-fail/regions-close-param-into-object.rs +++ b/src/test/compile-fail/regions-close-param-into-object.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait X {} diff --git a/src/test/compile-fail/regions-creating-enums.rs b/src/test/compile-fail/regions-creating-enums.rs index 1774c9fada9..83cef9397c3 100644 --- a/src/test/compile-fail/regions-creating-enums.rs +++ b/src/test/compile-fail/regions-creating-enums.rs @@ -9,25 +9,25 @@ // except according to those terms. enum ast<'a> { - num(uint), + num(usize), add(&'a ast<'a>, &'a ast<'a>) } fn build() { - let x = ast::num(3u); - let y = ast::num(4u); + let x = ast::num(3us); + let y = ast::num(4us); let z = ast::add(&x, &y); compute(&z); } -fn compute(x: &ast) -> uint { +fn compute(x: &ast) -> usize { match *x { ast::num(x) => { x } ast::add(x, y) => { compute(x) + compute(y) } } } -fn map_nums<'a,'b, F>(x: &ast, f: &mut F) -> &'a ast<'b> where F: FnMut(uint) -> uint { +fn map_nums<'a,'b, F>(x: &ast, f: &mut F) -> &'a ast<'b> where F: FnMut(usize) -> usize { match *x { ast::num(x) => { return &ast::num((*f)(x)); //~ ERROR borrowed value does not live long enough diff --git a/src/test/compile-fail/regions-creating-enums3.rs b/src/test/compile-fail/regions-creating-enums3.rs index 6f38f29591f..4c8484540aa 100644 --- a/src/test/compile-fail/regions-creating-enums3.rs +++ b/src/test/compile-fail/regions-creating-enums3.rs @@ -9,7 +9,7 @@ // except according to those terms. enum ast<'a> { - num(uint), + num(usize), add(&'a ast<'a>, &'a ast<'a>) } diff --git a/src/test/compile-fail/regions-creating-enums4.rs b/src/test/compile-fail/regions-creating-enums4.rs index 34a125c809f..5dc9b370f32 100644 --- a/src/test/compile-fail/regions-creating-enums4.rs +++ b/src/test/compile-fail/regions-creating-enums4.rs @@ -9,7 +9,7 @@ // except according to those terms. enum ast<'a> { - num(uint), + num(usize), add(&'a ast<'a>, &'a ast<'a>) } diff --git a/src/test/compile-fail/regions-early-bound-error-method.rs b/src/test/compile-fail/regions-early-bound-error-method.rs index 0cb88b924f8..9de0ed070c7 100644 --- a/src/test/compile-fail/regions-early-bound-error-method.rs +++ b/src/test/compile-fail/regions-early-bound-error-method.rs @@ -12,21 +12,21 @@ // the value for a type parameter in a bound. trait GetRef<'a> { - fn get(&self) -> &'a int; + fn get(&self) -> &'a isize; } struct Box<'a> { - t: &'a int + t: &'a isize } impl<'a> GetRef<'a> for Box<'a> { - fn get(&self) -> &'a int { + fn get(&self) -> &'a isize { self.t } } impl<'a> Box<'a> { - fn or<'b,G:GetRef<'b>>(&self, g2: G) -> &'a int { + fn or<'b,G:GetRef<'b>>(&self, g2: G) -> &'a isize { g2.get() //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to } } diff --git a/src/test/compile-fail/regions-early-bound-error.rs b/src/test/compile-fail/regions-early-bound-error.rs index 5da281d93dd..37b74aea539 100644 --- a/src/test/compile-fail/regions-early-bound-error.rs +++ b/src/test/compile-fail/regions-early-bound-error.rs @@ -25,7 +25,7 @@ impl<'a,T:Clone> GetRef<'a,T> for Box<'a,T> { } } -fn get<'a,'b,G:GetRef<'a, int>>(g1: G, b: &'b int) -> &'b int { +fn get<'a,'b,G:GetRef<'a, isize>>(g1: G, b: &'b isize) -> &'b isize { g1.get() //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to } diff --git a/src/test/compile-fail/regions-enum-not-wf.rs b/src/test/compile-fail/regions-enum-not-wf.rs index 0691ad0de73..0165dbdabf3 100644 --- a/src/test/compile-fail/regions-enum-not-wf.rs +++ b/src/test/compile-fail/regions-enum-not-wf.rs @@ -18,7 +18,7 @@ enum Ref1<'a, T> { //~ ERROR the parameter type `T` may not live long enough enum Ref2<'a, T> { //~ ERROR the parameter type `T` may not live long enough Ref2Variant1, - Ref2Variant2(int, &'a T), + Ref2Variant2(isize, &'a T), } enum RefOk<'a, T:'a> { @@ -26,7 +26,7 @@ enum RefOk<'a, T:'a> { } enum RefIndirect<'a, T> { //~ ERROR the parameter type `T` may not live long enough - RefIndirectVariant1(int, RefOk<'a,T>) + RefIndirectVariant1(isize, RefOk<'a,T>) } enum RefDouble<'a, 'b, T> { //~ ERROR reference has a longer lifetime than the data diff --git a/src/test/compile-fail/regions-escape-bound-fn-2.rs b/src/test/compile-fail/regions-escape-bound-fn-2.rs index 547accbf086..1329d05a0f6 100644 --- a/src/test/compile-fail/regions-escape-bound-fn-2.rs +++ b/src/test/compile-fail/regions-escape-bound-fn-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn with_int<F>(f: F) where F: FnOnce(&int) { +fn with_int<F>(f: F) where F: FnOnce(&isize) { let x = 3; f(&x); } diff --git a/src/test/compile-fail/regions-escape-bound-fn.rs b/src/test/compile-fail/regions-escape-bound-fn.rs index 6d67bd80650..02e62ffddfd 100644 --- a/src/test/compile-fail/regions-escape-bound-fn.rs +++ b/src/test/compile-fail/regions-escape-bound-fn.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn with_int<F>(f: F) where F: FnOnce(&int) { +fn with_int<F>(f: F) where F: FnOnce(&isize) { let x = 3; f(&x); } fn main() { - let mut x: Option<&int> = None; + let mut x: Option<&isize> = None; with_int(|y| x = Some(y)); //~ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-escape-loop-via-variable.rs b/src/test/compile-fail/regions-escape-loop-via-variable.rs index 472df87dd2b..c300c86f70f 100644 --- a/src/test/compile-fail/regions-escape-loop-via-variable.rs +++ b/src/test/compile-fail/regions-escape-loop-via-variable.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = 3i; + let x = 3is; // Here, the variable `p` gets inferred to a type with a lifetime // of the loop body. The regionck then determines that this type @@ -17,7 +17,7 @@ fn main() { let mut p = &x; loop { - let x = 1i + *p; + let x = 1is + *p; p = &x; //~ ERROR `x` does not live long enough } } diff --git a/src/test/compile-fail/regions-escape-loop-via-vec.rs b/src/test/compile-fail/regions-escape-loop-via-vec.rs index 22c6bdd2d50..5e6e1858cf1 100644 --- a/src/test/compile-fail/regions-escape-loop-via-vec.rs +++ b/src/test/compile-fail/regions-escape-loop-via-vec.rs @@ -10,7 +10,7 @@ // The type of `y` ends up getting inferred to the type of the block. fn broken() { - let mut x = 3i; + let mut x = 3is; let mut _y = vec!(&mut x); while x < 10 { //~ ERROR cannot use `x` because it was mutably borrowed let mut z = x; //~ ERROR cannot use `x` because it was mutably borrowed diff --git a/src/test/compile-fail/regions-escape-unboxed-closure.rs b/src/test/compile-fail/regions-escape-unboxed-closure.rs index 70f0d61b5ee..06768fa6880 100644 --- a/src/test/compile-fail/regions-escape-unboxed-closure.rs +++ b/src/test/compile-fail/regions-escape-unboxed-closure.rs @@ -10,10 +10,10 @@ #![feature(unboxed_closures)] -fn with_int(f: &mut FnMut(&int)) { +fn with_int(f: &mut FnMut(&isize)) { } fn main() { - let mut x: Option<&int> = None; + let mut x: Option<&isize> = None; with_int(&mut |&mut: y| x = Some(y)); //~ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-escape-via-trait-or-not.rs b/src/test/compile-fail/regions-escape-via-trait-or-not.rs index 873d4cea039..a4363b00e1c 100644 --- a/src/test/compile-fail/regions-escape-via-trait-or-not.rs +++ b/src/test/compile-fail/regions-escape-via-trait-or-not.rs @@ -11,20 +11,20 @@ #![allow(dead_code)] trait Deref { - fn get(self) -> int; + fn get(self) -> isize; } -impl<'a> Deref for &'a int { - fn get(self) -> int { +impl<'a> Deref for &'a isize { + fn get(self) -> isize { *self } } -fn with<R:Deref, F>(f: F) -> int where F: FnOnce(&int) -> R { +fn with<R:Deref, F>(f: F) -> isize where F: FnOnce(&isize) -> R { f(&3).get() } -fn return_it() -> int { +fn return_it() -> isize { with(|o| o) //~ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-free-region-ordering-callee.rs b/src/test/compile-fail/regions-free-region-ordering-callee.rs index 6e59a29b8cf..22724081a1b 100644 --- a/src/test/compile-fail/regions-free-region-ordering-callee.rs +++ b/src/test/compile-fail/regions-free-region-ordering-callee.rs @@ -12,32 +12,32 @@ // that appear in their parameter list. See also // regions-free-region-ordering-caller.rs -fn ordering1<'a, 'b>(x: &'a &'b uint) -> &'a uint { +fn ordering1<'a, 'b>(x: &'a &'b usize) -> &'a usize { // It is safe to assume that 'a <= 'b due to the type of x - let y: &'b uint = &**x; + let y: &'b usize = &**x; return y; } -fn ordering2<'a, 'b>(x: &'a &'b uint, y: &'a uint) -> &'b uint { +fn ordering2<'a, 'b>(x: &'a &'b usize, y: &'a usize) -> &'b usize { // However, it is not safe to assume that 'b <= 'a &*y //~ ERROR cannot infer } -fn ordering3<'a, 'b>(x: &'a uint, y: &'b uint) -> &'a &'b uint { +fn ordering3<'a, 'b>(x: &'a usize, y: &'b usize) -> &'a &'b usize { // Do not infer an ordering from the return value. - let z: &'b uint = &*x; + let z: &'b usize = &*x; //~^ ERROR cannot infer panic!(); } -fn ordering4<'a, 'b, F>(a: &'a uint, b: &'b uint, x: F) where F: FnOnce(&'a &'b uint) { +fn ordering4<'a, 'b, F>(a: &'a usize, b: &'b usize, x: F) where F: FnOnce(&'a &'b usize) { // Do not infer ordering from closure argument types. - let z: Option<&'a &'b uint> = None; + let z: Option<&'a &'b usize> = None; //~^ ERROR reference has a longer lifetime than the data it references } -fn ordering5<'a, 'b>(a: &'a uint, b: &'b uint, x: Option<&'a &'b uint>) { - let z: Option<&'a &'b uint> = None; +fn ordering5<'a, 'b>(a: &'a usize, b: &'b usize, x: Option<&'a &'b usize>) { + let z: Option<&'a &'b usize> = None; } fn main() {} diff --git a/src/test/compile-fail/regions-free-region-ordering-caller.rs b/src/test/compile-fail/regions-free-region-ordering-caller.rs index 55c0cf3bb26..edca3b7ed41 100644 --- a/src/test/compile-fail/regions-free-region-ordering-caller.rs +++ b/src/test/compile-fail/regions-free-region-ordering-caller.rs @@ -12,21 +12,21 @@ // than the thing it points at and ensure that they result in // errors. See also regions-free-region-ordering-callee.rs -struct Paramd<'a> { x: &'a uint } +struct Paramd<'a> { x: &'a usize } -fn call2<'a, 'b>(a: &'a uint, b: &'b uint) { - let z: Option<&'b &'a uint> = None; +fn call2<'a, 'b>(a: &'a usize, b: &'b usize) { + let z: Option<&'b &'a usize> = None; //~^ ERROR reference has a longer lifetime than the data it references } -fn call3<'a, 'b>(a: &'a uint, b: &'b uint) { +fn call3<'a, 'b>(a: &'a usize, b: &'b usize) { let y: Paramd<'a> = Paramd { x: a }; let z: Option<&'b Paramd<'a>> = None; //~^ ERROR reference has a longer lifetime than the data it references } -fn call4<'a, 'b>(a: &'a uint, b: &'b uint) { - let z: Option<&'a &'b uint> = None; +fn call4<'a, 'b>(a: &'a usize, b: &'b usize) { + let z: Option<&'a &'b usize> = None; //~^ ERROR reference has a longer lifetime than the data it references } diff --git a/src/test/compile-fail/regions-free-region-ordering-caller1.rs b/src/test/compile-fail/regions-free-region-ordering-caller1.rs index b117a1a6476..b29518ccdab 100644 --- a/src/test/compile-fail/regions-free-region-ordering-caller1.rs +++ b/src/test/compile-fail/regions-free-region-ordering-caller1.rs @@ -12,11 +12,11 @@ // than the thing it points at and ensure that they result in // errors. See also regions-free-region-ordering-callee.rs -fn call1<'a>(x: &'a uint) { +fn call1<'a>(x: &'a usize) { // Test that creating a pointer like - // &'a &'z uint requires that 'a <= 'z: - let y: uint = 3; - let z: &'a & uint = &(&y); + // &'a &'z usize requires that 'a <= 'z: + let y: usize = 3; + let z: &'a & usize = &(&y); //~^ ERROR borrowed value does not live long enough //~^^ ERROR `y` does not live long enough } diff --git a/src/test/compile-fail/regions-glb-free-free.rs b/src/test/compile-fail/regions-glb-free-free.rs index 0eb47da16b6..f43d35c579e 100644 --- a/src/test/compile-fail/regions-glb-free-free.rs +++ b/src/test/compile-fail/regions-glb-free-free.rs @@ -12,8 +12,8 @@ mod argparse { pub struct Flag<'a> { name: &'a str, desc: &'a str, - max_count: uint, - value: uint + max_count: usize, + value: usize } pub fn flag<'r>(name: &'r str, desc: &'r str) -> Flag<'r> { diff --git a/src/test/compile-fail/regions-in-consts.rs b/src/test/compile-fail/regions-in-consts.rs index 9f2facf4e1f..8d0829a4cff 100644 --- a/src/test/compile-fail/regions-in-consts.rs +++ b/src/test/compile-fail/regions-in-consts.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static c_y: &int = &22; //~ ERROR missing lifetime specifier -static c_z: &'static int = &22; +static c_y: &isize = &22; //~ ERROR missing lifetime specifier +static c_z: &'static isize = &22; fn main() { } diff --git a/src/test/compile-fail/regions-in-enums-anon.rs b/src/test/compile-fail/regions-in-enums-anon.rs index 5c7a37d0359..305bf88c4d5 100644 --- a/src/test/compile-fail/regions-in-enums-anon.rs +++ b/src/test/compile-fail/regions-in-enums-anon.rs @@ -11,7 +11,7 @@ // Test that anonymous lifetimes are not permitted in enum declarations enum Foo { - Bar(&int) //~ ERROR missing lifetime specifier + Bar(&isize) //~ ERROR missing lifetime specifier } fn main() {} diff --git a/src/test/compile-fail/regions-in-enums.rs b/src/test/compile-fail/regions-in-enums.rs index 72b32e4a9af..613a90dda67 100644 --- a/src/test/compile-fail/regions-in-enums.rs +++ b/src/test/compile-fail/regions-in-enums.rs @@ -12,19 +12,19 @@ // See also regions-undeclared.rs enum yes0<'lt> { - X3(&'lt uint) + X3(&'lt usize) } enum yes1<'a> { - X4(&'a uint) + X4(&'a usize) } enum no0 { - X5(&'foo uint) //~ ERROR use of undeclared lifetime name `'foo` + X5(&'foo usize) //~ ERROR use of undeclared lifetime name `'foo` } enum no1 { - X6(&'a uint) //~ ERROR use of undeclared lifetime name `'a` + X6(&'a usize) //~ ERROR use of undeclared lifetime name `'a` } fn main() {} diff --git a/src/test/compile-fail/regions-in-structs-anon.rs b/src/test/compile-fail/regions-in-structs-anon.rs index 0f2036a56cd..b85928b1b9f 100644 --- a/src/test/compile-fail/regions-in-structs-anon.rs +++ b/src/test/compile-fail/regions-in-structs-anon.rs @@ -11,7 +11,7 @@ // Test that anonymous lifetimes are not permitted in struct declarations struct Foo { - x: &int //~ ERROR missing lifetime specifier + x: &isize //~ ERROR missing lifetime specifier } fn main() {} diff --git a/src/test/compile-fail/regions-in-structs.rs b/src/test/compile-fail/regions-in-structs.rs index 0c5cb98e6a4..c231d3a913e 100644 --- a/src/test/compile-fail/regions-in-structs.rs +++ b/src/test/compile-fail/regions-in-structs.rs @@ -9,16 +9,16 @@ // except according to those terms. struct yes1<'a> { - x: &'a uint, + x: &'a usize, } struct yes2<'a> { - x: &'a uint, + x: &'a usize, } struct StructDecl { - a: &'a int, //~ ERROR use of undeclared lifetime name `'a` - b: &'a int, //~ ERROR use of undeclared lifetime name `'a` + a: &'a isize, //~ ERROR use of undeclared lifetime name `'a` + b: &'a isize, //~ ERROR use of undeclared lifetime name `'a` } diff --git a/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs b/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs index b710578969b..2628e6a1ce2 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs +++ b/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs @@ -10,15 +10,15 @@ struct point { - x: int, - y: int, + x: isize, + y: isize, } -fn x_coord<'r>(p: &'r point) -> &'r int { +fn x_coord<'r>(p: &'r point) -> &'r isize { return &p.x; } -fn foo<'a>(p: Box<point>) -> &'a int { +fn foo<'a>(p: Box<point>) -> &'a isize { let xc = x_coord(&*p); //~ ERROR `*p` does not live long enough assert_eq!(*xc, 3); return xc; diff --git a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs index c8edd936bf2..a05658e9e58 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs +++ b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs @@ -13,9 +13,9 @@ fn borrow<T>(x: &T) -> &T {x} fn foo<C, M>(mut cond: C, mut make_box: M) where C: FnMut() -> bool, - M: FnMut() -> Box<int>, + M: FnMut() -> Box<isize>, { - let mut y: ∫ + let mut y: &isize; loop { let x = make_box(); diff --git a/src/test/compile-fail/regions-infer-bound-from-trait-self.rs b/src/test/compile-fail/regions-infer-bound-from-trait-self.rs index aeb003ca5d0..23b8ebfe54b 100644 --- a/src/test/compile-fail/regions-infer-bound-from-trait-self.rs +++ b/src/test/compile-fail/regions-infer-bound-from-trait-self.rs @@ -16,7 +16,7 @@ trait Static : 'static { } trait Is<'a> : 'a { } struct Inv<'a> { - x: Option<&'a mut &'a int> + x: Option<&'a mut &'a isize> } fn check_bound<'a,A:'a>(x: Inv<'a>, a: A) { } diff --git a/src/test/compile-fail/regions-infer-bound-from-trait.rs b/src/test/compile-fail/regions-infer-bound-from-trait.rs index d1111377f1e..f7a91054766 100644 --- a/src/test/compile-fail/regions-infer-bound-from-trait.rs +++ b/src/test/compile-fail/regions-infer-bound-from-trait.rs @@ -16,7 +16,7 @@ trait Static : 'static { } trait Is<'a> : 'a { } struct Inv<'a> { - x: Option<&'a mut &'a int> + x: Option<&'a mut &'a isize> } fn check_bound<'a,A:'a>(x: Inv<'a>, a: A) { } diff --git a/src/test/compile-fail/regions-infer-call-3.rs b/src/test/compile-fail/regions-infer-call-3.rs index ac41f2a5b3e..95783a420b6 100644 --- a/src/test/compile-fail/regions-infer-call-3.rs +++ b/src/test/compile-fail/regions-infer-call-3.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn select<'r>(x: &'r int, y: &'r int) -> &'r int { x } +fn select<'r>(x: &'r isize, y: &'r isize) -> &'r isize { x } -fn with<T, F>(f: F) -> T where F: FnOnce(&int) -> T { +fn with<T, F>(f: F) -> T where F: FnOnce(&isize) -> T { f(&20) } -fn manip<'a>(x: &'a int) -> int { +fn manip<'a>(x: &'a isize) -> isize { let z = with(|y| { select(x, y) }); //~^ ERROR cannot infer *z diff --git a/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs b/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs index 4d31d2c8e69..6c5e90a54de 100644 --- a/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs +++ b/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs @@ -24,8 +24,8 @@ struct Contravariant<'a> { } fn use_<'short,'long>(c: Contravariant<'short>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Contravariant<'short> <: Contravariant<'long>. Since diff --git a/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs b/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs index 1c3b7bb5960..d8e31fa1374 100644 --- a/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs +++ b/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs @@ -21,8 +21,8 @@ struct Covariant<'a> { } fn use_<'short,'long>(c: Covariant<'long>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Covariant<'long> <: Covariant<'short>. Since diff --git a/src/test/compile-fail/regions-infer-invariance-due-to-mutability-3.rs b/src/test/compile-fail/regions-infer-invariance-due-to-mutability-3.rs index 190e444fe7e..e42aa684e14 100644 --- a/src/test/compile-fail/regions-infer-invariance-due-to-mutability-3.rs +++ b/src/test/compile-fail/regions-infer-invariance-due-to-mutability-3.rs @@ -10,7 +10,7 @@ struct invariant<'a> { - f: Box<FnOnce(&mut &'a int) + 'static>, + f: Box<FnOnce(&mut &'a isize) + 'static>, } fn to_same_lifetime<'r>(bi: invariant<'r>) { diff --git a/src/test/compile-fail/regions-infer-invariance-due-to-mutability-4.rs b/src/test/compile-fail/regions-infer-invariance-due-to-mutability-4.rs index 71d0c988c5e..2e634dfe3eb 100644 --- a/src/test/compile-fail/regions-infer-invariance-due-to-mutability-4.rs +++ b/src/test/compile-fail/regions-infer-invariance-due-to-mutability-4.rs @@ -10,7 +10,7 @@ struct invariant<'a> { - f: Box<for<'b> FnOnce() -> &'b mut &'a int + 'static>, + f: Box<for<'b> FnOnce() -> &'b mut &'a isize + 'static>, } fn to_same_lifetime<'r>(bi: invariant<'r>) { diff --git a/src/test/compile-fail/regions-infer-not-param.rs b/src/test/compile-fail/regions-infer-not-param.rs index 323ebc3c20b..5d7a218ca8a 100644 --- a/src/test/compile-fail/regions-infer-not-param.rs +++ b/src/test/compile-fail/regions-infer-not-param.rs @@ -9,7 +9,7 @@ // except according to those terms. struct direct<'a> { - f: &'a int + f: &'a isize } struct indirect1 { diff --git a/src/test/compile-fail/regions-infer-paramd-method.rs b/src/test/compile-fail/regions-infer-paramd-method.rs index 772ccadda52..ef331bb0fd7 100644 --- a/src/test/compile-fail/regions-infer-paramd-method.rs +++ b/src/test/compile-fail/regions-infer-paramd-method.rs @@ -25,9 +25,9 @@ // refers to self. trait foo<'a> { - fn self_int(self) -> &'a int; + fn self_int(self) -> &'a isize; - fn any_int(self) -> ∫ + fn any_int(self) -> &isize; } struct with_foo<'a> { @@ -47,7 +47,7 @@ impl<'a> set_foo_foo for with_foo<'a> { // Bar is not region parameterized. trait bar { - fn any_int(&self) -> ∫ + fn any_int(&self) -> &isize; } struct with_bar { diff --git a/src/test/compile-fail/regions-infer-proc-static-upvar.rs b/src/test/compile-fail/regions-infer-proc-static-upvar.rs index 8b2fdfe7cdd..4e99f64dbf7 100644 --- a/src/test/compile-fail/regions-infer-proc-static-upvar.rs +++ b/src/test/compile-fail/regions-infer-proc-static-upvar.rs @@ -13,10 +13,10 @@ fn foo<F:FnOnce()+'static>(_p: F) { } -static i: int = 3; +static i: isize = 3; fn capture_local() { - let x = 3i; + let x = 3is; let y = &x; //~ ERROR `x` does not live long enough foo(move|| { let _a = *y; diff --git a/src/test/compile-fail/regions-lifetime-bounds-on-fns.rs b/src/test/compile-fail/regions-lifetime-bounds-on-fns.rs index 4a42728da6f..43940d499d2 100644 --- a/src/test/compile-fail/regions-lifetime-bounds-on-fns.rs +++ b/src/test/compile-fail/regions-lifetime-bounds-on-fns.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn a<'a, 'b:'a>(x: &mut &'a int, y: &mut &'b int) { +fn a<'a, 'b:'a>(x: &mut &'a isize, y: &mut &'b isize) { // Note: this is legal because of the `'b:'a` declaration. *x = *y; } -fn b<'a, 'b>(x: &mut &'a int, y: &mut &'b int) { +fn b<'a, 'b>(x: &mut &'a isize, y: &mut &'b isize) { // Illegal now because there is no `'b:'a` declaration. *x = *y; //~ ERROR cannot infer } -fn c<'a,'b>(x: &mut &'a int, y: &mut &'b int) { +fn c<'a,'b>(x: &mut &'a isize, y: &mut &'b isize) { // Here we try to call `foo` but do not know that `'a` and `'b` are // related as required. a(x, y); //~ ERROR cannot infer @@ -27,13 +27,13 @@ fn c<'a,'b>(x: &mut &'a int, y: &mut &'b int) { fn d() { // 'a and 'b are early bound in the function `a` because they appear // inconstraints: - let _: fn(&mut &int, &mut &int) = a; //~ ERROR mismatched types + let _: fn(&mut &isize, &mut &isize) = a; //~ ERROR mismatched types } fn e() { // 'a and 'b are late bound in the function `b` because there are // no constraints: - let _: fn(&mut &int, &mut &int) = b; + let _: fn(&mut &isize, &mut &isize) = b; } fn main() { } diff --git a/src/test/compile-fail/regions-name-duplicated.rs b/src/test/compile-fail/regions-name-duplicated.rs index 518fe0b00b6..b4b9cfd75cb 100644 --- a/src/test/compile-fail/regions-name-duplicated.rs +++ b/src/test/compile-fail/regions-name-duplicated.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo<'a, 'a> { //~ ERROR lifetime name `'a` declared twice - x: &'a int + x: &'a isize } fn main() {} diff --git a/src/test/compile-fail/regions-name-static.rs b/src/test/compile-fail/regions-name-static.rs index 9f50ad36660..29896aa486b 100644 --- a/src/test/compile-fail/regions-name-static.rs +++ b/src/test/compile-fail/regions-name-static.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo<'static> { //~ ERROR illegal lifetime parameter name: `'static` - x: &'static int + x: &'static isize } fn main() {} diff --git a/src/test/compile-fail/regions-name-undeclared.rs b/src/test/compile-fail/regions-name-undeclared.rs index b9c721159f2..a61d3094933 100644 --- a/src/test/compile-fail/regions-name-undeclared.rs +++ b/src/test/compile-fail/regions-name-undeclared.rs @@ -12,48 +12,48 @@ // rules correctly in various scenarios. struct Foo<'a> { - x: &'a int + x: &'a isize } impl<'a> Foo<'a> { // &'a is inherited: - fn m1(&self, arg: &'a int) { } + fn m1(&self, arg: &'a isize) { } fn m2(&'a self) { } fn m3(&self, arg: Foo<'a>) { } // &'b is not: - fn m4(&self, arg: &'b int) { } //~ ERROR undeclared lifetime + fn m4(&self, arg: &'b isize) { } //~ ERROR undeclared lifetime fn m5(&'b self) { } //~ ERROR undeclared lifetime fn m6(&self, arg: Foo<'b>) { } //~ ERROR undeclared lifetime } -fn bar<'a>(x: &'a int) { +fn bar<'a>(x: &'a isize) { // &'a is visible to code: - let y: &'a int = x; + let y: &'a isize = x; // &'a is not visible to *items*: - type X = Option<&'a int>; //~ ERROR undeclared lifetime + type X = Option<&'a isize>; //~ ERROR undeclared lifetime enum E { - E1(&'a int) //~ ERROR undeclared lifetime + E1(&'a isize) //~ ERROR undeclared lifetime } struct S { - f: &'a int //~ ERROR undeclared lifetime + f: &'a isize //~ ERROR undeclared lifetime } - fn f(a: &'a int) { } //~ ERROR undeclared lifetime + fn f(a: &'a isize) { } //~ ERROR undeclared lifetime // &'a CAN be declared on functions and used then: - fn g<'a>(a: &'a int) { } // OK - fn h(a: Box<for<'a> FnOnce(&'a int)>) { } // OK + fn g<'a>(a: &'a isize) { } // OK + fn h(a: Box<for<'a> FnOnce(&'a isize)>) { } // OK } // Test nesting of lifetimes in fn type declarations -fn fn_types(a: &'a int, //~ ERROR undeclared lifetime - b: Box<for<'a> FnOnce(&'a int, - &'b int, //~ ERROR undeclared lifetime - Box<for<'b> FnOnce(&'a int, - &'b int)>, - &'b int)>, //~ ERROR undeclared lifetime - c: &'a int) //~ ERROR undeclared lifetime +fn fn_types(a: &'a isize, //~ ERROR undeclared lifetime + b: Box<for<'a> FnOnce(&'a isize, + &'b isize, //~ ERROR undeclared lifetime + Box<for<'b> FnOnce(&'a isize, + &'b isize)>, + &'b isize)>, //~ ERROR undeclared lifetime + c: &'a isize) //~ ERROR undeclared lifetime { } diff --git a/src/test/compile-fail/regions-nested-fns-2.rs b/src/test/compile-fail/regions-nested-fns-2.rs index b7fe893a1f5..bdebadb2832 100644 --- a/src/test/compile-fail/regions-nested-fns-2.rs +++ b/src/test/compile-fail/regions-nested-fns-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn ignore<F>(_f: F) where F: for<'z> FnOnce(&'z int) -> &'z int {} +fn ignore<F>(_f: F) where F: for<'z> FnOnce(&'z isize) -> &'z isize {} fn nested() { let y = 3; diff --git a/src/test/compile-fail/regions-nested-fns.rs b/src/test/compile-fail/regions-nested-fns.rs index 5d8ef718ef0..58386c319f8 100644 --- a/src/test/compile-fail/regions-nested-fns.rs +++ b/src/test/compile-fail/regions-nested-fns.rs @@ -8,19 +8,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + fn ignore<T>(t: T) {} -fn nested<'x>(x: &'x int) { +fn nested<'x>(x: &'x isize) { let y = 3; let mut ay = &y; - ignore::<Box<for<'z> FnMut(&'z int)>>(box |z| { + ignore::<Box<for<'z> FnMut(&'z isize)>>(box |z| { ay = x; //~ ERROR cannot infer ay = &y; ay = z; }); - ignore::< Box<for<'z> FnMut(&'z int) -> &'z int>>(box |z| { + ignore::< Box<for<'z> FnMut(&'z isize) -> &'z isize>>(box |z| { if false { return x; } //~ ERROR cannot infer an appropriate lifetime for automatic if false { return ay; } return z; diff --git a/src/test/compile-fail/regions-proc-bound-capture.rs b/src/test/compile-fail/regions-proc-bound-capture.rs index 0841c1852f8..7ea4d1c7507 100644 --- a/src/test/compile-fail/regions-proc-bound-capture.rs +++ b/src/test/compile-fail/regions-proc-bound-capture.rs @@ -8,13 +8,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn borrowed_proc<'a>(x: &'a int) -> Box<FnMut()->(int) + 'a> { +#![feature(box_syntax)] + +fn borrowed_proc<'a>(x: &'a isize) -> Box<FnMut()->(isize) + 'a> { // This is legal, because the region bound on `proc` // states that it captures `x`. box move|| { *x } } -fn static_proc(x: &int) -> Box<FnMut()->(int) + 'static> { +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 } diff --git a/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref-mut-ref.rs b/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref-mut-ref.rs index 783009f6dcb..9743f11c966 100644 --- a/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref-mut-ref.rs +++ b/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref-mut-ref.rs @@ -10,7 +10,7 @@ // Issue #8624. Test for reborrowing with 3 levels, not just two. -fn copy_borrowed_ptr<'a, 'b, 'c>(p: &'a mut &'b mut &'c mut int) -> &'b mut int { +fn copy_borrowed_ptr<'a, 'b, 'c>(p: &'a mut &'b mut &'c mut isize) -> &'b mut isize { &mut ***p //~ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref.rs b/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref.rs index 4b1c7a2928b..399ebd6a2a7 100644 --- a/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref.rs +++ b/src/test/compile-fail/regions-reborrow-from-shorter-mut-ref.rs @@ -12,7 +12,7 @@ // pointer which is backed by another `&'a mut` can only be done // for `'a` (which must be a sublifetime of `'b`). -fn copy_borrowed_ptr<'a, 'b>(p: &'a mut &'b mut int) -> &'b mut int { +fn copy_borrowed_ptr<'a, 'b>(p: &'a mut &'b mut isize) -> &'b mut isize { &mut **p //~ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-ref-in-fn-arg.rs b/src/test/compile-fail/regions-ref-in-fn-arg.rs index f9eecb60c6a..13a903bf2b5 100644 --- a/src/test/compile-fail/regions-ref-in-fn-arg.rs +++ b/src/test/compile-fail/regions-ref-in-fn-arg.rs @@ -8,14 +8,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -fn arg_item(box ref x: Box<int>) -> &'static int { +fn arg_item(box ref x: Box<isize>) -> &'static isize { x //~^ ERROR borrowed value does not live long enough } -fn with<R, F>(f: F) -> R where F: FnOnce(Box<int>) -> R { f(box 3) } +fn with<R, F>(f: F) -> R where F: FnOnce(Box<isize>) -> R { f(box 3) } -fn arg_closure() -> &'static int { +fn arg_closure() -> &'static isize { with(|box ref x| x) //~ ERROR borrowed value does not live long enough } diff --git a/src/test/compile-fail/regions-ret-borrowed-1.rs b/src/test/compile-fail/regions-ret-borrowed-1.rs index bd14d31217e..b8cebe66518 100644 --- a/src/test/compile-fail/regions-ret-borrowed-1.rs +++ b/src/test/compile-fail/regions-ret-borrowed-1.rs @@ -12,11 +12,11 @@ // some point regions-ret-borrowed reported an error but this file did // not, due to special hardcoding around the anonymous region. -fn with<R, F>(f: F) -> R where F: for<'a> FnOnce(&'a int) -> R { +fn with<R, F>(f: F) -> R where F: for<'a> FnOnce(&'a isize) -> R { f(&3) } -fn return_it<'a>() -> &'a int { +fn return_it<'a>() -> &'a isize { with(|o| o) //~^ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-ret-borrowed.rs b/src/test/compile-fail/regions-ret-borrowed.rs index 4dfd4f1709a..40909ddd4ad 100644 --- a/src/test/compile-fail/regions-ret-borrowed.rs +++ b/src/test/compile-fail/regions-ret-borrowed.rs @@ -10,16 +10,16 @@ // Ensure that you cannot use generic types to return a region outside // of its bound. Here, in the `return_it()` fn, we call with() but -// with R bound to &int from the return_it. Meanwhile, with() +// with R bound to &isize from the return_it. Meanwhile, with() // provides a value that is only good within its own stack frame. This // used to successfully compile because we failed to account for the -// fact that fn(x: &int) rebound the region &. +// fact that fn(x: &isize) rebound the region &. -fn with<R, F>(f: F) -> R where F: FnOnce(&int) -> R { +fn with<R, F>(f: F) -> R where F: FnOnce(&isize) -> R { f(&3) } -fn return_it<'a>() -> &'a int { +fn return_it<'a>() -> &'a isize { with(|o| o) //~^ ERROR cannot infer } diff --git a/src/test/compile-fail/regions-ret.rs b/src/test/compile-fail/regions-ret.rs index 4986771c793..61c98d69d80 100644 --- a/src/test/compile-fail/regions-ret.rs +++ b/src/test/compile-fail/regions-ret.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(_x: &int) -> &int { +fn f(_x: &isize) -> &isize { return &3; //~ ERROR borrowed value does not live long enough } diff --git a/src/test/compile-fail/regions-return-ref-to-upvar-issue-17403.rs b/src/test/compile-fail/regions-return-ref-to-upvar-issue-17403.rs index d7b2a45cc63..21586f78db3 100644 --- a/src/test/compile-fail/regions-return-ref-to-upvar-issue-17403.rs +++ b/src/test/compile-fail/regions-return-ref-to-upvar-issue-17403.rs @@ -15,7 +15,7 @@ fn main() { // Unboxed closure case { - let mut x = 0u; + let mut x = 0us; let mut f = |&mut:| &mut x; //~ ERROR cannot infer let x = f(); let y = f(); diff --git a/src/test/compile-fail/regions-return-stack-allocated-vec.rs b/src/test/compile-fail/regions-return-stack-allocated-vec.rs index 3c5423c44d0..b5d4e07d04b 100644 --- a/src/test/compile-fail/regions-return-stack-allocated-vec.rs +++ b/src/test/compile-fail/regions-return-stack-allocated-vec.rs @@ -10,7 +10,7 @@ // Test that we cannot return a stack allocated slice -fn function(x: int) -> &'static [int] { +fn function(x: isize) -> &'static [isize] { &[x] //~ ERROR borrowed value does not live long enough } diff --git a/src/test/compile-fail/regions-steal-closure.rs b/src/test/compile-fail/regions-steal-closure.rs index 991040bc62f..583d9695be4 100644 --- a/src/test/compile-fail/regions-steal-closure.rs +++ b/src/test/compile-fail/regions-steal-closure.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { @@ -20,7 +21,7 @@ fn box_it<'r>(x: Box<FnMut() + 'r>) -> closure_box<'r> { fn main() { let cl_box = { - let mut i = 3i; + let mut i = 3is; box_it(box || i += 1) //~ ERROR cannot infer }; cl_box.cl.call_mut(()); diff --git a/src/test/compile-fail/regions-trait-1.rs b/src/test/compile-fail/regions-trait-1.rs index 7771a71c79b..63052580dc2 100644 --- a/src/test/compile-fail/regions-trait-1.rs +++ b/src/test/compile-fail/regions-trait-1.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -struct ctxt { v: uint } +struct ctxt { v: usize } trait get_ctxt { // Here the `&` is bound in the method definition: @@ -28,12 +29,12 @@ impl<'a> get_ctxt for has_ctxt<'a> { } -fn get_v(gc: Box<get_ctxt>) -> uint { +fn get_v(gc: Box<get_ctxt>) -> usize { gc.get_ctxt().v } fn main() { - let ctxt = ctxt { v: 22u }; + let ctxt = ctxt { v: 22us }; let hc = has_ctxt { c: &ctxt }; - assert_eq!(get_v(box hc as Box<get_ctxt>), 22u); + assert_eq!(get_v(box hc as Box<get_ctxt>), 22us); } diff --git a/src/test/compile-fail/regions-trait-2.rs b/src/test/compile-fail/regions-trait-2.rs index 92c1849c15b..8b36e87db3e 100644 --- a/src/test/compile-fail/regions-trait-2.rs +++ b/src/test/compile-fail/regions-trait-2.rs @@ -13,7 +13,7 @@ // Test that you cannot escape a reference // into a trait. -struct ctxt { v: uint } +struct ctxt { v: usize } trait get_ctxt { fn get_ctxt(&self) -> &'a ctxt; @@ -26,7 +26,7 @@ impl<'a> get_ctxt for has_ctxt<'a> { } fn make_gc() -> @get_ctxt { - let ctxt = ctxt { v: 22u }; + let ctxt = ctxt { v: 22us }; let hc = has_ctxt { c: &ctxt }; return @hc as @get_ctxt; //~^ ERROR source contains reference diff --git a/src/test/compile-fail/regions-trait-3.rs b/src/test/compile-fail/regions-trait-3.rs index 78d84fb7c75..8943abb49ae 100644 --- a/src/test/compile-fail/regions-trait-3.rs +++ b/src/test/compile-fail/regions-trait-3.rs @@ -22,7 +22,7 @@ // except according to those terms. trait get_ctxt<'a> { - fn get_ctxt(self) -> &'a uint; + fn get_ctxt(self) -> &'a usize; } fn make_gc1(gc: @get_ctxt<'a>) -> @get_ctxt<'b> { @@ -30,11 +30,11 @@ fn make_gc1(gc: @get_ctxt<'a>) -> @get_ctxt<'b> { } struct Foo { - r: &'a uint + r: &'a usize } impl get_ctxt for Foo<'a> { - fn get_ctxt(&self) -> &'a uint { self.r } + fn get_ctxt(&self) -> &'a usize { self.r } } fn make_gc2<'a,'b>(foo: Foo<'a>) -> @get_ctxt<'b> { diff --git a/src/test/compile-fail/regions-trait-variance.rs b/src/test/compile-fail/regions-trait-variance.rs index 4e31a41c4e0..9ba4ef4e358 100644 --- a/src/test/compile-fail/regions-trait-variance.rs +++ b/src/test/compile-fail/regions-trait-variance.rs @@ -8,18 +8,20 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + // Issue #12470. trait X { - fn get_i(&self) -> int; + fn get_i(&self) -> isize; } struct B { - i: int + i: isize } impl X for B { - fn get_i(&self) -> int { + fn get_i(&self) -> isize { self.i } } diff --git a/src/test/compile-fail/regions-undeclared.rs b/src/test/compile-fail/regions-undeclared.rs index 2d1de23616b..31908751580 100644 --- a/src/test/compile-fail/regions-undeclared.rs +++ b/src/test/compile-fail/regions-undeclared.rs @@ -8,15 +8,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static c_x: &'blk int = &22; //~ ERROR use of undeclared lifetime name `'blk` +static c_x: &'blk isize = &22; //~ ERROR use of undeclared lifetime name `'blk` enum EnumDecl { - Foo(&'a int), //~ ERROR use of undeclared lifetime name `'a` - Bar(&'a int), //~ ERROR use of undeclared lifetime name `'a` + Foo(&'a isize), //~ ERROR use of undeclared lifetime name `'a` + Bar(&'a isize), //~ ERROR use of undeclared lifetime name `'a` } -fn fnDecl(x: &'a int, //~ ERROR use of undeclared lifetime name `'a` - y: &'a int) //~ ERROR use of undeclared lifetime name `'a` +fn fnDecl(x: &'a isize, //~ ERROR use of undeclared lifetime name `'a` + y: &'a isize) //~ ERROR use of undeclared lifetime name `'a` {} fn main() { diff --git a/src/test/compile-fail/regions-var-type-out-of-scope.rs b/src/test/compile-fail/regions-var-type-out-of-scope.rs index a954b16699f..039de994ea3 100644 --- a/src/test/compile-fail/regions-var-type-out-of-scope.rs +++ b/src/test/compile-fail/regions-var-type-out-of-scope.rs @@ -14,8 +14,8 @@ fn foo(cond: bool) { let mut x; if cond { - x = &3i; //~ ERROR borrowed value does not live long enough - assert_eq!(*x, 3i); + x = &3is; //~ ERROR borrowed value does not live long enough + assert_eq!(*x, 3is); } } diff --git a/src/test/compile-fail/regions-variance-contravariant-use-covariant-in-second-position.rs b/src/test/compile-fail/regions-variance-contravariant-use-covariant-in-second-position.rs index 14ead8da158..a7ef3ec9ac1 100644 --- a/src/test/compile-fail/regions-variance-contravariant-use-covariant-in-second-position.rs +++ b/src/test/compile-fail/regions-variance-contravariant-use-covariant-in-second-position.rs @@ -16,13 +16,13 @@ // `S` is contravariant with respect to both parameters. struct S<'a, 'b> { - f: &'a int, - g: &'b int, + f: &'a isize, + g: &'b isize, } fn use_<'short,'long>(c: S<'long, 'short>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { let _: S<'long, 'short> = c; // OK diff --git a/src/test/compile-fail/regions-variance-contravariant-use-covariant.rs b/src/test/compile-fail/regions-variance-contravariant-use-covariant.rs index 3fc58071d2c..a79249ade4f 100644 --- a/src/test/compile-fail/regions-variance-contravariant-use-covariant.rs +++ b/src/test/compile-fail/regions-variance-contravariant-use-covariant.rs @@ -18,12 +18,12 @@ // Contravariant<'long> <: Contravariant<'short> iff // 'short <= 'long struct Contravariant<'a> { - f: &'a int + f: &'a isize } fn use_<'short,'long>(c: Contravariant<'short>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Contravariant<'short> <: Contravariant<'long>. Since diff --git a/src/test/compile-fail/regions-variance-covariant-use-contravariant.rs b/src/test/compile-fail/regions-variance-covariant-use-contravariant.rs index 844c8151a64..f42b7027d9e 100644 --- a/src/test/compile-fail/regions-variance-covariant-use-contravariant.rs +++ b/src/test/compile-fail/regions-variance-covariant-use-contravariant.rs @@ -18,12 +18,12 @@ // Covariant<'foo> <: Covariant<'static> because // 'foo <= 'static struct Covariant<'a> { - f: extern "Rust" fn(&'a int) + f: extern "Rust" fn(&'a isize) } fn use_<'short,'long>(c: Covariant<'long>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Covariant<'long> <: Covariant<'short>. Since diff --git a/src/test/compile-fail/regions-variance-invariant-use-contravariant.rs b/src/test/compile-fail/regions-variance-invariant-use-contravariant.rs index d09e6babe09..71023b26c27 100644 --- a/src/test/compile-fail/regions-variance-invariant-use-contravariant.rs +++ b/src/test/compile-fail/regions-variance-invariant-use-contravariant.rs @@ -15,12 +15,12 @@ // variance inference works in the first place. struct Invariant<'a> { - f: &'a mut &'a int + f: &'a mut &'a isize } fn use_<'short,'long>(c: Invariant<'long>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { // Test whether Invariant<'long> <: Invariant<'short>. Since diff --git a/src/test/compile-fail/regions-variance-invariant-use-covariant.rs b/src/test/compile-fail/regions-variance-invariant-use-covariant.rs index 861668ad50d..bd944a8b52c 100644 --- a/src/test/compile-fail/regions-variance-invariant-use-covariant.rs +++ b/src/test/compile-fail/regions-variance-invariant-use-covariant.rs @@ -15,7 +15,7 @@ // variance inference works in the first place. struct Invariant<'a> { - f: &'a mut &'a int + f: &'a mut &'a isize } fn use_<'b>(c: Invariant<'b>) { diff --git a/src/test/compile-fail/removed-syntax-enum-newtype.rs b/src/test/compile-fail/removed-syntax-enum-newtype.rs index ba1b5a616df..3b45fd81288 100644 --- a/src/test/compile-fail/removed-syntax-enum-newtype.rs +++ b/src/test/compile-fail/removed-syntax-enum-newtype.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum e = int; //~ ERROR expected one of `<` or `{`, found `=` +enum e = isize; //~ ERROR expected one of `<` or `{`, found `=` diff --git a/src/test/compile-fail/removed-syntax-extern-const.rs b/src/test/compile-fail/removed-syntax-extern-const.rs index 2f98552a953..98eec0977e0 100644 --- a/src/test/compile-fail/removed-syntax-extern-const.rs +++ b/src/test/compile-fail/removed-syntax-extern-const.rs @@ -9,5 +9,5 @@ // except according to those terms. extern { - const i: int; //~ ERROR unexpected token: `const` + const i: isize; //~ ERROR unexpected token: `const` } diff --git a/src/test/compile-fail/removed-syntax-fixed-vec.rs b/src/test/compile-fail/removed-syntax-fixed-vec.rs index 6537e3ddd27..0ca2380ef68 100644 --- a/src/test/compile-fail/removed-syntax-fixed-vec.rs +++ b/src/test/compile-fail/removed-syntax-fixed-vec.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type v = [int * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `*` +type v = [isize * 3]; //~ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `*` diff --git a/src/test/compile-fail/removed-syntax-mode.rs b/src/test/compile-fail/removed-syntax-mode.rs index d2ab1881b1a..b02de5ce08e 100644 --- a/src/test/compile-fail/removed-syntax-mode.rs +++ b/src/test/compile-fail/removed-syntax-mode.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn f(+x: int) {} //~ ERROR unexpected token: `+` +fn f(+x: isize) {} //~ ERROR unexpected token: `+` diff --git a/src/test/compile-fail/removed-syntax-mut-vec-ty.rs b/src/test/compile-fail/removed-syntax-mut-vec-ty.rs index efde1f1b24d..0f67a1d04ee 100644 --- a/src/test/compile-fail/removed-syntax-mut-vec-ty.rs +++ b/src/test/compile-fail/removed-syntax-mut-vec-ty.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type v = [mut int]; +type v = [mut isize]; //~^ ERROR expected identifier, found keyword `mut` - //~^^ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `int` + //~^^ ERROR expected one of `(`, `+`, `::`, `;`, or `]`, found `isize` diff --git a/src/test/compile-fail/removed-syntax-ptr-lifetime.rs b/src/test/compile-fail/removed-syntax-ptr-lifetime.rs index 1a1c4c9b40a..d94f2ec1e07 100644 --- a/src/test/compile-fail/removed-syntax-ptr-lifetime.rs +++ b/src/test/compile-fail/removed-syntax-ptr-lifetime.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type bptr = &lifetime/int; //~ ERROR expected one of `(`, `+`, `::`, or `;`, found `/` +type bptr = &lifetime/isize; //~ ERROR expected one of `(`, `+`, `::`, or `;`, found `/` diff --git a/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs b/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs index 8c3db89bad2..c051059aee6 100644 --- a/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs +++ b/src/test/compile-fail/removed-syntax-uniq-mut-ty.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -type mut_box = Box<mut int>; +type mut_box = Box<mut isize>; //~^ ERROR expected identifier, found keyword `mut` - //~^^ ERROR expected one of `(`, `+`, `,`, `::`, or `>`, found `int` + //~^^ ERROR expected one of `(`, `+`, `,`, `::`, or `>`, found `isize` diff --git a/src/test/compile-fail/repeat-to-run-dtor-twice.rs b/src/test/compile-fail/repeat-to-run-dtor-twice.rs index 762c976a943..c8457adb8d6 100644 --- a/src/test/compile-fail/repeat-to-run-dtor-twice.rs +++ b/src/test/compile-fail/repeat-to-run-dtor-twice.rs @@ -12,7 +12,7 @@ // literal syntax. struct Foo { - x: int, + x: isize, } diff --git a/src/test/compile-fail/repeat_count.rs b/src/test/compile-fail/repeat_count.rs index f851a8244f6..e94bf19955b 100644 --- a/src/test/compile-fail/repeat_count.rs +++ b/src/test/compile-fail/repeat_count.rs @@ -24,6 +24,6 @@ fn main() { //~^ ERROR: expected `usize`, found `&'static str` let f = [0; -4]; //~^ ERROR expected positive integer for repeat count, found negative integer - let f = [0u; -1]; + let f = [0us; -1]; //~^ ERROR expected positive integer for repeat count, found negative integer } diff --git a/src/test/compile-fail/require-parens-for-chained-comparison.rs b/src/test/compile-fail/require-parens-for-chained-comparison.rs new file mode 100644 index 00000000000..7513815ad73 --- /dev/null +++ b/src/test/compile-fail/require-parens-for-chained-comparison.rs @@ -0,0 +1,23 @@ +// 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. + +fn f<T>() {} + +fn main() { + false == false == false; + //~^ ERROR: Chained comparison operators require parentheses + + false == 0 < 2; + //~^ ERROR: Chained comparison operators require parentheses + + f<X>(); + //~^ ERROR: Chained comparison operators require parentheses + //~^^ HELP: Use ::< instead of < if you meant to specify type arguments. +} diff --git a/src/test/compile-fail/resolve-inconsistent-binding-mode.rs b/src/test/compile-fail/resolve-inconsistent-binding-mode.rs index df54a66f0a2..cdb81279048 100644 --- a/src/test/compile-fail/resolve-inconsistent-binding-mode.rs +++ b/src/test/compile-fail/resolve-inconsistent-binding-mode.rs @@ -9,7 +9,7 @@ // except according to those terms. enum opts { - a(int), b(int), c(int) + a(isize), b(isize), c(isize) } fn matcher1(x: opts) { diff --git a/src/test/compile-fail/resolve-unknown-trait.rs b/src/test/compile-fail/resolve-unknown-trait.rs index 699a30ad4eb..0d0dc0a05d1 100644 --- a/src/test/compile-fail/resolve-unknown-trait.rs +++ b/src/test/compile-fail/resolve-unknown-trait.rs @@ -12,7 +12,7 @@ trait NewTrait : SomeNonExistentTrait {} //~^ ERROR attempt to derive a nonexistent trait `SomeNonExistentTrait` -impl SomeNonExistentTrait for int {} +impl SomeNonExistentTrait for isize {} //~^ ERROR attempt to implement a nonexistent trait `SomeNonExistentTrait` fn f<T:SomeNonExistentTrait>() {} diff --git a/src/test/compile-fail/ret-non-nil.rs b/src/test/compile-fail/ret-non-nil.rs index d0cb2d4e812..4ee3cf4abac 100644 --- a/src/test/compile-fail/ret-non-nil.rs +++ b/src/test/compile-fail/ret-non-nil.rs @@ -12,6 +12,6 @@ fn f() { return; } -fn g() -> int { return; } +fn g() -> isize { return; } fn main() { f(); g(); } diff --git a/src/test/compile-fail/shadowed-lifetime.rs b/src/test/compile-fail/shadowed-lifetime.rs index ff8ce7769d7..57a2744d8f8 100644 --- a/src/test/compile-fail/shadowed-lifetime.rs +++ b/src/test/compile-fail/shadowed-lifetime.rs @@ -10,27 +10,27 @@ // Test that shadowed lifetimes generate an error. -struct Foo<'a>(&'a int); +struct Foo<'a>(&'a isize); impl<'a> Foo<'a> { //~^ HELP shadowed lifetime `'a` declared here - fn shadow_in_method<'a>(&'a self) -> &'a int { + fn shadow_in_method<'a>(&'a self) -> &'a isize { //~^ WARNING lifetime name `'a` shadows another lifetime name that is already in scope //~| HELP deprecated self.0 } - fn shadow_in_type<'b>(&'b self) -> &'b int { + fn shadow_in_type<'b>(&'b self) -> &'b isize { //~^ HELP shadowed lifetime `'b` declared here - let x: for<'b> fn(&'b int) = panic!(); + let x: for<'b> fn(&'b isize) = panic!(); //~^ WARNING lifetime name `'b` shadows another lifetime name that is already in scope //~| HELP deprecated self.0 } fn not_shadow_in_item<'b>(&'b self) { - struct Bar<'a, 'b>(&'a int, &'b int); // not a shadow, separate item - fn foo<'a, 'b>(x: &'a int, y: &'b int) { } // same + struct Bar<'a, 'b>(&'a isize, &'b isize); // not a shadow, separate item + fn foo<'a, 'b>(x: &'a isize, y: &'b isize) { } // same } } @@ -39,5 +39,5 @@ fn main() { // just to ensure that this test fails to compile; when shadowed // lifetimes become either an error or a proper lint, this will // not be needed. - let x: int = 3u; //~ ERROR mismatched types + let x: isize = 3us; //~ ERROR mismatched types } diff --git a/src/test/compile-fail/shadowed-type-parameter.rs b/src/test/compile-fail/shadowed-type-parameter.rs new file mode 100644 index 00000000000..1a3d7821159 --- /dev/null +++ b/src/test/compile-fail/shadowed-type-parameter.rs @@ -0,0 +1,38 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Test that shadowed lifetimes generate an error. + +#![feature(box_syntax)] + +struct Foo<T>; + +impl<T> Foo<T> { + fn shadow_in_method<T>(&self) {} + //~^ ERROR type parameter `T` shadows another type parameter + + fn not_shadow_in_item<U>(&self) { + struct Bar<T, U>; // not a shadow, separate item + fn foo<T, U>() {} // same + } +} + +trait Bar<T> { + fn shadow_in_required<T>(&self); + //~^ ERROR type parameter `T` shadows another type parameter + + fn shadow_in_provided<T>(&self) {} + //~^ ERROR type parameter `T` shadows another type parameter + + fn not_shadow_in_required<U>(&self); + fn not_shadow_in_provided<U>(&self) {} +} + +fn main() {} diff --git a/src/test/compile-fail/shadowing-in-the-same-pattern.rs b/src/test/compile-fail/shadowing-in-the-same-pattern.rs index 0b78023d318..c29534128ae 100644 --- a/src/test/compile-fail/shadowing-in-the-same-pattern.rs +++ b/src/test/compile-fail/shadowing-in-the-same-pattern.rs @@ -10,7 +10,7 @@ // Test for issue #14581. -fn f((a, a): (int, int)) {} //~ ERROR identifier `a` is bound more than once +fn f((a, a): (isize, isize)) {} //~ ERROR identifier `a` is bound more than once fn main() { let (a, a) = (1, 1); //~ ERROR identifier `a` is bound more than once diff --git a/src/test/compile-fail/shift-various-bad-types.rs b/src/test/compile-fail/shift-various-bad-types.rs new file mode 100644 index 00000000000..41788584049 --- /dev/null +++ b/src/test/compile-fail/shift-various-bad-types.rs @@ -0,0 +1,43 @@ +// 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. + +// Test that we can do shifts by any integral type. + +struct Panolpy { + char: char, + str: &'static str, +} + +fn foo(p: &Panolpy) { + 22 >> p.char; + //~^ ERROR right-hand-side of a shift operation must have integral type + + 22 >> p.str; + //~^ ERROR right-hand-side of a shift operation must have integral type + + 22 >> p; + //~^ ERROR right-hand-side of a shift operation must have integral type + + // We could be more accepting in the case of a type not yet inferred, but not + // known to be an integer, but meh. + let x; + 22 >> x; + //~^ ERROR right-hand-side of a shift operation must have integral type + + 22 >> 1; + // Integer literal types are OK + + // Type of the result follows the LHS, not the RHS: + let _: i32 = 22_i64 >> 1_i32; + //~^ ERROR mismatched types: expected `i32`, found `i64` +} + +fn main() { +} diff --git a/src/test/compile-fail/simd-binop.rs b/src/test/compile-fail/simd-binop.rs index 9fbb7364054..0c2d8972ce7 100644 --- a/src/test/compile-fail/simd-binop.rs +++ b/src/test/compile-fail/simd-binop.rs @@ -10,7 +10,7 @@ // ignore-tidy-linelength -#![allow(experimental)] +#![allow(unstable)] use std::simd::f32x4; diff --git a/src/test/compile-fail/simd-experimental.rs b/src/test/compile-fail/simd-experimental.rs index 5f9f56bf3c0..aea970f90b2 100644 --- a/src/test/compile-fail/simd-experimental.rs +++ b/src/test/compile-fail/simd-experimental.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![deny(experimental)] +#![deny(unstable)] use std::simd; diff --git a/src/test/compile-fail/simd-type.rs b/src/test/compile-fail/simd-type.rs index 16be3941298..c47bc1747de 100644 --- a/src/test/compile-fail/simd-type.rs +++ b/src/test/compile-fail/simd-type.rs @@ -20,6 +20,6 @@ struct empty; //~ ERROR SIMD vector cannot be empty struct i64f64(i64, f64); //~ ERROR SIMD vector should be homogeneous #[simd] -struct int4(int, int, int, int); //~ ERROR SIMD vector element type should be machine type +struct int4(isize, isize, isize, isize); //~ ERROR SIMD vector element type should be machine type fn main() {} diff --git a/src/test/compile-fail/slice-2.rs b/src/test/compile-fail/slice-2.rs index a03693b5fad..07162293565 100644 --- a/src/test/compile-fail/slice-2.rs +++ b/src/test/compile-fail/slice-2.rs @@ -10,8 +10,6 @@ // Test that slicing syntax gives errors if we have not implemented the trait. -#![feature(slicing_syntax)] - struct Foo; fn main() { diff --git a/src/test/compile-fail/slice-borrow.rs b/src/test/compile-fail/slice-borrow.rs index aab187f9751..0062f66ae22 100644 --- a/src/test/compile-fail/slice-borrow.rs +++ b/src/test/compile-fail/slice-borrow.rs @@ -10,12 +10,10 @@ // Test slicing expressions doesn't defeat the borrow checker. -#![feature(slicing_syntax)] - fn main() { let y; { - let x: &[int] = &[1, 2, 3, 4, 5]; //~ ERROR borrowed value does not live long enough + let x: &[isize] = &[1, 2, 3, 4, 5]; //~ ERROR borrowed value does not live long enough y = &x[1..]; } } diff --git a/src/test/compile-fail/slice-mut-2.rs b/src/test/compile-fail/slice-mut-2.rs index 1dedb0cf888..e20e968a012 100644 --- a/src/test/compile-fail/slice-mut-2.rs +++ b/src/test/compile-fail/slice-mut-2.rs @@ -10,11 +10,9 @@ // Test mutability and slicing syntax. -#![feature(slicing_syntax)] - fn main() { - let x: &[int] = &[1, 2, 3, 4, 5]; + let x: &[isize] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice - let slice: &mut [int] = &mut [0, 1]; - let _ = &mut x[2..4]; //~ERROR cannot borrow immutable dereference of `&`-pointer `*x` as mutabl + let slice: &mut [isize] = &mut [0, 1]; + let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable } diff --git a/src/test/compile-fail/slice-mut.rs b/src/test/compile-fail/slice-mut.rs index f0f525a5535..0e1dd0d8f6c 100644 --- a/src/test/compile-fail/slice-mut.rs +++ b/src/test/compile-fail/slice-mut.rs @@ -10,10 +10,8 @@ // Test mutability and slicing syntax. -#![feature(slicing_syntax)] - fn main() { - let x: &[int] = &[1, 2, 3, 4, 5]; + let x: &[isize] = &[1, 2, 3, 4, 5]; // Immutable slices are not mutable. - let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutab + let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable borrowed content as mutable } diff --git a/src/test/compile-fail/static-assert2.rs b/src/test/compile-fail/static-assert2.rs index 6adc3b0aaf8..e988cfb9097 100644 --- a/src/test/compile-fail/static-assert2.rs +++ b/src/test/compile-fail/static-assert2.rs @@ -11,6 +11,6 @@ #![allow(dead_code)] #[static_assert] -static E: bool = 1i == 2; //~ ERROR static assertion failed +static E: bool = 1is == 2; //~ ERROR static assertion failed fn main() {} diff --git a/src/test/compile-fail/static-items-cant-move.rs b/src/test/compile-fail/static-items-cant-move.rs index 14ad1b3041f..422e95338ed 100644 --- a/src/test/compile-fail/static-items-cant-move.rs +++ b/src/test/compile-fail/static-items-cant-move.rs @@ -13,7 +13,7 @@ use std::marker; struct Foo { - foo: int, + foo: isize, nocopy: marker::NoCopy } diff --git a/src/test/compile-fail/static-mut-bad-types.rs b/src/test/compile-fail/static-mut-bad-types.rs index 7aed3ce30bc..088c8ef3ab8 100644 --- a/src/test/compile-fail/static-mut-bad-types.rs +++ b/src/test/compile-fail/static-mut-bad-types.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static mut a: int = 3; +static mut a: isize = 3; fn main() { unsafe { diff --git a/src/test/compile-fail/static-mut-not-constant.rs b/src/test/compile-fail/static-mut-not-constant.rs index 84c72de5548..7c228ce413f 100644 --- a/src/test/compile-fail/static-mut-not-constant.rs +++ b/src/test/compile-fail/static-mut-not-constant.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] -static mut a: Box<int> = box 3; +static mut a: Box<isize> = box 3; //~^ ERROR statics are not allowed to have custom pointers //~^^ ERROR mutable statics are not allowed to have owned pointers diff --git a/src/test/compile-fail/static-mut-not-pat.rs b/src/test/compile-fail/static-mut-not-pat.rs index de93422cd7a..bfdeff6ed70 100644 --- a/src/test/compile-fail/static-mut-not-pat.rs +++ b/src/test/compile-fail/static-mut-not-pat.rs @@ -12,14 +12,14 @@ // statics cannot. This ensures that there's some form of error if this is // attempted. -static mut a: int = 3; +static mut a: isize = 3; fn main() { // If they can't be matched against, then it's possible to capture the same // name as a variable, hence this should be an unreachable pattern situation // instead of spitting out a custom error about some identifier collisions // (we should allow shadowing) - match 4i { + match 4is { a => {} //~ ERROR static variables cannot be referenced in a pattern _ => {} } diff --git a/src/test/compile-fail/static-mut-requires-unsafe.rs b/src/test/compile-fail/static-mut-requires-unsafe.rs index 7337920cce6..f6ad46a0527 100644 --- a/src/test/compile-fail/static-mut-requires-unsafe.rs +++ b/src/test/compile-fail/static-mut-requires-unsafe.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static mut a: int = 3; +static mut a: isize = 3; fn main() { a += 3; //~ ERROR: requires unsafe diff --git a/src/test/compile-fail/static-priv-by-default.rs b/src/test/compile-fail/static-priv-by-default.rs index 98b37242c03..14299a9b639 100644 --- a/src/test/compile-fail/static-priv-by-default.rs +++ b/src/test/compile-fail/static-priv-by-default.rs @@ -14,12 +14,12 @@ extern crate static_priv_by_default; mod child { pub mod childs_child { - static private: int = 0; - pub static public: int = 0; + static private: isize = 0; + pub static public: isize = 0; } } -fn foo(_: int) {} +fn foo(_: isize) {} fn full_ref() { foo(static_priv_by_default::private); //~ ERROR: static `private` is private diff --git a/src/test/compile-fail/static-priv-by-default2.rs b/src/test/compile-fail/static-priv-by-default2.rs index 2141099c7aa..577e4f7542d 100644 --- a/src/test/compile-fail/static-priv-by-default2.rs +++ b/src/test/compile-fail/static-priv-by-default2.rs @@ -14,8 +14,8 @@ extern crate static_priv_by_default; mod child { pub mod childs_child { - static private: int = 0; - pub static public: int = 0; + static private: isize = 0; + pub static public: isize = 0; } } diff --git a/src/test/compile-fail/static-reference-to-fn-1.rs b/src/test/compile-fail/static-reference-to-fn-1.rs index bce397c4793..cf8ee1ecb41 100644 --- a/src/test/compile-fail/static-reference-to-fn-1.rs +++ b/src/test/compile-fail/static-reference-to-fn-1.rs @@ -9,16 +9,16 @@ // except according to those terms. struct A<'a> { - func: &'a fn() -> Option<int> + func: &'a fn() -> Option<isize> } impl<'a> A<'a> { - fn call(&self) -> Option<int> { + fn call(&self) -> Option<isize> { (*self.func)() } } -fn foo() -> Option<int> { +fn foo() -> Option<isize> { None } diff --git a/src/test/compile-fail/static-region-bound.rs b/src/test/compile-fail/static-region-bound.rs index 1e5a5ecc08e..4c59e7a769f 100644 --- a/src/test/compile-fail/static-region-bound.rs +++ b/src/test/compile-fail/static-region-bound.rs @@ -8,12 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] fn f<T:'static>(_: T) {} fn main() { - let x = box 3i; + let x = box 3is; f(x); - let x = &3i; //~ ERROR borrowed value does not live long enough + let x = &3is; //~ ERROR borrowed value does not live long enough f(x); } diff --git a/src/test/compile-fail/static-vec-repeat-not-constant.rs b/src/test/compile-fail/static-vec-repeat-not-constant.rs index ff84ed5bf0c..7cb7615526a 100644 --- a/src/test/compile-fail/static-vec-repeat-not-constant.rs +++ b/src/test/compile-fail/static-vec-repeat-not-constant.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo() -> int { 23 } +fn foo() -> isize { 23 } -static a: [int; 2] = [foo(); 2]; +static a: [isize; 2] = [foo(); 2]; //~^ ERROR: function calls in constants are limited to struct and enum constructors fn main() {} diff --git a/src/test/compile-fail/staticness-mismatch.rs b/src/test/compile-fail/staticness-mismatch.rs index a6082d31480..bf4e46cace3 100644 --- a/src/test/compile-fail/staticness-mismatch.rs +++ b/src/test/compile-fail/staticness-mismatch.rs @@ -13,7 +13,7 @@ trait foo { fn bar(); } -impl foo for int { +impl foo for isize { fn bar(&self) {} //~^ ERROR method `bar` has a `&self` declaration in the impl, but not in the trait } diff --git a/src/test/compile-fail/std-uncopyable-atomics.rs b/src/test/compile-fail/std-uncopyable-atomics.rs index 5ebabc2e354..f27fa6470a6 100644 --- a/src/test/compile-fail/std-uncopyable-atomics.rs +++ b/src/test/compile-fail/std-uncopyable-atomics.rs @@ -16,11 +16,11 @@ use std::ptr; fn main() { let x = ATOMIC_BOOL_INIT; - let x = *&x; //~ ERROR: cannot move out of dereference + let x = *&x; //~ ERROR: cannot move out of borrowed content let x = ATOMIC_INT_INIT; - let x = *&x; //~ ERROR: cannot move out of dereference + let x = *&x; //~ ERROR: cannot move out of borrowed content let x = ATOMIC_UINT_INIT; - let x = *&x; //~ ERROR: cannot move out of dereference - let x: AtomicPtr<uint> = AtomicPtr::new(ptr::null_mut()); - let x = *&x; //~ ERROR: cannot move out of dereference + let x = *&x; //~ ERROR: cannot move out of borrowed content + let x: AtomicPtr<usize> = AtomicPtr::new(ptr::null_mut()); + let x = *&x; //~ ERROR: cannot move out of borrowed content } diff --git a/src/test/compile-fail/struct-base-wrong-type.rs b/src/test/compile-fail/struct-base-wrong-type.rs index af6fc645351..2bb8d32a7e3 100644 --- a/src/test/compile-fail/struct-base-wrong-type.rs +++ b/src/test/compile-fail/struct-base-wrong-type.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo { a: int, b: int } -struct Bar { x: int } +struct Foo { a: isize, b: isize } +struct Bar { x: isize } static bar: Bar = Bar { x: 5 }; static foo: Foo = Foo { a: 2, ..bar }; //~ ERROR mismatched types: expected `Foo`, found `Bar` diff --git a/src/test/compile-fail/struct-field-assignability.rs b/src/test/compile-fail/struct-field-assignability.rs index 2c3d48e9bf7..685ce28d510 100644 --- a/src/test/compile-fail/struct-field-assignability.rs +++ b/src/test/compile-fail/struct-field-assignability.rs @@ -12,7 +12,7 @@ struct Foo<'a> { - x: &'a int + x: &'a isize } pub fn main() { diff --git a/src/test/compile-fail/struct-field-privacy.rs b/src/test/compile-fail/struct-field-privacy.rs index ae421815e4d..667e944f92c 100644 --- a/src/test/compile-fail/struct-field-privacy.rs +++ b/src/test/compile-fail/struct-field-privacy.rs @@ -13,17 +13,17 @@ extern crate "struct-field-privacy" as xc; struct A { - a: int, + a: isize, } mod inner { struct A { - a: int, - pub b: int, + a: isize, + pub b: isize, } pub struct B { - pub a: int, - b: int, + pub a: isize, + b: isize, } } diff --git a/src/test/compile-fail/struct-fields-decl-dupe.rs b/src/test/compile-fail/struct-fields-decl-dupe.rs index 78216d5f4af..049569e8a18 100644 --- a/src/test/compile-fail/struct-fields-decl-dupe.rs +++ b/src/test/compile-fail/struct-fields-decl-dupe.rs @@ -9,8 +9,8 @@ // except according to those terms. struct BuildData { - foo: int, - foo: int, //~ ERROR field `foo` is already declared + foo: isize, + foo: isize, //~ ERROR field `foo` is already declared } fn main() { diff --git a/src/test/compile-fail/struct-fields-dupe.rs b/src/test/compile-fail/struct-fields-dupe.rs index ffbfecdc48c..578091f5e9a 100644 --- a/src/test/compile-fail/struct-fields-dupe.rs +++ b/src/test/compile-fail/struct-fields-dupe.rs @@ -9,7 +9,7 @@ // except according to those terms. struct BuildData { - foo: int, + foo: isize, } fn main() { diff --git a/src/test/compile-fail/struct-fields-missing.rs b/src/test/compile-fail/struct-fields-missing.rs index 0afc84ee1b3..1fd9357cf2d 100644 --- a/src/test/compile-fail/struct-fields-missing.rs +++ b/src/test/compile-fail/struct-fields-missing.rs @@ -10,8 +10,8 @@ struct BuildData { - foo: int, - bar: Box<int>, + foo: isize, + bar: Box<isize>, } fn main() { diff --git a/src/test/compile-fail/struct-fields-too-many.rs b/src/test/compile-fail/struct-fields-too-many.rs index de58b5d110e..9244a9d4f9d 100644 --- a/src/test/compile-fail/struct-fields-too-many.rs +++ b/src/test/compile-fail/struct-fields-too-many.rs @@ -9,7 +9,7 @@ // except according to those terms. struct BuildData { - foo: int, + foo: isize, } fn main() { diff --git a/src/test/compile-fail/struct-like-enum-nonexhaustive.rs b/src/test/compile-fail/struct-like-enum-nonexhaustive.rs index 1115d78e560..a14e43f4c94 100644 --- a/src/test/compile-fail/struct-like-enum-nonexhaustive.rs +++ b/src/test/compile-fail/struct-like-enum-nonexhaustive.rs @@ -9,7 +9,7 @@ // except according to those terms. enum A { - B { x: Option<int> }, + B { x: Option<isize> }, C } diff --git a/src/test/compile-fail/struct-literal-in-for.rs b/src/test/compile-fail/struct-literal-in-for.rs index a37197b889d..4bb5d5e6aa1 100644 --- a/src/test/compile-fail/struct-literal-in-for.rs +++ b/src/test/compile-fail/struct-literal-in-for.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } impl Foo { diff --git a/src/test/compile-fail/struct-literal-in-if.rs b/src/test/compile-fail/struct-literal-in-if.rs index 9759e4f7bda..b2bc8a4901f 100644 --- a/src/test/compile-fail/struct-literal-in-if.rs +++ b/src/test/compile-fail/struct-literal-in-if.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } impl Foo { diff --git a/src/test/compile-fail/struct-literal-in-match-discriminant.rs b/src/test/compile-fail/struct-literal-in-match-discriminant.rs index 297d3f7347f..8f50940806a 100644 --- a/src/test/compile-fail/struct-literal-in-match-discriminant.rs +++ b/src/test/compile-fail/struct-literal-in-match-discriminant.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } fn main() { diff --git a/src/test/compile-fail/struct-literal-in-while.rs b/src/test/compile-fail/struct-literal-in-while.rs index 5b1679cf9a1..05fa3a8dd5f 100644 --- a/src/test/compile-fail/struct-literal-in-while.rs +++ b/src/test/compile-fail/struct-literal-in-while.rs @@ -9,7 +9,7 @@ // except according to those terms. struct Foo { - x: int, + x: isize, } impl Foo { diff --git a/src/test/compile-fail/struct-pat-derived-error.rs b/src/test/compile-fail/struct-pat-derived-error.rs index cafead3af0e..4b65292340f 100644 --- a/src/test/compile-fail/struct-pat-derived-error.rs +++ b/src/test/compile-fail/struct-pat-derived-error.rs @@ -9,8 +9,8 @@ // except according to those terms. struct a { - b: uint, - c: uint + b: usize, + c: usize } impl a { diff --git a/src/test/compile-fail/struct-pattern-match-useless.rs b/src/test/compile-fail/struct-pattern-match-useless.rs index b9c0be9276d..9f7ebc261ad 100644 --- a/src/test/compile-fail/struct-pattern-match-useless.rs +++ b/src/test/compile-fail/struct-pattern-match-useless.rs @@ -9,8 +9,8 @@ // except according to those terms. struct Foo { - x: int, - y: int, + x: isize, + y: isize, } pub fn main() { diff --git a/src/test/compile-fail/struct-variant-no-pub.rs b/src/test/compile-fail/struct-variant-no-pub.rs index 15ed69083e0..e62b39ad5aa 100644 --- a/src/test/compile-fail/struct-variant-no-pub.rs +++ b/src/test/compile-fail/struct-variant-no-pub.rs @@ -10,7 +10,7 @@ enum Foo { Bar { - pub a: int //~ ERROR: `pub` is not allowed here + pub a: isize //~ ERROR: `pub` is not allowed here } } diff --git a/src/test/compile-fail/struct-variant-privacy.rs b/src/test/compile-fail/struct-variant-privacy.rs index bf404c27648..f36862364e7 100644 --- a/src/test/compile-fail/struct-variant-privacy.rs +++ b/src/test/compile-fail/struct-variant-privacy.rs @@ -9,7 +9,7 @@ // except according to those terms. mod foo { enum Bar { - Baz { a: int } + Baz { a: isize } } } diff --git a/src/test/compile-fail/syntax-extension-bytes-too-small-u8-literal.rs b/src/test/compile-fail/syntax-extension-bytes-too-small-u8-literal.rs deleted file mode 100644 index ac33ffb60e2..00000000000 --- a/src/test/compile-fail/syntax-extension-bytes-too-small-u8-literal.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let vec = bytes!(-1024u8); //~ ERROR non-literal in bytes - //~^ WARN `bytes!` is deprecated -} diff --git a/src/test/compile-fail/syntax-extension-bytes-unsupported-literal.rs b/src/test/compile-fail/syntax-extension-bytes-unsupported-literal.rs deleted file mode 100644 index f6b3659354c..00000000000 --- a/src/test/compile-fail/syntax-extension-bytes-unsupported-literal.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - let vec = bytes!(45f64); //~ ERROR unsupported literal in bytes! - //~^ WARN `bytes!` is deprecated -} diff --git a/src/test/compile-fail/tag-variant-cast-non-nullary.rs b/src/test/compile-fail/tag-variant-cast-non-nullary.rs index 1d05c5d181d..b0106329126 100644 --- a/src/test/compile-fail/tag-variant-cast-non-nullary.rs +++ b/src/test/compile-fail/tag-variant-cast-non-nullary.rs @@ -12,10 +12,10 @@ enum non_nullary { nullary, - other(int), + other(isize), } fn main() { let v = non_nullary::nullary; - let val = v as int; + let val = v as isize; } diff --git a/src/test/compile-fail/tail-typeck.rs b/src/test/compile-fail/tail-typeck.rs index 786d1e12137..a934bbe61c4 100644 --- a/src/test/compile-fail/tail-typeck.rs +++ b/src/test/compile-fail/tail-typeck.rs @@ -10,8 +10,8 @@ // error-pattern: mismatched types -fn f() -> int { return g(); } +fn f() -> isize { return g(); } -fn g() -> uint { return 0u; } +fn g() -> usize { return 0us; } fn main() { let y = f(); } diff --git a/src/test/compile-fail/terr-in-field.rs b/src/test/compile-fail/terr-in-field.rs index 88da7bc8542..1e5422a798e 100644 --- a/src/test/compile-fail/terr-in-field.rs +++ b/src/test/compile-fail/terr-in-field.rs @@ -9,13 +9,13 @@ // except according to those terms. struct foo { - a: int, - b: int, + a: isize, + b: isize, } struct bar { - a: int, - b: uint, + a: isize, + b: usize, } fn want_foo(f: foo) {} diff --git a/src/test/compile-fail/terr-sorts.rs b/src/test/compile-fail/terr-sorts.rs index 53ebe1f9b5b..d1a37c99c47 100644 --- a/src/test/compile-fail/terr-sorts.rs +++ b/src/test/compile-fail/terr-sorts.rs @@ -10,8 +10,8 @@ struct foo { - a: int, - b: int, + a: isize, + b: isize, } type bar = Box<foo>; diff --git a/src/test/compile-fail/trailing-plus-in-bounds.rs b/src/test/compile-fail/trailing-plus-in-bounds.rs index b189acb685a..069c2e88793 100644 --- a/src/test/compile-fail/trailing-plus-in-bounds.rs +++ b/src/test/compile-fail/trailing-plus-in-bounds.rs @@ -11,7 +11,7 @@ use std::fmt::Show; fn main() { - let x: Box<Show+> = box 3i as Box<Show+>; + let x: Box<Show+> = box 3is as Box<Show+>; //~^ ERROR at least one type parameter bound must be specified //~^^ ERROR at least one type parameter bound must be specified } diff --git a/src/test/compile-fail/trait-bounds-on-structs-and-enums-locals.rs b/src/test/compile-fail/trait-bounds-on-structs-and-enums-locals.rs index 52035c09dd6..45a74a235e0 100644 --- a/src/test/compile-fail/trait-bounds-on-structs-and-enums-locals.rs +++ b/src/test/compile-fail/trait-bounds-on-structs-and-enums-locals.rs @@ -17,10 +17,10 @@ struct Foo<T:Trait> { fn main() { let foo = Foo { //~^ ERROR not implemented - x: 3i + x: 3is }; - let baz: Foo<uint> = panic!(); + let baz: Foo<usize> = panic!(); //~^ ERROR not implemented } diff --git a/src/test/compile-fail/trait-bounds-on-structs-and-enums-static.rs b/src/test/compile-fail/trait-bounds-on-structs-and-enums-static.rs index c26cccc8b14..d5369817e9a 100644 --- a/src/test/compile-fail/trait-bounds-on-structs-and-enums-static.rs +++ b/src/test/compile-fail/trait-bounds-on-structs-and-enums-static.rs @@ -14,7 +14,7 @@ struct Foo<T:Trait> { x: T, } -static X: Foo<uint> = Foo { +static X: Foo<usize> = Foo { //~^ ERROR not implemented x: 1, }; diff --git a/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc.rs b/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc.rs index d01f9d59fb4..ded75aa1d85 100644 --- a/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc.rs +++ b/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc.rs @@ -14,7 +14,7 @@ extern crate trait_bounds_on_structs_and_enums_xc; use trait_bounds_on_structs_and_enums_xc::{Bar, Foo, Trait}; -fn explode(x: Foo<uint>) {} +fn explode(x: Foo<usize>) {} //~^ ERROR not implemented fn kaboom(y: Bar<f32>) {} diff --git a/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc1.rs b/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc1.rs index d3689067aef..6179301c11d 100644 --- a/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc1.rs +++ b/src/test/compile-fail/trait-bounds-on-structs-and-enums-xc1.rs @@ -17,7 +17,7 @@ use trait_bounds_on_structs_and_enums_xc::{Bar, Foo, Trait}; fn main() { let foo = Foo { //~^ ERROR not implemented - x: 3i + x: 3is }; let bar: Bar<f64> = return; //~^ ERROR not implemented diff --git a/src/test/compile-fail/trait-bounds-on-structs-and-enums.rs b/src/test/compile-fail/trait-bounds-on-structs-and-enums.rs index c11b5d22878..490ee0e8ad6 100644 --- a/src/test/compile-fail/trait-bounds-on-structs-and-enums.rs +++ b/src/test/compile-fail/trait-bounds-on-structs-and-enums.rs @@ -15,9 +15,9 @@ struct Foo<T:Trait> { } enum Bar<T:Trait> { - ABar(int), + ABar(isize), BBar(T), - CBar(uint), + CBar(usize), } fn explode(x: Foo<u32>) {} @@ -33,12 +33,12 @@ impl<T> Foo<T> { struct Baz { //~^ ERROR not implemented - a: Foo<int>, + a: Foo<isize>, } enum Boo { //~^ ERROR not implemented - Quux(Bar<uint>), + Quux(Bar<usize>), } struct Badness<U> { @@ -57,7 +57,7 @@ trait PolyTrait<T> { struct Struct; -impl PolyTrait<Foo<uint>> for Struct { +impl PolyTrait<Foo<usize>> for Struct { //~^ ERROR not implemented fn whatever() {} } diff --git a/src/test/compile-fail/trait-coercion-generic-bad.rs b/src/test/compile-fail/trait-coercion-generic-bad.rs index e6ea8e10b22..1ddfc5b7ccd 100644 --- a/src/test/compile-fail/trait-coercion-generic-bad.rs +++ b/src/test/compile-fail/trait-coercion-generic-bad.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct Struct { person: &'static str diff --git a/src/test/compile-fail/trait-coercion-generic-regions.rs b/src/test/compile-fail/trait-coercion-generic-regions.rs index 5f4d51918ed..9c78d7ea243 100644 --- a/src/test/compile-fail/trait-coercion-generic-regions.rs +++ b/src/test/compile-fail/trait-coercion-generic-regions.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct Struct { person: &'static str diff --git a/src/test/compile-fail/trait-impl-1.rs b/src/test/compile-fail/trait-impl-1.rs index 44b478bfb15..1c7fa1e4263 100644 --- a/src/test/compile-fail/trait-impl-1.rs +++ b/src/test/compile-fail/trait-impl-1.rs @@ -18,7 +18,7 @@ impl<'a> T+'a { fn foo(&self) {} } -impl T for int {} +impl T for isize {} fn main() { let x = &42is; diff --git a/src/test/compile-fail/trait-impl-can-not-have-untraitful-methods.rs b/src/test/compile-fail/trait-impl-can-not-have-untraitful-methods.rs index 1471d9232b2..3538c7f1289 100644 --- a/src/test/compile-fail/trait-impl-can-not-have-untraitful-methods.rs +++ b/src/test/compile-fail/trait-impl-can-not-have-untraitful-methods.rs @@ -10,7 +10,7 @@ trait A { } -impl A for int { +impl A for isize { fn foo(&self) { } //~ ERROR method `foo` is not a member of trait `A` } diff --git a/src/test/compile-fail/trait-impl-different-num-params.rs b/src/test/compile-fail/trait-impl-different-num-params.rs index ea2062dd272..647dd4e05fa 100644 --- a/src/test/compile-fail/trait-impl-different-num-params.rs +++ b/src/test/compile-fail/trait-impl-different-num-params.rs @@ -9,10 +9,10 @@ // except according to those terms. trait foo { - fn bar(&self, x: uint) -> Self; + fn bar(&self, x: usize) -> Self; } -impl foo for int { - fn bar(&self) -> int { +impl foo for isize { + fn bar(&self) -> isize { //~^ ERROR method `bar` has 1 parameter but the declaration in trait `foo::bar` has 2 *self } diff --git a/src/test/compile-fail/trait-impl-method-mismatch.rs b/src/test/compile-fail/trait-impl-method-mismatch.rs index 73224c7b45c..4e2eb224213 100644 --- a/src/test/compile-fail/trait-impl-method-mismatch.rs +++ b/src/test/compile-fail/trait-impl-method-mismatch.rs @@ -10,12 +10,12 @@ trait Mumbo { - fn jumbo(&self, x: &uint) -> uint; + fn jumbo(&self, x: &usize) -> usize; } -impl Mumbo for uint { +impl Mumbo for usize { // Cannot have a larger effect than the trait: - unsafe fn jumbo(&self, x: &uint) { *self + *x; } + unsafe fn jumbo(&self, x: &usize) { *self + *x; } //~^ ERROR expected normal fn, found unsafe fn } diff --git a/src/test/compile-fail/trait-impl-of-supertrait-has-wrong-lifetime-parameters.rs b/src/test/compile-fail/trait-impl-of-supertrait-has-wrong-lifetime-parameters.rs index 716362415a6..44c53e70f86 100644 --- a/src/test/compile-fail/trait-impl-of-supertrait-has-wrong-lifetime-parameters.rs +++ b/src/test/compile-fail/trait-impl-of-supertrait-has-wrong-lifetime-parameters.rs @@ -13,26 +13,26 @@ // an impl of T1<'a>, but we have an impl of T1<'b>. trait T1<'x> { - fn x(&self) -> &'x int; + fn x(&self) -> &'x isize; } trait T2<'x, 'y> : T1<'x> { - fn y(&self) -> &'y int; + fn y(&self) -> &'y isize; } struct S<'a, 'b> { - a: &'a int, - b: &'b int + a: &'a isize, + b: &'b isize } impl<'a,'b> T1<'b> for S<'a, 'b> { - fn x(&self) -> &'b int { + fn x(&self) -> &'b isize { self.b } } impl<'a,'b> T2<'a, 'b> for S<'a, 'b> { //~ ERROR cannot infer an appropriate lifetime - fn y(&self) -> &'b int { + fn y(&self) -> &'b isize { self.b } } diff --git a/src/test/compile-fail/trait-matching-lifetimes.rs b/src/test/compile-fail/trait-matching-lifetimes.rs index 333730e0c4b..5ab80065572 100644 --- a/src/test/compile-fail/trait-matching-lifetimes.rs +++ b/src/test/compile-fail/trait-matching-lifetimes.rs @@ -12,8 +12,8 @@ // (Issue #15517.) struct Foo<'a,'b> { - x: &'a int, - y: &'b int, + x: &'a isize, + y: &'b isize, } trait Tr : Sized { diff --git a/src/test/compile-fail/trait-safety-fn-body.rs b/src/test/compile-fail/trait-safety-fn-body.rs index f894e2ee28e..499b58f70d7 100644 --- a/src/test/compile-fail/trait-safety-fn-body.rs +++ b/src/test/compile-fail/trait-safety-fn-body.rs @@ -15,7 +15,7 @@ unsafe trait UnsafeTrait : Sized { fn foo(self) { } } -unsafe impl UnsafeTrait for *mut int { +unsafe impl UnsafeTrait for *mut isize { fn foo(self) { // Unsafe actions are not made legal by taking place in an unsafe trait: *self += 1; //~ ERROR E0133 diff --git a/src/test/compile-fail/trait-safety-trait-impl-cc.rs b/src/test/compile-fail/trait-safety-trait-impl-cc.rs index 21dd5a237c5..032deb2e017 100644 --- a/src/test/compile-fail/trait-safety-trait-impl-cc.rs +++ b/src/test/compile-fail/trait-safety-trait-impl-cc.rs @@ -17,8 +17,8 @@ extern crate "trait-safety-lib" as lib; struct Bar; impl lib::Foo for Bar { //~ ERROR requires an `unsafe impl` declaration - fn foo(&self) -> int { - *self as int + fn foo(&self) -> isize { + *self as isize } } diff --git a/src/test/compile-fail/trait-test-2.rs b/src/test/compile-fail/trait-test-2.rs index a24f7710d7b..bdfc6dcda88 100644 --- a/src/test/compile-fail/trait-test-2.rs +++ b/src/test/compile-fail/trait-test-2.rs @@ -8,13 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait bar { fn dup(&self) -> Self; fn blah<X>(&self); } -impl bar for int { fn dup(&self) -> int { *self } fn blah<X>(&self) {} } -impl bar for uint { fn dup(&self) -> uint { *self } fn blah<X>(&self) {} } +impl bar for isize { fn dup(&self) -> isize { *self } fn blah<X>(&self) {} } +impl bar for usize { fn dup(&self) -> usize { *self } fn blah<X>(&self) {} } fn main() { - 10i.dup::<int>(); //~ ERROR does not take type parameters - 10i.blah::<int, int>(); //~ ERROR incorrect number of type parameters - (box 10i as Box<bar>).dup(); //~ ERROR cannot convert to a trait object + 10is.dup::<isize>(); //~ ERROR does not take type parameters + 10is.blah::<isize, isize>(); //~ ERROR incorrect number of type parameters + (box 10is as Box<bar>).dup(); //~ ERROR cannot convert to a trait object } diff --git a/src/test/compile-fail/trait-test.rs b/src/test/compile-fail/trait-test.rs index 1682e98fb23..d53e353d9d9 100644 --- a/src/test/compile-fail/trait-test.rs +++ b/src/test/compile-fail/trait-test.rs @@ -10,6 +10,6 @@ trait foo { fn foo(&self); } -impl int for uint { fn foo(&self) {} } //~ ERROR trait +impl isize for usize { fn foo(&self) {} } //~ ERROR trait fn main() {} diff --git a/src/test/compile-fail/traits-multidispatch-bad.rs b/src/test/compile-fail/traits-multidispatch-bad.rs index f5ce904a4bb..e9a4005b4b4 100644 --- a/src/test/compile-fail/traits-multidispatch-bad.rs +++ b/src/test/compile-fail/traits-multidispatch-bad.rs @@ -14,9 +14,9 @@ trait Convert<Target> { fn convert(&self) -> Target; } -impl Convert<uint> for int { - fn convert(&self) -> uint { - *self as uint +impl Convert<usize> for isize { + fn convert(&self) -> usize { + *self as usize } } @@ -26,7 +26,7 @@ where T : Convert<U> } fn a() { - test(22i, 44i); //~ ERROR not implemented + test(22is, 44is); //~ ERROR not implemented } fn main() {} diff --git a/src/test/compile-fail/transmute-impl.rs b/src/test/compile-fail/transmute-impl.rs index a68bba285df..a77a37a77e1 100644 --- a/src/test/compile-fail/transmute-impl.rs +++ b/src/test/compile-fail/transmute-impl.rs @@ -19,12 +19,12 @@ struct Foo<T: ?Sized> { } impl<T: ?Sized> Foo<T> { - fn m(x: &T) -> &int where T : Sized { + fn m(x: &T) -> &isize where T : Sized { // OK here, because T : Sized is in scope. unsafe { transmute(x) } } - fn n(x: &T) -> &int { + fn n(x: &T) -> &isize { // Not OK here, because T : Sized is not in scope. unsafe { transmute(x) } //~ ERROR transmute called on types with potentially different sizes } diff --git a/src/test/compile-fail/transmute-type-parameters.rs b/src/test/compile-fail/transmute-type-parameters.rs index 2286c0e75bd..b06966bd867 100644 --- a/src/test/compile-fail/transmute-type-parameters.rs +++ b/src/test/compile-fail/transmute-type-parameters.rs @@ -13,15 +13,15 @@ use std::mem::transmute; unsafe fn f<T>(x: T) { - let _: int = transmute(x); //~ ERROR cannot transmute + let _: isize = transmute(x); //~ ERROR cannot transmute } -unsafe fn g<T>(x: (T, int)) { - let _: int = transmute(x); //~ ERROR cannot transmute +unsafe fn g<T>(x: (T, isize)) { + let _: isize = transmute(x); //~ ERROR cannot transmute } unsafe fn h<T>(x: [T; 10]) { - let _: int = transmute(x); //~ ERROR cannot transmute + let _: isize = transmute(x); //~ ERROR cannot transmute } struct Bad<T> { @@ -29,7 +29,7 @@ struct Bad<T> { } unsafe fn i<T>(x: Bad<T>) { - let _: int = transmute(x); //~ ERROR cannot transmute + let _: isize = transmute(x); //~ ERROR cannot transmute } enum Worse<T> { @@ -38,11 +38,11 @@ enum Worse<T> { } unsafe fn j<T>(x: Worse<T>) { - let _: int = transmute(x); //~ ERROR cannot transmute + let _: isize = transmute(x); //~ ERROR cannot transmute } unsafe fn k<T>(x: Option<T>) { - let _: int = transmute(x); //~ ERROR cannot transmute + let _: isize = transmute(x); //~ ERROR cannot transmute } fn main() {} diff --git a/src/test/compile-fail/tuple-index-not-tuple.rs b/src/test/compile-fail/tuple-index-not-tuple.rs index 33aeebb3691..bf2a63abbfd 100644 --- a/src/test/compile-fail/tuple-index-not-tuple.rs +++ b/src/test/compile-fail/tuple-index-not-tuple.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Point { x: int, y: int } +struct Point { x: isize, y: isize } struct Empty; fn main() { diff --git a/src/test/compile-fail/tuple-struct-nonexhaustive.rs b/src/test/compile-fail/tuple-struct-nonexhaustive.rs index 1f14fbb27ad..e4fda6dd534 100644 --- a/src/test/compile-fail/tuple-struct-nonexhaustive.rs +++ b/src/test/compile-fail/tuple-struct-nonexhaustive.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct Foo(int, int); +struct Foo(isize, isize); fn main() { let x = Foo(1, 2); diff --git a/src/test/compile-fail/tutorial-suffix-inference-test.rs b/src/test/compile-fail/tutorial-suffix-inference-test.rs index 85ad302f3ed..1b44c7e8128 100644 --- a/src/test/compile-fail/tutorial-suffix-inference-test.rs +++ b/src/test/compile-fail/tutorial-suffix-inference-test.rs @@ -23,7 +23,7 @@ fn main() { let a = 3is; - fn identity_i(n: isize) -> int { n } + fn identity_i(n: isize) -> isize { n } identity_i(a); // ok identity_u16(a); diff --git a/src/test/compile-fail/type-parameters-in-field-exprs.rs b/src/test/compile-fail/type-parameters-in-field-exprs.rs index 023f7d1c29f..54ddb3e19fa 100644 --- a/src/test/compile-fail/type-parameters-in-field-exprs.rs +++ b/src/test/compile-fail/type-parameters-in-field-exprs.rs @@ -9,8 +9,8 @@ // except according to those terms. struct Foo { - x: int, - y: int, + x: isize, + y: isize, } fn main() { @@ -18,7 +18,7 @@ fn main() { x: 1, y: 2, }; - f.x::<int>; + f.x::<isize>; //~^ ERROR field expressions may not have type parameters } diff --git a/src/test/compile-fail/type-recursive.rs b/src/test/compile-fail/type-recursive.rs index a2b4e8d9782..9dcb60628a9 100644 --- a/src/test/compile-fail/type-recursive.rs +++ b/src/test/compile-fail/type-recursive.rs @@ -10,7 +10,7 @@ // error-pattern:this type cannot be instantiated struct t1 { - foo: int, + foo: isize, foolish: t1 } diff --git a/src/test/compile-fail/type-shadow.rs b/src/test/compile-fail/type-shadow.rs index 50c8cf99d3c..6d8c0fe22bd 100644 --- a/src/test/compile-fail/type-shadow.rs +++ b/src/test/compile-fail/type-shadow.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - type X = int; + type X = isize; type Y = X; if true { type X = &'static str; diff --git a/src/test/compile-fail/typeck-unsafe-always-share.rs b/src/test/compile-fail/typeck-unsafe-always-share.rs index 5166a4e9654..a9113c6e99f 100644 --- a/src/test/compile-fail/typeck-unsafe-always-share.rs +++ b/src/test/compile-fail/typeck-unsafe-always-share.rs @@ -28,7 +28,7 @@ fn test<T: Sync>(s: T){ } fn main() { - let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)}); + let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0is)}); test(us); //~^ ERROR `core::marker::Sync` is not implemented diff --git a/src/test/compile-fail/typeck_type_placeholder_item.rs b/src/test/compile-fail/typeck_type_placeholder_item.rs index 723c5fda3a7..d69c0dc5d1f 100644 --- a/src/test/compile-fail/typeck_type_placeholder_item.rs +++ b/src/test/compile-fail/typeck_type_placeholder_item.rs @@ -14,7 +14,7 @@ fn test() -> _ { 5 } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures -fn test2() -> (_, _) { (5u, 5u) } +fn test2() -> (_, _) { (5us, 5us) } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures //~^^ ERROR the type placeholder `_` is not allowed within types on item signatures @@ -31,7 +31,7 @@ static TEST5: (_, _) = (1, 2); fn test6(_: _) { } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures -fn test7(x: _) { let _x: uint = x; } +fn test7(x: _) { let _x: usize = x; } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures fn test8(_f: fn() -> _) { } @@ -67,7 +67,7 @@ pub fn main() { fn fn_test() -> _ { 5 } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures - fn fn_test2() -> (_, _) { (5u, 5u) } + fn fn_test2() -> (_, _) { (5us, 5us) } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures //~^^ ERROR the type placeholder `_` is not allowed within types on item signatures @@ -84,7 +84,7 @@ pub fn main() { fn fn_test6(_: _) { } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures - fn fn_test7(x: _) { let _x: uint = x; } + fn fn_test7(x: _) { let _x: usize = x; } //~^ ERROR the type placeholder `_` is not allowed within types on item signatures fn fn_test8(_f: fn() -> _) { } diff --git a/src/test/compile-fail/typeck_type_placeholder_lifetime_1.rs b/src/test/compile-fail/typeck_type_placeholder_lifetime_1.rs index 9694c1d9f98..e1d17e4fef7 100644 --- a/src/test/compile-fail/typeck_type_placeholder_lifetime_1.rs +++ b/src/test/compile-fail/typeck_type_placeholder_lifetime_1.rs @@ -16,6 +16,6 @@ struct Foo<'a, T:'a> { } pub fn main() { - let c: Foo<_, _> = Foo { r: &5u }; + let c: Foo<_, _> = Foo { r: &5us }; //~^ ERROR wrong number of type arguments: expected 1, found 2 } diff --git a/src/test/compile-fail/typeck_type_placeholder_lifetime_2.rs b/src/test/compile-fail/typeck_type_placeholder_lifetime_2.rs index 365b786cc1a..8178335de59 100644 --- a/src/test/compile-fail/typeck_type_placeholder_lifetime_2.rs +++ b/src/test/compile-fail/typeck_type_placeholder_lifetime_2.rs @@ -16,6 +16,6 @@ struct Foo<'a, T:'a> { } pub fn main() { - let c: Foo<_, uint> = Foo { r: &5 }; + let c: Foo<_, usize> = Foo { r: &5 }; //~^ ERROR wrong number of type arguments: expected 1, found 2 } diff --git a/src/test/compile-fail/ufcs-explicit-self-bad.rs b/src/test/compile-fail/ufcs-explicit-self-bad.rs index 8d3610affdf..6c323e8c1ae 100644 --- a/src/test/compile-fail/ufcs-explicit-self-bad.rs +++ b/src/test/compile-fail/ufcs-explicit-self-bad.rs @@ -8,12 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct Foo { - f: int, + f: isize, } impl Foo { - fn foo(self: int, x: int) -> int { //~ ERROR mismatched self type + fn foo(self: isize, x: isize) -> isize { //~ ERROR mismatched self type self.f + x } } @@ -23,10 +25,10 @@ struct Bar<T> { } impl<T> Bar<T> { - fn foo(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type + fn foo(self: Bar<isize>, x: isize) -> isize { //~ ERROR mismatched self type x } - fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type + fn bar(self: &Bar<usize>, x: isize) -> isize { //~ ERROR mismatched self type x } } diff --git a/src/test/compile-fail/unboxed-closure-feature-gate.rs b/src/test/compile-fail/unboxed-closure-feature-gate.rs index 9bb8037e2c3..5eb67a9bb71 100644 --- a/src/test/compile-fail/unboxed-closure-feature-gate.rs +++ b/src/test/compile-fail/unboxed-closure-feature-gate.rs @@ -15,11 +15,11 @@ trait Foo<A,R> { } fn main() { - let x: Box<Foo(int)>; + let x: Box<Foo(isize)>; //~^ ERROR parenthetical notation is only stable when used with the `Fn` family // No errors with these: - let x: Box<Fn(int)>; - let x: Box<FnMut(int)>; - let x: Box<FnOnce(int)>; + let x: Box<Fn(isize)>; + let x: Box<FnMut(isize)>; + let x: Box<FnOnce(isize)>; } diff --git a/src/test/compile-fail/unboxed-closure-illegal-move.rs b/src/test/compile-fail/unboxed-closure-illegal-move.rs index 9e981f2c9bb..d489c3a64fa 100644 --- a/src/test/compile-fail/unboxed-closure-illegal-move.rs +++ b/src/test/compile-fail/unboxed-closure-illegal-move.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] #![feature(unboxed_closures)] // Tests that we can't move out of an unboxed closure environment @@ -17,28 +18,28 @@ fn main() { // By-ref cases { - let x = box 0u; + let x = box 0us; let f = |&:| drop(x); //~ cannot move } { - let x = box 0u; + let x = box 0us; let f = |&mut:| drop(x); //~ cannot move } { - let x = box 0u; + let x = box 0us; let f = |:| drop(x); //~ cannot move } // By-value cases { - let x = box 0u; + let x = box 0us; let f = move |&:| drop(x); //~ cannot move } { - let x = box 0u; + let x = box 0us; let f = move |&mut:| drop(x); //~ cannot move } { - let x = box 0u; + let x = box 0us; let f = move |:| drop(x); // this one is ok } } diff --git a/src/test/compile-fail/unboxed-closure-immutable-capture.rs b/src/test/compile-fail/unboxed-closure-immutable-capture.rs index e28abaf2b1f..ebdd3c3107f 100644 --- a/src/test/compile-fail/unboxed-closure-immutable-capture.rs +++ b/src/test/compile-fail/unboxed-closure-immutable-capture.rs @@ -14,10 +14,10 @@ // environment cannot mutate captured variables that have not been // declared mutable (#18335) -fn set(x: &mut uint) { *x = 0; } +fn set(x: &mut usize) { *x = 0; } fn main() { - let x = 0u; + let x = 0us; move |&mut:| x = 1; //~ ERROR cannot assign move |&mut:| set(&mut x); //~ ERROR cannot borrow move |:| x = 1; //~ ERROR cannot assign diff --git a/src/test/compile-fail/unboxed-closure-region.rs b/src/test/compile-fail/unboxed-closure-region.rs index 2a71aeaca5f..9d966798694 100644 --- a/src/test/compile-fail/unboxed-closure-region.rs +++ b/src/test/compile-fail/unboxed-closure-region.rs @@ -14,7 +14,7 @@ // reference cannot escape the region of that variable. fn main() { let _f = { - let x = 0u; + let x = 0us; |:| x //~ ERROR cannot infer an appropriate lifetime due to conflicting requirements }; } diff --git a/src/test/compile-fail/unboxed-closure-sugar-default.rs b/src/test/compile-fail/unboxed-closure-sugar-default.rs index 82355ddf681..0d9e406b086 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-default.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-default.rs @@ -24,14 +24,14 @@ fn eq<A: ?Sized,B: ?Sized>() where A : Eq<B> { } fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. - eq::< Foo<(int,),()>, Foo(int) >(); + eq::< Foo<(isize,),()>, Foo(isize) >(); // In angle version, we supply something other than the default - eq::< Foo<(int,),(),int>, Foo(int) >(); + eq::< Foo<(isize,),(),isize>, Foo(isize) >(); //~^ ERROR not implemented // Supply default explicitly. - eq::< Foo<(int,),(),(int,)>, Foo(int) >(); + eq::< Foo<(isize,),(),(isize,)>, Foo(isize) >(); } fn main() { } diff --git a/src/test/compile-fail/unboxed-closure-sugar-equiv.rs b/src/test/compile-fail/unboxed-closure-sugar-equiv.rs index f36fad30670..9dff0e9e01e 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-equiv.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-equiv.rs @@ -27,26 +27,26 @@ fn eq<A: ?Sized,B: ?Sized +Eq<A>>() { } fn test<'a,'b>() { // No errors expected: eq::< Foo<(),()>, Foo() >(); - eq::< Foo<(int,),()>, Foo(int) >(); - eq::< Foo<(int,uint),()>, Foo(int,uint) >(); - eq::< Foo<(int,uint),uint>, Foo(int,uint) -> uint >(); - eq::< Foo<(&'a int,&'b uint),uint>, Foo(&'a int,&'b uint) -> uint >(); + eq::< Foo<(isize,),()>, Foo(isize) >(); + eq::< Foo<(isize,usize),()>, Foo(isize,usize) >(); + eq::< Foo<(isize,usize),usize>, Foo(isize,usize) -> usize >(); + eq::< Foo<(&'a isize,&'b usize),usize>, Foo(&'a isize,&'b usize) -> usize >(); // Test that anonymous regions in `()` form are equivalent // to fresh bound regions, and that we can intermingle // named and anonymous as we choose: - eq::< for<'x,'y> Foo<(&'x int,&'y uint),uint>, - for<'x,'y> Foo(&'x int,&'y uint) -> uint >(); - eq::< for<'x,'y> Foo<(&'x int,&'y uint),uint>, - for<'x> Foo(&'x int,&uint) -> uint >(); - eq::< for<'x,'y> Foo<(&'x int,&'y uint),uint>, - for<'y> Foo(&int,&'y uint) -> uint >(); - eq::< for<'x,'y> Foo<(&'x int,&'y uint),uint>, - Foo(&int,&uint) -> uint >(); + eq::< for<'x,'y> Foo<(&'x isize,&'y usize),usize>, + for<'x,'y> Foo(&'x isize,&'y usize) -> usize >(); + eq::< for<'x,'y> Foo<(&'x isize,&'y usize),usize>, + for<'x> Foo(&'x isize,&usize) -> usize >(); + eq::< for<'x,'y> Foo<(&'x isize,&'y usize),usize>, + for<'y> Foo(&isize,&'y usize) -> usize >(); + eq::< for<'x,'y> Foo<(&'x isize,&'y usize),usize>, + Foo(&isize,&usize) -> usize >(); // lifetime elision - eq::< for<'x> Foo<(&'x int,), &'x int>, - Foo(&int) -> &int >(); + eq::< for<'x> Foo<(&'x isize,), &'x isize>, + Foo(&isize) -> &isize >(); // Errors expected: eq::< Foo<(),()>, Foo(char) >(); diff --git a/src/test/compile-fail/unboxed-closure-sugar-lifetime-elision.rs b/src/test/compile-fail/unboxed-closure-sugar-lifetime-elision.rs index 2617be295cd..29429c708d2 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-lifetime-elision.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-lifetime-elision.rs @@ -25,10 +25,10 @@ impl<X: ?Sized> Eq<X> for X { } fn eq<A: ?Sized,B: ?Sized +Eq<A>>() { } fn main() { - eq::< for<'a> Foo<(&'a int,), &'a int>, - Foo(&int) -> &int >(); - eq::< for<'a> Foo<(&'a int,), (&'a int, &'a int)>, - Foo(&int) -> (&int, &int) >(); + eq::< for<'a> Foo<(&'a isize,), &'a isize>, + Foo(&isize) -> &isize >(); + eq::< for<'a> Foo<(&'a isize,), (&'a isize, &'a isize)>, + Foo(&isize) -> (&isize, &isize) >(); - let _: Foo(&int, &uint) -> &uint; //~ ERROR missing lifetime specifier + let _: Foo(&isize, &usize) -> &usize; //~ ERROR missing lifetime specifier } diff --git a/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs b/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs index 23e2d2f4365..12f62d805e1 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-nonexistent-trait.rs @@ -10,11 +10,11 @@ #![feature(unboxed_closures)] -fn f<F:Nonexist(int) -> int>(x: F) {} //~ ERROR nonexistent trait `Nonexist` +fn f<F:Nonexist(isize) -> isize>(x: F) {} //~ ERROR nonexistent trait `Nonexist` -type Typedef = int; +type Typedef = isize; -fn g<F:Typedef(int) -> int>(x: F) {} //~ ERROR `Typedef` is not a trait +fn g<F:Typedef(isize) -> isize>(x: F) {} //~ ERROR `Typedef` is not a trait fn main() {} diff --git a/src/test/compile-fail/unboxed-closure-sugar-region.rs b/src/test/compile-fail/unboxed-closure-sugar-region.rs index e0783b09cbd..c8dd33c11fd 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-region.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-region.rs @@ -29,14 +29,14 @@ fn same_type<A,B:Eq<A>>(a: A, b: B) { } fn test<'a,'b>() { // Parens are equivalent to omitting default in angle. - eq::< Foo<(int,),()>, Foo(int) >(); + eq::< Foo<(isize,),()>, Foo(isize) >(); // Here we specify 'static explicitly in angle-bracket version. // Parenthesized winds up getting inferred. - eq::< Foo<'static, (int,),()>, Foo(int) >(); + eq::< Foo<'static, (isize,),()>, Foo(isize) >(); } -fn test2(x: &Foo<(int,),()>, y: &Foo(int)) { +fn test2(x: &Foo<(isize,),()>, y: &Foo(isize)) { // Here, the omitted lifetimes are expanded to distinct things. same_type(x, y) //~ ERROR cannot infer } diff --git a/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs b/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs index 5e16adc4e42..d86f55d5368 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-used-on-struct-3.rs @@ -19,7 +19,7 @@ impl<A,B> Bar<A,B> { } fn bar() { - let b = Box::Bar::<int,uint>::new(); // OK + let b = Box::Bar::<isize,usize>::new(); // OK let b = Box::Bar::()::new(); //~^ ERROR expected ident, found `(` diff --git a/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs b/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs index ba1e931ac64..b58e08355c1 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-wrong-trait.rs @@ -12,7 +12,7 @@ trait Trait {} -fn f<F:Trait(int) -> int>(x: F) {} +fn f<F:Trait(isize) -> isize>(x: F) {} //~^ ERROR wrong number of type arguments: expected 0, found 2 fn main() {} diff --git a/src/test/compile-fail/unboxed-closures-borrow-conflict.rs b/src/test/compile-fail/unboxed-closures-borrow-conflict.rs index baf7f3f5e58..bb92e57d70c 100644 --- a/src/test/compile-fail/unboxed-closures-borrow-conflict.rs +++ b/src/test/compile-fail/unboxed-closures-borrow-conflict.rs @@ -14,7 +14,7 @@ // cause borrow conflicts. fn main() { - let mut x = 0u; + let mut x = 0us; let f = |:| x += 1; let _y = x; //~ ERROR cannot use `x` because it was mutably borrowed } diff --git a/src/test/compile-fail/unboxed-closures-fnmut-as-fn.rs b/src/test/compile-fail/unboxed-closures-fnmut-as-fn.rs index 9fbb8a18ae9..fc87ec9f959 100644 --- a/src/test/compile-fail/unboxed-closures-fnmut-as-fn.rs +++ b/src/test/compile-fail/unboxed-closures-fnmut-as-fn.rs @@ -18,13 +18,13 @@ use std::ops::{Fn,FnMut,FnOnce}; struct S; -impl FnMut<(int,),int> for S { - extern "rust-call" fn call_mut(&mut self, (x,): (int,)) -> int { +impl FnMut<(isize,),isize> for S { + extern "rust-call" fn call_mut(&mut self, (x,): (isize,)) -> isize { x * x } } -fn call_it<F:Fn(int)->int>(f: &F, x: int) -> int { +fn call_it<F:Fn(isize)->isize>(f: &F, x: isize) -> isize { f.call((x,)) } diff --git a/src/test/compile-fail/unboxed-closures-infer-argument-types-two-region-pointers.rs b/src/test/compile-fail/unboxed-closures-infer-argument-types-two-region-pointers.rs index 72109b22957..525d0b31995 100644 --- a/src/test/compile-fail/unboxed-closures-infer-argument-types-two-region-pointers.rs +++ b/src/test/compile-fail/unboxed-closures-infer-argument-types-two-region-pointers.rs @@ -23,7 +23,7 @@ fn doit<T,F>(val: T, f: &F) } pub fn main() { - doit(0i, &|&: x, y| { + doit(0is, &|&: x, y| { x.set(y); //~ ERROR cannot infer }); } diff --git a/src/test/compile-fail/unboxed-closures-static-call-wrong-trait.rs b/src/test/compile-fail/unboxed-closures-static-call-wrong-trait.rs index ddd2649a3fe..22bfabf040a 100644 --- a/src/test/compile-fail/unboxed-closures-static-call-wrong-trait.rs +++ b/src/test/compile-fail/unboxed-closures-static-call-wrong-trait.rs @@ -12,6 +12,6 @@ fn main() { let mut_ = |&mut: x| x; - mut_.call((0i, )); //~ ERROR does not implement any method in scope named `call` + mut_.call((0is, )); //~ ERROR does not implement any method in scope named `call` } diff --git a/src/test/compile-fail/unboxed-closures-type-mismatch.rs b/src/test/compile-fail/unboxed-closures-type-mismatch.rs index 61f13172832..f7ac2274ffb 100644 --- a/src/test/compile-fail/unboxed-closures-type-mismatch.rs +++ b/src/test/compile-fail/unboxed-closures-type-mismatch.rs @@ -13,7 +13,7 @@ use std::ops::FnMut; pub fn main() { - let mut f = |&mut: x: int, y: int| -> int { x + y }; - let z = f(1u, 2); //~ ERROR mismatched types + let mut f = |&mut: x: isize, y: isize| -> isize { x + y }; + let z = f(1us, 2); //~ ERROR mismatched types println!("{}", z); } diff --git a/src/test/compile-fail/unboxed-closures-unsafe-extern-fn.rs b/src/test/compile-fail/unboxed-closures-unsafe-extern-fn.rs index b0b37d077c1..ab909717cab 100644 --- a/src/test/compile-fail/unboxed-closures-unsafe-extern-fn.rs +++ b/src/test/compile-fail/unboxed-closures-unsafe-extern-fn.rs @@ -14,11 +14,11 @@ use std::ops::{Fn,FnMut,FnOnce}; -unsafe fn square(x: &int) -> int { (*x) * (*x) } +unsafe fn square(x: &isize) -> isize { (*x) * (*x) } -fn call_it<F:Fn(&int)->int>(_: &F, _: int) -> int { 0 } -fn call_it_mut<F:FnMut(&int)->int>(_: &mut F, _: int) -> int { 0 } -fn call_it_once<F:FnOnce(&int)->int>(_: F, _: int) -> int { 0 } +fn call_it<F:Fn(&isize)->isize>(_: &F, _: isize) -> isize { 0 } +fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 } +fn call_it_once<F:FnOnce(&isize)->isize>(_: F, _: isize) -> isize { 0 } fn a() { let x = call_it(&square, 22); //~ ERROR not implemented diff --git a/src/test/compile-fail/unboxed-closures-vtable-mismatch.rs b/src/test/compile-fail/unboxed-closures-vtable-mismatch.rs index 85b33f73bbc..95673a51319 100644 --- a/src/test/compile-fail/unboxed-closures-vtable-mismatch.rs +++ b/src/test/compile-fail/unboxed-closures-vtable-mismatch.rs @@ -12,12 +12,12 @@ use std::ops::FnMut; -fn call_it<F:FnMut<(int,int),int>>(y: int, mut f: F) -> int { +fn call_it<F:FnMut<(isize,isize),isize>>(y: isize, mut f: F) -> isize { f(2, y) } pub fn main() { - let f = |&mut: x: uint, y: int| -> int { (x as int) + y }; + let f = |&mut: x: usize, y: isize| -> isize { (x as isize) + y }; let z = call_it(3, f); //~ ERROR type mismatch println!("{}", z); } diff --git a/src/test/compile-fail/unboxed-closures-wrong-abi.rs b/src/test/compile-fail/unboxed-closures-wrong-abi.rs index 20a4ab85d7b..4a0b55558c0 100644 --- a/src/test/compile-fail/unboxed-closures-wrong-abi.rs +++ b/src/test/compile-fail/unboxed-closures-wrong-abi.rs @@ -14,11 +14,11 @@ use std::ops::{Fn,FnMut,FnOnce}; -extern "C" fn square(x: &int) -> int { (*x) * (*x) } +extern "C" fn square(x: &isize) -> isize { (*x) * (*x) } -fn call_it<F:Fn(&int)->int>(_: &F, _: int) -> int { 0 } -fn call_it_mut<F:FnMut(&int)->int>(_: &mut F, _: int) -> int { 0 } -fn call_it_once<F:FnOnce(&int)->int>(_: F, _: int) -> int { 0 } +fn call_it<F:Fn(&isize)->isize>(_: &F, _: isize) -> isize { 0 } +fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 } +fn call_it_once<F:FnOnce(&isize)->isize>(_: F, _: isize) -> isize { 0 } fn a() { let x = call_it(&square, 22); //~ ERROR not implemented diff --git a/src/test/compile-fail/unboxed-closures-wrong-arg-type-extern-fn.rs b/src/test/compile-fail/unboxed-closures-wrong-arg-type-extern-fn.rs index f08cff3cd68..b2fdf792630 100644 --- a/src/test/compile-fail/unboxed-closures-wrong-arg-type-extern-fn.rs +++ b/src/test/compile-fail/unboxed-closures-wrong-arg-type-extern-fn.rs @@ -14,12 +14,12 @@ use std::ops::{Fn,FnMut,FnOnce}; -unsafe fn square(x: int) -> int { x * x } -// note: argument type here is `int`, not `&int` +unsafe fn square(x: isize) -> isize { x * x } +// note: argument type here is `isize`, not `&isize` -fn call_it<F:Fn(&int)->int>(_: &F, _: int) -> int { 0 } -fn call_it_mut<F:FnMut(&int)->int>(_: &mut F, _: int) -> int { 0 } -fn call_it_once<F:FnOnce(&int)->int>(_: F, _: int) -> int { 0 } +fn call_it<F:Fn(&isize)->isize>(_: &F, _: isize) -> isize { 0 } +fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 } +fn call_it_once<F:FnOnce(&isize)->isize>(_: F, _: isize) -> isize { 0 } fn a() { let x = call_it(&square, 22); //~ ERROR not implemented diff --git a/src/test/compile-fail/unboxed-closures-wrong-trait.rs b/src/test/compile-fail/unboxed-closures-wrong-trait.rs index e15fe8ad049..e4255d0024f 100644 --- a/src/test/compile-fail/unboxed-closures-wrong-trait.rs +++ b/src/test/compile-fail/unboxed-closures-wrong-trait.rs @@ -10,13 +10,13 @@ #![feature(lang_items, overloaded_calls, unboxed_closures)] -fn c<F:Fn(int, int) -> int>(f: F) -> int { +fn c<F:Fn(isize, isize) -> isize>(f: F) -> isize { f(5, 6) } fn main() { - let z: int = 7; - assert_eq!(c(|&mut: x: int, y| x + y + z), 10); + let z: isize = 7; + assert_eq!(c(|&mut: x: isize, y| x + y + z), 10); //~^ ERROR not implemented } diff --git a/src/test/compile-fail/uninhabited-enum-cast.rs b/src/test/compile-fail/uninhabited-enum-cast.rs index 9f91337db9f..b4df5fb1e2a 100644 --- a/src/test/compile-fail/uninhabited-enum-cast.rs +++ b/src/test/compile-fail/uninhabited-enum-cast.rs @@ -11,7 +11,7 @@ enum E {} fn f(e: E) { - println!("{}", (e as int).to_string()); //~ ERROR non-scalar cast + println!("{}", (e as isize).to_string()); //~ ERROR non-scalar cast } fn main() {} diff --git a/src/test/compile-fail/unique-object-noncopyable.rs b/src/test/compile-fail/unique-object-noncopyable.rs index e237e2c8b75..5074d00ca15 100644 --- a/src/test/compile-fail/unique-object-noncopyable.rs +++ b/src/test/compile-fail/unique-object-noncopyable.rs @@ -8,13 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] trait Foo { fn f(&self); } struct Bar { - x: int, + x: isize, } impl Drop for Bar { diff --git a/src/test/compile-fail/unique-pinned-nocopy.rs b/src/test/compile-fail/unique-pinned-nocopy.rs index d306d171ca8..04eaa3d7ae0 100644 --- a/src/test/compile-fail/unique-pinned-nocopy.rs +++ b/src/test/compile-fail/unique-pinned-nocopy.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + #[derive(Show)] struct r { b: bool, diff --git a/src/test/compile-fail/unique-unique-kind.rs b/src/test/compile-fail/unique-unique-kind.rs index 49cebbf5255..4b7f11b0560 100644 --- a/src/test/compile-fail/unique-unique-kind.rs +++ b/src/test/compile-fail/unique-unique-kind.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] use std::rc::Rc; @@ -15,7 +16,7 @@ fn f<T:Send>(_i: T) { } fn main() { - let i = box Rc::new(100i); + let i = box Rc::new(100is); f(i); //~^ ERROR `core::marker::Send` is not implemented //~^^ ERROR `core::marker::Send` is not implemented diff --git a/src/test/compile-fail/unique-vec-res.rs b/src/test/compile-fail/unique-vec-res.rs index 4848c988300..4a84bb4c5ab 100644 --- a/src/test/compile-fail/unique-vec-res.rs +++ b/src/test/compile-fail/unique-vec-res.rs @@ -10,11 +10,13 @@ #![feature(unsafe_destructor)] +#![feature(box_syntax)] + use std::cell::Cell; #[derive(Show)] struct r<'a> { - i: &'a Cell<int>, + i: &'a Cell<isize>, } #[unsafe_destructor] diff --git a/src/test/compile-fail/unnecessary-private.rs b/src/test/compile-fail/unnecessary-private.rs index abbb084dbc0..6e6ffd23c4a 100644 --- a/src/test/compile-fail/unnecessary-private.rs +++ b/src/test/compile-fail/unnecessary-private.rs @@ -19,7 +19,7 @@ fn main() { } struct D { - pub foo: int, //~ ERROR: visibility has no effect + pub foo: isize, //~ ERROR: visibility has no effect } pub fn foo() {} //~ ERROR: visibility has no effect pub mod bar {} //~ ERROR: visibility has no effect diff --git a/src/test/compile-fail/unop-move-semantics.rs b/src/test/compile-fail/unop-move-semantics.rs index f8cbdb4e160..94656667598 100644 --- a/src/test/compile-fail/unop-move-semantics.rs +++ b/src/test/compile-fail/unop-move-semantics.rs @@ -31,9 +31,9 @@ fn illegal_dereference<T: Not<Output=T>>(mut x: T, y: T) { let m = &mut x; let n = &y; - !*m; //~ ERROR: cannot move out of dereference of `&mut`-pointer + !*m; //~ ERROR: cannot move out of borrowed content - !*n; //~ ERROR: cannot move out of dereference of `&`-pointer + !*n; //~ ERROR: cannot move out of borrowed content } fn main() {} diff --git a/src/test/compile-fail/unreachable-arm.rs b/src/test/compile-fail/unreachable-arm.rs index 3ff6c733026..f403457efbc 100644 --- a/src/test/compile-fail/unreachable-arm.rs +++ b/src/test/compile-fail/unreachable-arm.rs @@ -10,7 +10,8 @@ // error-pattern:unreachable pattern +#![feature(box_syntax)] -enum foo { a(Box<foo>, int), b(uint), } +enum foo { a(Box<foo>, isize), b(usize), } -fn main() { match foo::b(1u) { foo::b(_) | foo::a(box _, 1) => { } foo::a(_, 1) => { } } } +fn main() { match foo::b(1us) { foo::b(_) | foo::a(box _, 1) => { } foo::a(_, 1) => { } } } diff --git a/src/test/compile-fail/unreachable-code.rs b/src/test/compile-fail/unreachable-code.rs index 87342352e9a..d96578f2df9 100644 --- a/src/test/compile-fail/unreachable-code.rs +++ b/src/test/compile-fail/unreachable-code.rs @@ -14,5 +14,5 @@ fn main() { loop{} - let a = 3i; //~ ERROR: unreachable statement + let a = 3is; //~ ERROR: unreachable statement } diff --git a/src/test/compile-fail/unsafe-fn-autoderef.rs b/src/test/compile-fail/unsafe-fn-autoderef.rs index 464abd57872..97a7bf14710 100644 --- a/src/test/compile-fail/unsafe-fn-autoderef.rs +++ b/src/test/compile-fail/unsafe-fn-autoderef.rs @@ -9,10 +9,10 @@ // except according to those terms. struct Rec { - f: int + f: isize } -fn f(p: *const Rec) -> int { +fn f(p: *const Rec) -> isize { // Test that * ptrs do not autoderef. There is a deeper reason for // prohibiting this, beyond making unsafe things annoying (which doesn't diff --git a/src/test/compile-fail/unsendable-class.rs b/src/test/compile-fail/unsendable-class.rs index 96f36af53aa..abd93fdfc6c 100644 --- a/src/test/compile-fail/unsendable-class.rs +++ b/src/test/compile-fail/unsendable-class.rs @@ -16,11 +16,11 @@ use std::sync::mpsc::channel; use std::rc::Rc; struct foo { - i: int, + i: isize, j: Rc<String>, } -fn foo(i:int, j: Rc<String>) -> foo { +fn foo(i:isize, j: Rc<String>) -> foo { foo { i: i, j: j diff --git a/src/test/compile-fail/unsized2.rs b/src/test/compile-fail/unsized2.rs index c5f9e8d5991..604f7ba3255 100644 --- a/src/test/compile-fail/unsized2.rs +++ b/src/test/compile-fail/unsized2.rs @@ -13,5 +13,8 @@ fn f<X>() {} pub fn main() { - f<type>(); //~ ERROR expected identifier, found keyword `type` + f<type>(); + //~^ ERROR expected identifier, found keyword `type` + //~^^ ERROR: Chained comparison operators require parentheses + //~^^^ HELP: Use ::< instead of < if you meant to specify type arguments. } diff --git a/src/test/compile-fail/unsized3.rs b/src/test/compile-fail/unsized3.rs index 2d330654881..9d4cfe0f4ac 100644 --- a/src/test/compile-fail/unsized3.rs +++ b/src/test/compile-fail/unsized3.rs @@ -55,12 +55,12 @@ fn f8<X: ?Sized>(x1: &S<X>, x2: &S<X>) { // Test some tuples. fn f9<X: ?Sized>(x1: Box<S<X>>, x2: Box<E<X>>) { - f5(&(*x1, 34i)); + f5(&(*x1, 34is)); //~^ ERROR the trait `core::marker::Sized` is not implemented } fn f10<X: ?Sized>(x1: Box<S<X>>, x2: Box<E<X>>) { - f5(&(32i, *x2)); + f5(&(32is, *x2)); //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/unsized5.rs b/src/test/compile-fail/unsized5.rs index 026d496aa43..dc10f795cd4 100644 --- a/src/test/compile-fail/unsized5.rs +++ b/src/test/compile-fail/unsized5.rs @@ -12,26 +12,26 @@ struct S1<X: ?Sized> { f1: X, //~ ERROR `core::marker::Sized` is not implemented - f2: int, + f2: isize, } struct S2<X: ?Sized> { - f: int, + f: isize, g: X, //~ ERROR `core::marker::Sized` is not implemented - h: int, + h: isize, } struct S3 { f: str, //~ ERROR `core::marker::Sized` is not implemented - g: [uint] + g: [usize] } struct S4 { f: str, //~ ERROR `core::marker::Sized` is not implemented - g: uint + g: usize } enum E<X: ?Sized> { - V1(X, int), //~ERROR `core::marker::Sized` is not implemented + V1(X, isize), //~ERROR `core::marker::Sized` is not implemented } enum F<X: ?Sized> { - V2{f1: X, f: int}, //~ERROR `core::marker::Sized` is not implemented + V2{f1: X, f: isize}, //~ERROR `core::marker::Sized` is not implemented } pub fn main() { diff --git a/src/test/compile-fail/unsized6.rs b/src/test/compile-fail/unsized6.rs index 02f3404b72b..21953d1bb09 100644 --- a/src/test/compile-fail/unsized6.rs +++ b/src/test/compile-fail/unsized6.rs @@ -15,24 +15,24 @@ trait T {} fn f1<X: ?Sized>(x: &X) { let _: X; // <-- this is OK, no bindings created, no initializer. - let _: (int, (X, int)); // same + let _: (isize, (X, isize)); // same let y: X; //~ERROR the trait `core::marker::Sized` is not implemented - let y: (int, (X, int)); //~ERROR the trait `core::marker::Sized` is not implemented + let y: (isize, (X, isize)); //~ERROR the trait `core::marker::Sized` is not implemented } fn f2<X: ?Sized + T>(x: &X) { let y: X; //~ERROR the trait `core::marker::Sized` is not implemented - let y: (int, (X, int)); //~ERROR the trait `core::marker::Sized` is not implemented + let y: (isize, (X, isize)); //~ERROR the trait `core::marker::Sized` is not implemented } fn f3<X: ?Sized>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { let y: X = *x1; //~ERROR the trait `core::marker::Sized` is not implemented let y = *x2; //~ERROR the trait `core::marker::Sized` is not implemented - let (y, z) = (*x3, 4i); //~ERROR the trait `core::marker::Sized` is not implemented + let (y, z) = (*x3, 4is); //~ERROR the trait `core::marker::Sized` is not implemented } fn f4<X: ?Sized + T>(x1: Box<X>, x2: Box<X>, x3: Box<X>) { let y: X = *x1; //~ERROR the trait `core::marker::Sized` is not implemented let y = *x2; //~ERROR the trait `core::marker::Sized` is not implemented - let (y, z) = (*x3, 4i); //~ERROR the trait `core::marker::Sized` is not implemented + let (y, z) = (*x3, 4is); //~ERROR the trait `core::marker::Sized` is not implemented } fn g1<X: ?Sized>(x: X) {} //~ERROR the trait `core::marker::Sized` is not implemented diff --git a/src/test/compile-fail/unused-attr.rs b/src/test/compile-fail/unused-attr.rs index 786421c4ef9..635ceec73a3 100644 --- a/src/test/compile-fail/unused-attr.rs +++ b/src/test/compile-fail/unused-attr.rs @@ -44,7 +44,7 @@ fn bar(f: foo::Foo) { #[foo] //~ ERROR unused attribute struct Foo { #[foo] //~ ERROR unused attribute - a: int + a: isize } #[foo] //~ ERROR unused attribute diff --git a/src/test/compile-fail/unused-mut-warning-captured-var.rs b/src/test/compile-fail/unused-mut-warning-captured-var.rs index 2c000e03ce4..aa5adb6a6b0 100644 --- a/src/test/compile-fail/unused-mut-warning-captured-var.rs +++ b/src/test/compile-fail/unused-mut-warning-captured-var.rs @@ -11,7 +11,7 @@ #![forbid(unused_mut)] fn main() { - let mut x = 1i; + let mut x = 1is; //~^ ERROR: variable does not need to be mutable move|:| { println!("{}", x); }; } diff --git a/src/test/compile-fail/unused-result.rs b/src/test/compile-fail/unused-result.rs index 1263d7c5710..6ed3b081c97 100644 --- a/src/test/compile-fail/unused-result.rs +++ b/src/test/compile-fail/unused-result.rs @@ -19,30 +19,30 @@ enum MustUseMsg { Test2 } fn foo<T>() -> T { panic!() } -fn bar() -> int { return foo::<int>(); } +fn bar() -> isize { return foo::<isize>(); } fn baz() -> MustUse { return foo::<MustUse>(); } fn qux() -> MustUseMsg { return foo::<MustUseMsg>(); } #[allow(unused_results)] fn test() { - foo::<int>(); + foo::<isize>(); foo::<MustUse>(); //~ ERROR: unused result which must be used foo::<MustUseMsg>(); //~ ERROR: unused result which must be used: some message } #[allow(unused_results, unused_must_use)] fn test2() { - foo::<int>(); + foo::<isize>(); foo::<MustUse>(); foo::<MustUseMsg>(); } fn main() { - foo::<int>(); //~ ERROR: unused result + foo::<isize>(); //~ ERROR: unused result foo::<MustUse>(); //~ ERROR: unused result which must be used foo::<MustUseMsg>(); //~ ERROR: unused result which must be used: some message - let _ = foo::<int>(); + let _ = foo::<isize>(); let _ = foo::<MustUse>(); let _ = foo::<MustUseMsg>(); } diff --git a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs index 364bfc42985..d8a82d8fbf0 100644 --- a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs +++ b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs @@ -10,6 +10,8 @@ // ignore-tidy-linelength +#![feature(box_syntax)] + use std::fmt; struct Number { diff --git a/src/test/compile-fail/use-after-move-self-based-on-type.rs b/src/test/compile-fail/use-after-move-self-based-on-type.rs index a1b7f83da2f..810fc68a0f4 100644 --- a/src/test/compile-fail/use-after-move-self-based-on-type.rs +++ b/src/test/compile-fail/use-after-move-self-based-on-type.rs @@ -9,7 +9,7 @@ // except according to those terms. struct S { - x: int, + x: isize, } impl Drop for S { @@ -17,7 +17,7 @@ impl Drop for S { } impl S { - pub fn foo(self) -> int { + pub fn foo(self) -> isize { self.bar(); return self.x; //~ ERROR use of moved value: `self.x` } diff --git a/src/test/compile-fail/use-after-move-self.rs b/src/test/compile-fail/use-after-move-self.rs index 607d6163208..e9ffb26aba5 100644 --- a/src/test/compile-fail/use-after-move-self.rs +++ b/src/test/compile-fail/use-after-move-self.rs @@ -8,13 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] struct S { - x: Box<int>, + x: Box<isize>, } impl S { - pub fn foo(self) -> int { + pub fn foo(self) -> isize { self.bar(); return *self.x; //~ ERROR use of moved value: `*self.x` } diff --git a/src/test/compile-fail/use-mod-3.rs b/src/test/compile-fail/use-mod-3.rs index 040674fd6d9..bd954272fcc 100644 --- a/src/test/compile-fail/use-mod-3.rs +++ b/src/test/compile-fail/use-mod-3.rs @@ -17,7 +17,7 @@ use foo::bar::{ }; mod foo { - mod bar { pub type Bar = int; } + mod bar { pub type Bar = isize; } } fn main() {} diff --git a/src/test/compile-fail/useless-priv.rs b/src/test/compile-fail/useless-priv.rs index bb39107463e..d8531f4543d 100644 --- a/src/test/compile-fail/useless-priv.rs +++ b/src/test/compile-fail/useless-priv.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct A { pub i: int } +struct A { pub i: isize } pub enum C { pub Variant } //~ ERROR: unnecessary `pub` pub trait E { diff --git a/src/test/compile-fail/utf8_idents.rs b/src/test/compile-fail/utf8_idents.rs index 9bd14305b9a..a5471e87f22 100644 --- a/src/test/compile-fail/utf8_idents.rs +++ b/src/test/compile-fail/utf8_idents.rs @@ -16,7 +16,7 @@ fn foo< >() {} struct X { - δ: uint //~ ERROR non-ascii idents are not fully supported + δ: usize //~ ERROR non-ascii idents are not fully supported } pub fn main() { diff --git a/src/test/compile-fail/variadic-ffi-1.rs b/src/test/compile-fail/variadic-ffi-1.rs index 93f702d8052..34846ab496d 100644 --- a/src/test/compile-fail/variadic-ffi-1.rs +++ b/src/test/compile-fail/variadic-ffi-1.rs @@ -10,7 +10,7 @@ extern { fn printf(...); //~ ERROR: variadic function must be declared with at least one named argument - fn printf(..., foo: int); //~ ERROR: `...` must be last in argument list for variadic function + fn printf(..., foo: isize); //~ ERROR: `...` must be last in argument list for variadic function } fn main() {} diff --git a/src/test/compile-fail/variadic-ffi-2.rs b/src/test/compile-fail/variadic-ffi-2.rs index 9e2b015f33d..1d519c978a3 100644 --- a/src/test/compile-fail/variadic-ffi-2.rs +++ b/src/test/compile-fail/variadic-ffi-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn baz(f: extern "stdcall" fn(uint, ...)) { +fn baz(f: extern "stdcall" fn(usize, ...)) { //~^ ERROR: variadic function must have C calling convention f(22, 44); } diff --git a/src/test/compile-fail/variadic-ffi-3.rs b/src/test/compile-fail/variadic-ffi-3.rs index f143e715450..331a4523934 100644 --- a/src/test/compile-fail/variadic-ffi-3.rs +++ b/src/test/compile-fail/variadic-ffi-3.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn foo(x: int, ...) { +fn foo(x: isize, ...) { //~^ ERROR: only foreign functions are allowed to be variadic } diff --git a/src/test/compile-fail/variadic-ffi-4.rs b/src/test/compile-fail/variadic-ffi-4.rs index d4c54dfffe0..62e985f44f7 100644 --- a/src/test/compile-fail/variadic-ffi-4.rs +++ b/src/test/compile-fail/variadic-ffi-4.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern "C" fn foo(x: int, ...) { +extern "C" fn foo(x: isize, ...) { //~^ ERROR: only foreign functions are allowed to be variadic } diff --git a/src/test/compile-fail/variance-cell-is-invariant.rs b/src/test/compile-fail/variance-cell-is-invariant.rs index 0efca74f3ce..b8a8f9ad91c 100644 --- a/src/test/compile-fail/variance-cell-is-invariant.rs +++ b/src/test/compile-fail/variance-cell-is-invariant.rs @@ -14,12 +14,12 @@ use std::cell::Cell; struct Foo<'a> { - x: Cell<Option<&'a int>>, + x: Cell<Option<&'a isize>>, } fn use_<'short,'long>(c: Foo<'short>, - s: &'short int, - l: &'long int, + s: &'short isize, + l: &'long isize, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } diff --git a/src/test/compile-fail/variance-regions-direct.rs b/src/test/compile-fail/variance-regions-direct.rs index fa38482b21c..04389b67dba 100644 --- a/src/test/compile-fail/variance-regions-direct.rs +++ b/src/test/compile-fail/variance-regions-direct.rs @@ -15,8 +15,8 @@ #[rustc_variance] struct Test2<'a, 'b, 'c> { //~ ERROR regions=[[-, -, -];[];[]] - x: &'a int, - y: &'b [int], + x: &'a isize, + y: &'b [isize], c: &'c str } @@ -24,8 +24,8 @@ struct Test2<'a, 'b, 'c> { //~ ERROR regions=[[-, -, -];[];[]] #[rustc_variance] struct Test3<'a, 'b, 'c> { //~ ERROR regions=[[+, +, +];[];[]] - x: extern "Rust" fn(&'a int), - y: extern "Rust" fn(&'b [int]), + x: extern "Rust" fn(&'a isize), + y: extern "Rust" fn(&'b [isize]), c: extern "Rust" fn(&'c str), } @@ -33,7 +33,7 @@ struct Test3<'a, 'b, 'c> { //~ ERROR regions=[[+, +, +];[];[]] #[rustc_variance] struct Test4<'a, 'b:'a> { //~ ERROR regions=[[-, o];[];[]] - x: &'a mut &'b int, + x: &'a mut &'b isize, } // Mutability induces invariance, even when in a @@ -41,32 +41,32 @@ struct Test4<'a, 'b:'a> { //~ ERROR regions=[[-, o];[];[]] #[rustc_variance] struct Test5<'a, 'b> { //~ ERROR regions=[[+, o];[];[]] - x: extern "Rust" fn(&'a mut &'b int), + x: extern "Rust" fn(&'a mut &'b isize), } // Invariance is a trap from which NO ONE CAN ESCAPE. -// In other words, even though the `&'b int` occurs in +// In other words, even though the `&'b isize` occurs in // a argument list (which is contravariant), that // argument list occurs in an invariant context. #[rustc_variance] struct Test6<'a, 'b> { //~ ERROR regions=[[-, o];[];[]] - x: &'a mut extern "Rust" fn(&'b int), + x: &'a mut extern "Rust" fn(&'b isize), } // No uses at all is bivariant: #[rustc_variance] struct Test7<'a> { //~ ERROR regions=[[*];[];[]] - x: int + x: isize } // Try enums too. #[rustc_variance] enum Test8<'a, 'b, 'c:'b> { //~ ERROR regions=[[+, -, o];[];[]] - Test8A(extern "Rust" fn(&'a int)), - Test8B(&'b [int]), + Test8A(extern "Rust" fn(&'a isize)), + Test8B(&'b [isize]), Test8C(&'b mut &'c str), } diff --git a/src/test/compile-fail/variance-regions-indirect.rs b/src/test/compile-fail/variance-regions-indirect.rs index c049fbc0fed..e2c7958b31d 100644 --- a/src/test/compile-fail/variance-regions-indirect.rs +++ b/src/test/compile-fail/variance-regions-indirect.rs @@ -14,8 +14,8 @@ #[rustc_variance] enum Base<'a, 'b, 'c:'b, 'd> { //~ ERROR regions=[[+, -, o, *];[];[]] - Test8A(extern "Rust" fn(&'a int)), - Test8B(&'b [int]), + Test8A(extern "Rust" fn(&'a isize)), + Test8B(&'b [isize]), Test8C(&'b mut &'c str), } diff --git a/src/test/compile-fail/variance-trait-matching.rs b/src/test/compile-fail/variance-trait-matching.rs index 1644705222f..d4dab5f0ed0 100644 --- a/src/test/compile-fail/variance-trait-matching.rs +++ b/src/test/compile-fail/variance-trait-matching.rs @@ -11,18 +11,18 @@ // Issue #5781. Tests that subtyping is handled properly in trait matching. trait Make<'a> { - fn make(x: &'a mut int) -> Self; + fn make(x: &'a mut isize) -> Self; } -impl<'a> Make<'a> for &'a mut int { - fn make(x: &'a mut int) -> &'a mut int { +impl<'a> Make<'a> for &'a mut isize { + fn make(x: &'a mut isize) -> &'a mut isize { x } } -fn f() -> &'static mut int { +fn f() -> &'static mut isize { let mut x = 1; - let y: &'static mut int = Make::make(&mut x); //~ ERROR `x` does not live long enough + let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough y } diff --git a/src/test/compile-fail/vec-matching-obsolete-syntax.rs b/src/test/compile-fail/vec-matching-obsolete-syntax.rs index 6330aac2d8b..2715b31d196 100644 --- a/src/test/compile-fail/vec-matching-obsolete-syntax.rs +++ b/src/test/compile-fail/vec-matching-obsolete-syntax.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - let x = [1i, 2, 3]; + let x = [1is, 2, 3]; match x { [a, b, ..c] => { //~ ERROR obsolete syntax assert_eq!(a, 1); diff --git a/src/test/compile-fail/vec-mut-iter-borrow.rs b/src/test/compile-fail/vec-mut-iter-borrow.rs index c03956c42cb..59c490f2fff 100644 --- a/src/test/compile-fail/vec-mut-iter-borrow.rs +++ b/src/test/compile-fail/vec-mut-iter-borrow.rs @@ -9,9 +9,9 @@ // except according to those terms. fn main() { - let mut xs: Vec<int> = vec!(); + let mut xs: Vec<isize> = vec!(); for x in xs.iter_mut() { - xs.push(1i) //~ ERROR cannot borrow `xs` + xs.push(1is) //~ ERROR cannot borrow `xs` } } diff --git a/src/test/compile-fail/vec-res-add.rs b/src/test/compile-fail/vec-res-add.rs index dc166f9fd9d..97a684b2459 100644 --- a/src/test/compile-fail/vec-res-add.rs +++ b/src/test/compile-fail/vec-res-add.rs @@ -10,10 +10,10 @@ #[derive(Show)] struct r { - i:int + i:isize } -fn r(i:int) -> r { r { i: i } } +fn r(i:isize) -> r { r { i: i } } impl Drop for r { fn drop(&mut self) {} diff --git a/src/test/compile-fail/virtual-structs.rs b/src/test/compile-fail/virtual-structs.rs index 69125bab2ce..3b3c7d5a30f 100644 --- a/src/test/compile-fail/virtual-structs.rs +++ b/src/test/compile-fail/virtual-structs.rs @@ -12,7 +12,7 @@ #![feature(struct_inherit)] virtual struct SuperStruct { //~ ERROR `virtual` structs have been removed from the language - f1: int, + f1: isize, } struct Struct : SuperStruct; //~ ERROR `virtual` structs have been removed from the language diff --git a/src/test/compile-fail/vtable-res-trait-param.rs b/src/test/compile-fail/vtable-res-trait-param.rs index 12cfe9c20fa..bbe88379aa7 100644 --- a/src/test/compile-fail/vtable-res-trait-param.rs +++ b/src/test/compile-fail/vtable-res-trait-param.rs @@ -9,25 +9,25 @@ // except according to those terms. trait TraitA { - fn method_a(&self) -> int; + fn method_a(&self) -> isize; } trait TraitB { - fn gimme_an_a<A:TraitA>(&self, a: A) -> int; + fn gimme_an_a<A:TraitA>(&self, a: A) -> isize; } -impl TraitB for int { - fn gimme_an_a<A:TraitA>(&self, a: A) -> int { +impl TraitB for isize { + fn gimme_an_a<A:TraitA>(&self, a: A) -> isize { a.method_a() + *self } } -fn call_it<B:TraitB>(b: B) -> int { - let y = 4u; +fn call_it<B:TraitB>(b: B) -> isize { + let y = 4us; b.gimme_an_a(y) //~ ERROR the trait `TraitA` is not implemented } fn main() { - let x = 3i; + let x = 3is; assert_eq!(call_it(x), 22); } diff --git a/src/test/compile-fail/walk-struct-literal-with.rs b/src/test/compile-fail/walk-struct-literal-with.rs index bb3b310a68f..0f3754e09e4 100644 --- a/src/test/compile-fail/walk-struct-literal-with.rs +++ b/src/test/compile-fail/walk-struct-literal-with.rs @@ -10,7 +10,7 @@ struct Mine{ test: String, - other_val: int + other_val: isize } impl Mine{ diff --git a/src/test/compile-fail/warn-path-statement.rs b/src/test/compile-fail/warn-path-statement.rs index 8b6d160a6c5..304900df776 100644 --- a/src/test/compile-fail/warn-path-statement.rs +++ b/src/test/compile-fail/warn-path-statement.rs @@ -11,6 +11,6 @@ // compile-flags: -D path-statement fn main() { - let x = 10i; + let x = 10is; x; //~ ERROR path statement with no effect } diff --git a/src/test/compile-fail/where-clause-method-substituion.rs b/src/test/compile-fail/where-clause-method-substituion.rs index 40d2df45488..a5108f005dc 100644 --- a/src/test/compile-fail/where-clause-method-substituion.rs +++ b/src/test/compile-fail/where-clause-method-substituion.rs @@ -19,7 +19,7 @@ struct X; // Remove this impl causing the below resolution to fail // impl Foo<S> for X {} -impl Bar<X> for int { +impl Bar<X> for isize { fn method<U>(&self) where X: Foo<U> { } } diff --git a/src/test/compile-fail/where-clauses-not-parameter.rs b/src/test/compile-fail/where-clauses-not-parameter.rs index 148473f8987..5573464c5ab 100644 --- a/src/test/compile-fail/where-clauses-not-parameter.rs +++ b/src/test/compile-fail/where-clauses-not-parameter.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn equal<T>(_: &T, _: &T) -> bool where int : Eq { +fn equal<T>(_: &T, _: &T) -> bool where isize : Eq { true //~^ ERROR cannot bound type `isize`, where clause bounds may only be attached } @@ -16,28 +16,30 @@ fn equal<T>(_: &T, _: &T) -> bool where int : Eq { fn test<T: Eq>() -> bool where Option<T> : Eq {} // This should be rejected as well. -fn test2() -> bool where Option<int> : Eq {} -//~^ ERROR cannot bound type `core::option::Option<isize>`, where clause bounds +fn test2() -> bool where Option<isize> : Eq {} +//~^ ERROR cannot bound type `core::option::Option<isize>`, where clause bounds may #[derive(PartialEq)] //~^ ERROR cannot bound type `isize`, where clause bounds -enum Foo<T> where int : Eq { MkFoo } +enum Foo<T> where isize : Eq { MkFoo } //~^ ERROR cannot bound type `isize`, where clause bounds fn test3<T: Eq>() -> bool where Option<Foo<T>> : Eq {} -fn test4() -> bool where Option<Foo<int>> : Eq {} +fn test4() -> bool where Option<Foo<isize>> : Eq {} //~^ ERROR cannot bound type `core::option::Option<Foo<isize>>`, where clause bounds -trait Baz<T> where int : Eq { - fn baz() where String : Eq; +trait Baz<T> where isize : Eq { + //~^ ERROR cannot bound type `isize`, where clause bounds may only + fn baz() where String : Eq; //~ ERROR cannot bound type `collections::string::String` + //~^ ERROR cannot bound type `isize`, where clause } -impl Baz<int> for int where int : Eq { +impl Baz<isize> for isize where isize : Eq { //~^ ERROR cannot bound type `isize`, where clause bounds fn baz() where String : Eq {} } fn main() { - equal(&0i, &0i); + equal(&0is, &0is); } diff --git a/src/test/compile-fail/while-let.rs b/src/test/compile-fail/while-let.rs index adb8ee6940d..45e0d0aaeab 100644 --- a/src/test/compile-fail/while-let.rs +++ b/src/test/compile-fail/while-let.rs @@ -20,16 +20,16 @@ fn macros() { }} } - foo!(a, 1i, { //~ ERROR irrefutable while-let + foo!(a, 1is, { //~ ERROR irrefutable while-let println!("irrefutable pattern"); }); - bar!(a, 1i, { //~ ERROR irrefutable while-let + bar!(a, 1is, { //~ ERROR irrefutable while-let println!("irrefutable pattern"); }); } pub fn main() { - while let a = 1i { //~ ERROR irrefutable while-let + while let a = 1is { //~ ERROR irrefutable while-let println!("irrefutable pattern"); } } diff --git a/src/test/compile-fail/writing-to-immutable-vec.rs b/src/test/compile-fail/writing-to-immutable-vec.rs index 4e9f1545f3a..09c9439b464 100644 --- a/src/test/compile-fail/writing-to-immutable-vec.rs +++ b/src/test/compile-fail/writing-to-immutable-vec.rs @@ -10,6 +10,6 @@ fn main() { - let v: Vec<int> = vec!(1, 2, 3); + let v: Vec<isize> = vec!(1, 2, 3); v[1] = 4; //~ ERROR cannot borrow immutable local variable `v` as mutable } diff --git a/src/test/compile-fail/wrong-ret-type.rs b/src/test/compile-fail/wrong-ret-type.rs index ba3f3df7990..6db11fcffd2 100644 --- a/src/test/compile-fail/wrong-ret-type.rs +++ b/src/test/compile-fail/wrong-ret-type.rs @@ -9,5 +9,5 @@ // except according to those terms. // error-pattern: mismatched types -fn mk_int() -> uint { let i: int = 3; return i; } +fn mk_int() -> usize { let i: isize = 3; return i; } fn main() { } diff --git a/src/test/debuginfo/borrowed-struct.rs b/src/test/debuginfo/borrowed-struct.rs index e3cf438be43..53d2befc49d 100644 --- a/src/test/debuginfo/borrowed-struct.rs +++ b/src/test/debuginfo/borrowed-struct.rs @@ -64,6 +64,7 @@ // lldb-check:[...]$6 = 26.5 #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct SomeStruct { diff --git a/src/test/debuginfo/borrowed-tuple.rs b/src/test/debuginfo/borrowed-tuple.rs index ce0930f2fbf..c7e5987fbcf 100644 --- a/src/test/debuginfo/borrowed-tuple.rs +++ b/src/test/debuginfo/borrowed-tuple.rs @@ -42,6 +42,7 @@ #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] fn main() { diff --git a/src/test/debuginfo/borrowed-unique-basic.rs b/src/test/debuginfo/borrowed-unique-basic.rs index d152775a8ed..fc186a0b5b2 100644 --- a/src/test/debuginfo/borrowed-unique-basic.rs +++ b/src/test/debuginfo/borrowed-unique-basic.rs @@ -112,6 +112,7 @@ // lldb-check:[...]$12 = 3.5 #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] fn main() { diff --git a/src/test/debuginfo/box.rs b/src/test/debuginfo/box.rs index 5a70eb19041..0439e3dc34d 100644 --- a/src/test/debuginfo/box.rs +++ b/src/test/debuginfo/box.rs @@ -32,6 +32,7 @@ // lldb-check:[...]$1 = (2, 3.5) #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] fn main() { diff --git a/src/test/debuginfo/boxed-struct.rs b/src/test/debuginfo/boxed-struct.rs index f9d762bf99d..6397efa0a96 100644 --- a/src/test/debuginfo/boxed-struct.rs +++ b/src/test/debuginfo/boxed-struct.rs @@ -35,6 +35,7 @@ // lldb-check:[...]$1 = StructWithDestructor { x: 77, y: 777, z: 7777, w: 77777 } #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct StructWithSomePadding { diff --git a/src/test/debuginfo/closure-in-generic-function.rs b/src/test/debuginfo/closure-in-generic-function.rs index e3cb190c3f2..f8b12569400 100644 --- a/src/test/debuginfo/closure-in-generic-function.rs +++ b/src/test/debuginfo/closure-in-generic-function.rs @@ -46,6 +46,7 @@ // lldb-check:[...]$3 = 110 // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) { diff --git a/src/test/debuginfo/destructured-fn-argument.rs b/src/test/debuginfo/destructured-fn-argument.rs index b4688e4928a..73289c56bef 100644 --- a/src/test/debuginfo/destructured-fn-argument.rs +++ b/src/test/debuginfo/destructured-fn-argument.rs @@ -311,6 +311,7 @@ // lldb-command:continue #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] use self::Univariant::Unit; diff --git a/src/test/debuginfo/destructured-for-loop-variable.rs b/src/test/debuginfo/destructured-for-loop-variable.rs index 364720d0e4f..103bdc03550 100644 --- a/src/test/debuginfo/destructured-for-loop-variable.rs +++ b/src/test/debuginfo/destructured-for-loop-variable.rs @@ -153,6 +153,7 @@ // lldb-command:continue #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/destructured-local.rs b/src/test/debuginfo/destructured-local.rs index d5a6b36f1fc..1fd598e18c1 100644 --- a/src/test/debuginfo/destructured-local.rs +++ b/src/test/debuginfo/destructured-local.rs @@ -244,6 +244,7 @@ #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] use self::Univariant::Unit; diff --git a/src/test/debuginfo/generic-method-on-generic-struct.rs b/src/test/debuginfo/generic-method-on-generic-struct.rs index 0e358499a3d..66cd73622ff 100644 --- a/src/test/debuginfo/generic-method-on-generic-struct.rs +++ b/src/test/debuginfo/generic-method-on-generic-struct.rs @@ -112,6 +112,7 @@ // lldb-check:[...]$14 = -10.5 // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct<T> { diff --git a/src/test/debuginfo/method-on-enum.rs b/src/test/debuginfo/method-on-enum.rs index b1ebb124d4e..732e1d5c500 100644 --- a/src/test/debuginfo/method-on-enum.rs +++ b/src/test/debuginfo/method-on-enum.rs @@ -113,6 +113,7 @@ // lldb-check:[...]$14 = -10 // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] enum Enum { diff --git a/src/test/debuginfo/method-on-generic-struct.rs b/src/test/debuginfo/method-on-generic-struct.rs index 68a6ac8c1f3..c1785951e23 100644 --- a/src/test/debuginfo/method-on-generic-struct.rs +++ b/src/test/debuginfo/method-on-generic-struct.rs @@ -113,6 +113,7 @@ // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct<T> { diff --git a/src/test/debuginfo/method-on-struct.rs b/src/test/debuginfo/method-on-struct.rs index 84e74d4364c..d88a32b8475 100644 --- a/src/test/debuginfo/method-on-struct.rs +++ b/src/test/debuginfo/method-on-struct.rs @@ -113,6 +113,7 @@ // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/method-on-trait.rs b/src/test/debuginfo/method-on-trait.rs index f53bb11eac4..5622d17225b 100644 --- a/src/test/debuginfo/method-on-trait.rs +++ b/src/test/debuginfo/method-on-trait.rs @@ -113,6 +113,7 @@ // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/method-on-tuple-struct.rs b/src/test/debuginfo/method-on-tuple-struct.rs index 6994c38818c..02f7808221a 100644 --- a/src/test/debuginfo/method-on-tuple-struct.rs +++ b/src/test/debuginfo/method-on-tuple-struct.rs @@ -113,6 +113,7 @@ // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct TupleStruct(int, f64); diff --git a/src/test/debuginfo/recursive-struct.rs b/src/test/debuginfo/recursive-struct.rs index 90c32ad8da1..2cbe9f43789 100644 --- a/src/test/debuginfo/recursive-struct.rs +++ b/src/test/debuginfo/recursive-struct.rs @@ -69,6 +69,7 @@ // gdb-command:continue #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] use self::Opt::{Empty, Val}; diff --git a/src/test/debuginfo/self-in-default-method.rs b/src/test/debuginfo/self-in-default-method.rs index 87884d2f956..a1074e490f7 100644 --- a/src/test/debuginfo/self-in-default-method.rs +++ b/src/test/debuginfo/self-in-default-method.rs @@ -112,6 +112,7 @@ // lldb-check:[...]$14 = -10 // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/self-in-generic-default-method.rs b/src/test/debuginfo/self-in-generic-default-method.rs index 62b5e6872ee..f0da6e26870 100644 --- a/src/test/debuginfo/self-in-generic-default-method.rs +++ b/src/test/debuginfo/self-in-generic-default-method.rs @@ -112,6 +112,7 @@ // lldb-check:[...]$14 = -10.5 // lldb-command:continue +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/simd.rs b/src/test/debuginfo/simd.rs index 288e7461dd5..4aaa3e0b75f 100644 --- a/src/test/debuginfo/simd.rs +++ b/src/test/debuginfo/simd.rs @@ -41,7 +41,7 @@ // gdb-command:continue -#![allow(experimental)] +#![allow(unstable)] #![allow(unused_variables)] #![omit_gdb_pretty_printer_section] diff --git a/src/test/debuginfo/trait-pointers.rs b/src/test/debuginfo/trait-pointers.rs index 9f8c0aa06e6..b95190f875a 100644 --- a/src/test/debuginfo/trait-pointers.rs +++ b/src/test/debuginfo/trait-pointers.rs @@ -16,6 +16,7 @@ // lldb-command:run #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] trait Trait { diff --git a/src/test/debuginfo/type-names.rs b/src/test/debuginfo/type-names.rs index b508da73f4a..156e5f12ad5 100644 --- a/src/test/debuginfo/type-names.rs +++ b/src/test/debuginfo/type-names.rs @@ -173,6 +173,7 @@ // gdb-command:whatis closure2 // gdb-check:type = struct (closure, usize) +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] use self::Enum1::{Variant1_1, Variant1_2}; diff --git a/src/test/debuginfo/unique-enum.rs b/src/test/debuginfo/unique-enum.rs index 3d028eb1077..08622b2dca8 100644 --- a/src/test/debuginfo/unique-enum.rs +++ b/src/test/debuginfo/unique-enum.rs @@ -42,6 +42,7 @@ // lldb-check:[...]$2 = TheOnlyCase(123234) #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] // The first element is to ensure proper alignment, irrespective of the machines word size. Since diff --git a/src/test/debuginfo/var-captured-in-nested-closure.rs b/src/test/debuginfo/var-captured-in-nested-closure.rs index 3a7fbb9a3a1..d7831c983c0 100644 --- a/src/test/debuginfo/var-captured-in-nested-closure.rs +++ b/src/test/debuginfo/var-captured-in-nested-closure.rs @@ -79,6 +79,7 @@ // lldb-command:continue #![allow(unused_variables)] +#![feature(box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/var-captured-in-sendable-closure.rs b/src/test/debuginfo/var-captured-in-sendable-closure.rs index b34749260f3..30a07ea46dd 100644 --- a/src/test/debuginfo/var-captured-in-sendable-closure.rs +++ b/src/test/debuginfo/var-captured-in-sendable-closure.rs @@ -41,7 +41,7 @@ // lldb-check:[...]$2 = 5 #![allow(unused_variables)] -#![feature(unboxed_closures)] +#![feature(unboxed_closures, box_syntax)] #![omit_gdb_pretty_printer_section] struct Struct { diff --git a/src/test/debuginfo/var-captured-in-stack-closure.rs b/src/test/debuginfo/var-captured-in-stack-closure.rs index a743adae51e..9daf6abba11 100644 --- a/src/test/debuginfo/var-captured-in-stack-closure.rs +++ b/src/test/debuginfo/var-captured-in-stack-closure.rs @@ -70,7 +70,7 @@ // lldb-command:print *owned // lldb-check:[...]$9 = 6 -#![feature(unboxed_closures)] +#![feature(unboxed_closures, box_syntax)] #![allow(unused_variables)] #![omit_gdb_pretty_printer_section] diff --git a/src/test/debuginfo/vec-slices.rs b/src/test/debuginfo/vec-slices.rs index 14f1dbb9d65..949dffaac06 100644 --- a/src/test/debuginfo/vec-slices.rs +++ b/src/test/debuginfo/vec-slices.rs @@ -77,7 +77,6 @@ // lldb-check:[...]$5 = &[AStruct { x: 10, y: 11, z: 12 }, AStruct { x: 13, y: 14, z: 15 }] #![allow(unused_variables)] -#![feature(slicing_syntax)] #![omit_gdb_pretty_printer_section] struct AStruct { diff --git a/src/test/pretty/issue-4264.pp b/src/test/pretty/issue-4264.pp index f20087ef677..dac6e628d10 100644 --- a/src/test/pretty/issue-4264.pp +++ b/src/test/pretty/issue-4264.pp @@ -1,5 +1,4 @@ #![no_std] -#![feature(globs)] #[macro_use] extern crate "std" as std; #[prelude_import] diff --git a/src/test/pretty/path-type-bounds.rs b/src/test/pretty/path-type-bounds.rs index f575fb32924..382394b1407 100644 --- a/src/test/pretty/path-type-bounds.rs +++ b/src/test/pretty/path-type-bounds.rs @@ -19,6 +19,6 @@ fn foo<'a>(x: Box<Tr+ Sync + 'a>) -> Box<Tr+ Sync + 'a> { x } fn main() { let x: Box<Tr+ Sync>; - box() 1i as Box<Tr+ Sync>; + Box::new(1i) as Box<Tr+ Sync>; } diff --git a/src/test/run-fail/args-panic.rs b/src/test/run-fail/args-panic.rs index 4878ec59fd4..eab7475bc86 100644 --- a/src/test/run-fail/args-panic.rs +++ b/src/test/run-fail/args-panic.rs @@ -11,6 +11,9 @@ // error-pattern:meep +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f(_a: int, _b: int, _c: Box<int>) { panic!("moop"); } fn main() { f(1, panic!("meep"), box 42); } diff --git a/src/test/run-fail/panic-macro-any-wrapped.rs b/src/test/run-fail/panic-macro-any-wrapped.rs index e25390a7986..89e47bf46ab 100644 --- a/src/test/run-fail/panic-macro-any-wrapped.rs +++ b/src/test/run-fail/panic-macro-any-wrapped.rs @@ -10,6 +10,9 @@ // error-pattern:panicked at 'Box<Any>' +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { panic!(box 612_i64); } diff --git a/src/test/run-fail/panic-macro-any.rs b/src/test/run-fail/panic-macro-any.rs index b73c66c4f21..231c57390b3 100644 --- a/src/test/run-fail/panic-macro-any.rs +++ b/src/test/run-fail/panic-macro-any.rs @@ -10,6 +10,9 @@ // error-pattern:panicked at 'Box<Any>' +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { panic!(box 413i as Box<::std::any::Any+Send>); } diff --git a/src/test/run-fail/unique-panic.rs b/src/test/run-fail/unique-panic.rs index 07c9a21c5c1..9f643c09795 100644 --- a/src/test/run-fail/unique-panic.rs +++ b/src/test/run-fail/unique-panic.rs @@ -9,4 +9,8 @@ // except according to those terms. // error-pattern: panic + +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { box panic!(); } diff --git a/src/test/run-fail/unwind-unique.rs b/src/test/run-fail/unwind-unique.rs index 6b5aefbab80..f39ded8f98e 100644 --- a/src/test/run-fail/unwind-unique.rs +++ b/src/test/run-fail/unwind-unique.rs @@ -10,6 +10,8 @@ // error-pattern:fail +#![allow(unknown_features)] +#![feature(box_syntax)] fn failfn() { panic!(); diff --git a/src/test/run-make/graphviz-flowgraph/f01.rs b/src/test/run-make/graphviz-flowgraph/f01.rs index f1f1a1d5472..27b19807865 100644 --- a/src/test/run-make/graphviz-flowgraph/f01.rs +++ b/src/test/run-make/graphviz-flowgraph/f01.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn lit_1() { - 1i; + 1is; } diff --git a/src/test/run-make/graphviz-flowgraph/f02.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f02.dot-expected.dot index 230dcbaeb98..1f4a58ba0a3 100644 --- a/src/test/run-make/graphviz-flowgraph/f02.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f02.dot-expected.dot @@ -2,8 +2,8 @@ digraph block { N0[label="entry"]; N1[label="exit"]; N2[label="local _x"]; - N3[label="stmt let _x: int;"]; - N4[label="block { let _x: int; }"]; + N3[label="stmt let _x: isize;"]; + N4[label="block { let _x: isize; }"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f02.rs b/src/test/run-make/graphviz-flowgraph/f02.rs index 3cdd73a49e1..f7fe1266198 100644 --- a/src/test/run-make/graphviz-flowgraph/f02.rs +++ b/src/test/run-make/graphviz-flowgraph/f02.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn decl_x_2() { - let _x : int; + let _x : isize; } diff --git a/src/test/run-make/graphviz-flowgraph/f03.rs b/src/test/run-make/graphviz-flowgraph/f03.rs index 051409a49b1..c95dbcbb31c 100644 --- a/src/test/run-make/graphviz-flowgraph/f03.rs +++ b/src/test/run-make/graphviz-flowgraph/f03.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn expr_add_3() { - 3i + 4; + 3is + 4; } diff --git a/src/test/run-make/graphviz-flowgraph/f04.rs b/src/test/run-make/graphviz-flowgraph/f04.rs index ed2f7e25dae..552cb24c750 100644 --- a/src/test/run-make/graphviz-flowgraph/f04.rs +++ b/src/test/run-make/graphviz-flowgraph/f04.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn pat_id_4() { - let _x = 4i; + let _x = 4is; } diff --git a/src/test/run-make/graphviz-flowgraph/f05.rs b/src/test/run-make/graphviz-flowgraph/f05.rs index b2591bdd08a..09a45c9bd21 100644 --- a/src/test/run-make/graphviz-flowgraph/f05.rs +++ b/src/test/run-make/graphviz-flowgraph/f05.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn pat_tup_5() { - let (_x, _y) = (5i, 55i); + let (_x, _y) = (5is, 55is); } diff --git a/src/test/run-make/graphviz-flowgraph/f06.rs b/src/test/run-make/graphviz-flowgraph/f06.rs index c914409629c..538ef2af898 100644 --- a/src/test/run-make/graphviz-flowgraph/f06.rs +++ b/src/test/run-make/graphviz-flowgraph/f06.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -struct S6 { val: int } +struct S6 { val: isize } pub fn pat_struct_6() { let S6 { val: _x } = S6{ val: 6 }; } diff --git a/src/test/run-make/graphviz-flowgraph/f07.rs b/src/test/run-make/graphviz-flowgraph/f07.rs index fb3f2d24cdd..8334f81c080 100644 --- a/src/test/run-make/graphviz-flowgraph/f07.rs +++ b/src/test/run-make/graphviz-flowgraph/f07.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn pat_vec_7() { - match [7i, 77i, 777i, 7777i] { + match [7is, 77is, 777is, 7777is] { [x, y, ..] => x + y }; } diff --git a/src/test/run-make/graphviz-flowgraph/f08.rs b/src/test/run-make/graphviz-flowgraph/f08.rs index 5d166e5ffcd..ad96f30073b 100644 --- a/src/test/run-make/graphviz-flowgraph/f08.rs +++ b/src/test/run-make/graphviz-flowgraph/f08.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn expr_if_onearm_8() { - let x = 8i; let _y; - if x > 88i { - _y = 888i; + let x = 8is; let _y; + if x > 88is { + _y = 888is; } } diff --git a/src/test/run-make/graphviz-flowgraph/f10.rs b/src/test/run-make/graphviz-flowgraph/f10.rs index af263f0cf10..456f740d468 100644 --- a/src/test/run-make/graphviz-flowgraph/f10.rs +++ b/src/test/run-make/graphviz-flowgraph/f10.rs @@ -9,8 +9,8 @@ // except according to those terms. pub fn expr_while_10() { - let mut x = 10i; - while x > 0i { - x -= 1i; + let mut x = 10is; + while x > 0is { + x -= 1is; } } diff --git a/src/test/run-make/graphviz-flowgraph/f11.rs b/src/test/run-make/graphviz-flowgraph/f11.rs index 95260c608ec..65262f249bc 100644 --- a/src/test/run-make/graphviz-flowgraph/f11.rs +++ b/src/test/run-make/graphviz-flowgraph/f11.rs @@ -10,9 +10,9 @@ #[allow(unreachable_code)] pub fn expr_loop_11() { - let mut _x = 11i; + let mut _x = 11is; loop { - _x -= 1i; + _x -= 1is; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f12.rs b/src/test/run-make/graphviz-flowgraph/f12.rs index 625dd8cb03e..5651d73baff 100644 --- a/src/test/run-make/graphviz-flowgraph/f12.rs +++ b/src/test/run-make/graphviz-flowgraph/f12.rs @@ -10,9 +10,9 @@ #[allow(unreachable_code)] pub fn expr_loop_12() { - let mut x = 12i; + let mut x = 12is; loop { - x -= 1i; - if x == 2i { break; "unreachable"; } + x -= 1is; + if x == 2is { break; "unreachable"; } } } diff --git a/src/test/run-make/graphviz-flowgraph/f13.rs b/src/test/run-make/graphviz-flowgraph/f13.rs index fdda50b4312..babb283c734 100644 --- a/src/test/run-make/graphviz-flowgraph/f13.rs +++ b/src/test/run-make/graphviz-flowgraph/f13.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -enum E13 { E13a, E13b(int) } +enum E13 { E13a, E13b(isize) } pub fn expr_match_13() { let x = E13::E13b(13); let _y; match x { diff --git a/src/test/run-make/graphviz-flowgraph/f14.rs b/src/test/run-make/graphviz-flowgraph/f14.rs index 72616f31594..adb7b193d16 100644 --- a/src/test/run-make/graphviz-flowgraph/f14.rs +++ b/src/test/run-make/graphviz-flowgraph/f14.rs @@ -10,8 +10,8 @@ #[allow(unreachable_code)] pub fn expr_ret_14() { - let x = 14i; - if x > 1i { + let x = 14is; + if x > 1is { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f15.rs b/src/test/run-make/graphviz-flowgraph/f15.rs index 62233dcb7d8..a1141eb6768 100644 --- a/src/test/run-make/graphviz-flowgraph/f15.rs +++ b/src/test/run-make/graphviz-flowgraph/f15.rs @@ -10,21 +10,21 @@ #[allow(unreachable_code)] pub fn expr_break_label_15() { - let mut x = 15i; - let mut y = 151i; + let mut x = 15is; + let mut y = 151is; 'outer: loop { 'inner: loop { - if x == 1i { + if x == 1is { break 'outer; "unreachable"; } - if y >= 2i { + if y >= 2is { break; "unreachable"; } - y -= 3i; + y -= 3is; } - y -= 4i; - x -= 5i; + y -= 4is; + x -= 5is; } } diff --git a/src/test/run-make/graphviz-flowgraph/f16.rs b/src/test/run-make/graphviz-flowgraph/f16.rs index 2683d8bd06b..5d0e9f963a0 100644 --- a/src/test/run-make/graphviz-flowgraph/f16.rs +++ b/src/test/run-make/graphviz-flowgraph/f16.rs @@ -10,22 +10,22 @@ #[allow(unreachable_code)] pub fn expr_continue_label_16() { - let mut x = 16i; - let mut y = 16i; + let mut x = 16is; + let mut y = 16is; 'outer: loop { 'inner: loop { - if x == 1i { + if x == 1is { continue 'outer; "unreachable"; } - if y >= 1i { + if y >= 1is { break; "unreachable"; } - y -= 1i; + y -= 1is; } - y -= 1i; - x -= 1i; + y -= 1is; + x -= 1is; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f17.rs b/src/test/run-make/graphviz-flowgraph/f17.rs index 23ce212c0af..de9b3bd5676 100644 --- a/src/test/run-make/graphviz-flowgraph/f17.rs +++ b/src/test/run-make/graphviz-flowgraph/f17.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn expr_vec_17() { - let _v = [1i, 7i, 17i]; + let _v = [1is, 7is, 17is]; } diff --git a/src/test/run-make/graphviz-flowgraph/f18.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f18.dot-expected.dot index c4a39a519ed..78120e9009e 100644 --- a/src/test/run-make/graphviz-flowgraph/f18.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f18.dot-expected.dot @@ -1,14 +1,14 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="stmt fn inner(x: int) -> int { x + x }"]; + N2[label="stmt fn inner(x: isize) -> isize { x + x }"]; N3[label="expr inner"]; N4[label="expr inner"]; N5[label="expr 18"]; N6[label="expr inner(18)"]; N7[label="expr inner(inner(18))"]; N8[label="stmt inner(inner(18));"]; - N9[label="block {\l fn inner(x: int) -> int { x + x }\l inner(inner(18));\l}\l"]; + N9[label="block {\l fn inner(x: isize) -> isize { x + x }\l inner(inner(18));\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f18.rs b/src/test/run-make/graphviz-flowgraph/f18.rs index 0ace542b8f5..cbf8aa5db43 100644 --- a/src/test/run-make/graphviz-flowgraph/f18.rs +++ b/src/test/run-make/graphviz-flowgraph/f18.rs @@ -9,6 +9,6 @@ // except according to those terms. pub fn expr_call_18() { - fn inner(x:int) -> int { x + x } + fn inner(x:isize) -> isize { x + x } inner(inner(18)); } diff --git a/src/test/run-make/graphviz-flowgraph/f19.dot-expected.dot b/src/test/run-make/graphviz-flowgraph/f19.dot-expected.dot index 8d21ef80917..4752eac3e28 100644 --- a/src/test/run-make/graphviz-flowgraph/f19.dot-expected.dot +++ b/src/test/run-make/graphviz-flowgraph/f19.dot-expected.dot @@ -1,7 +1,7 @@ digraph block { N0[label="entry"]; N1[label="exit"]; - N2[label="stmt struct S19 {\l x: int,\l}\l"]; + N2[label="stmt struct S19 {\l x: isize,\l}\l"]; N3[label="stmt impl S19 {\l fn inner(self) -> S19 { S19{x: self.x + self.x,} }\l}\l"]; N4[label="expr 19"]; N5[label="expr S19{x: 19,}"]; @@ -11,7 +11,7 @@ digraph block { N9[label="expr s.inner()"]; N10[label="expr s.inner().inner()"]; N11[label="stmt s.inner().inner();"]; - N12[label="block {\l struct S19 {\l x: int,\l }\l impl S19 {\l fn inner(self) -> S19 { S19{x: self.x + self.x,} }\l }\l let s = S19{x: 19,};\l s.inner().inner();\l}\l"]; + N12[label="block {\l struct S19 {\l x: isize,\l }\l impl S19 {\l fn inner(self) -> S19 { S19{x: self.x + self.x,} }\l }\l let s = S19{x: 19,};\l s.inner().inner();\l}\l"]; N0 -> N2; N2 -> N3; N3 -> N4; diff --git a/src/test/run-make/graphviz-flowgraph/f19.rs b/src/test/run-make/graphviz-flowgraph/f19.rs index 092f6890a15..78c15dd64ad 100644 --- a/src/test/run-make/graphviz-flowgraph/f19.rs +++ b/src/test/run-make/graphviz-flowgraph/f19.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn expr_method_call_19() { - struct S19 { x: int } + struct S19 { x: isize } impl S19 { fn inner(self) -> S19 { S19 { x: self.x + self.x } } } let s = S19 { x: 19 }; s.inner().inner(); diff --git a/src/test/run-make/graphviz-flowgraph/f20.rs b/src/test/run-make/graphviz-flowgraph/f20.rs index 7110ebe2b54..3ca55cb521b 100644 --- a/src/test/run-make/graphviz-flowgraph/f20.rs +++ b/src/test/run-make/graphviz-flowgraph/f20.rs @@ -9,6 +9,6 @@ // except according to those terms. pub fn expr_index_20() { - let v = [2u, 0u, 20u]; - v[20u]; + let v = [2us, 0us, 20us]; + v[20us]; } diff --git a/src/test/run-make/graphviz-flowgraph/f21.rs b/src/test/run-make/graphviz-flowgraph/f21.rs index bff2da25061..25e93f65110 100644 --- a/src/test/run-make/graphviz-flowgraph/f21.rs +++ b/src/test/run-make/graphviz-flowgraph/f21.rs @@ -10,20 +10,20 @@ #[allow(unreachable_code)] pub fn expr_break_label_21() { - let mut x = 15i; - let mut y = 151i; + let mut x = 15is; + let mut y = 151is; 'outer: loop { 'inner: loop { - if x == 1i { + if x == 1is { break 'outer; "unreachable"; } - if y >= 2i { + if y >= 2is { return; "unreachable"; } - y -= 3i; - x -= 5i; + y -= 3is; + x -= 5is; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f22.rs b/src/test/run-make/graphviz-flowgraph/f22.rs index a6e3d571deb..6de703a42f6 100644 --- a/src/test/run-make/graphviz-flowgraph/f22.rs +++ b/src/test/run-make/graphviz-flowgraph/f22.rs @@ -10,20 +10,20 @@ #[allow(unreachable_code)] pub fn expr_break_label_21() { - let mut x = 15i; - let mut y = 151i; + let mut x = 15is; + let mut y = 151is; 'outer: loop { 'inner: loop { - if x == 1i { + if x == 1is { continue 'outer; "unreachable"; } - if y >= 2i { + if y >= 2is { return; "unreachable"; } - x -= 1i; - y -= 3i; + x -= 1is; + y -= 3is; } "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f23.rs b/src/test/run-make/graphviz-flowgraph/f23.rs index 73bcc288ca7..6ffa1838903 100644 --- a/src/test/run-make/graphviz-flowgraph/f23.rs +++ b/src/test/run-make/graphviz-flowgraph/f23.rs @@ -10,19 +10,19 @@ #[allow(unreachable_code)] pub fn expr_while_23() { - let mut x = 23i; - let mut y = 23i; - let mut z = 23i; + let mut x = 23is; + let mut y = 23is; + let mut z = 23is; - while x > 0i { - x -= 1i; + while x > 0is { + x -= 1is; - while y > 0i { - y -= 1i; + while y > 0is { + y -= 1is; - while z > 0i { z -= 1i; } + while z > 0is { z -= 1is; } - if x > 10i { + if x > 10is { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f24.rs b/src/test/run-make/graphviz-flowgraph/f24.rs index afba1d202c9..ebaf7f28101 100644 --- a/src/test/run-make/graphviz-flowgraph/f24.rs +++ b/src/test/run-make/graphviz-flowgraph/f24.rs @@ -10,24 +10,24 @@ #[allow(unreachable_code)] pub fn expr_while_24() { - let mut x = 24i; - let mut y = 24i; - let mut z = 24i; + let mut x = 24is; + let mut y = 24is; + let mut z = 24is; loop { - if x == 0i { break; "unreachable"; } - x -= 1i; + if x == 0is { break; "unreachable"; } + x -= 1is; loop { - if y == 0i { break; "unreachable"; } - y -= 1i; + if y == 0is { break; "unreachable"; } + y -= 1is; loop { - if z == 0i { break; "unreachable"; } - z -= 1i; + if z == 0is { break; "unreachable"; } + z -= 1is; } - if x > 10i { + if x > 10is { return; "unreachable"; } diff --git a/src/test/run-make/graphviz-flowgraph/f25.rs b/src/test/run-make/graphviz-flowgraph/f25.rs index 933f95f228c..8896a854787 100644 --- a/src/test/run-make/graphviz-flowgraph/f25.rs +++ b/src/test/run-make/graphviz-flowgraph/f25.rs @@ -10,24 +10,24 @@ #[allow(unreachable_code)] pub fn expr_while_25() { - let mut x = 25i; - let mut y = 25i; - let mut z = 25i; + let mut x = 25is; + let mut y = 25is; + let mut z = 25is; 'a: loop { - if x == 0i { break; "unreachable"; } - x -= 1i; + if x == 0is { break; "unreachable"; } + x -= 1is; 'a: loop { - if y == 0i { break; "unreachable"; } - y -= 1i; + if y == 0is { break; "unreachable"; } + y -= 1is; 'a: loop { - if z == 0i { break; "unreachable"; } - z -= 1i; + if z == 0is { break; "unreachable"; } + z -= 1is; } - if x > 10i { + if x > 10is { continue 'a; "unreachable"; } diff --git a/src/test/run-make/save-analysis/foo.rs b/src/test/run-make/save-analysis/foo.rs index 61c5312f234..c72d685b311 100644 --- a/src/test/run-make/save-analysis/foo.rs +++ b/src/test/run-make/save-analysis/foo.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + struct Foo { f: int } diff --git a/src/test/run-pass-fulldeps/lint-plugin-cmdline.rs b/src/test/run-pass-fulldeps/lint-plugin-cmdline-allow.rs index 7144d2b0f1e..7144d2b0f1e 100644 --- a/src/test/run-pass-fulldeps/lint-plugin-cmdline.rs +++ b/src/test/run-pass-fulldeps/lint-plugin-cmdline-allow.rs diff --git a/src/test/run-pass/bytes-macro-static.rs b/src/test/run-pass-fulldeps/lint-plugin-cmdline-load.rs index 2ce8c40c771..1af26094f23 100644 --- a/src/test/run-pass/bytes-macro-static.rs +++ b/src/test/run-pass-fulldeps/lint-plugin-cmdline-load.rs @@ -8,14 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static FOO: &'static [u8] = bytes!("hello, world"); +// aux-build:lint_plugin_test.rs +// ignore-stage1 +// ignore-pretty: Random space appears with the pretty test +// compile-flags: -Z extra-plugins=lint_plugin_test -pub fn main() { - let b: &'static [u8] = match true { - true => bytes!("test"), - false => unreachable!() - }; +fn lintme() { } //~ WARNING item is named 'lintme' - assert_eq!(b, "test".as_bytes()); - assert_eq!(FOO, "hello, world".as_bytes()); +#[allow(test_lint)] +pub fn main() { + fn lintme() { } } diff --git a/src/test/run-pass-valgrind/cleanup-auto-borrow-obj.rs b/src/test/run-pass-valgrind/cleanup-auto-borrow-obj.rs index 5d7dbbe5a29..195055f12d1 100644 --- a/src/test/run-pass-valgrind/cleanup-auto-borrow-obj.rs +++ b/src/test/run-pass-valgrind/cleanup-auto-borrow-obj.rs @@ -13,6 +13,7 @@ // schedule cleanups when auto borrowing trait objects. // This program should be valgrind clean. +#![feature(box_syntax)] static mut DROP_RAN: bool = false; diff --git a/src/test/run-pass-valgrind/dst-dtor-1.rs b/src/test/run-pass-valgrind/dst-dtor-1.rs index 8b8b7f169c5..47e2a18a999 100644 --- a/src/test/run-pass-valgrind/dst-dtor-1.rs +++ b/src/test/run-pass-valgrind/dst-dtor-1.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + static mut DROP_RAN: bool = false; struct Foo; diff --git a/src/test/run-pass-valgrind/dst-dtor-2.rs b/src/test/run-pass-valgrind/dst-dtor-2.rs index 743293c23f6..2c7b89d680a 100644 --- a/src/test/run-pass-valgrind/dst-dtor-2.rs +++ b/src/test/run-pass-valgrind/dst-dtor-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(box_syntax)] + static mut DROP_RAN: int = 0; struct Foo; diff --git a/src/test/run-pass/alignment-gep-tup-like-1.rs b/src/test/run-pass/alignment-gep-tup-like-1.rs index ecc1a6a495c..72a79e188b3 100644 --- a/src/test/run-pass/alignment-gep-tup-like-1.rs +++ b/src/test/run-pass/alignment-gep-tup-like-1.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct pair<A,B> { a: A, b: B } diff --git a/src/test/run-pass/assert-eq-macro-success.rs b/src/test/run-pass/assert-eq-macro-success.rs index 3da245efd79..089e1b8c5c2 100644 --- a/src/test/run-pass/assert-eq-macro-success.rs +++ b/src/test/run-pass/assert-eq-macro-success.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #[derive(PartialEq, Show)] struct Point { x : int } diff --git a/src/test/run-pass/associated-type-doubleendediterator-object.rs b/src/test/run-pass/associated-types-doubleendediterator-object.rs index 429027cbf30..7365e052171 100644 --- a/src/test/run-pass/associated-type-doubleendediterator-object.rs +++ b/src/test/run-pass/associated-types-doubleendediterator-object.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn pairwise_sub(mut t: Box<DoubleEndedIterator<Item=int>>) -> int { let mut result = 0; loop { diff --git a/src/test/run-pass/associated-types-nested-projections.rs b/src/test/run-pass/associated-types-nested-projections.rs new file mode 100644 index 00000000000..a907b9fcde5 --- /dev/null +++ b/src/test/run-pass/associated-types-nested-projections.rs @@ -0,0 +1,50 @@ +// 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. + +// Test that we can resolve nested projection types. Issue #20666. + +use std::slice; + +trait Bound {} + +impl<'a> Bound for &'a int {} + +trait IntoIterator { + type Iter: Iterator; + + fn into_iter(self) -> Self::Iter; +} + +impl<'a, T> IntoIterator for &'a [T; 3] { + type Iter = slice::Iter<'a, T>; + + fn into_iter(self) -> slice::Iter<'a, T> { + self.iter() + } +} + +fn foo<X>(x: X) where + X: IntoIterator, + <<X as IntoIterator>::Iter as Iterator>::Item: Bound, +{ +} + +fn bar<T, I, X>(x: X) where + T: Bound, + I: Iterator<Item=T>, + X: IntoIterator<Iter=I>, +{ + +} + +fn main() { + foo(&[0i, 1, 2]); + bar(&[0i, 1, 2]); +} diff --git a/src/test/run-pass/associated-types-projection-from-known-type-in-impl.rs b/src/test/run-pass/associated-types-projection-from-known-type-in-impl.rs new file mode 100644 index 00000000000..0a1a8589dec --- /dev/null +++ b/src/test/run-pass/associated-types-projection-from-known-type-in-impl.rs @@ -0,0 +1,44 @@ +// 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. + +// Test where the impl self type uses a projection from a constant type. + +trait Int +{ + type T; +} + +trait NonZero +{ + fn non_zero(self) -> bool; +} + +impl Int for i32 { type T = i32; } +impl Int for i64 { type T = i64; } +impl Int for u32 { type T = u32; } +impl Int for u64 { type T = u64; } + +impl NonZero for <i32 as Int>::T { fn non_zero(self) -> bool { self != 0 } } +impl NonZero for <i64 as Int>::T { fn non_zero(self) -> bool { self != 0 } } +impl NonZero for <u32 as Int>::T { fn non_zero(self) -> bool { self != 0 } } +impl NonZero for <u64 as Int>::T { fn non_zero(self) -> bool { self != 0 } } + +fn main () +{ + assert!(NonZero::non_zero(22_i32)); + assert!(NonZero::non_zero(22_i64)); + assert!(NonZero::non_zero(22_u32)); + assert!(NonZero::non_zero(22_u64)); + + assert!(!NonZero::non_zero(0_i32)); + assert!(!NonZero::non_zero(0_i64)); + assert!(!NonZero::non_zero(0_u32)); + assert!(!NonZero::non_zero(0_u64)); +} diff --git a/src/test/run-pass/associated-types-projection-in-supertrait.rs b/src/test/run-pass/associated-types-projection-in-supertrait.rs new file mode 100644 index 00000000000..e6fec675b03 --- /dev/null +++ b/src/test/run-pass/associated-types-projection-in-supertrait.rs @@ -0,0 +1,50 @@ +// 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. + +// Test that we are handle to correctly handle a projection type +// that appears in a supertrait bound. Issue #20559. + +trait A +{ + type TA; +} + +trait B<TB> +{ + fn foo (&self, t : TB) -> String; +} + +trait C<TC : A> : B<<TC as A>::TA> { } + +struct X; + +impl A for X +{ + type TA = i32; +} + +struct Y; + +impl C<X> for Y { } + +// Both of these impls are required for successful compilation +impl B<i32> for Y +{ + fn foo (&self, t : i32) -> String + { + format!("First {}", t) + } +} + +fn main () +{ + let y = Y; + assert_eq!(y.foo(5), format!("First 5")); +} diff --git a/src/test/run-pass/associated-types-ref-from-struct.rs b/src/test/run-pass/associated-types-ref-from-struct.rs new file mode 100644 index 00000000000..3c7cc7c4975 --- /dev/null +++ b/src/test/run-pass/associated-types-ref-from-struct.rs @@ -0,0 +1,62 @@ +// 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. + +// Test associated type references in structure fields. + +trait Test { + type V; + + fn test(&self, value: &Self::V) -> bool; +} + +/////////////////////////////////////////////////////////////////////////// + +struct TesterPair<T:Test> { + tester: T, + value: T::V, +} + +impl<T:Test> TesterPair<T> { + fn new(tester: T, value: T::V) -> TesterPair<T> { + TesterPair { tester: tester, value: value } + } + + fn test(&self) -> bool { + self.tester.test(&self.value) + } +} + +/////////////////////////////////////////////////////////////////////////// + +struct EqU32(u32); +impl Test for EqU32 { + type V = u32; + + fn test(&self, value: &u32) -> bool { + self.0 == *value + } +} + +struct EqI32(i32); +impl Test for EqI32 { + type V = i32; + + fn test(&self, value: &i32) -> bool { + self.0 == *value + } +} + +fn main() { + let tester = TesterPair::new(EqU32(22), 23); + tester.test(); + + let tester = TesterPair::new(EqI32(22), 23); + tester.test(); +} diff --git a/src/test/compile-fail/syntax-extension-bytes-non-ascii-char-literal.rs b/src/test/run-pass/associated-types-ref-in-struct-literal.rs index d03696cbbbc..b51d44a0c24 100644 --- a/src/test/compile-fail/syntax-extension-bytes-non-ascii-char-literal.rs +++ b/src/test/run-pass/associated-types-ref-in-struct-literal.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,7 +8,22 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// Test associated type references in a struct literal. Issue #20535. + +pub trait Foo { + type Bar; +} + +impl Foo for int { + type Bar = int; +} + +struct Thing<F: Foo> { + a: F, + b: F::Bar, +} + fn main() { - let vec = bytes!('λ'); //~ ERROR non-ascii char literal in bytes! - //~^ WARN `bytes!` is deprecated + let thing = Thing{a: 1i, b: 2i}; + assert_eq!(thing.a + 1, thing.b); } diff --git a/src/test/run-pass/associated-types-region-erasure-issue-20582.rs b/src/test/run-pass/associated-types-region-erasure-issue-20582.rs new file mode 100644 index 00000000000..03ab8f7e431 --- /dev/null +++ b/src/test/run-pass/associated-types-region-erasure-issue-20582.rs @@ -0,0 +1,27 @@ +// 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. + +// Regression test for #20582. This test caused an ICE related to +// inconsistent region erasure in trans. + +struct Foo<'a> { + buf: &'a[u8] +} + +impl<'a> Iterator for Foo<'a> { + type Item = &'a[u8]; + + fn next(&mut self) -> Option<<Self as Iterator>::Item> { + Some(self.buf) + } +} + +fn main() { +} diff --git a/src/test/run-pass/autoderef-method-on-trait.rs b/src/test/run-pass/autoderef-method-on-trait.rs index f13f598fda2..876fc123f48 100644 --- a/src/test/run-pass/autoderef-method-on-trait.rs +++ b/src/test/run-pass/autoderef-method-on-trait.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait double { fn double(self: Box<Self>) -> uint; diff --git a/src/test/run-pass/autoderef-method-priority.rs b/src/test/run-pass/autoderef-method-priority.rs index cc4dd13cf61..f5d5c81117e 100644 --- a/src/test/run-pass/autoderef-method-priority.rs +++ b/src/test/run-pass/autoderef-method-priority.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait double { fn double(self) -> uint; diff --git a/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs b/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs index 856ee686db3..282cf62190c 100644 --- a/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs +++ b/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait double { fn double(self: Box<Self>) -> uint; diff --git a/src/test/run-pass/autoderef-method-twice.rs b/src/test/run-pass/autoderef-method-twice.rs index 94da61483ea..eb44e3b52b9 100644 --- a/src/test/run-pass/autoderef-method-twice.rs +++ b/src/test/run-pass/autoderef-method-twice.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait double { fn double(self: Box<Self>) -> uint; } diff --git a/src/test/run-pass/autoderef-method.rs b/src/test/run-pass/autoderef-method.rs index 2e9751ce6ac..4bbb17c6dd6 100644 --- a/src/test/run-pass/autoderef-method.rs +++ b/src/test/run-pass/autoderef-method.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait double { fn double(self: Box<Self>) -> uint; } diff --git a/src/test/run-pass/autoref-intermediate-types-issue-3585.rs b/src/test/run-pass/autoref-intermediate-types-issue-3585.rs index 7f44bcdb50c..e026ac9dcba 100644 --- a/src/test/run-pass/autoref-intermediate-types-issue-3585.rs +++ b/src/test/run-pass/autoref-intermediate-types-issue-3585.rs @@ -9,6 +9,9 @@ // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait Foo { fn foo(&self) -> String; } diff --git a/src/test/run-pass/bitv-perf-test.rs b/src/test/run-pass/bitv-perf-test.rs index c5f69f249db..325f6dec76f 100644 --- a/src/test/run-pass/bitv-perf-test.rs +++ b/src/test/run-pass/bitv-perf-test.rs @@ -9,6 +9,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + extern crate collections; use std::collections::Bitv; diff --git a/src/test/run-pass/borrowck-borrow-from-expr-block.rs b/src/test/run-pass/borrowck-borrow-from-expr-block.rs index 038f9e5c9ab..9fcd87418be 100644 --- a/src/test/run-pass/borrowck-borrow-from-expr-block.rs +++ b/src/test/run-pass/borrowck-borrow-from-expr-block.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn borrow<F>(x: &int, f: F) where F: FnOnce(&int) { f(x) diff --git a/src/test/run-pass/borrowck-field-sensitivity.rs b/src/test/run-pass/borrowck-field-sensitivity.rs index 33be47e504b..89d80190042 100644 --- a/src/test/run-pass/borrowck-field-sensitivity.rs +++ b/src/test/run-pass/borrowck-field-sensitivity.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct A { a: int, b: Box<int> } struct B { a: Box<int>, b: Box<int> } diff --git a/src/test/run-pass/borrowck-macro-interaction-issue-6304.rs b/src/test/run-pass/borrowck-macro-interaction-issue-6304.rs index 28db3953a00..49483e40096 100644 --- a/src/test/run-pass/borrowck-macro-interaction-issue-6304.rs +++ b/src/test/run-pass/borrowck-macro-interaction-issue-6304.rs @@ -11,6 +11,7 @@ // Check that we do not ICE when compiling this // macro, which reuses the expression `$id` +#![feature(box_syntax)] struct Foo { a: int diff --git a/src/test/run-pass/borrowck-move-by-capture-ok.rs b/src/test/run-pass/borrowck-move-by-capture-ok.rs index a6b142bb126..773780ffb09 100644 --- a/src/test/run-pass/borrowck-move-by-capture-ok.rs +++ b/src/test/run-pass/borrowck-move-by-capture-ok.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] pub fn main() { diff --git a/src/test/run-pass/borrowck-mut-uniq.rs b/src/test/run-pass/borrowck-mut-uniq.rs index c586ff2c93a..4416c57e345 100644 --- a/src/test/run-pass/borrowck-mut-uniq.rs +++ b/src/test/run-pass/borrowck-mut-uniq.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::mem::swap; #[derive(Show)] diff --git a/src/test/run-pass/borrowck-use-mut-borrow.rs b/src/test/run-pass/borrowck-use-mut-borrow.rs index cbfdd5961ff..7be12ff3cc9 100644 --- a/src/test/run-pass/borrowck-use-mut-borrow.rs +++ b/src/test/run-pass/borrowck-use-mut-borrow.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct A { a: int, b: Box<int> } fn field_copy_after_field_borrow() { diff --git a/src/test/compile-fail/syntax-extension-bytes-non-literal.rs b/src/test/run-pass/box-new.rs index 3a2e104818f..168218e1b1e 100644 --- a/src/test/compile-fail/syntax-extension-bytes-non-literal.rs +++ b/src/test/run-pass/box-new.rs @@ -1,4 +1,4 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// 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. // @@ -9,6 +9,5 @@ // except according to those terms. fn main() { - let vec = bytes!(foo); //~ ERROR non-literal in bytes! - //~^ WARN `bytes!` is deprecated + let _a = Box::new(1); } diff --git a/src/test/run-pass/cancel-clean-via-immediate-rvalue-ref.rs b/src/test/run-pass/cancel-clean-via-immediate-rvalue-ref.rs index d326c20707d..631133cc7ff 100644 --- a/src/test/run-pass/cancel-clean-via-immediate-rvalue-ref.rs +++ b/src/test/run-pass/cancel-clean-via-immediate-rvalue-ref.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo(x: &mut Box<u8>) { *x = box 5; diff --git a/src/test/run-pass/capturing-logging.rs b/src/test/run-pass/capturing-logging.rs index e3e00410507..00673bee8b4 100644 --- a/src/test/run-pass/capturing-logging.rs +++ b/src/test/run-pass/capturing-logging.rs @@ -11,6 +11,9 @@ // ignore-android (FIXME #11419) // exec-env:RUST_LOG=info +#![allow(unknown_features)] +#![feature(box_syntax)] + #[macro_use] extern crate log; diff --git a/src/test/run-pass/cci_borrow.rs b/src/test/run-pass/cci_borrow.rs index 262c19174b1..ef5ee5aa3b4 100644 --- a/src/test/run-pass/cci_borrow.rs +++ b/src/test/run-pass/cci_borrow.rs @@ -10,6 +10,8 @@ // aux-build:cci_borrow_lib.rs +#![allow(unknown_features)] +#![feature(box_syntax)] extern crate cci_borrow_lib; use cci_borrow_lib::foo; diff --git a/src/test/run-pass/cfg_attr.rs b/src/test/run-pass/cfg_attr.rs index 15d3f4a04d5..7e508d91c87 100644 --- a/src/test/run-pass/cfg_attr.rs +++ b/src/test/run-pass/cfg_attr.rs @@ -14,37 +14,37 @@ use std::fmt::Show; struct NotShowable; -#[cfg_attr(set1, deriving(Show))] +#[cfg_attr(set1, derive(Show))] struct Set1; -#[cfg_attr(notset, deriving(Show))] +#[cfg_attr(notset, derive(Show))] struct Notset(NotShowable); -#[cfg_attr(not(notset), deriving(Show))] +#[cfg_attr(not(notset), derive(Show))] struct NotNotset; -#[cfg_attr(not(set1), deriving(Show))] +#[cfg_attr(not(set1), derive(Show))] struct NotSet1(NotShowable); -#[cfg_attr(all(set1, set2), deriving(Show))] +#[cfg_attr(all(set1, set2), derive(Show))] struct AllSet1Set2; -#[cfg_attr(all(set1, notset), deriving(Show))] +#[cfg_attr(all(set1, notset), derive(Show))] struct AllSet1Notset(NotShowable); -#[cfg_attr(any(set1, notset), deriving(Show))] +#[cfg_attr(any(set1, notset), derive(Show))] struct AnySet1Notset; -#[cfg_attr(any(notset, notset2), deriving(Show))] +#[cfg_attr(any(notset, notset2), derive(Show))] struct AnyNotsetNotset2(NotShowable); -#[cfg_attr(all(not(notset), any(set1, notset)), deriving(Show))] +#[cfg_attr(all(not(notset), any(set1, notset)), derive(Show))] struct Complex; -#[cfg_attr(any(notset, not(any(set1, notset))), deriving(Show))] +#[cfg_attr(any(notset, not(any(set1, notset))), derive(Show))] struct ComplexNot(NotShowable); -#[cfg_attr(any(target_endian = "little", target_endian = "big"), deriving(Show))] +#[cfg_attr(any(target_endian = "little", target_endian = "big"), derive(Show))] struct KeyValue; fn is_show<T: Show>() {} diff --git a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs index a041bbfe8ad..e6cae99067e 100644 --- a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs +++ b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs @@ -9,6 +9,10 @@ // except according to those terms. // aux-build:cci_class_cast.rs + +#![allow(unknown_features)] +#![feature(box_syntax)] + extern crate cci_class_cast; use std::string::ToString; diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index 9c7913dc0b0..c2fa98a66df 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::fmt; struct cat { diff --git a/src/test/run-pass/cleanup-arm-conditional.rs b/src/test/run-pass/cleanup-arm-conditional.rs index 65ad68ba702..0d155ae085c 100644 --- a/src/test/run-pass/cleanup-arm-conditional.rs +++ b/src/test/run-pass/cleanup-arm-conditional.rs @@ -21,6 +21,9 @@ // Test that cleanup scope for temporaries created in a match // arm is confined to the match arm itself. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::os; struct Test { x: int } diff --git a/src/test/run-pass/cleanup-rvalue-during-if-and-while.rs b/src/test/run-pass/cleanup-rvalue-during-if-and-while.rs index 89b00102081..83f93cb81a1 100644 --- a/src/test/run-pass/cleanup-rvalue-during-if-and-while.rs +++ b/src/test/run-pass/cleanup-rvalue-during-if-and-while.rs @@ -12,6 +12,8 @@ // This test verifies that temporaries created for `while`'s and `if` // conditions are dropped after the condition is evaluated. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Temporary; diff --git a/src/test/run-pass/cleanup-rvalue-scopes.rs b/src/test/run-pass/cleanup-rvalue-scopes.rs index 59763e417a2..bbfe0e6a18d 100644 --- a/src/test/run-pass/cleanup-rvalue-scopes.rs +++ b/src/test/run-pass/cleanup-rvalue-scopes.rs @@ -12,6 +12,8 @@ // statement or end of block, as appropriate given the temporary // lifetime rules. +#![feature(box_syntax)] + use std::ops::Drop; static mut FLAGS: u64 = 0; diff --git a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs index 526819940d0..04ab0d881a8 100644 --- a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs +++ b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs @@ -24,6 +24,9 @@ // It's unclear how likely such a bug is to recur, but it seems like a // scenario worth testing. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; enum Conzabble { diff --git a/src/test/run-pass/clone-with-exterior.rs b/src/test/run-pass/clone-with-exterior.rs index cb495859708..8eeae7a28ac 100644 --- a/src/test/run-pass/clone-with-exterior.rs +++ b/src/test/run-pass/clone-with-exterior.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; struct Pair { diff --git a/src/test/run-pass/close-over-big-then-small-data.rs b/src/test/run-pass/close-over-big-then-small-data.rs index 375767c8f51..99fdc346026 100644 --- a/src/test/run-pass/close-over-big-then-small-data.rs +++ b/src/test/run-pass/close-over-big-then-small-data.rs @@ -12,6 +12,9 @@ // storing closure data (as we used to do), the u64 would // overwrite the u16. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Pair<A,B> { a: A, b: B } diff --git a/src/test/run-pass/coerce-expect-unsized.rs b/src/test/run-pass/coerce-expect-unsized.rs index 09f230792a9..3964d54f860 100644 --- a/src/test/run-pass/coerce-expect-unsized.rs +++ b/src/test/run-pass/coerce-expect-unsized.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::fmt::Show; // Check that coercions apply at the pointer level and don't cause diff --git a/src/test/run-pass/coerce-match-calls.rs b/src/test/run-pass/coerce-match-calls.rs new file mode 100644 index 00000000000..0ff28b471a3 --- /dev/null +++ b/src/test/run-pass/coerce-match-calls.rs @@ -0,0 +1,23 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <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. + +// Check that coercions are propagated through match and if expressions. + +use std::boxed::Box; + +pub fn main() { + let _: Box<[int]> = if true { Box::new([1i, 2, 3]) } else { Box::new([1i]) }; + + let _: Box<[int]> = match true { true => Box::new([1i, 2, 3]), false => Box::new([1i]) }; + + // Check we don't get over-keen at propagating coercions in the case of casts. + let x = if true { 42 } else { 42u8 } as u16; + let x = match true { true => 42, false => 42u8 } as u16; +} diff --git a/src/test/run-pass/coerce-match.rs b/src/test/run-pass/coerce-match.rs index d67664bb1be..0992ee97d06 100644 --- a/src/test/run-pass/coerce-match.rs +++ b/src/test/run-pass/coerce-match.rs @@ -10,6 +10,9 @@ // Check that coercions are propagated through match and if expressions. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let _: Box<[int]> = if true { box [1i, 2, 3] } else { box [1i] }; diff --git a/src/test/run-pass/const-bound.rs b/src/test/run-pass/const-bound.rs index e24bc1dbff9..3a6973fe61c 100644 --- a/src/test/run-pass/const-bound.rs +++ b/src/test/run-pass/const-bound.rs @@ -11,6 +11,8 @@ // Make sure const bounds work on things, and test that a few types // are const. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo<T: Sync>(x: T) -> T { x } diff --git a/src/test/run-pass/crate-method-reexport-grrrrrrr.rs b/src/test/run-pass/crate-method-reexport-grrrrrrr.rs index 0088a36eda9..1a3e87b55b6 100644 --- a/src/test/run-pass/crate-method-reexport-grrrrrrr.rs +++ b/src/test/run-pass/crate-method-reexport-grrrrrrr.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] // This is a regression test that the metadata for the // name_pool::methods impl in the other crate is reachable from this diff --git a/src/test/run-pass/deref-lval.rs b/src/test/run-pass/deref-lval.rs index d9b0940f80b..ead0683b870 100644 --- a/src/test/run-pass/deref-lval.rs +++ b/src/test/run-pass/deref-lval.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] use std::cell::Cell; diff --git a/src/test/run-pass/deref.rs b/src/test/run-pass/deref.rs index 117b133a113..b4ee0246d87 100644 --- a/src/test/run-pass/deref.rs +++ b/src/test/run-pass/deref.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let x: Box<int> = box 10; diff --git a/src/test/run-pass/deriving-default-box.rs b/src/test/run-pass/deriving-default-box.rs index aea6ebd2597..b00ceb6ed22 100644 --- a/src/test/run-pass/deriving-default-box.rs +++ b/src/test/run-pass/deriving-default-box.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::default::Default; #[derive(Default)] diff --git a/src/test/run-pass/deriving-encodable-decodable-box.rs b/src/test/run-pass/deriving-encodable-decodable-box.rs index b7be14321fd..1a204fa3e20 100644 --- a/src/test/run-pass/deriving-encodable-decodable-box.rs +++ b/src/test/run-pass/deriving-encodable-decodable-box.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(old_orphan_check)] extern crate serialize; diff --git a/src/test/run-pass/deriving-eq-ord-boxed-slice.rs b/src/test/run-pass/deriving-eq-ord-boxed-slice.rs index 6701a321339..3b89c943edb 100644 --- a/src/test/run-pass/deriving-eq-ord-boxed-slice.rs +++ b/src/test/run-pass/deriving-eq-ord-boxed-slice.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + #[derive(PartialEq, PartialOrd, Eq, Ord)] struct Foo(Box<[u8]>); diff --git a/src/test/run-pass/deriving-hash.rs b/src/test/run-pass/deriving-hash.rs index ddad703d7df..02ab7e5db5b 100644 --- a/src/test/run-pass/deriving-hash.rs +++ b/src/test/run-pass/deriving-hash.rs @@ -8,9 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - -use std::hash; -use std::hash::Hash; +use std::hash::{Hash, SipHasher}; #[derive(Hash)] struct Person { @@ -19,6 +17,10 @@ struct Person { phone: uint, } +fn hash<T: Hash<SipHasher>>(t: &T) -> u64 { + std::hash::hash::<T, SipHasher>(t) +} + fn main() { let person1 = Person { id: 5, @@ -30,6 +32,6 @@ fn main() { name: "Bob".to_string(), phone: 555_666_7777 }; - assert!(hash::hash(&person1) == hash::hash(&person1)); - assert!(hash::hash(&person1) != hash::hash(&person2)); + assert!(hash(&person1) == hash(&person1)); + assert!(hash(&person1) != hash(&person2)); } diff --git a/src/test/run-pass/deriving-meta-multiple.rs b/src/test/run-pass/deriving-meta-multiple.rs index c435a1f344d..f45dce9da63 100644 --- a/src/test/run-pass/deriving-meta-multiple.rs +++ b/src/test/run-pass/deriving-meta-multiple.rs @@ -9,7 +9,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::hash::hash; +use std::hash::{Hash, SipHasher}; // testing multiple separate deriving attributes #[derive(PartialEq)] @@ -20,6 +20,8 @@ struct Foo { baz: int } +fn hash<T: Hash<SipHasher>>(_t: &T) {} + pub fn main() { let a = Foo {bar: 4, baz: -3}; diff --git a/src/test/run-pass/deriving-meta.rs b/src/test/run-pass/deriving-meta.rs index 54dc2b97b77..d6a2fad08ed 100644 --- a/src/test/run-pass/deriving-meta.rs +++ b/src/test/run-pass/deriving-meta.rs @@ -9,7 +9,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::hash::hash; +use std::hash::{Hash, SipHasher}; #[derive(PartialEq, Clone, Hash)] struct Foo { @@ -17,6 +17,8 @@ struct Foo { baz: int } +fn hash<T: Hash<SipHasher>>(_t: &T) {} + pub fn main() { let a = Foo {bar: 4, baz: -3}; diff --git a/src/test/run-pass/drop-on-empty-block-exit.rs b/src/test/run-pass/drop-on-empty-block-exit.rs index e3927bd5367..f875d0644a0 100644 --- a/src/test/run-pass/drop-on-empty-block-exit.rs +++ b/src/test/run-pass/drop-on-empty-block-exit.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] enum t { foo(Box<int>), } diff --git a/src/test/run-pass/drop-struct-as-object.rs b/src/test/run-pass/drop-struct-as-object.rs index 6d7715ed9a5..7a3b6df539f 100644 --- a/src/test/run-pass/drop-struct-as-object.rs +++ b/src/test/run-pass/drop-struct-as-object.rs @@ -11,6 +11,9 @@ // Test that destructor on a struct runs successfully after the struct // is boxed and converted to an object. +#![allow(unknown_features)] +#![feature(box_syntax)] + static mut value: uint = 0; struct Cat { diff --git a/src/test/run-pass/drop-trait-enum.rs b/src/test/run-pass/drop-trait-enum.rs index f1cc4fb1724..9bfb3572ab5 100644 --- a/src/test/run-pass/drop-trait-enum.rs +++ b/src/test/run-pass/drop-trait-enum.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; use std::sync::mpsc::{channel, Sender}; @@ -36,13 +39,13 @@ enum Foo { impl Drop for Foo { fn drop(&mut self) { match self { - &Foo::SimpleVariant(ref mut sender) => { + &mut Foo::SimpleVariant(ref mut sender) => { sender.send(Message::DestructorRan).unwrap(); } - &Foo::NestedVariant(_, _, ref mut sender) => { + &mut Foo::NestedVariant(_, _, ref mut sender) => { sender.send(Message::DestructorRan).unwrap(); } - &Foo::FailingVariant { .. } => { + &mut Foo::FailingVariant { .. } => { panic!("Failed"); } } @@ -66,7 +69,7 @@ pub fn main() { assert_eq!(receiver.recv().ok(), None); let (sender, receiver) = channel(); - let _t = Thread::spawn(move|| { + let _t = Thread::scoped(move|| { let v = Foo::FailingVariant { on_drop: SendOnDrop { sender: sender } }; }); assert_eq!(receiver.recv().unwrap(), Message::Dropped); @@ -74,7 +77,7 @@ pub fn main() { let (sender, receiver) = channel(); let _t = { - Thread::spawn(move|| { + Thread::scoped(move|| { let mut v = Foo::NestedVariant(box 42u, SendOnDrop { sender: sender.clone() }, sender.clone()); diff --git a/src/test/run-pass/dst-deref-mut.rs b/src/test/run-pass/dst-deref-mut.rs index 0a12df53de2..909f7f4897a 100644 --- a/src/test/run-pass/dst-deref-mut.rs +++ b/src/test/run-pass/dst-deref-mut.rs @@ -10,6 +10,9 @@ // Test that a custom deref with a fat pointer return type does not ICE +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::ops::{Deref, DerefMut}; pub struct Arr { diff --git a/src/test/run-pass/dst-deref.rs b/src/test/run-pass/dst-deref.rs index 8ef8f1a868d..ad4456b5b59 100644 --- a/src/test/run-pass/dst-deref.rs +++ b/src/test/run-pass/dst-deref.rs @@ -10,6 +10,9 @@ // Test that a custom deref with a fat pointer return type does not ICE +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::ops::Deref; pub struct Arr { diff --git a/src/test/run-pass/dst-struct.rs b/src/test/run-pass/dst-struct.rs index 9c0e5a6f5c8..b2092e745a1 100644 --- a/src/test/run-pass/dst-struct.rs +++ b/src/test/run-pass/dst-struct.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Fat<T: ?Sized> { f1: int, f2: &'static str, diff --git a/src/test/run-pass/dst-trait.rs b/src/test/run-pass/dst-trait.rs index 0b50609fddf..627d197879d 100644 --- a/src/test/run-pass/dst-trait.rs +++ b/src/test/run-pass/dst-trait.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Fat<T: ?Sized> { f1: int, f2: &'static str, diff --git a/src/test/run-pass/empty-allocation-non-null.rs b/src/test/run-pass/empty-allocation-non-null.rs index 56eb340ef59..269e0ee6ce4 100644 --- a/src/test/run-pass/empty-allocation-non-null.rs +++ b/src/test/run-pass/empty-allocation-non-null.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { assert!(Some(box() ()).is_some()); diff --git a/src/test/run-pass/empty-allocation-rvalue-non-null.rs b/src/test/run-pass/empty-allocation-rvalue-non-null.rs index 96c5f81558e..e95d58c706b 100644 --- a/src/test/run-pass/empty-allocation-rvalue-non-null.rs +++ b/src/test/run-pass/empty-allocation-rvalue-non-null.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let x = *box() (); } diff --git a/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs b/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs index 7d856fd5656..81713657202 100644 --- a/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs +++ b/src/test/run-pass/enum-nullable-simplifycfg-misopt.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] /*! * This is a regression test for a bug in LLVM, fixed in upstream r179587, diff --git a/src/test/run-pass/evec-slice.rs b/src/test/run-pass/evec-slice.rs index ab6576b9b42..734ac306653 100644 --- a/src/test/run-pass/evec-slice.rs +++ b/src/test/run-pass/evec-slice.rs @@ -22,7 +22,7 @@ pub fn main() { let c : &[int] = &[2,2,2,2,3]; let cc : &[int] = &[2,2,2,2,2,2]; - println!("{}", a); + println!("{:?}", a); assert!(a < b); assert!(a <= b); @@ -30,7 +30,7 @@ pub fn main() { assert!(b >= a); assert!(b > a); - println!("{}", b); + println!("{:?}", b); assert!(b < c); assert!(b <= c); @@ -44,7 +44,7 @@ pub fn main() { assert!(c >= a); assert!(c > a); - println!("{}", c); + println!("{:?}", c); assert!(a < cc); assert!(a <= cc); @@ -52,5 +52,5 @@ pub fn main() { assert!(cc >= a); assert!(cc > a); - println!("{}", cc); + println!("{:?}", cc); } diff --git a/src/test/run-pass/explicit-self-generic.rs b/src/test/run-pass/explicit-self-generic.rs index 87f1adba8dd..a2aaaa235e4 100644 --- a/src/test/run-pass/explicit-self-generic.rs +++ b/src/test/run-pass/explicit-self-generic.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct LM { resize_at: uint, size: uint } impl Copy for LM {} diff --git a/src/test/run-pass/explicit-self-objects-uniq.rs b/src/test/run-pass/explicit-self-objects-uniq.rs index e566f218aa8..501ba01b4ce 100644 --- a/src/test/run-pass/explicit-self-objects-uniq.rs +++ b/src/test/run-pass/explicit-self-objects-uniq.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait Foo { fn f(self: Box<Self>); diff --git a/src/test/run-pass/explicit-self.rs b/src/test/run-pass/explicit-self.rs index 8a67e40844a..e5d8ec3f8ad 100644 --- a/src/test/run-pass/explicit-self.rs +++ b/src/test/run-pass/explicit-self.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + static tau: f64 = 2.0*3.14159265358979323; struct Point {x: f64, y: f64} diff --git a/src/test/run-pass/expr-block-generic-unique1.rs b/src/test/run-pass/expr-block-generic-unique1.rs index 5c1039fe433..1654c87c6a4 100644 --- a/src/test/run-pass/expr-block-generic-unique1.rs +++ b/src/test/run-pass/expr-block-generic-unique1.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn test_generic<T, F>(expected: Box<T>, eq: F) where T: Clone, F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = { expected.clone() }; assert!(eq(expected, actual)); diff --git a/src/test/run-pass/expr-block-generic-unique2.rs b/src/test/run-pass/expr-block-generic-unique2.rs index 3d736cca6d5..e41ce37cc3a 100644 --- a/src/test/run-pass/expr-block-generic-unique2.rs +++ b/src/test/run-pass/expr-block-generic-unique2.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn test_generic<T, F>(expected: T, eq: F) where T: Clone, F: FnOnce(T, T) -> bool { let actual: T = { expected.clone() }; assert!(eq(expected, actual)); diff --git a/src/test/run-pass/expr-block-unique.rs b/src/test/run-pass/expr-block-unique.rs index 0dff989002f..d934ce677d1 100644 --- a/src/test/run-pass/expr-block-unique.rs +++ b/src/test/run-pass/expr-block-unique.rs @@ -9,6 +9,7 @@ // except according to those terms. - +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let x = { box 100i }; assert!((*x == 100)); } diff --git a/src/test/run-pass/expr-if-unique.rs b/src/test/run-pass/expr-if-unique.rs index b1fdf51d9b1..5294d05401c 100644 --- a/src/test/run-pass/expr-if-unique.rs +++ b/src/test/run-pass/expr-if-unique.rs @@ -9,7 +9,8 @@ // except according to those terms. - +#![allow(unknown_features)] +#![feature(box_syntax)] // Tests for if as expressions returning boxed types diff --git a/src/test/run-pass/expr-match-generic-unique1.rs b/src/test/run-pass/expr-match-generic-unique1.rs index 5fc9a502ca8..9de1379f480 100644 --- a/src/test/run-pass/expr-match-generic-unique1.rs +++ b/src/test/run-pass/expr-match-generic-unique1.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn test_generic<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() }, diff --git a/src/test/run-pass/expr-match-generic-unique2.rs b/src/test/run-pass/expr-match-generic-unique2.rs index e608f9c46c7..489cd8437d2 100644 --- a/src/test/run-pass/expr-match-generic-unique2.rs +++ b/src/test/run-pass/expr-match-generic-unique2.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool { let actual: T = match true { true => expected.clone(), diff --git a/src/test/run-pass/expr-match-unique.rs b/src/test/run-pass/expr-match-unique.rs index 83f2ada02b0..7958f4927da 100644 --- a/src/test/run-pass/expr-match-unique.rs +++ b/src/test/run-pass/expr-match-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] // Tests for match as expressions resulting in boxed types fn test_box() { diff --git a/src/test/run-pass/ext-expand-inner-exprs.rs b/src/test/run-pass/ext-expand-inner-exprs.rs index 1c96cbd9314..d204f808e44 100644 --- a/src/test/run-pass/ext-expand-inner-exprs.rs +++ b/src/test/run-pass/ext-expand-inner-exprs.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -static FOO : &'static [u8] = bytes!(concat!(concat!("hel", "lo"), "world")); +static FOO : &'static str = concat!(concat!("hel", "lo"), "world"); pub fn main() { - assert_eq!(FOO, "helloworld".as_bytes()); + assert_eq!(FOO, "helloworld"); } diff --git a/src/test/run-pass/extern-stress.rs b/src/test/run-pass/extern-stress.rs index bb9e9407382..c3e04177cce 100644 --- a/src/test/run-pass/extern-stress.rs +++ b/src/test/run-pass/extern-stress.rs @@ -42,7 +42,7 @@ fn count(n: libc::uintptr_t) -> libc::uintptr_t { pub fn main() { range(0u, 100).map(|_| { - Thread::spawn(move|| { + Thread::scoped(move|| { assert_eq!(count(5), 16); }) }).collect::<Vec<_>>(); diff --git a/src/test/run-pass/extern-yield.rs b/src/test/run-pass/extern-yield.rs index 46829e9ba6e..f5e91b9de67 100644 --- a/src/test/run-pass/extern-yield.rs +++ b/src/test/run-pass/extern-yield.rs @@ -39,7 +39,7 @@ fn count(n: libc::uintptr_t) -> libc::uintptr_t { pub fn main() { range(0, 10u).map(|i| { - Thread::spawn(move|| { + Thread::scoped(move|| { let result = count(5); println!("result = {}", result); assert_eq!(result, 16); diff --git a/src/test/run-pass/fsu-moves-and-copies.rs b/src/test/run-pass/fsu-moves-and-copies.rs index a08cd33362f..0f8d7c24360 100644 --- a/src/test/run-pass/fsu-moves-and-copies.rs +++ b/src/test/run-pass/fsu-moves-and-copies.rs @@ -11,6 +11,9 @@ // Issue 4691: Ensure that functional-struct-updates operates // correctly and moves rather than copy when appropriate. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::marker::NoCopy as NP; struct ncint { np: NP, v: int } diff --git a/src/test/run-pass/func-arg-incomplete-pattern.rs b/src/test/run-pass/func-arg-incomplete-pattern.rs index 6d06c12c450..b23d8db3cfd 100644 --- a/src/test/run-pass/func-arg-incomplete-pattern.rs +++ b/src/test/run-pass/func-arg-incomplete-pattern.rs @@ -11,6 +11,8 @@ // Test that we do not leak when the arg pattern must drop part of the // argument (in this case, the `y` field). +#![allow(unknown_features)] +#![feature(box_syntax)] struct Foo { x: Box<uint>, diff --git a/src/test/run-pass/func-arg-ref-pattern.rs b/src/test/run-pass/func-arg-ref-pattern.rs index 5eeace65054..9e94bca96f7 100644 --- a/src/test/run-pass/func-arg-ref-pattern.rs +++ b/src/test/run-pass/func-arg-ref-pattern.rs @@ -14,6 +14,8 @@ // boxes. Make sure that we don't free the box as we match the // pattern. +#![allow(unknown_features)] +#![feature(box_syntax)] fn getaddr(box ref x: Box<uint>) -> *const uint { let addr: *const uint = &*x; diff --git a/src/test/run-pass/generic-alias-unique.rs b/src/test/run-pass/generic-alias-unique.rs index 8b5dfb6cf75..34b7f15e4c6 100644 --- a/src/test/run-pass/generic-alias-unique.rs +++ b/src/test/run-pass/generic-alias-unique.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn id<T:Send>(t: T) -> T { return t; } pub fn main() { diff --git a/src/test/run-pass/generic-exterior-unique.rs b/src/test/run-pass/generic-exterior-unique.rs index 0746c994c2a..a2f7bdfd817 100644 --- a/src/test/run-pass/generic-exterior-unique.rs +++ b/src/test/run-pass/generic-exterior-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Recbox<T> {x: Box<T>} diff --git a/src/test/run-pass/generic-fn-unique.rs b/src/test/run-pass/generic-fn-unique.rs index e1a8ad7c20a..be83cb04f2c 100644 --- a/src/test/run-pass/generic-fn-unique.rs +++ b/src/test/run-pass/generic-fn-unique.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f<T>(x: Box<T>) -> Box<T> { return x; } pub fn main() { let x = f(box 3i); println!("{}", *x); } diff --git a/src/test/run-pass/generic-object.rs b/src/test/run-pass/generic-object.rs index d0a5af8e2ce..986b35cbecf 100644 --- a/src/test/run-pass/generic-object.rs +++ b/src/test/run-pass/generic-object.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait Foo<T> { fn get(&self) -> T; diff --git a/src/test/run-pass/generic-recursive-tag.rs b/src/test/run-pass/generic-recursive-tag.rs index b738b527122..845375d9b84 100644 --- a/src/test/run-pass/generic-recursive-tag.rs +++ b/src/test/run-pass/generic-recursive-tag.rs @@ -10,6 +10,8 @@ // ignore-pretty FIXME(#14193) +#![allow(unknown_features)] +#![feature(box_syntax)] enum list<T> { cons(Box<T>, Box<list<T>>), nil, } diff --git a/src/test/run-pass/generic-tag.rs b/src/test/run-pass/generic-tag.rs index 250c5bb66af..b0d4944ba54 100644 --- a/src/test/run-pass/generic-tag.rs +++ b/src/test/run-pass/generic-tag.rs @@ -10,6 +10,8 @@ #![allow(dead_assignment)] #![allow(unused_variable)] +#![allow(unknown_features)] +#![feature(box_syntax)] enum option<T> { some(Box<T>), none, } diff --git a/src/test/run-pass/generic-unique.rs b/src/test/run-pass/generic-unique.rs index 4821b9354bf..1d39c47417c 100644 --- a/src/test/run-pass/generic-unique.rs +++ b/src/test/run-pass/generic-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Triple<T> { x: T, y: T, z: T } diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index f83698edc90..0e82ad43782 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] /** diff --git a/src/test/run-pass/hrtb-precedence-of-plus.rs b/src/test/run-pass/hrtb-precedence-of-plus.rs index 9a43b5b711e..1d1e744ef08 100644 --- a/src/test/run-pass/hrtb-precedence-of-plus.rs +++ b/src/test/run-pass/hrtb-precedence-of-plus.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] // Test that `Fn(int) -> int + 'static` parses as `(Fn(int) -> int) + diff --git a/src/test/run-pass/huge-largest-array.rs b/src/test/run-pass/huge-largest-array.rs index e24731546ed..e1b0c115365 100644 --- a/src/test/run-pass/huge-largest-array.rs +++ b/src/test/run-pass/huge-largest-array.rs @@ -10,12 +10,12 @@ use std::mem::size_of; -#[cfg(target_word_size = "32")] +#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))] pub fn main() { assert_eq!(size_of::<[u8; (1 << 31) - 1]>(), (1 << 31) - 1); } -#[cfg(target_word_size = "64")] +#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))] pub fn main() { assert_eq!(size_of::<[u8; (1 << 47) - 1]>(), (1 << 47) - 1); } diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index 8b0d7c18fb1..dbc23a63bba 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -13,6 +13,8 @@ #![deny(warnings)] #![allow(unused_must_use)] +#![allow(unknown_features)] +#![feature(box_syntax)] use std::fmt; @@ -183,7 +185,7 @@ fn test_write() { // can do with them just yet (to test the output) fn test_print() { print!("hi"); - print!("{}", vec!(0u8)); + print!("{:?}", vec!(0u8)); println!("hello"); println!("this is a {}", "test"); println!("{foo}", foo="bar"); diff --git a/src/test/run-pass/init-res-into-things.rs b/src/test/run-pass/init-res-into-things.rs index ee82a99a808..eeae3f35cfc 100644 --- a/src/test/run-pass/init-res-into-things.rs +++ b/src/test/run-pass/init-res-into-things.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unsafe_destructor)] use std::cell::Cell; diff --git a/src/test/run-pass/intrinsic-atomics.rs b/src/test/run-pass/intrinsic-atomics.rs index 3b81943000b..0644fbbc99f 100644 --- a/src/test/run-pass/intrinsic-atomics.rs +++ b/src/test/run-pass/intrinsic-atomics.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(intrinsics)] mod rusti { diff --git a/src/test/run-pass/intrinsic-move-val.rs b/src/test/run-pass/intrinsic-move-val.rs index f1bbf353f71..fb04f67e380 100644 --- a/src/test/run-pass/intrinsic-move-val.rs +++ b/src/test/run-pass/intrinsic-move-val.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(intrinsics)] use std::mem::transmute; diff --git a/src/test/run-pass/issue-10682.rs b/src/test/run-pass/issue-10682.rs index fd0ad1ef47e..883e52b61d0 100644 --- a/src/test/run-pass/issue-10682.rs +++ b/src/test/run-pass/issue-10682.rs @@ -11,6 +11,9 @@ // Regression test for issue #10682 // Nested `proc` usage can't use outer owned data +#![allow(unknown_features)] +#![feature(box_syntax)] + fn work(_: Box<int>) {} fn foo<F:FnOnce()>(_: F) {} diff --git a/src/test/run-pass/issue-10767.rs b/src/test/run-pass/issue-10767.rs index d2895024187..c717053cffc 100644 --- a/src/test/run-pass/issue-10767.rs +++ b/src/test/run-pass/issue-10767.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { fn f() { diff --git a/src/test/run-pass/issue-10802.rs b/src/test/run-pass/issue-10802.rs index ab080834ac9..de2b4c51e52 100644 --- a/src/test/run-pass/issue-10802.rs +++ b/src/test/run-pass/issue-10802.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct DroppableStruct; enum DroppableEnum { DroppableVariant1, DroppableVariant2 diff --git a/src/test/run-pass/issue-11205.rs b/src/test/run-pass/issue-11205.rs index 549a70f19e3..194208620a8 100644 --- a/src/test/run-pass/issue-11205.rs +++ b/src/test/run-pass/issue-11205.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(dead_code)] +#![allow(unknown_features)] +#![feature(box_syntax)] trait Foo {} impl Foo for int {} diff --git a/src/test/run-pass/issue-11552.rs b/src/test/run-pass/issue-11552.rs index 92862961aca..f47f1e06011 100644 --- a/src/test/run-pass/issue-11552.rs +++ b/src/test/run-pass/issue-11552.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #[derive(Clone)] enum Noun diff --git a/src/test/run-pass/issue-11677.rs b/src/test/run-pass/issue-11677.rs index 14c1b1b06ea..6fa45058694 100644 --- a/src/test/run-pass/issue-11677.rs +++ b/src/test/run-pass/issue-11677.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(dead_code)] +#![allow(unknown_features)] +#![feature(box_syntax)] // this code used to cause an ICE diff --git a/src/test/run-pass/issue-12744.rs b/src/test/run-pass/issue-12744.rs index a91dbd2b716..ec929a9c792 100644 --- a/src/test/run-pass/issue-12744.rs +++ b/src/test/run-pass/issue-12744.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { fn test() -> Box<std::any::Any + 'static> { box 1i } println!("{:?}", test()) diff --git a/src/test/run-pass/issue-13323.rs b/src/test/run-pass/issue-13323.rs index b7cd8a90112..75d3c6f334d 100644 --- a/src/test/run-pass/issue-13323.rs +++ b/src/test/run-pass/issue-13323.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct StrWrap { s: String } diff --git a/src/test/run-pass/issue-13808.rs b/src/test/run-pass/issue-13808.rs index c0652b946db..3c5ece87b73 100644 --- a/src/test/run-pass/issue-13808.rs +++ b/src/test/run-pass/issue-13808.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Foo<'a> { listener: Box<FnMut() + 'a>, } diff --git a/src/test/run-pass/issue-14399.rs b/src/test/run-pass/issue-14399.rs index bb0fe6a87ab..7e533c2cf86 100644 --- a/src/test/run-pass/issue-14399.rs +++ b/src/test/run-pass/issue-14399.rs @@ -13,6 +13,9 @@ // value was coerced to a trait object. (v.clone() returns Box<B1> // which is coerced to Box<A>). +#![allow(unknown_features)] +#![feature(box_syntax)] + #[derive(Clone)] struct B1; diff --git a/src/test/run-pass/issue-14589.rs b/src/test/run-pass/issue-14589.rs index afc2fc6cf64..d9763baa826 100644 --- a/src/test/run-pass/issue-14589.rs +++ b/src/test/run-pass/issue-14589.rs @@ -11,6 +11,9 @@ // All 3 expressions should work in that the argument gets // coerced to a trait object +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { send::<Box<Foo>>(box Output(0)); Test::<Box<Foo>>::foo(box Output(0)); diff --git a/src/test/run-pass/issue-14919.rs b/src/test/run-pass/issue-14919.rs index 21bda93ecec..4d05b98147b 100644 --- a/src/test/run-pass/issue-14919.rs +++ b/src/test/run-pass/issue-14919.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait Matcher { fn next_match(&mut self) -> Option<(uint, uint)>; } diff --git a/src/test/run-pass/issue-15571.rs b/src/test/run-pass/issue-15571.rs index 03d18cf8c98..6b273b5786a 100644 --- a/src/test/run-pass/issue-15571.rs +++ b/src/test/run-pass/issue-15571.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn match_on_local() { let mut foo = Some(box 5i); match foo { diff --git a/src/test/run-pass/issue-15730.rs b/src/test/run-pass/issue-15730.rs index 4e1aa454a88..72daa0cba41 100644 --- a/src/test/run-pass/issue-15730.rs +++ b/src/test/run-pass/issue-15730.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - fn main() { let mut array = [1, 2, 3]; let pie_slice = &array[1..2]; diff --git a/src/test/run-pass/issue-15763.rs b/src/test/run-pass/issue-15763.rs index 48fdcb09080..283ea25b6fe 100644 --- a/src/test/run-pass/issue-15763.rs +++ b/src/test/run-pass/issue-15763.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #[derive(PartialEq, Show)] struct Bar { diff --git a/src/test/run-pass/issue-16668.rs b/src/test/run-pass/issue-16668.rs index 1febf337429..75b1e11ddc1 100644 --- a/src/test/run-pass/issue-16668.rs +++ b/src/test/run-pass/issue-16668.rs @@ -10,6 +10,8 @@ // ignore-pretty +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] struct Parser<'a, I, O> { diff --git a/src/test/run-pass/issue-16739.rs b/src/test/run-pass/issue-16739.rs index 552ce565f6b..cb6f068cf45 100644 --- a/src/test/run-pass/issue-16739.rs +++ b/src/test/run-pass/issue-16739.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] // Test that unboxing shim for calling rust-call ABI methods through a diff --git a/src/test/run-pass/issue-16774.rs b/src/test/run-pass/issue-16774.rs index 6ef4f868d21..175e2188811 100644 --- a/src/test/run-pass/issue-16774.rs +++ b/src/test/run-pass/issue-16774.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::ops::{Deref, DerefMut}; @@ -36,7 +38,7 @@ impl Deref for X { impl DerefMut for X { fn deref_mut(&mut self) -> &mut int { - let &X(box ref mut x) = self; + let &mut X(box ref mut x) = self; x } } diff --git a/src/test/run-pass/issue-17322.rs b/src/test/run-pass/issue-17322.rs index c5784154a2e..b50bf442b5d 100644 --- a/src/test/run-pass/issue-17322.rs +++ b/src/test/run-pass/issue-17322.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::io; fn f(wr: &mut Writer) { diff --git a/src/test/run-pass/issue-17503.rs b/src/test/run-pass/issue-17503.rs index 8acda175006..65bf088786e 100644 --- a/src/test/run-pass/issue-17503.rs +++ b/src/test/run-pass/issue-17503.rs @@ -8,14 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - fn main() { let s: &[int] = &[0, 1, 2, 3, 4]; let ss: &&[int] = &s; let sss: &&&[int] = &ss; - println!("{}", &s[0..3]); - println!("{}", &ss[3..]); - println!("{}", &sss[2..4]); + println!("{:?}", &s[0..3]); + println!("{:?}", &ss[3..]); + println!("{:?}", &sss[2..4]); } diff --git a/src/test/run-pass/issue-17734.rs b/src/test/run-pass/issue-17734.rs index f68ab01ea9b..e58fbe0b4c2 100644 --- a/src/test/run-pass/issue-17734.rs +++ b/src/test/run-pass/issue-17734.rs @@ -10,6 +10,9 @@ // Test that generating drop glue for Box<str> doesn't ICE +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f(s: Box<str>) -> Box<str> { s } diff --git a/src/test/run-pass/issue-18425.rs b/src/test/run-pass/issue-18425.rs index f61530c7418..6d223923ac1 100644 --- a/src/test/run-pass/issue-18425.rs +++ b/src/test/run-pass/issue-18425.rs @@ -11,6 +11,9 @@ // Check that trans doesn't ICE when translating an array repeat // expression with a count of 1 and a non-Copy element type. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn main() { let _ = [box 1u; 1]; } diff --git a/src/test/run-pass/issue-20644.rs b/src/test/run-pass/issue-20644.rs index 4a57ed56594..f74b09a3d24 100644 --- a/src/test/run-pass/issue-20644.rs +++ b/src/test/run-pass/issue-20644.rs @@ -11,7 +11,6 @@ // A reduced version of the rustbook ice. The problem this encountered // had to do with trans ignoring binders. -#![feature(slicing_syntax)] #![feature(associated_types)] #![feature(macro_rules)] diff --git a/src/test/run-pass/issue-2288.rs b/src/test/run-pass/issue-2288.rs index 1f371f0a1c2..7baead6929b 100644 --- a/src/test/run-pass/issue-2288.rs +++ b/src/test/run-pass/issue-2288.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait clam<A> { fn chowder(&self, y: A); diff --git a/src/test/run-pass/issue-2633-2.rs b/src/test/run-pass/issue-2633-2.rs index e2a03c696f2..c146f8a7a9a 100644 --- a/src/test/run-pass/issue-2633-2.rs +++ b/src/test/run-pass/issue-2633-2.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn a_val(x: Box<int>, y: Box<int>) -> int { *x + *y diff --git a/src/test/run-pass/issue-2708.rs b/src/test/run-pass/issue-2708.rs index 3ac4b874f3a..1f072af0f5a 100644 --- a/src/test/run-pass/issue-2708.rs +++ b/src/test/run-pass/issue-2708.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Font { fontbuf: uint, diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index 3ca3e0592e7..6f5f46edc01 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -11,6 +11,8 @@ // // ignore-lexer-test FIXME #15883 +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unsafe_destructor)] pub type Task = int; diff --git a/src/test/run-pass/issue-2734.rs b/src/test/run-pass/issue-2734.rs index 9eec2d048d4..3e4cffe5dfa 100644 --- a/src/test/run-pass/issue-2734.rs +++ b/src/test/run-pass/issue-2734.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait hax { } impl<A> hax for A { } diff --git a/src/test/run-pass/issue-2735.rs b/src/test/run-pass/issue-2735.rs index 74b64bb87cf..cb376d0e439 100644 --- a/src/test/run-pass/issue-2735.rs +++ b/src/test/run-pass/issue-2735.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait hax { } impl<A> hax for A { } diff --git a/src/test/run-pass/issue-2935.rs b/src/test/run-pass/issue-2935.rs index cdc41e892f9..295fd538de6 100644 --- a/src/test/run-pass/issue-2935.rs +++ b/src/test/run-pass/issue-2935.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] //type t = { a: int }; // type t = { a: bool }; diff --git a/src/test/run-pass/issue-3012-2.rs b/src/test/run-pass/issue-3012-2.rs index aa2ce824822..de2d4374d78 100644 --- a/src/test/run-pass/issue-3012-2.rs +++ b/src/test/run-pass/issue-3012-2.rs @@ -10,6 +10,8 @@ // aux-build:issue-3012-1.rs +#![allow(unknown_features)] +#![feature(box_syntax)] extern crate socketlib; extern crate libc; diff --git a/src/test/run-pass/issue-3026.rs b/src/test/run-pass/issue-3026.rs index b30c0a117a8..cd71bfce274 100644 --- a/src/test/run-pass/issue-3026.rs +++ b/src/test/run-pass/issue-3026.rs @@ -9,6 +9,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + extern crate collections; use std::collections::HashMap; diff --git a/src/test/run-pass/issue-3052.rs b/src/test/run-pass/issue-3052.rs index 72cf2219bb6..c08bdf54408 100644 --- a/src/test/run-pass/issue-3052.rs +++ b/src/test/run-pass/issue-3052.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] type Connection = Box<FnMut(Vec<u8>) + 'static>; diff --git a/src/test/run-pass/issue-3121.rs b/src/test/run-pass/issue-3121.rs index 9e9d611f1a3..c789921f622 100644 --- a/src/test/run-pass/issue-3121.rs +++ b/src/test/run-pass/issue-3121.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] enum side { mayo, catsup, vinegar } enum order { hamburger, fries(side), shake } diff --git a/src/test/run-pass/issue-3290.rs b/src/test/run-pass/issue-3290.rs index 139d984b507..a72b272abaa 100644 --- a/src/test/run-pass/issue-3290.rs +++ b/src/test/run-pass/issue-3290.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut x = box 3i; x = x; diff --git a/src/test/run-pass/issue-3424.rs b/src/test/run-pass/issue-3424.rs index 528870d0334..6647fbe2238 100644 --- a/src/test/run-pass/issue-3424.rs +++ b/src/test/run-pass/issue-3424.rs @@ -11,6 +11,8 @@ // rustc --test ignores2.rs && ./ignores2 +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::path::{Path}; diff --git a/src/test/run-pass/issue-3447.rs b/src/test/run-pass/issue-3447.rs index 4ebf981e4ee..12c2155dd57 100644 --- a/src/test/run-pass/issue-3447.rs +++ b/src/test/run-pass/issue-3447.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] use std::cell::RefCell; diff --git a/src/test/run-pass/issue-3609.rs b/src/test/run-pass/issue-3609.rs index c3cfaf22dee..56eb7486c92 100644 --- a/src/test/run-pass/issue-3609.rs +++ b/src/test/run-pass/issue-3609.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; use std::sync::mpsc::Sender; use std::thunk::Invoke; diff --git a/src/test/run-pass/issue-3794.rs b/src/test/run-pass/issue-3794.rs index 926b53cf92c..91c938981c1 100644 --- a/src/test/run-pass/issue-3794.rs +++ b/src/test/run-pass/issue-3794.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait T { fn print(&self); } diff --git a/src/test/run-pass/issue-3878.rs b/src/test/run-pass/issue-3878.rs index 063b2d70301..5434e44c173 100644 --- a/src/test/run-pass/issue-3878.rs +++ b/src/test/run-pass/issue-3878.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(path_statement)] +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let y = box 1i; diff --git a/src/test/run-pass/issue-3888-2.rs b/src/test/run-pass/issue-3888-2.rs index 5ed9729c142..bf3d0b786af 100644 --- a/src/test/run-pass/issue-3888-2.rs +++ b/src/test/run-pass/issue-3888-2.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] { &v[1..5] } diff --git a/src/test/run-pass/issue-4464.rs b/src/test/run-pass/issue-4464.rs index 2581069d29b..33a5c7a167f 100644 --- a/src/test/run-pass/issue-4464.rs +++ b/src/test/run-pass/issue-4464.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] } pub fn main() {} diff --git a/src/test/run-pass/issue-4735.rs b/src/test/run-pass/issue-4735.rs index 7730d75a3a9..bf422bd0405 100644 --- a/src/test/run-pass/issue-4735.rs +++ b/src/test/run-pass/issue-4735.rs @@ -10,6 +10,9 @@ // ignore-fast doesn't like extern crate +#![allow(unknown_features)] +#![feature(box_syntax)] + extern crate libc; use std::mem::transmute; diff --git a/src/test/run-pass/issue-4759.rs b/src/test/run-pass/issue-4759.rs index 4b5c3566965..2245e80971a 100644 --- a/src/test/run-pass/issue-4759.rs +++ b/src/test/run-pass/issue-4759.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct T { a: Box<int> } diff --git a/src/test/run-pass/issue-5192.rs b/src/test/run-pass/issue-5192.rs index 3b1a8c4a190..bb79cd4d046 100644 --- a/src/test/run-pass/issue-5192.rs +++ b/src/test/run-pass/issue-5192.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub trait EventLoop { } diff --git a/src/test/run-pass/issue-5666.rs b/src/test/run-pass/issue-5666.rs index 222e1d54a5d..e53f4c86923 100644 --- a/src/test/run-pass/issue-5666.rs +++ b/src/test/run-pass/issue-5666.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Dog { name : String diff --git a/src/test/run-pass/issue-5688.rs b/src/test/run-pass/issue-5688.rs index 7c8940aafbf..cfe9c8f994c 100644 --- a/src/test/run-pass/issue-5688.rs +++ b/src/test/run-pass/issue-5688.rs @@ -25,6 +25,6 @@ static V: &'static [X] = &[X { vec: &[1, 2, 3] }]; pub fn main() { for &v in V.iter() { - println!("{}", v.vec); + println!("{:?}", v.vec); } } diff --git a/src/test/run-pass/issue-5718.rs b/src/test/run-pass/issue-5718.rs index 589ccefd9ea..36aa8a9cbca 100644 --- a/src/test/run-pass/issue-5718.rs +++ b/src/test/run-pass/issue-5718.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Element; macro_rules! foo { diff --git a/src/test/run-pass/issue-5884.rs b/src/test/run-pass/issue-5884.rs index 4010c31eed5..6502c66d858 100644 --- a/src/test/run-pass/issue-5884.rs +++ b/src/test/run-pass/issue-5884.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub struct Foo { a: int, diff --git a/src/test/run-pass/issue-6117.rs b/src/test/run-pass/issue-6117.rs index e979bc86171..85de03dfe34 100644 --- a/src/test/run-pass/issue-6117.rs +++ b/src/test/run-pass/issue-6117.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] enum Either<T, U> { Left(T), Right(U) } diff --git a/src/test/run-pass/issue-6128.rs b/src/test/run-pass/issue-6128.rs index 4b31f393309..d96862b588f 100644 --- a/src/test/run-pass/issue-6128.rs +++ b/src/test/run-pass/issue-6128.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + extern crate collections; use std::collections::HashMap; diff --git a/src/test/run-pass/issue-6318.rs b/src/test/run-pass/issue-6318.rs index 2b474b8cfbb..b9f1a8bda7b 100644 --- a/src/test/run-pass/issue-6318.rs +++ b/src/test/run-pass/issue-6318.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub enum Thing { A(Box<Foo+'static>) diff --git a/src/test/run-pass/issue-6557.rs b/src/test/run-pass/issue-6557.rs index 7061a17dcdd..3163f139328 100644 --- a/src/test/run-pass/issue-6557.rs +++ b/src/test/run-pass/issue-6557.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo(box (_x, _y): Box<(int, int)>) {} diff --git a/src/test/run-pass/issue-7673-cast-generically-implemented-trait.rs b/src/test/run-pass/issue-7673-cast-generically-implemented-trait.rs index a08bdb09d3d..b6dfbb1ca42 100644 --- a/src/test/run-pass/issue-7673-cast-generically-implemented-trait.rs +++ b/src/test/run-pass/issue-7673-cast-generically-implemented-trait.rs @@ -14,6 +14,8 @@ */ +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() {} diff --git a/src/test/run-pass/issue-8498.rs b/src/test/run-pass/issue-8498.rs index e4f4db6ea63..2a2ca4f0712 100644 --- a/src/test/run-pass/issue-8498.rs +++ b/src/test/run-pass/issue-8498.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { match &[(box 5i,box 7i)] { ps => { diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index 0ca63d52bd8..42739628eed 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - fn assert_repr_eq<T: std::fmt::Show>(obj : T, expected : String) { assert_eq!(expected, format!("{:?}", obj)); } diff --git a/src/test/run-pass/issue-9129.rs b/src/test/run-pass/issue-9129.rs index 5d5240272e5..2ef1c1d264a 100644 --- a/src/test/run-pass/issue-9129.rs +++ b/src/test/run-pass/issue-9129.rs @@ -10,6 +10,8 @@ // ignore-pretty +#![allow(unknown_features)] +#![feature(box_syntax)] pub trait bomb { fn boom(&self, Ident); } pub struct S; diff --git a/src/test/run-pass/issue-9382.rs b/src/test/run-pass/issue-9382.rs index 369f93222e1..07212237305 100644 --- a/src/test/run-pass/issue-9382.rs +++ b/src/test/run-pass/issue-9382.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(unnecessary_allocation)] +#![allow(unknown_features)] +#![feature(box_syntax)] // Tests for a previous bug that occurred due to an interaction // between struct field initialization and the auto-coercion diff --git a/src/test/run-pass/issue-9396.rs b/src/test/run-pass/issue-9396.rs index 34bb50c5cf6..73355d15a27 100644 --- a/src/test/run-pass/issue-9396.rs +++ b/src/test/run-pass/issue-9396.rs @@ -15,7 +15,7 @@ use std::time::Duration; pub fn main() { let (tx, rx) = channel(); - let _t = Thread::spawn(move||{ + let _t = Thread::scoped(move||{ let mut timer = Timer::new().unwrap(); timer.sleep(Duration::milliseconds(10)); tx.send(()).unwrap(); diff --git a/src/test/run-pass/kindck-owned-trait-contains-1.rs b/src/test/run-pass/kindck-owned-trait-contains-1.rs index fbd6c92a020..999fb2c4b69 100644 --- a/src/test/run-pass/kindck-owned-trait-contains-1.rs +++ b/src/test/run-pass/kindck-owned-trait-contains-1.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait repeat<A> { fn get(&self) -> A; } diff --git a/src/test/run-pass/last-use-in-cap-clause.rs b/src/test/run-pass/last-use-in-cap-clause.rs index 6615bb6368f..9be9f098264 100644 --- a/src/test/run-pass/last-use-in-cap-clause.rs +++ b/src/test/run-pass/last-use-in-cap-clause.rs @@ -10,6 +10,8 @@ // Make sure #1399 stays fixed +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] struct A { a: Box<int> } diff --git a/src/test/run-pass/last-use-is-capture.rs b/src/test/run-pass/last-use-is-capture.rs index 206d4db3db4..4a7e844268f 100644 --- a/src/test/run-pass/last-use-is-capture.rs +++ b/src/test/run-pass/last-use-is-capture.rs @@ -10,6 +10,9 @@ // Make sure #1399 stays fixed +#![allow(unknown_features)] +#![feature(box_syntax)] + struct A { a: Box<int> } pub fn main() { diff --git a/src/test/run-pass/leak-unique-as-tydesc.rs b/src/test/run-pass/leak-unique-as-tydesc.rs index b109e94b74f..65808de3cf4 100644 --- a/src/test/run-pass/leak-unique-as-tydesc.rs +++ b/src/test/run-pass/leak-unique-as-tydesc.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn leaky<T>(_t: T) { } diff --git a/src/test/run-pass/let-assignability.rs b/src/test/run-pass/let-assignability.rs index 6bea1aebc45..9ac016d534f 100644 --- a/src/test/run-pass/let-assignability.rs +++ b/src/test/run-pass/let-assignability.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f() { let a = box 1; let b: &int = &*a; diff --git a/src/test/run-pass/list.rs b/src/test/run-pass/list.rs index 9b20398038d..e55c1b36f3e 100644 --- a/src/test/run-pass/list.rs +++ b/src/test/run-pass/list.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] enum list { cons(int, Box<list>), nil, } diff --git a/src/test/run-pass/match-implicit-copy-unique.rs b/src/test/run-pass/match-implicit-copy-unique.rs index 0e7c959d58c..6883187c402 100644 --- a/src/test/run-pass/match-implicit-copy-unique.rs +++ b/src/test/run-pass/match-implicit-copy-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Pair { a: Box<int>, b: Box<int> } diff --git a/src/test/run-pass/match-unique-bind.rs b/src/test/run-pass/match-unique-bind.rs index 5c834a06a74..ebe01a1d1f2 100644 --- a/src/test/run-pass/match-unique-bind.rs +++ b/src/test/run-pass/match-unique-bind.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { match box 100i { box x => { diff --git a/src/test/run-pass/match-value-binding-in-guard-3291.rs b/src/test/run-pass/match-value-binding-in-guard-3291.rs index 0e7e9be6765..beb125492b2 100644 --- a/src/test/run-pass/match-value-binding-in-guard-3291.rs +++ b/src/test/run-pass/match-value-binding-in-guard-3291.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo(x: Option<Box<int>>, b: bool) -> int { match x { diff --git a/src/test/run-pass/method-projection.rs b/src/test/run-pass/method-projection.rs new file mode 100644 index 00000000000..6f72a163981 --- /dev/null +++ b/src/test/run-pass/method-projection.rs @@ -0,0 +1,78 @@ +// 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. + +// Test that we can use method notation to call methods based on a +// projection bound from a trait. Issue #20469. + +/////////////////////////////////////////////////////////////////////////// + +trait MakeString { + fn make_string(&self) -> String; +} + +impl MakeString for int { + fn make_string(&self) -> String { + format!("{}", *self) + } +} + +impl MakeString for uint { + fn make_string(&self) -> String { + format!("{}", *self) + } +} + +/////////////////////////////////////////////////////////////////////////// + +trait Foo { + type F: MakeString; + + fn get(&self) -> &Self::F; +} + +fn foo<F:Foo>(f: &F) -> String { + f.get().make_string() +} + +/////////////////////////////////////////////////////////////////////////// + +struct SomeStruct { + field: int, +} + +impl Foo for SomeStruct { + type F = int; + + fn get(&self) -> &int { + &self.field + } +} + +/////////////////////////////////////////////////////////////////////////// + +struct SomeOtherStruct { + field: uint, +} + +impl Foo for SomeOtherStruct { + type F = uint; + + fn get(&self) -> &uint { + &self.field + } +} + +fn main() { + let x = SomeStruct { field: 22 }; + assert_eq!(foo(&x), format!("22")); + + let x = SomeOtherStruct { field: 44 }; + assert_eq!(foo(&x), format!("44")); +} diff --git a/src/test/run-pass/method-self-arg-aux1.rs b/src/test/run-pass/method-self-arg-aux1.rs index d4a0d514a7d..e9a1e19d4bf 100644 --- a/src/test/run-pass/method-self-arg-aux1.rs +++ b/src/test/run-pass/method-self-arg-aux1.rs @@ -10,6 +10,9 @@ // Test method calls with self as an argument (cross-crate) +#![allow(unknown_features)] +#![feature(box_syntax)] + // aux-build:method_self_arg1.rs extern crate method_self_arg1; use method_self_arg1::Foo; diff --git a/src/test/run-pass/method-self-arg-aux2.rs b/src/test/run-pass/method-self-arg-aux2.rs index b94f1ae6ba6..7fa810ce154 100644 --- a/src/test/run-pass/method-self-arg-aux2.rs +++ b/src/test/run-pass/method-self-arg-aux2.rs @@ -10,6 +10,9 @@ // Test method calls with self as an argument (cross-crate) +#![allow(unknown_features)] +#![feature(box_syntax)] + // aux-build:method_self_arg2.rs extern crate method_self_arg2; use method_self_arg2::{Foo, Bar}; diff --git a/src/test/run-pass/method-self-arg-trait.rs b/src/test/run-pass/method-self-arg-trait.rs index 29d100beb06..39018a87394 100644 --- a/src/test/run-pass/method-self-arg-trait.rs +++ b/src/test/run-pass/method-self-arg-trait.rs @@ -10,6 +10,9 @@ // Test method calls with self as an argument +#![allow(unknown_features)] +#![feature(box_syntax)] + static mut COUNT: u64 = 1; struct Foo; diff --git a/src/test/run-pass/method-self-arg.rs b/src/test/run-pass/method-self-arg.rs index 788a25efcf9..ae15bc60746 100644 --- a/src/test/run-pass/method-self-arg.rs +++ b/src/test/run-pass/method-self-arg.rs @@ -10,6 +10,9 @@ // Test method calls with self as an argument +#![allow(unknown_features)] +#![feature(box_syntax)] + static mut COUNT: uint = 1; struct Foo; diff --git a/src/test/run-pass/method-two-trait-defer-resolution-2.rs b/src/test/run-pass/method-two-trait-defer-resolution-2.rs index cae783e7ea8..b18c29dc3c1 100644 --- a/src/test/run-pass/method-two-trait-defer-resolution-2.rs +++ b/src/test/run-pass/method-two-trait-defer-resolution-2.rs @@ -16,6 +16,9 @@ // version will run (note that the `push` occurs after the call to // `foo()`). +#![allow(unknown_features)] +#![feature(box_syntax)] + trait Foo { fn foo(&self) -> int; } diff --git a/src/test/run-pass/move-1-unique.rs b/src/test/run-pass/move-1-unique.rs index 2da6076d138..018cd440cad 100644 --- a/src/test/run-pass/move-1-unique.rs +++ b/src/test/run-pass/move-1-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #[derive(Clone)] struct Triple { diff --git a/src/test/run-pass/move-2-unique.rs b/src/test/run-pass/move-2-unique.rs index 65d8281407c..50187ef8baa 100644 --- a/src/test/run-pass/move-2-unique.rs +++ b/src/test/run-pass/move-2-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct X { x: int, y: int, z: int } diff --git a/src/test/run-pass/move-2.rs b/src/test/run-pass/move-2.rs index 04540c2f35b..6561a9b2d5b 100644 --- a/src/test/run-pass/move-2.rs +++ b/src/test/run-pass/move-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct X { x: int, y: int, z: int } diff --git a/src/test/run-pass/move-3-unique.rs b/src/test/run-pass/move-3-unique.rs index 2820e0d7120..a10e3f9f5b0 100644 --- a/src/test/run-pass/move-3-unique.rs +++ b/src/test/run-pass/move-3-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #[derive(Clone)] struct Triple { diff --git a/src/test/run-pass/move-4-unique.rs b/src/test/run-pass/move-4-unique.rs index 286781a4822..9e5eeef7552 100644 --- a/src/test/run-pass/move-4-unique.rs +++ b/src/test/run-pass/move-4-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Triple {a: int, b: int, c: int} diff --git a/src/test/run-pass/move-4.rs b/src/test/run-pass/move-4.rs index 5e5d01ae6ee..c902677c645 100644 --- a/src/test/run-pass/move-4.rs +++ b/src/test/run-pass/move-4.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Triple { a: int, b: int, c: int } diff --git a/src/test/run-pass/move-arg-2-unique.rs b/src/test/run-pass/move-arg-2-unique.rs index 29fd070fc19..e496e9e2105 100644 --- a/src/test/run-pass/move-arg-2-unique.rs +++ b/src/test/run-pass/move-arg-2-unique.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn test(foo: Box<Vec<int>> ) { assert!(((*foo)[0] == 10)); } diff --git a/src/test/run-pass/move-arg-2.rs b/src/test/run-pass/move-arg-2.rs index 0f3d0baecbe..fdb6799b90f 100644 --- a/src/test/run-pass/move-arg-2.rs +++ b/src/test/run-pass/move-arg-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn test(foo: Box<Vec<int>>) { assert!(((*foo)[0] == 10)); } diff --git a/src/test/run-pass/mut-function-arguments.rs b/src/test/run-pass/mut-function-arguments.rs index f8072851913..388b814b2af 100644 --- a/src/test/run-pass/mut-function-arguments.rs +++ b/src/test/run-pass/mut-function-arguments.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn f(mut y: Box<int>) { *y = 5; diff --git a/src/test/run-pass/new-box-syntax.rs b/src/test/run-pass/new-box-syntax.rs index 991d0ecdc87..4ea51b3b409 100644 --- a/src/test/run-pass/new-box-syntax.rs +++ b/src/test/run-pass/new-box-syntax.rs @@ -11,6 +11,9 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ +#![allow(unknown_features)] +#![feature(box_syntax)] + // Tests that the new `box` syntax works with unique pointers. use std::boxed::{Box, HEAP}; diff --git a/src/test/run-pass/new-box.rs b/src/test/run-pass/new-box.rs index 8531fd5f975..1f2207ad873 100644 --- a/src/test/run-pass/new-box.rs +++ b/src/test/run-pass/new-box.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn f(x: Box<int>) { let y: &int = &*x; diff --git a/src/test/run-pass/newlambdas-ret-infer.rs b/src/test/run-pass/newlambdas-ret-infer.rs index d74f1349506..130cdc85b01 100644 --- a/src/test/run-pass/newlambdas-ret-infer.rs +++ b/src/test/run-pass/newlambdas-ret-infer.rs @@ -11,6 +11,9 @@ // Test that the lambda kind is inferred correctly as a return // expression +#![allow(unknown_features)] +#![feature(box_syntax)] + fn unique() -> Box<FnMut()+'static> { return box || (); } pub fn main() { diff --git a/src/test/run-pass/newlambdas-ret-infer2.rs b/src/test/run-pass/newlambdas-ret-infer2.rs index 43a6ac296e9..0952bedd6e3 100644 --- a/src/test/run-pass/newlambdas-ret-infer2.rs +++ b/src/test/run-pass/newlambdas-ret-infer2.rs @@ -11,6 +11,9 @@ // Test that the lambda kind is inferred correctly as a return // expression +#![allow(unknown_features)] +#![feature(box_syntax)] + fn unique() -> Box<FnMut()+'static> { box || () } pub fn main() { diff --git a/src/test/run-pass/nullable-pointer-iotareduction.rs b/src/test/run-pass/nullable-pointer-iotareduction.rs index 0293c4e36ac..bb62b1599a4 100644 --- a/src/test/run-pass/nullable-pointer-iotareduction.rs +++ b/src/test/run-pass/nullable-pointer-iotareduction.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::{option, mem}; // Iota-reduction is a rule in the Calculus of (Co-)Inductive Constructions, diff --git a/src/test/run-pass/object-one-type-two-traits.rs b/src/test/run-pass/object-one-type-two-traits.rs index 4964b3f6728..ebdf3c08a22 100644 --- a/src/test/run-pass/object-one-type-two-traits.rs +++ b/src/test/run-pass/object-one-type-two-traits.rs @@ -11,6 +11,9 @@ // Testing creating two vtables with the same self type, but different // traits. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::any::Any; trait Wrap { diff --git a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs index ab3d39e2733..cd97c34f8c6 100644 --- a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs +++ b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs @@ -12,6 +12,9 @@ // closed over do not contain managed values, and thus the boxes do // not have headers. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait FooTrait { fn foo(&self) -> uint; diff --git a/src/test/run-pass/objects-owned-object-owned-method.rs b/src/test/run-pass/objects-owned-object-owned-method.rs index 14ddc5d660f..d355999c506 100644 --- a/src/test/run-pass/objects-owned-object-owned-method.rs +++ b/src/test/run-pass/objects-owned-object-owned-method.rs @@ -12,6 +12,8 @@ // closed over contain managed values. This implies that the boxes // will have headers that must be skipped over. +#![allow(unknown_features)] +#![feature(box_syntax)] trait FooTrait { fn foo(self: Box<Self>) -> uint; diff --git a/src/test/run-pass/opt-out-copy.rs b/src/test/run-pass/opt-out-copy.rs deleted file mode 100644 index 8c7072cfdf5..00000000000 --- a/src/test/run-pass/opt-out-copy.rs +++ /dev/null @@ -1,46 +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. - -#![feature(opt_out_copy)] - -// Test the opt-out-copy feature guard. This is the same as the -// "opt-in-copy.rs" test from compile-fail, except that it is using -// the feature guard, and hence the structureds in this file are -// implicitly copyable, and hence we get no errors. This test can be -// safely removed once the opt-out-copy "feature" is rejected. - -struct CantCopyThis; - -struct IWantToCopyThis { - but_i_cant: CantCopyThis, -} - -impl Copy for IWantToCopyThis {} - -enum CantCopyThisEither { - A, - B, -} - -enum IWantToCopyThisToo { - ButICant(CantCopyThisEither), -} - -impl Copy for IWantToCopyThisToo {} - -fn is_copy<T:Copy>() { } - -fn main() { - is_copy::<CantCopyThis>(); - is_copy::<CantCopyThisEither>(); - is_copy::<IWantToCopyThis>(); - is_copy::<IWantToCopyThisToo>(); -} - diff --git a/src/test/run-pass/output-slot-variants.rs b/src/test/run-pass/output-slot-variants.rs index 8a10cc8c1ef..fb87cd5eb69 100644 --- a/src/test/run-pass/output-slot-variants.rs +++ b/src/test/run-pass/output-slot-variants.rs @@ -10,6 +10,8 @@ #![allow(dead_assignment)] #![allow(unused_variable)] +#![allow(unknown_features)] +#![feature(box_syntax)] struct A { a: int, b: int } struct Abox { a: Box<int>, b: Box<int> } diff --git a/src/test/run-pass/overloaded-autoderef.rs b/src/test/run-pass/overloaded-autoderef.rs index 949a7b158d4..5831d500b83 100644 --- a/src/test/run-pass/overloaded-autoderef.rs +++ b/src/test/run-pass/overloaded-autoderef.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::cell::RefCell; use std::rc::Rc; use std::num::ToPrimitive; diff --git a/src/test/run-pass/overloaded-deref.rs b/src/test/run-pass/overloaded-deref.rs index 1251394a549..a2cc7b7dfea 100644 --- a/src/test/run-pass/overloaded-deref.rs +++ b/src/test/run-pass/overloaded-deref.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::cell::RefCell; use std::rc::Rc; use std::string::String; diff --git a/src/test/run-pass/overloaded-index-autoderef.rs b/src/test/run-pass/overloaded-index-autoderef.rs index bc67c0afc7b..637d2c94694 100644 --- a/src/test/run-pass/overloaded-index-autoderef.rs +++ b/src/test/run-pass/overloaded-index-autoderef.rs @@ -10,6 +10,9 @@ // Test overloaded indexing combined with autoderef. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::ops::{Index, IndexMut}; struct Foo { diff --git a/src/test/run-pass/owned-implies-static.rs b/src/test/run-pass/owned-implies-static.rs index 498b81d307e..e784318fc76 100644 --- a/src/test/run-pass/owned-implies-static.rs +++ b/src/test/run-pass/owned-implies-static.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f<T: 'static>(_x: T) {} pub fn main() { diff --git a/src/test/run-pass/pure-sum.rs b/src/test/run-pass/pure-sum.rs index 3b2897cf3a6..7fbdd2f219e 100644 --- a/src/test/run-pass/pure-sum.rs +++ b/src/test/run-pass/pure-sum.rs @@ -10,6 +10,8 @@ // Check that functions can modify local state. +#![allow(unknown_features)] +#![feature(box_syntax)] fn sums_to(v: Vec<int> , sum: int) -> bool { let mut i = 0u; diff --git a/src/test/run-pass/range.rs b/src/test/run-pass/range.rs index 43b6d4b3109..90e87168990 100644 --- a/src/test/run-pass/range.rs +++ b/src/test/run-pass/range.rs @@ -10,8 +10,6 @@ // Test range syntax. -#![feature(slicing_syntax)] - fn foo() -> int { 42 } pub fn main() { diff --git a/src/test/run-pass/ranges-precedence.rs b/src/test/run-pass/ranges-precedence.rs new file mode 100644 index 00000000000..f678eed8775 --- /dev/null +++ b/src/test/run-pass/ranges-precedence.rs @@ -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. + +// Test that the precedence of ranges is correct + +#![feature(slicing_syntax)] + +struct Foo { + foo: uint, +} + +impl Foo { + fn bar(&self) -> uint { 5 } +} + +fn main() { + let x = 1+3..4+5; + assert!(x == (4..9)); + + let x = 1..4+5; + assert!(x == (1..9)); + + let x = 1+3..4; + assert!(x == (4..4)); + + let a = Foo { foo: 3 }; + let x = a.foo..a.bar(); + assert!(x == (3..5)); + + let x = 1+3..; + assert!(x == (4..)); + let x = ..1+3; + assert!(x == (..4)); + + let a = &[0i32, 1, 2, 3, 4, 5, 6]; + let x = &a[1+1..2+2]; + assert!(x == &a[2..4]); + let x = &a[..1+2]; + assert!(x == &a[..3]); + let x = &a[1+2..]; + assert!(x == &a[3..]); + + for _i in 2+4..10-3 {} +} + diff --git a/src/test/run-pass/rcvr-borrowed-to-region.rs b/src/test/run-pass/rcvr-borrowed-to-region.rs index 8ad2dbc1acb..84a230fd576 100644 --- a/src/test/run-pass/rcvr-borrowed-to-region.rs +++ b/src/test/run-pass/rcvr-borrowed-to-region.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait get { fn get(self) -> int; diff --git a/src/test/run-pass/regions-borrow-at.rs b/src/test/run-pass/regions-borrow-at.rs index 9a758c5d8ad..ba86e3f7b57 100644 --- a/src/test/run-pass/regions-borrow-at.rs +++ b/src/test/run-pass/regions-borrow-at.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo(x: &uint) -> uint { *x diff --git a/src/test/run-pass/regions-borrow-uniq.rs b/src/test/run-pass/regions-borrow-uniq.rs index 36f7d88f7d7..30a22512d2a 100644 --- a/src/test/run-pass/regions-borrow-uniq.rs +++ b/src/test/run-pass/regions-borrow-uniq.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn foo(x: &uint) -> uint { *x } diff --git a/src/test/run-pass/regions-close-over-type-parameter-successfully.rs b/src/test/run-pass/regions-close-over-type-parameter-successfully.rs index 5dba80ad38a..3922cb1219c 100644 --- a/src/test/run-pass/regions-close-over-type-parameter-successfully.rs +++ b/src/test/run-pass/regions-close-over-type-parameter-successfully.rs @@ -11,6 +11,9 @@ // A test where we (successfully) close over a reference into // an object. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait SomeTrait { fn get(&self) -> int; } impl<'a> SomeTrait for &'a int { diff --git a/src/test/run-pass/regions-copy-closure.rs b/src/test/run-pass/regions-copy-closure.rs index a7724e68310..0152793d96c 100644 --- a/src/test/run-pass/regions-copy-closure.rs +++ b/src/test/run-pass/regions-copy-closure.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { diff --git a/src/test/run-pass/regions-dependent-addr-of.rs b/src/test/run-pass/regions-dependent-addr-of.rs index 41396ef01be..e38a472fa4c 100644 --- a/src/test/run-pass/regions-dependent-addr-of.rs +++ b/src/test/run-pass/regions-dependent-addr-of.rs @@ -11,6 +11,8 @@ // Test lifetimes are linked properly when we create dependent region pointers. // Issue #3148. +#![allow(unknown_features)] +#![feature(box_syntax)] struct A { value: B diff --git a/src/test/run-pass/regions-early-bound-trait-param.rs b/src/test/run-pass/regions-early-bound-trait-param.rs index 907f610ff25..3267ff2c7e0 100644 --- a/src/test/run-pass/regions-early-bound-trait-param.rs +++ b/src/test/run-pass/regions-early-bound-trait-param.rs @@ -11,6 +11,8 @@ // Tests that you can use an early-bound lifetime parameter as // on of the generic parameters in a trait. +#![allow(unknown_features)] +#![feature(box_syntax)] trait Trait<'a> { fn long(&'a self) -> int; diff --git a/src/test/run-pass/regions-escape-into-other-fn.rs b/src/test/run-pass/regions-escape-into-other-fn.rs index 5b0b7cc5b4e..9637c43170f 100644 --- a/src/test/run-pass/regions-escape-into-other-fn.rs +++ b/src/test/run-pass/regions-escape-into-other-fn.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn foo(x: &uint) -> &uint { x } fn bar(x: &uint) -> uint { *x } diff --git a/src/test/run-pass/regions-fn-subtyping.rs b/src/test/run-pass/regions-fn-subtyping.rs index e9f774150dc..faa9b37bdcc 100644 --- a/src/test/run-pass/regions-fn-subtyping.rs +++ b/src/test/run-pass/regions-fn-subtyping.rs @@ -12,6 +12,8 @@ #![allow(dead_assignment)] #![allow(unused_variable)] +#![allow(unknown_features)] +#![feature(box_syntax)] // Should pass region checking. fn ok(f: Box<FnMut(&uint)>) { diff --git a/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs b/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs index 1ecaf41702e..f397b5124ca 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn borrow<T>(x: &T) -> &T {x} pub fn main() { diff --git a/src/test/run-pass/regions-infer-borrow-scope.rs b/src/test/run-pass/regions-infer-borrow-scope.rs index d3dbca53f60..708d031a68a 100644 --- a/src/test/run-pass/regions-infer-borrow-scope.rs +++ b/src/test/run-pass/regions-infer-borrow-scope.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Point {x: int, y: int} diff --git a/src/test/run-pass/regions-lifetime-nonfree-late-bound.rs b/src/test/run-pass/regions-lifetime-nonfree-late-bound.rs index c796566b79d..c4852c9162c 100644 --- a/src/test/run-pass/regions-lifetime-nonfree-late-bound.rs +++ b/src/test/run-pass/regions-lifetime-nonfree-late-bound.rs @@ -22,6 +22,9 @@ // doing region-folding, when really all clients of the region-folding // case only want to see FREE lifetime variables, not bound ones. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { fn explicit() { fn test<F>(_x: Option<Box<F>>) where F: FnMut(Box<for<'a> FnMut(&'a int)>) {} diff --git a/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs b/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs index 6eb98104616..e779e002b29 100644 --- a/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs +++ b/src/test/run-pass/regions-relate-bound-regions-on-closures-to-inference-variables.rs @@ -17,6 +17,9 @@ // changes were caught. However, those uses in the compiler could // easily get changed or refactored away in the future. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Ctxt<'tcx> { x: &'tcx Vec<int> } diff --git a/src/test/run-pass/regions-static-closure.rs b/src/test/run-pass/regions-static-closure.rs index 0f36dc04575..abd5789bb1f 100644 --- a/src/test/run-pass/regions-static-closure.rs +++ b/src/test/run-pass/regions-static-closure.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] struct closure_box<'a> { diff --git a/src/test/run-pass/repeated-vector-syntax.rs b/src/test/run-pass/repeated-vector-syntax.rs index e854a732632..d1d37ea5bb0 100644 --- a/src/test/run-pass/repeated-vector-syntax.rs +++ b/src/test/run-pass/repeated-vector-syntax.rs @@ -8,16 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(slicing_syntax)] - pub fn main() { let x = [ [true]; 512 ]; let y = [ 0i; 1 ]; print!("["); for xi in x.iter() { - print!("{}, ", &xi[]); + print!("{:?}, ", &xi[]); } println!("]"); - println!("{}", &y[]); + println!("{:?}", &y[]); } diff --git a/src/test/run-pass/rust-log-filter.rs b/src/test/run-pass/rust-log-filter.rs index 95f90ebbf8e..28d47f7aa9b 100644 --- a/src/test/run-pass/rust-log-filter.rs +++ b/src/test/run-pass/rust-log-filter.rs @@ -10,6 +10,9 @@ // exec-env:RUST_LOG=rust-log-filter/f.o +#![allow(unknown_features)] +#![feature(box_syntax)] + #[macro_use] extern crate log; diff --git a/src/test/run-pass/self-impl.rs b/src/test/run-pass/self-impl.rs index 74416b96e93..40a4dc52a70 100644 --- a/src/test/run-pass/self-impl.rs +++ b/src/test/run-pass/self-impl.rs @@ -10,6 +10,9 @@ // Test that we can use `Self` types in impls in the expected way. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Foo; // Test uses on inherent impl. diff --git a/src/test/run-pass/self-in-mut-slot-default-method.rs b/src/test/run-pass/self-in-mut-slot-default-method.rs index bced8012b68..e934498ea05 100644 --- a/src/test/run-pass/self-in-mut-slot-default-method.rs +++ b/src/test/run-pass/self-in-mut-slot-default-method.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct X { a: int diff --git a/src/test/run-pass/self-re-assign.rs b/src/test/run-pass/self-re-assign.rs index 75fb98f8e24..3092898d986 100644 --- a/src/test/run-pass/self-re-assign.rs +++ b/src/test/run-pass/self-re-assign.rs @@ -11,6 +11,9 @@ // Ensure assigning an owned or managed variable to itself works. In particular, // that we do not glue_drop before we glue_take (#3290). +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::rc::Rc; pub fn main() { diff --git a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs index a6e4716c3b8..89624c3ac16 100644 --- a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs +++ b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; pub fn main() { test05(); } diff --git a/src/test/run-pass/shift-various-types.rs b/src/test/run-pass/shift-various-types.rs new file mode 100644 index 00000000000..2f56e09b2df --- /dev/null +++ b/src/test/run-pass/shift-various-types.rs @@ -0,0 +1,56 @@ +// 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. + +// Test that we can do shifts by any integral type. + +struct Panolpy { + i8: i8, + i16: i16, + i32: i32, + i64: i64, + isize: isize, + + u8: u8, + u16: u16, + u32: u32, + u64: u64, + usize: usize, +} + +fn foo(p: &Panolpy) { + assert_eq!(22_i32 >> p.i8, 11_i32); + assert_eq!(22_i32 >> p.i16, 11_i32); + assert_eq!(22_i32 >> p.i32, 11_i32); + assert_eq!(22_i32 >> p.i64, 11_i32); + assert_eq!(22_i32 >> p.isize, 11_i32); + + assert_eq!(22_i32 >> p.u8, 11_i32); + assert_eq!(22_i32 >> p.u16, 11_i32); + assert_eq!(22_i32 >> p.u32, 11_i32); + assert_eq!(22_i32 >> p.u64, 11_i32); + assert_eq!(22_i32 >> p.usize, 11_i32); +} + +fn main() { + let p = Panolpy { + i8: 1, + i16: 1, + i32: 1, + i64: 1, + isize: 1, + + u8: 1, + u16: 1, + u32: 1, + u64: 1, + usize: 1, + }; + foo(&p) +} diff --git a/src/test/run-pass/show-boxed-slice.rs b/src/test/run-pass/show-boxed-slice.rs index e0d005a485b..fc0b501e9c5 100644 --- a/src/test/run-pass/show-boxed-slice.rs +++ b/src/test/run-pass/show-boxed-slice.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + #[derive(Show)] struct Foo(Box<[u8]>); diff --git a/src/test/run-pass/simd-binop.rs b/src/test/run-pass/simd-binop.rs index 7f9be78d583..690ad351247 100644 --- a/src/test/run-pass/simd-binop.rs +++ b/src/test/run-pass/simd-binop.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![allow(experimental)] +#![allow(unstable)] use std::simd::{i32x4, f32x4, u32x4}; diff --git a/src/test/run-pass/simd-issue-10604.rs b/src/test/run-pass/simd-issue-10604.rs index 966db25a128..6f0db23e2a6 100644 --- a/src/test/run-pass/simd-issue-10604.rs +++ b/src/test/run-pass/simd-issue-10604.rs @@ -9,7 +9,7 @@ // except according to those terms. -#![allow(experimental)] +#![allow(unstable)] #![feature(simd)] pub fn main() { diff --git a/src/test/run-pass/simd-size-align.rs b/src/test/run-pass/simd-size-align.rs new file mode 100644 index 00000000000..582810f0def --- /dev/null +++ b/src/test/run-pass/simd-size-align.rs @@ -0,0 +1,70 @@ +// 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. + +#![feature(simd)] +#![allow(non_camel_case_types)] + +use std::mem; + +/// `T` should satisfy `size_of T (mod min_align_of T) === 0` to be stored at `Vec<T>` properly +/// Please consult the issue #20460 +fn check<T>() { + assert_eq!(mem::size_of::<T>() % mem::min_align_of::<T>(), 0) +} + +fn main() { + check::<u8x2>(); + check::<u8x3>(); + check::<u8x4>(); + check::<u8x5>(); + check::<u8x6>(); + check::<u8x7>(); + check::<u8x8>(); + + check::<i16x2>(); + check::<i16x3>(); + check::<i16x4>(); + check::<i16x5>(); + check::<i16x6>(); + check::<i16x7>(); + check::<i16x8>(); + + check::<f32x2>(); + check::<f32x3>(); + check::<f32x4>(); + check::<f32x5>(); + check::<f32x6>(); + check::<f32x7>(); + check::<f32x8>(); +} + +#[simd] struct u8x2(u8, u8); +#[simd] struct u8x3(u8, u8, u8); +#[simd] struct u8x4(u8, u8, u8, u8); +#[simd] struct u8x5(u8, u8, u8, u8, u8); +#[simd] struct u8x6(u8, u8, u8, u8, u8, u8); +#[simd] struct u8x7(u8, u8, u8, u8, u8, u8, u8); +#[simd] struct u8x8(u8, u8, u8, u8, u8, u8, u8, u8); + +#[simd] struct i16x2(i16, i16); +#[simd] struct i16x3(i16, i16, i16); +#[simd] struct i16x4(i16, i16, i16, i16); +#[simd] struct i16x5(i16, i16, i16, i16, i16); +#[simd] struct i16x6(i16, i16, i16, i16, i16, i16); +#[simd] struct i16x7(i16, i16, i16, i16, i16, i16, i16); +#[simd] struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16); + +#[simd] struct f32x2(f32, f32); +#[simd] struct f32x3(f32, f32, f32); +#[simd] struct f32x4(f32, f32, f32, f32); +#[simd] struct f32x5(f32, f32, f32, f32, f32); +#[simd] struct f32x6(f32, f32, f32, f32, f32, f32); +#[simd] struct f32x7(f32, f32, f32, f32, f32, f32, f32); +#[simd] struct f32x8(f32, f32, f32, f32, f32, f32, f32, f32); diff --git a/src/test/run-pass/slice-2.rs b/src/test/run-pass/slice-2.rs index 05f318b53c2..8f031d2e97e 100644 --- a/src/test/run-pass/slice-2.rs +++ b/src/test/run-pass/slice-2.rs @@ -10,8 +10,6 @@ // Test slicing expressions on slices and Vecs. -#![feature(slicing_syntax)] - fn main() { let x: &[int] = &[1, 2, 3, 4, 5]; let cmp: &[int] = &[1, 2, 3, 4, 5]; diff --git a/src/test/run-pass/slice-panic-1.rs b/src/test/run-pass/slice-panic-1.rs index 8b9a3f10a60..b2e3d83ca9b 100644 --- a/src/test/run-pass/slice-panic-1.rs +++ b/src/test/run-pass/slice-panic-1.rs @@ -10,8 +10,6 @@ // Test that if a slicing expr[..] fails, the correct cleanups happen. -#![feature(slicing_syntax)] - use std::thread::Thread; struct Foo; diff --git a/src/test/run-pass/slice-panic-2.rs b/src/test/run-pass/slice-panic-2.rs index 94a0530bffb..dea45e63ab0 100644 --- a/src/test/run-pass/slice-panic-2.rs +++ b/src/test/run-pass/slice-panic-2.rs @@ -10,8 +10,6 @@ // Test that if a slicing expr[..] fails, the correct cleanups happen. -#![feature(slicing_syntax)] - use std::thread::Thread; struct Foo; diff --git a/src/test/run-pass/slice.rs b/src/test/run-pass/slice.rs index fca7daeb07d..9cb7cfd7fe9 100644 --- a/src/test/run-pass/slice.rs +++ b/src/test/run-pass/slice.rs @@ -10,11 +10,10 @@ // Test slicing sugar. -#![feature(slicing_syntax)] #![feature(associated_types)] extern crate core; -use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange}; +use core::ops::{Index, IndexMut, Range, RangeTo, RangeFrom, FullRange}; static mut COUNT: uint = 0; diff --git a/src/test/run-pass/syntax-extension-bytes.rs b/src/test/run-pass/syntax-extension-bytes.rs deleted file mode 100644 index 1f92677fb6f..00000000000 --- a/src/test/run-pass/syntax-extension-bytes.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -static static_vec: &'static [u8] = bytes!("abc", 0xFF, '!'); - -pub fn main() { - let vec: &'static [u8] = bytes!("abc"); - let expected: &[u8] = &[97_u8, 98_u8, 99_u8]; - assert_eq!(vec, expected); - - let vec: &'static [u8] = bytes!("null", 0); - let expected: &[u8] = &[110_u8, 117_u8, 108_u8, 108_u8, 0_u8]; - assert_eq!(vec, expected); - - let vec: &'static [u8] = bytes!(' ', " ", 32, 32u8); - let expected: &[u8] = &[32_u8, 32_u8, 32_u8, 32_u8]; - assert_eq!(vec, expected); - - let expected: &[u8] = &[97_u8, 98_u8, 99_u8, 255_u8, 33_u8]; - assert_eq!(static_vec, expected); -} diff --git a/src/test/run-pass/task-spawn-move-and-copy.rs b/src/test/run-pass/task-spawn-move-and-copy.rs index b2bcf395783..ca2a8cf5506 100644 --- a/src/test/run-pass/task-spawn-move-and-copy.rs +++ b/src/test/run-pass/task-spawn-move-and-copy.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; use std::sync::mpsc::channel; diff --git a/src/test/run-pass/task-stderr.rs b/src/test/run-pass/task-stderr.rs index 7ff5960375c..5e6247bac93 100644 --- a/src/test/run-pass/task-stderr.rs +++ b/src/test/run-pass/task-stderr.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::sync::mpsc::channel; use std::io::{ChanReader, ChanWriter}; use std::thread; diff --git a/src/test/run-pass/tcp-accept-stress.rs b/src/test/run-pass/tcp-accept-stress.rs index cd3cb872fd3..cad71732034 100644 --- a/src/test/run-pass/tcp-accept-stress.rs +++ b/src/test/run-pass/tcp-accept-stress.rs @@ -34,11 +34,11 @@ fn test() { let (srv_tx, srv_rx) = channel(); let (cli_tx, cli_rx) = channel(); - for _ in range(0, N) { + let _t = range(0, N).map(|_| { let a = a.clone(); let cnt = cnt.clone(); let srv_tx = srv_tx.clone(); - Thread::spawn(move|| { + Thread::scoped(move|| { let mut a = a; loop { match a.accept() { @@ -52,18 +52,18 @@ fn test() { } } srv_tx.send(()); - }); - } + }) + }).collect::<Vec<_>>(); - for _ in range(0, N) { + let _t = range(0, N).map(|_| { let cli_tx = cli_tx.clone(); - Thread::spawn(move|| { + Thread::scoped(move|| { for _ in range(0, M) { let _s = TcpStream::connect(addr).unwrap(); } cli_tx.send(()); - }); - } + }) + }).collect::<Vec<_>>(); drop((cli_tx, srv_tx)); // wait for senders diff --git a/src/test/run-pass/tcp-connect-timeouts.rs b/src/test/run-pass/tcp-connect-timeouts.rs index 4ab089b6eaa..56044289fba 100644 --- a/src/test/run-pass/tcp-connect-timeouts.rs +++ b/src/test/run-pass/tcp-connect-timeouts.rs @@ -16,7 +16,7 @@ // one test task to ensure that errors are timeouts, not file descriptor // exhaustion. -#![allow(experimental)] +#![allow(unstable)] #![reexport_test_harness_main = "test_main"] #![allow(unused_imports)] diff --git a/src/test/run-pass/threads.rs b/src/test/run-pass/threads.rs index c47ca0db2a1..abc2938df00 100644 --- a/src/test/run-pass/threads.rs +++ b/src/test/run-pass/threads.rs @@ -13,7 +13,7 @@ use std::thread::Thread; pub fn main() { let mut i = 10; while i > 0 { - Thread::spawn({let i = i; move|| child(i)}); + Thread::scoped({let i = i; move|| child(i)}); i = i - 1; } println!("main thread exiting"); diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index bc397bb6319..0089646d0a1 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -13,6 +13,8 @@ // ignore-pretty +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::sync::Arc; diff --git a/src/test/run-pass/trait-coercion-generic.rs b/src/test/run-pass/trait-coercion-generic.rs index 7d924f977cb..22db6c64770 100644 --- a/src/test/run-pass/trait-coercion-generic.rs +++ b/src/test/run-pass/trait-coercion-generic.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] trait Trait<T> { fn f(&self, x: T); diff --git a/src/test/run-pass/trait-coercion.rs b/src/test/run-pass/trait-coercion.rs index 37d69ddfe07..0d4a05bed7f 100644 --- a/src/test/run-pass/trait-coercion.rs +++ b/src/test/run-pass/trait-coercion.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::io; trait Trait { diff --git a/src/test/run-pass/trait-contravariant-self.rs b/src/test/run-pass/trait-contravariant-self.rs index e06e01b9e05..19d76b88901 100644 --- a/src/test/run-pass/trait-contravariant-self.rs +++ b/src/test/run-pass/trait-contravariant-self.rs @@ -22,6 +22,9 @@ // 4. `Bar for Box<Foo> <: Bar for Box<Foo:Send>` because // `Box<Foo:Send> <: Box<Foo>`. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait Foo { } struct SFoo; impl Foo for SFoo { } diff --git a/src/test/run-pass/trait-object-generics.rs b/src/test/run-pass/trait-object-generics.rs index 81aa5daaf91..76352c799a0 100644 --- a/src/test/run-pass/trait-object-generics.rs +++ b/src/test/run-pass/trait-object-generics.rs @@ -10,6 +10,8 @@ // test for #8664 +#![allow(unknown_features)] +#![feature(box_syntax)] pub trait Trait2<A> { fn doit(&self); diff --git a/src/test/run-pass/traits-conditional-dispatch.rs b/src/test/run-pass/traits-conditional-dispatch.rs index a94f73c2b6d..7e2b7ae0663 100644 --- a/src/test/run-pass/traits-conditional-dispatch.rs +++ b/src/test/run-pass/traits-conditional-dispatch.rs @@ -12,6 +12,9 @@ // blanket impl for T:Copy coexists with an impl for Box<T>, because // Box does not impl Copy. +#![allow(unknown_features)] +#![feature(box_syntax)] + trait Get { fn get(&self) -> Self; } diff --git a/src/test/run-pass/type-param-constraints.rs b/src/test/run-pass/type-param-constraints.rs index 7265ddf6615..3fcb04d6848 100644 --- a/src/test/run-pass/type-param-constraints.rs +++ b/src/test/run-pass/type-param-constraints.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn p_foo<T>(_pinned: T) { } fn s_foo<T>(_shared: T) { } diff --git a/src/test/run-pass/typeclasses-eq-example-static.rs b/src/test/run-pass/typeclasses-eq-example-static.rs index 63a59b6f750..20a28c5a9ea 100644 --- a/src/test/run-pass/typeclasses-eq-example-static.rs +++ b/src/test/run-pass/typeclasses-eq-example-static.rs @@ -9,6 +9,9 @@ // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + // Example from lkuper's intern talk, August 2012 -- now with static // methods! use Color::{cyan, magenta, yellow, black}; diff --git a/src/test/run-pass/typeclasses-eq-example.rs b/src/test/run-pass/typeclasses-eq-example.rs index 431a9383b3b..aa290edd863 100644 --- a/src/test/run-pass/typeclasses-eq-example.rs +++ b/src/test/run-pass/typeclasses-eq-example.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] // Example from lkuper's intern talk, August 2012. use Color::{cyan, magenta, yellow, black}; diff --git a/src/test/run-pass/typeid-intrinsic.rs b/src/test/run-pass/typeid-intrinsic.rs index bba043ea8f8..e346c4ff349 100644 --- a/src/test/run-pass/typeid-intrinsic.rs +++ b/src/test/run-pass/typeid-intrinsic.rs @@ -14,7 +14,7 @@ extern crate "typeid-intrinsic" as other1; extern crate "typeid-intrinsic2" as other2; -use std::hash; +use std::hash::{self, SipHasher}; use std::intrinsics; use std::intrinsics::TypeId; @@ -70,5 +70,6 @@ pub fn main() { // check it has a hash let (a, b) = (TypeId::of::<uint>(), TypeId::of::<uint>()); - assert_eq!(hash::hash(&a), hash::hash(&b)); + assert_eq!(hash::hash::<TypeId, SipHasher>(&a), + hash::hash::<TypeId, SipHasher>(&b)); } diff --git a/src/test/run-pass/ufcs-explicit-self.rs b/src/test/run-pass/ufcs-explicit-self.rs index b6b9fb67f90..968f3511247 100644 --- a/src/test/run-pass/ufcs-explicit-self.rs +++ b/src/test/run-pass/ufcs-explicit-self.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Foo { f: int, } diff --git a/src/test/run-pass/unboxed-closures-boxed.rs b/src/test/run-pass/unboxed-closures-boxed.rs index 60e59400e1a..dc35d5bf2ca 100644 --- a/src/test/run-pass/unboxed-closures-boxed.rs +++ b/src/test/run-pass/unboxed-closures-boxed.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::ops::FnMut; diff --git a/src/test/run-pass/unboxed-closures-call-sugar-object-autoderef.rs b/src/test/run-pass/unboxed-closures-call-sugar-object-autoderef.rs index 8909f4e261f..da647e90c00 100644 --- a/src/test/run-pass/unboxed-closures-call-sugar-object-autoderef.rs +++ b/src/test/run-pass/unboxed-closures-call-sugar-object-autoderef.rs @@ -10,6 +10,8 @@ // Test that the call operator autoderefs when calling to an object type. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::ops::FnMut; diff --git a/src/test/run-pass/unboxed-closures-call-sugar-object.rs b/src/test/run-pass/unboxed-closures-call-sugar-object.rs index 2dec53cc13a..8ee3c96f580 100644 --- a/src/test/run-pass/unboxed-closures-call-sugar-object.rs +++ b/src/test/run-pass/unboxed-closures-call-sugar-object.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] use std::ops::FnMut; diff --git a/src/test/run-pass/unboxed-closures-monomorphization.rs b/src/test/run-pass/unboxed-closures-monomorphization.rs index 52855f82673..6701f879e4f 100644 --- a/src/test/run-pass/unboxed-closures-monomorphization.rs +++ b/src/test/run-pass/unboxed-closures-monomorphization.rs @@ -11,6 +11,8 @@ // Test that unboxed closures in contexts with free type parameters // monomorphize correctly (issue #16791) +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] fn main(){ diff --git a/src/test/run-pass/unboxed-closures-prelude.rs b/src/test/run-pass/unboxed-closures-prelude.rs index d1bd7e908c8..915715727e8 100644 --- a/src/test/run-pass/unboxed-closures-prelude.rs +++ b/src/test/run-pass/unboxed-closures-prelude.rs @@ -10,6 +10,8 @@ // Tests that the reexports of `FnOnce` et al from the prelude work. +#![allow(unknown_features)] +#![feature(box_syntax)] #![feature(unboxed_closures)] fn main() { diff --git a/src/test/run-pass/uniq-self-in-mut-slot.rs b/src/test/run-pass/uniq-self-in-mut-slot.rs index 4d7830e1cdc..b7980ed9021 100644 --- a/src/test/run-pass/uniq-self-in-mut-slot.rs +++ b/src/test/run-pass/uniq-self-in-mut-slot.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct X { a: int diff --git a/src/test/run-pass/unique-assign-copy.rs b/src/test/run-pass/unique-assign-copy.rs index fb5f6e4a8aa..9e3d9544d42 100644 --- a/src/test/run-pass/unique-assign-copy.rs +++ b/src/test/run-pass/unique-assign-copy.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut i = box 1i; // Should be a copy diff --git a/src/test/run-pass/unique-assign-drop.rs b/src/test/run-pass/unique-assign-drop.rs index 505e9b46e03..81c4b6ab7e5 100644 --- a/src/test/run-pass/unique-assign-drop.rs +++ b/src/test/run-pass/unique-assign-drop.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(dead_assignment)] +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let i = box 1i; diff --git a/src/test/run-pass/unique-assign-generic.rs b/src/test/run-pass/unique-assign-generic.rs index 493ec8ddc20..7c9bbd64171 100644 --- a/src/test/run-pass/unique-assign-generic.rs +++ b/src/test/run-pass/unique-assign-generic.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f<T>(t: T) -> T { let t1 = t; diff --git a/src/test/run-pass/unique-assign.rs b/src/test/run-pass/unique-assign.rs index 64d65a7b2e5..199657fd995 100644 --- a/src/test/run-pass/unique-assign.rs +++ b/src/test/run-pass/unique-assign.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut i; i = box 1i; diff --git a/src/test/run-pass/unique-autoderef-field.rs b/src/test/run-pass/unique-autoderef-field.rs index 67f96decaa9..aab7f4108fb 100644 --- a/src/test/run-pass/unique-autoderef-field.rs +++ b/src/test/run-pass/unique-autoderef-field.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct J { j: int } pub fn main() { diff --git a/src/test/run-pass/unique-autoderef-index.rs b/src/test/run-pass/unique-autoderef-index.rs index f9bd5114e7d..1c7b4c534ed 100644 --- a/src/test/run-pass/unique-autoderef-index.rs +++ b/src/test/run-pass/unique-autoderef-index.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let i = box vec!(100i); diff --git a/src/test/run-pass/unique-cmp.rs b/src/test/run-pass/unique-cmp.rs index 38be635d837..dba4d8db849 100644 --- a/src/test/run-pass/unique-cmp.rs +++ b/src/test/run-pass/unique-cmp.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 100i; assert!(i == box 100i); diff --git a/src/test/run-pass/unique-containing-tag.rs b/src/test/run-pass/unique-containing-tag.rs index ccb21b605c1..e4099c94c2f 100644 --- a/src/test/run-pass/unique-containing-tag.rs +++ b/src/test/run-pass/unique-containing-tag.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { enum t { t1(int), t2(int), } diff --git a/src/test/run-pass/unique-create.rs b/src/test/run-pass/unique-create.rs index acd405e2659..cec74d251b3 100644 --- a/src/test/run-pass/unique-create.rs +++ b/src/test/run-pass/unique-create.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { box 100i; } diff --git a/src/test/run-pass/unique-decl-init-copy.rs b/src/test/run-pass/unique-decl-init-copy.rs index ddc2bb6c30f..d0ad03b773c 100644 --- a/src/test/run-pass/unique-decl-init-copy.rs +++ b/src/test/run-pass/unique-decl-init-copy.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut i = box 1i; // Should be a copy diff --git a/src/test/run-pass/unique-decl-init.rs b/src/test/run-pass/unique-decl-init.rs index 1d98cfb6b4b..d7c19eb6358 100644 --- a/src/test/run-pass/unique-decl-init.rs +++ b/src/test/run-pass/unique-decl-init.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 1i; let j = i; diff --git a/src/test/run-pass/unique-decl-move.rs b/src/test/run-pass/unique-decl-move.rs index e2e7b2ec771..0acdc8f3b80 100644 --- a/src/test/run-pass/unique-decl-move.rs +++ b/src/test/run-pass/unique-decl-move.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 100i; let j = i; diff --git a/src/test/run-pass/unique-deref.rs b/src/test/run-pass/unique-deref.rs index 37ca58913ab..752ea830aa5 100644 --- a/src/test/run-pass/unique-deref.rs +++ b/src/test/run-pass/unique-deref.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 100i; assert_eq!(*i, 100); diff --git a/src/test/run-pass/unique-destructure.rs b/src/test/run-pass/unique-destructure.rs index 0b3041f2249..3213146cbf4 100644 --- a/src/test/run-pass/unique-destructure.rs +++ b/src/test/run-pass/unique-destructure.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct Foo { a: int, b: int } pub fn main() { diff --git a/src/test/run-pass/unique-drop-complex.rs b/src/test/run-pass/unique-drop-complex.rs index a4b6ff5accf..ec2c9f8c666 100644 --- a/src/test/run-pass/unique-drop-complex.rs +++ b/src/test/run-pass/unique-drop-complex.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let _x = box vec!(0i,0,0,0,0); } diff --git a/src/test/run-pass/unique-fn-arg-move.rs b/src/test/run-pass/unique-fn-arg-move.rs index 68290d85d0e..0e47d39e55f 100644 --- a/src/test/run-pass/unique-fn-arg-move.rs +++ b/src/test/run-pass/unique-fn-arg-move.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn f(i: Box<int>) { assert_eq!(*i, 100); } diff --git a/src/test/run-pass/unique-fn-arg-mut.rs b/src/test/run-pass/unique-fn-arg-mut.rs index ccf6a4fd7ae..e1d148cc9a5 100644 --- a/src/test/run-pass/unique-fn-arg-mut.rs +++ b/src/test/run-pass/unique-fn-arg-mut.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn f(i: &mut Box<int>) { *i = box 200; diff --git a/src/test/run-pass/unique-fn-arg.rs b/src/test/run-pass/unique-fn-arg.rs index 6769011cffe..301994a74a8 100644 --- a/src/test/run-pass/unique-fn-arg.rs +++ b/src/test/run-pass/unique-fn-arg.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn f(i: Box<int>) { assert_eq!(*i, 100); diff --git a/src/test/run-pass/unique-fn-ret.rs b/src/test/run-pass/unique-fn-ret.rs index 8493652cf8a..de2c265089b 100644 --- a/src/test/run-pass/unique-fn-ret.rs +++ b/src/test/run-pass/unique-fn-ret.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] fn f() -> Box<int> { box 100 diff --git a/src/test/run-pass/unique-in-tag.rs b/src/test/run-pass/unique-in-tag.rs index ffff9b98f54..4f02018346b 100644 --- a/src/test/run-pass/unique-in-tag.rs +++ b/src/test/run-pass/unique-in-tag.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn test1() { enum bar { u(Box<int>), w(int), } diff --git a/src/test/run-pass/unique-in-vec-copy.rs b/src/test/run-pass/unique-in-vec-copy.rs index 577a8f1430b..4620815e74e 100644 --- a/src/test/run-pass/unique-in-vec-copy.rs +++ b/src/test/run-pass/unique-in-vec-copy.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let mut a = vec!(box 10i); diff --git a/src/test/run-pass/unique-in-vec.rs b/src/test/run-pass/unique-in-vec.rs index 0f8527664b9..389ca2c18b1 100644 --- a/src/test/run-pass/unique-in-vec.rs +++ b/src/test/run-pass/unique-in-vec.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let vect = vec!(box 100i); assert!(vect[0] == box 100); diff --git a/src/test/run-pass/unique-init.rs b/src/test/run-pass/unique-init.rs index 6e58ec23a3b..b36d08364a2 100644 --- a/src/test/run-pass/unique-init.rs +++ b/src/test/run-pass/unique-init.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let _i = box 100i; } diff --git a/src/test/run-pass/unique-kinds.rs b/src/test/run-pass/unique-kinds.rs index d3f4a8b1090..56f7a3f7990 100644 --- a/src/test/run-pass/unique-kinds.rs +++ b/src/test/run-pass/unique-kinds.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::cmp::PartialEq; fn sendable() { diff --git a/src/test/run-pass/unique-log.rs b/src/test/run-pass/unique-log.rs index bae87230ba0..05579796dab 100644 --- a/src/test/run-pass/unique-log.rs +++ b/src/test/run-pass/unique-log.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 100i; println!("{}", i); diff --git a/src/test/run-pass/unique-match-discrim.rs b/src/test/run-pass/unique-match-discrim.rs index 68b46db3a94..a1502c2eb8c 100644 --- a/src/test/run-pass/unique-match-discrim.rs +++ b/src/test/run-pass/unique-match-discrim.rs @@ -10,6 +10,9 @@ // Issue #961 +#![allow(unknown_features)] +#![feature(box_syntax)] + fn altsimple() { match box true { _ => { } diff --git a/src/test/run-pass/unique-move-drop.rs b/src/test/run-pass/unique-move-drop.rs index 1b6ef92865c..1388c6c5d2b 100644 --- a/src/test/run-pass/unique-move-drop.rs +++ b/src/test/run-pass/unique-move-drop.rs @@ -9,6 +9,8 @@ // except according to those terms. #![allow(unused_variable)] +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let i = box 100i; diff --git a/src/test/run-pass/unique-move-temp.rs b/src/test/run-pass/unique-move-temp.rs index 1902fabe639..af82d3e14ea 100644 --- a/src/test/run-pass/unique-move-temp.rs +++ b/src/test/run-pass/unique-move-temp.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut i; i = box 100i; diff --git a/src/test/run-pass/unique-move.rs b/src/test/run-pass/unique-move.rs index 398db63ce08..791c4799bf0 100644 --- a/src/test/run-pass/unique-move.rs +++ b/src/test/run-pass/unique-move.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let i = box 100i; let mut j; diff --git a/src/test/run-pass/unique-mutable.rs b/src/test/run-pass/unique-mutable.rs index eebb1705590..c4f860d930b 100644 --- a/src/test/run-pass/unique-mutable.rs +++ b/src/test/run-pass/unique-mutable.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let mut i = box 0i; *i = 1; diff --git a/src/test/run-pass/unique-object-move.rs b/src/test/run-pass/unique-object-move.rs index 6d0432faf55..cec523a0671 100644 --- a/src/test/run-pass/unique-object-move.rs +++ b/src/test/run-pass/unique-object-move.rs @@ -10,6 +10,8 @@ // Issue #5192 +#![allow(unknown_features)] +#![feature(box_syntax)] pub trait EventLoop { } diff --git a/src/test/run-pass/unique-pat-2.rs b/src/test/run-pass/unique-pat-2.rs index bf99f06f58a..eab775fc1db 100644 --- a/src/test/run-pass/unique-pat-2.rs +++ b/src/test/run-pass/unique-pat-2.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] struct Foo {a: int, b: uint} diff --git a/src/test/run-pass/unique-pat-3.rs b/src/test/run-pass/unique-pat-3.rs index 559d8f8cb3c..42a4b1a9c0c 100644 --- a/src/test/run-pass/unique-pat-3.rs +++ b/src/test/run-pass/unique-pat-3.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + enum bar { u(Box<int>), w(int), } pub fn main() { diff --git a/src/test/run-pass/unique-pat.rs b/src/test/run-pass/unique-pat.rs index a0eee7e3cb6..ee975b9c81a 100644 --- a/src/test/run-pass/unique-pat.rs +++ b/src/test/run-pass/unique-pat.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + fn simple() { match box true { box true => { } diff --git a/src/test/run-pass/unique-rec.rs b/src/test/run-pass/unique-rec.rs index ff7f009990d..756911d29fc 100644 --- a/src/test/run-pass/unique-rec.rs +++ b/src/test/run-pass/unique-rec.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + struct X { x: int } pub fn main() { diff --git a/src/test/run-pass/unique-send-2.rs b/src/test/run-pass/unique-send-2.rs index bb3019ede4b..90f4b2e6344 100644 --- a/src/test/run-pass/unique-send-2.rs +++ b/src/test/run-pass/unique-send-2.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::sync::mpsc::{channel, Sender}; use std::thread::Thread; @@ -19,13 +22,13 @@ pub fn main() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; - for i in range(0u, n) { + let _t = range(0u, n).map(|i| { + expected += i; let tx = tx.clone(); - Thread::spawn(move|| { + Thread::scoped(move|| { child(&tx, i) - }); - expected += i; - } + }) + }).collect::<Vec<_>>(); let mut actual = 0u; for _ in range(0u, n) { diff --git a/src/test/run-pass/unique-send.rs b/src/test/run-pass/unique-send.rs index afafb204c1c..13728585455 100644 --- a/src/test/run-pass/unique-send.rs +++ b/src/test/run-pass/unique-send.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::sync::mpsc::channel; pub fn main() { diff --git a/src/test/run-pass/unique-swap.rs b/src/test/run-pass/unique-swap.rs index d467d042e4e..cd3b59a69ba 100644 --- a/src/test/run-pass/unique-swap.rs +++ b/src/test/run-pass/unique-swap.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::mem::swap; pub fn main() { diff --git a/src/test/run-pass/unsized2.rs b/src/test/run-pass/unsized2.rs index c7e8b2a05ec..285100dd719 100644 --- a/src/test/run-pass/unsized2.rs +++ b/src/test/run-pass/unsized2.rs @@ -10,6 +10,9 @@ // // ignore-lexer-test FIXME #15879 +#![allow(unknown_features)] +#![feature(box_syntax)] + // Test sized-ness checking in substitution. // Unbounded. diff --git a/src/test/run-pass/unsized3.rs b/src/test/run-pass/unsized3.rs index 271f5817c9e..983152cd056 100644 --- a/src/test/run-pass/unsized3.rs +++ b/src/test/run-pass/unsized3.rs @@ -10,6 +10,9 @@ // Test structs with always-unsized fields. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::mem; use std::raw; diff --git a/src/test/run-pass/unused-move-capture.rs b/src/test/run-pass/unused-move-capture.rs index bd20a174d1e..27945f46920 100644 --- a/src/test/run-pass/unused-move-capture.rs +++ b/src/test/run-pass/unused-move-capture.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { let _x = box 1i; let lam_move = |&:| {}; diff --git a/src/test/run-pass/unused-move.rs b/src/test/run-pass/unused-move.rs index 883ec44bf2e..22201c7d83f 100644 --- a/src/test/run-pass/unused-move.rs +++ b/src/test/run-pass/unused-move.rs @@ -13,6 +13,8 @@ // Abstract: zero-fill to block after drop #![allow(path_statement)] +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { diff --git a/src/test/run-pass/unwind-resource.rs b/src/test/run-pass/unwind-resource.rs index 3f59b2c6c76..159bac10183 100644 --- a/src/test/run-pass/unwind-resource.rs +++ b/src/test/run-pass/unwind-resource.rs @@ -37,7 +37,7 @@ fn f(tx: Sender<bool>) { pub fn main() { let (tx, rx) = channel(); - let _t = Thread::spawn(move|| f(tx.clone())); + let _t = Thread::scoped(move|| f(tx.clone())); println!("hiiiiiiiii"); assert!(rx.recv().unwrap()); } diff --git a/src/test/run-pass/unwind-unique.rs b/src/test/run-pass/unwind-unique.rs index 554a08ea644..371fd677bd9 100644 --- a/src/test/run-pass/unwind-unique.rs +++ b/src/test/run-pass/unwind-unique.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + use std::thread::Thread; fn f() { diff --git a/src/test/run-pass/vec-dst.rs b/src/test/run-pass/vec-dst.rs index 4a36231e72b..40073c2b742 100644 --- a/src/test/run-pass/vec-dst.rs +++ b/src/test/run-pass/vec-dst.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![allow(unknown_features)] +#![feature(box_syntax)] + pub fn main() { // Tests for indexing into box/& [T; n] let x: [int; 3] = [1, 2, 3]; diff --git a/src/test/run-pass/vec-fixed-length.rs b/src/test/run-pass/vec-fixed-length.rs index 20e1becd008..101999bbe08 100644 --- a/src/test/run-pass/vec-fixed-length.rs +++ b/src/test/run-pass/vec-fixed-length.rs @@ -21,7 +21,7 @@ pub fn main() { // FIXME #10183 // FIXME #18069 - //if cfg!(target_word_size = "64") { + //if cfg!(target_pointer_width = "64") { // assert_eq!(size_of::<[u8; (1 << 32)]>(), (1u << 32)); //} } diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index 52e0ba89479..97c12d0954e 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - assert_eq!((vec!(0i, 1)).to_string(), "[0, 1]".to_string()); + assert_eq!(format!("{:?}", vec!(0i, 1)), "[0i, 1i]".to_string()); let foo = vec!(3i, 4); let bar: &[int] = &[4, 5]; - assert_eq!(foo.to_string(), "[3, 4]".to_string()); - assert_eq!(bar.to_string(), "[4, 5]".to_string()); + assert_eq!(format!("{:?}", foo), "[3i, 4i]"); + assert_eq!(format!("{:?}", bar), "[4i, 5i]"); } diff --git a/src/test/run-pass/vector-no-ann-2.rs b/src/test/run-pass/vector-no-ann-2.rs index ba66a448c25..6391893b9a4 100644 --- a/src/test/run-pass/vector-no-ann-2.rs +++ b/src/test/run-pass/vector-no-ann-2.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - +#![allow(unknown_features)] +#![feature(box_syntax)] pub fn main() { let _quux: Box<Vec<uint>> = box Vec::new(); } |
