diff --git a/.travis.yml b/.travis.yml index 88be81be7550c..c76e17a27d188 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ matrix: fast_finish: true include: # Images used in testing PR and try-build should be run first. - - env: IMAGE=x86_64-gnu-llvm-3.7 RUST_BACKTRACE=1 + - env: IMAGE=x86_64-gnu-llvm-3.9 RUST_BACKTRACE=1 if: type = pull_request OR branch = auto - env: IMAGE=dist-x86_64-linux DEPLOY=1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d67a74f681e23..4c296a28e90b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -365,6 +365,116 @@ In order to prepare your PR, you can run the build locally by doing there, you may wish to set `submodules = false` in the `config.toml` to prevent `x.py` from resetting to the original branch. +#### Breaking Tools Built With The Compiler +[breaking-tools-built-with-the-compiler]: #breaking-tools-built-with-the-compiler + +Rust's build system builds a number of tools that make use of the +internals of the compiler. This includes clippy, +[RLS](https://github.com/rust-lang-nursery/rls) and +[rustfmt](https://github.com/rust-lang-nursery/rustfmt). If these tools +break because of your changes, you may run into a sort of "chicken and egg" +problem. These tools rely on the latest compiler to be built so you can't update +them to reflect your changes to the compiler until those changes are merged into +the compiler. At the same time, you can't get your changes merged into the compiler +because the rust-lang/rust build won't pass until those tools build and pass their +tests. + +That means that, in the default state, you can't update the compiler without first +fixing rustfmt, rls and the other tools that the compiler builds. + +Luckily, a feature was [added to Rust's build](https://github.com/rust-lang/rust/pull/45243) +to make all of this easy to handle. The idea is that you mark the tools as "broken", +so that the rust-lang/rust build passes without trying to build them, then land the change +in the compiler, wait for a nightly, and go update the tools that you broke. Once you're done +and the tools are working again, you go back in the compiler and change the tools back +from "broken". + +This should avoid a bunch of synchronization dances and is also much easier on contributors as +there's no need to block on rls/rustfmt/other tools changes going upstream. + +Here are those same steps in detail: + +1. (optional) First, if it doesn't exist already, create a `config.toml` by copying + `config.toml.example` in the root directory of the Rust repository. + Set `submodules = false` in the `[build]` section. This will prevent `x.py` + from resetting to the original branch after you make your changes. If you + need to [update any submodules to their latest versions][updating-submodules], + see the section of this file about that for more information. +2. (optional) Run `./x.py test src/tools/rustfmt` (substituting the submodule + that broke for `rustfmt`). Fix any errors in the submodule (and possibly others). +3. (optional) Make commits for your changes and send them to upstream repositories as a PR. +4. (optional) Maintainers of these submodules will **not** merge the PR. The PR can't be + merged because CI will be broken. You'll want to write a message on the PR referencing + your change, and how the PR should be merged once your change makes it into a nightly. +5. Update `src/tools/toolstate.toml` to indicate that the tool in question is "broken", + that will disable building it on CI. See the documentation in that file for the exact + configuration values you can use. +6. Commit the changes to `src/tools/toolstate.toml`, **do not update submodules in your commit**, + and then update the PR you have for rust-lang/rust. +7. Wait for your PR to merge. +8. Wait for a nightly +9. (optional) Help land your PR on the upstream repository now that your changes are in nightly. +10. (optional) Send a PR to rust-lang/rust updating the submodule, reverting `src/tools/toolstate.toml` back to a "building" or "testing" state. + +#### Updating submodules +[updating-submodules]: #updating-submodules + +These instructions are specific to updating `rustfmt`, however they may apply +to the other submodules as well. Please help by improving these instructions +if you find any discrepencies or special cases that need to be addressed. + +To update the `rustfmt` submodule, start by running the appropriate +[`git submodule` command](https://git-scm.com/book/en/v2/Git-Tools-Submodules). +For example, to update to the latest commit on the remote master branch, +you may want to run: +``` +git submodule update --remote src/tools/rustfmt +``` +If you run `./x.py build` now, and you are lucky, it may just work. If you see +an error message about patches that did not resolve to any crates, you will need +to complete a few more steps which are outlined with their rationale below. + +*(This error may change in the future to include more information.)* +``` +error: failed to resolve patches for `https://github.com/rust-lang-nursery/rustfmt` + +Caused by: + patch for `rustfmt-nightly` in `https://github.com/rust-lang-nursery/rustfmt` did not resolve to any crates +failed to run: ~/rust/build/x86_64-unknown-linux-gnu/stage0/bin/cargo build --manifest-path ~/rust/src/bootstrap/Cargo.toml +``` + +If you haven't used the `[patch]` +section of `Cargo.toml` before, there is [some relevant documentation about it +in the cargo docs](http://doc.crates.io/manifest.html#the-patch-section). In +addition to that, you should read the +[Overriding dependencies](http://doc.crates.io/specifying-dependencies.html#overriding-dependencies) +section of the documentation as well. + +Specifically, the following [section in Overriding dependencies](http://doc.crates.io/specifying-dependencies.html#testing-a-bugfix) reveals what the problem is: + +> Next up we need to ensure that our lock file is updated to use this new version of uuid so our project uses the locally checked out copy instead of one from crates.io. The way [patch] works is that it'll load the dependency at ../path/to/uuid and then whenever crates.io is queried for versions of uuid it'll also return the local version. +> +> This means that the version number of the local checkout is significant and will affect whether the patch is used. Our manifest declared uuid = "1.0" which means we'll only resolve to >= 1.0.0, < 2.0.0, and Cargo's greedy resolution algorithm also means that we'll resolve to the maximum version within that range. Typically this doesn't matter as the version of the git repository will already be greater or match the maximum version published on crates.io, but it's important to keep this in mind! + +This says that when we updated the submodule, the version number in our +`src/tools/rustfmt/Cargo.toml` changed. The new version is different from +the version in `Cargo.lock`, so the build can no longer continue. + +To resolve this, we need to update `Cargo.lock`. Luckily, cargo provides a +command to do this easily. + +First, go into the `src/` directory since that is where `Cargo.toml` is in +the rust repository. Then run, `cargo update -p rustfmt-nightly` to solve +the problem. + +``` +$ cd src +$ cargo update -p rustfmt-nightly +``` + +This should change the version listed in `src/Cargo.lock` to the new version you updated +the submodule to. Running `./x.py build` should work now. + ## Writing Documentation [writing-documentation]: #writing-documentation diff --git a/config.toml.example b/config.toml.example index f50543e18a764..261fe2053879f 100644 --- a/config.toml.example +++ b/config.toml.example @@ -35,7 +35,7 @@ # If an external LLVM root is specified, we automatically check the version by # default to make sure it's within the range that we're expecting, but setting # this flag will indicate that this version check should not be done. -#version-check = false +#version-check = true # Link libstdc++ statically into the librustc_llvm instead of relying on a # dynamic version to be available. diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 69e0f58f1cd06..d6c83e3acfc8a 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -299,6 +299,7 @@ impl Config { let mut config = Config::default(); config.llvm_enabled = true; config.llvm_optimize = true; + config.llvm_version_check = true; config.use_jemalloc = true; config.backtrace = true; config.rust_optimize = true; diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 941ea96bbec23..c37b1dad4c687 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -259,11 +259,14 @@ fn check_llvm_version(build: &Build, llvm_config: &Path) { let mut cmd = Command::new(llvm_config); let version = output(cmd.arg("--version")); - if version.starts_with("3.5") || version.starts_with("3.6") || - version.starts_with("3.7") { - return + let mut parts = version.split('.').take(2) + .filter_map(|s| s.parse::().ok()); + if let (Some(major), Some(minor)) = (parts.next(), parts.next()) { + if major > 3 || (major == 3 && minor >= 9) { + return + } } - panic!("\n\nbad LLVM version: {}, need >=3.5\n\n", version) + panic!("\n\nbad LLVM version: {}, need >=3.9\n\n", version) } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] diff --git a/src/ci/docker/x86_64-gnu-llvm-3.7/Dockerfile b/src/ci/docker/x86_64-gnu-llvm-3.9/Dockerfile similarity index 72% rename from src/ci/docker/x86_64-gnu-llvm-3.7/Dockerfile rename to src/ci/docker/x86_64-gnu-llvm-3.9/Dockerfile index e832a2445ba14..6b8186048988d 100644 --- a/src/ci/docker/x86_64-gnu-llvm-3.7/Dockerfile +++ b/src/ci/docker/x86_64-gnu-llvm-3.9/Dockerfile @@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ cmake \ sudo \ gdb \ - llvm-3.7-tools \ + llvm-3.9-tools \ libedit-dev \ zlib1g-dev \ xz-utils @@ -19,7 +19,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh +# using llvm-link-shared due to libffi issues -- see #34486 ENV RUST_CONFIGURE_ARGS \ --build=x86_64-unknown-linux-gnu \ - --llvm-root=/usr/lib/llvm-3.7 + --llvm-root=/usr/lib/llvm-3.9 \ + --enable-llvm-link-shared ENV RUST_CHECK_TARGET check diff --git a/src/doc/unstable-book/src/language-features/lang-items.md b/src/doc/unstable-book/src/language-features/lang-items.md index ecbc860e25c03..0137a052a62d8 100644 --- a/src/doc/unstable-book/src/language-features/lang-items.md +++ b/src/doc/unstable-book/src/language-features/lang-items.md @@ -227,3 +227,95 @@ A third function, `rust_eh_unwind_resume`, is also needed if the `custom_unwind_ flag is set in the options of the compilation target. It allows customizing the process of resuming unwind at the end of the landing pads. The language item's name is `eh_unwind_resume`. + +## List of all language items + +This is a list of all language items in Rust along with where they are located in +the source code. + +- Primitives + - `i8`: `libcore/num/mod.rs` + - `i16`: `libcore/num/mod.rs` + - `i32`: `libcore/num/mod.rs` + - `i64`: `libcore/num/mod.rs` + - `i128`: `libcore/num/mod.rs` + - `isize`: `libcore/num/mod.rs` + - `u8`: `libcore/num/mod.rs` + - `u16`: `libcore/num/mod.rs` + - `u32`: `libcore/num/mod.rs` + - `u64`: `libcore/num/mod.rs` + - `u128`: `libcore/num/mod.rs` + - `usize`: `libcore/num/mod.rs` + - `f32`: `libstd/f32.rs` + - `f64`: `libstd/f64.rs` + - `char`: `libstd_unicode/char.rs` + - `slice`: `liballoc/slice.rs` + - `str`: `liballoc/str.rs` + - `const_ptr`: `libcore/ptr.rs` + - `mut_ptr`: `libcore/ptr.rs` + - `unsafe_cell`: `libcore/cell.rs` +- Runtime + - `start`: `libstd/rt.rs` + - `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC) + - `eh_personality`: `libpanic_unwind/seh64_gnu.rs` (SEH64 GNU) + - `eh_personality`: `libpanic_unwind/seh.rs` (SEH) + - `eh_unwind_resume`: `libpanic_unwind/seh64_gnu.rs` (SEH64 GNU) + - `eh_unwind_resume`: `libpanic_unwind/gcc.rs` (GCC) + - `msvc_try_filter`: `libpanic_unwind/seh.rs` (SEH) + - `panic`: `libcore/panicking.rs` + - `panic_bounds_check`: `libcore/panicking.rs` + - `panic_fmt`: `libcore/panicking.rs` + - `panic_fmt`: `libstd/panicking.rs` +- Allocations + - `owned_box`: `liballoc/boxed.rs` + - `exchange_malloc`: `liballoc/heap.rs` + - `box_free`: `liballoc/heap.rs` +- Operands + - `not`: `libcore/ops/bit.rs` + - `bitand`: `libcore/ops/bit.rs` + - `bitor`: `libcore/ops/bit.rs` + - `bitxor`: `libcore/ops/bit.rs` + - `shl`: `libcore/ops/bit.rs` + - `shr`: `libcore/ops/bit.rs` + - `bitand_assign`: `libcore/ops/bit.rs` + - `bitor_assign`: `libcore/ops/bit.rs` + - `bitxor_assign`: `libcore/ops/bit.rs` + - `shl_assign`: `libcore/ops/bit.rs` + - `shr_assign`: `libcore/ops/bit.rs` + - `deref`: `libcore/ops/deref.rs` + - `deref_mut`: `libcore/ops/deref.rs` + - `index`: `libcore/ops/index.rs` + - `index_mut`: `libcore/ops/index.rs` + - `add`: `libcore/ops/arith.rs` + - `sub`: `libcore/ops/arith.rs` + - `mul`: `libcore/ops/arith.rs` + - `div`: `libcore/ops/arith.rs` + - `rem`: `libcore/ops/arith.rs` + - `neg`: `libcore/ops/arith.rs` + - `add_assign`: `libcore/ops/arith.rs` + - `sub_assign`: `libcore/ops/arith.rs` + - `mul_assign`: `libcore/ops/arith.rs` + - `div_assign`: `libcore/ops/arith.rs` + - `rem_assign`: `libcore/ops/arith.rs` + - `eq`: `libcore/cmp.rs` + - `ord`: `libcore/cmp.rs` +- Functions + - `fn`: `libcore/ops/function.rs` + - `fn_mut`: `libcore/ops/function.rs` + - `fn_once`: `libcore/ops/function.rs` + - `generator_state`: `libcore/ops/generator.rs` + - `generator`: `libcore/ops/generator.rs` +- Other + - `coerce_unsized`: `libcore/ops/unsize.rs` + - `drop`: `libcore/ops/drop.rs` + - `drop_in_place`: `libcore/ptr.rs` + - `clone`: `libcore/clone.rs` + - `copy`: `libcore/marker.rs` + - `send`: `libcore/marker.rs` + - `sized`: `libcore/marker.rs` + - `unsize`: `libcore/marker.rs` + - `sync`: `libcore/marker.rs` + - `phantom_data`: `libcore/marker.rs` + - `freeze`: `libcore/marker.rs` + - `debug_trait`: `libcore/fmt/mod.rs` + - `non_zero`: `libcore/nonzero.rs` \ No newline at end of file diff --git a/src/doc/unstable-book/src/library-features/alloc-jemalloc.md b/src/doc/unstable-book/src/library-features/alloc-jemalloc.md index 18ff838dd32b9..425d4cb79b2df 100644 --- a/src/doc/unstable-book/src/library-features/alloc-jemalloc.md +++ b/src/doc/unstable-book/src/library-features/alloc-jemalloc.md @@ -8,55 +8,6 @@ See also [`alloc_system`](library-features/alloc-system.html). ------------------------ -The compiler currently ships two default allocators: `alloc_system` and -`alloc_jemalloc` (some targets don't have jemalloc, however). These allocators -are normal Rust crates and contain an implementation of the routines to -allocate and deallocate memory. The standard library is not compiled assuming -either one, and the compiler will decide which allocator is in use at -compile-time depending on the type of output artifact being produced. - -Binaries generated by the compiler will use `alloc_jemalloc` by default (where -available). In this situation the compiler "controls the world" in the sense of -it has power over the final link. Primarily this means that the allocator -decision can be left up the compiler. - -Dynamic and static libraries, however, will use `alloc_system` by default. Here -Rust is typically a 'guest' in another application or another world where it -cannot authoritatively decide what allocator is in use. As a result it resorts -back to the standard APIs (e.g. `malloc` and `free`) for acquiring and releasing -memory. - -# Switching Allocators - -Although the compiler's default choices may work most of the time, it's often -necessary to tweak certain aspects. Overriding the compiler's decision about -which allocator is in use is done simply by linking to the desired allocator: - -```rust,no_run -#![feature(alloc_system)] - -extern crate alloc_system; - -fn main() { - let a = Box::new(4); // Allocates from the system allocator. - println!("{}", a); -} -``` - -In this example the binary generated will not link to jemalloc by default but -instead use the system allocator. Conversely to generate a dynamic library which -uses jemalloc by default one would write: - -```rust,ignore -#![feature(alloc_jemalloc)] -#![crate_type = "dylib"] - -extern crate alloc_jemalloc; - -pub fn foo() { - let a = Box::new(4); // Allocates from jemalloc. - println!("{}", a); -} -# fn main() {} -``` +This feature has been replaced by [the `jemallocator` crate on crates.io.][jemallocator]. +[jemallocator]: https://crates.io/crates/jemallocator diff --git a/src/doc/unstable-book/src/library-features/alloc-system.md b/src/doc/unstable-book/src/library-features/alloc-system.md index 1d261db6ba1b3..9effab202cabd 100644 --- a/src/doc/unstable-book/src/library-features/alloc-system.md +++ b/src/doc/unstable-book/src/library-features/alloc-system.md @@ -1,10 +1,10 @@ # `alloc_system` -The tracking issue for this feature is: [#33082] +The tracking issue for this feature is: [#32838] -[#33082]: https://github.com/rust-lang/rust/issues/33082 +[#32838]: https://github.com/rust-lang/rust/issues/32838 -See also [`alloc_jemalloc`](library-features/alloc-jemalloc.html). +See also [`global_allocator`](language-features/global-allocator.html). ------------------------ @@ -30,13 +30,18 @@ memory. Although the compiler's default choices may work most of the time, it's often necessary to tweak certain aspects. Overriding the compiler's decision about -which allocator is in use is done simply by linking to the desired allocator: +which allocator is in use is done through the `#[global_allocator]` attribute: ```rust,no_run -#![feature(alloc_system)] +#![feature(alloc_system, global_allocator, allocator_api)] extern crate alloc_system; +use alloc_system::System; + +#[global_allocator] +static A: System = System; + fn main() { let a = Box::new(4); // Allocates from the system allocator. println!("{}", a); @@ -47,11 +52,22 @@ In this example the binary generated will not link to jemalloc by default but instead use the system allocator. Conversely to generate a dynamic library which uses jemalloc by default one would write: +(The `alloc_jemalloc` crate cannot be used to control the global allocator, +crate.io’s `jemallocator` crate provides equivalent functionality.) + +```toml +# Cargo.toml +[dependencies] +jemallocator = "0.1" +``` ```rust,ignore -#![feature(alloc_jemalloc)] +#![feature(global_allocator)] #![crate_type = "dylib"] -extern crate alloc_jemalloc; +extern crate jemallocator; + +#[global_allocator] +static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; pub fn foo() { let a = Box::new(4); // Allocates from jemalloc. @@ -59,4 +75,3 @@ pub fn foo() { } # fn main() {} ``` - diff --git a/src/liballoc_system/lib.rs b/src/liballoc_system/lib.rs index 2eb659699eb9b..7aa5f8a9186b0 100644 --- a/src/liballoc_system/lib.rs +++ b/src/liballoc_system/lib.rs @@ -14,7 +14,7 @@ #![unstable(feature = "alloc_system", reason = "this library is unlikely to be stabilized in its current \ form or name", - issue = "27783")] + issue = "32838")] #![feature(global_allocator)] #![feature(allocator_api)] #![feature(alloc)] diff --git a/src/librustc/ich/impls_ty.rs b/src/librustc/ich/impls_ty.rs index f719ce150924f..50f7e4ba176e5 100644 --- a/src/librustc/ich/impls_ty.rs +++ b/src/librustc/ich/impls_ty.rs @@ -518,7 +518,7 @@ impl_stable_hash_for!(enum ty::cast::CastKind { FnPtrAddrCast }); -impl_stable_hash_for!(struct ::middle::region::FirstStatementIndex { idx }); +impl_stable_hash_for!(tuple_struct ::middle::region::FirstStatementIndex { idx }); impl_stable_hash_for!(struct ::middle::region::Scope { id, code }); impl<'gcx> ToStableHashKey> for region::Scope { diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 635bcbf7771e3..fa4ee7c009291 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -156,26 +156,11 @@ pub struct BlockRemainder { pub first_statement_index: FirstStatementIndex, } -#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable, - RustcDecodable, Copy)] -pub struct FirstStatementIndex { pub idx: u32 } - -impl Idx for FirstStatementIndex { - fn new(idx: usize) -> Self { - assert!(idx <= SCOPE_DATA_REMAINDER_MAX as usize); - FirstStatementIndex { idx: idx as u32 } - } - - fn index(self) -> usize { - self.idx as usize - } -} - -impl fmt::Debug for FirstStatementIndex { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self.index(), formatter) - } -} +newtype_index!(FirstStatementIndex + { + DEBUG_NAME = "", + MAX = SCOPE_DATA_REMAINDER_MAX, + }); impl From for Scope { #[inline] @@ -208,7 +193,7 @@ impl Scope { SCOPE_DATA_DESTRUCTION => ScopeData::Destruction(self.id), idx => ScopeData::Remainder(BlockRemainder { block: self.id, - first_statement_index: FirstStatementIndex { idx } + first_statement_index: FirstStatementIndex::new(idx as usize) }) } } diff --git a/src/librustc_data_structures/indexed_vec.rs b/src/librustc_data_structures/indexed_vec.rs index 6c5a37aa1e575..1d1b367de200e 100644 --- a/src/librustc_data_structures/indexed_vec.rs +++ b/src/librustc_data_structures/indexed_vec.rs @@ -65,7 +65,7 @@ macro_rules! newtype_index { (@type[$type:ident] @max[$max:expr] @debug_name[$debug_name:expr]) => ( #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, RustcEncodable, RustcDecodable)] - pub struct $type(u32); + pub struct $type(pub u32); impl Idx for $type { fn new(value: usize) -> Self { @@ -99,7 +99,7 @@ macro_rules! newtype_index { // Replace existing default for max (@type[$type:ident] @max[$_max:expr] @debug_name[$debug_name:expr] MAX = $max:expr, $($tokens:tt)*) => ( - newtype_index!(@type[$type] @max[$max] @debug_name[$debug_name] $(tokens)*); + newtype_index!(@type[$type] @max[$max] @debug_name[$debug_name] $($tokens)*); ); // Replace existing default for debug_name diff --git a/src/librustc_mir/diagnostics.rs b/src/librustc_mir/diagnostics.rs index 98c5345c69d35..0f67f7bf6deb4 100644 --- a/src/librustc_mir/diagnostics.rs +++ b/src/librustc_mir/diagnostics.rs @@ -320,20 +320,68 @@ Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out of `x` when we set `y`. This is fundamental to Rust's ownership system: outside of workarounds like `Rc`, a value cannot be owned by more than one variable. -If we own the type, the easiest way to address this problem is to implement -`Copy` and `Clone` on it, as shown below. This allows `y` to copy the -information in `x`, while leaving the original version owned by `x`. Subsequent -changes to `x` will not be reflected when accessing `y`. +Sometimes we don't need to move the value. Using a reference, we can let another +function borrow the value without changing its ownership. In the example below, +we don't actually have to move our string to `calculate_length`, we can give it +a reference to it with `&` instead. + +``` +fn main() { + let s1 = String::from("hello"); + + let len = calculate_length(&s1); + + println!("The length of '{}' is {}.", s1, len); +} + +fn calculate_length(s: &String) -> usize { + s.len() +} +``` + +A mutable reference can be created with `&mut`. + +Sometimes we don't want a reference, but a duplicate. All types marked `Clone` +can be duplicated by calling `.clone()`. Subsequent changes to a clone do not +affect the original variable. + +Most types in the standard library are marked `Clone`. The example below +demonstrates using `clone()` on a string. `s1` is first set to "many", and then +copied to `s2`. Then the first character of `s1` is removed, without affecting +`s2`. "any many" is printed to the console. + +``` +fn main() { + let mut s1 = String::from("many"); + let s2 = s1.clone(); + s1.remove(0); + println!("{} {}", s1, s2); +} +``` + +If we control the definition of a type, we can implement `Clone` on it ourselves +with `#[derive(Clone)]`. + +Some types have no ownership semantics at all and are trivial to duplicate. An +example is `i32` and the other number types. We don't have to call `.clone()` to +clone them, because they are marked `Copy` in addition to `Clone`. Implicit +cloning is more convienient in this case. We can mark our own types `Copy` if +all their members also are marked `Copy`. + +In the example below, we implement a `Point` type. Because it only stores two +integers, we opt-out of ownership semantics with `Copy`. Then we can +`let p2 = p1` without `p1` being moved. ``` #[derive(Copy, Clone)] -struct MyStruct { s: u32 } +struct Point { x: i32, y: i32 } fn main() { - let mut x = MyStruct{ s: 5u32 }; - let y = x; - x.s = 6; - println!("{}", x.s); + let mut p1 = Point{ x: -1, y: 2 }; + let p2 = p1; + p1.x = 1; + println!("p1: {}, {}", p1.x, p1.y); + println!("p2: {}, {}", p2.x, p2.y); } ``` diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e217978648efa..ad171c4babbce 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -238,6 +238,7 @@ impl Clean for CrateNum { if prim.is_some() { break; } + // FIXME: should warn on unknown primitives? } } } @@ -1627,6 +1628,7 @@ pub enum PrimitiveType { Slice, Array, Tuple, + Unit, RawPointer, Reference, Fn, @@ -1662,7 +1664,11 @@ impl Type { Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p), Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice), Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array), - Tuple(..) => Some(PrimitiveType::Tuple), + Tuple(ref tys) => if tys.is_empty() { + Some(PrimitiveType::Unit) + } else { + Some(PrimitiveType::Tuple) + }, RawPointer(..) => Some(PrimitiveType::RawPointer), BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference), BareFunction(..) => Some(PrimitiveType::Fn), @@ -1708,7 +1714,11 @@ impl GetDefId for Type { BorrowedRef { type_: box Generic(..), .. } => Primitive(PrimitiveType::Reference).def_id(), BorrowedRef { ref type_, .. } => type_.def_id(), - Tuple(..) => Primitive(PrimitiveType::Tuple).def_id(), + Tuple(ref tys) => if tys.is_empty() { + Primitive(PrimitiveType::Unit).def_id() + } else { + Primitive(PrimitiveType::Tuple).def_id() + }, BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(), Slice(..) => Primitive(PrimitiveType::Slice).def_id(), Array(..) => Primitive(PrimitiveType::Array).def_id(), @@ -1742,6 +1752,7 @@ impl PrimitiveType { "array" => Some(PrimitiveType::Array), "slice" => Some(PrimitiveType::Slice), "tuple" => Some(PrimitiveType::Tuple), + "unit" => Some(PrimitiveType::Unit), "pointer" => Some(PrimitiveType::RawPointer), "reference" => Some(PrimitiveType::Reference), "fn" => Some(PrimitiveType::Fn), @@ -1772,6 +1783,7 @@ impl PrimitiveType { Array => "array", Slice => "slice", Tuple => "tuple", + Unit => "unit", RawPointer => "pointer", Reference => "reference", Fn => "fn", @@ -2693,6 +2705,7 @@ fn build_deref_target_impls(cx: &DocContext, Slice => tcx.lang_items().slice_impl(), Array => tcx.lang_items().slice_impl(), Tuple => None, + Unit => None, RawPointer => tcx.lang_items().const_ptr_impl(), Reference => None, Fn => None, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 6303fd662bf2b..18d6b1cc1e0f0 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -614,7 +614,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt: } clean::Tuple(ref typs) => { match &typs[..] { - &[] => primitive_link(f, PrimitiveType::Tuple, "()"), + &[] => primitive_link(f, PrimitiveType::Unit, "()"), &[ref one] => { primitive_link(f, PrimitiveType::Tuple, "(")?; //carry f.alternate() into this display w/o branching manually diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 8f7cd244c2fa6..e9a3cfd908eb3 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -39,6 +39,13 @@ "associatedconstant", "union"]; + // On the search screen, so you remain on the last tab you opened. + // + // 0 for "Types/modules" + // 1 for "As parameters" + // 2 for "As return value" + var currentTab = 0; + function hasClass(elem, className) { if (elem && className && elem.className) { var elemClass = elem.className; @@ -758,7 +765,7 @@ var output = ''; if (array.length > 0) { - output = ``; + output = '
'; var shown = []; array.forEach(function(item) { @@ -812,7 +819,7 @@ }); output += '
'; } else { - output = `
No results :(
` + + output = '
No results :(
' + 'Try on DuckDuckGo?
'; @@ -820,6 +827,13 @@ return output; } + function makeTabHeader(tabNb, text) { + if (currentTab === tabNb) { + return '
' + text + '
'; + } + return '
' + text + '
'; + } + function showResults(results) { var output, query = getQuery(); @@ -827,9 +841,10 @@ output = '

Results for ' + escape(query.query) + (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '

' + '
' + - '
Types/modules
' + - '
As parameters
' + - '
As return value
'; + makeTabHeader(0, "Types/modules") + + makeTabHeader(1, "As parameters") + + makeTabHeader(2, "As return value") + + '
'; output += addTab(results['others'], query); output += addTab(results['in_args'], query, false); @@ -1405,6 +1420,9 @@ // In the search display, allows to switch between tabs. function printTab(nb) { + if (nb === 0 || nb === 1 || nb === 2) { + currentTab = nb; + } var nb_copy = nb; onEach(document.getElementById('titles').childNodes, function(elem) { if (nb_copy === 0) { diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 890e1169c0591..20da99a6b1376 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -170,6 +170,9 @@ pub fn opts() -> Vec { stable("no-default", |o| { o.optflag("", "no-defaults", "don't run the default passes") }), + stable("document-private-items", |o| { + o.optflag("", "document-private-items", "document private items") + }), stable("test", |o| o.optflag("", "test", "run code examples as tests")), stable("test-args", |o| { o.optmulti("", "test-args", "arguments to pass to the test runner", @@ -275,6 +278,9 @@ pub fn main_args(args: &[String]) -> isize { // Check for unstable options. nightly_options::check_nightly_options(&matches, &opts()); + // check for deprecated options + check_deprecated_options(&matches); + if matches.opt_present("h") || matches.opt_present("help") { usage("rustdoc"); return 0; @@ -458,6 +464,18 @@ where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R { let mut passes = matches.opt_strs("passes"); let mut plugins = matches.opt_strs("plugins"); + // We hardcode in the passes here, as this is a new flag and we + // are generally deprecating passes. + if matches.opt_present("document-private-items") { + default_passes = false; + + passes = vec![ + String::from("strip-hidden"), + String::from("collapse-docs"), + String::from("unindent-comments"), + ]; + } + // First, parse the crate and extract all relevant information. let mut paths = SearchPaths::new(); for s in &matches.opt_strs("L") { @@ -550,3 +568,26 @@ where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R { }); rx.recv().unwrap() } + +/// Prints deprecation warnings for deprecated options +fn check_deprecated_options(matches: &getopts::Matches) { + let deprecated_flags = [ + "input-format", + "output-format", + "plugin-path", + "plugins", + "no-defaults", + "passes", + ]; + + for flag in deprecated_flags.into_iter() { + if matches.opt_present(flag) { + eprintln!("WARNING: the '{}' flag is considered deprecated", flag); + eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136"); + } + } + + if matches.opt_present("no-defaults") { + eprintln!("WARNING: (you may want to use --document-private-items)"); + } +} diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index a53c76a333a99..cb18eed8ee54b 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -325,7 +325,10 @@ impl LocalKey { /// /// Once the initialization expression succeeds, the key transitions to the /// `Valid` state which will guarantee that future calls to [`with`] will - /// succeed within the thread. + /// succeed within the thread. Some keys might skip the `Uninitialized` + /// state altogether and start in the `Valid` state as an optimization + /// (e.g. keys initialized with a constant expression), but no guarantees + /// are made. /// /// When a thread exits, each key will be destroyed in turn, and as keys are /// destroyed they will enter the `Destroyed` state just before the diff --git a/src/test/codegen/abi-x86-interrupt.rs b/src/test/codegen/abi-x86-interrupt.rs index 838cd4bf6d745..e0b37cb2f3224 100644 --- a/src/test/codegen/abi-x86-interrupt.rs +++ b/src/test/codegen/abi-x86-interrupt.rs @@ -14,7 +14,6 @@ // ignore-arm // ignore-aarch64 -// min-llvm-version 3.8 // compile-flags: -C no-prepopulate-passes diff --git a/src/test/codegen/mainsubprogram.rs b/src/test/codegen/mainsubprogram.rs index 657f4b662f728..f0508bc90f20c 100644 --- a/src/test/codegen/mainsubprogram.rs +++ b/src/test/codegen/mainsubprogram.rs @@ -8,14 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// The minimum LLVM version is set to 3.8, but really this test -// depends on a patch that is was committed to upstream LLVM before -// 4.0; and also backported to the Rust LLVM fork. +// This test depends on a patch that was committed to upstream LLVM +// before 4.0, formerly backported to the Rust LLVM fork. // ignore-tidy-linelength // ignore-windows // ignore-macos -// min-llvm-version 3.8 +// min-llvm-version 4.0 // compile-flags: -g -C no-prepopulate-passes diff --git a/src/test/codegen/mainsubprogramstart.rs b/src/test/codegen/mainsubprogramstart.rs index cd34a1670dc7d..8325318f9afc5 100644 --- a/src/test/codegen/mainsubprogramstart.rs +++ b/src/test/codegen/mainsubprogramstart.rs @@ -8,14 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// The minimum LLVM version is set to 3.8, but really this test -// depends on a patch that is was committed to upstream LLVM before -// 4.0; and also backported to the Rust LLVM fork. +// This test depends on a patch that was committed to upstream LLVM +// before 4.0, formerly backported to the Rust LLVM fork. // ignore-tidy-linelength // ignore-windows // ignore-macos -// min-llvm-version 3.8 +// min-llvm-version 4.0 // compile-flags: -g -C no-prepopulate-passes diff --git a/src/test/run-pass/issue-36023.rs b/src/test/run-pass/issue-36023.rs index 53a8a403b6410..f6c03b384f23d 100644 --- a/src/test/run-pass/issue-36023.rs +++ b/src/test/run-pass/issue-36023.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// min-llvm-version 3.9 - use std::ops::Deref; fn main() { diff --git a/src/test/rustdoc/empty-mod-private.rs b/src/test/rustdoc/empty-mod-private.rs index 6b86af62a663a..6c6af19be88f9 100644 --- a/src/test/rustdoc/empty-mod-private.rs +++ b/src/test/rustdoc/empty-mod-private.rs @@ -9,7 +9,7 @@ // except according to those terms. // ignore-tidy-linelength -// compile-flags: --no-defaults --passes collapse-docs --passes unindent-comments --passes strip-priv-imports +// compile-flags: --document-private-items // @has 'empty_mod_private/index.html' '//a[@href="foo/index.html"]' 'foo' // @has 'empty_mod_private/sidebar-items.js' 'foo' diff --git a/src/test/rustdoc/issue-15347.rs b/src/test/rustdoc/issue-15347.rs index 266a30891941d..c50df6edd484a 100644 --- a/src/test/rustdoc/issue-15347.rs +++ b/src/test/rustdoc/issue-15347.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// compile-flags:--no-defaults --passes collapse-docs --passes unindent-comments +// compile-flags: --no-defaults --passes collapse-docs --passes unindent-comments // @has issue_15347/fn.foo.html #[doc(hidden)] diff --git a/src/test/rustdoc/pub-method.rs b/src/test/rustdoc/pub-method.rs index 5998734e4a20c..24d566e082eea 100644 --- a/src/test/rustdoc/pub-method.rs +++ b/src/test/rustdoc/pub-method.rs @@ -9,7 +9,7 @@ // except according to those terms. // ignore-tidy-linelength -// compile-flags: --no-defaults --passes collapse-docs --passes unindent-comments --passes strip-priv-imports +// compile-flags: --document-private-items #![crate_name = "foo"]