Brian Dawn <brian.t.dawn@gmail.com>
Brian Leibig <brian@brianleibig.com> Brian Leibig <brian.leibig@gmail.com>
Carl-Anton Ingmarsson <mail@carlanton.se> <ca.ingmarsson@gmail.com>
-Carol (Nichols || Goulding) <carol.nichols@gmail.com> Carol Nichols <carol.nichols@gmail.com>
-Carol (Nichols || Goulding) <carol.nichols@gmail.com> Carol Nichols <cnichols@thinkthroughmath.com>
+Carol (Nichols || Goulding) <carol.nichols@gmail.com>
+Carol (Nichols || Goulding) <cnichols@thinkthroughmath.com>
Carol Willing <carolcode@willingconsulting.com>
Chris C Cerami <chrisccerami@users.noreply.github.com> Chris C Cerami <chrisccerami@gmail.com>
Chris Pressey <cpressey@gmail.com>
Jauhien Piatlicki <jauhien@gentoo.org> Jauhien Piatlicki <jpiatlicki@zertisa.com>
Jay True <glacjay@gmail.com>
Jeremy Letang <letang.jeremy@gmail.com>
+Jethro Beekman <github@jbeekman.nl>
Jihyun Yu <j.yu@navercorp.com> <yjh0502@gmail.com>
Jihyun Yu <j.yu@navercorp.com> jihyun <jihyun@nablecomm.com>
Jihyun Yu <j.yu@navercorp.com> Jihyun Yu <jihyun@nclab.kaist.ac.kr>
SRC=.
os: osx
osx_image: xcode8.2
- before_script: &osx_before_script >
- ulimit -c unlimited
install: &osx_install_sccache >
curl -L https://api.pub.build.mozilla.org/tooltool/sha512/d0025b286468cc5ada83b23d3fafbc936b9f190eaa7d4a981715b18e8e3bf720a7bcee7bfe758cfdeb8268857f6098fd52dcdd8818232692a30ce91039936596 |
tar xJf - -C /usr/local/bin --strip-components=1
- after_failure: &osx_after_failure >
- echo 'bt all' > cmds;
- for file in $(ls /cores); do
- echo core file $file;
- lldb -c /cores/$file `which ld` -b -s cmds;
- done
- env: >
SCRIPT="./x.py test && ./x.py dist"
DEPLOY=1
os: osx
osx_image: xcode8.2
- before_script: *osx_before_script
install: *osx_install_sccache
- after_failure: *osx_after_failure
- env: >
RUST_CHECK_TARGET=check
RUST_CONFIGURE_ARGS=--build=x86_64-apple-darwin --disable-rustbuild
SRC=.
os: osx
osx_image: xcode8.2
- before_script: *osx_before_script
install: *osx_install_sccache
- after_failure: *osx_after_failure
- env: >
RUST_CHECK_TARGET=dist
RUST_CONFIGURE_ARGS="--target=aarch64-apple-ios,armv7-apple-ios,armv7s-apple-ios,i386-apple-ios,x86_64-apple-ios --enable-extended"
DEPLOY=1
os: osx
osx_image: xcode8.2
- before_script: *osx_before_script
install: *osx_install_sccache
- after_failure: *osx_after_failure
env:
global:
- mkdir -p deploy/$TRAVIS_COMMIT
- >
if [ "$TRAVIS_OS_NAME" == "osx" ]; then
- cp build/dist/*.tar.gz deploy/$TRAVIS_COMMIT;
+ cp -r build/dist deploy/$TRAVIS_COMMIT;
else
- cp obj/build/dist/*.tar.gz deploy/$TRAVIS_COMMIT;
+ cp -r obj/build/dist deploy/$TRAVIS_COMMIT;
fi
deploy:
before_deploy:
- ps: |
New-Item -Path deploy -ItemType directory
- Get-ChildItem -Path build\dist -Filter '*.tar.gz' | Move-Item -Destination deploy
+ Get-ChildItem -Path build\dist | Move-Item -Destination deploy
Get-ChildItem -Path deploy | Foreach-Object {
Push-AppveyorArtifact $_.FullName -FileName ${env:APPVEYOR_REPO_COMMIT}/$_
}
bucket: rust-lang-ci
set_public: true
region: us-east-1
- artifact: /.*\.tar.gz/
+ artifact: /.*/
folder: rustc-builds
on:
branch: auto
"toml 0.1.30 (registry+https://github.com/rust-lang/crates.io-index)",
]
+[[package]]
+name = "build-manifest"
+version = "0.1.0"
+dependencies = [
+ "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)",
+ "toml 0.1.30 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
[[package]]
name = "build_helper"
version = "0.1.0"
"tools/linkchecker",
"tools/rustbook",
"tools/tidy",
+ "tools/build-manifest",
]
# Curiously, compiletest will segfault if compiled with opt-level=3 on 64-bit
pub cargo: Option<PathBuf>,
pub local_rebuild: bool,
+ // dist misc
+ pub dist_sign_folder: Option<PathBuf>,
+ pub dist_upload_addr: Option<String>,
+ pub dist_gpg_password_file: Option<PathBuf>,
+
// libstd features
pub debug_jemalloc: bool,
pub use_jemalloc: bool,
llvm: Option<Llvm>,
rust: Option<Rust>,
target: Option<HashMap<String, TomlTarget>>,
+ dist: Option<Dist>,
}
/// TOML representation of various global build decisions.
targets: Option<String>,
}
+#[derive(RustcDecodable, Default, Clone)]
+struct Dist {
+ sign_folder: Option<String>,
+ gpg_password_file: Option<String>,
+ upload_addr: Option<String>,
+}
+
#[derive(RustcDecodable)]
enum StringOrBool {
String(String),
}
}
+ if let Some(ref t) = toml.dist {
+ config.dist_sign_folder = t.sign_folder.clone().map(PathBuf::from);
+ config.dist_gpg_password_file = t.gpg_password_file.clone().map(PathBuf::from);
+ config.dist_upload_addr = t.upload_addr.clone();
+ }
+
return config
}
# that this option only makes sense for MUSL targets that produce statically
# linked binaries
#musl-root = "..."
+
+# =============================================================================
+# Distribution options
+#
+# These options are related to distribution, mostly for the Rust project itself.
+# You probably won't need to concern yourself with any of these options
+# =============================================================================
+[dist]
+
+# This is the folder of artifacts that the build system will sign. All files in
+# this directory will be signed with the default gpg key using the system `gpg`
+# binary. The `asc` and `sha256` files will all be output into the standard dist
+# output folder (currently `build/dist`)
+#
+# This folder should be populated ahead of time before the build system is
+# invoked.
+#sign-folder = "path/to/folder/to/sign"
+
+# This is a file which contains the password of the default gpg key. This will
+# be passed to `gpg` down the road when signing all files in `sign-folder`
+# above. This should be stored in plaintext.
+#gpg-password-file = "path/to/gpg/password"
+
+# The remote address that all artifacts will eventually be uploaded to. The
+# build system generates manifests which will point to these urls, and for the
+# manifests to be correct they'll have to have the right URLs encoded.
+#
+# Note that this address should not contain a trailing slash as file names will
+# be appended to it.
+#upload-addr = "https://example.com/folder"
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{PathBuf, Path};
-use std::process::Command;
+use std::process::{Command, Stdio};
use build_helper::output;
cmd.env("CFG_PLATFORM", "x86");
}
}
+
+pub fn hash_and_sign(build: &Build) {
+ let compiler = Compiler::new(0, &build.config.build);
+ let mut cmd = build.tool_cmd(&compiler, "build-manifest");
+ let sign = build.config.dist_sign_folder.as_ref().unwrap_or_else(|| {
+ panic!("\n\nfailed to specify `dist.sign-folder` in `config.toml`\n\n")
+ });
+ let addr = build.config.dist_upload_addr.as_ref().unwrap_or_else(|| {
+ panic!("\n\nfailed to specify `dist.upload-addr` in `config.toml`\n\n")
+ });
+ let file = build.config.dist_gpg_password_file.as_ref().unwrap_or_else(|| {
+ panic!("\n\nfailed to specify `dist.gpg-password-file` in `config.toml`\n\n")
+ });
+ let mut pass = String::new();
+ t!(t!(File::open(&file)).read_to_string(&mut pass));
+
+ let today = output(Command::new("date").arg("+%Y-%m-%d"));
+
+ cmd.arg(sign);
+ cmd.arg(distdir(build));
+ cmd.arg(today.trim());
+ cmd.arg(package_vers(build));
+ cmd.arg(addr);
+
+ t!(fs::create_dir_all(distdir(build)));
+
+ let mut child = t!(cmd.stdin(Stdio::piped()).spawn());
+ t!(child.stdin.take().unwrap().write_all(pass.as_bytes()));
+ let status = t!(child.wait());
+ assert!(status.success());
+}
rules.build("tool-compiletest", "src/tools/compiletest")
.dep(|s| s.name("libtest"))
.run(move |s| compile::tool(build, s.stage, s.target, "compiletest"));
+ rules.build("tool-build-manifest", "src/tools/build-manifest")
+ .dep(|s| s.name("libstd"))
+ .run(move |s| compile::tool(build, s.stage, s.target, "build-manifest"));
// ========================================================================
// Documentation targets
.dep(|d| d.name("dist-cargo"))
.run(move |s| dist::extended(build, s.stage, s.target));
+ rules.dist("dist-sign", "hash-and-sign")
+ .host(true)
+ .only_build(true)
+ .only_host_build(true)
+ .dep(move |s| s.name("tool-build-manifest").target(&build.config.build).stage(0))
+ .run(move |_| dist::hash_and_sign(build));
+
rules.verify();
return rules;
}
those who abort the process. See the documentation of [`catch_unwind()`]
for more information.
-[`catch_unwind()`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
+[`catch_unwind()`]: ../std/panic/fn.catch_unwind.html
# Representing opaque structs
For instance, a custom implementation of `Box` might write `Drop` like this:
```rust
-#![feature(alloc, heap_api, drop_in_place, unique)]
+#![feature(alloc, heap_api, unique)]
extern crate alloc;
However this wouldn't work:
```rust
-#![feature(alloc, heap_api, drop_in_place, unique)]
+#![feature(alloc, heap_api, unique)]
extern crate alloc;
of Self during `drop` is to use an Option:
```rust
-#![feature(alloc, heap_api, drop_in_place, unique)]
+#![feature(alloc, heap_api, unique)]
extern crate alloc;
/// as long as `T` implements [`Send`] and [`Sync`][sync]. The disadvantage is
/// that atomic operations are more expensive than ordinary memory accesses.
/// If you are not sharing reference-counted values between threads, consider
-/// using [`rc::Rc`] for lower overhead. [`Rc`] is a safe default, because
+/// using [`rc::Rc`][`Rc`] for lower overhead. [`Rc`] is a safe default, because
/// the compiler will catch any attempt to send an [`Rc`] between threads.
/// However, a library might choose `Arc` in order to give library consumers
/// more flexibility.
reason = "matches collection reform specification, \
waiting for dust to settle",
issue = "37966")]
+#![rustc_deprecated(since = "1.16.0", reason = "long since replaced")]
+#![allow(deprecated)]
use core::marker;
use core::fmt;
#[doc(no_inline)]
pub use linked_list::LinkedList;
#[doc(no_inline)]
+#[allow(deprecated)]
pub use enum_set::EnumSet;
#[doc(no_inline)]
pub use vec_deque::VecDeque;
core_slice::SliceExt::swap(self, a, b)
}
- /// Reverse the order of elements in a slice, in place.
+ /// Reverses the order of elements in a slice, in place.
///
/// # Example
///
core_slice::SliceExt::binary_search_by_key(self, b, f)
}
- /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
+ /// Sorts the slice.
///
/// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
///
/// Basic usage:
///
/// ```
- /// # #![feature(str_replacen)]
/// let s = "foo foo 123 foo";
/// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
/// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
/// When the pattern doesn't match:
///
/// ```
- /// # #![feature(str_replacen)]
/// let s = "this is old";
/// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
/// ```
- #[unstable(feature = "str_replacen",
- issue = "36436",
- reason = "only need to replace first N matches")]
+ #[stable(feature = "str_replacen", since = "1.16.0")]
pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
// Hope to reduce the times of re-allocation
let mut result = String::with_capacity(32);
/// Basic usage:
///
/// ```
- /// #![feature(repeat_str)]
- ///
/// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
/// ```
- #[unstable(feature = "repeat_str", issue = "37079")]
+ #[stable(feature = "repeat_str", since = "1.16.0")]
pub fn repeat(&self, n: usize) -> String {
let mut s = String::with_capacity(self.len() * n);
s.extend((0..n).map(|_| self));
/// Basic usage:
///
/// ```
- /// #![feature(insert_str)]
- ///
/// let mut s = String::from("bar");
///
/// s.insert_str(0, "foo");
/// assert_eq!("foobar", s);
/// ```
#[inline]
- #[unstable(feature = "insert_str",
- reason = "recent addition",
- issue = "35553")]
+ #[stable(feature = "insert_str", since = "1.16.0")]
pub fn insert_str(&mut self, idx: usize, string: &str) {
assert!(self.is_char_boundary(idx));
/// # Examples
///
/// ```
- /// # #![feature(string_split_off)]
/// # fn main() {
/// let mut hello = String::from("Hello, World!");
/// let world = hello.split_off(7);
/// # }
/// ```
#[inline]
- #[unstable(feature = "string_split_off", issue = "38080")]
+ #[stable(feature = "string_split_off", since = "1.16.0")]
pub fn split_off(&mut self, mid: usize) -> String {
assert!(self.is_char_boundary(mid));
let other = self.vec.split_off(mid);
/// # Examples
///
/// ```
- /// #![feature(dedup_by)]
- ///
/// let mut vec = vec![10, 20, 21, 30, 20];
///
/// vec.dedup_by_key(|i| *i / 10);
///
/// assert_eq!(vec, [10, 20, 30, 20]);
/// ```
- #[unstable(feature = "dedup_by", reason = "recently added", issue = "37087")]
+ #[stable(feature = "dedup_by", since = "1.16.0")]
#[inline]
pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
self.dedup_by(|a, b| key(a) == key(b))
/// # Examples
///
/// ```
- /// #![feature(dedup_by)]
/// use std::ascii::AsciiExt;
///
/// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
///
/// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
/// ```
- #[unstable(feature = "dedup_by", reason = "recently added", issue = "37087")]
+ #[stable(feature = "dedup_by", since = "1.16.0")]
pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
unsafe {
// Although we have a mutable reference to `self`, we cannot make
/// # Examples
///
/// ```
- /// #![feature(deque_extras)]
- ///
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// assert_eq!(buf.len(), 1);
/// assert_eq!(Some(&5), buf.get(0));
/// ```
- #[unstable(feature = "deque_extras",
- reason = "matches collection reform specification; waiting on panic semantics",
- issue = "27788")]
+ #[stable(feature = "deque_extras", since = "1.16.0")]
pub fn truncate(&mut self, len: usize) {
for _ in len..self.len() {
self.pop_back();
/// # Examples
///
/// ```
- /// #![feature(deque_extras)]
- ///
/// use std::collections::VecDeque;
///
/// let mut buf = VecDeque::new();
/// assert_eq!(a, b);
/// }
/// ```
- #[unstable(feature = "deque_extras",
- reason = "matches collection reform specification; waiting on panic semantics",
- issue = "27788")]
+ #[stable(feature = "deque_extras", since = "1.16.0")]
pub fn resize(&mut self, new_len: usize, value: T) {
let len = self.len();
+++ /dev/null
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
-// file at the top-level directory of this distribution and at
-// http://rust-lang.org/COPYRIGHT.
-//
-// Licensed under the Apache License, Version 2.0 <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 std::mem;
-
-use collections::enum_set::{CLike, EnumSet};
-
-use self::Foo::*;
-
-#[derive(Copy, Clone, PartialEq, Debug)]
-#[repr(usize)]
-enum Foo {
- A,
- B,
- C,
-}
-
-impl CLike for Foo {
- fn to_usize(&self) -> usize {
- *self as usize
- }
-
- fn from_usize(v: usize) -> Foo {
- unsafe { mem::transmute(v) }
- }
-}
-
-#[test]
-fn test_new() {
- let e: EnumSet<Foo> = EnumSet::new();
- assert!(e.is_empty());
-}
-
-#[test]
-fn test_show() {
- let mut e = EnumSet::new();
- assert!(format!("{:?}", e) == "{}");
- e.insert(A);
- assert!(format!("{:?}", e) == "{A}");
- e.insert(C);
- assert!(format!("{:?}", e) == "{A, C}");
-}
-
-#[test]
-fn test_len() {
- let mut e = EnumSet::new();
- assert_eq!(e.len(), 0);
- e.insert(A);
- e.insert(B);
- e.insert(C);
- assert_eq!(e.len(), 3);
- e.remove(&A);
- assert_eq!(e.len(), 2);
- e.clear();
- assert_eq!(e.len(), 0);
-}
-
-///////////////////////////////////////////////////////////////////////////
-// intersect
-
-#[test]
-fn test_two_empties_do_not_intersect() {
- let e1: EnumSet<Foo> = EnumSet::new();
- let e2: EnumSet<Foo> = EnumSet::new();
- assert!(e1.is_disjoint(&e2));
-}
-
-#[test]
-fn test_empty_does_not_intersect_with_full() {
- let e1: EnumSet<Foo> = EnumSet::new();
-
- let mut e2: EnumSet<Foo> = EnumSet::new();
- e2.insert(A);
- e2.insert(B);
- e2.insert(C);
-
- assert!(e1.is_disjoint(&e2));
-}
-
-#[test]
-fn test_disjoint_intersects() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
- e1.insert(A);
-
- let mut e2: EnumSet<Foo> = EnumSet::new();
- e2.insert(B);
-
- assert!(e1.is_disjoint(&e2));
-}
-
-#[test]
-fn test_overlapping_intersects() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
- e1.insert(A);
-
- let mut e2: EnumSet<Foo> = EnumSet::new();
- e2.insert(A);
- e2.insert(B);
-
- assert!(!e1.is_disjoint(&e2));
-}
-
-///////////////////////////////////////////////////////////////////////////
-// contains and contains_elem
-
-#[test]
-fn test_superset() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
- e1.insert(A);
-
- let mut e2: EnumSet<Foo> = EnumSet::new();
- e2.insert(A);
- e2.insert(B);
-
- let mut e3: EnumSet<Foo> = EnumSet::new();
- e3.insert(C);
-
- assert!(e1.is_subset(&e2));
- assert!(e2.is_superset(&e1));
- assert!(!e3.is_superset(&e2));
- assert!(!e2.is_superset(&e3))
-}
-
-#[test]
-fn test_contains() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
- e1.insert(A);
- assert!(e1.contains(&A));
- assert!(!e1.contains(&B));
- assert!(!e1.contains(&C));
-
- e1.insert(A);
- e1.insert(B);
- assert!(e1.contains(&A));
- assert!(e1.contains(&B));
- assert!(!e1.contains(&C));
-}
-
-///////////////////////////////////////////////////////////////////////////
-// iter
-
-#[test]
-fn test_iterator() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
-
- let elems: Vec<Foo> = e1.iter().collect();
- assert!(elems.is_empty());
-
- e1.insert(A);
- let elems: Vec<_> = e1.iter().collect();
- assert_eq!(elems, [A]);
-
- e1.insert(C);
- let elems: Vec<_> = e1.iter().collect();
- assert_eq!(elems, [A, C]);
-
- e1.insert(C);
- let elems: Vec<_> = e1.iter().collect();
- assert_eq!(elems, [A, C]);
-
- e1.insert(B);
- let elems: Vec<_> = e1.iter().collect();
- assert_eq!(elems, [A, B, C]);
-}
-
-///////////////////////////////////////////////////////////////////////////
-// operators
-
-#[test]
-fn test_operators() {
- let mut e1: EnumSet<Foo> = EnumSet::new();
- e1.insert(A);
- e1.insert(C);
-
- let mut e2: EnumSet<Foo> = EnumSet::new();
- e2.insert(B);
- e2.insert(C);
-
- let e_union = e1 | e2;
- let elems: Vec<_> = e_union.iter().collect();
- assert_eq!(elems, [A, B, C]);
-
- let e_intersection = e1 & e2;
- let elems: Vec<_> = e_intersection.iter().collect();
- assert_eq!(elems, [C]);
-
- // Another way to express intersection
- let e_intersection = e1 - (e1 - e2);
- let elems: Vec<_> = e_intersection.iter().collect();
- assert_eq!(elems, [C]);
-
- let e_subtract = e1 - e2;
- let elems: Vec<_> = e_subtract.iter().collect();
- assert_eq!(elems, [A]);
-
- // Bitwise XOR of two sets, aka symmetric difference
- let e_symmetric_diff = e1 ^ e2;
- let elems: Vec<_> = e_symmetric_diff.iter().collect();
- assert_eq!(elems, [A, B]);
-
- // Another way to express symmetric difference
- let e_symmetric_diff = (e1 - e2) | (e2 - e1);
- let elems: Vec<_> = e_symmetric_diff.iter().collect();
- assert_eq!(elems, [A, B]);
-
- // Yet another way to express symmetric difference
- let e_symmetric_diff = (e1 | e2) - (e1 & e2);
- let elems: Vec<_> = e_symmetric_diff.iter().collect();
- assert_eq!(elems, [A, B]);
-}
-
-#[test]
-#[should_panic]
-fn test_overflow() {
- #[allow(dead_code)]
- #[derive(Copy, Clone)]
- #[repr(usize)]
- enum Bar {
- V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
- V10, V11, V12, V13, V14, V15, V16, V17, V18, V19,
- V20, V21, V22, V23, V24, V25, V26, V27, V28, V29,
- V30, V31, V32, V33, V34, V35, V36, V37, V38, V39,
- V40, V41, V42, V43, V44, V45, V46, V47, V48, V49,
- V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
- V60, V61, V62, V63, V64, V65, V66, V67, V68, V69,
- }
-
- impl CLike for Bar {
- fn to_usize(&self) -> usize {
- *self as usize
- }
-
- fn from_usize(v: usize) -> Bar {
- unsafe { mem::transmute(v) }
- }
- }
- let mut set = EnumSet::new();
- set.insert(Bar::V64);
-}
-
-#[test]
-fn test_extend_ref() {
- let mut a = EnumSet::new();
- a.insert(A);
-
- a.extend(&[A, C]);
-
- assert_eq!(a.len(), 2);
- assert!(a.contains(&A));
- assert!(a.contains(&C));
-
- let mut b = EnumSet::new();
- b.insert(B);
-
- a.extend(&b);
-
- assert_eq!(a.len(), 3);
- assert!(a.contains(&A));
- assert!(a.contains(&B));
- assert!(a.contains(&C));
-}
#![feature(collections)]
#![feature(collections_bound)]
#![feature(const_fn)]
-#![feature(dedup_by)]
-#![feature(enumset)]
#![feature(exact_size_is_empty)]
#![feature(pattern)]
#![feature(placement_in_syntax)]
#![feature(rand)]
-#![feature(repeat_str)]
#![feature(step_by)]
#![feature(str_escape)]
-#![feature(str_replacen)]
-#![feature(string_split_off)]
#![feature(test)]
#![feature(unboxed_closures)]
#![feature(unicode)]
mod binary_heap;
mod btree;
mod cow_str;
-mod enum_set;
mod fmt;
mod linked_list;
mod slice;
/// [`BuildHasher`]: trait.BuildHasher.html
/// [`Default`]: ../default/trait.Default.html
/// [`Hasher`]: trait.Hasher.html
+/// [`HashMap`]: ../../std/collections/struct.HashMap.html
#[stable(since = "1.7.0", feature = "build_hasher")]
pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
///
/// One of the keys to `collect()`'s power is that many things you might
/// not think of as 'collections' actually are. For example, a [`String`]
- /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
- /// be thought of as single [`Result`]`<Collection<T>, E>`. See the examples
- /// below for more.
+ /// is a collection of [`char`]s. And a collection of
+ /// [`Result<T, E>`][`Result`] can be thought of as single
+ /// [`Result`]`<Collection<T>, E>`. See the examples below for more.
///
/// Because `collect()` is so general, it can cause problems with type
/// inference. As such, `collect()` is one of the few times you'll see
/// Basic usage:
///
/// ```
- /// #![feature(ptr_wrapping_offset)]
/// // Iterate using a raw pointer in increments of two elements
/// let data = [1u8, 2, 3, 4, 5];
/// let mut ptr: *const u8 = data.as_ptr();
/// ptr = ptr.wrapping_offset(step);
/// }
/// ```
- #[unstable(feature = "ptr_wrapping_offset", issue = "37570")]
+ #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
#[inline]
pub fn wrapping_offset(self, count: isize) -> *const T where T: Sized {
unsafe {
/// Basic usage:
///
/// ```
- /// #![feature(ptr_wrapping_offset)]
/// // Iterate using a raw pointer in increments of two elements
/// let mut data = [1u8, 2, 3, 4, 5];
/// let mut ptr: *mut u8 = data.as_mut_ptr();
/// }
/// assert_eq!(&data, &[0, 2, 0, 4, 0]);
/// ```
- #[unstable(feature = "ptr_wrapping_offset", issue = "37570")]
+ #[stable(feature = "ptr_wrapping_offset", since = "1.16.0")]
#[inline]
pub fn wrapping_offset(self, count: isize) -> *mut T where T: Sized {
unsafe {
/// `Err` on error.
///
/// ```
- /// #![feature(result_unwrap_or_default)]
- ///
/// let good_year_from_input = "1909";
/// let bad_year_from_input = "190blarg";
/// let good_year = good_year_from_input.parse().unwrap_or_default();
/// [`FromStr`]: ../../std/str/trait.FromStr.html
/// ```
#[inline]
- #[unstable(feature = "result_unwrap_or_default", issue = "37516")]
+ #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
pub fn unwrap_or_default(self) -> T {
match self {
Ok(x) => x,
//! same as [LLVM atomic orderings][1]. For more information see the [nomicon][2].
//!
//! [1]: http://llvm.org/docs/LangRef.html#memory-model-for-concurrent-operations
-//! [2]: https://doc.rust-lang.org/nomicon/atomics.html
+//! [2]: ../../../nomicon/atomics.html
//!
//! Atomic variables are safe to share between threads (they implement `Sync`)
//! but they do not themselves provide the mechanism for sharing and follow the
/// LLVM's](http://llvm.org/docs/LangRef.html#memory-model-for-concurrent-operations).
///
/// For more information see the [nomicon][1].
-/// [1]: https://doc.rust-lang.org/nomicon/atomics.html
+/// [1]: ../../../nomicon/atomics.html
#[stable(feature = "rust1", since = "1.0.0")]
#[derive(Copy, Clone, Debug)]
pub enum Ordering {
#![feature(unicode)]
#![feature(unique)]
#![feature(ordering_chaining)]
-#![feature(result_unwrap_or_default)]
#![feature(ptr_unaligned)]
extern crate core;
//! ported to this system, and which relies on string concatenation at the
//! time of error detection.
-use self::FreshOrKept::*;
-
use super::InferCtxt;
use super::TypeTrace;
use super::SubregionOrigin;
use super::region_inference::ProcessedErrorOrigin;
use super::region_inference::SameRegions;
-use std::collections::HashSet;
-
use hir::map as hir_map;
use hir;
use lint;
-use hir::def::Def;
use hir::def_id::DefId;
use infer;
use middle::region;
use ty::{Region, ReFree};
use ty::error::TypeError;
-use std::cell::{Cell, RefCell};
-use std::char::from_u32;
use std::fmt;
use syntax::ast;
-use syntax::ptr::P;
-use syntax::symbol::Symbol;
-use syntax_pos::{self, Pos, Span};
+use syntax_pos::{Pos, Span};
use errors::DiagnosticBuilder;
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
ProcessedErrors(ref origins,
ref same_regions) => {
if !same_regions.is_empty() {
- self.report_processed_errors(origins, same_regions);
+ self.report_processed_errors(origins);
}
}
}
}
fn report_processed_errors(&self,
- origins: &[ProcessedErrorOrigin<'tcx>],
- same_regions: &[SameRegions]) {
- for (i, origin) in origins.iter().enumerate() {
+ origins: &[ProcessedErrorOrigin<'tcx>]) {
+ for origin in origins.iter() {
let mut err = match *origin {
ProcessedErrorOrigin::VariableFailure(ref var_origin) =>
self.report_inference_failure(var_origin.clone()),
self.report_concrete_failure(sr_origin.clone(), sub, sup),
};
- // attach the suggestion to the last such error
- if i == origins.len() - 1 {
- self.give_suggestion(&mut err, same_regions);
- }
-
err.emit();
}
}
- fn give_suggestion(&self, err: &mut DiagnosticBuilder, same_regions: &[SameRegions]) {
- let scope_id = same_regions[0].scope_id;
- let parent = self.tcx.hir.get_parent(scope_id);
- let parent_node = self.tcx.hir.find(parent);
- let taken = lifetimes_in_scope(self.tcx, scope_id);
- let life_giver = LifeGiver::with_taken(&taken[..]);
- let node_inner = match parent_node {
- Some(ref node) => match *node {
- hir_map::NodeItem(ref item) => {
- match item.node {
- hir::ItemFn(ref fn_decl, unsafety, constness, _, ref gen, body) => {
- Some((fn_decl, gen, unsafety, constness, item.name, item.span, body))
- }
- _ => None,
- }
- }
- hir_map::NodeImplItem(item) => {
- let id = self.tcx.hir.get_parent(item.id);
- if let Some(hir_map::NodeItem(parent_scope)) = self.tcx.hir.find(id) {
- if let hir::ItemImpl(_, _, _, None, _, _) = parent_scope.node {
- // this impl scope implements a trait, do not recomend
- // using explicit lifetimes (#37363)
- return;
- }
- }
- if let hir::ImplItemKind::Method(ref sig, body) = item.node {
- Some((&sig.decl,
- &sig.generics,
- sig.unsafety,
- sig.constness,
- item.name,
- item.span,
- body))
- } else {
- None
- }
- },
- hir_map::NodeTraitItem(item) => {
- match item.node {
- hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
- Some((&sig.decl,
- &sig.generics,
- sig.unsafety,
- sig.constness,
- item.name,
- item.span,
- body))
- }
- _ => None,
- }
- }
- _ => None,
- },
- None => None,
- };
- let (fn_decl, generics, unsafety, constness, name, span, body)
- = node_inner.expect("expect item fn");
- let rebuilder = Rebuilder::new(self.tcx, fn_decl, generics, same_regions, &life_giver);
- let (fn_decl, generics) = rebuilder.rebuild();
- self.give_expl_lifetime_param(
- err, &fn_decl, unsafety, constness, name, &generics, span, body);
- }
-
pub fn issue_32330_warnings(&self, span: Span, issue32330s: &[ty::Issue32330]) {
for issue32330 in issue32330s {
match *issue32330 {
}
}
-struct RebuildPathInfo<'a> {
- path: &'a hir::Path,
- // indexes to insert lifetime on path.lifetimes
- indexes: Vec<u32>,
- // number of lifetimes we expect to see on the type referred by `path`
- // (e.g., expected=1 for struct Foo<'a>)
- expected: u32,
- anon_nums: &'a HashSet<u32>,
- region_names: &'a HashSet<ast::Name>
-}
-
-struct Rebuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
- tcx: TyCtxt<'a, 'gcx, 'tcx>,
- fn_decl: &'a hir::FnDecl,
- generics: &'a hir::Generics,
- same_regions: &'a [SameRegions],
- life_giver: &'a LifeGiver,
- cur_anon: Cell<u32>,
- inserted_anons: RefCell<HashSet<u32>>,
-}
-
-enum FreshOrKept {
- Fresh,
- Kept
-}
-
-impl<'a, 'gcx, 'tcx> Rebuilder<'a, 'gcx, 'tcx> {
- fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>,
- fn_decl: &'a hir::FnDecl,
- generics: &'a hir::Generics,
- same_regions: &'a [SameRegions],
- life_giver: &'a LifeGiver)
- -> Rebuilder<'a, 'gcx, 'tcx> {
- Rebuilder {
- tcx: tcx,
- fn_decl: fn_decl,
- generics: generics,
- same_regions: same_regions,
- life_giver: life_giver,
- cur_anon: Cell::new(0),
- inserted_anons: RefCell::new(HashSet::new()),
- }
- }
-
- fn rebuild(&self) -> (hir::FnDecl, hir::Generics) {
- let mut inputs = self.fn_decl.inputs.clone();
- let mut output = self.fn_decl.output.clone();
- let mut ty_params = self.generics.ty_params.clone();
- let where_clause = self.generics.where_clause.clone();
- let mut kept_lifetimes = HashSet::new();
- for sr in self.same_regions {
- self.cur_anon.set(0);
- self.offset_cur_anon();
- let (anon_nums, region_names) =
- self.extract_anon_nums_and_names(sr);
- let (lifetime, fresh_or_kept) = self.pick_lifetime(®ion_names);
- match fresh_or_kept {
- Kept => { kept_lifetimes.insert(lifetime.name); }
- _ => ()
- }
- 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,
- ®ion_names);
- }
- let fresh_lifetimes = self.life_giver.get_generated_lifetimes();
- let all_region_names = self.extract_all_region_names();
- let generics = self.rebuild_generics(self.generics,
- &fresh_lifetimes,
- &kept_lifetimes,
- &all_region_names,
- ty_params,
- where_clause);
- let new_fn_decl = hir::FnDecl {
- inputs: inputs,
- output: output,
- variadic: self.fn_decl.variadic
- };
- (new_fn_decl, generics)
- }
-
- fn pick_lifetime(&self,
- region_names: &HashSet<ast::Name>)
- -> (hir::Lifetime, FreshOrKept) {
- if !region_names.is_empty() {
- // It's not necessary to convert the set of region names to a
- // vector of string and then sort them. However, it makes the
- // choice of lifetime name deterministic and thus easier to test.
- let mut names = Vec::new();
- for rn in region_names {
- let lt_name = rn.to_string();
- names.push(lt_name);
- }
- names.sort();
- let name = Symbol::intern(&names[0]);
- return (name_to_dummy_lifetime(name), Kept);
- }
- return (self.life_giver.give_lifetime(), Fresh);
- }
-
- fn extract_anon_nums_and_names(&self, same_regions: &SameRegions)
- -> (HashSet<u32>, HashSet<ast::Name>) {
- let mut anon_nums = HashSet::new();
- let mut region_names = HashSet::new();
- for br in &same_regions.regions {
- match *br {
- ty::BrAnon(i) => {
- anon_nums.insert(i);
- }
- ty::BrNamed(_, name, _) => {
- region_names.insert(name);
- }
- _ => ()
- }
- }
- (anon_nums, region_names)
- }
-
- fn extract_all_region_names(&self) -> HashSet<ast::Name> {
- let mut all_region_names = HashSet::new();
- for sr in self.same_regions {
- for br in &sr.regions {
- match *br {
- ty::BrNamed(_, name, _) => {
- all_region_names.insert(name);
- }
- _ => ()
- }
- }
- }
- all_region_names
- }
-
- fn inc_cur_anon(&self, n: u32) {
- let anon = self.cur_anon.get();
- self.cur_anon.set(anon+n);
- }
-
- fn offset_cur_anon(&self) {
- let mut anon = self.cur_anon.get();
- while self.inserted_anons.borrow().contains(&anon) {
- anon += 1;
- }
- self.cur_anon.set(anon);
- }
-
- fn inc_and_offset_cur_anon(&self, n: u32) {
- self.inc_cur_anon(n);
- self.offset_cur_anon();
- }
-
- fn track_anon(&self, anon: u32) {
- self.inserted_anons.borrow_mut().insert(anon);
- }
-
- fn rebuild_ty_params(&self,
- ty_params: hir::HirVec<hir::TyParam>,
- lifetime: hir::Lifetime,
- region_names: &HashSet<ast::Name>)
- -> hir::HirVec<hir::TyParam> {
- ty_params.into_iter().map(|ty_param| {
- let bounds = self.rebuild_ty_param_bounds(ty_param.bounds,
- lifetime,
- region_names);
- hir::TyParam {
- name: ty_param.name,
- id: ty_param.id,
- bounds: bounds,
- default: ty_param.default,
- span: ty_param.span,
- pure_wrt_drop: ty_param.pure_wrt_drop,
- }
- }).collect()
- }
-
- fn rebuild_ty_param_bounds(&self,
- ty_param_bounds: hir::TyParamBounds,
- lifetime: hir::Lifetime,
- region_names: &HashSet<ast::Name>)
- -> hir::TyParamBounds {
- ty_param_bounds.iter().map(|tpb| {
- match tpb {
- &hir::RegionTyParamBound(lt) => {
- // FIXME -- it's unclear whether I'm supposed to
- // substitute lifetime here. I suspect we need to
- // be passing down a map.
- hir::RegionTyParamBound(lt)
- }
- &hir::TraitTyParamBound(ref poly_tr, modifier) => {
- let tr = &poly_tr.trait_ref;
- let last_seg = tr.path.segments.last().unwrap();
- let mut insert = Vec::new();
- let lifetimes = last_seg.parameters.lifetimes();
- for (i, lt) in lifetimes.iter().enumerate() {
- if region_names.contains(<.name) {
- insert.push(i as u32);
- }
- }
- let rebuild_info = RebuildPathInfo {
- path: &tr.path,
- indexes: insert,
- expected: lifetimes.len() as u32,
- anon_nums: &HashSet::new(),
- region_names: region_names
- };
- let new_path = self.rebuild_path(rebuild_info, lifetime);
- hir::TraitTyParamBound(hir::PolyTraitRef {
- bound_lifetimes: poly_tr.bound_lifetimes.clone(),
- trait_ref: hir::TraitRef {
- path: new_path,
- ref_id: tr.ref_id,
- },
- span: poly_tr.span,
- }, modifier)
- }
- }
- }).collect()
- }
-
- fn rebuild_generics(&self,
- generics: &hir::Generics,
- add: &Vec<hir::Lifetime>,
- keep: &HashSet<ast::Name>,
- remove: &HashSet<ast::Name>,
- ty_params: hir::HirVec<hir::TyParam>,
- where_clause: hir::WhereClause)
- -> hir::Generics {
- let mut lifetimes = Vec::new();
- for lt in add {
- lifetimes.push(hir::LifetimeDef {
- lifetime: *lt,
- bounds: hir::HirVec::new(),
- pure_wrt_drop: false,
- });
- }
- for lt in &generics.lifetimes {
- if keep.contains(<.lifetime.name) ||
- !remove.contains(<.lifetime.name) {
- lifetimes.push((*lt).clone());
- }
- }
- hir::Generics {
- lifetimes: lifetimes.into(),
- ty_params: ty_params,
- where_clause: where_clause,
- span: generics.span,
- }
- }
-
- fn rebuild_args_ty(&self,
- inputs: &[P<hir::Ty>],
- lifetime: hir::Lifetime,
- anon_nums: &HashSet<u32>,
- region_names: &HashSet<ast::Name>)
- -> hir::HirVec<P<hir::Ty>> {
- inputs.iter().map(|arg_ty| {
- self.rebuild_arg_ty_or_output(arg_ty, lifetime, anon_nums, region_names)
- }).collect()
- }
-
- fn rebuild_output(&self, ty: &hir::FunctionRetTy,
- lifetime: hir::Lifetime,
- anon_nums: &HashSet<u32>,
- region_names: &HashSet<ast::Name>) -> hir::FunctionRetTy {
- match *ty {
- hir::Return(ref ret_ty) => hir::Return(
- self.rebuild_arg_ty_or_output(&ret_ty, lifetime, anon_nums, region_names)
- ),
- hir::DefaultReturn(span) => hir::DefaultReturn(span),
- }
- }
-
- fn rebuild_arg_ty_or_output(&self,
- ty: &hir::Ty,
- lifetime: hir::Lifetime,
- anon_nums: &HashSet<u32>,
- region_names: &HashSet<ast::Name>)
- -> P<hir::Ty> {
- let mut new_ty = P(ty.clone());
- let mut ty_queue = vec![ty];
- while !ty_queue.is_empty() {
- let cur_ty = ty_queue.remove(0);
- match cur_ty.node {
- hir::TyRptr(lt_opt, ref mut_ty) => {
- let rebuild = match lt_opt {
- Some(lt) => region_names.contains(<.name),
- None => {
- let anon = self.cur_anon.get();
- let rebuild = anon_nums.contains(&anon);
- if rebuild {
- self.track_anon(anon);
- }
- self.inc_and_offset_cur_anon(1);
- rebuild
- }
- };
- if rebuild {
- let to = hir::Ty {
- id: cur_ty.id,
- node: hir::TyRptr(Some(lifetime), mut_ty.clone()),
- span: cur_ty.span
- };
- new_ty = self.rebuild_ty(new_ty, P(to));
- }
- ty_queue.push(&mut_ty.ty);
- }
- hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
- match path.def {
- Def::Enum(did) | Def::TyAlias(did) |
- Def::Struct(did) | Def::Union(did) => {
- let generics = self.tcx.item_generics(did);
-
- let expected =
- generics.regions.len() as u32;
- let lifetimes =
- path.segments.last().unwrap().parameters.lifetimes();
- let mut insert = Vec::new();
- if lifetimes.is_empty() {
- let anon = self.cur_anon.get();
- for (i, a) in (anon..anon+expected).enumerate() {
- if anon_nums.contains(&a) {
- insert.push(i as u32);
- }
- self.track_anon(a);
- }
- self.inc_and_offset_cur_anon(expected);
- } else {
- for (i, lt) in lifetimes.iter().enumerate() {
- if region_names.contains(<.name) {
- insert.push(i as u32);
- }
- }
- }
- let rebuild_info = RebuildPathInfo {
- path: path,
- indexes: insert,
- expected: expected,
- anon_nums: anon_nums,
- region_names: region_names
- };
- let new_path = self.rebuild_path(rebuild_info, lifetime);
- let qself = maybe_qself.as_ref().map(|qself| {
- self.rebuild_arg_ty_or_output(qself, lifetime,
- anon_nums, region_names)
- });
- let to = hir::Ty {
- id: cur_ty.id,
- node: hir::TyPath(hir::QPath::Resolved(qself, P(new_path))),
- span: cur_ty.span
- };
- new_ty = self.rebuild_ty(new_ty, P(to));
- }
- _ => ()
- }
- }
-
- hir::TyPtr(ref mut_ty) => {
- ty_queue.push(&mut_ty.ty);
- }
- hir::TySlice(ref ty) |
- hir::TyArray(ref ty, _) => {
- ty_queue.push(&ty);
- }
- hir::TyTup(ref tys) => ty_queue.extend(tys.iter().map(|ty| &**ty)),
- _ => {}
- }
- }
- new_ty
- }
-
- fn rebuild_ty(&self,
- from: P<hir::Ty>,
- to: P<hir::Ty>)
- -> P<hir::Ty> {
-
- fn build_to(from: P<hir::Ty>,
- to: &mut Option<P<hir::Ty>>)
- -> P<hir::Ty> {
- if Some(from.id) == to.as_ref().map(|ty| ty.id) {
- return to.take().expect("`to` type found more than once during rebuild");
- }
- from.map(|hir::Ty {id, node, span}| {
- let new_node = match node {
- hir::TyRptr(lifetime, mut_ty) => {
- hir::TyRptr(lifetime, hir::MutTy {
- mutbl: mut_ty.mutbl,
- ty: build_to(mut_ty.ty, to),
- })
- }
- hir::TyPtr(mut_ty) => {
- hir::TyPtr(hir::MutTy {
- mutbl: mut_ty.mutbl,
- ty: build_to(mut_ty.ty, to),
- })
- }
- hir::TySlice(ty) => hir::TySlice(build_to(ty, to)),
- hir::TyArray(ty, e) => {
- hir::TyArray(build_to(ty, to), e)
- }
- hir::TyTup(tys) => {
- hir::TyTup(tys.into_iter().map(|ty| build_to(ty, to)).collect())
- }
- other => other
- };
- hir::Ty { id: id, node: new_node, span: span }
- })
- }
-
- build_to(from, &mut Some(to))
- }
-
- fn rebuild_path(&self,
- rebuild_info: RebuildPathInfo,
- lifetime: hir::Lifetime)
- -> hir::Path
- {
- let RebuildPathInfo {
- path,
- indexes,
- expected,
- anon_nums,
- region_names,
- } = rebuild_info;
-
- let last_seg = path.segments.last().unwrap();
- let new_parameters = match last_seg.parameters {
- hir::ParenthesizedParameters(..) => {
- last_seg.parameters.clone()
- }
-
- hir::AngleBracketedParameters(ref data) => {
- let mut new_lts = Vec::new();
- if data.lifetimes.is_empty() {
- // traverse once to see if there's a need to insert lifetime
- let need_insert = (0..expected).any(|i| {
- indexes.contains(&i)
- });
- if need_insert {
- for i in 0..expected {
- if indexes.contains(&i) {
- new_lts.push(lifetime);
- } else {
- new_lts.push(self.life_giver.give_lifetime());
- }
- }
- }
- } else {
- for (i, lt) in data.lifetimes.iter().enumerate() {
- if indexes.contains(&(i as u32)) {
- new_lts.push(lifetime);
- } else {
- new_lts.push(*lt);
- }
- }
- }
- let new_types = data.types.iter().map(|t| {
- self.rebuild_arg_ty_or_output(&t, lifetime, anon_nums, region_names)
- }).collect();
- let new_bindings = data.bindings.iter().map(|b| {
- hir::TypeBinding {
- id: b.id,
- name: b.name,
- ty: self.rebuild_arg_ty_or_output(&b.ty,
- lifetime,
- anon_nums,
- region_names),
- span: b.span
- }
- }).collect();
- hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
- lifetimes: new_lts.into(),
- types: new_types,
- infer_types: data.infer_types,
- bindings: new_bindings,
- })
- }
- };
- let new_seg = hir::PathSegment {
- name: last_seg.name,
- parameters: new_parameters
- };
- let mut new_segs = Vec::new();
- new_segs.extend_from_slice(path.segments.split_last().unwrap().1);
- new_segs.push(new_seg);
- hir::Path {
- span: path.span,
- def: path.def,
- segments: new_segs.into()
- }
- }
-}
-
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
- fn give_expl_lifetime_param(&self,
- err: &mut DiagnosticBuilder,
- decl: &hir::FnDecl,
- unsafety: hir::Unsafety,
- constness: hir::Constness,
- name: ast::Name,
- generics: &hir::Generics,
- span: Span,
- body: hir::BodyId) {
- let s = hir::print::to_string(&self.tcx.hir, |s| {
- use syntax::abi::Abi;
- use syntax::print::pprust::PrintState;
-
- s.head("")?;
- s.print_fn(decl,
- unsafety,
- constness,
- Abi::Rust,
- Some(name),
- generics,
- &hir::Inherited,
- &[],
- Some(body))?;
- s.end()?; // Close the head box
- s.end() // Close the outer box
- });
- let msg = format!("consider using an explicit lifetime parameter as shown: {}", s);
- err.span_help(span, &msg[..]);
- }
-
fn report_inference_failure(&self,
var_origin: RegionVariableOrigin)
-> DiagnosticBuilder<'tcx> {
}
}
-fn lifetimes_in_scope<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
- scope_id: ast::NodeId)
- -> Vec<hir::LifetimeDef> {
- let mut taken = Vec::new();
- let parent = tcx.hir.get_parent(scope_id);
- let method_id_opt = match tcx.hir.find(parent) {
- Some(node) => match node {
- hir_map::NodeItem(item) => match item.node {
- hir::ItemFn(.., ref gen, _) => {
- taken.extend_from_slice(&gen.lifetimes);
- None
- },
- _ => None
- },
- hir_map::NodeImplItem(ii) => {
- match ii.node {
- hir::ImplItemKind::Method(ref sig, _) => {
- taken.extend_from_slice(&sig.generics.lifetimes);
- Some(ii.id)
- }
- _ => None,
- }
- }
- _ => None
- },
- None => None
- };
- if let Some(method_id) = method_id_opt {
- let parent = tcx.hir.get_parent(method_id);
- if let Some(node) = tcx.hir.find(parent) {
- match node {
- hir_map::NodeItem(item) => match item.node {
- hir::ItemImpl(_, _, ref gen, ..) => {
- taken.extend_from_slice(&gen.lifetimes);
- }
- _ => ()
- },
- _ => ()
- }
- }
- }
- return taken;
-}
-
-// LifeGiver is responsible for generating fresh lifetime names
-struct LifeGiver {
- taken: HashSet<String>,
- counter: Cell<usize>,
- generated: RefCell<Vec<hir::Lifetime>>,
-}
-
-impl LifeGiver {
- fn with_taken(taken: &[hir::LifetimeDef]) -> LifeGiver {
- let mut taken_ = HashSet::new();
- for lt in taken {
- let lt_name = lt.lifetime.name.to_string();
- taken_.insert(lt_name);
- }
- LifeGiver {
- taken: taken_,
- counter: Cell::new(0),
- generated: RefCell::new(Vec::new()),
- }
- }
-
- fn inc_counter(&self) {
- let c = self.counter.get();
- self.counter.set(c+1);
- }
-
- fn give_lifetime(&self) -> hir::Lifetime {
- let lifetime;
- loop {
- let mut s = String::from("'");
- s.push_str(&num_to_string(self.counter.get()));
- if !self.taken.contains(&s) {
- lifetime = name_to_dummy_lifetime(Symbol::intern(&s));
- self.generated.borrow_mut().push(lifetime);
- break;
- }
- self.inc_counter();
- }
- self.inc_counter();
- return lifetime;
-
- // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
- fn num_to_string(counter: usize) -> String {
- let mut s = String::new();
- let (n, r) = (counter/26 + 1, counter % 26);
- let letter: char = from_u32((r+97) as u32).unwrap();
- for _ in 0..n {
- s.push(letter);
- }
- s
- }
- }
-
- fn get_generated_lifetimes(&self) -> Vec<hir::Lifetime> {
- self.generated.borrow().clone()
- }
-}
-
-fn name_to_dummy_lifetime(name: ast::Name) -> hir::Lifetime {
- hir::Lifetime { id: ast::DUMMY_NODE_ID,
- span: syntax_pos::DUMMY_SP,
- name: name }
-}
-
impl<'tcx> ObligationCause<'tcx> {
fn as_failure_str(&self) -> &'static str {
use traits::ObligationCauseCode::*;
}
}
}
-
}
}
TyRef(_, ref tm) => {
- if tcx.sess.features.borrow().never_type {
- tm.ty.uninhabited_from(visited, tcx)
- } else {
- DefIdForest::empty()
- }
+ tm.ty.uninhabited_from(visited, tcx)
}
_ => DefIdForest::empty(),
/// Data must be immutable but not aliasable. This kind of borrow
/// cannot currently be expressed by the user and is used only in
- /// implicit closure bindings. It is needed when you the closure
+ /// implicit closure bindings. It is needed when the closure
/// is borrowing or mutating a mutable referent, e.g.:
///
/// let x: &mut isize = ...;
fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
pcx: PatternContext<'tcx>) -> Vec<Constructor>
{
+ let check_inhabited = cx.tcx.sess.features.borrow().never_type;
debug!("all_constructors({:?})", pcx.ty);
match pcx.ty.sty {
ty::TyBool =>
[true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
ty::TySlice(ref sub_ty) => {
- if sub_ty.is_uninhabited_from(cx.module, cx.tcx) {
+ if sub_ty.is_uninhabited_from(cx.module, cx.tcx)
+ && check_inhabited
+ {
vec![Slice(0)]
} else {
(0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
}
}
ty::TyArray(ref sub_ty, length) => {
- if length == 0 || !sub_ty.is_uninhabited_from(cx.module, cx.tcx) {
+ if length == 0 || !(sub_ty.is_uninhabited_from(cx.module, cx.tcx)
+ && check_inhabited)
+ {
vec![Slice(length)]
} else {
vec![]
let forest = v.uninhabited_from(&mut visited,
cx.tcx, substs,
AdtKind::Enum);
- if forest.contains(cx.tcx, cx.module) {
+ if forest.contains(cx.tcx, cx.module)
+ && check_inhabited
+ {
None
} else {
Some(Variant(v.did))
}).collect()
}
_ => {
- if pcx.ty.is_uninhabited_from(cx.module, cx.tcx) {
+ if pcx.ty.is_uninhabited_from(cx.module, cx.tcx)
+ && check_inhabited
+ {
vec![]
} else {
vec![Single]
}
PatternKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
- let irrefutable = adt_def.variants.iter().enumerate().all(|(i, v)| {
- i == variant_index || {
- let mut visited = FxHashSet::default();
- let node_set = v.uninhabited_from(&mut visited,
- self.hir.tcx(),
- substs,
- adt_def.adt_kind());
- !node_set.is_empty()
+ if self.hir.tcx().sess.features.borrow().never_type {
+ let irrefutable = adt_def.variants.iter().enumerate().all(|(i, v)| {
+ i == variant_index || {
+ let mut visited = FxHashSet::default();
+ let node_set = v.uninhabited_from(&mut visited,
+ self.hir.tcx(),
+ substs,
+ adt_def.adt_kind());
+ !node_set.is_empty()
+ }
+ });
+ if irrefutable {
+ let lvalue = match_pair.lvalue.downcast(adt_def, variant_index);
+ candidate.match_pairs.extend(self.field_match_pairs(lvalue, subpatterns));
+ Ok(())
+ } else {
+ Err(match_pair)
}
- });
- if irrefutable {
- let lvalue = match_pair.lvalue.downcast(adt_def, variant_index);
- candidate.match_pairs.extend(self.field_match_pairs(lvalue, subpatterns));
- Ok(())
} else {
Err(match_pair)
}
where I: Iterator<Item=DefId>, 'tcx: 'a
{
let mut first = true;
- for def_id in iter {
+ for def_id in iter.filter(DefId::is_local) {
let mir = &tcx.item_mir(def_id);
if first {
fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
where F: FnOnce(&mut DumpVisitor<'l, 'tcx, 'll, D>)
{
- let old_tables = self.save_ctxt.tables;
let item_def_id = self.tcx.hir.local_def_id(item_id);
- self.save_ctxt.tables = self.tcx.item_tables(item_def_id);
- f(self);
- self.save_ctxt.tables = old_tables;
+ match self.tcx.tables.borrow().get(&item_def_id) {
+ Some(tables) => {
+ let old_tables = self.save_ctxt.tables;
+ self.save_ctxt.tables = tables;
+ f(self);
+ self.save_ctxt.tables = old_tables;
+ }
+ None => f(self),
+ }
}
pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
pub fn C_big_integral(t: Type, u: u128, sign_extend: bool) -> ValueRef {
if ::std::mem::size_of::<u128>() == 16 {
unsafe {
- llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, &u as *const u128 as *const u64)
+ let words = [u as u64, u.wrapping_shr(64) as u64];
+ llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr())
}
} else {
// SNAP: remove after snapshot
use super::FnCtxt;
use hir::def_id::DefId;
-use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue};
+use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue, TypeVariants};
use rustc::infer::type_variable::TypeVariableOrigin;
use syntax::ast;
use syntax::symbol::Symbol;
"binary operation `{}` cannot be applied to type `{}`",
op.node.as_str(),
lhs_ty);
+
+ if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
+ if !self.infcx.type_moves_by_default(ty_mut.ty, lhs_expr.span) &&
+ self.lookup_op_method(expr, ty_mut.ty, vec![rhs_ty_var],
+ Symbol::intern(name), trait_def_id,
+ lhs_expr).is_ok() {
+ err.span_note(
+ lhs_expr.span,
+ &format!(
+ "this is a reference of type that `{}` can be applied to, \
+ you need to dereference this variable once for this \
+ operation to work",
+ op.node.as_str()));
+ }
+ }
+
let missing_trait = match op.node {
hir::BiAdd => Some("std::ops::Add"),
hir::BiSub => Some("std::ops::Sub"),
.span_label(item.span, &format!("impl doesn't use types inside crate"))
.note(&format!("the impl does not reference any types defined in \
this crate"))
+ .note("define and implement a trait or new type instead")
.emit();
return;
}
//! Implementations of serialization for structures found in libcollections
use std::hash::{Hash, BuildHasher};
-use std::mem;
use {Decodable, Encodable, Decoder, Encoder};
use std::collections::{LinkedList, VecDeque, BTreeMap, BTreeSet, HashMap, HashSet};
-use collections::enum_set::{EnumSet, CLike};
impl<
T: Encodable
}
}
-impl<
- T: Encodable + CLike
-> Encodable for EnumSet<T> {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- let mut bits = 0;
- for item in self {
- bits |= 1 << item.to_usize();
- }
- s.emit_usize(bits)
- }
-}
-
-impl<
- T: Decodable + CLike
-> Decodable for EnumSet<T> {
- fn decode<D: Decoder>(d: &mut D) -> Result<EnumSet<T>, D::Error> {
- let bits = d.read_usize()?;
- let mut set = EnumSet::new();
- for bit in 0..(mem::size_of::<usize>()*8) {
- if bits & (1 << bit) != 0 {
- set.insert(CLike::from_usize(bit));
- }
- }
- Ok(set)
- }
-}
-
impl<K, V, S> Encodable for HashMap<K, V, S>
where K: Encodable + Hash + Eq,
V: Encodable,
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core_intrinsics)]
-#![feature(enumset)]
#![feature(specialization)]
#![feature(staged_api)]
#![cfg_attr(test, feature(test))]
/// Possible errors from the [`env::var`] function.
///
-/// [env::var]: fn.var.html
+/// [`env::var`]: fn.var.html
#[derive(Debug, PartialEq, Eq, Clone)]
#[stable(feature = "env", since = "1.0.0")]
pub enum VarError {
/// # Examples
///
/// ```
- /// #![feature(set_permissions_atomic)]
/// # fn foo() -> std::io::Result<()> {
/// use std::fs::File;
///
/// # Ok(())
/// # }
/// ```
- #[unstable(feature = "set_permissions_atomic", issue="37916")]
+ #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
self.inner.set_permissions(perm.0)
}
/// # Examples
///
/// ```
- /// #![feature(sockaddr_checker)]
- ///
/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
///
/// fn main() {
/// assert_eq!(socket.is_ipv6(), false);
/// }
/// ```
- #[unstable(feature = "sockaddr_checker", issue = "36949")]
+ #[stable(feature = "sockaddr_checker", since = "1.16.0")]
pub fn is_ipv4(&self) -> bool {
match *self {
SocketAddr::V4(_) => true,
/// # Examples
///
/// ```
- /// #![feature(sockaddr_checker)]
- ///
/// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
///
/// fn main() {
/// assert_eq!(socket.is_ipv6(), true);
/// }
/// ```
- #[unstable(feature = "sockaddr_checker", issue = "36949")]
+ #[stable(feature = "sockaddr_checker", since = "1.16.0")]
pub fn is_ipv6(&self) -> bool {
match *self {
SocketAddr::V4(_) => false,
/// # Examples
///
/// ```
- /// #![feature(ipaddr_checker)]
- ///
/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
///
/// fn main() {
/// false);
/// }
/// ```
- #[unstable(feature = "ipaddr_checker", issue = "36949")]
+ #[stable(feature = "ipaddr_checker", since = "1.16.0")]
pub fn is_ipv4(&self) -> bool {
match *self {
IpAddr::V4(_) => true,
/// # Examples
///
/// ```
- /// #![feature(ipaddr_checker)]
- ///
/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
///
/// fn main() {
/// true);
/// }
/// ```
- #[unstable(feature = "ipaddr_checker", issue = "36949")]
+ #[stable(feature = "ipaddr_checker", since = "1.16.0")]
pub fn is_ipv6(&self) -> bool {
match *self {
IpAddr::V4(_) => false,
}
/// Windows-specific extensions to the `std::process::Command` builder
-#[unstable(feature = "windows_process_extensions", issue = "37827")]
+#[stable(feature = "windows_process_extensions", since = "1.16.0")]
pub trait CommandExt {
/// Sets the [process creation flags][1] to be passed to `CreateProcess`.
///
/// These will always be ORed with `CREATE_UNICODE_ENVIRONMENT`.
/// [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
- #[unstable(feature = "windows_process_extensions", issue = "37827")]
+ #[stable(feature = "windows_process_extensions", since = "1.16.0")]
fn creation_flags(&mut self, flags: u32) -> &mut process::Command;
}
-#[unstable(feature = "windows_process_extensions", issue = "37827")]
+#[stable(feature = "windows_process_extensions", since = "1.16.0")]
impl CommandExt for process::Command {
fn creation_flags(&mut self, flags: u32) -> &mut process::Command {
self.as_inner_mut().creation_flags(flags);
/// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html
/// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
-/// [`panic!`]: ../../std/macro.panic.html
+/// [`panic`]: ../../std/macro.panic.html
/// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
///
/// # Examples
/// to [`panic`].
///
/// [`Err`]: ../../std/result/enum.Result.html#variant.Err
- /// [`panic!`]: ../../std/macro.panic.html
+ /// [`panic`]: ../../std/macro.panic.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
- /// #![feature(duration_checked_ops)]
- ///
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
/// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
/// ```
- #[unstable(feature = "duration_checked_ops", issue = "35774")]
+ #[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[inline]
pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
/// Basic usage:
///
/// ```
- /// #![feature(duration_checked_ops)]
- ///
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
/// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
/// ```
- #[unstable(feature = "duration_checked_ops", issue = "35774")]
+ #[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[inline]
pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
/// Basic usage:
///
/// ```
- /// #![feature(duration_checked_ops)]
- ///
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
/// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
/// ```
- #[unstable(feature = "duration_checked_ops", issue = "35774")]
+ #[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[inline]
pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
// Multiply nanoseconds as u64, because it cannot overflow that way.
/// Basic usage:
///
/// ```
- /// #![feature(duration_checked_ops)]
- ///
/// use std::time::Duration;
///
/// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
/// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
/// assert_eq!(Duration::new(2, 0).checked_div(0), None);
/// ```
- #[unstable(feature = "duration_checked_ops", issue = "35774")]
+ #[stable(feature = "duration_checked_ops", since = "1.16.0")]
#[inline]
pub fn checked_div(self, rhs: u32) -> Option<Duration> {
if rhs != 0 {
}
}
+fn ident_can_begin_expr(ident: ast::Ident) -> bool {
+ let ident_token: Token = Ident(ident);
+
+ !ident_token.is_any_keyword() ||
+ ident_token.is_path_segment_keyword() ||
+ [
+ keywords::Box.name(),
+ keywords::Break.name(),
+ keywords::Continue.name(),
+ keywords::False.name(),
+ keywords::For.name(),
+ keywords::If.name(),
+ keywords::Loop.name(),
+ keywords::Match.name(),
+ keywords::Move.name(),
+ keywords::Return.name(),
+ keywords::True.name(),
+ keywords::Unsafe.name(),
+ keywords::While.name(),
+ ].contains(&ident.name)
+}
+
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug)]
pub enum Token {
/* Expression-operator symbols. */
pub fn can_begin_expr(&self) -> bool {
match *self {
OpenDelim(..) => true,
- Ident(..) => true,
+ Ident(ident) => ident_can_begin_expr(ident),
Literal(..) => true,
Not => true,
BinOp(Minus) => true,
impl Drop for u32 {} //~ ERROR E0117
//~^ NOTE impl doesn't use types inside crate
//~| NOTE the impl does not reference any types defined in this crate
+//~| NOTE define and implement a trait or new type instead
fn main() {
}
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
//~| NOTE impl doesn't use types inside crate
//~| NOTE the impl does not reference any types defined in this crate
+//~| NOTE define and implement a trait or new type instead
#[derive(Copy, Clone)]
struct Bar;
--- /dev/null
+// Copyright 2012-2016 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 v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
+ let vr = v.iter().filter(|x| {
+ x % 2 == 0
+ //~^ ERROR binary operation `%` cannot be applied to type `&&{integer}`
+ //~| NOTE this is a reference of type that `%` can be applied to
+ //~| NOTE an implementation of `std::ops::Rem` might be missing for `&&{integer}`
+ });
+ println!("{:?}", vr);
+}
--- /dev/null
+// 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.
+
+pub fn main() {
+
+ return;
+ return ();
+ return as ();
+ return return as ();
+ return return return;
+
+ return if true {
+ ()
+ } else {
+ ()
+ };
+
+ loop {
+ return break as ();
+ }
+
+ return enum; //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `enum`
+}
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
//~| NOTE impl doesn't use types inside crate
//~| NOTE the impl does not reference any types defined in this crate
+//~| NOTE define and implement a trait or new type instead
impl Copy for &'static NotSync {}
//~^ ERROR the trait `Copy` may not be implemented for this type
//~^ ERROR the trait `Copy` may not be implemented for this type
//~| NOTE type is not a structure or enumeration
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
-//~| NOTE impl doesn't use types inside crate
//~| NOTE the impl does not reference any types defined in this crate
+//~| NOTE define and implement a trait or new type instead
+//~| NOTE impl doesn't use types inside crate
impl Copy for &'static [NotSync] {}
//~^ ERROR the trait `Copy` may not be implemented for this type
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
//~| NOTE impl doesn't use types inside crate
//~| NOTE the impl does not reference any types defined in this crate
+//~| NOTE define and implement a trait or new type instead
fn main() {
}
}
fn check<'r, I: Iterator<Item=usize>, T: Itble<'r, usize, I>>(cont: &T) -> bool
-//~^ HELP 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 an appropriate lifetime for autoref due to conflicting requirements
+++ /dev/null
-// 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.
-
-// ignore-tidy-linelength
-
-use std::ops::Range;
-
-trait Itble<'r, T, I: Iterator<Item=T>> { fn iter(&'r self) -> I; }
-
-impl<'r> Itble<'r, usize, Range<usize>> for (usize, usize) {
- fn iter(&'r self) -> Range<usize> {
- let &(min, max) = self;
- min..max
- }
-}
-
-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(0), |state, val| {
- state.map_or(None, |mask| {
- let bit = 1 << val;
- if mask & bit == 0 {Some(mask|bit)} else {None}
- })
- });
- result.is_some()
-}
-
-fn main() {}
+++ /dev/null
-// 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.
-
-// ignore-tidy-linelength
-
-use std::marker::PhantomData;
-
-struct Bar<'x, 'y, 'z> { bar: &'y i32, baz: i32, marker: PhantomData<(&'x(),&'y(),&'z())> }
-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 E0312
- //~| ERROR cannot infer
- //~| ERROR cannot infer
-}
-
-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 E0312
- //~| ERROR cannot infer
- //~| ERROR cannot infer
-}
-
-fn main() { }
+++ /dev/null
-// 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.
-
-// ignore-tidy-linelength
-
-use std::marker::PhantomData;
-
-struct Foo<'x> { bar: isize, marker: PhantomData<&'x ()> }
-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 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 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 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 isize, t: T }
-struct Dog<'y> { dog: &'y isize }
-
-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 E0312
-}
-
-struct Baz<'x> {
- bar: &'x isize
-}
-
-impl<'a> Baz<'a> {
- fn baz2<'b>(&self, x: &isize) -> (&'b isize, &'b isize) {
- (self.bar, x) //~ ERROR E0312
- //~^ ERROR E0312
- }
-}
-
-fn main() {}
--- /dev/null
+// Copyright 2012-2016 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 a: &String = &"1".to_owned();
+ let b: &str = &"2";
+ let c = a + b;
+ //~^ ERROR binary operation `+` cannot be applied to type `&std::string::String`
+ //~| NOTE an implementation of `std::ops::Add` might be missing for `&std::string::String`
+ println!("{:?}", c);
+}
--- /dev/null
+// Copyright 2016 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(slice_patterns)]
+
+enum Void {}
+
+fn main() {
+ let x: Result<u32, &'static Void> = Ok(23);
+ let _ = match x { //~ ERROR non-exhaustive
+ Ok(n) => n,
+ };
+
+ let x: &Void = unsafe { std::mem::uninitialized() };
+ let _ = match x {};
+ //~^ ERROR non-exhaustive
+
+ let x: (Void,) = unsafe { std::mem::uninitialized() };
+ let _ = match x {};
+ //~^ ERROR non-exhaustive
+
+ let x: [Void; 1] = unsafe { std::mem::uninitialized() };
+ let _ = match x {};
+ //~^ ERROR non-exhaustive
+
+ let x: &[Void] = unsafe { std::mem::uninitialized() };
+ let _ = match x { //~ ERROR non-exhaustive
+ &[] => (),
+ };
+
+ let x: Void = unsafe { std::mem::uninitialized() };
+ let _ = match x {}; // okay
+
+ let x: Result<u32, Void> = Ok(23);
+ let _ = match x { //~ ERROR non-exhaustive
+ Ok(x) => x,
+ };
+
+ let x: Result<u32, Void> = Ok(23);
+ let Ok(x) = x;
+ //~^ ERROR refutable
+}
+
+++ /dev/null
-// Copyright 2016 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.
-
-enum Void {}
-
-fn main() {
- let x: Result<u32, &'static Void> = Ok(23);
- let _ = match x { //~ ERROR non-exhaustive
- Ok(n) => n,
- };
-}
-
// aux-build:fat_drop.rs
-#![feature(drop_in_place)]
-
extern crate fat_drop;
fn main() {
+++ /dev/null
-// Copyright 2016 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 std::str::FromStr;
-
-pub struct Foo<'a> {
- field: &'a str,
-}
-
-impl<'a> Foo<'a> {
- fn bar(path: &str) -> Result<Self, ()> {
- Ok(Foo { field: path })
- }
-}
-
-impl<'a> FromStr for Foo<'a> {
- type Err = ();
- fn from_str(path: &str) -> Result<Self, ()> {
- Ok(Foo { field: path })
- }
-}
+++ /dev/null
-error: main function not found
-
-error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
- --> $DIR/consider-using-explicit-lifetime.rs:19:12
- |
-19 | Ok(Foo { field: path })
- | ^^^
-
-error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
- --> $DIR/consider-using-explicit-lifetime.rs:26:12
- |
-26 | Ok(Foo { field: path })
- | ^^^
- |
-help: consider using an explicit lifetime parameter as shown: fn from_str(path: &'a str) -> Result<Self, ()>
- --> $DIR/consider-using-explicit-lifetime.rs:25:5
- |
-25 | fn from_str(path: &str) -> Result<Self, ()> {
- | _____^ starting here...
-26 | | Ok(Foo { field: path })
-27 | | }
- | |_____^ ...ending here
-
-error: aborting due to 2 previous errors
-
--- /dev/null
+[package]
+name = "build-manifest"
+version = "0.1.0"
+authors = ["Alex Crichton <alex@alexcrichton.com>"]
+
+[dependencies]
+toml = "0.1"
+rustc-serialize = "0.3"
--- /dev/null
+// Copyright 2017 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.
+
+extern crate toml;
+extern crate rustc_serialize;
+
+use std::collections::HashMap;
+use std::env;
+use std::fs::File;
+use std::io::{self, Read, Write};
+use std::path::{PathBuf, Path};
+use std::process::{Command, Stdio};
+
+static HOSTS: &'static [&'static str] = &[
+ "aarch64-unknown-linux-gnu",
+ "arm-unknown-linux-gnueabi",
+ "arm-unknown-linux-gnueabihf",
+ "armv7-unknown-linux-gnueabihf",
+ "i686-apple-darwin",
+ "i686-pc-windows-gnu",
+ "i686-pc-windows-msvc",
+ "i686-unknown-linux-gnu",
+ "mips-unknown-linux-gnu",
+ "mips64-unknown-linux-gnuabi64",
+ "mips64el-unknown-linux-gnuabi64",
+ "mipsel-unknown-linux-gnu",
+ "powerpc-unknown-linux-gnu",
+ "powerpc64-unknown-linux-gnu",
+ "powerpc64le-unknown-linux-gnu",
+ "s390x-unknown-linux-gnu",
+ "x86_64-apple-darwin",
+ "x86_64-pc-windows-gnu",
+ "x86_64-pc-windows-msvc",
+ "x86_64-unknown-freebsd",
+ "x86_64-unknown-linux-gnu",
+ "x86_64-unknown-netbsd",
+];
+
+static TARGETS: &'static [&'static str] = &[
+ "aarch64-apple-ios",
+ "aarch64-linux-android",
+ "aarch64-unknown-linux-gnu",
+ "arm-linux-androideabi",
+ "arm-unknown-linux-gnueabi",
+ "arm-unknown-linux-gnueabihf",
+ "arm-unknown-linux-musleabi",
+ "arm-unknown-linux-musleabihf",
+ "armv7-apple-ios",
+ "armv7-linux-androideabi",
+ "armv7-unknown-linux-gnueabihf",
+ "armv7-unknown-linux-musleabihf",
+ "armv7s-apple-ios",
+ "asmjs-unknown-emscripten",
+ "i386-apple-ios",
+ "i586-pc-windows-msvc",
+ "i586-unknown-linux-gnu",
+ "i686-apple-darwin",
+ "i686-linux-android",
+ "i686-pc-windows-gnu",
+ "i686-pc-windows-msvc",
+ "i686-unknown-freebsd",
+ "i686-unknown-linux-gnu",
+ "i686-unknown-linux-musl",
+ "mips-unknown-linux-gnu",
+ "mips-unknown-linux-musl",
+ "mips64-unknown-linux-gnuabi64",
+ "mips64el-unknown-linux-gnuabi64",
+ "mipsel-unknown-linux-gnu",
+ "mipsel-unknown-linux-musl",
+ "powerpc-unknown-linux-gnu",
+ "powerpc64-unknown-linux-gnu",
+ "powerpc64le-unknown-linux-gnu",
+ "s390x-unknown-linux-gnu",
+ "wasm32-unknown-emscripten",
+ "x86_64-apple-darwin",
+ "x86_64-apple-ios",
+ "x86_64-pc-windows-gnu",
+ "x86_64-pc-windows-msvc",
+ "x86_64-rumprun-netbsd",
+ "x86_64-unknown-freebsd",
+ "x86_64-unknown-linux-gnu",
+ "x86_64-unknown-linux-musl",
+ "x86_64-unknown-netbsd",
+];
+
+static MINGW: &'static [&'static str] = &[
+ "i686-pc-windows-gnu",
+ "x86_64-pc-windows-gnu",
+];
+
+#[derive(RustcEncodable)]
+struct Manifest {
+ manifest_version: String,
+ date: String,
+ pkg: HashMap<String, Package>,
+}
+
+#[derive(RustcEncodable)]
+struct Package {
+ version: String,
+ target: HashMap<String, Target>,
+}
+
+#[derive(RustcEncodable)]
+struct Target {
+ available: bool,
+ url: Option<String>,
+ hash: Option<String>,
+ components: Option<Vec<Component>>,
+ extensions: Option<Vec<Component>>,
+}
+
+#[derive(RustcEncodable)]
+struct Component {
+ pkg: String,
+ target: String,
+}
+
+macro_rules! t {
+ ($e:expr) => (match $e {
+ Ok(e) => e,
+ Err(e) => panic!("{} failed with {}", stringify!($e), e),
+ })
+}
+
+struct Builder {
+ channel: String,
+ input: PathBuf,
+ output: PathBuf,
+ gpg_passphrase: String,
+ digests: HashMap<String, String>,
+ s3_address: String,
+ date: String,
+ rust_version: String,
+ cargo_version: String,
+}
+
+fn main() {
+ let mut args = env::args().skip(1);
+ let input = PathBuf::from(args.next().unwrap());
+ let output = PathBuf::from(args.next().unwrap());
+ let date = args.next().unwrap();
+ let channel = args.next().unwrap();
+ let s3_address = args.next().unwrap();
+ let mut passphrase = String::new();
+ t!(io::stdin().read_to_string(&mut passphrase));
+
+ Builder {
+ channel: channel,
+ input: input,
+ output: output,
+ gpg_passphrase: passphrase,
+ digests: HashMap::new(),
+ s3_address: s3_address,
+ date: date,
+ rust_version: String::new(),
+ cargo_version: String::new(),
+ }.build();
+}
+
+impl Builder {
+ fn build(&mut self) {
+ self.rust_version = self.version("rust", "x86_64-unknown-linux-gnu");
+ self.cargo_version = self.version("cargo", "x86_64-unknown-linux-gnu");
+
+ self.digest_and_sign();
+ let manifest = self.build_manifest();
+ let manifest = toml::encode(&manifest).to_string();
+
+ let filename = format!("channel-rust-{}.toml", self.channel);
+ self.write_manifest(&manifest, &filename);
+
+ if self.channel != "beta" && self.channel != "nightly" {
+ self.write_manifest(&manifest, "channel-rust-stable.toml");
+ }
+ }
+
+ fn digest_and_sign(&mut self) {
+ for file in t!(self.input.read_dir()).map(|e| t!(e).path()) {
+ let filename = file.file_name().unwrap().to_str().unwrap();
+ let digest = self.hash(&file);
+ self.sign(&file);
+ assert!(self.digests.insert(filename.to_string(), digest).is_none());
+ }
+ }
+
+ fn build_manifest(&mut self) -> Manifest {
+ let mut manifest = Manifest {
+ manifest_version: "2".to_string(),
+ date: self.date.to_string(),
+ pkg: HashMap::new(),
+ };
+
+ self.package("rustc", &mut manifest.pkg, HOSTS);
+ self.package("cargo", &mut manifest.pkg, HOSTS);
+ self.package("rust-mingw", &mut manifest.pkg, MINGW);
+ self.package("rust-std", &mut manifest.pkg, TARGETS);
+ self.package("rust-docs", &mut manifest.pkg, TARGETS);
+ self.package("rust-src", &mut manifest.pkg, &["*"]);
+
+ let mut pkg = Package {
+ version: self.cached_version("rust").to_string(),
+ target: HashMap::new(),
+ };
+ for host in HOSTS {
+ let filename = self.filename("rust", host);
+ let digest = match self.digests.remove(&filename) {
+ Some(digest) => digest,
+ None => {
+ pkg.target.insert(host.to_string(), Target {
+ available: false,
+ url: None,
+ hash: None,
+ components: None,
+ extensions: None,
+ });
+ continue
+ }
+ };
+ let mut components = Vec::new();
+ let mut extensions = Vec::new();
+
+ // rustc/rust-std/cargo are all required, and so is rust-mingw if it's
+ // available for the target.
+ components.extend(vec![
+ Component { pkg: "rustc".to_string(), target: host.to_string() },
+ Component { pkg: "rust-std".to_string(), target: host.to_string() },
+ Component { pkg: "cargo".to_string(), target: host.to_string() },
+ ]);
+ if host.contains("pc-windows-gnu") {
+ components.push(Component {
+ pkg: "rust-mingw".to_string(),
+ target: host.to_string(),
+ });
+ }
+
+ // Docs, other standard libraries, and the source package are all
+ // optional.
+ extensions.push(Component {
+ pkg: "rust-docs".to_string(),
+ target: host.to_string(),
+ });
+ for target in TARGETS {
+ if target != host {
+ extensions.push(Component {
+ pkg: "rust-std".to_string(),
+ target: target.to_string(),
+ });
+ }
+ }
+ extensions.push(Component {
+ pkg: "rust-src".to_string(),
+ target: "*".to_string(),
+ });
+
+ pkg.target.insert(host.to_string(), Target {
+ available: true,
+ url: Some(self.url("rust", host)),
+ hash: Some(to_hex(digest.as_ref())),
+ components: Some(components),
+ extensions: Some(extensions),
+ });
+ }
+ manifest.pkg.insert("rust".to_string(), pkg);
+
+ return manifest
+ }
+
+ fn package(&mut self,
+ pkgname: &str,
+ dst: &mut HashMap<String, Package>,
+ targets: &[&str]) {
+ let targets = targets.iter().map(|name| {
+ let filename = self.filename(pkgname, name);
+ let digest = match self.digests.remove(&filename) {
+ Some(digest) => digest,
+ None => {
+ return (name.to_string(), Target {
+ available: false,
+ url: None,
+ hash: None,
+ components: None,
+ extensions: None,
+ })
+ }
+ };
+
+ (name.to_string(), Target {
+ available: true,
+ url: Some(self.url(pkgname, name)),
+ hash: Some(digest),
+ components: None,
+ extensions: None,
+ })
+ }).collect();
+
+ dst.insert(pkgname.to_string(), Package {
+ version: self.cached_version(pkgname).to_string(),
+ target: targets,
+ });
+ }
+
+ fn url(&self, component: &str, target: &str) -> String {
+ format!("{}/{}/{}",
+ self.s3_address,
+ self.date,
+ self.filename(component, target))
+ }
+
+ fn filename(&self, component: &str, target: &str) -> String {
+ if component == "rust-src" {
+ format!("rust-src-{}.tar.gz", self.channel)
+ } else {
+ format!("{}-{}-{}.tar.gz", component, self.channel, target)
+ }
+ }
+
+ fn cached_version(&self, component: &str) -> &str {
+ if component == "cargo" {
+ &self.cargo_version
+ } else {
+ &self.rust_version
+ }
+ }
+
+ fn version(&self, component: &str, target: &str) -> String {
+ let mut cmd = Command::new("tar");
+ let filename = self.filename(component, target);
+ cmd.arg("xf")
+ .arg(self.input.join(&filename))
+ .arg(format!("{}/version", filename.replace(".tar.gz", "")))
+ .arg("-O");
+ let version = t!(cmd.output());
+ if !version.status.success() {
+ panic!("failed to learn version:\n\n{:?}\n\n{}\n\n{}",
+ cmd,
+ String::from_utf8_lossy(&version.stdout),
+ String::from_utf8_lossy(&version.stderr));
+ }
+ String::from_utf8_lossy(&version.stdout).trim().to_string()
+ }
+
+ fn hash(&self, path: &Path) -> String {
+ let sha = t!(Command::new("shasum")
+ .arg("-a").arg("256")
+ .arg(path)
+ .output());
+ assert!(sha.status.success());
+
+ let filename = path.file_name().unwrap().to_str().unwrap();
+ let sha256 = self.output.join(format!("{}.sha256", filename));
+ t!(t!(File::create(&sha256)).write_all(&sha.stdout));
+
+ let stdout = String::from_utf8_lossy(&sha.stdout);
+ stdout.split_whitespace().next().unwrap().to_string()
+ }
+
+ fn sign(&self, path: &Path) {
+ let filename = path.file_name().unwrap().to_str().unwrap();
+ let asc = self.output.join(format!("{}.asc", filename));
+ println!("signing: {:?}", path);
+ let mut cmd = Command::new("gpg");
+ cmd.arg("--no-tty")
+ .arg("--yes")
+ .arg("--passphrase-fd").arg("0")
+ .arg("--armor")
+ .arg("--output").arg(&asc)
+ .arg("--detach-sign").arg(path)
+ .stdin(Stdio::piped());
+ let mut child = t!(cmd.spawn());
+ t!(child.stdin.take().unwrap().write_all(self.gpg_passphrase.as_bytes()));
+ assert!(t!(child.wait()).success());
+ }
+
+ fn write_manifest(&self, manifest: &str, name: &str) {
+ let dst = self.output.join(name);
+ t!(t!(File::create(&dst)).write_all(manifest.as_bytes()));
+ self.hash(&dst);
+ self.sign(&dst);
+ }
+}
+
+fn to_hex(digest: &[u8]) -> String {
+ let mut ret = String::new();
+ for byte in digest {
+ ret.push(hex((byte & 0xf0) >> 4));
+ ret.push(hex(byte & 0xf));
+ }
+ return ret;
+
+ fn hex(b: u8) -> char {
+ match b {
+ 0...9 => (b'0' + b) as char,
+ _ => (b'a' + b - 10) as char,
+ }
+ }
+}