Rollup merge of #63487 - sd234678:remove-meaningless-comments-in-src/test-2, r=Centril
Remove meaningless comments in src/test
Moved from #63411
diff --git a/Cargo.lock b/Cargo.lock
index ab6731e..c784246 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -106,7 +106,7 @@
"cfg-if 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
"compiler_builtins 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)",
- "rustc-demangle 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-std-workspace-core 1.0.0",
]
@@ -1138,19 +1138,12 @@
[[package]]
name = "hashbrown"
-version = "0.4.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"compiler_builtins 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-std-workspace-alloc 1.0.0",
"rustc-std-workspace-core 1.0.0",
-]
-
-[[package]]
-name = "hashbrown"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
"serde 1.0.92 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -2736,7 +2729,7 @@
[[package]]
name = "rustc-demangle"
-version = "0.1.15"
+version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"compiler_builtins 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2894,7 +2887,7 @@
"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)",
"punycode 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc 0.0.0",
- "rustc-demangle 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_data_structures 0.0.0",
"rustc_metadata 0.0.0",
"rustc_target 0.0.0",
@@ -3534,7 +3527,7 @@
"core 0.0.0",
"dlmalloc 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"fortanix-sgx-abi 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
- "hashbrown 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "hashbrown 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.60 (registry+https://github.com/rust-lang/crates.io-index)",
"panic_abort 0.0.0",
"panic_unwind 0.0.0",
@@ -4450,7 +4443,6 @@
"checksum globset 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ef4feaabe24a0a658fd9cf4a9acf6ed284f045c77df0f49020ba3245cfb7b454"
"checksum h2 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)" = "a539b63339fbbb00e081e84b6e11bd1d9634a82d91da2984a18ac74a8823f392"
"checksum handlebars 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "df044dd42cdb7e32f28557b661406fc0f2494be75199779998810dbc35030e0d"
-"checksum hashbrown 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9529213c67695ca2d146e6f263b7b72df8fa973368beadf767e8ed80c03f2f36"
"checksum hashbrown 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e1de41fb8dba9714efd92241565cdff73f78508c95697dd56787d3cba27e2353"
"checksum heck 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ea04fa3ead4e05e51a7c806fc07271fdbde4e246a6c6d1efd52e72230b771b82"
"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77"
@@ -4600,7 +4592,7 @@
"checksum rustc-ap-serialize 546.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "61673783f2089e01033ffa82d1988f55175402071b31253a358292e1624d4602"
"checksum rustc-ap-syntax 546.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "28f3dd1346d5b0269c07a4a78855e309a298ab569c9c1302d4d4f57f8eee4e84"
"checksum rustc-ap-syntax_pos 546.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45e67b526dbda3a0c7dab91c8947d43685e7697f52686a4949da3c179cd7c979"
-"checksum rustc-demangle 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)" = "a7f4dccf6f4891ebcc0c39f9b6eb1a83b9bf5d747cb439ec6fba4f3b977038af"
+"checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783"
"checksum rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7540fc8b0c49f096ee9c961cda096467dce8084bec6bdca2fc83895fd9b28cb8"
"checksum rustc-rayon 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d2e07e19601f21c59aad953c2632172ba70cb27e685771514ea66e4062b3363"
"checksum rustc-rayon-core 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "79d38ca7cbc22fa59f09d8534ea4b27f67b0facf0cbe274433aceea227a02543"
diff --git a/config.toml.example b/config.toml.example
index cb9f388..a3ec4f2 100644
--- a/config.toml.example
+++ b/config.toml.example
@@ -141,10 +141,10 @@
# library and facade crates.
#compiler-docs = false
-# Indicate whether submodules are managed and updated automatically.
+# Indicate whether git submodules are managed and updated automatically.
#submodules = true
-# Update submodules only when the checked out commit in the submodules differs
+# Update git submodules only when the checked out commit in the submodules differs
# from what is committed in the main rustc repo.
#fast-submodules = true
diff --git a/src/bootstrap/bin/rustc.rs b/src/bootstrap/bin/rustc.rs
index 9c01de8..ce92ce0 100644
--- a/src/bootstrap/bin/rustc.rs
+++ b/src/bootstrap/bin/rustc.rs
@@ -37,7 +37,7 @@
let mut new = None;
if let Some(current_as_str) = args[i].to_str() {
if (&*args[i - 1] == "-C" && current_as_str.starts_with("metadata")) ||
- current_as_str.starts_with("-Cmetadata") {
+ current_as_str.starts_with("-Cmetadata") {
new = Some(format!("{}-{}", current_as_str, s));
}
}
@@ -89,7 +89,7 @@
if let Some(crate_name) = crate_name {
if let Some(target) = env::var_os("RUSTC_TIME") {
if target == "all" ||
- target.into_string().unwrap().split(",").any(|c| c.trim() == crate_name)
+ target.into_string().unwrap().split(",").any(|c| c.trim() == crate_name)
{
cmd.arg("-Ztime");
}
@@ -102,8 +102,13 @@
// FIXME: the fact that core here is excluded is due to core_arch from our stdarch submodule
// being broken on the beta compiler with bootstrap passed, so this is a temporary workaround
// (we've just snapped, so there are no cfg(bootstrap) related annotations in core).
- if stage == "0" && crate_name != Some("core") {
- cmd.arg("--cfg").arg("bootstrap");
+ if stage == "0" {
+ if crate_name != Some("core") {
+ cmd.arg("--cfg").arg("bootstrap");
+ } else {
+ // NOTE(eddyb) see FIXME above, except now we need annotations again in core.
+ cmd.arg("--cfg").arg("boostrap_stdarch_ignore_this");
+ }
}
// Print backtrace in case of ICE
@@ -276,10 +281,6 @@
cmd.arg("-C").arg("target-feature=-crt-static");
}
}
-
- if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
- cmd.arg("--remap-path-prefix").arg(&map);
- }
} else {
// Override linker if necessary.
if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") {
@@ -296,6 +297,10 @@
}
}
+ if let Ok(map) = env::var("RUSTC_DEBUGINFO_MAP") {
+ cmd.arg("--remap-path-prefix").arg(&map);
+ }
+
// Force all crates compiled by this compiler to (a) be unstable and (b)
// allow the `rustc_private` feature to link to other unstable crates
// also in the sysroot. We also do this for host crates, since those
diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs
index 8dad5f2..f0054c3 100644
--- a/src/bootstrap/builder.rs
+++ b/src/bootstrap/builder.rs
@@ -754,76 +754,20 @@
let mut cargo = Command::new(&self.initial_cargo);
let out_dir = self.stage_out(compiler, mode);
- // command specific path, we call clear_if_dirty with this
- let mut my_out = match cmd {
- "build" => self.cargo_out(compiler, mode, target),
-
- // This is the intended out directory for crate documentation.
- "doc" | "rustdoc" => self.crate_doc_out(target),
-
- _ => self.stage_out(compiler, mode),
- };
-
- // This is for the original compiler, but if we're forced to use stage 1, then
- // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since
- // we copy the libs forward.
- let cmp = self.compiler_for(compiler.stage, compiler.host, target);
-
- let libstd_stamp = match cmd {
- "check" | "clippy" | "fix" => check::libstd_stamp(self, cmp, target),
- _ => compile::libstd_stamp(self, cmp, target),
- };
-
- let libtest_stamp = match cmd {
- "check" | "clippy" | "fix" => check::libtest_stamp(self, cmp, target),
- _ => compile::libtest_stamp(self, cmp, target),
- };
-
- let librustc_stamp = match cmd {
- "check" | "clippy" | "fix" => check::librustc_stamp(self, cmp, target),
- _ => compile::librustc_stamp(self, cmp, target),
- };
+ // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
+ // so we need to explicitly clear out if they've been updated.
+ for backend in self.codegen_backends(compiler) {
+ self.clear_if_dirty(&out_dir, &backend);
+ }
if cmd == "doc" || cmd == "rustdoc" {
- if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen {
+ let my_out = match mode {
// This is the intended out directory for compiler documentation.
- my_out = self.compiler_doc_out(target);
- }
+ Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
+ _ => self.crate_doc_out(target),
+ };
let rustdoc = self.rustdoc(compiler);
self.clear_if_dirty(&my_out, &rustdoc);
- } else if cmd != "test" {
- match mode {
- Mode::Std => {
- self.clear_if_dirty(&my_out, &self.rustc(compiler));
- for backend in self.codegen_backends(compiler) {
- self.clear_if_dirty(&my_out, &backend);
- }
- },
- Mode::Test => {
- self.clear_if_dirty(&my_out, &libstd_stamp);
- },
- Mode::Rustc => {
- self.clear_if_dirty(&my_out, &self.rustc(compiler));
- self.clear_if_dirty(&my_out, &libstd_stamp);
- self.clear_if_dirty(&my_out, &libtest_stamp);
- },
- Mode::Codegen => {
- self.clear_if_dirty(&my_out, &librustc_stamp);
- },
- Mode::ToolBootstrap => { },
- Mode::ToolStd => {
- self.clear_if_dirty(&my_out, &libstd_stamp);
- },
- Mode::ToolTest => {
- self.clear_if_dirty(&my_out, &libstd_stamp);
- self.clear_if_dirty(&my_out, &libtest_stamp);
- },
- Mode::ToolRustc => {
- self.clear_if_dirty(&my_out, &libstd_stamp);
- self.clear_if_dirty(&my_out, &libtest_stamp);
- self.clear_if_dirty(&my_out, &librustc_stamp);
- },
- }
}
cargo
@@ -861,6 +805,19 @@
},
}
+ // This tells Cargo (and in turn, rustc) to output more complete
+ // dependency information. Most importantly for rustbuild, this
+ // includes sysroot artifacts, like libstd, which means that we don't
+ // need to track those in rustbuild (an error prone process!). This
+ // feature is currently unstable as there may be some bugs and such, but
+ // it represents a big improvement in rustbuild's reliability on
+ // rebuilds, so we're using it here.
+ //
+ // For some additional context, see #63470 (the PR originally adding
+ // this), as well as #63012 which is the tracking issue for this
+ // feature on the rustc side.
+ cargo.arg("-Zbinary-dep-depinfo");
+
cargo.arg("-j").arg(self.jobs().to_string());
// Remove make-related flags to ensure Cargo can correctly set things up
cargo.env_remove("MAKEFLAGS");
diff --git a/src/bootstrap/cc_detect.rs b/src/bootstrap/cc_detect.rs
index c58a98b..a4cb81d3 100644
--- a/src/bootstrap/cc_detect.rs
+++ b/src/bootstrap/cc_detect.rs
@@ -46,7 +46,7 @@
} else if target.contains("openbsd") {
Some(PathBuf::from("ar"))
} else if target.contains("vxworks") {
- Some(PathBuf::from("vx-ar"))
+ Some(PathBuf::from("wr-ar"))
} else {
let parent = cc.parent().unwrap();
let file = cc.file_name().unwrap().to_str().unwrap();
diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs
index 11b082a..6e6fea6 100644
--- a/src/bootstrap/check.rs
+++ b/src/bootstrap/check.rs
@@ -245,7 +245,6 @@
let libdir = builder.sysroot_libdir(compiler, target);
let hostdir = builder.sysroot_libdir(compiler, compiler.host);
add_to_sysroot(&builder, &libdir, &hostdir, &rustdoc_stamp(builder, compiler, target));
- builder.cargo(compiler, Mode::ToolRustc, target, "clean");
}
}
diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs
index 4b4b072..96987d0 100644
--- a/src/bootstrap/compile.rs
+++ b/src/bootstrap/compile.rs
@@ -15,7 +15,7 @@
use std::process::{Command, Stdio, exit};
use std::str;
-use build_helper::{output, mtime, t, up_to_date};
+use build_helper::{output, t, up_to_date};
use filetime::FileTime;
use serde::Deserialize;
use serde_json;
@@ -274,8 +274,6 @@
// for reason why the sanitizers are not built in stage0.
copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), "osx", &libdir);
}
-
- builder.cargo(target_compiler, Mode::ToolStd, target, "clean");
}
}
@@ -480,8 +478,6 @@
&builder.sysroot_libdir(target_compiler, compiler.host),
&libtest_stamp(builder, compiler, target)
);
-
- builder.cargo(target_compiler, Mode::ToolTest, target, "clean");
}
}
@@ -639,7 +635,6 @@
&builder.sysroot_libdir(target_compiler, compiler.host),
&librustc_stamp(builder, compiler, target)
);
- builder.cargo(target_compiler, Mode::ToolRustc, target, "clean");
}
}
@@ -795,6 +790,9 @@
if builder.config.llvm_use_libcxx {
cargo.env("LLVM_USE_LIBCXX", "1");
}
+ if builder.config.llvm_optimize && !builder.config.llvm_release_debuginfo {
+ cargo.env("LLVM_NDEBUG", "1");
+ }
}
_ => panic!("unknown backend: {}", backend),
}
@@ -1202,41 +1200,13 @@
deps.push((path_to_add.into(), false));
}
- // Now we want to update the contents of the stamp file, if necessary. First
- // we read off the previous contents along with its mtime. If our new
- // contents (the list of files to copy) is different or if any dep's mtime
- // is newer then we rewrite the stamp file.
deps.sort();
- let stamp_contents = fs::read(stamp);
- let stamp_mtime = mtime(&stamp);
let mut new_contents = Vec::new();
- let mut max = None;
- let mut max_path = None;
for (dep, proc_macro) in deps.iter() {
- let mtime = mtime(dep);
- if Some(mtime) > max {
- max = Some(mtime);
- max_path = Some(dep.clone());
- }
new_contents.extend(if *proc_macro { b"h" } else { b"t" });
new_contents.extend(dep.to_str().unwrap().as_bytes());
new_contents.extend(b"\0");
}
- let max = max.unwrap();
- let max_path = max_path.unwrap();
- let contents_equal = stamp_contents
- .map(|contents| contents == new_contents)
- .unwrap_or_default();
- if contents_equal && max <= stamp_mtime {
- builder.verbose(&format!("not updating {:?}; contents equal and {:?} <= {:?}",
- stamp, max, stamp_mtime));
- return deps.into_iter().map(|(d, _)| d).collect()
- }
- if max > stamp_mtime {
- builder.verbose(&format!("updating {:?} as {:?} changed", stamp, max_path));
- } else {
- builder.verbose(&format!("updating {:?} as deps changed", stamp));
- }
t!(fs::write(&stamp, &new_contents));
deps.into_iter().map(|(d, _)| d).collect()
}
diff --git a/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in
index 73d6fe5..e0a1f46 100644
--- a/src/bootstrap/mk/Makefile.in
+++ b/src/bootstrap/mk/Makefile.in
@@ -81,5 +81,14 @@
ci-subset-2:
$(Q)$(BOOTSTRAP) test $(TESTS_IN_2)
+TESTS_IN_MINGW_2 := \
+ src/test/ui \
+ src/test/compile-fail
+
+ci-mingw-subset-1:
+ $(Q)$(BOOTSTRAP) test $(TESTS_IN_MINGW_2:%=--exclude %)
+ci-mingw-subset-2:
+ $(Q)$(BOOTSTRAP) test $(TESTS_IN_MINGW_2)
+
.PHONY: dist
diff --git a/src/bootstrap/sanity.rs b/src/bootstrap/sanity.rs
index 4e3930c..bffe748 100644
--- a/src/bootstrap/sanity.rs
+++ b/src/bootstrap/sanity.rs
@@ -202,10 +202,6 @@
panic!("couldn't find libc.a in musl dir: {}",
root.join("lib").display());
}
- if fs::metadata(root.join("lib/libunwind.a")).is_err() {
- panic!("couldn't find libunwind.a in musl dir: {}",
- root.join("lib").display());
- }
}
None => {
panic!("when targeting MUSL either the rust.musl-root \
diff --git a/src/ci/azure-pipelines/auto.yml b/src/ci/azure-pipelines/auto.yml
index 06fa3bd..77c9cda 100644
--- a/src/ci/azure-pipelines/auto.yml
+++ b/src/ci/azure-pipelines/auto.yml
@@ -272,7 +272,7 @@
i686-mingw-1:
MSYS_BITS: 32
RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu
- SCRIPT: make ci-subset-1
+ SCRIPT: make ci-mingw-subset-1
MINGW_URL: https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc
MINGW_ARCHIVE: i686-6.3.0-release-posix-dwarf-rt_v5-rev2.7z
MINGW_DIR: mingw32
@@ -282,13 +282,13 @@
i686-mingw-2:
MSYS_BITS: 32
RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu
- SCRIPT: make ci-subset-2
+ SCRIPT: make ci-mingw-subset-2
MINGW_URL: https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc
MINGW_ARCHIVE: i686-6.3.0-release-posix-dwarf-rt_v5-rev2.7z
MINGW_DIR: mingw32
x86_64-mingw-1:
MSYS_BITS: 64
- SCRIPT: make ci-subset-1
+ SCRIPT: make ci-mingw-subset-1
RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu
MINGW_URL: https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc
MINGW_ARCHIVE: x86_64-6.3.0-release-posix-seh-rt_v5-rev2.7z
@@ -298,7 +298,7 @@
NO_LLVM_ASSERTIONS: 1
x86_64-mingw-2:
MSYS_BITS: 64
- SCRIPT: make ci-subset-2
+ SCRIPT: make ci-mingw-subset-2
RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu
MINGW_URL: https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc
MINGW_ARCHIVE: x86_64-6.3.0-release-posix-seh-rt_v5-rev2.7z
diff --git a/src/ci/azure-pipelines/steps/run.yml b/src/ci/azure-pipelines/steps/run.yml
index ca32888..ac6b344 100644
--- a/src/ci/azure-pipelines/steps/run.yml
+++ b/src/ci/azure-pipelines/steps/run.yml
@@ -199,7 +199,7 @@
# Upload CPU usage statistics that we've been gathering this whole time. Always
# execute this step in case we want to inspect failed builds, but don't let
# errors here ever fail the build since this is just informational.
-- bash: aws s3 cp --acl public-read cpu-usage.csv s3://$DEPLOY_BUCKET/rustc-builds/$BUILD_SOURCEVERSION/cpu-$SYSTEM_JOBNAME.csv
+- bash: aws s3 cp --acl public-read cpu-usage.csv s3://$DEPLOY_BUCKET/rustc-builds/$BUILD_SOURCEVERSION/cpu-$CI_JOB_NAME.csv
env:
AWS_SECRET_ACCESS_KEY: $(AWS_SECRET_ACCESS_KEY)
condition: variables['AWS_SECRET_ACCESS_KEY']
diff --git a/src/ci/docker/scripts/musl-toolchain.sh b/src/ci/docker/scripts/musl-toolchain.sh
index 55899fa..74ba2f0 100644
--- a/src/ci/docker/scripts/musl-toolchain.sh
+++ b/src/ci/docker/scripts/musl-toolchain.sh
@@ -54,29 +54,3 @@
ln -s $TARGET-g++ /usr/local/bin/$exec
done
fi
-
-export CC=$TARGET-gcc
-export CXX=$TARGET-g++
-
-LLVM=70
-
-# may have been downloaded in a previous run
-if [ ! -d libunwind-release_$LLVM ]; then
- curl -L https://github.com/llvm-mirror/llvm/archive/release_$LLVM.tar.gz | tar xzf -
- curl -L https://github.com/llvm-mirror/libunwind/archive/release_$LLVM.tar.gz | tar xzf -
-fi
-
-# fixme(mati865): Replace it with https://github.com/rust-lang/rust/pull/59089
-mkdir libunwind-build
-cd libunwind-build
-cmake ../libunwind-release_$LLVM \
- -DLLVM_PATH=/build/llvm-release_$LLVM \
- -DLIBUNWIND_ENABLE_SHARED=0 \
- -DCMAKE_C_COMPILER=$CC \
- -DCMAKE_CXX_COMPILER=$CXX \
- -DCMAKE_C_FLAGS="$CFLAGS" \
- -DCMAKE_CXX_FLAGS="$CXXFLAGS"
-
-hide_output make -j$(nproc)
-cp lib/libunwind.a $OUTPUT/$TARGET/lib
-cd - && rm -rf libunwind-build
diff --git a/src/ci/docker/scripts/musl.sh b/src/ci/docker/scripts/musl.sh
index c2cf77d..d847c40 100644
--- a/src/ci/docker/scripts/musl.sh
+++ b/src/ci/docker/scripts/musl.sh
@@ -20,6 +20,8 @@
TAG=$1
shift
+# Ancient binutils versions don't understand debug symbols produced by more recent tools.
+# Apparently applying `-fPIC` everywhere allows them to link successfully.
export CFLAGS="-fPIC $CFLAGS"
MUSL=musl-1.1.22
@@ -38,27 +40,3 @@
fi
hide_output make install
hide_output make clean
-
-cd ..
-
-LLVM=70
-
-# may have been downloaded in a previous run
-if [ ! -d libunwind-release_$LLVM ]; then
- curl -L https://github.com/llvm-mirror/llvm/archive/release_$LLVM.tar.gz | tar xzf -
- curl -L https://github.com/llvm-mirror/libunwind/archive/release_$LLVM.tar.gz | tar xzf -
-fi
-
-mkdir libunwind-build
-cd libunwind-build
-cmake ../libunwind-release_$LLVM \
- -DLLVM_PATH=/build/llvm-release_$LLVM \
- -DLIBUNWIND_ENABLE_SHARED=0 \
- -DCMAKE_C_COMPILER=$CC \
- -DCMAKE_CXX_COMPILER=$CXX \
- -DCMAKE_C_FLAGS="$CFLAGS" \
- -DCMAKE_CXX_FLAGS="$CXXFLAGS"
-
-hide_output make -j$(nproc)
-cp lib/libunwind.a /musl-$TAG/lib
-cd ../ && rm -rf libunwind-build
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs
index c92db51..c61e318 100644
--- a/src/liballoc/boxed.rs
+++ b/src/liballoc/boxed.rs
@@ -91,8 +91,10 @@
CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
};
use core::ptr::{self, NonNull, Unique};
+use core::slice;
use core::task::{Context, Poll};
+use crate::alloc::{self, Global, Alloc};
use crate::vec::Vec;
use crate::raw_vec::RawVec;
use crate::str::from_boxed_utf8_unchecked;
@@ -121,6 +123,34 @@
box x
}
+ /// Constructs a new box with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ ///
+ /// let mut five = Box::<u32>::new_uninit();
+ ///
+ /// let five = unsafe {
+ /// // Deferred initialization:
+ /// five.as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
+ let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
+ let ptr = unsafe {
+ Global.alloc(layout)
+ .unwrap_or_else(|_| alloc::handle_alloc_error(layout))
+ };
+ Box(ptr.cast().into())
+ }
+
/// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
/// `x` will be pinned in memory and unable to be moved.
#[stable(feature = "pin", since = "1.33.0")]
@@ -130,6 +160,111 @@
}
}
+impl<T> Box<[T]> {
+ /// Constructs a new boxed slice with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ ///
+ /// let mut values = Box::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// values[0].as_mut_ptr().write(1);
+ /// values[1].as_mut_ptr().write(2);
+ /// values[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
+ let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
+ let ptr = unsafe { alloc::alloc(layout) };
+ let unique = Unique::new(ptr).unwrap_or_else(|| alloc::handle_alloc_error(layout));
+ let slice = unsafe { slice::from_raw_parts_mut(unique.cast().as_ptr(), len) };
+ Box(Unique::from(slice))
+ }
+}
+
+impl<T> Box<mem::MaybeUninit<T>> {
+ /// Converts to `Box<T>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the value
+ /// really is in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ ///
+ /// let mut five = Box::<u32>::new_uninit();
+ ///
+ /// let five: Box<u32> = unsafe {
+ /// // Deferred initialization:
+ /// five.as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Box<T> {
+ Box(Box::into_unique(self).cast())
+ }
+}
+
+impl<T> Box<[mem::MaybeUninit<T>]> {
+ /// Converts to `Box<[T]>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the values
+ /// really are in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ ///
+ /// let mut values = Box::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// values[0].as_mut_ptr().write(1);
+ /// values[1].as_mut_ptr().write(2);
+ /// values[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Box<[T]> {
+ Box(Unique::new_unchecked(Box::into_raw(self) as _))
+ }
+}
+
impl<T: ?Sized> Box<T> {
/// Constructs a box from a raw pointer.
///
diff --git a/src/liballoc/collections/mod.rs b/src/liballoc/collections/mod.rs
index 5a33ddc..f1f22fe 100644
--- a/src/liballoc/collections/mod.rs
+++ b/src/liballoc/collections/mod.rs
@@ -41,32 +41,35 @@
#[doc(no_inline)]
pub use vec_deque::VecDeque;
-use crate::alloc::{AllocErr, LayoutErr};
+use crate::alloc::{Layout, LayoutErr};
-/// Augments `AllocErr` with a CapacityOverflow variant.
+/// The error type for `try_reserve` methods.
#[derive(Clone, PartialEq, Eq, Debug)]
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
-pub enum CollectionAllocErr {
+pub enum TryReserveError {
/// Error due to the computed capacity exceeding the collection's maximum
/// (usually `isize::MAX` bytes).
CapacityOverflow,
- /// Error due to the allocator (see the `AllocErr` type's docs).
- AllocErr,
+
+ /// The memory allocator returned an error
+ AllocError {
+ /// The layout of allocation request that failed
+ layout: Layout,
+
+ #[doc(hidden)]
+ #[unstable(feature = "container_error_extra", issue = "0", reason = "\
+ Enable exposing the allocator’s custom error value \
+ if an associated type is added in the future: \
+ https://github.com/rust-lang/wg-allocators/issues/23")]
+ non_exhaustive: (),
+ },
}
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
-impl From<AllocErr> for CollectionAllocErr {
- #[inline]
- fn from(AllocErr: AllocErr) -> Self {
- CollectionAllocErr::AllocErr
- }
-}
-
-#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
-impl From<LayoutErr> for CollectionAllocErr {
+impl From<LayoutErr> for TryReserveError {
#[inline]
fn from(_: LayoutErr) -> Self {
- CollectionAllocErr::CapacityOverflow
+ TryReserveError::CapacityOverflow
}
}
diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs
index 9240346..2fc8741 100644
--- a/src/liballoc/collections/vec_deque.rs
+++ b/src/liballoc/collections/vec_deque.rs
@@ -18,7 +18,7 @@
use core::slice;
use core::hash::{Hash, Hasher};
-use crate::collections::CollectionAllocErr;
+use crate::collections::TryReserveError;
use crate::raw_vec::RawVec;
use crate::vec::Vec;
@@ -576,10 +576,10 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
/// use std::collections::VecDeque;
///
- /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
+ /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
/// let mut output = VecDeque::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -595,7 +595,7 @@
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.try_reserve(additional)
}
@@ -614,10 +614,10 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
/// use std::collections::VecDeque;
///
- /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, CollectionAllocErr> {
+ /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, TryReserveError> {
/// let mut output = VecDeque::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -633,12 +633,12 @@
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
let old_cap = self.cap();
let used_cap = self.len() + 1;
let new_cap = used_cap.checked_add(additional)
.and_then(|needed_cap| needed_cap.checked_next_power_of_two())
- .ok_or(CollectionAllocErr::CapacityOverflow)?;
+ .ok_or(TryReserveError::CapacityOverflow)?;
if new_cap > old_cap {
self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs
index 7421bed..4a48945 100644
--- a/src/liballoc/lib.rs
+++ b/src/liballoc/lib.rs
@@ -87,6 +87,7 @@
#![feature(const_in_array_repeat_expressions)]
#![feature(dispatch_from_dyn)]
#![feature(core_intrinsics)]
+#![feature(container_error_extra)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fmt_internals)]
diff --git a/src/liballoc/macros.rs b/src/liballoc/macros.rs
index 250c419..0b5e186d 100644
--- a/src/liballoc/macros.rs
+++ b/src/liballoc/macros.rs
@@ -98,5 +98,5 @@
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! format {
- ($($arg:tt)*) => ($crate::fmt::format(format_args!($($arg)*)))
+ ($($arg:tt)*) => ($crate::fmt::format(::core::format_args!($($arg)*)))
}
diff --git a/src/liballoc/raw_vec.rs b/src/liballoc/raw_vec.rs
index 0abab45..bc8a38f 100644
--- a/src/liballoc/raw_vec.rs
+++ b/src/liballoc/raw_vec.rs
@@ -7,8 +7,8 @@
use core::ptr::{self, NonNull, Unique};
use core::slice;
-use crate::alloc::{Alloc, Layout, Global, handle_alloc_error};
-use crate::collections::CollectionAllocErr::{self, *};
+use crate::alloc::{Alloc, Layout, Global, AllocErr, handle_alloc_error};
+use crate::collections::TryReserveError::{self, *};
use crate::boxed::Box;
#[cfg(test)]
@@ -385,7 +385,7 @@
/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
pub fn try_reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize)
- -> Result<(), CollectionAllocErr> {
+ -> Result<(), TryReserveError> {
self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Exact)
}
@@ -413,7 +413,7 @@
pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Exact) {
Err(CapacityOverflow) => capacity_overflow(),
- Err(AllocErr) => unreachable!(),
+ Err(AllocError { .. }) => unreachable!(),
Ok(()) => { /* yay */ }
}
}
@@ -422,7 +422,7 @@
/// needed_extra_capacity` elements. This logic is used in amortized reserve methods.
/// Returns `(new_capacity, new_alloc_size)`.
fn amortized_new_size(&self, used_capacity: usize, needed_extra_capacity: usize)
- -> Result<usize, CollectionAllocErr> {
+ -> Result<usize, TryReserveError> {
// Nothing we can really do about these checks :(
let required_cap = used_capacity.checked_add(needed_extra_capacity)
@@ -435,7 +435,7 @@
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
pub fn try_reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize)
- -> Result<(), CollectionAllocErr> {
+ -> Result<(), TryReserveError> {
self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Amortized)
}
@@ -494,7 +494,7 @@
pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Amortized) {
Err(CapacityOverflow) => capacity_overflow(),
- Err(AllocErr) => unreachable!(),
+ Err(AllocError { .. }) => unreachable!(),
Ok(()) => { /* yay */ }
}
}
@@ -640,10 +640,8 @@
needed_extra_capacity: usize,
fallibility: Fallibility,
strategy: ReserveStrategy,
- ) -> Result<(), CollectionAllocErr> {
+ ) -> Result<(), TryReserveError> {
unsafe {
- use crate::alloc::AllocErr;
-
// NOTE: we don't early branch on ZSTs here because we want this
// to actually catch "asking for more than usize::MAX" in that case.
// If we make it past the first branch then we are guaranteed to
@@ -672,12 +670,16 @@
None => self.a.alloc(new_layout),
};
- match (&res, fallibility) {
+ let ptr = match (res, fallibility) {
(Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
- _ => {}
- }
+ (Err(AllocErr), Fallible) => return Err(TryReserveError::AllocError {
+ layout: new_layout,
+ non_exhaustive: (),
+ }),
+ (Ok(ptr), _) => ptr,
+ };
- self.ptr = res?.cast().into();
+ self.ptr = ptr.cast().into();
self.cap = new_cap;
Ok(())
@@ -737,7 +739,7 @@
// all 4GB in user-space. e.g., PAE or x32
#[inline]
-fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> {
+fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
if mem::size_of::<usize>() < 8 && alloc_size > core::isize::MAX as usize {
Err(CapacityOverflow)
} else {
diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs
index 0c406a9..2b222ca 100644
--- a/src/liballoc/rc.rs
+++ b/src/liballoc/rc.rs
@@ -327,6 +327,37 @@
}))
}
+ /// Constructs a new `Rc` with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::rc::Rc;
+ ///
+ /// let mut five = Rc::<u32>::new_uninit();
+ ///
+ /// let five = unsafe {
+ /// // Deferred initialization:
+ /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> {
+ unsafe {
+ Rc::from_ptr(Rc::allocate_for_layout(
+ Layout::new::<T>(),
+ |mem| mem as *mut RcBox<mem::MaybeUninit<T>>,
+ ))
+ }
+ }
+
/// Constructs a new `Pin<Rc<T>>`. If `T` does not implement `Unpin`, then
/// `value` will be pinned in memory and unable to be moved.
#[stable(feature = "pin", since = "1.33.0")]
@@ -377,6 +408,118 @@
}
}
+impl<T> Rc<[T]> {
+ /// Constructs a new reference-counted slice with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::rc::Rc;
+ ///
+ /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
+ /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
+ /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> {
+ unsafe {
+ Rc::from_ptr(Rc::allocate_for_slice(len))
+ }
+ }
+}
+
+impl<T> Rc<mem::MaybeUninit<T>> {
+ /// Converts to `Rc<T>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the value
+ /// really is in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::rc::Rc;
+ ///
+ /// let mut five = Rc::<u32>::new_uninit();
+ ///
+ /// let five = unsafe {
+ /// // Deferred initialization:
+ /// Rc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Rc<T> {
+ Rc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
+ }
+}
+
+impl<T> Rc<[mem::MaybeUninit<T>]> {
+ /// Converts to `Rc<[T]>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the value
+ /// really is in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::rc::Rc;
+ ///
+ /// let mut values = Rc::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// Rc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
+ /// Rc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
+ /// Rc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Rc<[T]> {
+ Rc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _)
+ }
+}
+
impl<T: ?Sized> Rc<T> {
/// Consumes the `Rc`, returning the wrapped pointer.
///
@@ -560,13 +703,46 @@
pub fn get_mut(this: &mut Self) -> Option<&mut T> {
if Rc::is_unique(this) {
unsafe {
- Some(&mut this.ptr.as_mut().value)
+ Some(Rc::get_mut_unchecked(this))
}
} else {
None
}
}
+ /// Returns a mutable reference to the inner value,
+ /// without any check.
+ ///
+ /// See also [`get_mut`], which is safe and does appropriate checks.
+ ///
+ /// [`get_mut`]: struct.Rc.html#method.get_mut
+ ///
+ /// # Safety
+ ///
+ /// Any other `Rc` or [`Weak`] pointers to the same value must not be dereferenced
+ /// for the duration of the returned borrow.
+ /// This is trivially the case if no such pointers exist,
+ /// for example immediately after `Rc::new`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::rc::Rc;
+ ///
+ /// let mut x = Rc::new(String::new());
+ /// unsafe {
+ /// Rc::get_mut_unchecked(&mut x).push_str("foo")
+ /// }
+ /// assert_eq!(*x, "foo");
+ /// ```
+ #[inline]
+ #[unstable(feature = "get_mut_unchecked", issue = "63292")]
+ pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
+ &mut this.ptr.as_mut().value
+ }
+
#[inline]
#[stable(feature = "ptr_eq", since = "1.17.0")]
/// Returns `true` if the two `Rc`s point to the same value (not
@@ -704,11 +880,11 @@
impl<T: ?Sized> Rc<T> {
/// Allocates an `RcBox<T>` with sufficient space for
- /// an unsized value where the value has the layout provided.
+ /// a possibly-unsized value where the value has the layout provided.
///
/// The function `mem_to_rcbox` is called with the data pointer
/// and must return back a (potentially fat)-pointer for the `RcBox<T>`.
- unsafe fn allocate_for_unsized(
+ unsafe fn allocate_for_layout(
value_layout: Layout,
mem_to_rcbox: impl FnOnce(*mut u8) -> *mut RcBox<T>
) -> *mut RcBox<T> {
@@ -737,7 +913,7 @@
/// Allocates an `RcBox<T>` with sufficient space for an unsized value
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
// Allocate for the `RcBox<T>` using the given value.
- Self::allocate_for_unsized(
+ Self::allocate_for_layout(
Layout::for_value(&*ptr),
|mem| set_data_ptr(ptr as *mut T, mem) as *mut RcBox<T>,
)
@@ -768,7 +944,7 @@
impl<T> Rc<[T]> {
/// Allocates an `RcBox<[T]>` with the given length.
unsafe fn allocate_for_slice(len: usize) -> *mut RcBox<[T]> {
- Self::allocate_for_unsized(
+ Self::allocate_for_layout(
Layout::array::<T>(len).unwrap(),
|mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut RcBox<[T]>,
)
diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs
index eca726c..b65f191 100644
--- a/src/liballoc/string.rs
+++ b/src/liballoc/string.rs
@@ -56,7 +56,7 @@
use core::str::{pattern::Pattern, lossy};
use crate::borrow::{Cow, ToOwned};
-use crate::collections::CollectionAllocErr;
+use crate::collections::TryReserveError;
use crate::boxed::Box;
use crate::str::{self, from_boxed_utf8_unchecked, FromStr, Utf8Error, Chars};
use crate::vec::Vec;
@@ -937,9 +937,9 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
///
- /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
+ /// fn process_data(data: &str) -> Result<String, TryReserveError> {
/// let mut output = String::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -953,7 +953,7 @@
/// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.vec.try_reserve(additional)
}
@@ -975,9 +975,9 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
///
- /// fn process_data(data: &str) -> Result<String, CollectionAllocErr> {
+ /// fn process_data(data: &str) -> Result<String, TryReserveError> {
/// let mut output = String::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -991,7 +991,7 @@
/// # process_data("rust").expect("why is the test harness OOMing on 4 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.vec.try_reserve_exact(additional)
}
diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs
index 7d3b265..3411721 100644
--- a/src/liballoc/sync.rs
+++ b/src/liballoc/sync.rs
@@ -311,6 +311,37 @@
Self::from_inner(Box::into_raw_non_null(x))
}
+ /// Constructs a new `Arc` with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::sync::Arc;
+ ///
+ /// let mut five = Arc::<u32>::new_uninit();
+ ///
+ /// let five = unsafe {
+ /// // Deferred initialization:
+ /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit() -> Arc<mem::MaybeUninit<T>> {
+ unsafe {
+ Arc::from_ptr(Arc::allocate_for_layout(
+ Layout::new::<T>(),
+ |mem| mem as *mut ArcInner<mem::MaybeUninit<T>>,
+ ))
+ }
+ }
+
/// Constructs a new `Pin<Arc<T>>`. If `T` does not implement `Unpin`, then
/// `data` will be pinned in memory and unable to be moved.
#[stable(feature = "pin", since = "1.33.0")]
@@ -361,6 +392,118 @@
}
}
+impl<T> Arc<[T]> {
+ /// Constructs a new reference-counted slice with uninitialized contents.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::sync::Arc;
+ ///
+ /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
+ /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
+ /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> {
+ unsafe {
+ Arc::from_ptr(Arc::allocate_for_slice(len))
+ }
+ }
+}
+
+impl<T> Arc<mem::MaybeUninit<T>> {
+ /// Converts to `Arc<T>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the value
+ /// really is in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::sync::Arc;
+ ///
+ /// let mut five = Arc::<u32>::new_uninit();
+ ///
+ /// let five = unsafe {
+ /// // Deferred initialization:
+ /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
+ ///
+ /// five.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*five, 5)
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Arc<T> {
+ Arc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
+ }
+}
+
+impl<T> Arc<[mem::MaybeUninit<T>]> {
+ /// Converts to `Arc<[T]>`.
+ ///
+ /// # Safety
+ ///
+ /// As with [`MaybeUninit::assume_init`],
+ /// it is up to the caller to guarantee that the value
+ /// really is in an initialized state.
+ /// Calling this when the content is not yet fully initialized
+ /// causes immediate undefined behavior.
+ ///
+ /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(new_uninit)]
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::sync::Arc;
+ ///
+ /// let mut values = Arc::<[u32]>::new_uninit_slice(3);
+ ///
+ /// let values = unsafe {
+ /// // Deferred initialization:
+ /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1);
+ /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2);
+ /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3);
+ ///
+ /// values.assume_init()
+ /// };
+ ///
+ /// assert_eq!(*values, [1, 2, 3])
+ /// ```
+ #[unstable(feature = "new_uninit", issue = "63291")]
+ #[inline]
+ pub unsafe fn assume_init(self) -> Arc<[T]> {
+ Arc::from_ptr(mem::ManuallyDrop::new(self).ptr.as_ptr() as _)
+ }
+}
+
impl<T: ?Sized> Arc<T> {
/// Consumes the `Arc`, returning the wrapped pointer.
///
@@ -593,11 +736,11 @@
impl<T: ?Sized> Arc<T> {
/// Allocates an `ArcInner<T>` with sufficient space for
- /// an unsized value where the value has the layout provided.
+ /// a possibly-unsized value where the value has the layout provided.
///
/// The function `mem_to_arcinner` is called with the data pointer
/// and must return back a (potentially fat)-pointer for the `ArcInner<T>`.
- unsafe fn allocate_for_unsized(
+ unsafe fn allocate_for_layout(
value_layout: Layout,
mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner<T>
) -> *mut ArcInner<T> {
@@ -625,7 +768,7 @@
/// Allocates an `ArcInner<T>` with sufficient space for an unsized value.
unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
// Allocate for the `ArcInner<T>` using the given value.
- Self::allocate_for_unsized(
+ Self::allocate_for_layout(
Layout::for_value(&*ptr),
|mem| set_data_ptr(ptr as *mut T, mem) as *mut ArcInner<T>,
)
@@ -656,7 +799,7 @@
impl<T> Arc<[T]> {
/// Allocates an `ArcInner<[T]>` with the given length.
unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> {
- Self::allocate_for_unsized(
+ Self::allocate_for_layout(
Layout::array::<T>(len).unwrap(),
|mem| ptr::slice_from_raw_parts_mut(mem as *mut T, len) as *mut ArcInner<[T]>,
)
@@ -945,13 +1088,46 @@
// the Arc itself to be `mut`, so we're returning the only possible
// reference to the inner data.
unsafe {
- Some(&mut this.ptr.as_mut().data)
+ Some(Arc::get_mut_unchecked(this))
}
} else {
None
}
}
+ /// Returns a mutable reference to the inner value,
+ /// without any check.
+ ///
+ /// See also [`get_mut`], which is safe and does appropriate checks.
+ ///
+ /// [`get_mut`]: struct.Arc.html#method.get_mut
+ ///
+ /// # Safety
+ ///
+ /// Any other `Arc` or [`Weak`] pointers to the same value must not be dereferenced
+ /// for the duration of the returned borrow.
+ /// This is trivially the case if no such pointers exist,
+ /// for example immediately after `Arc::new`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(get_mut_unchecked)]
+ ///
+ /// use std::sync::Arc;
+ ///
+ /// let mut x = Arc::new(String::new());
+ /// unsafe {
+ /// Arc::get_mut_unchecked(&mut x).push_str("foo")
+ /// }
+ /// assert_eq!(*x, "foo");
+ /// ```
+ #[inline]
+ #[unstable(feature = "get_mut_unchecked", issue = "63292")]
+ pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
+ &mut this.ptr.as_mut().data
+ }
+
/// Determine whether this is the unique reference (including weak refs) to
/// the underlying data.
///
diff --git a/src/liballoc/tests/string.rs b/src/liballoc/tests/string.rs
index 765210e..55edf56 100644
--- a/src/liballoc/tests/string.rs
+++ b/src/liballoc/tests/string.rs
@@ -1,5 +1,5 @@
use std::borrow::Cow;
-use std::collections::CollectionAllocErr::*;
+use std::collections::TryReserveError::*;
use std::mem::size_of;
use std::{usize, isize};
@@ -566,11 +566,11 @@
} else { panic!("usize::MAX should trigger an overflow!") }
} else {
// Check isize::MAX + 1 is an OOM
- if let Err(AllocErr) = empty_string.try_reserve(MAX_CAP + 1) {
+ if let Err(AllocError { .. }) = empty_string.try_reserve(MAX_CAP + 1) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
// Check usize::MAX is an OOM
- if let Err(AllocErr) = empty_string.try_reserve(MAX_USIZE) {
+ if let Err(AllocError { .. }) = empty_string.try_reserve(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an OOM!") }
}
}
@@ -590,7 +590,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
// Should always overflow in the add-to-len
@@ -629,10 +629,10 @@
if let Err(CapacityOverflow) = empty_string.try_reserve_exact(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an overflow!") }
} else {
- if let Err(AllocErr) = empty_string.try_reserve_exact(MAX_CAP + 1) {
+ if let Err(AllocError { .. }) = empty_string.try_reserve_exact(MAX_CAP + 1) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
- if let Err(AllocErr) = empty_string.try_reserve_exact(MAX_USIZE) {
+ if let Err(AllocError { .. }) = empty_string.try_reserve_exact(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an OOM!") }
}
}
@@ -651,7 +651,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) {
diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs
index 6e8ffe1..29a22aa 100644
--- a/src/liballoc/tests/vec.rs
+++ b/src/liballoc/tests/vec.rs
@@ -2,7 +2,7 @@
use std::mem::size_of;
use std::{usize, isize};
use std::vec::{Drain, IntoIter};
-use std::collections::CollectionAllocErr::*;
+use std::collections::TryReserveError::*;
struct DropCounter<'a> {
count: &'a mut u32,
@@ -1121,11 +1121,11 @@
} else { panic!("usize::MAX should trigger an overflow!") }
} else {
// Check isize::MAX + 1 is an OOM
- if let Err(AllocErr) = empty_bytes.try_reserve(MAX_CAP + 1) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_CAP + 1) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
// Check usize::MAX is an OOM
- if let Err(AllocErr) = empty_bytes.try_reserve(MAX_USIZE) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an OOM!") }
}
}
@@ -1145,7 +1145,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
// Should always overflow in the add-to-len
@@ -1168,7 +1168,7 @@
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
+ if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
// Should fail in the mul-by-size
@@ -1209,10 +1209,10 @@
if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an overflow!") }
} else {
- if let Err(AllocErr) = empty_bytes.try_reserve_exact(MAX_CAP + 1) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve_exact(MAX_CAP + 1) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
- if let Err(AllocErr) = empty_bytes.try_reserve_exact(MAX_USIZE) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve_exact(MAX_USIZE) {
} else { panic!("usize::MAX should trigger an OOM!") }
}
}
@@ -1231,7 +1231,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) {
@@ -1252,7 +1252,7 @@
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
+ if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_USIZE - 20) {
diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs
index 1bbcca9..d49b553 100644
--- a/src/liballoc/tests/vec_deque.rs
+++ b/src/liballoc/tests/vec_deque.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
use std::collections::{VecDeque, vec_deque::Drain};
-use std::collections::CollectionAllocErr::*;
+use std::collections::TryReserveError::*;
use std::mem::size_of;
use std::{usize, isize};
@@ -1168,7 +1168,7 @@
// VecDeque starts with capacity 7, always adds 1 to the capacity
// and also rounds the number to next power of 2 so this is the
// furthest we can go without triggering CapacityOverflow
- if let Err(AllocErr) = empty_bytes.try_reserve(MAX_CAP) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_CAP) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
}
@@ -1188,7 +1188,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
// Should always overflow in the add-to-len
@@ -1211,7 +1211,7 @@
if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
+ if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
// Should fail in the mul-by-size
@@ -1256,7 +1256,7 @@
// VecDeque starts with capacity 7, always adds 1 to the capacity
// and also rounds the number to next power of 2 so this is the
// furthest we can go without triggering CapacityOverflow
- if let Err(AllocErr) = empty_bytes.try_reserve_exact(MAX_CAP) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve_exact(MAX_CAP) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
}
@@ -1275,7 +1275,7 @@
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
+ if let Err(AllocError { .. }) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) {
@@ -1296,7 +1296,7 @@
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an overflow!"); }
} else {
- if let Err(AllocErr) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
+ if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
} else { panic!("isize::MAX + 1 should trigger an OOM!") }
}
if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_USIZE - 20) {
diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs
index dac04e4..d279895 100644
--- a/src/liballoc/vec.rs
+++ b/src/liballoc/vec.rs
@@ -70,7 +70,7 @@
use core::slice::{self, SliceIndex};
use crate::borrow::{ToOwned, Cow};
-use crate::collections::CollectionAllocErr;
+use crate::collections::TryReserveError;
use crate::boxed::Box;
use crate::raw_vec::RawVec;
@@ -498,9 +498,9 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
///
- /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
+ /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
/// let mut output = Vec::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -516,7 +516,7 @@
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.buf.try_reserve(self.len, additional)
}
@@ -538,9 +538,9 @@
///
/// ```
/// #![feature(try_reserve)]
- /// use std::collections::CollectionAllocErr;
+ /// use std::collections::TryReserveError;
///
- /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
+ /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
/// let mut output = Vec::new();
///
/// // Pre-reserve the memory, exiting if we can't
@@ -556,7 +556,7 @@
/// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
/// ```
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.buf.try_reserve_exact(self.len, additional)
}
diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs
index ec22a7c..ec70d39 100644
--- a/src/libcore/clone.rs
+++ b/src/libcore/clone.rs
@@ -135,7 +135,7 @@
/// Derive macro generating an impl of the trait `Clone`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
pub macro Clone($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs
index b802216..cb9feb0 100644
--- a/src/libcore/cmp.rs
+++ b/src/libcore/cmp.rs
@@ -202,7 +202,7 @@
/// Derive macro generating an impl of the trait `PartialEq`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro PartialEq($item:item) { /* compiler built-in */ }
@@ -265,7 +265,7 @@
/// Derive macro generating an impl of the trait `Eq`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_eq)]
pub macro Eq($item:item) { /* compiler built-in */ }
@@ -616,7 +616,7 @@
/// Derive macro generating an impl of the trait `Ord`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro Ord($item:item) { /* compiler built-in */ }
@@ -865,7 +865,7 @@
/// Derive macro generating an impl of the trait `PartialOrd`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro PartialOrd($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/default.rs b/src/libcore/default.rs
index 9b1616c..66acc51 100644
--- a/src/libcore/default.rs
+++ b/src/libcore/default.rs
@@ -117,7 +117,7 @@
/// Derive macro generating an impl of the trait `Default`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro Default($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/fmt/builders.rs b/src/libcore/fmt/builders.rs
index cb4e326..15ce227 100644
--- a/src/libcore/fmt/builders.rs
+++ b/src/libcore/fmt/builders.rs
@@ -98,7 +98,7 @@
has_fields: bool,
}
-pub fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>,
+pub(super) fn debug_struct_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>,
name: &str)
-> DebugStruct<'a, 'b> {
let result = fmt.write_str(name);
@@ -251,7 +251,10 @@
empty_name: bool,
}
-pub fn debug_tuple_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>, name: &str) -> DebugTuple<'a, 'b> {
+pub(super) fn debug_tuple_new<'a, 'b>(
+ fmt: &'a mut fmt::Formatter<'b>,
+ name: &str,
+) -> DebugTuple<'a, 'b> {
let result = fmt.write_str(name);
DebugTuple {
fmt,
@@ -418,7 +421,7 @@
inner: DebugInner<'a, 'b>,
}
-pub fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
+pub(super) fn debug_set_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugSet<'a, 'b> {
let result = fmt.write_str("{");
DebugSet {
inner: DebugInner {
@@ -555,7 +558,7 @@
inner: DebugInner<'a, 'b>,
}
-pub fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
+pub(super) fn debug_list_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugList<'a, 'b> {
let result = fmt.write_str("[");
DebugList {
inner: DebugInner {
@@ -697,7 +700,7 @@
state: PadAdapterState,
}
-pub fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
+pub(super) fn debug_map_new<'a, 'b>(fmt: &'a mut fmt::Formatter<'b>) -> DebugMap<'a, 'b> {
let result = fmt.write_str("{");
DebugMap {
fmt,
diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs
index d5fae9e..bd31d25 100644
--- a/src/libcore/fmt/mod.rs
+++ b/src/libcore/fmt/mod.rs
@@ -549,7 +549,7 @@
pub(crate) mod macros {
/// Derive macro generating an impl of the trait `Debug`.
#[rustc_builtin_macro]
- #[rustc_macro_transparency = "semitransparent"]
+ #[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro Debug($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/hash/mod.rs b/src/libcore/hash/mod.rs
index b397119..bf3daa3 100644
--- a/src/libcore/hash/mod.rs
+++ b/src/libcore/hash/mod.rs
@@ -202,7 +202,7 @@
pub(crate) mod macros {
/// Derive macro generating an impl of the trait `Hash`.
#[rustc_builtin_macro]
- #[rustc_macro_transparency = "semitransparent"]
+ #[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro Hash($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs
index ceaa870..d145f22 100644
--- a/src/libcore/intrinsics.rs
+++ b/src/libcore/intrinsics.rs
@@ -1293,18 +1293,40 @@
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_add` method. For example,
/// [`std::u32::wrapping_add`](../../std/primitive.u32.html#method.wrapping_add)
+ #[cfg(boostrap_stdarch_ignore_this)]
pub fn overflowing_add<T>(a: T, b: T) -> T;
/// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_sub` method. For example,
/// [`std::u32::wrapping_sub`](../../std/primitive.u32.html#method.wrapping_sub)
+ #[cfg(boostrap_stdarch_ignore_this)]
pub fn overflowing_sub<T>(a: T, b: T) -> T;
/// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_mul` method. For example,
/// [`std::u32::wrapping_mul`](../../std/primitive.u32.html#method.wrapping_mul)
+ #[cfg(boostrap_stdarch_ignore_this)]
pub fn overflowing_mul<T>(a: T, b: T) -> T;
+ /// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
+ /// The stabilized versions of this intrinsic are available on the integer
+ /// primitives via the `wrapping_add` method. For example,
+ /// [`std::u32::wrapping_add`](../../std/primitive.u32.html#method.wrapping_add)
+ #[cfg(not(boostrap_stdarch_ignore_this))]
+ pub fn wrapping_add<T>(a: T, b: T) -> T;
+ /// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
+ /// The stabilized versions of this intrinsic are available on the integer
+ /// primitives via the `wrapping_sub` method. For example,
+ /// [`std::u32::wrapping_sub`](../../std/primitive.u32.html#method.wrapping_sub)
+ #[cfg(not(boostrap_stdarch_ignore_this))]
+ pub fn wrapping_sub<T>(a: T, b: T) -> T;
+ /// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
+ /// The stabilized versions of this intrinsic are available on the integer
+ /// primitives via the `wrapping_mul` method. For example,
+ /// [`std::u32::wrapping_mul`](../../std/primitive.u32.html#method.wrapping_mul)
+ #[cfg(not(boostrap_stdarch_ignore_this))]
+ pub fn wrapping_mul<T>(a: T, b: T) -> T;
+
/// Computes `a + b`, while saturating at numeric bounds.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `saturating_add` method. For example,
diff --git a/src/libcore/iter/adapters/chain.rs b/src/libcore/iter/adapters/chain.rs
index 76239eb..0b9f7f6 100644
--- a/src/libcore/iter/adapters/chain.rs
+++ b/src/libcore/iter/adapters/chain.rs
@@ -207,6 +207,29 @@
}
}
+ #[inline]
+ fn nth_back(&mut self, mut n: usize) -> Option<A::Item> {
+ match self.state {
+ ChainState::Both | ChainState::Back => {
+ for x in self.b.by_ref().rev() {
+ if n == 0 {
+ return Some(x)
+ }
+ n -= 1;
+ }
+ if let ChainState::Both = self.state {
+ self.state = ChainState::Front;
+ }
+ }
+ ChainState::Front => {}
+ }
+ if let ChainState::Front = self.state {
+ self.a.nth_back(n)
+ } else {
+ None
+ }
+ }
+
fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
{
diff --git a/src/libcore/iter/adapters/flatten.rs b/src/libcore/iter/adapters/flatten.rs
index e3c8565..a45173f 100644
--- a/src/libcore/iter/adapters/flatten.rs
+++ b/src/libcore/iter/adapters/flatten.rs
@@ -72,8 +72,7 @@
impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F>
where
F: FnMut(I::Item) -> U,
- U: IntoIterator,
- U::IntoIter: DoubleEndedIterator,
+ U: IntoIterator<IntoIter: DoubleEndedIterator>,
{
#[inline]
fn next_back(&mut self) -> Option<U::Item> { self.inner.next_back() }
@@ -107,10 +106,7 @@
/// [`Iterator`]: trait.Iterator.html
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "iterator_flatten", since = "1.29.0")]
-pub struct Flatten<I: Iterator>
-where
- I::Item: IntoIterator,
-{
+pub struct Flatten<I: Iterator<Item: IntoIterator>> {
inner: FlattenCompat<I, <I::Item as IntoIterator>::IntoIter>,
}
diff --git a/src/libcore/iter/adapters/mod.rs b/src/libcore/iter/adapters/mod.rs
index 58e0a70..a63434a 100644
--- a/src/libcore/iter/adapters/mod.rs
+++ b/src/libcore/iter/adapters/mod.rs
@@ -405,6 +405,36 @@
_ => (usize::MAX, None)
}
}
+
+ #[inline]
+ fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
+ where
+ F: FnMut(Acc, Self::Item) -> R,
+ R: Try<Ok = Acc>,
+ {
+ // fully iterate the current iterator. this is necessary because
+ // `self.iter` may be empty even when `self.orig` isn't
+ acc = self.iter.try_fold(acc, &mut f)?;
+ self.iter = self.orig.clone();
+
+ // complete a full cycle, keeping track of whether the cycled
+ // iterator is empty or not. we need to return early in case
+ // of an empty iterator to prevent an infinite loop
+ let mut is_empty = true;
+ acc = self.iter.try_fold(acc, |acc, x| {
+ is_empty = false;
+ f(acc, x)
+ })?;
+
+ if is_empty {
+ return Try::from_ok(acc);
+ }
+
+ loop {
+ self.iter = self.orig.clone();
+ acc = self.iter.try_fold(acc, &mut f)?;
+ }
+ }
}
#[stable(feature = "fused", since = "1.26.0")]
diff --git a/src/libcore/iter/traits/double_ended.rs b/src/libcore/iter/traits/double_ended.rs
index 8e5bc9b..006b243 100644
--- a/src/libcore/iter/traits/double_ended.rs
+++ b/src/libcore/iter/traits/double_ended.rs
@@ -69,7 +69,7 @@
/// Returns the `n`th element from the end of the iterator.
///
/// This is essentially the reversed version of [`nth`]. Although like most indexing
- /// operations, the count starts from zero, so `nth_back(0)` returns the first value fro
+ /// operations, the count starts from zero, so `nth_back(0)` returns the first value from
/// the end, `nth_back(1)` the second, and so on.
///
/// Note that all elements between the end and the returned element will be
diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs
index bbed951..6c88a76 100644
--- a/src/libcore/macros.rs
+++ b/src/libcore/macros.rs
@@ -2,21 +2,21 @@
///
/// For details, see `std::macros`.
#[macro_export]
-#[allow_internal_unstable(core_panic, __rust_unstable_column)]
+#[allow_internal_unstable(core_panic)]
#[stable(feature = "core", since = "1.6.0")]
macro_rules! panic {
() => (
$crate::panic!("explicit panic")
);
($msg:expr) => ({
- $crate::panicking::panic(&($msg, file!(), line!(), __rust_unstable_column!()))
+ $crate::panicking::panic(&($msg, $crate::file!(), $crate::line!(), $crate::column!()))
});
($msg:expr,) => (
$crate::panic!($msg)
);
($fmt:expr, $($arg:tt)+) => ({
- $crate::panicking::panic_fmt(format_args!($fmt, $($arg)+),
- &(file!(), line!(), __rust_unstable_column!()))
+ $crate::panicking::panic_fmt($crate::format_args!($fmt, $($arg)+),
+ &($crate::file!(), $crate::line!(), $crate::column!()))
});
}
@@ -70,7 +70,7 @@
panic!(r#"assertion failed: `(left == right)`
left: `{:?}`,
right: `{:?}`: {}"#, &*left_val, &*right_val,
- format_args!($($arg)+))
+ $crate::format_args!($($arg)+))
}
}
}
@@ -127,7 +127,7 @@
panic!(r#"assertion failed: `(left != right)`
left: `{:?}`,
right: `{:?}`: {}"#, &*left_val, &*right_val,
- format_args!($($arg)+))
+ $crate::format_args!($($arg)+))
}
}
}
@@ -181,7 +181,7 @@
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert {
- ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
+ ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
}
/// Asserts that two expressions are equal to each other.
@@ -208,7 +208,7 @@
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! debug_assert_eq {
- ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
+ ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
}
/// Asserts that two expressions are not equal to each other.
@@ -235,7 +235,7 @@
#[macro_export]
#[stable(feature = "assert_ne", since = "1.13.0")]
macro_rules! debug_assert_ne {
- ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
+ ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
}
/// Unwraps a result or propagates its error.
@@ -386,7 +386,7 @@
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! write {
- ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
+ ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
}
/// Write formatted data into a buffer, with a newline appended.
@@ -446,7 +446,7 @@
$crate::writeln!($dst)
);
($dst:expr, $($arg:tt)*) => (
- $dst.write_fmt(format_args_nl!($($arg)*))
+ $dst.write_fmt($crate::format_args_nl!($($arg)*))
);
}
@@ -515,7 +515,7 @@
$crate::unreachable!($msg)
});
($fmt:expr, $($arg:tt)*) => ({
- panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
+ panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
});
}
@@ -573,7 +573,7 @@
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! unimplemented {
() => (panic!("not yet implemented"));
- ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
+ ($($arg:tt)+) => (panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
}
/// Indicates unfinished code.
@@ -632,7 +632,7 @@
#[unstable(feature = "todo_macro", issue = "59277")]
macro_rules! todo {
() => (panic!("not yet implemented"));
- ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
+ ($($arg:tt)+) => (panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
}
/// Definitions of built-in macros.
@@ -927,13 +927,6 @@
#[macro_export]
macro_rules! column { () => { /* compiler built-in */ } }
- /// Same as `column`, but less likely to be shadowed.
- #[unstable(feature = "__rust_unstable_column", issue = "0",
- reason = "internal implementation detail of the `panic` macro")]
- #[rustc_builtin_macro]
- #[macro_export]
- macro_rules! __rust_unstable_column { () => { /* compiler built-in */ } }
-
/// Expands to the file name in which it was invoked.
///
/// With [`line!`] and [`column!`], these macros provide debugging information for
@@ -1270,14 +1263,14 @@
/// Unstable implementation detail of the `rustc` compiler, do not use.
#[rustc_builtin_macro]
- #[rustc_macro_transparency = "semitransparent"]
+ #[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
pub macro RustcDecodable($item:item) { /* compiler built-in */ }
/// Unstable implementation detail of the `rustc` compiler, do not use.
#[rustc_builtin_macro]
- #[rustc_macro_transparency = "semitransparent"]
+ #[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable(core_intrinsics)]
pub macro RustcEncodable($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs
index 3befd42..89af252 100644
--- a/src/libcore/marker.rs
+++ b/src/libcore/marker.rs
@@ -290,7 +290,7 @@
/// Derive macro generating an impl of the trait `Copy`.
#[rustc_builtin_macro]
-#[rustc_macro_transparency = "semitransparent"]
+#[cfg_attr(boostrap_stdarch_ignore_this, rustc_macro_transparency = "semitransparent")]
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
pub macro Copy($item:item) { /* compiler built-in */ }
diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs
index 67e30e7..b46e06f 100644
--- a/src/libcore/num/mod.rs
+++ b/src/libcore/num/mod.rs
@@ -1112,7 +1112,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_add(self, rhs: Self) -> Self {
- intrinsics::overflowing_add(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_add(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_add(self, rhs)
+ }
}
}
@@ -1135,7 +1141,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
- intrinsics::overflowing_sub(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_sub(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_sub(self, rhs)
+ }
}
}
@@ -1157,7 +1169,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
- intrinsics::overflowing_mul(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_mul(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_mul(self, rhs)
+ }
}
}
@@ -3031,7 +3049,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_add(self, rhs: Self) -> Self {
- intrinsics::overflowing_add(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_add(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_add(self, rhs)
+ }
}
}
@@ -3053,7 +3077,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
- intrinsics::overflowing_sub(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_sub(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_sub(self, rhs)
+ }
}
}
@@ -3076,7 +3106,13 @@
without modifying the original"]
#[inline]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
- intrinsics::overflowing_mul(self, rhs)
+ #[cfg(boostrap_stdarch_ignore_this)] {
+ intrinsics::overflowing_mul(self, rhs)
+ }
+
+ #[cfg(not(boostrap_stdarch_ignore_this))] {
+ intrinsics::wrapping_mul(self, rhs)
+ }
}
doc_comment! {
diff --git a/src/libcore/prelude/v1.rs b/src/libcore/prelude/v1.rs
index 7624037..7cc279a 100644
--- a/src/libcore/prelude/v1.rs
+++ b/src/libcore/prelude/v1.rs
@@ -56,7 +56,6 @@
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[doc(no_inline)]
pub use crate::{
- __rust_unstable_column,
asm,
assert,
cfg,
diff --git a/src/libcore/ptr/unique.rs b/src/libcore/ptr/unique.rs
index f0d011f..3521dd7 100644
--- a/src/libcore/ptr/unique.rs
+++ b/src/libcore/ptr/unique.rs
@@ -122,6 +122,14 @@
pub unsafe fn as_mut(&mut self) -> &mut T {
&mut *self.as_ptr()
}
+
+ /// Casts to a pointer of another type.
+ #[inline]
+ pub const fn cast<U>(self) -> Unique<U> {
+ unsafe {
+ Unique::new_unchecked(self.as_ptr() as *mut U)
+ }
+ }
}
#[unstable(feature = "ptr_internals", issue = "0")]
diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs
index 3615fab..a1a27e1 100644
--- a/src/libcore/tests/iter.rs
+++ b/src/libcore/tests/iter.rs
@@ -104,6 +104,22 @@
}
#[test]
+fn test_iterator_chain_nth_back() {
+ let xs = [0, 1, 2, 3, 4, 5];
+ let ys = [30, 40, 50, 60];
+ let zs = [];
+ let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
+ for (i, x) in expected.iter().rev().enumerate() {
+ assert_eq!(Some(x), xs.iter().chain(&ys).nth_back(i));
+ }
+ assert_eq!(zs.iter().chain(&xs).nth_back(0), Some(&5));
+
+ let mut it = xs.iter().chain(&zs);
+ assert_eq!(it.nth_back(5), Some(&0));
+ assert_eq!(it.next(), None);
+}
+
+#[test]
fn test_iterator_chain_last() {
let xs = [0, 1, 2, 3, 4, 5];
let ys = [30, 40, 50, 60];
@@ -1136,6 +1152,18 @@
assert_eq!(empty::<i32>().cycle().fold(0, |acc, x| acc + x), 0);
assert_eq!(once(1).cycle().skip(1).take(4).fold(0, |acc, x| acc + x), 4);
+
+ assert_eq!((0..10).cycle().take(5).sum::<i32>(), 10);
+ assert_eq!((0..10).cycle().take(15).sum::<i32>(), 55);
+ assert_eq!((0..10).cycle().take(25).sum::<i32>(), 100);
+
+ let mut iter = (0..10).cycle();
+ iter.nth(14);
+ assert_eq!(iter.take(8).sum::<i32>(), 38);
+
+ let mut iter = (0..10).cycle();
+ iter.nth(9);
+ assert_eq!(iter.take(3).sum::<i32>(), 3);
}
#[test]
diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs
index 9e5d637..0f6e834 100644
--- a/src/librustc/hir/lowering.rs
+++ b/src/librustc/hir/lowering.rs
@@ -67,7 +67,7 @@
use syntax::ext::base::SpecialDerives;
use syntax::ext::hygiene::ExpnId;
use syntax::print::pprust;
-use syntax::source_map::{respan, ExpnInfo, ExpnKind, DesugaringKind, Spanned};
+use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned};
use syntax::symbol::{kw, sym, Symbol};
use syntax::tokenstream::{TokenStream, TokenTree};
use syntax::parse::token::{self, Token};
@@ -704,10 +704,9 @@
span: Span,
allow_internal_unstable: Option<Lrc<[Symbol]>>,
) -> Span {
- span.fresh_expansion(ExpnId::root(), ExpnInfo {
- def_site: span,
+ span.fresh_expansion(ExpnData {
allow_internal_unstable,
- ..ExpnInfo::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
+ ..ExpnData::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
})
}
@@ -1224,7 +1223,7 @@
P(hir::Path {
res,
segments: hir_vec![hir::PathSegment::from_ident(
- Ident::with_empty_ctxt(kw::SelfUpper)
+ Ident::with_dummy_span(kw::SelfUpper)
)],
span: t.span,
}),
@@ -1558,7 +1557,7 @@
let (name, kind) = match name {
hir::LifetimeName::Underscore => (
- hir::ParamName::Plain(Ident::with_empty_ctxt(kw::UnderscoreLifetime)),
+ hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)),
hir::LifetimeParamKind::Elided,
),
hir::LifetimeName::Param(param_name) => (
@@ -2002,7 +2001,7 @@
bindings: hir_vec![
hir::TypeBinding {
hir_id: this.next_id(),
- ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
+ ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
kind: hir::TypeBindingKind::Equality {
ty: output
.as_ref()
@@ -2394,7 +2393,7 @@
let future_params = P(hir::GenericArgs {
args: hir_vec![],
bindings: hir_vec![hir::TypeBinding {
- ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME),
+ ident: Ident::with_dummy_span(FN_OUTPUT_NAME),
kind: hir::TypeBindingKind::Equality {
ty: output_ty,
},
diff --git a/src/librustc/hir/lowering/expr.rs b/src/librustc/hir/lowering/expr.rs
index e3a5400..ff0c44a 100644
--- a/src/librustc/hir/lowering/expr.rs
+++ b/src/librustc/hir/lowering/expr.rs
@@ -552,7 +552,7 @@
// let mut pinned = <expr>;
let expr = P(self.lower_expr(expr));
- let pinned_ident = Ident::with_empty_ctxt(sym::pinned);
+ let pinned_ident = Ident::with_dummy_span(sym::pinned);
let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
span,
pinned_ident,
@@ -593,7 +593,7 @@
let loop_node_id = self.sess.next_node_id();
let loop_hir_id = self.lower_node_id(loop_node_id);
let ready_arm = {
- let x_ident = Ident::with_empty_ctxt(sym::result);
+ let x_ident = Ident::with_dummy_span(sym::result);
let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
let ready_pat = self.pat_std_enum(
@@ -984,7 +984,6 @@
volatile: asm.volatile,
alignstack: asm.alignstack,
dialect: asm.dialect,
- ctxt: asm.ctxt,
};
let outputs = asm.outputs
@@ -1070,9 +1069,9 @@
);
head.span = desugared_span;
- let iter = Ident::with_empty_ctxt(sym::iter);
+ let iter = Ident::with_dummy_span(sym::iter);
- let next_ident = Ident::with_empty_ctxt(sym::__next);
+ let next_ident = Ident::with_dummy_span(sym::__next);
let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
desugared_span,
next_ident,
@@ -1081,7 +1080,7 @@
// `::std::option::Option::Some(val) => __next = val`
let pat_arm = {
- let val_ident = Ident::with_empty_ctxt(sym::val);
+ let val_ident = Ident::with_dummy_span(sym::val);
let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
@@ -1247,7 +1246,7 @@
// `Ok(val) => #[allow(unreachable_code)] val,`
let ok_arm = {
- let val_ident = Ident::with_empty_ctxt(sym::val);
+ let val_ident = Ident::with_dummy_span(sym::val);
let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
let val_expr = P(self.expr_ident_with_attrs(
span,
@@ -1263,7 +1262,7 @@
// `Err(err) => #[allow(unreachable_code)]
// return Try::from_error(From::from(err)),`
let err_arm = {
- let err_ident = Ident::with_empty_ctxt(sym::err);
+ let err_ident = Ident::with_dummy_span(sym::err);
let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
let from_expr = {
let from_path = &[sym::convert, sym::From, sym::from];
diff --git a/src/librustc/hir/lowering/item.rs b/src/librustc/hir/lowering/item.rs
index 51a0c41..4f9a9ed 100644
--- a/src/librustc/hir/lowering/item.rs
+++ b/src/librustc/hir/lowering/item.rs
@@ -750,10 +750,7 @@
}
fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<hir::GlobalAsm> {
- P(hir::GlobalAsm {
- asm: ga.asm,
- ctxt: ga.ctxt,
- })
+ P(hir::GlobalAsm { asm: ga.asm })
}
fn lower_variant(&mut self, v: &Variant) -> hir::Variant {
diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs
index 7c2f990..e5ada1f 100644
--- a/src/librustc/hir/mod.rs
+++ b/src/librustc/hir/mod.rs
@@ -23,7 +23,6 @@
use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
use syntax::attr::{InlineAttr, OptimizeAttr};
-use syntax::ext::hygiene::SyntaxContext;
use syntax::symbol::{Symbol, kw};
use syntax::tokenstream::TokenStream;
use syntax::util::parser::ExprPrecedence;
@@ -202,7 +201,7 @@
match *self {
ParamName::Plain(ident) => ident,
ParamName::Fresh(_) |
- ParamName::Error => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
+ ParamName::Error => Ident::with_dummy_span(kw::UnderscoreLifetime),
}
}
@@ -237,8 +236,8 @@
pub fn ident(&self) -> Ident {
match *self {
LifetimeName::Implicit | LifetimeName::Error => Ident::invalid(),
- LifetimeName::Underscore => Ident::with_empty_ctxt(kw::UnderscoreLifetime),
- LifetimeName::Static => Ident::with_empty_ctxt(kw::StaticLifetime),
+ LifetimeName::Underscore => Ident::with_dummy_span(kw::UnderscoreLifetime),
+ LifetimeName::Static => Ident::with_dummy_span(kw::StaticLifetime),
LifetimeName::Param(param_name) => param_name.ident(),
}
}
@@ -2004,8 +2003,6 @@
pub volatile: bool,
pub alignstack: bool,
pub dialect: AsmDialect,
- #[stable_hasher(ignore)] // This is used for error reporting
- pub ctxt: SyntaxContext,
}
/// Represents an argument in a function header.
@@ -2184,8 +2181,6 @@
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
pub struct GlobalAsm {
pub asm: Symbol,
- #[stable_hasher(ignore)] // This is used for error reporting
- pub ctxt: SyntaxContext,
}
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs
index caf8220..2fd683e 100644
--- a/src/librustc/hir/print.rs
+++ b/src/librustc/hir/print.rs
@@ -1457,7 +1457,7 @@
}
pub fn print_name(&mut self, name: ast::Name) {
- self.print_ident(ast::Ident::with_empty_ctxt(name))
+ self.print_ident(ast::Ident::with_dummy_span(name))
}
pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) {
diff --git a/src/librustc/ich/hcx.rs b/src/librustc/ich/hcx.rs
index ae7d82c..e77faea 100644
--- a/src/librustc/ich/hcx.rs
+++ b/src/librustc/ich/hcx.rs
@@ -350,7 +350,7 @@
let line_col_len = col | line | len;
std_hash::Hash::hash(&line_col_len, hasher);
- if span.ctxt == SyntaxContext::empty() {
+ if span.ctxt == SyntaxContext::root() {
TAG_NO_EXPANSION.hash_stable(hcx, hasher);
} else {
TAG_EXPANSION.hash_stable(hcx, hasher);
@@ -370,7 +370,7 @@
}
let mut hasher = StableHasher::new();
- expn_id.expn_info().hash_stable(hcx, &mut hasher);
+ expn_id.expn_data().hash_stable(hcx, &mut hasher);
let sub_hash: Fingerprint = hasher.finish();
let sub_hash = sub_hash.to_smaller_hash();
cache.borrow_mut().insert(expn_id, sub_hash);
diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs
index 5cc8324..7003f71 100644
--- a/src/librustc/ich/impls_syntax.rs
+++ b/src/librustc/ich/impls_syntax.rs
@@ -397,9 +397,10 @@
Opaque,
});
-impl_stable_hash_for!(struct ::syntax_pos::hygiene::ExpnInfo {
- call_site,
+impl_stable_hash_for!(struct ::syntax_pos::hygiene::ExpnData {
kind,
+ parent -> _,
+ call_site,
def_site,
default_transparency,
allow_internal_unstable,
diff --git a/src/librustc/lint/internal.rs b/src/librustc/lint/internal.rs
index dea1cc6..be73b30 100644
--- a/src/librustc/lint/internal.rs
+++ b/src/librustc/lint/internal.rs
@@ -9,7 +9,6 @@
use rustc_data_structures::fx::FxHashMap;
use syntax::ast::{Ident, Item, ItemKind};
use syntax::symbol::{sym, Symbol};
-use syntax_pos::ExpnInfo;
declare_tool_lint! {
pub rustc::DEFAULT_HASH_TYPES,
@@ -108,7 +107,7 @@
.help("try using `Ty` instead")
.emit();
} else {
- if ty.span.ctxt().outer_expn_info().is_some() {
+ if ty.span.from_expansion() {
return;
}
if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
@@ -228,30 +227,20 @@
if let ItemKind::Impl(_, _, _, _, Some(lint_pass), _, _) = &item.node {
if let Some(last) = lint_pass.path.segments.last() {
if last.ident.name == sym::LintPass {
- match &lint_pass.path.span.ctxt().outer_expn_info() {
- Some(info) if is_lint_pass_expansion(info) => {}
- _ => {
- cx.struct_span_lint(
- LINT_PASS_IMPL_WITHOUT_MACRO,
- lint_pass.path.span,
- "implementing `LintPass` by hand",
- )
- .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
- .emit();
- }
+ let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
+ let call_site = expn_data.call_site;
+ if expn_data.kind.descr() != sym::impl_lint_pass &&
+ call_site.ctxt().outer_expn_data().kind.descr() != sym::declare_lint_pass {
+ cx.struct_span_lint(
+ LINT_PASS_IMPL_WITHOUT_MACRO,
+ lint_pass.path.span,
+ "implementing `LintPass` by hand",
+ )
+ .help("try using `declare_lint_pass!` or `impl_lint_pass!` instead")
+ .emit();
}
}
}
}
}
}
-
-fn is_lint_pass_expansion(expn_info: &ExpnInfo) -> bool {
- if expn_info.kind.descr() == sym::impl_lint_pass {
- true
- } else if let Some(info) = expn_info.call_site.ctxt().outer_expn_info() {
- info.kind.descr() == sym::declare_lint_pass
- } else {
- false
- }
-}
diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs
index 8cb5b1e..2b58627 100644
--- a/src/librustc/lint/mod.rs
+++ b/src/librustc/lint/mod.rs
@@ -885,21 +885,16 @@
/// This is used to test whether a lint should not even begin to figure out whether it should
/// be reported on the current node.
pub fn in_external_macro(sess: &Session, span: Span) -> bool {
- let info = match span.ctxt().outer_expn_info() {
- Some(info) => info,
- // no ExpnInfo means this span doesn't come from a macro
- None => return false,
- };
-
- match info.kind {
+ let expn_data = span.ctxt().outer_expn_data();
+ match expn_data.kind {
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
ExpnKind::Desugaring(_) => true, // well, it's "external"
ExpnKind::Macro(MacroKind::Bang, _) => {
- if info.def_site.is_dummy() {
+ if expn_data.def_site.is_dummy() {
// dummy span for the def_site means it's an external macro
return true;
}
- match sess.source_map().span_to_snippet(info.def_site) {
+ match sess.source_map().span_to_snippet(expn_data.def_site) {
Ok(code) => !code.starts_with("macro_rules"),
// no snippet = external macro or compiler-builtin expansion
Err(_) => true,
@@ -911,10 +906,8 @@
/// Returns whether `span` originates in a derive macro's expansion
pub fn in_derive_expansion(span: Span) -> bool {
- if let Some(info) = span.ctxt().outer_expn_info() {
- if let ExpnKind::Macro(MacroKind::Derive, _) = info.kind {
- return true;
- }
+ if let ExpnKind::Macro(MacroKind::Derive, _) = span.ctxt().outer_expn_data().kind {
+ return true;
}
false
}
diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs
index d37b236..de84fcd 100644
--- a/src/librustc/middle/cstore.rs
+++ b/src/librustc/middle/cstore.rs
@@ -178,8 +178,7 @@
-> Result<MetadataRef, String>;
}
-/// A store of Rust crates, through with their metadata
-/// can be accessed.
+/// A store of Rust crates, through which their metadata can be accessed.
///
/// Note that this trait should probably not be expanding today. All new
/// functionality should be driven through queries instead!
diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs
index 1e2ec08..11701a6 100644
--- a/src/librustc/mir/mod.rs
+++ b/src/librustc/mir/mod.rs
@@ -2197,7 +2197,6 @@
let ty = tcx.type_of(def_id).subst(tcx, substs);
Operand::Constant(box Constant {
span,
- ty,
user_ty: None,
literal: ty::Const::zero_sized(tcx, ty),
})
@@ -2476,7 +2475,6 @@
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, HashStable)]
pub struct Constant<'tcx> {
pub span: Span,
- pub ty: Ty<'tcx>,
/// Optional user-given type: for something like
/// `collect::<Vec<_>>`, this would be present and would
@@ -3385,12 +3383,11 @@
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
Constant {
span: self.span.clone(),
- ty: self.ty.fold_with(folder),
user_ty: self.user_ty.fold_with(folder),
literal: self.literal.fold_with(folder),
}
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
- self.ty.visit_with(visitor) || self.literal.visit_with(visitor)
+ self.literal.visit_with(visitor)
}
}
diff --git a/src/librustc/mir/tcx.rs b/src/librustc/mir/tcx.rs
index f888938..e9f7636 100644
--- a/src/librustc/mir/tcx.rs
+++ b/src/librustc/mir/tcx.rs
@@ -252,7 +252,7 @@
match self {
&Operand::Copy(ref l) |
&Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
- &Operand::Constant(ref c) => c.ty,
+ &Operand::Constant(ref c) => c.literal.ty,
}
}
}
diff --git a/src/librustc/mir/visit.rs b/src/librustc/mir/visit.rs
index ee4ecb6..2d16e7b 100644
--- a/src/librustc/mir/visit.rs
+++ b/src/librustc/mir/visit.rs
@@ -782,13 +782,11 @@
location: Location) {
let Constant {
span,
- ty,
user_ty,
literal,
} = constant;
self.visit_span(span);
- self.visit_ty(ty, TyContext::Location(location));
drop(user_ty); // no visit method for this
self.visit_const(literal, location);
}
diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs
index 3536b2a..8e3b910 100644
--- a/src/librustc/session/config.rs
+++ b/src/librustc/session/config.rs
@@ -395,7 +395,7 @@
output_types: OutputTypes [TRACKED],
search_paths: Vec<SearchPath> [UNTRACKED],
libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
- maybe_sysroot: Option<PathBuf> [TRACKED],
+ maybe_sysroot: Option<PathBuf> [UNTRACKED],
target_triple: TargetTriple [TRACKED],
diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs
index 83bd5c5..ba92e85 100644
--- a/src/librustc/traits/error_reporting.rs
+++ b/src/librustc/traits/error_reporting.rs
@@ -36,7 +36,7 @@
use std::fmt;
use syntax::ast;
use syntax::symbol::sym;
-use syntax_pos::{DUMMY_SP, Span, ExpnInfo, ExpnKind};
+use syntax_pos::{DUMMY_SP, Span, ExpnKind};
impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
pub fn report_fulfillment_errors(&self,
@@ -61,9 +61,9 @@
// We want to ignore desugarings here: spans are equivalent even
// if one is the result of a desugaring and the other is not.
let mut span = error.obligation.cause.span;
- if let Some(ExpnInfo { kind: ExpnKind::Desugaring(_), def_site, .. })
- = span.ctxt().outer_expn_info() {
- span = def_site;
+ let expn_data = span.ctxt().outer_expn_data();
+ if let ExpnKind::Desugaring(_) = expn_data.kind {
+ span = expn_data.call_site;
}
error_map.entry(span).or_default().push(
diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs
index 38263f2..72df45d 100644
--- a/src/librustc/traits/project.rs
+++ b/src/librustc/traits/project.rs
@@ -1417,7 +1417,7 @@
projection_ty: ty::ProjectionTy::from_ref_and_name(
tcx,
trait_ref,
- Ident::with_empty_ctxt(FN_OUTPUT_NAME),
+ Ident::with_dummy_span(FN_OUTPUT_NAME),
),
ty: ret_type
}
diff --git a/src/librustc/ty/query/on_disk_cache.rs b/src/librustc/ty/query/on_disk_cache.rs
index 00871a1cb..8bf0197 100644
--- a/src/librustc/ty/query/on_disk_cache.rs
+++ b/src/librustc/ty/query/on_disk_cache.rs
@@ -23,16 +23,16 @@
use syntax::ast::NodeId;
use syntax::source_map::{SourceMap, StableSourceFileId};
use syntax_pos::{BytePos, Span, DUMMY_SP, SourceFile};
-use syntax_pos::hygiene::{ExpnId, SyntaxContext, ExpnInfo};
+use syntax_pos::hygiene::{ExpnId, SyntaxContext, ExpnData};
const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
-const TAG_NO_EXPANSION_INFO: u8 = 0;
-const TAG_EXPANSION_INFO_SHORTHAND: u8 = 1;
-const TAG_EXPANSION_INFO_INLINE: u8 = 2;
+const TAG_NO_EXPN_DATA: u8 = 0;
+const TAG_EXPN_DATA_SHORTHAND: u8 = 1;
+const TAG_EXPN_DATA_INLINE: u8 = 2;
const TAG_VALID_SPAN: u8 = 0;
const TAG_INVALID_SPAN: u8 = 1;
@@ -58,7 +58,7 @@
// These two fields caches that are populated lazily during decoding.
file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
- synthetic_expansion_infos: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
+ synthetic_syntax_contexts: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
// A map from dep-node to the position of the cached query result in
// `serialized_data`.
@@ -135,7 +135,7 @@
current_diagnostics: Default::default(),
query_result_index: footer.query_result_index.into_iter().collect(),
prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
- synthetic_expansion_infos: Default::default(),
+ synthetic_syntax_contexts: Default::default(),
alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
}
}
@@ -151,7 +151,7 @@
current_diagnostics: Default::default(),
query_result_index: Default::default(),
prev_diagnostics_index: Default::default(),
- synthetic_expansion_infos: Default::default(),
+ synthetic_syntax_contexts: Default::default(),
alloc_decoding_state: AllocDecodingState::new(Vec::new()),
}
}
@@ -185,7 +185,7 @@
encoder,
type_shorthands: Default::default(),
predicate_shorthands: Default::default(),
- expn_info_shorthands: Default::default(),
+ expn_data_shorthands: Default::default(),
interpret_allocs: Default::default(),
interpret_allocs_inverse: Vec::new(),
source_map: CachingSourceMapView::new(tcx.sess.source_map()),
@@ -383,7 +383,7 @@
cnum_map: self.cnum_map.get(),
file_index_to_file: &self.file_index_to_file,
file_index_to_stable_id: &self.file_index_to_stable_id,
- synthetic_expansion_infos: &self.synthetic_expansion_infos,
+ synthetic_syntax_contexts: &self.synthetic_syntax_contexts,
alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
};
@@ -440,7 +440,7 @@
opaque: opaque::Decoder<'a>,
source_map: &'a SourceMap,
cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
- synthetic_expansion_infos: &'a Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
+ synthetic_syntax_contexts: &'a Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
alloc_decoding_session: AllocDecodingSession<'a>,
@@ -586,37 +586,37 @@
let lo = file_lo.lines[line_lo - 1] + col_lo;
let hi = lo + len;
- let expn_info_tag = u8::decode(self)?;
+ let expn_data_tag = u8::decode(self)?;
- // FIXME(mw): This method does not restore `InternalExpnData::parent` or
+ // FIXME(mw): This method does not restore `ExpnData::parent` or
// `SyntaxContextData::prev_ctxt` or `SyntaxContextData::opaque`. These things
// don't seem to be used after HIR lowering, so everything should be fine
// as long as incremental compilation does not kick in before that.
- let location = || Span::new(lo, hi, SyntaxContext::empty());
- let recover_from_expn_info = |this: &Self, expn_info, pos| {
- let span = location().fresh_expansion(ExpnId::root(), expn_info);
- this.synthetic_expansion_infos.borrow_mut().insert(pos, span.ctxt());
+ let location = || Span::with_root_ctxt(lo, hi);
+ let recover_from_expn_data = |this: &Self, expn_data, pos| {
+ let span = location().fresh_expansion(expn_data);
+ this.synthetic_syntax_contexts.borrow_mut().insert(pos, span.ctxt());
span
};
- Ok(match expn_info_tag {
- TAG_NO_EXPANSION_INFO => {
+ Ok(match expn_data_tag {
+ TAG_NO_EXPN_DATA => {
location()
}
- TAG_EXPANSION_INFO_INLINE => {
- let expn_info = Decodable::decode(self)?;
- recover_from_expn_info(
- self, expn_info, AbsoluteBytePos::new(self.opaque.position())
+ TAG_EXPN_DATA_INLINE => {
+ let expn_data = Decodable::decode(self)?;
+ recover_from_expn_data(
+ self, expn_data, AbsoluteBytePos::new(self.opaque.position())
)
}
- TAG_EXPANSION_INFO_SHORTHAND => {
+ TAG_EXPN_DATA_SHORTHAND => {
let pos = AbsoluteBytePos::decode(self)?;
- let cached_ctxt = self.synthetic_expansion_infos.borrow().get(&pos).cloned();
+ let cached_ctxt = self.synthetic_syntax_contexts.borrow().get(&pos).cloned();
if let Some(ctxt) = cached_ctxt {
Span::new(lo, hi, ctxt)
} else {
- let expn_info =
- self.with_position(pos.to_usize(), |this| ExpnInfo::decode(this))?;
- recover_from_expn_info(self, expn_info, pos)
+ let expn_data =
+ self.with_position(pos.to_usize(), |this| ExpnData::decode(this))?;
+ recover_from_expn_data(self, expn_data, pos)
}
}
_ => {
@@ -725,7 +725,7 @@
encoder: &'a mut E,
type_shorthands: FxHashMap<Ty<'tcx>, usize>,
predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
- expn_info_shorthands: FxHashMap<ExpnId, AbsoluteBytePos>,
+ expn_data_shorthands: FxHashMap<ExpnId, AbsoluteBytePos>,
interpret_allocs: FxHashMap<interpret::AllocId, usize>,
interpret_allocs_inverse: Vec<interpret::AllocId>,
source_map: CachingSourceMapView<'tcx>,
@@ -816,22 +816,18 @@
col_lo.encode(self)?;
len.encode(self)?;
- if span_data.ctxt == SyntaxContext::empty() {
- TAG_NO_EXPANSION_INFO.encode(self)
+ if span_data.ctxt == SyntaxContext::root() {
+ TAG_NO_EXPN_DATA.encode(self)
} else {
- let (expn_id, expn_info) = span_data.ctxt.outer_expn_with_info();
- if let Some(expn_info) = expn_info {
- if let Some(pos) = self.expn_info_shorthands.get(&expn_id).cloned() {
- TAG_EXPANSION_INFO_SHORTHAND.encode(self)?;
- pos.encode(self)
- } else {
- TAG_EXPANSION_INFO_INLINE.encode(self)?;
- let pos = AbsoluteBytePos::new(self.position());
- self.expn_info_shorthands.insert(expn_id, pos);
- expn_info.encode(self)
- }
+ let (expn_id, expn_data) = span_data.ctxt.outer_expn_with_data();
+ if let Some(pos) = self.expn_data_shorthands.get(&expn_id).cloned() {
+ TAG_EXPN_DATA_SHORTHAND.encode(self)?;
+ pos.encode(self)
} else {
- TAG_NO_EXPANSION_INFO.encode(self)
+ TAG_EXPN_DATA_INLINE.encode(self)?;
+ let pos = AbsoluteBytePos::new(self.position());
+ self.expn_data_shorthands.insert(expn_id, pos);
+ expn_data.encode(self)
}
}
}
diff --git a/src/librustc_codegen_llvm/asm.rs b/src/librustc_codegen_llvm/asm.rs
index 9763d52..b68ee2c 100644
--- a/src/librustc_codegen_llvm/asm.rs
+++ b/src/librustc_codegen_llvm/asm.rs
@@ -6,9 +6,9 @@
use rustc::hir;
use rustc_codegen_ssa::traits::*;
-
use rustc_codegen_ssa::mir::place::PlaceRef;
use rustc_codegen_ssa::mir::operand::OperandValue;
+use syntax_pos::Span;
use std::ffi::{CStr, CString};
use libc::{c_uint, c_char};
@@ -19,7 +19,8 @@
&mut self,
ia: &hir::InlineAsm,
outputs: Vec<PlaceRef<'tcx, &'ll Value>>,
- mut inputs: Vec<&'ll Value>
+ mut inputs: Vec<&'ll Value>,
+ span: Span,
) -> bool {
let mut ext_constraints = vec![];
let mut output_types = vec![];
@@ -102,7 +103,7 @@
let kind = llvm::LLVMGetMDKindIDInContext(self.llcx,
key.as_ptr() as *const c_char, key.len() as c_uint);
- let val: &'ll Value = self.const_i32(ia.ctxt.outer_expn().as_u32() as i32);
+ let val: &'ll Value = self.const_i32(span.ctxt().outer_expn().as_u32() as i32);
llvm::LLVMSetMetadata(r, kind,
llvm::LLVMMDNodeInContext(self.llcx, &val, 1));
diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs
index a9b8962..9483ffc 100644
--- a/src/librustc_codegen_llvm/intrinsic.rs
+++ b/src/librustc_codegen_llvm/intrinsic.rs
@@ -328,7 +328,7 @@
},
"ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
"bitreverse" | "add_with_overflow" | "sub_with_overflow" |
- "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
+ "mul_with_overflow" | "wrapping_add" | "wrapping_sub" | "wrapping_mul" |
"unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" |
"unchecked_add" | "unchecked_sub" | "unchecked_mul" | "exact_div" |
"rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
@@ -398,9 +398,9 @@
return;
},
- "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
- "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
- "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
+ "wrapping_add" => self.add(args[0].immediate(), args[1].immediate()),
+ "wrapping_sub" => self.sub(args[0].immediate(), args[1].immediate()),
+ "wrapping_mul" => self.mul(args[0].immediate(), args[1].immediate()),
"exact_div" =>
if signed {
self.exactsdiv(args[0].immediate(), args[1].immediate())
diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs
index c9e4663..eec0984 100644
--- a/src/librustc_codegen_ssa/back/write.rs
+++ b/src/librustc_codegen_ssa/back/write.rs
@@ -1775,10 +1775,7 @@
}
}
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
- match ExpnId::from_u32(cookie).expn_info() {
- Some(ei) => sess.span_err(ei.call_site, &msg),
- None => sess.err(&msg),
- }
+ sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
}
Ok(SharedEmitterMessage::AbortIfErrors) => {
sess.abort_if_errors();
diff --git a/src/librustc_codegen_ssa/mir/analyze.rs b/src/librustc_codegen_ssa/mir/analyze.rs
index cc0c733..e63f1b9 100644
--- a/src/librustc_codegen_ssa/mir/analyze.rs
+++ b/src/librustc_codegen_ssa/mir/analyze.rs
@@ -221,7 +221,7 @@
mir::TerminatorKind::Call {
func: mir::Operand::Constant(ref c),
ref args, ..
- } => match c.ty.sty {
+ } => match c.literal.ty.sty {
ty::FnDef(did, _) => Some((did, args)),
_ => None,
},
diff --git a/src/librustc_codegen_ssa/mir/block.rs b/src/librustc_codegen_ssa/mir/block.rs
index ce98979..dbce5ce 100644
--- a/src/librustc_codegen_ssa/mir/block.rs
+++ b/src/librustc_codegen_ssa/mir/block.rs
@@ -651,7 +651,7 @@
let (llval, ty) = self.simd_shuffle_indices(
&bx,
constant.span,
- constant.ty,
+ constant.literal.ty,
c,
);
return OperandRef {
diff --git a/src/librustc_codegen_ssa/mir/mod.rs b/src/librustc_codegen_ssa/mir/mod.rs
index e7517d6..32bcdeb 100644
--- a/src/librustc_codegen_ssa/mir/mod.rs
+++ b/src/librustc_codegen_ssa/mir/mod.rs
@@ -8,7 +8,7 @@
use crate::debuginfo::{self, VariableAccess, VariableKind, FunctionDebugContext};
use crate::traits::*;
-use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span};
+use syntax_pos::{DUMMY_SP, BytePos, Span};
use syntax::symbol::kw;
use std::iter;
@@ -120,7 +120,7 @@
// In order to have a good line stepping behavior in debugger, we overwrite debug
// locations of macro expansions with that of the outermost expansion site
// (unless the crate is being compiled with `-Z debug-macros`).
- if source_info.span.ctxt() == NO_EXPANSION ||
+ if !source_info.span.from_expansion() ||
self.cx.sess().opts.debugging_opts.debug_macros {
let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo());
(scope, source_info.span)
diff --git a/src/librustc_codegen_ssa/mir/operand.rs b/src/librustc_codegen_ssa/mir/operand.rs
index 5e5804b..254b73d 100644
--- a/src/librustc_codegen_ssa/mir/operand.rs
+++ b/src/librustc_codegen_ssa/mir/operand.rs
@@ -466,7 +466,6 @@
}
mir::Operand::Constant(ref constant) => {
- let ty = self.monomorphize(&constant.ty);
self.eval_mir_constant(constant)
.map(|c| OperandRef::from_const(bx, c))
.unwrap_or_else(|err| {
@@ -481,6 +480,7 @@
// the above error (or silence it under some conditions) will not cause UB
bx.abort();
// We've errored, so we don't have to produce working code.
+ let ty = self.monomorphize(&constant.literal.ty);
let layout = bx.cx().layout_of(ty);
bx.load_operand(PlaceRef::new_sized(
bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),
diff --git a/src/librustc_codegen_ssa/mir/statement.rs b/src/librustc_codegen_ssa/mir/statement.rs
index 3717be4..3617f3a 100644
--- a/src/librustc_codegen_ssa/mir/statement.rs
+++ b/src/librustc_codegen_ssa/mir/statement.rs
@@ -89,7 +89,12 @@
});
if input_vals.len() == asm.inputs.len() {
- let res = bx.codegen_inline_asm(&asm.asm, outputs, input_vals);
+ let res = bx.codegen_inline_asm(
+ &asm.asm,
+ outputs,
+ input_vals,
+ statement.source_info.span,
+ );
if !res {
span_err!(bx.sess(), statement.source_info.span, E0668,
"malformed inline assembly");
diff --git a/src/librustc_codegen_ssa/traits/asm.rs b/src/librustc_codegen_ssa/traits/asm.rs
index fd3c868..c9e1ed8 100644
--- a/src/librustc_codegen_ssa/traits/asm.rs
+++ b/src/librustc_codegen_ssa/traits/asm.rs
@@ -1,6 +1,7 @@
use super::BackendTypes;
use crate::mir::place::PlaceRef;
use rustc::hir::{GlobalAsm, InlineAsm};
+use syntax_pos::Span;
pub trait AsmBuilderMethods<'tcx>: BackendTypes {
/// Take an inline assembly expression and splat it out via LLVM
@@ -9,6 +10,7 @@
ia: &InlineAsm,
outputs: Vec<PlaceRef<'tcx, Self::Value>>,
inputs: Vec<Self::Value>,
+ span: Span,
) -> bool;
}
diff --git a/src/librustc_codegen_utils/Cargo.toml b/src/librustc_codegen_utils/Cargo.toml
index d93589e..89b50c5 100644
--- a/src/librustc_codegen_utils/Cargo.toml
+++ b/src/librustc_codegen_utils/Cargo.toml
@@ -13,7 +13,7 @@
flate2 = "1.0"
log = "0.4"
punycode = "0.4.0"
-rustc-demangle = "0.1.15"
+rustc-demangle = "0.1.16"
syntax = { path = "../libsyntax" }
syntax_pos = { path = "../libsyntax_pos" }
diff --git a/src/librustc_codegen_utils/symbol_names/v0.rs b/src/librustc_codegen_utils/symbol_names/v0.rs
index 47601da..8d6a1d7 100644
--- a/src/librustc_codegen_utils/symbol_names/v0.rs
+++ b/src/librustc_codegen_utils/symbol_names/v0.rs
@@ -198,10 +198,14 @@
let lifetimes = regions.into_iter().map(|br| {
match br {
- ty::BrAnon(i) => i + 1,
+ ty::BrAnon(i) => {
+ // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
+ assert_ne!(i, 0);
+ i - 1
+ },
_ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value),
}
- }).max().unwrap_or(0);
+ }).max().map_or(0, |max| max + 1);
self.push_opt_integer_62("G", lifetimes as u64);
lifetime_depths.end += lifetimes;
@@ -297,6 +301,10 @@
// Late-bound lifetimes use indices starting at 1,
// see `BinderLevel` for more details.
ty::ReLateBound(debruijn, ty::BrAnon(i)) => {
+ // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`.
+ assert_ne!(i, 0);
+ let i = i - 1;
+
let binder = &self.binders[self.binders.len() - 1 - debruijn.index()];
let depth = binder.lifetime_depths.start + i;
diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs
index e9d85a5..fdd0773 100644
--- a/src/librustc_driver/lib.rs
+++ b/src/librustc_driver/lib.rs
@@ -678,7 +678,7 @@
let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
let gated_cfg = GatedCfg::gate(&ast::MetaItem {
- path: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
+ path: ast::Path::from_ident(ast::Ident::with_dummy_span(name)),
node: ast::MetaItemKind::Word,
span: DUMMY_SP,
});
diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs
index f3e5241..4018a66 100644
--- a/src/librustc_errors/lib.rs
+++ b/src/librustc_errors/lib.rs
@@ -43,8 +43,7 @@
SourceFile,
FileName,
MultiSpan,
- Span,
- NO_EXPANSION};
+ Span};
/// Indicates the confidence in the correctness of a suggestion.
///
@@ -189,7 +188,7 @@
// Find the bounding span.
let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
- let bounding_span = Span::new(lo, hi, NO_EXPANSION);
+ let bounding_span = Span::with_root_ctxt(lo, hi);
let lines = cm.span_to_lines(bounding_span).unwrap();
assert!(!lines.lines.is_empty());
diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs
index 47b4e7c..8216008 100644
--- a/src/librustc_lint/builtin.rs
+++ b/src/librustc_lint/builtin.rs
@@ -42,7 +42,7 @@
use syntax::edition::Edition;
use syntax::feature_gate::{self, AttributeGate, AttributeType};
use syntax::feature_gate::{Stability, deprecated_attributes};
-use syntax_pos::{BytePos, Span, SyntaxContext};
+use syntax_pos::{BytePos, Span};
use syntax::symbol::{Symbol, kw, sym};
use syntax::errors::{Applicability, DiagnosticBuilder};
use syntax::print::pprust::expr_to_string;
@@ -78,7 +78,7 @@
if let ast::ExprKind::While(cond, ..) = &e.node {
if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).node {
if let ast::LitKind::Bool(true) = lit.node {
- if lit.span.ctxt() == SyntaxContext::empty() {
+ if !lit.span.from_expansion() {
let msg = "denote infinite loops with `loop { ... }`";
let condition_span = cx.sess.source_map().def_span(e.span);
cx.struct_span_lint(WHILE_TRUE, condition_span, msg)
@@ -167,7 +167,7 @@
if fieldpat.is_shorthand {
continue;
}
- if fieldpat.span.ctxt().outer_expn_info().is_some() {
+ if fieldpat.span.from_expansion() {
// Don't lint if this is a macro expansion: macro authors
// shouldn't have to worry about this kind of style issue
// (Issue #49588)
@@ -1012,7 +1012,7 @@
let mut applicability = Applicability::MachineApplicable;
match vis.node {
hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => {
- if span.ctxt().outer_expn_info().is_some() {
+ if span.from_expansion() {
applicability = Applicability::MaybeIncorrect;
}
let def_span = cx.tcx.sess.source_map().def_span(span);
diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs
index 6a3dfdb..90e4677 100644
--- a/src/librustc_lint/unused.rs
+++ b/src/librustc_lint/unused.rs
@@ -517,9 +517,8 @@
// trigger in situations that macro authors shouldn't have to care about, e.g.,
// when a parenthesized token tree matched in one macro expansion is matched as
// an expression in another and used as a fn/method argument (Issue #47775)
- if e.span.ctxt().outer_expn_info()
- .map_or(false, |info| info.call_site.ctxt().outer_expn_info().is_some()) {
- return;
+ if e.span.ctxt().outer_expn_data().call_site.from_expansion() {
+ return;
}
let msg = format!("{} argument", call_kind);
for arg in args_to_check {
diff --git a/src/librustc_llvm/build.rs b/src/librustc_llvm/build.rs
index 16cdbb7..40ddd65 100644
--- a/src/librustc_llvm/build.rs
+++ b/src/librustc_llvm/build.rs
@@ -151,6 +151,10 @@
cfg.define("LLVM_RUSTLLVM", None);
}
+ if env::var_os("LLVM_NDEBUG").is_some() {
+ cfg.define("NDEBUG", None);
+ }
+
build_helper::rerun_if_changed_anything_in_dir(Path::new("../rustllvm"));
cfg.file("../rustllvm/PassWrapper.cpp")
.file("../rustllvm/RustWrapper.cpp")
@@ -250,8 +254,11 @@
let llvm_use_libcxx = env::var_os("LLVM_USE_LIBCXX");
let stdcppname = if target.contains("openbsd") {
- // llvm-config on OpenBSD doesn't mention stdlib=libc++
- "c++"
+ if target.contains("sparc64") {
+ "estdc++"
+ } else {
+ "c++"
+ }
} else if target.contains("freebsd") {
"c++"
} else if target.contains("darwin") {
diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs
index 5d8fabc..4ac0a5b9 100644
--- a/src/librustc_metadata/cstore.rs
+++ b/src/librustc_metadata/cstore.rs
@@ -70,7 +70,7 @@
// whichever `TyCtxt` is being used to decode those values.
pub root: schema::CrateRoot<'static>,
- /// For each public item in this crate, we encode a key. When the
+ /// For each definition in this crate, we encode a key. When the
/// crate is loaded, we read all the keys and put them in this
/// hashmap, which gives the reverse mapping. This allows us to
/// quickly retrace a `DefPath`, which is needed for incremental
diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs
index ee1175e..b46758a 100644
--- a/src/librustc_metadata/cstore_impl.rs
+++ b/src/librustc_metadata/cstore_impl.rs
@@ -35,7 +35,7 @@
use syntax::parse::source_file_to_stream;
use syntax::parse::parser::emit_unclosed_delims;
use syntax::symbol::{Symbol, sym};
-use syntax_pos::{Span, NO_EXPANSION, FileName};
+use syntax_pos::{Span, FileName};
use rustc_data_structures::bit_set::BitSet;
macro_rules! provide {
@@ -443,7 +443,7 @@
let source_name = FileName::Macros(macro_full_name);
let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
- let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
+ let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
emit_unclosed_delims(&mut errors, &sess.diagnostic());
diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs
index 935187d..772b2d3 100644
--- a/src/librustc_metadata/decoder.rs
+++ b/src/librustc_metadata/decoder.rs
@@ -32,7 +32,7 @@
use syntax::symbol::{Symbol, sym};
use syntax::ext::base::{MacroKind, SyntaxExtension};
use syntax::ext::hygiene::ExpnId;
-use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
+use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP};
use log::debug;
pub struct DecodeContext<'a, 'tcx> {
@@ -344,7 +344,15 @@
let hi = (hi + source_file.translated_source_file.start_pos)
- source_file.original_start_pos;
- Ok(Span::new(lo, hi, NO_EXPANSION))
+ Ok(Span::with_root_ctxt(lo, hi))
+ }
+}
+
+impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
+ fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
+ // FIXME(jseyfried): intercrate hygiene
+
+ Ok(Ident::with_dummy_span(Symbol::decode(self)?))
}
}
@@ -569,7 +577,7 @@
ty::VariantDef::new(
tcx,
- Ident::with_empty_ctxt(self.item_name(index)),
+ Ident::with_dummy_span(self.item_name(index)),
variant_did,
ctor_did,
data.discr,
@@ -577,7 +585,7 @@
let f = self.entry(index);
ty::FieldDef {
did: self.local_def_id(index),
- ident: Ident::with_empty_ctxt(self.item_name(index)),
+ ident: Ident::with_dummy_span(self.item_name(index)),
vis: f.visibility.decode(self)
}
}).collect(),
@@ -741,7 +749,7 @@
DefKind::Macro(ext.macro_kind()),
self.local_def_id(DefIndex::from_proc_macro_index(id)),
);
- let ident = Ident::with_empty_ctxt(name);
+ let ident = Ident::with_dummy_span(name);
callback(def::Export {
ident: ident,
res: res,
@@ -783,7 +791,7 @@
if let Some(kind) = self.def_kind(child_index) {
callback(def::Export {
res: Res::Def(kind, self.local_def_id(child_index)),
- ident: Ident::with_empty_ctxt(self.item_name(child_index)),
+ ident: Ident::with_dummy_span(self.item_name(child_index)),
vis: self.get_visibility(child_index),
span: self.entry(child_index).span.decode((self, sess)),
});
diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs
index fb675d7..e2de055 100644
--- a/src/librustc_metadata/encoder.rs
+++ b/src/librustc_metadata/encoder.rs
@@ -31,7 +31,7 @@
use syntax::ast;
use syntax::attr;
use syntax::source_map::Spanned;
-use syntax::symbol::{kw, sym};
+use syntax::symbol::{kw, sym, Ident};
use syntax_pos::{self, FileName, SourceFile, Span};
use log::{debug, trace};
@@ -173,6 +173,13 @@
}
}
+impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
+ fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
+ // FIXME(jseyfried): intercrate hygiene
+ ident.name.encode(self)
+ }
+}
+
impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
#[inline]
fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs
index 70d6c15..9ff0c6c 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs
@@ -272,12 +272,11 @@
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
self.super_constant(constant, location);
- self.sanitize_constant(constant, location);
- self.sanitize_type(constant, constant.ty);
+ self.sanitize_type(constant, constant.literal.ty);
if let Some(annotation_index) = constant.user_ty {
if let Err(terr) = self.cx.relate_type_and_user_type(
- constant.ty,
+ constant.literal.ty,
ty::Variance::Invariant,
&UserTypeProjection { base: annotation_index, projs: vec![], },
location.to_locations(),
@@ -289,7 +288,7 @@
constant,
"bad constant user type {:?} vs {:?}: {:?}",
annotation,
- constant.ty,
+ constant.literal.ty,
terr,
);
}
@@ -299,7 +298,7 @@
location.to_locations(),
ConstraintCategory::Boring,
self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
- constant.ty, def_id, UserSubsts { substs, user_self_ty: None },
+ constant.literal.ty, def_id, UserSubsts { substs, user_self_ty: None },
)),
) {
span_mirbug!(
@@ -403,41 +402,6 @@
}
}
- /// Checks that the constant's `ty` field matches up with what would be
- /// expected from its literal. Unevaluated constants and well-formed
- /// constraints are checked by `visit_constant`.
- fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
- debug!(
- "sanitize_constant(constant={:?}, location={:?})",
- constant, location
- );
-
- let literal = constant.literal;
-
- if let ConstValue::Unevaluated(..) = literal.val {
- return;
- }
-
- debug!("sanitize_constant: expected_ty={:?}", literal.ty);
-
- if let Err(terr) = self.cx.eq_types(
- literal.ty,
- constant.ty,
- location.to_locations(),
- ConstraintCategory::Boring,
- ) {
- span_mirbug!(
- self,
- constant,
- "constant {:?} should have type {:?} but has {:?} ({:?})",
- constant,
- literal.ty,
- constant.ty,
- terr,
- );
- }
- }
-
/// Checks that the types internal to the `place` match up with
/// what would be expected.
fn sanitize_place(
diff --git a/src/librustc_mir/build/expr/as_constant.rs b/src/librustc_mir/build/expr/as_constant.rs
index 5197981..39bdc87 100644
--- a/src/librustc_mir/build/expr/as_constant.rs
+++ b/src/librustc_mir/build/expr/as_constant.rs
@@ -38,9 +38,9 @@
inferred_ty: ty,
})
});
+ assert_eq!(literal.ty, ty);
Constant {
span,
- ty,
user_ty,
literal,
}
diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs
index ec061e7..1a186fa 100644
--- a/src/librustc_mir/build/expr/as_rvalue.rs
+++ b/src/librustc_mir/build/expr/as_rvalue.rs
@@ -591,7 +591,7 @@
let n = (!0u128) >> (128 - bits);
let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
- self.literal_operand(span, ty, literal)
+ self.literal_operand(span, literal)
}
// Helper to get the minimum value of the appropriate type
@@ -602,6 +602,6 @@
let n = 1 << (bits - 1);
let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
- self.literal_operand(span, ty, literal)
+ self.literal_operand(span, literal)
}
}
diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs
index 02ab53f..889861b 100644
--- a/src/librustc_mir/build/expr/into.rs
+++ b/src/librustc_mir/build/expr/into.rs
@@ -114,7 +114,6 @@
destination,
Constant {
span: expr_span,
- ty: this.hir.bool_ty(),
user_ty: None,
literal: this.hir.true_literal(),
},
@@ -126,7 +125,6 @@
destination,
Constant {
span: expr_span,
- ty: this.hir.bool_ty(),
user_ty: None,
literal: this.hir.false_literal(),
},
diff --git a/src/librustc_mir/build/matches/simplify.rs b/src/librustc_mir/build/matches/simplify.rs
index d9b748f..3473155 100644
--- a/src/librustc_mir/build/matches/simplify.rs
+++ b/src/librustc_mir/build/matches/simplify.rs
@@ -108,8 +108,8 @@
Err(match_pair)
}
- PatternKind::Range(PatternRange { lo, hi, ty, end }) => {
- let (range, bias) = match ty.sty {
+ PatternKind::Range(PatternRange { lo, hi, end }) => {
+ let (range, bias) = match lo.ty.sty {
ty::Char => {
(Some(('\u{0000}' as u128, '\u{10FFFF}' as u128, Size::from_bits(32))), 0)
}
diff --git a/src/librustc_mir/build/matches/test.rs b/src/librustc_mir/build/matches/test.rs
index 1c93abd..65e92d4 100644
--- a/src/librustc_mir/build/matches/test.rs
+++ b/src/librustc_mir/build/matches/test.rs
@@ -63,7 +63,8 @@
}
PatternKind::Range(range) => {
- assert!(range.ty == match_pair.pattern.ty);
+ assert_eq!(range.lo.ty, match_pair.pattern.ty);
+ assert_eq!(range.hi.ty, match_pair.pattern.ty);
Test {
span: match_pair.pattern.span,
kind: TestKind::Range(range),
@@ -270,8 +271,9 @@
);
} else {
if let [success, fail] = *make_target_blocks(self) {
+ assert_eq!(value.ty, ty);
+ let expect = self.literal_operand(test.span, value);
let val = Operand::Copy(place.clone());
- let expect = self.literal_operand(test.span, ty, value);
self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
} else {
bug!("`TestKind::Eq` should have two target blocks");
@@ -279,13 +281,13 @@
}
}
- TestKind::Range(PatternRange { ref lo, ref hi, ty, ref end }) => {
+ TestKind::Range(PatternRange { ref lo, ref hi, ref end }) => {
let lower_bound_success = self.cfg.start_new_block();
let target_blocks = make_target_blocks(self);
// Test `val` by computing `lo <= val && val <= hi`, using primitive comparisons.
- let lo = self.literal_operand(test.span, ty, lo);
- let hi = self.literal_operand(test.span, ty, hi);
+ let lo = self.literal_operand(test.span, lo);
+ let hi = self.literal_operand(test.span, hi);
let val = Operand::Copy(place.clone());
if let [success, fail] = *target_blocks {
@@ -387,7 +389,7 @@
) {
use rustc::middle::lang_items::EqTraitLangItem;
- let mut expect = self.literal_operand(source_info.span, value.ty, value);
+ let mut expect = self.literal_operand(source_info.span, value);
let mut val = Operand::Copy(place.clone());
// If we're using `b"..."` as a pattern, we need to insert an
@@ -440,7 +442,7 @@
};
let eq_def_id = self.hir.tcx().require_lang_item(EqTraitLangItem);
- let (mty, method) = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
+ let method = self.hir.trait_method(eq_def_id, sym::eq, deref_ty, &[deref_ty.into()]);
let bool_ty = self.hir.bool_ty();
let eq_result = self.temp(bool_ty, source_info.span);
@@ -449,7 +451,6 @@
self.cfg.terminate(block, source_info, TerminatorKind::Call {
func: Operand::Constant(box Constant {
span: source_info.span,
- ty: mty,
// FIXME(#54571): This constant comes from user input (a
// constant in a pattern). Are there forms where users can add
@@ -656,8 +657,9 @@
let tcx = self.hir.tcx();
- let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test.ty)?;
- let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test.ty)?;
+ let test_ty = test.lo.ty;
+ let lo = compare_const_vals(tcx, test.lo, pat.hi, self.hir.param_env, test_ty)?;
+ let hi = compare_const_vals(tcx, test.hi, pat.lo, self.hir.param_env, test_ty)?;
match (test.end, pat.end, lo, hi) {
// pat < test
@@ -774,8 +776,8 @@
let tcx = self.hir.tcx();
- let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.ty)?;
- let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.ty)?;
+ let a = compare_const_vals(tcx, range.lo, value, self.hir.param_env, range.lo.ty)?;
+ let b = compare_const_vals(tcx, value, range.hi, self.hir.param_env, range.lo.ty)?;
match (b, range.end) {
(Less, _) |
diff --git a/src/librustc_mir/build/misc.rs b/src/librustc_mir/build/misc.rs
index 56025ee..d038310 100644
--- a/src/librustc_mir/build/misc.rs
+++ b/src/librustc_mir/build/misc.rs
@@ -26,12 +26,10 @@
/// without any user type annotation.
pub fn literal_operand(&mut self,
span: Span,
- ty: Ty<'tcx>,
literal: &'tcx ty::Const<'tcx>)
-> Operand<'tcx> {
let constant = box Constant {
span,
- ty,
user_ty: None,
literal,
};
@@ -47,7 +45,7 @@
pub fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = ty::Const::from_bits(self.hir.tcx(), 0, ty::ParamEnv::empty().and(ty));
- self.literal_operand(span, ty, literal)
+ self.literal_operand(span, literal)
}
pub fn push_usize(&mut self,
@@ -61,7 +59,6 @@
block, source_info, &temp,
Constant {
span: source_info.span,
- ty: self.hir.usize_ty(),
user_ty: None,
literal: self.hir.usize_literal(value),
});
diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs
index 1c6a743..a33d720 100644
--- a/src/librustc_mir/hair/cx/expr.rs
+++ b/src/librustc_mir/hair/cx/expr.rs
@@ -927,7 +927,7 @@
ExprKind::Literal {
literal: cx.tcx.mk_const(ty::Const {
val: ConstValue::Unevaluated(def_id, substs),
- ty: cx.tcx.type_of(def_id),
+ ty: cx.tables().node_type(expr.hir_id),
}),
user_ty,
}
diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs
index 3d9349d..740dc20 100644
--- a/src/librustc_mir/hair/cx/mod.rs
+++ b/src/librustc_mir/hair/cx/mod.rs
@@ -170,13 +170,13 @@
method_name: Symbol,
self_ty: Ty<'tcx>,
params: &[Kind<'tcx>])
- -> (Ty<'tcx>, &'tcx ty::Const<'tcx>) {
+ -> &'tcx ty::Const<'tcx> {
let substs = self.tcx.mk_substs_trait(self_ty, params);
for item in self.tcx.associated_items(trait_def_id) {
if item.kind == ty::AssocKind::Method && item.ident.name == method_name {
let method_ty = self.tcx.type_of(item.def_id);
let method_ty = method_ty.subst(self.tcx, substs);
- return (method_ty, ty::Const::zero_sized(self.tcx, method_ty));
+ return ty::Const::zero_sized(self.tcx, method_ty);
}
}
diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs
index 8a3d904..1833ee3 100644
--- a/src/librustc_mir/hair/pattern/_match.rs
+++ b/src/librustc_mir/hair/pattern/_match.rs
@@ -609,7 +609,6 @@
ConstantRange(lo, hi, ty, end) => PatternKind::Range(PatternRange {
lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
- ty,
end,
}),
_ => PatternKind::Wild,
@@ -880,10 +879,10 @@
let range = loop {
match pat.kind {
box PatternKind::Constant { value } => break ConstantValue(value),
- box PatternKind::Range(PatternRange { lo, hi, ty, end }) => break ConstantRange(
- lo.eval_bits(tcx, param_env, ty),
- hi.eval_bits(tcx, param_env, ty),
- ty,
+ box PatternKind::Range(PatternRange { lo, hi, end }) => break ConstantRange(
+ lo.eval_bits(tcx, param_env, lo.ty),
+ hi.eval_bits(tcx, param_env, hi.ty),
+ lo.ty,
end,
),
box PatternKind::AscribeUserType { ref subpattern, .. } => {
@@ -1339,11 +1338,11 @@
Some(vec![Variant(adt_def.variants[variant_index].def_id)])
}
PatternKind::Constant { value } => Some(vec![ConstantValue(value)]),
- PatternKind::Range(PatternRange { lo, hi, ty, end }) =>
+ PatternKind::Range(PatternRange { lo, hi, end }) =>
Some(vec![ConstantRange(
- lo.eval_bits(cx.tcx, cx.param_env, ty),
- hi.eval_bits(cx.tcx, cx.param_env, ty),
- ty,
+ lo.eval_bits(cx.tcx, cx.param_env, lo.ty),
+ hi.eval_bits(cx.tcx, cx.param_env, hi.ty),
+ lo.ty,
end,
)]),
PatternKind::Array { .. } => match pcx.ty.sty {
@@ -1656,7 +1655,7 @@
) -> Result<bool, ErrorReported> {
let (from, to, end, ty) = match pat.kind {
box PatternKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
- box PatternKind::Range(PatternRange { lo, hi, end, ty }) => (lo, hi, end, ty),
+ box PatternKind::Range(PatternRange { lo, hi, end }) => (lo, hi, end, lo.ty),
_ => bug!("`constructor_covered_by_range` called with {:?}", pat),
};
trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs
index 1022315..bebb071 100644
--- a/src/librustc_mir/hair/pattern/mod.rs
+++ b/src/librustc_mir/hair/pattern/mod.rs
@@ -181,7 +181,6 @@
pub struct PatternRange<'tcx> {
pub lo: &'tcx ty::Const<'tcx>,
pub hi: &'tcx ty::Const<'tcx>,
- pub ty: Ty<'tcx>,
pub end: RangeEnd,
}
@@ -296,7 +295,7 @@
PatternKind::Constant { value } => {
write!(f, "{}", value)
}
- PatternKind::Range(PatternRange { lo, hi, ty: _, end }) => {
+ PatternKind::Range(PatternRange { lo, hi, end }) => {
write!(f, "{}", lo)?;
match end {
RangeEnd::Included => write!(f, "..=")?,
@@ -442,6 +441,8 @@
let mut kind = match (lo, hi) {
(PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => {
+ assert_eq!(lo.ty, ty);
+ assert_eq!(hi.ty, ty);
let cmp = compare_const_vals(
self.tcx,
lo,
@@ -451,7 +452,7 @@
);
match (end, cmp) {
(RangeEnd::Excluded, Some(Ordering::Less)) =>
- PatternKind::Range(PatternRange { lo, hi, ty, end }),
+ PatternKind::Range(PatternRange { lo, hi, end }),
(RangeEnd::Excluded, _) => {
span_err!(
self.tcx.sess,
@@ -465,7 +466,7 @@
PatternKind::Constant { value: lo }
}
(RangeEnd::Included, Some(Ordering::Less)) => {
- PatternKind::Range(PatternRange { lo, hi, ty, end })
+ PatternKind::Range(PatternRange { lo, hi, end })
}
(RangeEnd::Included, _) => {
let mut err = struct_span_err!(
@@ -1416,17 +1417,7 @@
} => PatternKind::Constant {
value,
},
- PatternKind::Range(PatternRange {
- lo,
- hi,
- ty,
- end,
- }) => PatternKind::Range(PatternRange {
- lo,
- hi,
- ty: ty.fold_with(folder),
- end,
- }),
+ PatternKind::Range(range) => PatternKind::Range(range),
PatternKind::Slice {
ref prefix,
ref slice,
diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs
index 89c5be1..ee105fe 100644
--- a/src/librustc_mir/interpret/intrinsics.rs
+++ b/src/librustc_mir/interpret/intrinsics.rs
@@ -110,18 +110,18 @@
};
self.write_scalar(out_val, dest)?;
}
- | "overflowing_add"
- | "overflowing_sub"
- | "overflowing_mul"
+ | "wrapping_add"
+ | "wrapping_sub"
+ | "wrapping_mul"
| "add_with_overflow"
| "sub_with_overflow"
| "mul_with_overflow" => {
let lhs = self.read_immediate(args[0])?;
let rhs = self.read_immediate(args[1])?;
let (bin_op, ignore_overflow) = match intrinsic_name {
- "overflowing_add" => (BinOp::Add, true),
- "overflowing_sub" => (BinOp::Sub, true),
- "overflowing_mul" => (BinOp::Mul, true),
+ "wrapping_add" => (BinOp::Add, true),
+ "wrapping_sub" => (BinOp::Sub, true),
+ "wrapping_mul" => (BinOp::Mul, true),
"add_with_overflow" => (BinOp::Add, false),
"sub_with_overflow" => (BinOp::Sub, false),
"mul_with_overflow" => (BinOp::Mul, false),
diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs
index 33447eba..063e779 100644
--- a/src/librustc_mir/shim.rs
+++ b/src/librustc_mir/shim.rs
@@ -445,7 +445,6 @@
let func_ty = tcx.mk_fn_def(self.def_id, substs);
let func = Operand::Constant(box Constant {
span: self.span,
- ty: func_ty,
user_ty: None,
literal: ty::Const::zero_sized(tcx, func_ty),
});
@@ -505,7 +504,6 @@
fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
box Constant {
span: self.span,
- ty: self.tcx.types.usize,
user_ty: None,
literal: ty::Const::from_usize(self.tcx, value),
}
@@ -745,7 +743,6 @@
let ty = tcx.type_of(def_id);
(Operand::Constant(box Constant {
span,
- ty,
user_ty: None,
literal: ty::Const::zero_sized(tcx, ty),
}),
diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs
index 38d26d0..c3c432d 100644
--- a/src/librustc_mir/transform/const_prop.rs
+++ b/src/librustc_mir/transform/const_prop.rs
@@ -539,7 +539,6 @@
Operand::Constant(Box::new(
Constant {
span,
- ty,
user_ty: None,
literal: self.tcx.mk_const(*ty::Const::from_scalar(
self.tcx,
diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs
index 0a021d9..4480d1e 100644
--- a/src/librustc_mir/transform/elaborate_drops.rs
+++ b/src/librustc_mir/transform/elaborate_drops.rs
@@ -527,7 +527,6 @@
fn constant_bool(&self, span: Span, val: bool) -> Rvalue<'tcx> {
Rvalue::Use(Operand::Constant(Box::new(Constant {
span,
- ty: self.tcx.types.bool,
user_ty: None,
literal: ty::Const::from_bool(self.tcx, val),
})))
diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs
index 94bb70e..f694188 100644
--- a/src/librustc_mir/transform/generator.rs
+++ b/src/librustc_mir/transform/generator.rs
@@ -975,7 +975,6 @@
let term = TerminatorKind::Assert {
cond: Operand::Constant(box Constant {
span: body.span,
- ty: tcx.types.bool,
user_ty: None,
literal: ty::Const::from_bool(tcx, false),
}),
diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs
index 40cb1fb..bc7bd39 100644
--- a/src/librustc_mir/transform/inline.rs
+++ b/src/librustc_mir/transform/inline.rs
@@ -328,7 +328,7 @@
}
TerminatorKind::Call {func: Operand::Constant(ref f), .. } => {
- if let ty::FnDef(def_id, _) = f.ty.sty {
+ if let ty::FnDef(def_id, _) = f.literal.ty.sty {
// Don't give intrinsics the extra penalty for calls
let f = tcx.fn_sig(def_id);
if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
diff --git a/src/librustc_mir/transform/instcombine.rs b/src/librustc_mir/transform/instcombine.rs
index 5542926..b2d063a 100644
--- a/src/librustc_mir/transform/instcombine.rs
+++ b/src/librustc_mir/transform/instcombine.rs
@@ -97,8 +97,7 @@
let place_ty = place.ty(&self.body.local_decls, self.tcx).ty;
if let ty::Array(_, len) = place_ty.sty {
let span = self.body.source_info(location).span;
- let ty = self.tcx.types.usize;
- let constant = Constant { span, ty, literal: len, user_ty: None };
+ let constant = Constant { span, literal: len, user_ty: None };
self.optimizations.arrays_lengths.insert(location, constant);
}
}
diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs
index dcfc809..649cccc 100644
--- a/src/librustc_mir/transform/qualify_consts.rs
+++ b/src/librustc_mir/transform/qualify_consts.rs
@@ -249,7 +249,7 @@
if let ConstValue::Unevaluated(def_id, _) = constant.literal.val {
// Don't peek inside trait associated constants.
if cx.tcx.trait_of_item(def_id).is_some() {
- Self::in_any_value_of_ty(cx, constant.ty).unwrap_or(false)
+ Self::in_any_value_of_ty(cx, constant.literal.ty).unwrap_or(false)
} else {
let (bits, _) = cx.tcx.at(constant.span).mir_const_qualif(def_id);
@@ -258,7 +258,7 @@
// Just in case the type is more specific than
// the definition, e.g., impl associated const
// with type parameters, take it into account.
- qualif && Self::mask_for_ty(cx, constant.ty)
+ qualif && Self::mask_for_ty(cx, constant.literal.ty)
}
} else {
false
@@ -537,9 +537,9 @@
| "cttz_nonzero"
| "ctlz"
| "ctlz_nonzero"
- | "overflowing_add"
- | "overflowing_sub"
- | "overflowing_mul"
+ | "wrapping_add"
+ | "wrapping_sub"
+ | "wrapping_mul"
| "unchecked_shl"
| "unchecked_shr"
| "rotate_left"
diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs
index b84bc31..334d0ce 100644
--- a/src/librustc_mir/transform/qualify_min_const_fn.rs
+++ b/src/librustc_mir/transform/qualify_min_const_fn.rs
@@ -379,9 +379,9 @@
| "add_with_overflow" // ~> .overflowing_add
| "sub_with_overflow" // ~> .overflowing_sub
| "mul_with_overflow" // ~> .overflowing_mul
- | "overflowing_add" // ~> .wrapping_add
- | "overflowing_sub" // ~> .wrapping_sub
- | "overflowing_mul" // ~> .wrapping_mul
+ | "wrapping_add" // ~> .wrapping_add
+ | "wrapping_sub" // ~> .wrapping_sub
+ | "wrapping_mul" // ~> .wrapping_mul
| "saturating_add" // ~> .saturating_add
| "saturating_sub" // ~> .saturating_sub
| "unchecked_shl" // ~> .wrapping_shl
diff --git a/src/librustc_mir/transform/rustc_peek.rs b/src/librustc_mir/transform/rustc_peek.rs
index 7fe8480..598de3a 100644
--- a/src/librustc_mir/transform/rustc_peek.rs
+++ b/src/librustc_mir/transform/rustc_peek.rs
@@ -224,7 +224,7 @@
if let Some(mir::Terminator { ref kind, source_info, .. }) = *terminator {
if let mir::TerminatorKind::Call { func: ref oper, ref args, .. } = *kind {
if let mir::Operand::Constant(ref func) = *oper {
- if let ty::FnDef(def_id, _) = func.ty.sty {
+ if let ty::FnDef(def_id, _) = func.literal.ty.sty {
let abi = tcx.fn_sig(def_id).abi();
let name = tcx.item_name(def_id);
if abi == Abi::RustIntrinsic && name == sym::rustc_peek {
diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs
index 52fd645..c5561a1 100644
--- a/src/librustc_mir/util/elaborate_drops.rs
+++ b/src/librustc_mir/util/elaborate_drops.rs
@@ -970,7 +970,6 @@
fn constant_usize(&self, val: u16) -> Operand<'tcx> {
Operand::Constant(box Constant {
span: self.source_info.span,
- ty: self.tcx().types.usize,
user_ty: None,
literal: ty::Const::from_usize(self.tcx(), val.into()),
})
diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs
index 68880fc..ac27019 100644
--- a/src/librustc_mir/util/pretty.rs
+++ b/src/librustc_mir/util/pretty.rs
@@ -397,10 +397,9 @@
impl Visitor<'tcx> for ExtraComments<'tcx> {
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
self.super_constant(constant, location);
- let Constant { span, ty, user_ty, literal } = constant;
+ let Constant { span, user_ty, literal } = constant;
self.push("mir::Constant");
self.push(&format!("+ span: {:?}", span));
- self.push(&format!("+ ty: {:?}", ty));
if let Some(user_ty) = user_ty {
self.push(&format!("+ user_ty: {:?}", user_ty));
}
diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs
index 0a32b0c..1510d74 100644
--- a/src/librustc_resolve/build_reduced_graph.rs
+++ b/src/librustc_resolve/build_reduced_graph.rs
@@ -1,9 +1,11 @@
-//! Reduced graph building.
+//! After we obtain a fresh AST fragment from a macro, code in this module helps to integrate
+//! that fragment into the module structures that are already partially built.
//!
-//! Here we build the "reduced graph": the graph of the module tree without
-//! any imports resolved.
+//! Items from the fragment are placed into modules,
+//! unexpanded macros in the fragment are visited and registered.
+//! Imports are also considered items and placed into modules here, but not resolved yet.
-use crate::macros::{InvocationData, LegacyBinding, LegacyScope};
+use crate::macros::{LegacyBinding, LegacyScope};
use crate::resolve_imports::ImportDirective;
use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleImport};
use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
@@ -14,6 +16,7 @@
use rustc::bug;
use rustc::hir::def::{self, *};
use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
+use rustc::hir::map::DefCollector;
use rustc::ty;
use rustc::middle::cstore::CrateStore;
use rustc_metadata::cstore::LoadedMacro;
@@ -30,6 +33,7 @@
use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
use syntax::ast::{MetaItemKind, StmtKind, TraitItem, TraitItemKind, Variant};
use syntax::ext::base::{MacroKind, SyntaxExtension};
+use syntax::ext::expand::AstFragment;
use syntax::ext::hygiene::ExpnId;
use syntax::feature_gate::is_builtin_attr;
use syntax::parse::token::{self, Token};
@@ -67,7 +71,7 @@
}
}
-pub(crate) struct IsMacroExport;
+struct IsMacroExport;
impl<'a> ToNameBinding<'a> for (Res, ty::Visibility, Span, ExpnId, IsMacroExport) {
fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
@@ -84,7 +88,7 @@
impl<'a> Resolver<'a> {
/// Defines `name` in namespace `ns` of module `parent` to be `def` if it is not yet defined;
/// otherwise, reports an error.
- pub fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
+ crate fn define<T>(&mut self, parent: Module<'a>, ident: Ident, ns: Namespace, def: T)
where T: ToNameBinding<'a>,
{
let binding = def.to_name_binding(self.arenas);
@@ -93,7 +97,7 @@
}
}
- pub fn get_module(&mut self, def_id: DefId) -> Module<'a> {
+ crate fn get_module(&mut self, def_id: DefId) -> Module<'a> {
if def_id.krate == LOCAL_CRATE {
return self.module_map[&def_id]
}
@@ -119,7 +123,7 @@
module
}
- pub fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
+ crate fn macro_def_scope(&mut self, expn_id: ExpnId) -> Module<'a> {
let def_id = match self.macro_defs.get(&expn_id) {
Some(def_id) => *def_id,
None => return self.graph_root,
@@ -141,7 +145,7 @@
}
}
- crate fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
+ fn get_macro_by_def_id(&mut self, def_id: DefId) -> Option<Lrc<SyntaxExtension>> {
if let Some(ext) = self.macro_map.get(&def_id) {
return Some(ext.clone());
}
@@ -156,23 +160,32 @@
Some(ext)
}
- /// Ensures that the reduced graph rooted at the given external module
- /// is built, building it if it is not.
- pub fn populate_module_if_necessary(&mut self, module: Module<'a>) {
- if module.populated.get() { return }
- let def_id = module.def_id().unwrap();
+ crate fn build_reduced_graph(
+ &mut self, fragment: &AstFragment, parent_scope: ParentScope<'a>
+ ) -> LegacyScope<'a> {
+ fragment.visit_with(&mut DefCollector::new(&mut self.definitions, parent_scope.expansion));
+ let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope };
+ fragment.visit_with(&mut visitor);
+ visitor.parent_scope.legacy
+ }
+
+ crate fn build_reduced_graph_external(&mut self, module: Module<'a>) {
+ let def_id = module.def_id().expect("unpopulated module without a def-id");
for child in self.cstore.item_children_untracked(def_id, self.session) {
let child = child.map_id(|_| panic!("unexpected id"));
- BuildReducedGraphVisitor { parent_scope: self.dummy_parent_scope(), r: self }
- .build_reduced_graph_for_external_crate_res(module, child);
+ BuildReducedGraphVisitor { r: self, parent_scope: ParentScope::module(module) }
+ .build_reduced_graph_for_external_crate_res(child);
}
- module.populated.set(true)
}
}
-pub struct BuildReducedGraphVisitor<'a, 'b> {
- pub r: &'b mut Resolver<'a>,
- pub parent_scope: ParentScope<'a>,
+struct BuildReducedGraphVisitor<'a, 'b> {
+ r: &'b mut Resolver<'a>,
+ parent_scope: ParentScope<'a>,
+}
+
+impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
+ fn as_mut(&mut self) -> &mut Resolver<'a> { self.r }
}
impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
@@ -300,10 +313,9 @@
root_id: NodeId,
vis: ty::Visibility,
) {
- let parent_scope = &self.parent_scope;
- let current_module = parent_scope.module;
+ let current_module = self.parent_scope.module;
let directive = self.r.arenas.alloc_import_directive(ImportDirective {
- parent_scope: parent_scope.clone(),
+ parent_scope: self.parent_scope,
module_path,
imported_module: Cell::new(None),
subclass,
@@ -593,15 +605,13 @@
self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
};
- self.r.populate_module_if_necessary(module);
-
let used = self.process_legacy_macro_imports(item, module);
let binding =
(module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas);
let directive = self.r.arenas.alloc_import_directive(ImportDirective {
root_id: item.id,
id: item.id,
- parent_scope: self.parent_scope.clone(),
+ parent_scope: self.parent_scope,
imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
subclass: ImportDirectiveSubclass::ExternCrate {
source: orig_name,
@@ -706,7 +716,7 @@
self.r.define(parent, ident, TypeNS, (module, vis, sp, expansion));
for variant in &(*enum_definition).variants {
- self.build_reduced_graph_for_variant(variant, module, vis, expansion);
+ self.build_reduced_graph_for_variant(variant, module, vis);
}
}
@@ -797,8 +807,8 @@
fn build_reduced_graph_for_variant(&mut self,
variant: &Variant,
parent: Module<'a>,
- vis: ty::Visibility,
- expn_id: ExpnId) {
+ vis: ty::Visibility) {
+ let expn_id = self.parent_scope.expansion;
let ident = variant.ident;
// Define a name in the type namespace.
@@ -861,20 +871,19 @@
}
/// Builds the reduced graph for a single item in an external crate.
- fn build_reduced_graph_for_external_crate_res(
- &mut self,
- parent: Module<'a>,
- child: Export<ast::NodeId>,
- ) {
+ fn build_reduced_graph_for_external_crate_res(&mut self, child: Export<ast::NodeId>) {
+ let parent = self.parent_scope.module;
let Export { ident, res, vis, span } = child;
// FIXME: We shouldn't create the gensym here, it should come from metadata,
// but metadata cannot encode gensyms currently, so we create it here.
// This is only a guess, two equivalent idents may incorrectly get different gensyms here.
let ident = ident.gensym_if_underscore();
let expansion = ExpnId::root(); // FIXME(jseyfried) intercrate hygiene
+ // Record primary definitions.
match res {
Res::Def(kind @ DefKind::Mod, def_id)
- | Res::Def(kind @ DefKind::Enum, def_id) => {
+ | Res::Def(kind @ DefKind::Enum, def_id)
+ | Res::Def(kind @ DefKind::Trait, def_id) => {
let module = self.r.new_module(parent,
ModuleKind::Def(kind, def_id, ident.name),
def_id,
@@ -882,70 +891,55 @@
span);
self.r.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
}
- Res::Def(DefKind::Variant, _)
+ Res::Def(DefKind::Struct, _)
+ | Res::Def(DefKind::Union, _)
+ | Res::Def(DefKind::Variant, _)
| Res::Def(DefKind::TyAlias, _)
| Res::Def(DefKind::ForeignTy, _)
| Res::Def(DefKind::OpaqueTy, _)
| Res::Def(DefKind::TraitAlias, _)
+ | Res::Def(DefKind::AssocTy, _)
+ | Res::Def(DefKind::AssocOpaqueTy, _)
| Res::PrimTy(..)
- | Res::ToolMod => {
- self.r.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
- }
+ | Res::ToolMod =>
+ self.r.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion)),
Res::Def(DefKind::Fn, _)
+ | Res::Def(DefKind::Method, _)
| Res::Def(DefKind::Static, _)
| Res::Def(DefKind::Const, _)
- | Res::Def(DefKind::Ctor(CtorOf::Variant, ..), _) => {
- self.r.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
- }
- Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
- self.r.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion));
-
- if let Some(struct_def_id) =
- self.r.cstore.def_key(def_id).parent
- .map(|index| DefId { krate: def_id.krate, index: index }) {
- self.r.struct_constructors.insert(struct_def_id, (res, vis));
- }
- }
- Res::Def(DefKind::Trait, def_id) => {
- let module_kind = ModuleKind::Def(DefKind::Trait, def_id, ident.name);
- let module = self.r.new_module(parent,
- module_kind,
- parent.normal_ancestor_id,
- expansion,
- span);
- self.r.define(parent, ident, TypeNS, (module, vis, DUMMY_SP, expansion));
-
- for child in self.r.cstore.item_children_untracked(def_id, self.r.session) {
- let res = child.res.map_id(|_| panic!("unexpected id"));
- let ns = if let Res::Def(DefKind::AssocTy, _) = res {
- TypeNS
- } else { ValueNS };
- self.r.define(module, child.ident, ns,
- (res, ty::Visibility::Public, DUMMY_SP, expansion));
-
- if self.r.cstore.associated_item_cloned_untracked(child.res.def_id())
- .method_has_self_argument {
- self.r.has_self.insert(res.def_id());
- }
- }
- module.populated.set(true);
- }
+ | Res::Def(DefKind::AssocConst, _)
+ | Res::Def(DefKind::Ctor(..), _) =>
+ self.r.define(parent, ident, ValueNS, (res, vis, DUMMY_SP, expansion)),
+ Res::Def(DefKind::Macro(..), _)
+ | Res::NonMacroAttr(..) =>
+ self.r.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion)),
+ Res::Def(DefKind::TyParam, _) | Res::Def(DefKind::ConstParam, _)
+ | Res::Local(..) | Res::SelfTy(..) | Res::SelfCtor(..) | Res::Err =>
+ bug!("unexpected resolution: {:?}", res)
+ }
+ // Record some extra data for better diagnostics.
+ match res {
Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) => {
- self.r.define(parent, ident, TypeNS, (res, vis, DUMMY_SP, expansion));
-
- // Record field names for error reporting.
let field_names = self.r.cstore.struct_field_names_untracked(def_id);
self.insert_field_names(def_id, field_names);
}
- Res::Def(DefKind::Macro(..), _) | Res::NonMacroAttr(..) => {
- self.r.define(parent, ident, MacroNS, (res, vis, DUMMY_SP, expansion));
+ Res::Def(DefKind::Method, def_id) => {
+ if self.r.cstore.associated_item_cloned_untracked(def_id).method_has_self_argument {
+ self.r.has_self.insert(def_id);
+ }
}
- _ => bug!("unexpected resolution: {:?}", res)
+ Res::Def(DefKind::Ctor(CtorOf::Struct, ..), def_id) => {
+ let parent = self.r.cstore.def_key(def_id).parent;
+ if let Some(struct_def_id) = parent.map(|index| DefId { index, ..def_id }) {
+ self.r.struct_constructors.insert(struct_def_id, (res, vis));
+ }
+ }
+ _ => {}
}
}
fn legacy_import_macro(&mut self,
- name: Name,
+ name: ast::Name,
binding: &'a NameBinding<'a>,
span: Span,
allow_shadowing: bool) {
@@ -997,7 +991,7 @@
|this: &Self, span| this.r.arenas.alloc_import_directive(ImportDirective {
root_id: item.id,
id: item.id,
- parent_scope: this.parent_scope.clone(),
+ parent_scope: this.parent_scope,
imported_module: Cell::new(Some(ModuleOrUniformRoot::Module(module))),
subclass: ImportDirectiveSubclass::MacroUse,
use_span_with_attributes: item.span_with_attributes(),
@@ -1014,9 +1008,9 @@
if let Some(span) = import_all {
let directive = macro_use_directive(self, span);
self.r.potentially_unused_imports.push(directive);
- module.for_each_child(|ident, ns, binding| if ns == MacroNS {
- let imported_binding = self.r.import(binding, directive);
- self.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
+ module.for_each_child(self, |this, ident, ns, binding| if ns == MacroNS {
+ let imported_binding = this.r.import(binding, directive);
+ this.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing);
});
} else {
for ident in single_imports.iter().cloned() {
@@ -1066,20 +1060,15 @@
false
}
- fn visit_invoc(&mut self, id: ast::NodeId) -> &'a InvocationData<'a> {
+ fn visit_invoc(&mut self, id: ast::NodeId) -> LegacyScope<'a> {
let invoc_id = id.placeholder_to_expn_id();
self.parent_scope.module.unresolved_invocations.borrow_mut().insert(invoc_id);
- let invocation_data = self.r.arenas.alloc_invocation_data(InvocationData {
- module: self.parent_scope.module,
- parent_legacy_scope: self.parent_scope.legacy,
- output_legacy_scope: Cell::new(None),
- });
- let old_invocation_data = self.r.invocations.insert(invoc_id, invocation_data);
- assert!(old_invocation_data.is_none(), "invocation data is reset for an invocation");
+ let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope);
+ assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation");
- invocation_data
+ LegacyScope::Invocation(invoc_id)
}
fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
@@ -1180,7 +1169,7 @@
return
}
ItemKind::Mac(..) => {
- self.parent_scope.legacy = LegacyScope::Invocation(self.visit_invoc(item.id));
+ self.parent_scope.legacy = self.visit_invoc(item.id);
return
}
ItemKind::Mod(..) => self.contains_macro_use(&item.attrs),
@@ -1199,7 +1188,7 @@
fn visit_stmt(&mut self, stmt: &'b ast::Stmt) {
if let ast::StmtKind::Mac(..) = stmt.node {
- self.parent_scope.legacy = LegacyScope::Invocation(self.visit_invoc(stmt.id));
+ self.parent_scope.legacy = self.visit_invoc(stmt.id);
} else {
visit::walk_stmt(self, stmt);
}
@@ -1267,9 +1256,7 @@
fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
if !attr.is_sugared_doc && is_builtin_attr(attr) {
- self.parent_scope.module.builtin_attrs.borrow_mut().push((
- attr.path.segments[0].ident, self.parent_scope.clone()
- ));
+ self.r.builtin_attrs.push((attr.path.segments[0].ident, self.parent_scope));
}
visit::walk_attribute(self, attr);
}
diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs
index 1de67ed..b79e0c2 100644
--- a/src/librustc_resolve/diagnostics.rs
+++ b/src/librustc_resolve/diagnostics.rs
@@ -73,20 +73,23 @@
false
}
-crate fn add_module_candidates(
- module: Module<'_>, names: &mut Vec<TypoSuggestion>, filter_fn: &impl Fn(Res) -> bool
-) {
- for (&(ident, _), resolution) in module.resolutions.borrow().iter() {
- if let Some(binding) = resolution.borrow().binding {
- let res = binding.res();
- if filter_fn(res) {
- names.push(TypoSuggestion::from_res(ident.name, res));
+impl<'a> Resolver<'a> {
+ crate fn add_module_candidates(
+ &mut self,
+ module: Module<'a>,
+ names: &mut Vec<TypoSuggestion>,
+ filter_fn: &impl Fn(Res) -> bool,
+ ) {
+ for (&(ident, _), resolution) in self.resolutions(module).borrow().iter() {
+ if let Some(binding) = resolution.borrow().binding {
+ let res = binding.res();
+ if filter_fn(res) {
+ names.push(TypoSuggestion::from_res(ident.name, res));
+ }
}
}
}
-}
-impl<'a> Resolver<'a> {
/// Combines an error with provided span and emits it.
///
/// This takes the error provided, combines it with the span and any additional spans inside the
@@ -166,12 +169,14 @@
err
}
ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
- let mut err = struct_span_err!(self.session,
- span,
- E0403,
- "the name `{}` is already used for a generic \
- parameter in this list of generic parameters",
- name);
+ let mut err = struct_span_err!(
+ self.session,
+ span,
+ E0403,
+ "the name `{}` is already used for a generic \
+ parameter in this item's generic parameters",
+ name,
+ );
err.span_label(span, "already used");
err.span_label(first_use_span, format!("first use of `{}`", name));
err
@@ -376,9 +381,9 @@
Scope::DeriveHelpers => {
let res = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
if filter_fn(res) {
- for derive in &parent_scope.derives {
+ for derive in parent_scope.derives {
let parent_scope =
- &ParentScope { derives: Vec::new(), ..*parent_scope };
+ &ParentScope { derives: &[], ..*parent_scope };
if let Ok((Some(ext), _)) = this.resolve_macro_path(
derive, Some(MacroKind::Derive), parent_scope, false, false
) {
@@ -402,10 +407,10 @@
Scope::CrateRoot => {
let root_ident = Ident::new(kw::PathRoot, ident.span);
let root_module = this.resolve_crate_root(root_ident);
- add_module_candidates(root_module, &mut suggestions, filter_fn);
+ this.add_module_candidates(root_module, &mut suggestions, filter_fn);
}
Scope::Module(module) => {
- add_module_candidates(module, &mut suggestions, filter_fn);
+ this.add_module_candidates(module, &mut suggestions, filter_fn);
}
Scope::MacroUsePrelude => {
suggestions.extend(this.macro_use_prelude.iter().filter_map(|(name, binding)| {
@@ -453,9 +458,9 @@
Scope::StdLibPrelude => {
if let Some(prelude) = this.prelude {
let mut tmp_suggestions = Vec::new();
- add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
+ this.add_module_candidates(prelude, &mut tmp_suggestions, filter_fn);
suggestions.extend(tmp_suggestions.into_iter().filter(|s| {
- use_prelude || this.is_builtin_macro(s.res.opt_def_id())
+ use_prelude || this.is_builtin_macro(s.res)
}));
}
}
@@ -509,11 +514,9 @@
while let Some((in_module,
path_segments,
in_module_is_extern)) = worklist.pop() {
- self.populate_module_if_necessary(in_module);
-
// We have to visit module children in deterministic order to avoid
// instabilities in reported imports (#43552).
- in_module.for_each_child_stable(|ident, ns, name_binding| {
+ in_module.for_each_child_stable(self, |this, ident, ns, name_binding| {
// avoid imports entirely
if name_binding.is_import() && !name_binding.is_extern_crate() { return; }
// avoid non-importable candidates as well
@@ -547,7 +550,7 @@
// outside crate private modules => no need to check this)
if !in_module_is_extern || name_binding.vis == ty::Visibility::Public {
let did = match res {
- Res::Def(DefKind::Ctor(..), did) => self.parent(did),
+ Res::Def(DefKind::Ctor(..), did) => this.parent(did),
_ => res.opt_def_id(),
};
candidates.push(ImportSuggestion { did, path });
@@ -595,7 +598,7 @@
where FilterFn: Fn(Res) -> bool
{
let mut suggestions = self.lookup_import_candidates_from_module(
- lookup_ident, namespace, self.graph_root, Ident::with_empty_ctxt(kw::Crate), &filter_fn
+ lookup_ident, namespace, self.graph_root, Ident::with_dummy_span(kw::Crate), &filter_fn
);
if lookup_ident.span.rust_2018() {
@@ -607,8 +610,6 @@
krate: crate_id,
index: CRATE_DEF_INDEX,
});
- self.populate_module_if_necessary(&crate_root);
-
suggestions.extend(self.lookup_import_candidates_from_module(
lookup_ident, namespace, crate_root, ident, &filter_fn));
}
@@ -805,7 +806,7 @@
/// at the root of the crate instead of the module where it is defined
/// ```
pub(crate) fn check_for_module_export_macro(
- &self,
+ &mut self,
directive: &'b ImportDirective<'b>,
module: ModuleOrUniformRoot<'b>,
ident: Ident,
@@ -826,7 +827,7 @@
return None;
}
- let resolutions = crate_module.resolutions.borrow();
+ let resolutions = self.r.resolutions(crate_module).borrow();
let resolution = resolutions.get(&(ident, MacroNS))?;
let binding = resolution.borrow().binding()?;
if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
diff --git a/src/librustc_resolve/error_codes.rs b/src/librustc_resolve/error_codes.rs
index e01f537..1faaf97 100644
--- a/src/librustc_resolve/error_codes.rs
+++ b/src/librustc_resolve/error_codes.rs
@@ -526,15 +526,25 @@
Erroneous code example:
```compile_fail,E0403
-fn foo<T, T>(s: T, u: T) {} // error: the name `T` is already used for a type
- // parameter in this type parameter list
+fn f<T, T>(s: T, u: T) {} // error: the name `T` is already used for a generic
+ // parameter in this item's generic parameters
```
Please verify that none of the type parameters are misspelled, and rename any
clashing parameters. Example:
```
-fn foo<T, Y>(s: T, u: Y) {} // ok!
+fn f<T, Y>(s: T, u: Y) {} // ok!
+```
+
+Type parameters in an associated item also cannot shadow parameters from the
+containing item:
+
+```compile_fail,E0403
+trait Foo<T> {
+ fn do_something(&self) -> T;
+ fn do_something_else<T: Clone>(&self, bar: T);
+}
```
"##,
diff --git a/src/librustc_resolve/late.rs b/src/librustc_resolve/late.rs
index 358eaae..e15d02a 100644
--- a/src/librustc_resolve/late.rs
+++ b/src/librustc_resolve/late.rs
@@ -1,3 +1,10 @@
+//! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
+//! It runs when the crate is fully expanded and its module structure is fully built.
+//! So it just walks through the crate and resolves all the expressions, types, etc.
+//!
+//! If you wonder why there's no `early.rs`, that's because it's split into three files -
+//! `build_reduced_graph.rs`, `macros.rs` and `resolve_imports.rs`.
+
use GenericParameters::*;
use RibKind::*;
@@ -104,6 +111,24 @@
TyParamAsConstParamTy,
}
+impl RibKind<'_> {
+ // Whether this rib kind contains generic parameters, as opposed to local
+ // variables.
+ crate fn contains_params(&self) -> bool {
+ match self {
+ NormalRibKind
+ | FnItemRibKind
+ | ConstantItemRibKind
+ | ModuleRibKind(_)
+ | MacroDefinition(_) => false,
+ AssocItemRibKind
+ | ItemRibKind
+ | ForwardTyParamBanRibKind
+ | TyParamAsConstParamTy => true,
+ }
+ }
+}
+
/// A single local scope.
///
/// A rib represents a scope names can live in. Note that these appear in many places, not just
@@ -352,7 +377,7 @@
self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
}
TyKind::ImplicitSelf => {
- let self_ty = Ident::with_empty_ctxt(kw::SelfUpper);
+ let self_ty = Ident::with_dummy_span(kw::SelfUpper);
let res = self.resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span)
.map_or(Res::Err, |d| d.res());
self.r.record_partial_res(ty.id, PartialRes::new(res));
@@ -442,7 +467,7 @@
GenericParamKind::Type { ref default, .. } => {
found_default |= default.is_some();
if found_default {
- Some((Ident::with_empty_ctxt(param.ident.name), Res::Err))
+ Some((Ident::with_dummy_span(param.ident.name), Res::Err))
} else {
None
}
@@ -459,7 +484,7 @@
false
}
})
- .map(|param| (Ident::with_empty_ctxt(param.ident.name), Res::Err)));
+ .map(|param| (Ident::with_dummy_span(param.ident.name), Res::Err)));
for param in &generics.params {
match param.kind {
@@ -476,7 +501,7 @@
}
// Allow all following defaults to refer to this type parameter.
- default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
+ default_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name));
}
GenericParamKind::Const { ref ty } => {
self.ribs[TypeNS].push(const_ty_param_ban_rib);
@@ -501,8 +526,8 @@
fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b> {
// During late resolution we only track the module component of the parent scope,
// although it may be useful to track other components as well for diagnostics.
- let parent_scope = resolver.dummy_parent_scope();
let graph_root = resolver.graph_root;
+ let parent_scope = ParentScope::module(graph_root);
LateResolutionVisitor {
r: resolver,
parent_scope,
@@ -574,7 +599,6 @@
self.ribs[ValueNS].push(Rib::new(ModuleRibKind(module)));
self.ribs[TypeNS].push(Rib::new(ModuleRibKind(module)));
- self.r.finalize_current_module_macro_resolutions(module);
let ret = f(self);
self.parent_scope.module = orig_module;
@@ -792,6 +816,19 @@
let mut function_type_rib = Rib::new(rib_kind);
let mut function_value_rib = Rib::new(rib_kind);
let mut seen_bindings = FxHashMap::default();
+ // We also can't shadow bindings from the parent item
+ if let AssocItemRibKind = rib_kind {
+ let mut add_bindings_for_ns = |ns| {
+ let parent_rib = self.ribs[ns].iter()
+ .rfind(|rib| if let ItemRibKind = rib.kind { true } else { false })
+ .expect("associated item outside of an item");
+ seen_bindings.extend(
+ parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)),
+ );
+ };
+ add_bindings_for_ns(ValueNS);
+ add_bindings_for_ns(TypeNS);
+ }
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => {}
@@ -965,7 +1002,7 @@
let mut self_type_rib = Rib::new(NormalRibKind);
// Plain insert (no renaming, since types are not currently hygienic)
- self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
+ self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
self.ribs[TypeNS].push(self_type_rib);
f(self);
self.ribs[TypeNS].pop();
@@ -976,7 +1013,7 @@
{
let self_res = Res::SelfCtor(impl_id);
let mut self_type_rib = Rib::new(NormalRibKind);
- self_type_rib.bindings.insert(Ident::with_empty_ctxt(kw::SelfUpper), self_res);
+ self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
self.ribs[ValueNS].push(self_type_rib);
f(self);
self.ribs[ValueNS].pop();
@@ -1227,7 +1264,6 @@
self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
self.parent_scope.module = anonymous_module;
- self.r.finalize_current_module_macro_resolutions(anonymous_module);
} else {
self.ribs[ValueNS].push(Rib::new(NormalRibKind));
}
@@ -1476,7 +1512,7 @@
self.r.trait_map.insert(id, traits);
}
- let mut std_path = vec![Segment::from_ident(Ident::with_empty_ctxt(sym::std))];
+ let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
std_path.extend(path);
if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
let cl = CrateLint::No;
@@ -1507,7 +1543,7 @@
fn self_type_is_available(&mut self, span: Span) -> bool {
let binding = self.resolve_ident_in_lexical_scope(
- Ident::with_empty_ctxt(kw::SelfUpper),
+ Ident::with_dummy_span(kw::SelfUpper),
TypeNS,
None,
span,
@@ -1924,7 +1960,7 @@
let mut traits = module.traits.borrow_mut();
if traits.is_none() {
let mut collected_traits = Vec::new();
- module.for_each_child(|name, ns, binding| {
+ module.for_each_child(self.r, |_, name, ns, binding| {
if ns != TypeNS { return }
match binding.res() {
Res::Def(DefKind::Trait, _) |
@@ -1984,7 +2020,6 @@
impl<'a> Resolver<'a> {
pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
- self.finalize_current_module_macro_resolutions(self.graph_root);
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
visit::walk_crate(&mut late_resolution_visitor, krate);
for (id, span) in late_resolution_visitor.unused_labels.iter() {
diff --git a/src/librustc_resolve/late/diagnostics.rs b/src/librustc_resolve/late/diagnostics.rs
index 68f9c16..a822fa0 100644
--- a/src/librustc_resolve/late/diagnostics.rs
+++ b/src/librustc_resolve/late/diagnostics.rs
@@ -1,8 +1,7 @@
use crate::{CrateLint, Module, ModuleKind, ModuleOrUniformRoot};
use crate::{PathResult, PathSource, Segment};
use crate::path_names_to_string;
-use crate::diagnostics::{add_typo_suggestion, add_module_candidates};
-use crate::diagnostics::{ImportSuggestion, TypoSuggestion};
+use crate::diagnostics::{add_typo_suggestion, ImportSuggestion, TypoSuggestion};
use crate::late::{LateResolutionVisitor, RibKind};
use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
@@ -548,7 +547,7 @@
// Items in scope
if let RibKind::ModuleRibKind(module) = rib.kind {
// Items from this module
- add_module_candidates(module, &mut names, &filter_fn);
+ self.r.add_module_candidates(module, &mut names, &filter_fn);
if let ModuleKind::Block(..) = module.kind {
// We can see through blocks
@@ -577,7 +576,7 @@
}));
if let Some(prelude) = self.r.prelude {
- add_module_candidates(prelude, &mut names, &filter_fn);
+ self.r.add_module_candidates(prelude, &mut names, &filter_fn);
}
}
break;
@@ -599,7 +598,7 @@
mod_path, Some(TypeNS), false, span, CrateLint::No
) {
if let ModuleOrUniformRoot::Module(module) = module {
- add_module_candidates(module, &mut names, &filter_fn);
+ self.r.add_module_candidates(module, &mut names, &filter_fn);
}
}
}
@@ -717,9 +716,7 @@
// abort if the module is already found
if result.is_some() { break; }
- self.r.populate_module_if_necessary(in_module);
-
- in_module.for_each_child_stable(|ident, _, name_binding| {
+ in_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
// abort if the module is already found or if name_binding is private external
if result.is_some() || !name_binding.vis.is_visible_locally() {
return
@@ -750,10 +747,8 @@
fn collect_enum_variants(&mut self, def_id: DefId) -> Option<Vec<Path>> {
self.find_module(def_id).map(|(enum_module, enum_import_suggestion)| {
- self.r.populate_module_if_necessary(enum_module);
-
let mut variants = Vec::new();
- enum_module.for_each_child_stable(|ident, _, name_binding| {
+ enum_module.for_each_child_stable(self.r, |_, ident, _, name_binding| {
if let Res::Def(DefKind::Variant, _) = name_binding.res() {
let mut segms = enum_import_suggestion.path.segments.clone();
segms.push(ast::PathSegment::from_ident(ident));
diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs
index 8a4a60c..984473d 100644
--- a/src/librustc_resolve/lib.rs
+++ b/src/librustc_resolve/lib.rs
@@ -1,3 +1,12 @@
+//! This crate is responsible for the part of name resolution that doesn't require type checker.
+//!
+//! Module structure of the crate is built here.
+//! Paths in macros, imports, expressions, types, patterns are resolved here.
+//! Label names are resolved here as well.
+//!
+//! Type-relative name resolution (methods, fields, associated items) happens in `librustc_typeck`.
+//! Lifetime names are resolved in `librustc/middle/resolve_lifetime.rs`.
+
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(crate_visibility_modifier)]
@@ -54,7 +63,7 @@
use diagnostics::{find_span_of_binding_until_next_binding, extend_span_to_previous_binding};
use late::{PathSource, Rib, RibKind::*};
use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver};
-use macros::{InvocationData, LegacyBinding, LegacyScope};
+use macros::{LegacyBinding, LegacyScope};
type Res = def::Res<NodeId>;
@@ -122,12 +131,25 @@
/// Serves as a starting point for the scope visitor.
/// This struct is currently used only for early resolution (imports and macros),
/// but not for late resolution yet.
-#[derive(Clone, Debug)]
+#[derive(Clone, Copy, Debug)]
pub struct ParentScope<'a> {
module: Module<'a>,
expansion: ExpnId,
legacy: LegacyScope<'a>,
- derives: Vec<ast::Path>,
+ derives: &'a [ast::Path],
+}
+
+impl<'a> ParentScope<'a> {
+ /// Creates a parent scope with the passed argument used as the module scope component,
+ /// and other scope components set to default empty values.
+ pub fn module(module: Module<'a>) -> ParentScope<'a> {
+ ParentScope {
+ module,
+ expansion: ExpnId::root(),
+ legacy: LegacyScope::Empty,
+ derives: &[],
+ }
+ }
}
#[derive(Eq)]
@@ -274,7 +296,7 @@
ItemKind::Use(..) => {
// don't suggest placing a use before the prelude
// import or other generated ones
- if item.span.ctxt().outer_expn_info().is_none() {
+ if !item.span.from_expansion() {
self.span = Some(item.span.shrink_to_lo());
self.found_use = true;
return;
@@ -284,7 +306,7 @@
ItemKind::ExternCrate(_) => {}
// but place them before the first other item
_ => if self.span.map_or(true, |span| item.span < span ) {
- if item.span.ctxt().outer_expn_info().is_none() {
+ if !item.span.from_expansion() {
// don't insert between attributes and an item
if item.attrs.is_empty() {
self.span = Some(item.span.shrink_to_lo());
@@ -409,6 +431,8 @@
}
}
+type Resolutions<'a> = RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>;
+
/// One node in the tree of modules.
pub struct ModuleData<'a> {
parent: Option<Module<'a>>,
@@ -417,12 +441,11 @@
// The def id of the closest normal module (`mod`) ancestor (including this module).
normal_ancestor_id: DefId,
- resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
- single_segment_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
- Option<&'a NameBinding<'a>>)>>,
- multi_segment_macro_resolutions: RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
- Option<Res>)>>,
- builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
+ // Mapping between names and their (possibly in-progress) resolutions in this module.
+ // Resolutions in modules from other crates are not populated until accessed.
+ lazy_resolutions: Resolutions<'a>,
+ // True if this is a module from other crate that needs to be populated on access.
+ populate_on_access: Cell<bool>,
// Macro invocations that can expand into items in this module.
unresolved_invocations: RefCell<FxHashSet<ExpnId>>,
@@ -435,11 +458,6 @@
// Used to memoize the traits in this module for faster searches through all traits in scope.
traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
- // Whether this module is populated. If not populated, any attempt to
- // access the children must be preceded with a
- // `populate_module_if_necessary` call.
- populated: Cell<bool>,
-
/// Span of the module itself. Used for error reporting.
span: Span,
@@ -458,33 +476,34 @@
parent,
kind,
normal_ancestor_id,
- resolutions: Default::default(),
- single_segment_macro_resolutions: RefCell::new(Vec::new()),
- multi_segment_macro_resolutions: RefCell::new(Vec::new()),
- builtin_attrs: RefCell::new(Vec::new()),
+ lazy_resolutions: Default::default(),
+ populate_on_access: Cell::new(!normal_ancestor_id.is_local()),
unresolved_invocations: Default::default(),
no_implicit_prelude: false,
glob_importers: RefCell::new(Vec::new()),
globs: RefCell::new(Vec::new()),
traits: RefCell::new(None),
- populated: Cell::new(normal_ancestor_id.is_local()),
span,
expansion,
}
}
- fn for_each_child<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
- for (&(ident, ns), name_resolution) in self.resolutions.borrow().iter() {
- name_resolution.borrow().binding.map(|binding| f(ident, ns, binding));
+ fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
+ where R: AsMut<Resolver<'a>>, F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>)
+ {
+ for (&(ident, ns), name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
+ name_resolution.borrow().binding.map(|binding| f(resolver, ident, ns, binding));
}
}
- fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
- let resolutions = self.resolutions.borrow();
+ fn for_each_child_stable<R, F>(&'a self, resolver: &mut R, mut f: F)
+ where R: AsMut<Resolver<'a>>, F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>)
+ {
+ let resolutions = resolver.as_mut().resolutions(self).borrow();
let mut resolutions = resolutions.iter().collect::<Vec<_>>();
resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.as_str(), ns));
for &(&(ident, ns), &resolution) in resolutions.iter() {
- resolution.borrow().binding.map(|binding| f(ident, ns, binding));
+ resolution.borrow().binding.map(|binding| f(resolver, ident, ns, binding));
}
}
@@ -807,7 +826,7 @@
pub definitions: Definitions,
- graph_root: Module<'a>,
+ pub graph_root: Module<'a>,
prelude: Option<Module<'a>>,
pub extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
@@ -896,15 +915,24 @@
local_macro_def_scopes: FxHashMap<NodeId, Module<'a>>,
unused_macros: NodeMap<Span>,
proc_macro_stubs: NodeSet,
+ /// Traces collected during macro resolution and validated when it's complete.
+ single_segment_macro_resolutions: Vec<(Ident, MacroKind, ParentScope<'a>,
+ Option<&'a NameBinding<'a>>)>,
+ multi_segment_macro_resolutions: Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>,
+ Option<Res>)>,
+ builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
/// Some built-in derives mark items they are applied to so they are treated specially later.
/// Derive macros cannot modify the item themselves and have to store the markers in the global
/// context, so they attach the markers to derive container IDs using this resolver table.
/// FIXME: Find a way for `PartialEq` and `Eq` to emulate `#[structural_match]`
/// by marking the produced impls rather than the original items.
special_derives: FxHashMap<ExpnId, SpecialDerives>,
-
- /// Maps the `ExpnId` of an expansion to its containing module or block.
- invocations: FxHashMap<ExpnId, &'a InvocationData<'a>>,
+ /// Parent scopes in which the macros were invoked.
+ /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
+ invocation_parent_scopes: FxHashMap<ExpnId, ParentScope<'a>>,
+ /// Legacy scopes *produced* by expanding the macro invocations,
+ /// include all the `macro_rules` items and other invocations generated by them.
+ output_legacy_scopes: FxHashMap<ExpnId, LegacyScope<'a>>,
/// Avoid duplicated errors for "name already defined".
name_already_seen: FxHashMap<Name, Span>,
@@ -927,8 +955,8 @@
name_bindings: arena::TypedArena<NameBinding<'a>>,
import_directives: arena::TypedArena<ImportDirective<'a>>,
name_resolutions: arena::TypedArena<RefCell<NameResolution<'a>>>,
- invocation_data: arena::TypedArena<InvocationData<'a>>,
legacy_bindings: arena::TypedArena<LegacyBinding<'a>>,
+ ast_paths: arena::TypedArena<ast::Path>,
}
impl<'a> ResolverArenas<'a> {
@@ -952,13 +980,16 @@
fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
self.name_resolutions.alloc(Default::default())
}
- fn alloc_invocation_data(&'a self, expansion_data: InvocationData<'a>)
- -> &'a InvocationData<'a> {
- self.invocation_data.alloc(expansion_data)
- }
fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> {
self.legacy_bindings.alloc(binding)
}
+ fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
+ self.ast_paths.alloc_from_iter(paths.iter().cloned())
+ }
+}
+
+impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
+ fn as_mut(&mut self) -> &mut Resolver<'a> { self }
}
impl<'a, 'b> ty::DefIdTree for &'a Resolver<'b> {
@@ -985,11 +1016,11 @@
} else {
kw::Crate
};
- let segments = iter::once(Ident::with_empty_ctxt(root))
+ let segments = iter::once(Ident::with_dummy_span(root))
.chain(
crate_root.into_iter()
.chain(components.iter().cloned())
- .map(Ident::with_empty_ctxt)
+ .map(Ident::with_dummy_span)
).map(|i| self.new_ast_path_segment(i)).collect::<Vec<_>>();
let path = ast::Path {
@@ -997,7 +1028,7 @@
segments,
};
- let parent_scope = &self.dummy_parent_scope();
+ let parent_scope = &ParentScope::module(self.graph_root);
let res = match self.resolve_ast_path(&path, ns, parent_scope) {
Ok(res) => res,
Err((span, error)) => {
@@ -1060,18 +1091,17 @@
.collect();
if !attr::contains_name(&krate.attrs, sym::no_core) {
- extern_prelude.insert(Ident::with_empty_ctxt(sym::core), Default::default());
+ extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
if !attr::contains_name(&krate.attrs, sym::no_std) {
- extern_prelude.insert(Ident::with_empty_ctxt(sym::std), Default::default());
+ extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
if session.rust_2018() {
- extern_prelude.insert(Ident::with_empty_ctxt(sym::meta), Default::default());
+ extern_prelude.insert(Ident::with_dummy_span(sym::meta), Default::default());
}
}
}
- let mut invocations = FxHashMap::default();
- invocations.insert(ExpnId::root(),
- arenas.alloc_invocation_data(InvocationData::root(graph_root)));
+ let mut invocation_parent_scopes = FxHashMap::default();
+ invocation_parent_scopes.insert(ExpnId::root(), ParentScope::module(graph_root));
let mut macro_defs = FxHashMap::default();
macro_defs.insert(ExpnId::root(), root_def_id);
@@ -1143,7 +1173,8 @@
dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)],
- invocations,
+ invocation_parent_scopes,
+ output_legacy_scopes: Default::default(),
macro_defs,
local_macro_def_scopes: FxHashMap::default(),
name_already_seen: FxHashMap::default(),
@@ -1151,6 +1182,9 @@
struct_constructors: Default::default(),
unused_macros: Default::default(),
proc_macro_stubs: Default::default(),
+ single_segment_macro_resolutions: Default::default(),
+ multi_segment_macro_resolutions: Default::default(),
+ builtin_attrs: Default::default(),
special_derives: Default::default(),
active_features:
features.declared_lib_features.iter().map(|(feat, ..)| *feat)
@@ -1182,9 +1216,8 @@
f(self, MacroNS);
}
- fn is_builtin_macro(&mut self, def_id: Option<DefId>) -> bool {
- def_id.and_then(|def_id| self.get_macro_by_def_id(def_id))
- .map_or(false, |ext| ext.is_builtin)
+ fn is_builtin_macro(&mut self, res: Res) -> bool {
+ self.get_macro(res).map_or(false, |ext| ext.is_builtin)
}
fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
@@ -1203,6 +1236,7 @@
/// Entry point to crate resolution.
pub fn resolve_crate(&mut self, krate: &Crate) {
ImportResolver { r: self }.finalize_imports();
+ self.finalize_macro_resolutions();
self.late_resolve_crate(krate);
@@ -1223,6 +1257,20 @@
self.arenas.alloc_module(module)
}
+ fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
+ if module.populate_on_access.get() {
+ module.populate_on_access.set(false);
+ self.build_reduced_graph_external(module);
+ }
+ &module.lazy_resolutions
+ }
+
+ fn resolution(&mut self, module: Module<'a>, ident: Ident, ns: Namespace)
+ -> &'a RefCell<NameResolution<'a>> {
+ *self.resolutions(module).borrow_mut().entry((ident.modern(), ns))
+ .or_insert_with(|| self.arenas.alloc_name_resolution())
+ }
+
fn record_use(&mut self, ident: Ident, ns: Namespace,
used_binding: &'a NameBinding<'a>, is_lexical_scope: bool) {
if let Some((b2, kind)) = used_binding.ambiguity {
@@ -1319,13 +1367,15 @@
ScopeSet::AbsolutePath(ns) => (ns, true),
ScopeSet::Macro(_) => (MacroNS, false),
};
+ // Jump out of trait or enum modules, they do not act as scopes.
+ let module = parent_scope.module.nearest_item_scope();
let mut scope = match ns {
_ if is_absolute_path => Scope::CrateRoot,
- TypeNS | ValueNS => Scope::Module(parent_scope.module),
+ TypeNS | ValueNS => Scope::Module(module),
MacroNS => Scope::DeriveHelpers,
};
let mut ident = ident.modern();
- let mut use_prelude = !parent_scope.module.no_implicit_prelude;
+ let mut use_prelude = !module.no_implicit_prelude;
loop {
let visit = match scope {
@@ -1355,10 +1405,11 @@
LegacyScope::Binding(binding) => Scope::MacroRules(
binding.parent_legacy_scope
),
- LegacyScope::Invocation(invoc) => Scope::MacroRules(
- invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope)
+ LegacyScope::Invocation(invoc_id) => Scope::MacroRules(
+ self.output_legacy_scopes.get(&invoc_id).cloned()
+ .unwrap_or(self.invocation_parent_scopes[&invoc_id].legacy)
),
- LegacyScope::Empty => Scope::Module(parent_scope.module),
+ LegacyScope::Empty => Scope::Module(module),
}
Scope::CrateRoot => match ns {
TypeNS => {
@@ -1430,7 +1481,7 @@
}
let (general_span, modern_span) = if ident.name == kw::SelfUpper {
// FIXME(jseyfried) improve `Self` hygiene
- let empty_span = ident.span.with_ctxt(SyntaxContext::empty());
+ let empty_span = ident.span.with_ctxt(SyntaxContext::root());
(empty_span, empty_span)
} else if ns == TypeNS {
let modern_span = ident.span.modern();
@@ -1448,7 +1499,7 @@
debug!("walk rib\n{:?}", ribs[i].bindings);
// Use the rib kind to determine whether we are resolving parameters
// (modern hygiene) or local variables (legacy hygiene).
- let rib_ident = if let AssocItemRibKind | ItemRibKind = ribs[i].kind {
+ let rib_ident = if ribs[i].kind.contains_params() {
modern_ident
} else {
ident
@@ -1501,7 +1552,7 @@
self.hygienic_lexical_parent(module, &mut ident.span)
};
module = unwrap_or!(opt_module, break);
- let adjusted_parent_scope = &ParentScope { module, ..parent_scope.clone() };
+ let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
let result = self.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(module),
ident,
@@ -1637,7 +1688,7 @@
ModuleOrUniformRoot::Module(m) => {
if let Some(def) = ident.span.modernize_and_adjust(m.expansion) {
tmp_parent_scope =
- ParentScope { module: self.macro_def_scope(def), ..parent_scope.clone() };
+ ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
adjusted_parent_scope = &tmp_parent_scope;
}
}
@@ -2606,7 +2657,6 @@
return None;
};
let crate_root = self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
- self.populate_module_if_necessary(&crate_root);
Some((crate_root, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
.to_name_binding(self.arenas))
}
@@ -2624,7 +2674,7 @@
let path = if path_str.starts_with("::") {
ast::Path {
span,
- segments: iter::once(Ident::with_empty_ctxt(kw::PathRoot))
+ segments: iter::once(Ident::with_dummy_span(kw::PathRoot))
.chain({
path_str.split("::").skip(1).map(Ident::from_str)
})
@@ -2645,7 +2695,7 @@
let def_id = self.definitions.local_def_id(module_id);
self.module_map.get(&def_id).copied().unwrap_or(self.graph_root)
});
- let parent_scope = &ParentScope { module, ..self.dummy_parent_scope() };
+ let parent_scope = &ParentScope::module(module);
let res = self.resolve_ast_path(&path, ns, parent_scope).map_err(|_| ())?;
Ok((path, res))
}
@@ -2713,7 +2763,7 @@
fn collect_mod(names: &mut Vec<Ident>, module: Module<'_>) {
if let ModuleKind::Def(.., name) = module.kind {
if let Some(parent) = module.parent {
- names.push(Ident::with_empty_ctxt(name));
+ names.push(Ident::with_dummy_span(name));
collect_mod(names, parent);
}
} else {
diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs
index 71e26da..6f49377 100644
--- a/src/librustc_resolve/macros.rs
+++ b/src/librustc_resolve/macros.rs
@@ -1,12 +1,13 @@
+//! A bunch of methods and structures more or less related to resolving macros and
+//! interface provided by `Resolver` to macro expander.
+
use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc, Determinacy};
use crate::{CrateLint, Resolver, ResolutionError, Scope, ScopeSet, ParentScope, Weak};
-use crate::{Module, ModuleKind, NameBinding, PathResult, Segment, ToNameBinding};
+use crate::{ModuleKind, NameBinding, PathResult, Segment, ToNameBinding};
use crate::{ModuleOrUniformRoot, KNOWN_TOOLS};
use crate::Namespace::*;
-use crate::build_reduced_graph::BuildReducedGraphVisitor;
use crate::resolve_imports::ImportResolver;
use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
-use rustc::hir::map::DefCollector;
use rustc::middle::stability;
use rustc::{ty, lint, span_bug};
use syntax::ast::{self, Ident};
@@ -15,43 +16,18 @@
use syntax::ext::base::{self, Indeterminate, SpecialDerives};
use syntax::ext::base::{MacroKind, SyntaxExtension};
use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
-use syntax::ext::hygiene::{self, ExpnId, ExpnInfo, ExpnKind};
+use syntax::ext::hygiene::{self, ExpnId, ExpnData, ExpnKind};
use syntax::ext::tt::macro_rules;
use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
use syntax::feature_gate::GateIssue;
use syntax::symbol::{Symbol, kw, sym};
use syntax_pos::{Span, DUMMY_SP};
-use std::cell::Cell;
use std::{mem, ptr};
use rustc_data_structures::sync::Lrc;
type Res = def::Res<ast::NodeId>;
-// FIXME: Merge this with `ParentScope`.
-#[derive(Clone, Debug)]
-pub struct InvocationData<'a> {
- /// The module in which the macro was invoked.
- crate module: Module<'a>,
- /// The legacy scope in which the macro was invoked.
- /// The invocation path is resolved in this scope.
- crate parent_legacy_scope: LegacyScope<'a>,
- /// The legacy scope *produced* by expanding this macro invocation,
- /// includes all the macro_rules items, other invocations, etc generated by it.
- /// `None` if the macro is not expanded yet.
- crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
-}
-
-impl<'a> InvocationData<'a> {
- pub fn root(graph_root: Module<'a>) -> Self {
- InvocationData {
- module: graph_root,
- parent_legacy_scope: LegacyScope::Empty,
- output_legacy_scope: Cell::new(None),
- }
- }
-}
-
/// Binding produced by a `macro_rules` item.
/// Not modularized, can shadow previous legacy bindings, etc.
#[derive(Debug)]
@@ -75,7 +51,7 @@
Binding(&'a LegacyBinding<'a>),
/// The scope introduced by a macro invocation that can potentially
/// create a `macro_rules!` macro definition.
- Invocation(&'a InvocationData<'a>),
+ Invocation(ExpnId),
}
// Macro namespace is separated into two sub-namespaces, one for bang macros and
@@ -120,17 +96,12 @@
}
fn get_module_scope(&mut self, id: ast::NodeId) -> ExpnId {
- let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::default(
+ let expn_id = ExpnId::fresh(Some(ExpnData::default(
ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, self.session.edition()
- ));
- let expn_id = span.ctxt().outer_expn();
+ )));
let module = self.module_map[&self.definitions.local_def_id(id)];
+ self.invocation_parent_scopes.insert(expn_id, ParentScope::module(module));
self.definitions.set_invocation_parent(expn_id, module.def_id().unwrap().index);
- self.invocations.insert(expn_id, self.arenas.alloc_invocation_data(InvocationData {
- module,
- parent_legacy_scope: LegacyScope::Empty,
- output_legacy_scope: Cell::new(None),
- }));
expn_id
}
@@ -144,29 +115,23 @@
});
}
- fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment,
- derives: &[ExpnId]) {
- fragment.visit_with(&mut DefCollector::new(&mut self.definitions, expn_id));
-
- let invocation = self.invocations[&expn_id];
- invocation.module.unresolved_invocations.borrow_mut().remove(&expn_id);
- invocation.module.unresolved_invocations.borrow_mut().extend(derives);
- let parent_def = self.definitions.invocation_parent(expn_id);
+ fn visit_ast_fragment_with_placeholders(
+ &mut self, expansion: ExpnId, fragment: &AstFragment, derives: &[ExpnId]
+ ) {
+ // Fill in some data for derives if the fragment is from a derive container.
+ // We are inside the `expansion` now, but other parent scope components are still the same.
+ let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
+ let parent_def = self.definitions.invocation_parent(expansion);
+ self.invocation_parent_scopes.extend(derives.iter().map(|&derive| (derive, parent_scope)));
for &derive_invoc_id in derives {
self.definitions.set_invocation_parent(derive_invoc_id, parent_def);
}
- self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
- let mut visitor = BuildReducedGraphVisitor {
- r: self,
- parent_scope: ParentScope {
- module: invocation.module,
- expansion: expn_id,
- legacy: invocation.parent_legacy_scope,
- derives: Vec::new(),
- },
- };
- fragment.visit_with(&mut visitor);
- invocation.output_legacy_scope.set(Some(visitor.parent_scope.legacy));
+ parent_scope.module.unresolved_invocations.borrow_mut().remove(&expansion);
+ parent_scope.module.unresolved_invocations.borrow_mut().extend(derives);
+
+ // Integrate the new AST fragment into all the definition and module structures.
+ let output_legacy_scope = self.build_reduced_graph(fragment, parent_scope);
+ self.output_legacy_scopes.insert(expansion, output_legacy_scope);
}
fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension) {
@@ -182,13 +147,14 @@
fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: ExpnId, force: bool)
-> Result<Option<Lrc<SyntaxExtension>>, Indeterminate> {
- let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
+ let parent_scope = self.invocation_parent_scopes[&invoc_id];
+ let (path, kind, derives, after_derive) = match invoc.kind {
InvocationKind::Attr { ref attr, ref derives, after_derive, .. } =>
- (&attr.path, MacroKind::Attr, derives.clone(), after_derive),
+ (&attr.path, MacroKind::Attr, self.arenas.alloc_ast_paths(derives), after_derive),
InvocationKind::Bang { ref mac, .. } =>
- (&mac.path, MacroKind::Bang, Vec::new(), false),
+ (&mac.path, MacroKind::Bang, &[][..], false),
InvocationKind::Derive { ref path, .. } =>
- (path, MacroKind::Derive, Vec::new(), false),
+ (path, MacroKind::Derive, &[][..], false),
InvocationKind::DeriveContainer { ref derives, .. } => {
// Block expansion of derives in the container until we know whether one of them
// is a built-in `Copy`. Skip the resolution if there's only one derive - either
@@ -196,10 +162,9 @@
// will automatically knows about itself.
let mut result = Ok(None);
if derives.len() > 1 {
- let parent_scope = &self.invoc_parent_scope(invoc_id, Vec::new());
for path in derives {
match self.resolve_macro_path(path, Some(MacroKind::Derive),
- parent_scope, true, force) {
+ &parent_scope, true, force) {
Ok((Some(ref ext), _)) if ext.is_derive_copy => {
self.add_derives(invoc.expansion_data.id, SpecialDerives::COPY);
return Ok(None);
@@ -213,11 +178,14 @@
}
};
- let parent_scope = &self.invoc_parent_scope(invoc_id, derives_in_scope);
+ // Derives are not included when `invocations` are collected, so we have to add them here.
+ let parent_scope = &ParentScope { derives, ..parent_scope };
let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, force)?;
let span = invoc.span();
- invoc.expansion_data.id.set_expn_info(ext.expn_info(span, fast_print_path(path)));
+ invoc.expansion_data.id.set_expn_data(
+ ext.expn_data(parent_scope.expansion, span, fast_print_path(path))
+ );
if let Res::Def(_, def_id) = res {
if after_derive {
@@ -251,20 +219,6 @@
}
impl<'a> Resolver<'a> {
- pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
- self.invoc_parent_scope(ExpnId::root(), Vec::new())
- }
-
- fn invoc_parent_scope(&self, invoc_id: ExpnId, derives: Vec<ast::Path>) -> ParentScope<'a> {
- let invoc = self.invocations[&invoc_id];
- ParentScope {
- module: invoc.module.nearest_item_scope(),
- expansion: invoc_id.parent(),
- legacy: invoc.parent_legacy_scope,
- derives,
- }
- }
-
/// Resolve macro path with error reporting and recovery.
fn smart_resolve_macro_path(
&mut self,
@@ -346,8 +300,7 @@
// Possibly apply the macro helper hack
if kind == Some(MacroKind::Bang) && path.len() == 1 &&
- path[0].ident.span.ctxt().outer_expn_info()
- .map_or(false, |info| info.local_inner_macros) {
+ path[0].ident.span.ctxt().outer_expn_data().local_inner_macros {
let root = Ident::new(kw::DollarCrate, path[0].ident.span);
path.insert(0, Segment::from_ident(root));
}
@@ -367,8 +320,8 @@
if trace {
let kind = kind.expect("macro kind must be specified if tracing is enabled");
- parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
- .push((path, path_span, kind, parent_scope.clone(), res.ok()));
+ self.multi_segment_macro_resolutions
+ .push((path, path_span, kind, *parent_scope, res.ok()));
}
self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
@@ -384,8 +337,8 @@
if trace {
let kind = kind.expect("macro kind must be specified if tracing is enabled");
- parent_scope.module.single_segment_macro_resolutions.borrow_mut()
- .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
+ self.single_segment_macro_resolutions
+ .push((path[0].ident, kind, *parent_scope, binding.ok()));
}
let res = binding.map(|binding| binding.res());
@@ -454,8 +407,8 @@
let result = match scope {
Scope::DeriveHelpers => {
let mut result = Err(Determinacy::Determined);
- for derive in &parent_scope.derives {
- let parent_scope = &ParentScope { derives: Vec::new(), ..*parent_scope };
+ for derive in parent_scope.derives {
+ let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
match this.resolve_macro_path(derive, Some(MacroKind::Derive),
parent_scope, true, force) {
Ok((Some(ext), _)) => if ext.helper_attrs.contains(&ident.name) {
@@ -475,8 +428,9 @@
Scope::MacroRules(legacy_scope) => match legacy_scope {
LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
Ok((legacy_binding.binding, Flags::MACRO_RULES)),
- LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
- Err(Determinacy::Undetermined),
+ LegacyScope::Invocation(invoc_id)
+ if !this.output_legacy_scopes.contains_key(&invoc_id) =>
+ Err(Determinacy::Undetermined),
_ => Err(Determinacy::Determined),
}
Scope::CrateRoot => {
@@ -500,7 +454,7 @@
}
}
Scope::Module(module) => {
- let adjusted_parent_scope = &ParentScope { module, ..parent_scope.clone() };
+ let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
let binding = this.resolve_ident_in_module_unadjusted_ext(
ModuleOrUniformRoot::Module(module),
ident,
@@ -575,7 +529,7 @@
false,
path_span,
) {
- if use_prelude || this.is_builtin_macro(binding.res().opt_def_id()) {
+ if use_prelude || this.is_builtin_macro(binding.res()) {
result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
}
}
@@ -694,7 +648,7 @@
}
}
- pub fn finalize_current_module_macro_resolutions(&mut self, module: Module<'a>) {
+ crate fn finalize_macro_resolutions(&mut self) {
let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
initial_res: Option<Res>, res: Res| {
if let Some(initial_res) = initial_res {
@@ -730,8 +684,7 @@
}
};
- let macro_resolutions =
- mem::take(&mut *module.multi_segment_macro_resolutions.borrow_mut());
+ let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
// FIXME: Path resolution will ICE if segment IDs present.
for seg in &mut path { seg.id = None; }
@@ -758,8 +711,7 @@
}
}
- let macro_resolutions =
- mem::take(&mut *module.single_segment_macro_resolutions.borrow_mut());
+ let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
&parent_scope, true, true, ident.span) {
@@ -784,7 +736,7 @@
}
}
- let builtin_attrs = mem::take(&mut *module.builtin_attrs.borrow_mut());
+ let builtin_attrs = mem::take(&mut self.builtin_attrs);
for (ident, parent_scope) in builtin_attrs {
let _ = self.early_resolve_ident_in_lexical_scope(
ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs
index 00e89f0fda..b49f186 100644
--- a/src/librustc_resolve/resolve_imports.rs
+++ b/src/librustc_resolve/resolve_imports.rs
@@ -1,3 +1,5 @@
+//! A bunch of methods and structures more or less related to resolving imports.
+
use ImportDirectiveSubclass::*;
use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
@@ -5,9 +7,8 @@
use crate::Determinacy::{self, *};
use crate::Namespace::{self, TypeNS, MacroNS};
use crate::{NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
-use crate::{Resolver, ResolutionError, Segment};
+use crate::{Resolver, ResolutionError, Segment, ModuleKind};
use crate::{names_to_string, module_to_string};
-use crate::ModuleKind;
use crate::diagnostics::Suggestion;
use errors::Applicability;
@@ -35,7 +36,7 @@
use log::*;
-use std::cell::{Cell, RefCell};
+use std::cell::Cell;
use std::{mem, ptr};
type Res = def::Res<NodeId>;
@@ -159,12 +160,6 @@
}
impl<'a> Resolver<'a> {
- crate fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
- -> &'a RefCell<NameResolution<'a>> {
- *module.resolutions.borrow_mut().entry((ident.modern(), ns))
- .or_insert_with(|| self.arenas.alloc_name_resolution())
- }
-
crate fn resolve_ident_in_module_unadjusted(
&mut self,
module: ModuleOrUniformRoot<'a>,
@@ -240,8 +235,6 @@
}
};
- self.populate_module_if_necessary(module);
-
let resolution = self.resolution(module, ident, ns)
.try_borrow_mut()
.map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
@@ -394,7 +387,7 @@
match ident.span.glob_adjust(module.expansion, glob_import.span) {
Some(Some(def)) => {
tmp_parent_scope =
- ParentScope { module: self.macro_def_scope(def), ..parent_scope.clone() };
+ ParentScope { module: self.macro_def_scope(def), ..*parent_scope };
adjusted_parent_scope = &tmp_parent_scope;
}
Some(None) => {}
@@ -848,7 +841,7 @@
directive.vis.set(orig_vis);
let module = match path_res {
PathResult::Module(module) => {
- // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
+ // Consistency checks, analogous to `finalize_macro_resolutions`.
if let Some(initial_module) = directive.imported_module.get() {
if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
span_bug!(directive.span, "inconsistent resolution for an import");
@@ -973,7 +966,7 @@
match binding {
Ok(binding) => {
- // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
+ // Consistency checks, analogous to `finalize_macro_resolutions`.
let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false;
if let Some(target_binding) = target_bindings[ns].get() {
@@ -1025,7 +1018,8 @@
return if all_ns_failed {
let resolutions = match module {
- ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
+ ModuleOrUniformRoot::Module(module) =>
+ Some(self.r.resolutions(module).borrow()),
_ => None,
};
let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
@@ -1263,8 +1257,6 @@
}
};
- self.r.populate_module_if_necessary(module);
-
if module.is_trait() {
self.r.session.span_err(directive.span, "items in traits are not importable.");
return;
@@ -1280,8 +1272,8 @@
// Ensure that `resolutions` isn't borrowed during `try_define`,
// since it might get updated via a glob cycle.
- let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
- resolution.borrow().binding().map(|binding| (ident, binding))
+ let bindings = self.r.resolutions(module).borrow().iter().filter_map(|(ident, resolution)| {
+ resolution.borrow().binding().map(|binding| (*ident, binding))
}).collect::<Vec<_>>();
for ((mut ident, ns), binding) in bindings {
let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
@@ -1308,7 +1300,7 @@
let mut reexports = Vec::new();
- for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
+ for (&(ident, ns), resolution) in self.r.resolutions(module).borrow().iter() {
let resolution = &mut *resolution.borrow_mut();
let binding = match resolution.binding {
Some(binding) => binding,
@@ -1367,8 +1359,8 @@
Some(ModuleOrUniformRoot::Module(module)) => module,
_ => bug!("module should exist"),
};
- let resolutions = imported_module.parent.expect("parent should exist")
- .resolutions.borrow();
+ let parent_module = imported_module.parent.expect("parent should exist");
+ let resolutions = self.r.resolutions(parent_module).borrow();
let enum_path_segment_index = directive.module_path.len() - 1;
let enum_ident = directive.module_path[enum_path_segment_index].ident;
diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs
index 9da6cd8..0bbbbb8 100644
--- a/src/librustc_save_analysis/lib.rs
+++ b/src/librustc_save_analysis/lib.rs
@@ -1156,7 +1156,7 @@
// Helper function to determine if a span came from a
// macro expansion or syntax extension.
fn generated_code(span: Span) -> bool {
- span.ctxt() != NO_EXPANSION || span.is_dummy()
+ span.from_expansion() || span.is_dummy()
}
// DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
diff --git a/src/librustc_target/spec/aarch64_wrs_vxworks.rs b/src/librustc_target/spec/aarch64_wrs_vxworks.rs
index 6ad6632..65caeac 100644
--- a/src/librustc_target/spec/aarch64_wrs_vxworks.rs
+++ b/src/librustc_target/spec/aarch64_wrs_vxworks.rs
@@ -9,15 +9,14 @@
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
- target_env: "gnu".to_string(),
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
target_os: "vxworks".to_string(),
- target_vendor: "unknown".to_string(),
+ target_env: "gnu".to_string(),
+ target_vendor: "wrs".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
abi_blacklist: super::arm_base::abi_blacklist(),
- target_mcount: "\u{1}_mcount".to_string(),
.. base
},
})
diff --git a/src/librustc_target/spec/arm_wrs_vxworks_sf.rs b/src/librustc_target/spec/arm_wrs_vxworks_sf.rs
deleted file mode 100644
index bde903d..0000000
--- a/src/librustc_target/spec/arm_wrs_vxworks_sf.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-
-pub fn target() -> TargetResult {
- let mut base = super::vxworks_base::opts();
- base.max_atomic_width = Some(64);
- Ok(Target {
- llvm_target: "arm-unknown-linux-gnueabi".to_string(),
- target_endian: "little".to_string(),
- target_pointer_width: "32".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
- arch: "arm".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
-
- options: TargetOptions {
- features: "+strict-align,+v6".to_string(),
- abi_blacklist: super::arm_base::abi_blacklist(),
- target_mcount: "\u{1}__gnu_mcount_nc".to_string(),
- .. base
- },
- })
-}
diff --git a/src/librustc_target/spec/armv7_wrs_vxworks.rs b/src/librustc_target/spec/armv7_wrs_vxworks.rs
deleted file mode 100644
index 06c51ae..0000000
--- a/src/librustc_target/spec/armv7_wrs_vxworks.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-
-// This target is for glibc Linux on ARMv7 without NEON or
-// thumb-mode. See the thumbv7neon variant for enabling both.
-
-pub fn target() -> TargetResult {
- let base = super::vxworks_base::opts();
- Ok(Target {
- llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
- target_endian: "little".to_string(),
- target_pointer_width: "32".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
- arch: "arm".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
-
- options: TargetOptions {
- // Info about features at https://wiki.debian.org/ArmHardFloatPort
- features: "+v7,+vfp3,-d32,+thumb2,-neon".to_string(),
- cpu: "generic".to_string(),
- max_atomic_width: Some(64),
- abi_blacklist: super::arm_base::abi_blacklist(),
- target_mcount: "\u{1}__gnu_mcount_nc".to_string(),
- position_independent_executables: false,
- .. base
- }
- })
-}
diff --git a/src/librustc_target/spec/arm_wrs_vxworks.rs b/src/librustc_target/spec/armv7_wrs_vxworks_eabihf.rs
similarity index 77%
rename from src/librustc_target/spec/arm_wrs_vxworks.rs
rename to src/librustc_target/spec/armv7_wrs_vxworks_eabihf.rs
index 06c51ae..9e3b24d 100644
--- a/src/librustc_target/spec/arm_wrs_vxworks.rs
+++ b/src/librustc_target/spec/armv7_wrs_vxworks_eabihf.rs
@@ -1,8 +1,5 @@
use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-// This target is for glibc Linux on ARMv7 without NEON or
-// thumb-mode. See the thumbv7neon variant for enabling both.
-
pub fn target() -> TargetResult {
let base = super::vxworks_base::opts();
Ok(Target {
@@ -14,17 +11,14 @@
arch: "arm".to_string(),
target_os: "vxworks".to_string(),
target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
+ target_vendor: "wrs".to_string(),
linker_flavor: LinkerFlavor::Gcc,
-
options: TargetOptions {
// Info about features at https://wiki.debian.org/ArmHardFloatPort
features: "+v7,+vfp3,-d32,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
- target_mcount: "\u{1}__gnu_mcount_nc".to_string(),
- position_independent_executables: false,
.. base
}
})
diff --git a/src/librustc_target/spec/i586_wrs_vxworks.rs b/src/librustc_target/spec/i586_wrs_vxworks.rs
deleted file mode 100644
index 355250e..0000000
--- a/src/librustc_target/spec/i586_wrs_vxworks.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use crate::spec::TargetResult;
-
-pub fn target() -> TargetResult {
- let mut base = super::i686_wrs_vxworks::target()?;
- base.options.cpu = "pentium".to_string();
- base.llvm_target = "i586-unknown-linux-gnu".to_string();
- Ok(base)
-}
diff --git a/src/librustc_target/spec/i686_wrs_vxworks.rs b/src/librustc_target/spec/i686_wrs_vxworks.rs
index 4b1ff5c..c5f9583 100644
--- a/src/librustc_target/spec/i686_wrs_vxworks.rs
+++ b/src/librustc_target/spec/i686_wrs_vxworks.rs
@@ -16,7 +16,7 @@
arch: "x86".to_string(),
target_os: "vxworks".to_string(),
target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
+ target_vendor: "wrs".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
diff --git a/src/librustc_target/spec/i686_wrs_vxworks_gnu.rs b/src/librustc_target/spec/i686_wrs_vxworks_gnu.rs
deleted file mode 100644
index 4b1ff5c..0000000
--- a/src/librustc_target/spec/i686_wrs_vxworks_gnu.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetResult};
-
-pub fn target() -> TargetResult {
- let mut base = super::vxworks_base::opts();
- base.cpu = "pentium4".to_string();
- base.max_atomic_width = Some(64);
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
- base.stack_probes = true;
-
- Ok(Target {
- llvm_target: "i686-unknown-linux-gnu".to_string(),
- target_endian: "little".to_string(),
- target_pointer_width: "32".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128".to_string(),
- arch: "x86".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
- options: base,
- })
-}
diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs
index 9a009ca..539e28f 100644
--- a/src/librustc_target/spec/mod.rs
+++ b/src/librustc_target/spec/mod.rs
@@ -398,6 +398,7 @@
("aarch64-unknown-openbsd", aarch64_unknown_openbsd),
("i686-unknown-openbsd", i686_unknown_openbsd),
+ ("sparc64-unknown-openbsd", sparc64_unknown_openbsd),
("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
("aarch64-unknown-netbsd", aarch64_unknown_netbsd),
@@ -492,10 +493,9 @@
("nvptx64-nvidia-cuda", nvptx64_nvidia_cuda),
- ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
("i686-wrs-vxworks", i686_wrs_vxworks),
- ("i586-wrs-vxworks", i586_wrs_vxworks),
- ("armv7-wrs-vxworks", armv7_wrs_vxworks),
+ ("x86_64-wrs-vxworks", x86_64_wrs_vxworks),
+ ("armv7-wrs-vxworks-eabihf", armv7_wrs_vxworks_eabihf),
("aarch64-wrs-vxworks", aarch64_wrs_vxworks),
("powerpc-wrs-vxworks", powerpc_wrs_vxworks),
("powerpc-wrs-vxworks-spe", powerpc_wrs_vxworks_spe),
diff --git a/src/librustc_target/spec/powerpc64_wrs_vxworks.rs b/src/librustc_target/spec/powerpc64_wrs_vxworks.rs
index a952070..27a84b9 100644
--- a/src/librustc_target/spec/powerpc64_wrs_vxworks.rs
+++ b/src/librustc_target/spec/powerpc64_wrs_vxworks.rs
@@ -15,10 +15,9 @@
arch: "powerpc64".to_string(),
target_os: "vxworks".to_string(),
target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
+ target_vendor: "wrs".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
- target_mcount: "_mcount".to_string(),
.. base
},
})
diff --git a/src/librustc_target/spec/powerpc64_wrs_vxworks_gnusf.rs b/src/librustc_target/spec/powerpc64_wrs_vxworks_gnusf.rs
deleted file mode 100644
index c2dae85..0000000
--- a/src/librustc_target/spec/powerpc64_wrs_vxworks_gnusf.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-
-pub fn target() -> TargetResult {
- let mut base = super::vxworks_base::opts();
- base.cpu = "ppc64".to_string();
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
- base.max_atomic_width = Some(64);
-
- Ok(Target {
- llvm_target: "powerpc64-unknown-linux-gnu".to_string(),
- target_endian: "big".to_string(),
- target_pointer_width: "64".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "E-m:e-i64:64-n32:64".to_string(),
- arch: "powerpc64".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "unknown".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
- options: TargetOptions {
- features: "-hard-float".to_string(),
- target_mcount: "_mcount".to_string(),
- .. base
- },
- })
-}
diff --git a/src/librustc_target/spec/powerpc_wrs_vxworks.rs b/src/librustc_target/spec/powerpc_wrs_vxworks.rs
index 2e833ee..a4d2897 100644
--- a/src/librustc_target/spec/powerpc_wrs_vxworks.rs
+++ b/src/librustc_target/spec/powerpc_wrs_vxworks.rs
@@ -19,7 +19,6 @@
linker_flavor: LinkerFlavor::Gcc,
options: TargetOptions {
features: "+secure-plt".to_string(),
- target_mcount: "_mcount".to_string(),
.. base
},
})
diff --git a/src/librustc_target/spec/powerpc_wrs_vxworks_gnusf.rs b/src/librustc_target/spec/powerpc_wrs_vxworks_gnusf.rs
deleted file mode 100644
index 43723ea..0000000
--- a/src/librustc_target/spec/powerpc_wrs_vxworks_gnusf.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-
-pub fn target() -> TargetResult {
- let mut base = super::vxworks_base::opts();
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m32".to_string());
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("--secure-plt".to_string());
- base.max_atomic_width = Some(32);
-
- Ok(Target {
- llvm_target: "powerpc-unknown-linux-gnu".to_string(),
- target_endian: "big".to_string(),
- target_pointer_width: "32".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "E-m:e-p:32:32-i64:64-n32".to_string(),
- arch: "powerpc".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "wrs".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
- options: TargetOptions {
- features: "+secure-plt,-hard-float".to_string(),
- target_mcount: "_mcount".to_string(),
- .. base
- },
- })
-}
diff --git a/src/librustc_target/spec/powerpc_wrs_vxworks_gnuspesf.rs b/src/librustc_target/spec/powerpc_wrs_vxworks_gnuspesf.rs
deleted file mode 100644
index 8f23623..0000000
--- a/src/librustc_target/spec/powerpc_wrs_vxworks_gnuspesf.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
-
-pub fn target() -> TargetResult {
- let mut base = super::vxworks_base::opts();
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-mspe".to_string());
- base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("--secure-plt".to_string());
- base.max_atomic_width = Some(32);
-
- Ok(Target {
- llvm_target: "powerpc-unknown-linux-gnuspe".to_string(),
- target_endian: "big".to_string(),
- target_pointer_width: "32".to_string(),
- target_c_int_width: "32".to_string(),
- data_layout: "E-m:e-p:32:32-i64:64-n32".to_string(),
- arch: "powerpc".to_string(),
- target_os: "vxworks".to_string(),
- target_env: "gnu".to_string(),
- target_vendor: "wrs".to_string(),
- linker_flavor: LinkerFlavor::Gcc,
- options: TargetOptions {
- // feature msync would disable instruction 'fsync' which is not supported by fsl_p1p2
- features: "+secure-plt,+msync,-hard-float".to_string(),
- target_mcount: "_mcount".to_string(),
- .. base
- },
- })
-}
diff --git a/src/librustc_target/spec/powerpc_wrs_vxworks_spe.rs b/src/librustc_target/spec/powerpc_wrs_vxworks_spe.rs
index 2305b4b..90118a14 100644
--- a/src/librustc_target/spec/powerpc_wrs_vxworks_spe.rs
+++ b/src/librustc_target/spec/powerpc_wrs_vxworks_spe.rs
@@ -20,7 +20,6 @@
options: TargetOptions {
// feature msync would disable instruction 'fsync' which is not supported by fsl_p1p2
features: "+secure-plt,+msync".to_string(),
- target_mcount: "_mcount".to_string(),
.. base
},
})
diff --git a/src/librustc_target/spec/sparc64_unknown_openbsd.rs b/src/librustc_target/spec/sparc64_unknown_openbsd.rs
new file mode 100644
index 0000000..229e062
--- /dev/null
+++ b/src/librustc_target/spec/sparc64_unknown_openbsd.rs
@@ -0,0 +1,22 @@
+use crate::spec::{LinkerFlavor, Target, TargetResult};
+
+pub fn target() -> TargetResult {
+ let mut base = super::openbsd_base::opts();
+ base.cpu = "v9".to_string();
+ base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
+ base.max_atomic_width = Some(64);
+
+ Ok(Target {
+ llvm_target: "sparc64-unknown-openbsd".to_string(),
+ target_endian: "big".to_string(),
+ target_pointer_width: "64".to_string(),
+ target_c_int_width: "32".to_string(),
+ data_layout: "E-m:e-i64:64-n32:64-S128".to_string(),
+ arch: "sparc64".to_string(),
+ target_os: "openbsd".to_string(),
+ target_env: String::new(),
+ target_vendor: "unknown".to_string(),
+ linker_flavor: LinkerFlavor::Gcc,
+ options: base,
+ })
+}
diff --git a/src/librustc_target/spec/vxworks_base.rs b/src/librustc_target/spec/vxworks_base.rs
index 6db56c5..16acd41 100644
--- a/src/librustc_target/spec/vxworks_base.rs
+++ b/src/librustc_target/spec/vxworks_base.rs
@@ -1,7 +1,11 @@
-use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};
use std::default::Default;
pub fn opts() -> TargetOptions {
+ let mut args_crt = LinkArgs::new();
+ args_crt.insert(LinkerFlavor::Gcc, vec![
+ "--static-crt".to_string(),
+ ]);
let mut args = LinkArgs::new();
args.insert(LinkerFlavor::Gcc, vec![
// We want to be able to strip as much executable code as possible
@@ -12,30 +16,25 @@
// following libraries so we're sure to pass it as one of the first
// arguments.
"-Wl,--as-needed".to_string(),
-
- // Always enable NX protection when it is available
- "-Wl,-z,noexecstack".to_string(),
- ]);
-
- let mut late_lk_args = LinkArgs::new();
- late_lk_args.insert(LinkerFlavor::Gcc, vec![
- "-lnet".to_string(),
- "-lunix".to_string(),
]);
TargetOptions {
- linker: Some("vx-cxx".to_string()),
+ linker: Some("wr-c++".to_string()),
exe_suffix: ".vxe".to_string(),
- late_link_args: late_lk_args,
dynamic_linking: true,
executables: true,
target_family: Some("unix".to_string()),
linker_is_gnu: true,
has_rpath: true,
pre_link_args: args,
- position_independent_executables: true,
- relro_level: RelroLevel::Full,
+ position_independent_executables: false,
has_elf_tls: true,
+ pre_link_args_crt: args_crt,
+ crt_static_default: true,
+ crt_static_respected: true,
+ crt_static_allows_dylibs: true,
+ // VxWorks needs to implement this to support profiling
+ target_mcount: "_mcount".to_string(),
.. Default::default()
}
}
diff --git a/src/librustc_target/spec/x86_64_wrs_vxworks.rs b/src/librustc_target/spec/x86_64_wrs_vxworks.rs
index eac7cd7..1ab2f3a 100644
--- a/src/librustc_target/spec/x86_64_wrs_vxworks.rs
+++ b/src/librustc_target/spec/x86_64_wrs_vxworks.rs
@@ -6,6 +6,7 @@
base.max_atomic_width = Some(64);
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.stack_probes = true;
+ base.disable_redzone = true;
Ok(Target {
llvm_target: "x86_64-unknown-linux-gnu".to_string(),
diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs
index ed25601..de5ba8b 100644
--- a/src/librustc_typeck/check/demand.rs
+++ b/src/librustc_typeck/check/demand.rs
@@ -347,9 +347,9 @@
sp,
);
- // Check the `expn_info()` to see if this is a macro; if so, it's hard to
- // extract the text and make a good suggestion, so don't bother.
- let is_macro = sp.ctxt().outer_expn_info().is_some();
+ // If the span is from a macro, then it's hard to extract the text
+ // and make a good suggestion, so don't bother.
+ let is_macro = sp.from_expansion();
match (&expr.node, &expected.sty, &checked_ty.sty) {
(_, &ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.sty, &check.sty) {
@@ -554,6 +554,10 @@
// FIXME(estebank): modify once we decide to suggest `as` casts
return false;
}
+ if !self.tcx.sess.source_map().span_to_filename(expr.span).is_real() {
+ // Ignore if span is from within a macro.
+ return false;
+ }
// If casting this expression to a given numeric type would be appropriate in case of a type
// mismatch.
diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs
index 9680f61..d139cd4 100644
--- a/src/librustc_typeck/check/expr.rs
+++ b/src/librustc_typeck/check/expr.rs
@@ -24,6 +24,7 @@
use syntax::util::lev_distance::find_best_match_for_name;
use rustc::hir;
use rustc::hir::{ExprKind, QPath};
+use rustc::hir::def_id::DefId;
use rustc::hir::def::{CtorKind, Res, DefKind};
use rustc::hir::ptr::P;
use rustc::infer;
@@ -1336,114 +1337,180 @@
autoderef.unambiguous_final_ty(self);
if let Some((did, field_ty)) = private_candidate {
- let struct_path = self.tcx().def_path_str(did);
- let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616,
- "field `{}` of struct `{}` is private",
- field, struct_path);
- // Also check if an accessible method exists, which is often what is meant.
- if self.method_exists(field, expr_t, expr.hir_id, false)
- && !self.expr_in_place(expr.hir_id)
- {
- self.suggest_method_call(
- &mut err,
- &format!("a method `{}` also exists, call it with parentheses", field),
- field,
- expr_t,
- expr.hir_id,
- );
- }
- err.emit();
- field_ty
- } else if field.name == kw::Invalid {
- self.tcx().types.err
- } else if self.method_exists(field, expr_t, expr.hir_id, true) {
- let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
- "attempted to take value of method `{}` on type `{}`",
- field, expr_t);
-
- if !self.expr_in_place(expr.hir_id) {
- self.suggest_method_call(
- &mut err,
- "use parentheses to call the method",
- field,
- expr_t,
- expr.hir_id
- );
- } else {
- err.help("methods are immutable and cannot be assigned to");
- }
-
- err.emit();
- self.tcx().types.err
- } else {
- if !expr_t.is_primitive_ty() {
- let mut err = self.no_such_field_err(field.span, field, expr_t);
-
- match expr_t.sty {
- ty::Adt(def, _) if !def.is_enum() => {
- if let Some(suggested_field_name) =
- Self::suggest_field_name(def.non_enum_variant(),
- &field.as_str(), vec![]) {
- err.span_suggestion(
- field.span,
- "a field with a similar name exists",
- suggested_field_name.to_string(),
- Applicability::MaybeIncorrect,
- );
- } else {
- err.span_label(field.span, "unknown field");
- let struct_variant_def = def.non_enum_variant();
- let field_names = self.available_field_names(struct_variant_def);
- if !field_names.is_empty() {
- err.note(&format!("available fields are: {}",
- self.name_series_display(field_names)));
- }
- };
- }
- ty::Array(_, len) => {
- if let (Some(len), Ok(user_index)) = (
- len.try_eval_usize(self.tcx, self.param_env),
- field.as_str().parse::<u64>()
- ) {
- let base = self.tcx.sess.source_map()
- .span_to_snippet(base.span)
- .unwrap_or_else(|_|
- self.tcx.hir().hir_to_pretty_string(base.hir_id));
- let help = "instead of using tuple indexing, use array indexing";
- let suggestion = format!("{}[{}]", base, field);
- let applicability = if len < user_index {
- Applicability::MachineApplicable
- } else {
- Applicability::MaybeIncorrect
- };
- err.span_suggestion(
- expr.span, help, suggestion, applicability
- );
- }
- }
- ty::RawPtr(..) => {
- let base = self.tcx.sess.source_map()
- .span_to_snippet(base.span)
- .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
- let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
- let suggestion = format!("(*{}).{}", base, field);
- err.span_suggestion(
- expr.span,
- &msg,
- suggestion,
- Applicability::MaybeIncorrect,
- );
- }
- _ => {}
- }
- err
- } else {
- type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
- "`{}` is a primitive type and therefore doesn't have fields",
- expr_t)
- }.emit();
- self.tcx().types.err
+ self.ban_private_field_access(expr, expr_t, field, did);
+ return field_ty;
}
+
+ if field.name == kw::Invalid {
+ } else if self.method_exists(field, expr_t, expr.hir_id, true) {
+ self.ban_take_value_of_method(expr, expr_t, field);
+ } else if !expr_t.is_primitive_ty() {
+ let mut err = self.no_such_field_err(field.span, field, expr_t);
+
+ match expr_t.sty {
+ ty::Adt(def, _) if !def.is_enum() => {
+ self.suggest_fields_on_recordish(&mut err, def, field);
+ }
+ ty::Array(_, len) => {
+ self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
+ }
+ ty::RawPtr(..) => {
+ self.suggest_first_deref_field(&mut err, expr, base, field);
+ }
+ _ => {}
+ }
+
+ if field.name == kw::Await {
+ // We know by construction that `<expr>.await` is either on Rust 2015
+ // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
+ err.note("to `.await` a `Future`, switch to Rust 2018");
+ err.help("set `edition = \"2018\"` in `Cargo.toml`");
+ err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
+ }
+
+ err.emit();
+ } else {
+ type_error_struct!(
+ self.tcx().sess,
+ field.span,
+ expr_t,
+ E0610,
+ "`{}` is a primitive type and therefore doesn't have fields",
+ expr_t
+ )
+ .emit();
+ }
+
+ self.tcx().types.err
+ }
+
+ fn ban_private_field_access(
+ &self,
+ expr: &hir::Expr,
+ expr_t: Ty<'tcx>,
+ field: ast::Ident,
+ base_did: DefId,
+ ) {
+ let struct_path = self.tcx().def_path_str(base_did);
+ let mut err = struct_span_err!(
+ self.tcx().sess,
+ expr.span,
+ E0616,
+ "field `{}` of struct `{}` is private",
+ field,
+ struct_path
+ );
+ // Also check if an accessible method exists, which is often what is meant.
+ if self.method_exists(field, expr_t, expr.hir_id, false)
+ && !self.expr_in_place(expr.hir_id)
+ {
+ self.suggest_method_call(
+ &mut err,
+ &format!("a method `{}` also exists, call it with parentheses", field),
+ field,
+ expr_t,
+ expr.hir_id,
+ );
+ }
+ err.emit();
+ }
+
+ fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
+ let mut err = type_error_struct!(
+ self.tcx().sess,
+ field.span,
+ expr_t,
+ E0615,
+ "attempted to take value of method `{}` on type `{}`",
+ field,
+ expr_t
+ );
+
+ if !self.expr_in_place(expr.hir_id) {
+ self.suggest_method_call(
+ &mut err,
+ "use parentheses to call the method",
+ field,
+ expr_t,
+ expr.hir_id
+ );
+ } else {
+ err.help("methods are immutable and cannot be assigned to");
+ }
+
+ err.emit();
+ }
+
+ fn suggest_fields_on_recordish(
+ &self,
+ err: &mut DiagnosticBuilder<'_>,
+ def: &'tcx ty::AdtDef,
+ field: ast::Ident,
+ ) {
+ if let Some(suggested_field_name) =
+ Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
+ {
+ err.span_suggestion(
+ field.span,
+ "a field with a similar name exists",
+ suggested_field_name.to_string(),
+ Applicability::MaybeIncorrect,
+ );
+ } else {
+ err.span_label(field.span, "unknown field");
+ let struct_variant_def = def.non_enum_variant();
+ let field_names = self.available_field_names(struct_variant_def);
+ if !field_names.is_empty() {
+ err.note(&format!("available fields are: {}",
+ self.name_series_display(field_names)));
+ }
+ }
+ }
+
+ fn maybe_suggest_array_indexing(
+ &self,
+ err: &mut DiagnosticBuilder<'_>,
+ expr: &hir::Expr,
+ base: &hir::Expr,
+ field: ast::Ident,
+ len: &ty::Const<'tcx>,
+ ) {
+ if let (Some(len), Ok(user_index)) = (
+ len.try_eval_usize(self.tcx, self.param_env),
+ field.as_str().parse::<u64>()
+ ) {
+ let base = self.tcx.sess.source_map()
+ .span_to_snippet(base.span)
+ .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
+ let help = "instead of using tuple indexing, use array indexing";
+ let suggestion = format!("{}[{}]", base, field);
+ let applicability = if len < user_index {
+ Applicability::MachineApplicable
+ } else {
+ Applicability::MaybeIncorrect
+ };
+ err.span_suggestion(expr.span, help, suggestion, applicability);
+ }
+ }
+
+ fn suggest_first_deref_field(
+ &self,
+ err: &mut DiagnosticBuilder<'_>,
+ expr: &hir::Expr,
+ base: &hir::Expr,
+ field: ast::Ident,
+ ) {
+ let base = self.tcx.sess.source_map()
+ .span_to_snippet(base.span)
+ .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
+ let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
+ let suggestion = format!("(*{}).{}", base, field);
+ err.span_suggestion(
+ expr.span,
+ &msg,
+ suggestion,
+ Applicability::MaybeIncorrect,
+ );
}
fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs
index 8bb24ee..dfbf8bc 100644
--- a/src/librustc_typeck/check/intrinsic.rs
+++ b/src/librustc_typeck/check/intrinsic.rs
@@ -67,7 +67,7 @@
match intrinsic {
"size_of" | "min_align_of" | "needs_drop" |
"add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
- "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
+ "wrapping_add" | "wrapping_sub" | "wrapping_mul" |
"saturating_add" | "saturating_sub" |
"rotate_left" | "rotate_right" |
"ctpop" | "ctlz" | "cttz" | "bswap" | "bitreverse" |
@@ -314,7 +314,7 @@
(1, vec![param(0), param(0)], param(0)),
"unchecked_add" | "unchecked_sub" | "unchecked_mul" =>
(1, vec![param(0), param(0)], param(0)),
- "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
+ "wrapping_add" | "wrapping_sub" | "wrapping_mul" =>
(1, vec![param(0), param(0)], param(0)),
"saturating_add" | "saturating_sub" =>
(1, vec![param(0), param(0)], param(0)),
diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs
index 4a5eba1..53024d9 100644
--- a/src/librustc_typeck/check/method/suggest.rs
+++ b/src/librustc_typeck/check/method/suggest.rs
@@ -985,7 +985,7 @@
hir::ItemKind::Use(..) => {
// Don't suggest placing a `use` before the prelude
// import or other generated ones.
- if item.span.ctxt().outer_expn_info().is_none() {
+ if !item.span.from_expansion() {
self.span = Some(item.span.shrink_to_lo());
self.found_use = true;
return;
@@ -995,7 +995,7 @@
hir::ItemKind::ExternCrate(_) => {}
// ...but do place them before the first other item.
_ => if self.span.map_or(true, |span| item.span < span ) {
- if item.span.ctxt().outer_expn_info().is_none() {
+ if !item.span.from_expansion() {
// Don't insert between attributes and an item.
if item.attrs.is_empty() {
self.span = Some(item.span.shrink_to_lo());
diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs
index 92f8fb3..fc1ee64 100644
--- a/src/librustc_typeck/check/mod.rs
+++ b/src/librustc_typeck/check/mod.rs
@@ -2943,7 +2943,7 @@
(PlaceOp::Index, false) => (self.tcx.lang_items().index_trait(), sym::index),
(PlaceOp::Index, true) => (self.tcx.lang_items().index_mut_trait(), sym::index_mut),
};
- (tr, ast::Ident::with_empty_ctxt(name))
+ (tr, ast::Ident::with_dummy_span(name))
}
fn try_overloaded_place_op(&self,
diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs
index b2c0e34..28a1ccd 100644
--- a/src/librustc_typeck/check/wfcheck.rs
+++ b/src/librustc_typeck/check/wfcheck.rs
@@ -203,7 +203,6 @@
fcx.register_wf_obligation(ty, span, code.clone());
}
ty::AssocKind::Method => {
- reject_shadowing_parameters(fcx.tcx, item.def_id);
let sig = fcx.tcx.fn_sig(item.def_id);
let sig = fcx.normalize_associated_types_in(span, &sig);
check_fn_or_method(tcx, fcx, span, sig,
@@ -998,34 +997,6 @@
err.emit();
}
-fn reject_shadowing_parameters(tcx: TyCtxt<'_>, def_id: DefId) {
- let generics = tcx.generics_of(def_id);
- let parent = tcx.generics_of(generics.parent.unwrap());
- let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
- GenericParamDefKind::Lifetime => None,
- GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
- Some((param.name, param.def_id))
- }
- }).collect();
-
- for method_param in &generics.params {
- // Shadowing is checked in `resolve_lifetime`.
- if let GenericParamDefKind::Lifetime = method_param.kind {
- continue
- }
- if impl_params.contains_key(&method_param.name) {
- // Tighten up the span to focus on only the shadowing type.
- let type_span = tcx.def_span(method_param.def_id);
-
- // The expectation here is that the original trait declaration is
- // local so it should be okay to just unwrap everything.
- let trait_def_id = impl_params[&method_param.name];
- let trait_decl_span = tcx.def_span(trait_def_id);
- error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
- }
- }
-}
-
/// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
/// aren't true.
fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
@@ -1152,12 +1123,3 @@
err.span_label(span, "unused parameter");
err
}
-
-fn error_194(tcx: TyCtxt<'_>, span: Span, trait_decl_span: Span, name: &str) {
- struct_span_err!(tcx.sess, span, E0194,
- "type parameter `{}` shadows another type parameter of the same name",
- name)
- .span_label(span, "shadows another type parameter")
- .span_label(trait_decl_span, format!("first `{}` declared here", name))
- .emit();
-}
diff --git a/src/librustc_typeck/error_codes.rs b/src/librustc_typeck/error_codes.rs
index 90118a9..ca9ce3d 100644
--- a/src/librustc_typeck/error_codes.rs
+++ b/src/librustc_typeck/error_codes.rs
@@ -1718,22 +1718,6 @@
reason to also specify it in a `where` clause.
"##,
-E0194: r##"
-A type parameter was declared which shadows an existing one. An example of this
-error:
-
-```compile_fail,E0194
-trait Foo<T> {
- fn do_something(&self) -> T;
- fn do_something_else<T: Clone>(&self, bar: T);
-}
-```
-
-In this example, the trait `Foo` and the trait method `do_something_else` both
-define a type parameter `T`. This is not allowed: if the method wishes to
-define a type parameter, it must use a different name for it.
-"##,
-
E0195: r##"
Your method's lifetime parameters do not match the trait declaration.
Erroneous code example:
@@ -4837,6 +4821,7 @@
// E0188, // can not cast an immutable reference to a mutable pointer
// E0189, // deprecated: can only cast a boxed pointer to a boxed object
// E0190, // deprecated: can only cast a &-pointer to an &-object
+// E0194, // merged into E0403
// E0196, // cannot determine a type for this closure
E0203, // type parameter has more than one relaxed default bound,
// and only one is supported
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index d5becd2..fede9e9 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -930,7 +930,7 @@
if attr.check_name(sym::enable) {
if let Some(feat) = attr.value_str() {
let meta = attr::mk_name_value_item_str(
- Ident::with_empty_ctxt(sym::target_feature), feat, DUMMY_SP
+ Ident::with_dummy_span(sym::target_feature), feat, DUMMY_SP
);
if let Ok(feat_cfg) = Cfg::parse(&meta) {
cfg &= feat_cfg;
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index 5c9fac7..c73c464 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -4,6 +4,7 @@
use rustc::hir;
use rustc::lint as lint;
use rustc::ty;
+use rustc_resolve::ParentScope;
use syntax;
use syntax::ast::{self, Ident};
use syntax::ext::base::SyntaxExtensionKind;
@@ -431,7 +432,7 @@
let path = ast::Path::from_ident(Ident::from_str(path_str));
cx.enter_resolver(|resolver| {
if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
- &path, None, &resolver.dummy_parent_scope(), false, false
+ &path, None, &ParentScope::module(resolver.graph_root), false, false
) {
if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
return Some(res.map_id(|_| panic!("unexpected id")));
diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml
index 5334c4d..3288d0b 100644
--- a/src/libstd/Cargo.toml
+++ b/src/libstd/Cargo.toml
@@ -23,7 +23,7 @@
compiler_builtins = { version = "0.1.16" }
profiler_builtins = { path = "../libprofiler_builtins", optional = true }
unwind = { path = "../libunwind" }
-hashbrown = { version = "0.4.0", features = ['rustc-dep-of-std'] }
+hashbrown = { version = "0.5.0", features = ['rustc-dep-of-std'] }
[dependencies.backtrace]
version = "0.3.34"
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index 1e28ee8..a053898 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -6,7 +6,7 @@
use crate::borrow::Borrow;
use crate::cell::Cell;
-use crate::collections::CollectionAllocErr;
+use crate::collections::TryReserveError;
use crate::fmt::{self, Debug};
#[allow(deprecated)]
use crate::hash::{BuildHasher, Hash, Hasher, SipHasher13};
@@ -588,7 +588,7 @@
/// ```
#[inline]
#[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
- pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.base
.try_reserve(additional)
.map_err(map_collection_alloc_err)
@@ -2542,10 +2542,13 @@
}
#[inline]
-fn map_collection_alloc_err(err: hashbrown::CollectionAllocErr) -> CollectionAllocErr {
+fn map_collection_alloc_err(err: hashbrown::CollectionAllocErr) -> TryReserveError {
match err {
- hashbrown::CollectionAllocErr::CapacityOverflow => CollectionAllocErr::CapacityOverflow,
- hashbrown::CollectionAllocErr::AllocErr => CollectionAllocErr::AllocErr,
+ hashbrown::CollectionAllocErr::CapacityOverflow => TryReserveError::CapacityOverflow,
+ hashbrown::CollectionAllocErr::AllocErr { layout } => TryReserveError::AllocError {
+ layout,
+ non_exhaustive: (),
+ },
}
}
@@ -2605,7 +2608,7 @@
use super::RandomState;
use crate::cell::RefCell;
use rand::{thread_rng, Rng};
- use realstd::collections::CollectionAllocErr::*;
+ use realstd::collections::TryReserveError::*;
use realstd::usize;
// https://github.com/rust-lang/rust/issues/62301
@@ -3405,7 +3408,7 @@
panic!("usize::MAX should trigger an overflow!");
}
- if let Err(AllocErr) = empty_bytes.try_reserve(MAX_USIZE / 8) {
+ if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_USIZE / 8) {
} else {
panic!("usize::MAX / 8 should trigger an OOM!")
}
diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs
index d243412..26db651 100644
--- a/src/libstd/collections/hash/set.rs
+++ b/src/libstd/collections/hash/set.rs
@@ -1,5 +1,5 @@
use crate::borrow::Borrow;
-use crate::collections::CollectionAllocErr;
+use crate::collections::TryReserveError;
use crate::fmt;
use crate::hash::{Hash, BuildHasher};
use crate::iter::{Chain, FromIterator, FusedIterator};
@@ -383,7 +383,7 @@
/// ```
#[inline]
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
- pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
+ pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.map.try_reserve(additional)
}
diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs
index 15c2532..f595746 100644
--- a/src/libstd/collections/mod.rs
+++ b/src/libstd/collections/mod.rs
@@ -427,7 +427,7 @@
pub use self::hash_set::HashSet;
#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
-pub use alloc_crate::collections::CollectionAllocErr;
+pub use alloc_crate::collections::TryReserveError;
mod hash;
diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs
index 1f48315..c3882ba 100644
--- a/src/libstd/lib.rs
+++ b/src/libstd/lib.rs
@@ -228,7 +228,6 @@
// std is implemented with unstable features, many of which are internal
// compiler details that will never be stable
// NB: the following list is sorted to minimize merge conflicts.
-#![feature(__rust_unstable_column)]
#![feature(alloc_error_handler)]
#![feature(alloc_layout_extra)]
#![feature(allocator_api)]
@@ -251,6 +250,7 @@
#![feature(concat_idents)]
#![feature(const_cstr_unchecked)]
#![feature(const_raw_ptr_deref)]
+#![feature(container_error_extra)]
#![feature(core_intrinsics)]
#![feature(custom_test_frameworks)]
#![feature(doc_alias)]
@@ -550,7 +550,6 @@
option_env,
stringify,
// Unstable
- __rust_unstable_column,
asm,
concat_idents,
format_args_nl,
diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs
index f200093..cbeaf20 100644
--- a/src/libstd/macros.rs
+++ b/src/libstd/macros.rs
@@ -53,20 +53,20 @@
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
-#[allow_internal_unstable(__rust_unstable_column, libstd_sys_internals)]
+#[allow_internal_unstable(libstd_sys_internals)]
macro_rules! panic {
() => ({
$crate::panic!("explicit panic")
});
($msg:expr) => ({
- $crate::rt::begin_panic($msg, &(file!(), line!(), __rust_unstable_column!()))
+ $crate::rt::begin_panic($msg, &($crate::file!(), $crate::line!(), $crate::column!()))
});
($msg:expr,) => ({
$crate::panic!($msg)
});
($fmt:expr, $($arg:tt)+) => ({
- $crate::rt::begin_panic_fmt(&format_args!($fmt, $($arg)+),
- &(file!(), line!(), __rust_unstable_column!()))
+ $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+),
+ &($crate::file!(), $crate::line!(), $crate::column!()))
});
}
@@ -113,7 +113,7 @@
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable(print_internals)]
macro_rules! print {
- ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
+ ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
}
/// Prints to the standard output, with a newline.
@@ -147,7 +147,7 @@
macro_rules! println {
() => ($crate::print!("\n"));
($($arg:tt)*) => ({
- $crate::io::_print(format_args_nl!($($arg)*));
+ $crate::io::_print($crate::format_args_nl!($($arg)*));
})
}
@@ -176,7 +176,7 @@
#[stable(feature = "eprint", since = "1.19.0")]
#[allow_internal_unstable(print_internals)]
macro_rules! eprint {
- ($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
+ ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
}
/// Prints to the standard error, with a newline.
@@ -206,7 +206,7 @@
macro_rules! eprintln {
() => ($crate::eprint!("\n"));
($($arg:tt)*) => ({
- $crate::io::_eprint(format_args_nl!($($arg)*));
+ $crate::io::_eprint($crate::format_args_nl!($($arg)*));
})
}
@@ -337,7 +337,7 @@
#[stable(feature = "dbg_macro", since = "1.32.0")]
macro_rules! dbg {
() => {
- $crate::eprintln!("[{}:{}]", file!(), line!());
+ $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
};
($val:expr) => {
// Use of `match` here is intentional because it affects the lifetimes
@@ -345,7 +345,7 @@
match $val {
tmp => {
$crate::eprintln!("[{}:{}] {} = {:#?}",
- file!(), line!(), stringify!($val), &tmp);
+ $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
tmp
}
}
diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs
index 752c620..3e4cf91 100644
--- a/src/libstd/prelude/v1.rs
+++ b/src/libstd/prelude/v1.rs
@@ -40,7 +40,6 @@
#[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
#[doc(no_inline)]
pub use core::prelude::v1::{
- __rust_unstable_column,
asm,
assert,
cfg,
diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs
index 3ae37f7..9091607 100644
--- a/src/libsyntax/ast.rs
+++ b/src/libsyntax/ast.rs
@@ -5,7 +5,7 @@
pub use crate::symbol::{Ident, Symbol as Name};
pub use crate::util::parser::ExprPrecedence;
-use crate::ext::hygiene::{ExpnId, SyntaxContext};
+use crate::ext::hygiene::ExpnId;
use crate::parse::token::{self, DelimToken};
use crate::print::pprust;
use crate::ptr::P;
@@ -1782,7 +1782,6 @@
pub volatile: bool,
pub alignstack: bool,
pub dialect: AsmDialect,
- pub ctxt: SyntaxContext,
}
/// An argument in a function header.
@@ -2030,7 +2029,6 @@
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
pub struct GlobalAsm {
pub asm: Symbol,
- pub ctxt: SyntaxContext,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs
index 85c661d..bcf03b5 100644
--- a/src/libsyntax/attr/mod.rs
+++ b/src/libsyntax/attr/mod.rs
@@ -327,7 +327,7 @@
if self.is_sugared_doc {
let comment = self.value_str().unwrap();
let meta = mk_name_value_item_str(
- Ident::with_empty_ctxt(sym::doc),
+ Ident::with_dummy_span(sym::doc),
Symbol::intern(&strip_doc_comment_decoration(&comment.as_str())),
DUMMY_SP,
);
@@ -412,7 +412,7 @@
Attribute {
id: mk_attr_id(),
style,
- path: Path::from_ident(Ident::with_empty_ctxt(sym::doc).with_span_pos(span)),
+ path: Path::from_ident(Ident::with_dummy_span(sym::doc).with_span_pos(span)),
tokens: MetaItemKind::NameValue(lit).tokens(span),
is_sugared_doc: true,
span,
diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs
index 80591ad..9618b5a 100644
--- a/src/libsyntax/diagnostics/plugin.rs
+++ b/src/libsyntax/diagnostics/plugin.rs
@@ -172,7 +172,7 @@
(descriptions.len(), ecx.expr_vec(span, descriptions))
});
- let static_ = ecx.lifetime(span, Ident::with_empty_ctxt(kw::StaticLifetime));
+ let static_ = ecx.lifetime(span, Ident::with_dummy_span(kw::StaticLifetime));
let ty_str = ecx.ty_rptr(
span,
ecx.ty_ident(span, ecx.ident_of("str")),
diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs
index edeca04..fb1bf4d 100644
--- a/src/libsyntax/ext/base.rs
+++ b/src/libsyntax/ext/base.rs
@@ -15,7 +15,7 @@
use errors::{DiagnosticBuilder, DiagnosticId};
use smallvec::{smallvec, SmallVec};
use syntax_pos::{FileName, Span, MultiSpan, DUMMY_SP};
-use syntax_pos::hygiene::{ExpnInfo, ExpnKind};
+use syntax_pos::hygiene::{ExpnData, ExpnKind};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{self, Lrc};
@@ -640,10 +640,11 @@
SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
}
- pub fn expn_info(&self, call_site: Span, descr: Symbol) -> ExpnInfo {
- ExpnInfo {
- call_site,
+ pub fn expn_data(&self, parent: ExpnId, call_site: Span, descr: Symbol) -> ExpnData {
+ ExpnData {
kind: ExpnKind::Macro(self.macro_kind(), descr),
+ parent,
+ call_site,
def_site: self.span,
default_transparency: self.default_transparency,
allow_internal_unstable: self.allow_internal_unstable.clone(),
@@ -707,7 +708,7 @@
/// One of these is made during expansion and incrementally updated as we go;
/// when a macro expansion occurs, the resulting nodes have the `backtrace()
-/// -> expn_info` of their expansion context stored into their span.
+/// -> expn_data` of their expansion context stored into their span.
pub struct ExtCtxt<'a> {
pub parse_sess: &'a parse::ParseSess,
pub ecfg: expand::ExpansionConfig<'a>,
@@ -756,13 +757,10 @@
pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
pub fn call_site(&self) -> Span {
- match self.current_expansion.id.expn_info() {
- Some(expn_info) => expn_info.call_site,
- None => DUMMY_SP,
- }
+ self.current_expansion.id.expn_data().call_site
}
pub fn backtrace(&self) -> SyntaxContext {
- SyntaxContext::empty().apply_mark(self.current_expansion.id)
+ SyntaxContext::root().apply_mark(self.current_expansion.id)
}
/// Returns span for the macro which originally caused the current expansion to happen.
@@ -772,17 +770,13 @@
let mut ctxt = self.backtrace();
let mut last_macro = None;
loop {
- if ctxt.outer_expn_info().map_or(None, |info| {
- if info.kind.descr() == sym::include {
- // Stop going up the backtrace once include! is encountered
- return None;
- }
- ctxt = info.call_site.ctxt();
- last_macro = Some(info.call_site);
- Some(())
- }).is_none() {
- break
+ let expn_data = ctxt.outer_expn_data();
+ // Stop going up the backtrace once include! is encountered
+ if expn_data.is_root() || expn_data.kind.descr() == sym::include {
+ break;
}
+ ctxt = expn_data.call_site.ctxt();
+ last_macro = Some(expn_data.call_site);
}
last_macro
}
@@ -872,7 +866,7 @@
pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
let def_site = DUMMY_SP.apply_mark(self.current_expansion.id);
iter::once(Ident::new(kw::DollarCrate, def_site))
- .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
+ .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
.collect()
}
pub fn name_of(&self, st: &str) -> ast::Name {
diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs
index 38f46ee..e2ac4d5 100644
--- a/src/libsyntax/ext/build.rs
+++ b/src/libsyntax/ext/build.rs
@@ -340,7 +340,7 @@
self.expr_path(self.path_ident(span, id))
}
pub fn expr_self(&self, span: Span) -> P<ast::Expr> {
- self.expr_ident(span, Ident::with_empty_ctxt(kw::SelfLower))
+ self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower))
}
pub fn expr_binary(&self, sp: Span, op: ast::BinOpKind,
diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs
index 9798394..dac4029 100644
--- a/src/libsyntax/ext/expand.rs
+++ b/src/libsyntax/ext/expand.rs
@@ -5,7 +5,7 @@
use crate::config::StripUnconfigured;
use crate::ext::base::*;
use crate::ext::proc_macro::collect_derives;
-use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnInfo, ExpnKind};
+use crate::ext::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
use crate::ext::tt::macro_rules::annotate_err_with_kind;
use crate::ext::placeholders::{placeholder, PlaceholderExpander};
use crate::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
@@ -25,7 +25,6 @@
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc;
-use std::fs;
use std::io::ErrorKind;
use std::{iter, mem};
use std::ops::DerefMut;
@@ -353,7 +352,7 @@
derives.reserve(traits.len());
invocations.reserve(traits.len());
for path in traits {
- let expn_id = ExpnId::fresh(self.cx.current_expansion.id, None);
+ let expn_id = ExpnId::fresh(None);
derives.push(expn_id);
invocations.push(Invocation {
kind: InvocationKind::Derive { path, item: item.clone() },
@@ -475,11 +474,11 @@
}
if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
- let info = self.cx.current_expansion.id.expn_info().unwrap();
+ let expn_data = self.cx.current_expansion.id.expn_data();
let suggested_limit = self.cx.ecfg.recursion_limit * 2;
- let mut err = self.cx.struct_span_err(info.call_site,
+ let mut err = self.cx.struct_span_err(expn_data.call_site,
&format!("recursion limit reached while expanding the macro `{}`",
- info.kind.descr()));
+ expn_data.kind.descr()));
err.help(&format!(
"consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
suggested_limit));
@@ -759,7 +758,7 @@
let msg = format!("macro expansion ignores token `{}` and any following",
self.this_token_to_string());
// Avoid emitting backtrace info twice.
- let def_site_span = self.token.span.with_ctxt(SyntaxContext::empty());
+ let def_site_span = self.token.span.with_ctxt(SyntaxContext::root());
let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
err.span_label(span, "caused by the macro expansion here");
let msg = format!(
@@ -796,17 +795,20 @@
impl<'a, 'b> InvocationCollector<'a, 'b> {
fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
- // Expansion info for all the collected invocations is set upon their resolution,
+ // Expansion data for all the collected invocations is set upon their resolution,
// with exception of the derive container case which is not resolved and can get
- // its expansion info immediately.
- let expn_info = match &kind {
- InvocationKind::DeriveContainer { item, .. } => Some(ExpnInfo::default(
- ExpnKind::Macro(MacroKind::Attr, sym::derive),
- item.span(), self.cx.parse_sess.edition,
- )),
+ // its expansion data immediately.
+ let expn_data = match &kind {
+ InvocationKind::DeriveContainer { item, .. } => Some(ExpnData {
+ parent: self.cx.current_expansion.id,
+ ..ExpnData::default(
+ ExpnKind::Macro(MacroKind::Attr, sym::derive),
+ item.span(), self.cx.parse_sess.edition,
+ )
+ }),
_ => None,
};
- let expn_id = ExpnId::fresh(self.cx.current_expansion.id, expn_info);
+ let expn_id = ExpnId::fresh(expn_data);
self.invocations.push(Invocation {
kind,
fragment_kind,
@@ -1238,32 +1240,30 @@
}
let filename = self.cx.resolve_path(&*file.as_str(), it.span());
- match fs::read_to_string(&filename) {
- Ok(src) => {
- let src_interned = Symbol::intern(&src);
-
- // Add this input file to the code map to make it available as
- // dependency information
- self.cx.source_map().new_source_file(filename.into(), src);
+ match self.cx.source_map().load_file(&filename) {
+ Ok(source_file) => {
+ let src = source_file.src.as_ref()
+ .expect("freshly loaded file should have a source");
+ let src_interned = Symbol::intern(src.as_str());
let include_info = vec![
ast::NestedMetaItem::MetaItem(
attr::mk_name_value_item_str(
- Ident::with_empty_ctxt(sym::file),
+ Ident::with_dummy_span(sym::file),
file,
DUMMY_SP,
),
),
ast::NestedMetaItem::MetaItem(
attr::mk_name_value_item_str(
- Ident::with_empty_ctxt(sym::contents),
+ Ident::with_dummy_span(sym::contents),
src_interned,
DUMMY_SP,
),
),
];
- let include_ident = Ident::with_empty_ctxt(sym::include);
+ let include_ident = Ident::with_dummy_span(sym::include);
let item = attr::mk_list_item(include_ident, include_info);
items.push(ast::NestedMetaItem::MetaItem(item));
}
@@ -1325,7 +1325,7 @@
}
}
- let meta = attr::mk_list_item(Ident::with_empty_ctxt(sym::doc), items);
+ let meta = attr::mk_list_item(Ident::with_dummy_span(sym::doc), items);
*at = attr::Attribute {
span: at.span,
id: at.id,
diff --git a/src/libsyntax/ext/proc_macro_server.rs b/src/libsyntax/ext/proc_macro_server.rs
index 36621ce..1619fa6 100644
--- a/src/libsyntax/ext/proc_macro_server.rs
+++ b/src/libsyntax/ext/proc_macro_server.rs
@@ -362,10 +362,10 @@
impl<'a> Rustc<'a> {
pub fn new(cx: &'a ExtCtxt<'_>) -> Self {
// No way to determine def location for a proc macro right now, so use call location.
- let location = cx.current_expansion.id.expn_info().unwrap().call_site;
+ let location = cx.current_expansion.id.expn_data().call_site;
let to_span = |transparency| {
location.with_ctxt(
- SyntaxContext::empty()
+ SyntaxContext::root()
.apply_mark_with_transparency(cx.current_expansion.id, transparency),
)
};
@@ -677,7 +677,7 @@
self.sess.source_map().lookup_char_pos(span.lo()).file
}
fn parent(&mut self, span: Self::Span) -> Option<Self::Span> {
- span.ctxt().outer_expn_info().map(|i| i.call_site)
+ span.parent()
}
fn source(&mut self, span: Self::Span) -> Self::Span {
span.source_callsite()
diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs
index 8a56ae1..1a87a90 100644
--- a/src/libsyntax/feature_gate.rs
+++ b/src/libsyntax/feature_gate.rs
@@ -30,7 +30,6 @@
use errors::{Applicability, DiagnosticBuilder, Handler};
use rustc_data_structures::fx::FxHashMap;
-use rustc_data_structures::sync::Lock;
use rustc_target::spec::abi::Abi;
use syntax_pos::{Span, DUMMY_SP, MultiSpan};
use log::debug;
@@ -2088,11 +2087,6 @@
"type ascription is experimental");
}
}
- ast::ExprKind::Yield(..) => {
- gate_feature_post!(&self, generators,
- e.span,
- "yield syntax is experimental");
- }
ast::ExprKind::TryBlock(_) => {
gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
}
@@ -2427,10 +2421,6 @@
features
}
-fn for_each_in_lock<T>(vec: &Lock<Vec<T>>, f: impl Fn(&T)) {
- vec.borrow().iter().for_each(f);
-}
-
pub fn check_crate(krate: &ast::Crate,
sess: &ParseSess,
features: &Features,
@@ -2443,26 +2433,16 @@
plugin_attributes,
};
- for_each_in_lock(&sess.param_attr_spans, |span| gate_feature!(
- &ctx,
- param_attrs,
- *span,
- "attributes on function parameters are unstable"
- ));
+ macro_rules! gate_all {
+ ($spans:ident, $gate:ident, $msg:literal) => {
+ for span in &*sess.$spans.borrow() { gate_feature!(&ctx, $gate, *span, $msg); }
+ }
+ }
- for_each_in_lock(&sess.let_chains_spans, |span| gate_feature!(
- &ctx,
- let_chains,
- *span,
- "`let` expressions in this position are experimental"
- ));
-
- for_each_in_lock(&sess.async_closure_spans, |span| gate_feature!(
- &ctx,
- async_closure,
- *span,
- "async closures are unstable"
- ));
+ gate_all!(param_attr_spans, param_attrs, "attributes on function parameters are unstable");
+ gate_all!(let_chains_spans, let_chains, "`let` expressions in this position are experimental");
+ gate_all!(async_closure_spans, async_closure, "async closures are unstable");
+ gate_all!(yield_spans, generators, "yield syntax is experimental");
let visitor = &mut PostExpansionVisitor {
context: &ctx,
diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs
index acafe32..18d4a64 100644
--- a/src/libsyntax/mut_visit.rs
+++ b/src/libsyntax/mut_visit.rs
@@ -1182,7 +1182,7 @@
}
ExprKind::InlineAsm(asm) => {
let InlineAsm { asm: _, asm_str_style: _, outputs, inputs, clobbers: _, volatile: _,
- alignstack: _, dialect: _, ctxt: _ } = asm.deref_mut();
+ alignstack: _, dialect: _ } = asm.deref_mut();
for out in outputs {
let InlineAsmOutput { constraint: _, expr, is_rw: _, is_indirect: _ } = out;
vis.visit_expr(expr);
diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs
index e86d4c7..17629d3 100644
--- a/src/libsyntax/parse/lexer/mod.rs
+++ b/src/libsyntax/parse/lexer/mod.rs
@@ -4,7 +4,7 @@
use crate::parse::unescape_error_reporting::{emit_unescape_error, push_escaped_char};
use errors::{FatalError, DiagnosticBuilder};
-use syntax_pos::{BytePos, Pos, Span, NO_EXPANSION};
+use syntax_pos::{BytePos, Pos, Span};
use rustc_lexer::Base;
use rustc_lexer::unescape;
@@ -84,7 +84,7 @@
fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
- self.override_span.unwrap_or_else(|| Span::new(lo, hi, NO_EXPANSION))
+ self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi))
}
/// Returns the next token, including trivia like whitespace or comments.
diff --git a/src/libsyntax/parse/lexer/tests.rs b/src/libsyntax/parse/lexer/tests.rs
index fc47e4f..9457014 100644
--- a/src/libsyntax/parse/lexer/tests.rs
+++ b/src/libsyntax/parse/lexer/tests.rs
@@ -1,41 +1,17 @@
use super::*;
-use crate::ast::CrateConfig;
use crate::symbol::Symbol;
use crate::source_map::{SourceMap, FilePathMapping};
-use crate::feature_gate::UnstableFeatures;
use crate::parse::token;
-use crate::diagnostics::plugin::ErrorMap;
use crate::with_default_globals;
use std::io;
use std::path::PathBuf;
-use syntax_pos::{BytePos, Span, NO_EXPANSION, edition::Edition};
-use rustc_data_structures::fx::{FxHashSet, FxHashMap};
-use rustc_data_structures::sync::{Lock, Once};
+use errors::{Handler, emitter::EmitterWriter};
+use syntax_pos::{BytePos, Span};
fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
- let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
- Some(sm.clone()),
- false,
- false,
- false);
- ParseSess {
- span_diagnostic: errors::Handler::with_emitter(true, None, Box::new(emitter)),
- unstable_features: UnstableFeatures::from_environment(),
- config: CrateConfig::default(),
- included_mod_stack: Lock::new(Vec::new()),
- source_map: sm,
- missing_fragment_specifiers: Lock::new(FxHashSet::default()),
- raw_identifier_spans: Lock::new(Vec::new()),
- registered_diagnostics: Lock::new(ErrorMap::new()),
- buffered_lints: Lock::new(vec![]),
- edition: Edition::from_session(),
- ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
- param_attr_spans: Lock::new(Vec::new()),
- let_chains_spans: Lock::new(Vec::new()),
- async_closure_spans: Lock::new(Vec::new()),
- injected_crate_name: Once::new(),
- }
+ let emitter = EmitterWriter::new(Box::new(io::sink()), Some(sm.clone()), false, false, false);
+ ParseSess::with_span_handler(Handler::with_emitter(true, None, Box::new(emitter)), sm)
}
// open a string reader for the given string
@@ -61,7 +37,7 @@
let tok1 = string_reader.next_token();
let tok2 = Token::new(
mk_ident("fn"),
- Span::new(BytePos(21), BytePos(23), NO_EXPANSION),
+ Span::with_root_ctxt(BytePos(21), BytePos(23)),
);
assert_eq!(tok1.kind, tok2.kind);
assert_eq!(tok1.span, tok2.span);
@@ -71,7 +47,7 @@
assert_eq!(string_reader.pos.clone(), BytePos(28));
let tok4 = Token::new(
mk_ident("main"),
- Span::new(BytePos(24), BytePos(28), NO_EXPANSION),
+ Span::with_root_ctxt(BytePos(24), BytePos(28)),
);
assert_eq!(tok3.kind, tok4.kind);
assert_eq!(tok3.span, tok4.span);
diff --git a/src/libsyntax/parse/lexer/unicode_chars.rs b/src/libsyntax/parse/lexer/unicode_chars.rs
index eaa736c..525b421 100644
--- a/src/libsyntax/parse/lexer/unicode_chars.rs
+++ b/src/libsyntax/parse/lexer/unicode_chars.rs
@@ -3,7 +3,7 @@
use super::StringReader;
use errors::{Applicability, DiagnosticBuilder};
-use syntax_pos::{BytePos, Pos, Span, NO_EXPANSION, symbol::kw};
+use syntax_pos::{BytePos, Pos, Span, symbol::kw};
use crate::parse::token;
#[rustfmt::skip] // for line breaks
@@ -343,7 +343,7 @@
None => return None,
};
- let span = Span::new(pos, pos + Pos::from_usize(ch.len_utf8()), NO_EXPANSION);
+ let span = Span::with_root_ctxt(pos, pos + Pos::from_usize(ch.len_utf8()));
let (ascii_name, token) = match ASCII_ARRAY.iter().find(|&&(c, _, _)| c == ascii_char) {
Some((_ascii_char, ascii_name, token)) => (ascii_name, token),
@@ -362,10 +362,9 @@
ascii_char, ascii_name
);
err.span_suggestion(
- Span::new(
+ Span::with_root_ctxt(
pos,
pos + Pos::from_usize('“'.len_utf8() + s.len() + '”'.len_utf8()),
- NO_EXPANSION,
),
&msg,
format!("\"{}\"", s),
diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs
index 80aa7a3..9088f92 100644
--- a/src/libsyntax/parse/mod.rs
+++ b/src/libsyntax/parse/mod.rs
@@ -16,6 +16,7 @@
use rustc_data_structures::sync::{Lrc, Lock, Once};
use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
use syntax_pos::edition::Edition;
+use syntax_pos::hygiene::ExpnId;
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use std::borrow::Cow;
@@ -62,6 +63,8 @@
pub let_chains_spans: Lock<Vec<Span>>,
// Places where `async || ..` exprs were used and should be feature gated.
pub async_closure_spans: Lock<Vec<Span>>,
+ // Places where `yield e?` exprs were used and should be feature gated.
+ pub yield_spans: Lock<Vec<Span>>,
pub injected_crate_name: Once<Symbol>,
}
@@ -86,11 +89,12 @@
included_mod_stack: Lock::new(vec![]),
source_map,
buffered_lints: Lock::new(vec![]),
- edition: Edition::from_session(),
+ edition: ExpnId::root().expn_data().edition,
ambiguous_block_expr_parse: Lock::new(FxHashMap::default()),
param_attr_spans: Lock::new(Vec::new()),
let_chains_spans: Lock::new(Vec::new()),
async_closure_spans: Lock::new(Vec::new()),
+ yield_spans: Lock::new(Vec::new()),
injected_crate_name: Once::new(),
}
}
diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs
index 2286e74..89725d8 100644
--- a/src/libsyntax/parse/parser.rs
+++ b/src/libsyntax/parse/parser.rs
@@ -13,7 +13,6 @@
use crate::ast::{self, AttrStyle, Attribute, Arg, BindingMode, StrStyle, SelfKind};
use crate::ast::{FnDecl, Ident, IsAsync, MacDelimiter, Mutability, TyKind};
use crate::ast::{Visibility, VisibilityKind, Unsafety, CrateSugar};
-use crate::ext::hygiene::SyntaxContext;
use crate::source_map::{self, respan};
use crate::parse::{SeqSep, literal, token};
use crate::parse::lexer::UnmatchedBrace;
@@ -1101,7 +1100,7 @@
crate fn process_potential_macro_variable(&mut self) {
self.token = match self.token.kind {
- token::Dollar if self.token.span.ctxt() != SyntaxContext::empty() &&
+ token::Dollar if self.token.span.from_expansion() &&
self.look_ahead(1, |t| t.is_ident()) => {
self.bump();
let name = match self.token.kind {
diff --git a/src/libsyntax/parse/parser/expr.rs b/src/libsyntax/parse/parser/expr.rs
index f4b6a92..ccc6bd150 100644
--- a/src/libsyntax/parse/parser/expr.rs
+++ b/src/libsyntax/parse/parser/expr.rs
@@ -997,6 +997,9 @@
} else {
ex = ExprKind::Yield(None);
}
+
+ let span = lo.to(hi);
+ self.sess.yield_spans.borrow_mut().push(span);
} else if self.eat_keyword(kw::Let) {
return self.parse_let_expr(attrs);
} else if is_span_rust_2018 && self.eat_keyword(kw::Await) {
diff --git a/src/libsyntax/parse/parser/module.rs b/src/libsyntax/parse/parser/module.rs
index 58a7ffb..3f6f87b 100644
--- a/src/libsyntax/parse/parser/module.rs
+++ b/src/libsyntax/parse/parser/module.rs
@@ -60,7 +60,7 @@
// Record that we fetched the mod from an external file
if warn {
let attr = attr::mk_attr_outer(
- attr::mk_word_item(Ident::with_empty_ctxt(sym::warn_directory_ownership)));
+ attr::mk_word_item(Ident::with_dummy_span(sym::warn_directory_ownership)));
attr::mark_known(&attr);
attrs.push(attr);
}
diff --git a/src/libsyntax/parse/tests.rs b/src/libsyntax/parse/tests.rs
index 9edc83a..6a789ef 100644
--- a/src/libsyntax/parse/tests.rs
+++ b/src/libsyntax/parse/tests.rs
@@ -12,7 +12,7 @@
use crate::tests::{matches_codepattern, string_to_stream, with_error_checking_parse};
use crate::tokenstream::{DelimSpan, TokenTree, TokenStream};
use crate::with_default_globals;
-use syntax_pos::{Span, BytePos, Pos, NO_EXPANSION};
+use syntax_pos::{Span, BytePos, Pos};
use std::path::PathBuf;
@@ -27,7 +27,7 @@
// produce a syntax_pos::span
fn sp(a: u32, b: u32) -> Span {
- Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
+ Span::with_root_ctxt(BytePos(a), BytePos(b))
}
/// Parse a string, return an expr
diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs
index 5955b91..8a70098 100644
--- a/src/libsyntax/print/pprust.rs
+++ b/src/libsyntax/print/pprust.rs
@@ -123,13 +123,13 @@
// of the feature gate, so we fake them up here.
// #![feature(prelude_import)]
- let pi_nested = attr::mk_nested_word_item(ast::Ident::with_empty_ctxt(sym::prelude_import));
- let list = attr::mk_list_item(ast::Ident::with_empty_ctxt(sym::feature), vec![pi_nested]);
+ let pi_nested = attr::mk_nested_word_item(ast::Ident::with_dummy_span(sym::prelude_import));
+ let list = attr::mk_list_item(ast::Ident::with_dummy_span(sym::feature), vec![pi_nested]);
let fake_attr = attr::mk_attr_inner(list);
s.print_attribute(&fake_attr);
// #![no_std]
- let no_std_meta = attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::no_std));
+ let no_std_meta = attr::mk_word_item(ast::Ident::with_dummy_span(sym::no_std));
let fake_attr = attr::mk_attr_inner(no_std_meta);
s.print_attribute(&fake_attr);
}
diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs
index 74cab00..7190cfd 100644
--- a/src/libsyntax/source_map.rs
+++ b/src/libsyntax/source_map.rs
@@ -8,7 +8,7 @@
//! information, source code snippets, etc.
pub use syntax_pos::*;
-pub use syntax_pos::hygiene::{ExpnKind, ExpnInfo};
+pub use syntax_pos::hygiene::{ExpnKind, ExpnData};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::StableHasher;
@@ -29,14 +29,15 @@
/// Returns the span itself if it doesn't come from a macro expansion,
/// otherwise return the call site span up to the `enclosing_sp` by
-/// following the `expn_info` chain.
+/// following the `expn_data` chain.
pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
- let call_site1 = sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
- let call_site2 = enclosing_sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
- match (call_site1, call_site2) {
- (None, _) => sp,
- (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
- (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
+ let expn_data1 = sp.ctxt().outer_expn_data();
+ let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
+ if expn_data1.is_root() ||
+ !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site {
+ sp
+ } else {
+ original_sp(expn_data1.call_site, enclosing_sp)
}
}
@@ -170,6 +171,26 @@
Ok(self.new_source_file(filename, src))
}
+ /// Loads source file as a binary blob.
+ ///
+ /// Unlike `load_file`, guarantees that no normalization like BOM-removal
+ /// takes place.
+ pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
+ // Ideally, this should use `self.file_loader`, but it can't
+ // deal with binary files yet.
+ let bytes = fs::read(path)?;
+
+ // We need to add file to the `SourceMap`, so that it is present
+ // in dep-info. There's also an edge case that file might be both
+ // loaded as a binary via `include_bytes!` and as proper `SourceFile`
+ // via `mod`, so we try to use real file contents and not just an
+ // empty string.
+ let text = std::str::from_utf8(&bytes).unwrap_or("")
+ .to_string();
+ self.new_source_file(path.to_owned().into(), text);
+ Ok(bytes)
+ }
+
pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
}
diff --git a/src/libsyntax/source_map/tests.rs b/src/libsyntax/source_map/tests.rs
index 427e86b..c7b8332 100644
--- a/src/libsyntax/source_map/tests.rs
+++ b/src/libsyntax/source_map/tests.rs
@@ -91,7 +91,7 @@
fn t7() {
// Test span_to_lines for a span ending at the end of source_file
let sm = init_source_map();
- let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
+ let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
let file_lines = sm.span_to_lines(span).unwrap();
assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
@@ -107,7 +107,7 @@
assert_eq!(input.len(), selection.len());
let left_index = selection.find('~').unwrap() as u32;
let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
- Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
+ Span::with_root_ctxt(BytePos(left_index), BytePos(right_index + 1))
}
/// Tests span_to_snippet and span_to_lines for a span converting 3
@@ -137,7 +137,7 @@
fn t8() {
// Test span_to_snippet for a span ending at the end of source_file
let sm = init_source_map();
- let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
+ let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
let snippet = sm.span_to_snippet(span);
assert_eq!(snippet, Ok("second line".to_string()));
@@ -147,7 +147,7 @@
fn t9() {
// Test span_to_str for a span ending at the end of source_file
let sm = init_source_map();
- let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
+ let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
let sstr = sm.span_to_string(span);
assert_eq!(sstr, "blork.rs:2:1: 2:12");
@@ -198,10 +198,9 @@
let lo = hi + offset;
hi = lo + substring.len();
if i == n {
- let span = Span::new(
+ let span = Span::with_root_ctxt(
BytePos(lo as u32 + file.start_pos.0),
BytePos(hi as u32 + file.start_pos.0),
- NO_EXPANSION,
);
assert_eq!(&self.span_to_snippet(span).unwrap()[..],
substring);
diff --git a/src/libsyntax/tests.rs b/src/libsyntax/tests.rs
index cff034f..4c0e1e3 100644
--- a/src/libsyntax/tests.rs
+++ b/src/libsyntax/tests.rs
@@ -9,7 +9,7 @@
use errors::emitter::EmitterWriter;
use errors::Handler;
use rustc_data_structures::sync::Lrc;
-use syntax_pos::{BytePos, NO_EXPANSION, Span, MultiSpan};
+use syntax_pos::{BytePos, Span, MultiSpan};
use std::io;
use std::io::prelude::*;
@@ -169,7 +169,7 @@
let start = make_pos(file_text, start);
let end = make_pos(file_text, end) + end.string.len(); // just after matching thing ends
assert!(start <= end);
- Span::new(BytePos(start as u32), BytePos(end as u32), NO_EXPANSION)
+ Span::with_root_ctxt(BytePos(start as u32), BytePos(end as u32))
}
fn make_pos(file_text: &str, pos: &Position) -> usize {
diff --git a/src/libsyntax/tokenstream/tests.rs b/src/libsyntax/tokenstream/tests.rs
index 72e22a4..5017e5f 100644
--- a/src/libsyntax/tokenstream/tests.rs
+++ b/src/libsyntax/tokenstream/tests.rs
@@ -3,14 +3,14 @@
use crate::ast::Name;
use crate::with_default_globals;
use crate::tests::string_to_stream;
-use syntax_pos::{Span, BytePos, NO_EXPANSION};
+use syntax_pos::{Span, BytePos};
fn string_to_ts(string: &str) -> TokenStream {
string_to_stream(string.to_owned())
}
fn sp(a: u32, b: u32) -> Span {
- Span::new(BytePos(a), BytePos(b), NO_EXPANSION)
+ Span::with_root_ctxt(BytePos(a), BytePos(b))
}
#[test]
diff --git a/src/libsyntax_ext/asm.rs b/src/libsyntax_ext/asm.rs
index 950166f..644a44f 100644
--- a/src/libsyntax_ext/asm.rs
+++ b/src/libsyntax_ext/asm.rs
@@ -63,7 +63,7 @@
MacEager::expr(P(ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprKind::InlineAsm(P(inline_asm)),
- span: sp,
+ span: sp.with_ctxt(cx.backtrace()),
attrs: ThinVec::new(),
}))
}
@@ -277,6 +277,5 @@
volatile,
alignstack,
dialect,
- ctxt: cx.backtrace(),
}))
}
diff --git a/src/libsyntax_ext/deriving/clone.rs b/src/libsyntax_ext/deriving/clone.rs
index d80da56..d030ea4 100644
--- a/src/libsyntax_ext/deriving/clone.rs
+++ b/src/libsyntax_ext/deriving/clone.rs
@@ -35,7 +35,7 @@
match annitem.node {
ItemKind::Struct(_, Generics { ref params, .. }) |
ItemKind::Enum(_, Generics { ref params, .. }) => {
- let container_id = cx.current_expansion.id.parent();
+ let container_id = cx.current_expansion.id.expn_data().parent;
if cx.resolver.has_derives(container_id, SpecialDerives::COPY) &&
!params.iter().any(|param| match param.kind {
ast::GenericParamKind::Type { .. } => true,
@@ -129,7 +129,7 @@
if is_union {
// let _: AssertParamIsCopy<Self>;
let self_ty =
- cx.ty_path(cx.path_ident(trait_span, ast::Ident::with_empty_ctxt(kw::SelfUpper)));
+ cx.ty_path(cx.path_ident(trait_span, ast::Ident::with_dummy_span(kw::SelfUpper)));
assert_ty_bounds(cx, &mut stmts, self_ty, trait_span, "AssertParamIsCopy");
} else {
match *substr.fields {
diff --git a/src/libsyntax_ext/deriving/cmp/eq.rs b/src/libsyntax_ext/deriving/cmp/eq.rs
index 5d7c4a8..54027c6 100644
--- a/src/libsyntax_ext/deriving/cmp/eq.rs
+++ b/src/libsyntax_ext/deriving/cmp/eq.rs
@@ -13,7 +13,7 @@
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
- cx.resolver.add_derives(cx.current_expansion.id.parent(), SpecialDerives::EQ);
+ cx.resolver.add_derives(cx.current_expansion.id.expn_data().parent, SpecialDerives::EQ);
let inline = cx.meta_word(span, sym::inline);
let hidden = cx.meta_list_item_word(span, sym::hidden);
diff --git a/src/libsyntax_ext/deriving/cmp/ord.rs b/src/libsyntax_ext/deriving/cmp/ord.rs
index 885cfee..55687c3 100644
--- a/src/libsyntax_ext/deriving/cmp/ord.rs
+++ b/src/libsyntax_ext/deriving/cmp/ord.rs
@@ -43,17 +43,18 @@
}
-pub fn ordering_collapsed(cx: &mut ExtCtxt<'_>,
- span: Span,
- self_arg_tags: &[ast::Ident])
- -> P<ast::Expr> {
+pub fn ordering_collapsed(
+ cx: &mut ExtCtxt<'_>,
+ span: Span,
+ self_arg_tags: &[ast::Ident],
+) -> P<ast::Expr> {
let lft = cx.expr_ident(span, self_arg_tags[0]);
let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
- cx.expr_method_call(span, lft, cx.ident_of("cmp"), vec![rgt])
+ cx.expr_method_call(span, lft, ast::Ident::new(sym::cmp, span), vec![rgt])
}
pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P<Expr> {
- let test_id = cx.ident_of("cmp").gensym();
+ let test_id = ast::Ident::new(sym::cmp, span);
let equals_path = cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::Equal]));
let cmp_path = cx.std_path(&[sym::cmp, sym::Ord, sym::cmp]);
@@ -75,34 +76,34 @@
// as the outermost one, and the last as the innermost.
false,
|cx, span, old, self_f, other_fs| {
- // match new {
- // ::std::cmp::Ordering::Equal => old,
- // cmp => cmp
- // }
+ // match new {
+ // ::std::cmp::Ordering::Equal => old,
+ // cmp => cmp
+ // }
- let new = {
- let other_f = match other_fs {
- [o_f] => o_f,
- _ => cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`"),
- };
+ let new = {
+ let other_f = match other_fs {
+ [o_f] => o_f,
+ _ => cx.span_bug(span, "not exactly 2 arguments in `derive(Ord)`"),
+ };
- let args = vec![
- cx.expr_addr_of(span, self_f),
- cx.expr_addr_of(span, other_f.clone()),
- ];
+ let args = vec![
+ cx.expr_addr_of(span, self_f),
+ cx.expr_addr_of(span, other_f.clone()),
+ ];
- cx.expr_call_global(span, cmp_path.clone(), args)
- };
+ cx.expr_call_global(span, cmp_path.clone(), args)
+ };
- let eq_arm = cx.arm(span,
- vec![cx.pat_path(span, equals_path.clone())],
- old);
- let neq_arm = cx.arm(span,
- vec![cx.pat_ident(span, test_id)],
- cx.expr_ident(span, test_id));
+ let eq_arm = cx.arm(span,
+ vec![cx.pat_path(span, equals_path.clone())],
+ old);
+ let neq_arm = cx.arm(span,
+ vec![cx.pat_ident(span, test_id)],
+ cx.expr_ident(span, test_id));
- cx.expr_match(span, new, vec![eq_arm, neq_arm])
- },
+ cx.expr_match(span, new, vec![eq_arm, neq_arm])
+ },
cx.expr_path(equals_path.clone()),
Box::new(|cx, span, (self_args, tag_tuple), _non_self_args| {
if self_args.len() != 2 {
diff --git a/src/libsyntax_ext/deriving/cmp/partial_eq.rs b/src/libsyntax_ext/deriving/cmp/partial_eq.rs
index 7d7c4ae..91e1e80 100644
--- a/src/libsyntax_ext/deriving/cmp/partial_eq.rs
+++ b/src/libsyntax_ext/deriving/cmp/partial_eq.rs
@@ -13,7 +13,7 @@
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
- cx.resolver.add_derives(cx.current_expansion.id.parent(), SpecialDerives::PARTIAL_EQ);
+ cx.resolver.add_derives(cx.current_expansion.id.expn_data().parent, SpecialDerives::PARTIAL_EQ);
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
diff --git a/src/libsyntax_ext/deriving/cmp/partial_ord.rs b/src/libsyntax_ext/deriving/cmp/partial_ord.rs
index 0ec30f5..740b92a 100644
--- a/src/libsyntax_ext/deriving/cmp/partial_ord.rs
+++ b/src/libsyntax_ext/deriving/cmp/partial_ord.rs
@@ -94,11 +94,12 @@
GeOp,
}
-pub fn some_ordering_collapsed(cx: &mut ExtCtxt<'_>,
- span: Span,
- op: OrderingOp,
- self_arg_tags: &[ast::Ident])
- -> P<ast::Expr> {
+pub fn some_ordering_collapsed(
+ cx: &mut ExtCtxt<'_>,
+ span: Span,
+ op: OrderingOp,
+ self_arg_tags: &[ast::Ident],
+) -> P<ast::Expr> {
let lft = cx.expr_ident(span, self_arg_tags[0]);
let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
let op_str = match op {
@@ -108,11 +109,11 @@
GtOp => "gt",
GeOp => "ge",
};
- cx.expr_method_call(span, lft, cx.ident_of(op_str), vec![rgt])
+ cx.expr_method_call(span, lft, ast::Ident::from_str_and_span(op_str, span), vec![rgt])
}
pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> P<Expr> {
- let test_id = cx.ident_of("cmp").gensym();
+ let test_id = ast::Ident::new(sym::cmp, span);
let ordering = cx.path_global(span, cx.std_path(&[sym::cmp, sym::Ordering, sym::Equal]));
let ordering_expr = cx.expr_path(ordering.clone());
let equals_expr = cx.expr_some(span, ordering_expr);
diff --git a/src/libsyntax_ext/deriving/debug.rs b/src/libsyntax_ext/deriving/debug.rs
index 15e93f2..4415354 100644
--- a/src/libsyntax_ext/deriving/debug.rs
+++ b/src/libsyntax_ext/deriving/debug.rs
@@ -62,7 +62,7 @@
// We want to make sure we have the ctxt set so that we can use unstable methods
let span = span.with_ctxt(cx.backtrace());
let name = cx.expr_lit(span, ast::LitKind::Str(ident.name, ast::StrStyle::Cooked));
- let builder = Ident::from_str("debug_trait_builder").gensym();
+ let builder = Ident::from_str_and_span("debug_trait_builder", span);
let builder_expr = cx.expr_ident(span, builder.clone());
let fmt = substr.nonself_args[0].clone();
@@ -73,7 +73,7 @@
// tuple struct/"normal" variant
let expr =
cx.expr_method_call(span, fmt, Ident::from_str("debug_tuple"), vec![name]);
- stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));
+ stmts.push(cx.stmt_let(span, true, builder, expr));
for field in fields {
// Use double indirection to make sure this works for unsized types
@@ -82,7 +82,7 @@
let expr = cx.expr_method_call(span,
builder_expr.clone(),
- Ident::with_empty_ctxt(sym::field),
+ Ident::new(sym::field, span),
vec![field]);
// Use `let _ = expr;` to avoid triggering the
@@ -106,7 +106,7 @@
let field = cx.expr_addr_of(field.span, field);
let expr = cx.expr_method_call(span,
builder_expr.clone(),
- Ident::with_empty_ctxt(sym::field),
+ Ident::new(sym::field, span),
vec![name, field]);
stmts.push(stmt_let_undescore(cx, span, expr));
}
diff --git a/src/libsyntax_ext/deriving/decodable.rs b/src/libsyntax_ext/deriving/decodable.rs
index 293c5a1..9b6f851 100644
--- a/src/libsyntax_ext/deriving/decodable.rs
+++ b/src/libsyntax_ext/deriving/decodable.rs
@@ -1,6 +1,6 @@
-//! The compiler code necessary for `#[derive(Decodable)]`. See encodable.rs for more.
+//! The compiler code necessary for `#[derive(RustcDecodable)]`. See encodable.rs for more.
-use crate::deriving::{self, pathvec_std};
+use crate::deriving::pathvec_std;
use crate::deriving::generic::*;
use crate::deriving::generic::ty::*;
@@ -17,7 +17,7 @@
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
let krate = "rustc_serialize";
- let typaram = &*deriving::hygienic_type_parameter(item, "__D");
+ let typaram = "__D";
let trait_def = TraitDef {
span,
diff --git a/src/libsyntax_ext/deriving/encodable.rs b/src/libsyntax_ext/deriving/encodable.rs
index 52e74a7..8b18fb2 100644
--- a/src/libsyntax_ext/deriving/encodable.rs
+++ b/src/libsyntax_ext/deriving/encodable.rs
@@ -1,11 +1,12 @@
-//! The compiler code necessary to implement the `#[derive(Encodable)]`
-//! (and `Decodable`, in `decodable.rs`) extension. The idea here is that
-//! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`.
+//! The compiler code necessary to implement the `#[derive(RustcEncodable)]`
+//! (and `RustcDecodable`, in `decodable.rs`) extension. The idea here is that
+//! type-defining items may be tagged with
+//! `#[derive(RustcEncodable, RustcDecodable)]`.
//!
//! For example, a type like:
//!
//! ```
-//! #[derive(Encodable, Decodable)]
+//! #[derive(RustcEncodable, RustcDecodable)]
//! struct Node { id: usize }
//! ```
//!
@@ -40,15 +41,17 @@
//! references other non-built-in types. A type definition like:
//!
//! ```
-//! # #[derive(Encodable, Decodable)] struct Span;
-//! #[derive(Encodable, Decodable)]
+//! # #[derive(RustcEncodable, RustcDecodable)]
+//! # struct Span;
+//! #[derive(RustcEncodable, RustcDecodable)]
//! struct Spanned<T> { node: T, span: Span }
//! ```
//!
//! would yield functions like:
//!
//! ```
-//! # #[derive(Encodable, Decodable)] struct Span;
+//! # #[derive(RustcEncodable, RustcDecodable)]
+//! # struct Span;
//! # struct Spanned<T> { node: T, span: Span }
//! impl<
//! S: Encoder<E>,
@@ -82,7 +85,7 @@
//! }
//! ```
-use crate::deriving::{self, pathvec_std};
+use crate::deriving::pathvec_std;
use crate::deriving::generic::*;
use crate::deriving::generic::ty::*;
@@ -98,7 +101,7 @@
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
let krate = "rustc_serialize";
- let typaram = &*deriving::hygienic_type_parameter(item, "__S");
+ let typaram = "__S";
let trait_def = TraitDef {
span,
diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs
index d080dc3..1475bac 100644
--- a/src/libsyntax_ext/deriving/generic/mod.rs
+++ b/src/libsyntax_ext/deriving/generic/mod.rs
@@ -425,7 +425,7 @@
return;
}
};
- let container_id = cx.current_expansion.id.parent();
+ let container_id = cx.current_expansion.id.expn_data().parent;
let is_always_copy =
cx.resolver.has_derives(container_id, SpecialDerives::COPY) &&
has_no_type_params;
@@ -890,7 +890,7 @@
for (ty, name) in self.args.iter() {
let ast_ty = ty.to_ty(cx, trait_.span, type_ident, generics);
- let ident = cx.ident_of(name).gensym();
+ let ident = ast::Ident::from_str_and_span(name, trait_.span);
arg_tys.push((ident, ast_ty));
let arg_expr = cx.expr_ident(trait_.span, ident);
@@ -928,7 +928,7 @@
let args = {
let self_args = explicit_self.map(|explicit_self| {
- let ident = Ident::with_empty_ctxt(kw::SelfLower).with_span_pos(trait_.span);
+ let ident = Ident::with_dummy_span(kw::SelfLower).with_span_pos(trait_.span);
ast::Arg::from_self(ThinVec::default(), explicit_self, ident)
});
let nonself_args = arg_types.into_iter()
@@ -1210,7 +1210,7 @@
let vi_idents = self_arg_names.iter()
.map(|name| {
let vi_suffix = format!("{}_vi", &name[..]);
- cx.ident_of(&vi_suffix[..]).gensym()
+ ast::Ident::from_str_and_span(&vi_suffix[..], trait_.span)
})
.collect::<Vec<ast::Ident>>();
@@ -1387,7 +1387,10 @@
let variant_value =
deriving::call_intrinsic(cx, sp, "discriminant_value", vec![self_addr]);
- let target_ty = cx.ty_ident(sp, cx.ident_of(target_type_name));
+ let target_ty = cx.ty_ident(
+ sp,
+ ast::Ident::from_str_and_span(target_type_name, sp),
+ );
let variant_disr = cx.expr_cast(sp, variant_value, target_ty);
let let_stmt = cx.stmt_let(sp, false, ident, variant_disr);
index_let_stmts.push(let_stmt);
@@ -1588,7 +1591,7 @@
let mut ident_exprs = Vec::new();
for (i, struct_field) in struct_def.fields().iter().enumerate() {
let sp = struct_field.span.with_ctxt(self.span.ctxt());
- let ident = cx.ident_of(&format!("{}_{}", prefix, i)).gensym();
+ let ident = ast::Ident::from_str_and_span(&format!("{}_{}", prefix, i), self.span);
paths.push(ident.with_span_pos(sp));
let val = cx.expr_path(cx.path_ident(sp, ident));
let val = if use_temporaries {
diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs
index 399829e..7fcf036 100644
--- a/src/libsyntax_ext/deriving/generic/ty.rs
+++ b/src/libsyntax_ext/deriving/generic/ty.rs
@@ -72,7 +72,7 @@
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
- let mut idents = self.path.iter().map(|s| cx.ident_of(*s)).collect();
+ let mut idents = self.path.iter().map(|s| Ident::from_str_and_span(*s, span)).collect();
let lt = mk_lifetimes(cx, span, &self.lifetime);
let tys: Vec<P<ast::Ty>> =
self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect();
@@ -209,7 +209,7 @@
cx.trait_bound(path)
})
.collect();
- cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None)
+ cx.typaram(span, ast::Ident::from_str_and_span(name, span), attrs.to_owned(), bounds, None)
}
fn mk_generics(params: Vec<ast::GenericParam>, span: Span) -> Generics {
diff --git a/src/libsyntax_ext/deriving/hash.rs b/src/libsyntax_ext/deriving/hash.rs
index 9787722..2fc594a 100644
--- a/src/libsyntax_ext/deriving/hash.rs
+++ b/src/libsyntax_ext/deriving/hash.rs
@@ -16,7 +16,7 @@
let path = Path::new_(pathvec_std!(cx, hash::Hash), None, vec![], PathKind::Std);
- let typaram = &*deriving::hygienic_type_parameter(item, "__H");
+ let typaram = "__H";
let arg = Path::new_local(typaram);
let hash_trait_def = TraitDef {
diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs
index 8cd2853..da68eea 100644
--- a/src/libsyntax_ext/deriving/mod.rs
+++ b/src/libsyntax_ext/deriving/mod.rs
@@ -54,33 +54,6 @@
}
}
-/// Construct a name for the inner type parameter that can't collide with any type parameters of
-/// the item. This is achieved by starting with a base and then concatenating the names of all
-/// other type parameters.
-// FIXME(aburka): use real hygiene when that becomes possible
-fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String {
- let mut typaram = String::from(base);
- if let Annotatable::Item(ref item) = *item {
- match item.node {
- ast::ItemKind::Struct(_, ast::Generics { ref params, .. }) |
- ast::ItemKind::Enum(_, ast::Generics { ref params, .. }) => {
- for param in params {
- match param.kind {
- ast::GenericParamKind::Type { .. } => {
- typaram.push_str(¶m.ident.as_str());
- }
- _ => {}
- }
- }
- }
-
- _ => {}
- }
- }
-
- typaram
-}
-
/// Constructs an expression that calls an intrinsic
fn call_intrinsic(cx: &ExtCtxt<'_>,
span: Span,
diff --git a/src/libsyntax_ext/env.rs b/src/libsyntax_ext/env.rs
index 442f27c..9834130 100644
--- a/src/libsyntax_ext/env.rs
+++ b/src/libsyntax_ext/env.rs
@@ -23,13 +23,13 @@
let sp = sp.apply_mark(cx.current_expansion.id);
let e = match env::var(&*var.as_str()) {
Err(..) => {
- let lt = cx.lifetime(sp, Ident::with_empty_ctxt(kw::StaticLifetime));
+ let lt = cx.lifetime(sp, Ident::with_dummy_span(kw::StaticLifetime));
cx.expr_path(cx.path_all(sp,
true,
cx.std_path(&[sym::option, sym::Option, sym::None]),
vec![GenericArg::Type(cx.ty_rptr(sp,
cx.ty_ident(sp,
- Ident::with_empty_ctxt(sym::str)),
+ Ident::with_dummy_span(sym::str)),
Some(lt),
ast::Mutability::Immutable))],
vec![]))
diff --git a/src/libsyntax_ext/global_allocator.rs b/src/libsyntax_ext/global_allocator.rs
index f788b51..d2121ab 100644
--- a/src/libsyntax_ext/global_allocator.rs
+++ b/src/libsyntax_ext/global_allocator.rs
@@ -29,7 +29,7 @@
};
// Generate a bunch of new items using the AllocFnFactory
- let span = item.span.with_ctxt(SyntaxContext::empty().apply_mark(ecx.current_expansion.id));
+ let span = item.span.with_ctxt(SyntaxContext::root().apply_mark(ecx.current_expansion.id));
let f = AllocFnFactory {
span,
kind: AllocatorKind::Global,
@@ -44,7 +44,7 @@
let const_ty = ecx.ty(span, TyKind::Tup(Vec::new()));
let const_body = ecx.expr_block(ecx.block(span, stmts));
let const_item =
- ecx.item_const(span, Ident::with_empty_ctxt(kw::Underscore), const_ty, const_body);
+ ecx.item_const(span, Ident::with_dummy_span(kw::Underscore), const_ty, const_body);
// Return the original item and the new methods.
vec![Annotatable::Item(item), Annotatable::Item(const_item)]
@@ -120,7 +120,7 @@
) -> P<Expr> {
match *ty {
AllocatorTy::Layout => {
- let usize = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::usize));
+ let usize = self.cx.path_ident(self.span, Ident::with_dummy_span(sym::usize));
let ty_usize = self.cx.ty_path(usize);
let size = ident();
let align = ident();
@@ -178,12 +178,12 @@
}
fn usize(&self) -> P<Ty> {
- let usize = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::usize));
+ let usize = self.cx.path_ident(self.span, Ident::with_dummy_span(sym::usize));
self.cx.ty_path(usize)
}
fn ptr_u8(&self) -> P<Ty> {
- let u8 = self.cx.path_ident(self.span, Ident::with_empty_ctxt(sym::u8));
+ let u8 = self.cx.path_ident(self.span, Ident::with_dummy_span(sym::u8));
let ty_u8 = self.cx.ty_path(u8);
self.cx.ty_ptr(self.span, ty_u8, Mutability::Mutable)
}
diff --git a/src/libsyntax_ext/global_asm.rs b/src/libsyntax_ext/global_asm.rs
index 112192f..73ebeae 100644
--- a/src/libsyntax_ext/global_asm.rs
+++ b/src/libsyntax_ext/global_asm.rs
@@ -30,7 +30,7 @@
id: ast::DUMMY_NODE_ID,
node: ast::ItemKind::GlobalAsm(P(global_asm)),
vis: respan(sp.shrink_to_lo(), ast::VisibilityKind::Inherited),
- span: sp,
+ span: sp.with_ctxt(cx.backtrace()),
tokens: None,
})])
}
@@ -61,8 +61,5 @@
None => return Ok(None),
};
- Ok(Some(ast::GlobalAsm {
- asm,
- ctxt: cx.backtrace(),
- }))
+ Ok(Some(ast::GlobalAsm { asm }))
}
diff --git a/src/libsyntax_ext/lib.rs b/src/libsyntax_ext/lib.rs
index 0f3f5c0..4add226 100644
--- a/src/libsyntax_ext/lib.rs
+++ b/src/libsyntax_ext/lib.rs
@@ -42,7 +42,7 @@
pub fn register_builtin_macros(resolver: &mut dyn syntax::ext::base::Resolver, edition: Edition) {
let mut register = |name, kind| resolver.register_builtin_macro(
- Ident::with_empty_ctxt(name), SyntaxExtension {
+ Ident::with_dummy_span(name), SyntaxExtension {
is_builtin: true, ..SyntaxExtension::default(kind, edition)
},
);
@@ -57,7 +57,6 @@
}
register_bang! {
- __rust_unstable_column: source_util::expand_column,
asm: asm::expand_asm,
assert: assert::expand_assert,
cfg: cfg::expand_cfg,
diff --git a/src/libsyntax_ext/plugin_macro_defs.rs b/src/libsyntax_ext/plugin_macro_defs.rs
index a725f5e..dbfd8fe 100644
--- a/src/libsyntax_ext/plugin_macro_defs.rs
+++ b/src/libsyntax_ext/plugin_macro_defs.rs
@@ -11,7 +11,7 @@
use syntax::symbol::sym;
use syntax::tokenstream::*;
use syntax_pos::{Span, DUMMY_SP};
-use syntax_pos::hygiene::{ExpnId, ExpnInfo, ExpnKind, MacroKind};
+use syntax_pos::hygiene::{ExpnData, ExpnKind, MacroKind};
use std::mem;
@@ -43,12 +43,12 @@
) {
if !named_exts.is_empty() {
let mut extra_items = Vec::new();
- let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
+ let span = DUMMY_SP.fresh_expansion(ExpnData::allow_unstable(
ExpnKind::Macro(MacroKind::Attr, sym::plugin), DUMMY_SP, edition,
[sym::rustc_attrs][..].into(),
));
for (name, ext) in named_exts {
- resolver.register_builtin_macro(Ident::with_empty_ctxt(name), ext);
+ resolver.register_builtin_macro(Ident::with_dummy_span(name), ext);
extra_items.push(plugin_macro_def(name, span));
}
// The `macro_rules` items must be inserted before any other items.
diff --git a/src/libsyntax_ext/proc_macro_harness.rs b/src/libsyntax_ext/proc_macro_harness.rs
index 7032553..e772eaf 100644
--- a/src/libsyntax_ext/proc_macro_harness.rs
+++ b/src/libsyntax_ext/proc_macro_harness.rs
@@ -3,10 +3,9 @@
use smallvec::smallvec;
use syntax::ast::{self, Ident};
use syntax::attr;
-use syntax::source_map::{ExpnInfo, ExpnKind, respan};
+use syntax::source_map::{ExpnData, ExpnKind, respan};
use syntax::ext::base::{ExtCtxt, MacroKind};
use syntax::ext::expand::{AstFragment, ExpansionConfig};
-use syntax::ext::hygiene::ExpnId;
use syntax::ext::proc_macro::is_proc_macro_attr;
use syntax::parse::ParseSess;
use syntax::ptr::P;
@@ -328,7 +327,7 @@
custom_attrs: &[ProcMacroDef],
custom_macros: &[ProcMacroDef],
) -> P<ast::Item> {
- let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
+ let span = DUMMY_SP.fresh_expansion(ExpnData::allow_unstable(
ExpnKind::Macro(MacroKind::Attr, sym::proc_macro), DUMMY_SP, cx.parse_sess.edition,
[sym::rustc_attrs, sym::proc_macro_internals][..].into(),
));
@@ -337,7 +336,7 @@
let doc = cx.meta_list(span, sym::doc, vec![hidden]);
let doc_hidden = cx.attribute(doc);
- let proc_macro = Ident::with_empty_ctxt(sym::proc_macro);
+ let proc_macro = Ident::with_dummy_span(sym::proc_macro);
let krate = cx.item(span,
proc_macro,
Vec::new(),
@@ -349,7 +348,7 @@
let custom_derive = Ident::from_str("custom_derive");
let attr = Ident::from_str("attr");
let bang = Ident::from_str("bang");
- let crate_kw = Ident::with_empty_ctxt(kw::Crate);
+ let crate_kw = Ident::with_dummy_span(kw::Crate);
let decls = {
let local_path = |sp: Span, name| {
diff --git a/src/libsyntax_ext/source_util.rs b/src/libsyntax_ext/source_util.rs
index cbc01b4..e008ed7 100644
--- a/src/libsyntax_ext/source_util.rs
+++ b/src/libsyntax_ext/source_util.rs
@@ -9,8 +9,6 @@
use smallvec::SmallVec;
use syntax_pos::{self, Pos, Span};
-use std::fs;
-use std::io::ErrorKind;
use rustc_data_structures::sync::Lrc;
// These macros all relate to the file system; they either return
@@ -114,20 +112,17 @@
None => return DummyResult::any(sp)
};
let file = cx.resolve_path(file, sp);
- match fs::read_to_string(&file) {
- Ok(src) => {
- let interned_src = Symbol::intern(&src);
-
- // Add this input file to the code map to make it available as
- // dependency information
- cx.source_map().new_source_file(file.into(), src);
-
- base::MacEager::expr(cx.expr_str(sp, interned_src))
+ match cx.source_map().load_binary_file(&file) {
+ Ok(bytes) => match std::str::from_utf8(&bytes) {
+ Ok(src) => {
+ let interned_src = Symbol::intern(&src);
+ base::MacEager::expr(cx.expr_str(sp, interned_src))
+ }
+ Err(_) => {
+ cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
+ DummyResult::any(sp)
+ }
},
- Err(ref e) if e.kind() == ErrorKind::InvalidData => {
- cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
- DummyResult::any(sp)
- }
Err(e) => {
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp)
@@ -142,18 +137,8 @@
None => return DummyResult::any(sp)
};
let file = cx.resolve_path(file, sp);
- match fs::read(&file) {
+ match cx.source_map().load_binary_file(&file) {
Ok(bytes) => {
- // Add the contents to the source map if it contains UTF-8.
- let (contents, bytes) = match String::from_utf8(bytes) {
- Ok(s) => {
- let bytes = s.as_bytes().to_owned();
- (s, bytes)
- },
- Err(e) => (String::new(), e.into_bytes()),
- };
- cx.source_map().new_source_file(file.into(), contents);
-
base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
},
Err(e) => {
diff --git a/src/libsyntax_ext/standard_library_imports.rs b/src/libsyntax_ext/standard_library_imports.rs
index 68b13bd..8ca3763 100644
--- a/src/libsyntax_ext/standard_library_imports.rs
+++ b/src/libsyntax_ext/standard_library_imports.rs
@@ -1,8 +1,8 @@
use syntax::{ast, attr};
use syntax::edition::Edition;
-use syntax::ext::hygiene::{ExpnId, MacroKind};
+use syntax::ext::hygiene::MacroKind;
use syntax::ptr::P;
-use syntax::source_map::{ExpnInfo, ExpnKind, dummy_spanned, respan};
+use syntax::source_map::{ExpnData, ExpnKind, dummy_spanned, respan};
use syntax::symbol::{Ident, Symbol, kw, sym};
use syntax_pos::DUMMY_SP;
@@ -32,7 +32,7 @@
// HACK(eddyb) gensym the injected crates on the Rust 2018 edition,
// so they don't accidentally interfere with the new import paths.
let orig_name_sym = Symbol::intern(orig_name_str);
- let orig_name_ident = Ident::with_empty_ctxt(orig_name_sym);
+ let orig_name_ident = Ident::with_dummy_span(orig_name_sym);
let (rename, orig_name) = if rust_2018 {
(orig_name_ident.gensym(), Some(orig_name_sym))
} else {
@@ -40,7 +40,7 @@
};
krate.module.items.insert(0, P(ast::Item {
attrs: vec![attr::mk_attr_outer(
- attr::mk_word_item(ast::Ident::with_empty_ctxt(sym::macro_use))
+ attr::mk_word_item(ast::Ident::with_dummy_span(sym::macro_use))
)],
vis: dummy_spanned(ast::VisibilityKind::Inherited),
node: ast::ItemKind::ExternCrate(alt_std_name.or(orig_name)),
@@ -55,7 +55,7 @@
// the prelude.
let name = names[0];
- let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
+ let span = DUMMY_SP.fresh_expansion(ExpnData::allow_unstable(
ExpnKind::Macro(MacroKind::Attr, sym::std_inject), DUMMY_SP, edition,
[sym::prelude_import][..].into(),
));
@@ -66,7 +66,7 @@
vis: respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
node: ast::ItemKind::Use(P(ast::UseTree {
prefix: ast::Path {
- segments: iter::once(ast::Ident::with_empty_ctxt(kw::PathRoot))
+ segments: iter::once(ast::Ident::with_dummy_span(kw::PathRoot))
.chain(
[name, "prelude", "v1"].iter().cloned()
.map(ast::Ident::from_str)
diff --git a/src/libsyntax_ext/test.rs b/src/libsyntax_ext/test.rs
index 993ef25..08582e7 100644
--- a/src/libsyntax_ext/test.rs
+++ b/src/libsyntax_ext/test.rs
@@ -29,7 +29,7 @@
if !ecx.ecfg.should_test { return vec![]; }
- let sp = attr_sp.with_ctxt(SyntaxContext::empty().apply_mark(ecx.current_expansion.id));
+ let sp = attr_sp.with_ctxt(SyntaxContext::root().apply_mark(ecx.current_expansion.id));
let mut item = anno_item.expect_item();
item = item.map(|mut item| {
item.vis = respan(item.vis.span, ast::VisibilityKind::Public);
@@ -93,7 +93,7 @@
return vec![Annotatable::Item(item)];
}
- let ctxt = SyntaxContext::empty().apply_mark(cx.current_expansion.id);
+ let ctxt = SyntaxContext::root().apply_mark(cx.current_expansion.id);
let (sp, attr_sp) = (item.span.with_ctxt(ctxt), attr_sp.with_ctxt(ctxt));
// Gensym "test" so we can extern crate without conflicting with any local names
diff --git a/src/libsyntax_ext/test_harness.rs b/src/libsyntax_ext/test_harness.rs
index 0267637..4a6ea0e 100644
--- a/src/libsyntax_ext/test_harness.rs
+++ b/src/libsyntax_ext/test_harness.rs
@@ -5,14 +5,13 @@
use syntax::ast::{self, Ident};
use syntax::attr;
use syntax::entry::{self, EntryPointType};
-use syntax::ext::base::{ExtCtxt, Resolver};
+use syntax::ext::base::{ExtCtxt, MacroKind, Resolver};
use syntax::ext::expand::{AstFragment, ExpansionConfig};
-use syntax::ext::hygiene::{ExpnId, MacroKind};
use syntax::feature_gate::Features;
use syntax::mut_visit::{*, ExpectOne};
use syntax::parse::ParseSess;
use syntax::ptr::P;
-use syntax::source_map::{ExpnInfo, ExpnKind, dummy_spanned};
+use syntax::source_map::{ExpnData, ExpnKind, dummy_spanned};
use syntax::symbol::{kw, sym, Symbol};
use syntax_pos::{Span, DUMMY_SP};
@@ -150,7 +149,7 @@
EntryPointType::MainAttr |
EntryPointType::Start =>
item.map(|ast::Item {id, ident, attrs, node, vis, span, tokens}| {
- let allow_ident = Ident::with_empty_ctxt(sym::allow);
+ let allow_ident = Ident::with_dummy_span(sym::allow);
let dc_nested = attr::mk_nested_word_item(Ident::from_str("dead_code"));
let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]);
let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item);
@@ -191,7 +190,7 @@
tests: Vec<Ident>,
tested_submods: Vec<(Ident, Ident)>)
-> (P<ast::Item>, Ident) {
- let super_ = Ident::with_empty_ctxt(kw::Super);
+ let super_ = Ident::with_dummy_span(kw::Super);
let items = tests.into_iter().map(|r| {
cx.ext_cx.item_use_simple(DUMMY_SP, dummy_spanned(ast::VisibilityKind::Public),
@@ -269,12 +268,12 @@
// #![main]
// test::test_main_static(&[..tests]);
// }
- let sp = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
+ let sp = DUMMY_SP.fresh_expansion(ExpnData::allow_unstable(
ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, cx.ext_cx.parse_sess.edition,
[sym::main, sym::test, sym::rustc_attrs][..].into(),
));
let ecx = &cx.ext_cx;
- let test_id = Ident::with_empty_ctxt(sym::test);
+ let test_id = Ident::with_dummy_span(sym::test);
// test::test_main_static(...)
let mut test_runner = cx.test_runner.clone().unwrap_or(
diff --git a/src/libsyntax_pos/edition.rs b/src/libsyntax_pos/edition.rs
index 2021656..00cd00f 100644
--- a/src/libsyntax_pos/edition.rs
+++ b/src/libsyntax_pos/edition.rs
@@ -1,7 +1,6 @@
use crate::symbol::{Symbol, sym};
use std::fmt;
use std::str::FromStr;
-use crate::GLOBALS;
/// The edition of the compiler (RFC 2052)
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Debug, RustcEncodable, RustcDecodable, Eq)]
@@ -39,10 +38,6 @@
}
impl Edition {
- pub fn from_session() -> Edition {
- GLOBALS.with(|globals| globals.edition)
- }
-
pub fn lint_name(&self) -> &'static str {
match *self {
Edition::Edition2015 => "rust_2015_compatibility",
diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs
index f91a229..ebfb076 100644
--- a/src/libsyntax_pos/hygiene.rs
+++ b/src/libsyntax_pos/hygiene.rs
@@ -13,8 +13,8 @@
//
// This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
// with a certain amount of redundancy in them. For example,
-// `SyntaxContext::outer_expn_info` combines `SyntaxContext::outer` and
-// `ExpnId::expn_info` so that two `HygieneData` accesses can be performed within
+// `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
+// `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
// a single `HygieneData::with` call.
//
// It also explains why many functions appear in `HygieneData` and again in
@@ -56,16 +56,6 @@
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct ExpnId(u32);
-// FIXME: Find a way to merge this with `ExpnInfo`.
-#[derive(Debug)]
-struct InternalExpnData {
- parent: ExpnId,
- /// Each expansion should have an associated expansion info, but sometimes there's a delay
- /// between creation of an expansion ID and obtaining its info (e.g. macros are collected
- /// first and then resolved later), so we use an `Option` here.
- expn_info: Option<ExpnInfo>,
-}
-
/// A property of a macro expansion that determines how identifiers
/// produced by that expansion are resolved.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, RustcEncodable, RustcDecodable)]
@@ -86,8 +76,8 @@
}
impl ExpnId {
- pub fn fresh(parent: ExpnId, expn_info: Option<ExpnInfo>) -> Self {
- HygieneData::with(|data| data.fresh_expn(parent, expn_info))
+ pub fn fresh(expn_data: Option<ExpnData>) -> Self {
+ HygieneData::with(|data| data.fresh_expn(expn_data))
}
/// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
@@ -107,21 +97,16 @@
}
#[inline]
- pub fn parent(self) -> ExpnId {
- HygieneData::with(|data| data.parent_expn(self))
+ pub fn expn_data(self) -> ExpnData {
+ HygieneData::with(|data| data.expn_data(self).clone())
}
#[inline]
- pub fn expn_info(self) -> Option<ExpnInfo> {
- HygieneData::with(|data| data.expn_info(self).cloned())
- }
-
- #[inline]
- pub fn set_expn_info(self, info: ExpnInfo) {
+ pub fn set_expn_data(self, expn_data: ExpnData) {
HygieneData::with(|data| {
- let old_info = &mut data.expn_data[self.0 as usize].expn_info;
- assert!(old_info.is_none(), "expansion info is reset for an expansion ID");
- *old_info = Some(info);
+ let old_expn_data = &mut data.expn_data[self.0 as usize];
+ assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
+ *old_expn_data = Some(expn_data);
})
}
@@ -139,12 +124,9 @@
#[inline]
pub fn looks_like_proc_macro_derive(self) -> bool {
HygieneData::with(|data| {
- if data.default_transparency(self) == Transparency::Opaque {
- if let Some(expn_info) = data.expn_info(self) {
- if let ExpnKind::Macro(MacroKind::Derive, _) = expn_info.kind {
- return true;
- }
- }
+ let expn_data = data.expn_data(self);
+ if let ExpnKind::Macro(MacroKind::Derive, _) = expn_data.kind {
+ return expn_data.default_transparency == Transparency::Opaque;
}
false
})
@@ -153,7 +135,10 @@
#[derive(Debug)]
crate struct HygieneData {
- expn_data: Vec<InternalExpnData>,
+ /// Each expansion should have an associated expansion data, but sometimes there's a delay
+ /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
+ /// first and then resolved later), so we use an `Option` here.
+ expn_data: Vec<Option<ExpnData>>,
syntax_context_data: Vec<SyntaxContextData>,
syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
}
@@ -161,10 +146,7 @@
impl HygieneData {
crate fn new(edition: Edition) -> Self {
HygieneData {
- expn_data: vec![InternalExpnData {
- parent: ExpnId::root(),
- expn_info: Some(ExpnInfo::default(ExpnKind::Root, DUMMY_SP, edition)),
- }],
+ expn_data: vec![Some(ExpnData::default(ExpnKind::Root, DUMMY_SP, edition))],
syntax_context_data: vec![SyntaxContextData {
outer_expn: ExpnId::root(),
outer_transparency: Transparency::Opaque,
@@ -181,25 +163,14 @@
GLOBALS.with(|globals| f(&mut *globals.hygiene_data.borrow_mut()))
}
- fn fresh_expn(&mut self, parent: ExpnId, expn_info: Option<ExpnInfo>) -> ExpnId {
- self.expn_data.push(InternalExpnData { parent, expn_info });
+ fn fresh_expn(&mut self, expn_data: Option<ExpnData>) -> ExpnId {
+ self.expn_data.push(expn_data);
ExpnId(self.expn_data.len() as u32 - 1)
}
- fn parent_expn(&self, expn_id: ExpnId) -> ExpnId {
- self.expn_data[expn_id.0 as usize].parent
- }
-
- fn expn_info(&self, expn_id: ExpnId) -> Option<&ExpnInfo> {
- if expn_id != ExpnId::root() {
- Some(self.expn_data[expn_id.0 as usize].expn_info.as_ref()
- .expect("no expansion info for an expansion ID"))
- } else {
- // FIXME: Some code relies on `expn_info().is_none()` meaning "no expansion".
- // Introduce a method for checking for "no expansion" instead and always return
- // `ExpnInfo` from this function instead of the `Option`.
- None
- }
+ fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
+ self.expn_data[expn_id.0 as usize].as_ref()
+ .expect("no expansion data for an expansion ID")
}
fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
@@ -207,17 +178,11 @@
if expn_id == ExpnId::root() {
return false;
}
- expn_id = self.parent_expn(expn_id);
+ expn_id = self.expn_data(expn_id).parent;
}
true
}
- fn default_transparency(&self, expn_id: ExpnId) -> Transparency {
- self.expn_info(expn_id).map_or(
- Transparency::SemiTransparent, |einfo| einfo.default_transparency
- )
- }
-
fn modern(&self, ctxt: SyntaxContext) -> SyntaxContext {
self.syntax_context_data[ctxt.0 as usize].opaque
}
@@ -246,7 +211,7 @@
fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
let mut marks = Vec::new();
- while ctxt != SyntaxContext::empty() {
+ while ctxt != SyntaxContext::root() {
marks.push((self.outer_expn(ctxt), self.outer_transparency(ctxt)));
ctxt = self.parent_ctxt(ctxt);
}
@@ -255,12 +220,8 @@
}
fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
- while span.ctxt() != crate::NO_EXPANSION && span.ctxt() != to {
- if let Some(info) = self.expn_info(self.outer_expn(span.ctxt())) {
- span = info.call_site;
- } else {
- break;
- }
+ while span.from_expansion() && span.ctxt() != to {
+ span = self.expn_data(self.outer_expn(span.ctxt())).call_site;
}
span
}
@@ -275,7 +236,9 @@
fn apply_mark(&mut self, ctxt: SyntaxContext, expn_id: ExpnId) -> SyntaxContext {
assert_ne!(expn_id, ExpnId::root());
- self.apply_mark_with_transparency(ctxt, expn_id, self.default_transparency(expn_id))
+ self.apply_mark_with_transparency(
+ ctxt, expn_id, self.expn_data(expn_id).default_transparency
+ )
}
fn apply_mark_with_transparency(&mut self, ctxt: SyntaxContext, expn_id: ExpnId,
@@ -285,15 +248,14 @@
return self.apply_mark_internal(ctxt, expn_id, transparency);
}
- let call_site_ctxt =
- self.expn_info(expn_id).map_or(SyntaxContext::empty(), |info| info.call_site.ctxt());
+ let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
self.modern(call_site_ctxt)
} else {
self.modern_and_legacy(call_site_ctxt)
};
- if call_site_ctxt == SyntaxContext::empty() {
+ if call_site_ctxt == SyntaxContext::root() {
return self.apply_mark_internal(ctxt, expn_id, transparency);
}
@@ -400,7 +362,7 @@
impl SyntaxContext {
#[inline]
- pub const fn empty() -> Self {
+ pub const fn root() -> Self {
SyntaxContext(0)
}
@@ -578,20 +540,20 @@
HygieneData::with(|data| data.outer_expn(self))
}
- /// `ctxt.outer_expn_info()` is equivalent to but faster than
- /// `ctxt.outer_expn().expn_info()`.
+ /// `ctxt.outer_expn_data()` is equivalent to but faster than
+ /// `ctxt.outer_expn().expn_data()`.
#[inline]
- pub fn outer_expn_info(self) -> Option<ExpnInfo> {
- HygieneData::with(|data| data.expn_info(data.outer_expn(self)).cloned())
+ pub fn outer_expn_data(self) -> ExpnData {
+ HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
}
- /// `ctxt.outer_expn_with_info()` is equivalent to but faster than
- /// `{ let outer = ctxt.outer_expn(); (outer, outer.expn_info()) }`.
+ /// `ctxt.outer_expn_with_data()` is equivalent to but faster than
+ /// `{ let outer = ctxt.outer_expn(); (outer, outer.expn_data()) }`.
#[inline]
- pub fn outer_expn_with_info(self) -> (ExpnId, Option<ExpnInfo>) {
+ pub fn outer_expn_with_data(self) -> (ExpnId, ExpnData) {
HygieneData::with(|data| {
let outer = data.outer_expn(self);
- (outer, data.expn_info(outer).cloned())
+ (outer, data.expn_data(outer).clone())
})
}
@@ -612,10 +574,10 @@
/// other compiler-generated code to set per-span properties like allowed unstable features.
/// The returned span belongs to the created expansion and has the new properties,
/// but its location is inherited from the current span.
- pub fn fresh_expansion(self, parent: ExpnId, expn_info: ExpnInfo) -> Span {
+ pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
HygieneData::with(|data| {
- let expn_id = data.fresh_expn(parent, Some(expn_info));
- self.with_ctxt(data.apply_mark(SyntaxContext::empty(), expn_id))
+ let expn_id = data.fresh_expn(Some(expn_data));
+ self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id))
})
}
}
@@ -623,8 +585,12 @@
/// A subset of properties from both macro definition and macro call available through global data.
/// Avoid using this if you have access to the original definition or call structures.
#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
-pub struct ExpnInfo {
+pub struct ExpnData {
// --- The part unique to each expansion.
+ /// The kind of this expansion - macro or compiler desugaring.
+ pub kind: ExpnKind,
+ /// The expansion that produced this expansion.
+ pub parent: ExpnId,
/// The location of the actual macro invocation or syntax sugar , e.g.
/// `let x = foo!();` or `if let Some(y) = x {}`
///
@@ -632,18 +598,18 @@
/// `foo!()` invoked `bar!()` internally, and there was an
/// expression inside `bar!`; the call_site of the expression in
/// the expansion would point to the `bar!` invocation; that
- /// call_site span would have its own ExpnInfo, with the call_site
+ /// call_site span would have its own ExpnData, with the call_site
/// pointing to the `foo!` invocation.
pub call_site: Span,
- /// The kind of this expansion - macro or compiler desugaring.
- pub kind: ExpnKind,
// --- The part specific to the macro/desugaring definition.
- // --- FIXME: Share it between expansions with the same definition.
+ // --- It may be reasonable to share this part between expansions with the same definition,
+ // --- but such sharing is known to bring some minor inconveniences without also bringing
+ // --- noticeable perf improvements (PR #62898).
/// The span of the macro definition (possibly dummy).
/// This span serves only informational purpose and is not used for resolution.
pub def_site: Span,
- /// Transparency used by `apply_mark` for the expansion with this expansion info by default.
+ /// Transparency used by `apply_mark` for the expansion with this expansion data by default.
pub default_transparency: Transparency,
/// List of #[unstable]/feature-gated features that the macro is allowed to use
/// internally without forcing the whole crate to opt-in
@@ -659,12 +625,13 @@
pub edition: Edition,
}
-impl ExpnInfo {
- /// Constructs an expansion info with default properties.
- pub fn default(kind: ExpnKind, call_site: Span, edition: Edition) -> ExpnInfo {
- ExpnInfo {
- call_site,
+impl ExpnData {
+ /// Constructs expansion data with default properties.
+ pub fn default(kind: ExpnKind, call_site: Span, edition: Edition) -> ExpnData {
+ ExpnData {
kind,
+ parent: ExpnId::root(),
+ call_site,
def_site: DUMMY_SP,
default_transparency: Transparency::SemiTransparent,
allow_internal_unstable: None,
@@ -675,12 +642,17 @@
}
pub fn allow_unstable(kind: ExpnKind, call_site: Span, edition: Edition,
- allow_internal_unstable: Lrc<[Symbol]>) -> ExpnInfo {
- ExpnInfo {
+ allow_internal_unstable: Lrc<[Symbol]>) -> ExpnData {
+ ExpnData {
allow_internal_unstable: Some(allow_internal_unstable),
- ..ExpnInfo::default(kind, call_site, edition)
+ ..ExpnData::default(kind, call_site, edition)
}
}
+
+ #[inline]
+ pub fn is_root(&self) -> bool {
+ if let ExpnKind::Root = self.kind { true } else { false }
+ }
}
/// Expansion kind.
@@ -767,14 +739,14 @@
}
}
-impl Encodable for SyntaxContext {
+impl Encodable for ExpnId {
fn encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
Ok(()) // FIXME(jseyfried) intercrate hygiene
}
}
-impl Decodable for SyntaxContext {
- fn decode<D: Decoder>(_: &mut D) -> Result<SyntaxContext, D::Error> {
- Ok(SyntaxContext::empty()) // FIXME(jseyfried) intercrate hygiene
+impl Decodable for ExpnId {
+ fn decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
+ Ok(ExpnId::root()) // FIXME(jseyfried) intercrate hygiene
}
}
diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs
index 02a7433..aa36fe2 100644
--- a/src/libsyntax_pos/lib.rs
+++ b/src/libsyntax_pos/lib.rs
@@ -21,7 +21,7 @@
pub mod edition;
use edition::Edition;
pub mod hygiene;
-pub use hygiene::{ExpnId, SyntaxContext, ExpnInfo, ExpnKind, MacroKind, DesugaringKind};
+pub use hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind, MacroKind, DesugaringKind};
mod span_encoding;
pub use span_encoding::{Span, DUMMY_SP};
@@ -49,7 +49,6 @@
symbol_interner: Lock<symbol::Interner>,
span_interner: Lock<span_encoding::SpanInterner>,
hygiene_data: Lock<hygiene::HygieneData>,
- edition: Edition,
}
impl Globals {
@@ -58,7 +57,6 @@
symbol_interner: Lock::new(symbol::Interner::fresh()),
span_interner: Lock::new(span_encoding::SpanInterner::default()),
hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
- edition,
}
}
}
@@ -288,6 +286,17 @@
span.lo.0 == 0 && span.hi.0 == 0
}
+ /// Returns `true` if this span comes from a macro or desugaring.
+ #[inline]
+ pub fn from_expansion(self) -> bool {
+ self.ctxt() != SyntaxContext::root()
+ }
+
+ #[inline]
+ pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
+ Span::new(lo, hi, SyntaxContext::root())
+ }
+
/// Returns a new span representing an empty span at the beginning of this span
#[inline]
pub fn shrink_to_lo(self) -> Span {
@@ -344,20 +353,20 @@
/// Returns the source span -- this is either the supplied span, or the span for
/// the macro callsite that expanded to it.
pub fn source_callsite(self) -> Span {
- self.ctxt().outer_expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
+ let expn_data = self.ctxt().outer_expn_data();
+ if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
}
/// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
/// if any.
pub fn parent(self) -> Option<Span> {
- self.ctxt().outer_expn_info().map(|i| i.call_site)
+ let expn_data = self.ctxt().outer_expn_data();
+ if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
}
/// Edition of the crate from which this span came.
pub fn edition(self) -> edition::Edition {
- self.ctxt().outer_expn_info().map_or_else(|| {
- Edition::from_session()
- }, |einfo| einfo.edition)
+ self.ctxt().outer_expn_data().edition
}
#[inline]
@@ -373,52 +382,42 @@
/// Returns the source callee.
///
/// Returns `None` if the supplied span has no expansion trace,
- /// else returns the `ExpnInfo` for the macro definition
+ /// else returns the `ExpnData` for the macro definition
/// corresponding to the source callsite.
- pub fn source_callee(self) -> Option<ExpnInfo> {
- fn source_callee(info: ExpnInfo) -> ExpnInfo {
- match info.call_site.ctxt().outer_expn_info() {
- Some(info) => source_callee(info),
- None => info,
- }
+ pub fn source_callee(self) -> Option<ExpnData> {
+ fn source_callee(expn_data: ExpnData) -> ExpnData {
+ let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
+ if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
}
- self.ctxt().outer_expn_info().map(source_callee)
+ let expn_data = self.ctxt().outer_expn_data();
+ if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
}
/// Checks if a span is "internal" to a macro in which `#[unstable]`
/// items can be used (that is, a macro marked with
/// `#[allow_internal_unstable]`).
pub fn allows_unstable(&self, feature: Symbol) -> bool {
- match self.ctxt().outer_expn_info() {
- Some(info) => info
- .allow_internal_unstable
- .map_or(false, |features| features.iter().any(|&f|
- f == feature || f == sym::allow_internal_unstable_backcompat_hack
- )),
- None => false,
- }
+ self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
+ features.iter().any(|&f| {
+ f == feature || f == sym::allow_internal_unstable_backcompat_hack
+ })
+ })
}
/// Checks if this span arises from a compiler desugaring of kind `kind`.
pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
- match self.ctxt().outer_expn_info() {
- Some(info) => match info.kind {
- ExpnKind::Desugaring(k) => k == kind,
- _ => false,
- },
- None => false,
+ match self.ctxt().outer_expn_data().kind {
+ ExpnKind::Desugaring(k) => k == kind,
+ _ => false,
}
}
/// Returns the compiler desugaring that created this span, or `None`
/// if this span is not from a desugaring.
pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
- match self.ctxt().outer_expn_info() {
- Some(info) => match info.kind {
- ExpnKind::Desugaring(k) => Some(k),
- _ => None
- },
- None => None
+ match self.ctxt().outer_expn_data().kind {
+ ExpnKind::Desugaring(k) => Some(k),
+ _ => None
}
}
@@ -426,19 +425,20 @@
/// can be used without triggering the `unsafe_code` lint
// (that is, a macro marked with `#[allow_internal_unsafe]`).
pub fn allows_unsafe(&self) -> bool {
- match self.ctxt().outer_expn_info() {
- Some(info) => info.allow_internal_unsafe,
- None => false,
- }
+ self.ctxt().outer_expn_data().allow_internal_unsafe
}
pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
let mut prev_span = DUMMY_SP;
let mut result = vec![];
- while let Some(info) = self.ctxt().outer_expn_info() {
+ loop {
+ let expn_data = self.ctxt().outer_expn_data();
+ if expn_data.is_root() {
+ break;
+ }
// Don't print recursive invocations.
- if !info.call_site.source_equal(&prev_span) {
- let (pre, post) = match info.kind {
+ if !expn_data.call_site.source_equal(&prev_span) {
+ let (pre, post) = match expn_data.kind {
ExpnKind::Root => break,
ExpnKind::Desugaring(..) => ("desugaring of ", ""),
ExpnKind::Macro(macro_kind, _) => match macro_kind {
@@ -448,14 +448,14 @@
}
};
result.push(MacroBacktrace {
- call_site: info.call_site,
- macro_decl_name: format!("{}{}{}", pre, info.kind.descr(), post),
- def_site_span: info.def_site,
+ call_site: expn_data.call_site,
+ macro_decl_name: format!("{}{}{}", pre, expn_data.kind.descr(), post),
+ def_site_span: expn_data.def_site,
});
}
prev_span = self;
- self = info.call_site;
+ self = expn_data.call_site;
}
result
}
@@ -468,9 +468,9 @@
// Return the macro span on its own to avoid weird diagnostic output. It is preferable to
// have an incomplete span than a completely nonsensical one.
if span_data.ctxt != end_data.ctxt {
- if span_data.ctxt == SyntaxContext::empty() {
+ if span_data.ctxt == SyntaxContext::root() {
return end;
- } else if end_data.ctxt == SyntaxContext::empty() {
+ } else if end_data.ctxt == SyntaxContext::root() {
return self;
}
// Both spans fall within a macro.
@@ -479,7 +479,7 @@
Span::new(
cmp::min(span_data.lo, end_data.lo),
cmp::max(span_data.hi, end_data.hi),
- if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
+ if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
)
}
@@ -490,7 +490,7 @@
Span::new(
span.hi,
end.lo,
- if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
+ if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
)
}
@@ -501,7 +501,7 @@
Span::new(
span.lo,
end.lo,
- if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
+ if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
)
}
@@ -611,7 +611,7 @@
d.read_struct("Span", 2, |d| {
let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
- Ok(Span::new(lo, hi, NO_EXPANSION))
+ Ok(Span::with_root_ctxt(lo, hi))
})
}
}
@@ -755,8 +755,6 @@
}
}
-pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
-
/// Identifies an offset of a multi-byte character in a `SourceFile`.
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
pub struct MultiByteChar {
diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs
index 2d95562..bed898f 100644
--- a/src/libsyntax_pos/symbol.rs
+++ b/src/libsyntax_pos/symbol.rs
@@ -8,13 +8,13 @@
use rustc_data_structures::newtype_index;
use rustc_macros::symbols;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
+use rustc_serialize::{UseSpecializedDecodable, UseSpecializedEncodable};
use std::cmp::{PartialEq, Ordering, PartialOrd, Ord};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str;
-use crate::hygiene::SyntaxContext;
use crate::{Span, DUMMY_SP, GLOBALS};
#[cfg(test)]
@@ -610,7 +610,6 @@
rust_eh_personality,
rust_eh_unwind_resume,
rust_oom,
- __rust_unstable_column,
rvalue_static_promotion,
sanitizer_runtime,
_Self,
@@ -745,25 +744,25 @@
Ident { name, span }
}
- /// Constructs a new identifier with an empty syntax context.
+ /// Constructs a new identifier with a dummy span.
#[inline]
- pub const fn with_empty_ctxt(name: Symbol) -> Ident {
+ pub const fn with_dummy_span(name: Symbol) -> Ident {
Ident::new(name, DUMMY_SP)
}
#[inline]
pub fn invalid() -> Ident {
- Ident::with_empty_ctxt(kw::Invalid)
+ Ident::with_dummy_span(kw::Invalid)
}
/// Maps an interned string to an identifier with an empty syntax context.
pub fn from_interned_str(string: InternedString) -> Ident {
- Ident::with_empty_ctxt(string.as_symbol())
+ Ident::with_dummy_span(string.as_symbol())
}
/// Maps a string to an identifier with an empty span.
pub fn from_str(string: &str) -> Ident {
- Ident::with_empty_ctxt(Symbol::intern(string))
+ Ident::with_dummy_span(Symbol::intern(string))
}
/// Maps a string and a span to an identifier.
@@ -849,28 +848,9 @@
}
}
-impl Encodable for Ident {
- fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
- if self.span.ctxt().modern() == SyntaxContext::empty() {
- s.emit_str(&self.as_str())
- } else { // FIXME(jseyfried): intercrate hygiene
- let mut string = "#".to_owned();
- string.push_str(&self.as_str());
- s.emit_str(&string)
- }
- }
-}
+impl UseSpecializedEncodable for Ident {}
-impl Decodable for Ident {
- fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
- let string = d.read_str()?;
- Ok(if !string.starts_with('#') {
- Ident::from_str(&string)
- } else { // FIXME(jseyfried): intercrate hygiene
- Ident::from_str(&string[1..]).gensym()
- })
- }
-}
+impl UseSpecializedDecodable for Ident {}
/// A symbol is an interned or gensymed string. A gensym is a symbol that is
/// never equal to any other symbol.
diff --git a/src/libunwind/Cargo.toml b/src/libunwind/Cargo.toml
index f0f1bab..f10df8c 100644
--- a/src/libunwind/Cargo.toml
+++ b/src/libunwind/Cargo.toml
@@ -22,7 +22,7 @@
cfg-if = "0.1.8"
[build-dependencies]
-cc = { optional = true, version = "1.0.1" }
+cc = { version = "1.0.1" }
[features]
-llvm-libunwind = ["cc"]
+llvm-libunwind = []
diff --git a/src/libunwind/build.rs b/src/libunwind/build.rs
index c1b0dbc..f24d957 100644
--- a/src/libunwind/build.rs
+++ b/src/libunwind/build.rs
@@ -5,14 +5,14 @@
let target = env::var("TARGET").expect("TARGET was not set");
if cfg!(feature = "llvm-libunwind") &&
- (target.contains("linux") ||
+ ((target.contains("linux") && !target.contains("musl")) ||
target.contains("fuchsia")) {
// Build the unwinding from libunwind C/C++ source code.
- #[cfg(feature = "llvm-libunwind")]
llvm_libunwind::compile();
} else if target.contains("linux") {
if target.contains("musl") {
- // musl is handled in lib.rs
+ // linking for musl is handled in lib.rs
+ llvm_libunwind::compile();
} else if !target.contains("android") {
println!("cargo:rustc-link-lib=gcc_s");
}
@@ -23,7 +23,11 @@
} else if target.contains("netbsd") {
println!("cargo:rustc-link-lib=gcc_s");
} else if target.contains("openbsd") {
- println!("cargo:rustc-link-lib=c++abi");
+ if target.contains("sparc64") {
+ println!("cargo:rustc-link-lib=gcc");
+ } else {
+ println!("cargo:rustc-link-lib=c++abi");
+ }
} else if target.contains("solaris") {
println!("cargo:rustc-link-lib=gcc_s");
} else if target.contains("dragonfly") {
@@ -44,7 +48,6 @@
}
}
-#[cfg(feature = "llvm-libunwind")]
mod llvm_libunwind {
use std::env;
use std::path::Path;
@@ -96,6 +99,15 @@
cfg.file(root.join("src").join(src));
}
+ if target_env == "musl" {
+ // use the same C compiler command to compile C++ code so we do not need to setup the
+ // C++ compiler env variables on the builders
+ cfg.cpp(false);
+ // linking for musl is handled in lib.rs
+ cfg.cargo_metadata(false);
+ println!("cargo:rustc-link-search=native={}", env::var("OUT_DIR").unwrap());
+ }
+
cfg.compile("unwind");
}
}
diff --git a/src/test/run-make-fulldeps/reproducible-build-2/Makefile b/src/test/run-make-fulldeps/reproducible-build-2/Makefile
index b96954f..45c9a74 100644
--- a/src/test/run-make-fulldeps/reproducible-build-2/Makefile
+++ b/src/test/run-make-fulldeps/reproducible-build-2/Makefile
@@ -5,7 +5,8 @@
# Objects are reproducible but their path is not.
all: \
- fat_lto
+ fat_lto \
+ sysroot
fat_lto:
rm -rf $(TMPDIR) && mkdir $(TMPDIR)
@@ -14,3 +15,12 @@
cp $(TMPDIR)/reproducible-build $(TMPDIR)/reproducible-build-a
$(RUSTC) reproducible-build.rs -C lto=fat
cmp "$(TMPDIR)/reproducible-build-a" "$(TMPDIR)/reproducible-build" || exit 1
+
+sysroot:
+ rm -rf $(TMPDIR) && mkdir $(TMPDIR)
+ $(RUSTC) reproducible-build-aux.rs
+ $(RUSTC) reproducible-build.rs --crate-type rlib --sysroot $(shell $(RUSTC) --print sysroot) --remap-path-prefix=$(shell $(RUSTC) --print sysroot)=/sysroot
+ cp -r $(shell $(RUSTC) --print sysroot) $(TMPDIR)/sysroot
+ cp $(TMPDIR)/libreproducible_build.rlib $(TMPDIR)/libfoo.rlib
+ $(RUSTC) reproducible-build.rs --crate-type rlib --sysroot $(TMPDIR)/sysroot --remap-path-prefix=$(TMPDIR)/sysroot=/sysroot
+ cmp "$(TMPDIR)/libreproducible_build.rlib" "$(TMPDIR)/libfoo.rlib" || exit 1
diff --git a/src/test/ui/.gitattributes b/src/test/ui/.gitattributes
index b62ade7..489dc8a 100644
--- a/src/test/ui/.gitattributes
+++ b/src/test/ui/.gitattributes
@@ -1,2 +1,3 @@
lexer-crlf-line-endings-string-literal-doc-comment.rs -text
trailing-carriage-return-in-string.rs -text
+*.bin -text
diff --git a/src/test/ui/abi-sysv64-arg-passing.rs b/src/test/ui/abi/abi-sysv64-arg-passing.rs
similarity index 100%
rename from src/test/ui/abi-sysv64-arg-passing.rs
rename to src/test/ui/abi/abi-sysv64-arg-passing.rs
diff --git a/src/test/ui/abi-sysv64-register-usage.rs b/src/test/ui/abi/abi-sysv64-register-usage.rs
similarity index 100%
rename from src/test/ui/abi-sysv64-register-usage.rs
rename to src/test/ui/abi/abi-sysv64-register-usage.rs
diff --git a/src/test/ui/abort-on-c-abi.rs b/src/test/ui/abi/abort-on-c-abi.rs
similarity index 100%
rename from src/test/ui/abort-on-c-abi.rs
rename to src/test/ui/abi/abort-on-c-abi.rs
diff --git a/src/test/ui/anon-extern-mod.rs b/src/test/ui/abi/anon-extern-mod.rs
similarity index 100%
rename from src/test/ui/anon-extern-mod.rs
rename to src/test/ui/abi/anon-extern-mod.rs
diff --git a/src/test/ui/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs
similarity index 100%
rename from src/test/ui/auxiliary/anon-extern-mod-cross-crate-1.rs
rename to src/test/ui/abi/auxiliary/anon-extern-mod-cross-crate-1.rs
diff --git a/src/test/ui/auxiliary/foreign_lib.rs b/src/test/ui/abi/auxiliary/foreign_lib.rs
similarity index 100%
rename from src/test/ui/auxiliary/foreign_lib.rs
rename to src/test/ui/abi/auxiliary/foreign_lib.rs
diff --git a/src/test/ui/c-stack-as-value.rs b/src/test/ui/abi/c-stack-as-value.rs
similarity index 100%
rename from src/test/ui/c-stack-as-value.rs
rename to src/test/ui/abi/c-stack-as-value.rs
diff --git a/src/test/ui/cabi-int-widening.rs b/src/test/ui/abi/cabi-int-widening.rs
similarity index 100%
rename from src/test/ui/cabi-int-widening.rs
rename to src/test/ui/abi/cabi-int-widening.rs
diff --git a/src/test/ui/consts/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs
similarity index 100%
rename from src/test/ui/consts/auxiliary/anon-extern-mod-cross-crate-1.rs
rename to src/test/ui/abi/consts/auxiliary/anon-extern-mod-cross-crate-1.rs
diff --git a/src/test/ui/cross-crate/anon-extern-mod-cross-crate-2.rs b/src/test/ui/abi/cross-crate/anon-extern-mod-cross-crate-2.rs
similarity index 100%
rename from src/test/ui/cross-crate/anon-extern-mod-cross-crate-2.rs
rename to src/test/ui/abi/cross-crate/anon-extern-mod-cross-crate-2.rs
diff --git a/src/test/ui/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs
similarity index 100%
rename from src/test/ui/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs
rename to src/test/ui/abi/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs
diff --git a/src/test/ui/duplicated-external-mods.rs b/src/test/ui/abi/duplicated-external-mods.rs
similarity index 100%
rename from src/test/ui/duplicated-external-mods.rs
rename to src/test/ui/abi/duplicated-external-mods.rs
diff --git a/src/test/ui/extern/auxiliary/extern-crosscrate-source.rs b/src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs
similarity index 100%
rename from src/test/ui/extern/auxiliary/extern-crosscrate-source.rs
rename to src/test/ui/abi/extern/auxiliary/extern-crosscrate-source.rs
diff --git a/src/test/ui/extern/extern-call-deep.rs b/src/test/ui/abi/extern/extern-call-deep.rs
similarity index 100%
rename from src/test/ui/extern/extern-call-deep.rs
rename to src/test/ui/abi/extern/extern-call-deep.rs
diff --git a/src/test/ui/extern/extern-call-deep2.rs b/src/test/ui/abi/extern/extern-call-deep2.rs
similarity index 100%
rename from src/test/ui/extern/extern-call-deep2.rs
rename to src/test/ui/abi/extern/extern-call-deep2.rs
diff --git a/src/test/ui/extern/extern-call-direct.rs b/src/test/ui/abi/extern/extern-call-direct.rs
similarity index 100%
rename from src/test/ui/extern/extern-call-direct.rs
rename to src/test/ui/abi/extern/extern-call-direct.rs
diff --git a/src/test/ui/extern/extern-call-indirect.rs b/src/test/ui/abi/extern/extern-call-indirect.rs
similarity index 100%
rename from src/test/ui/extern/extern-call-indirect.rs
rename to src/test/ui/abi/extern/extern-call-indirect.rs
diff --git a/src/test/ui/extern/extern-call-scrub.rs b/src/test/ui/abi/extern/extern-call-scrub.rs
similarity index 100%
rename from src/test/ui/extern/extern-call-scrub.rs
rename to src/test/ui/abi/extern/extern-call-scrub.rs
diff --git a/src/test/ui/extern/extern-crosscrate.rs b/src/test/ui/abi/extern/extern-crosscrate.rs
similarity index 100%
rename from src/test/ui/extern/extern-crosscrate.rs
rename to src/test/ui/abi/extern/extern-crosscrate.rs
diff --git a/src/test/ui/extern/extern-pass-TwoU16s.rs b/src/test/ui/abi/extern/extern-pass-TwoU16s.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-TwoU16s.rs
rename to src/test/ui/abi/extern/extern-pass-TwoU16s.rs
diff --git a/src/test/ui/extern/extern-pass-TwoU32s.rs b/src/test/ui/abi/extern/extern-pass-TwoU32s.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-TwoU32s.rs
rename to src/test/ui/abi/extern/extern-pass-TwoU32s.rs
diff --git a/src/test/ui/extern/extern-pass-TwoU64s.rs b/src/test/ui/abi/extern/extern-pass-TwoU64s.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-TwoU64s.rs
rename to src/test/ui/abi/extern/extern-pass-TwoU64s.rs
diff --git a/src/test/ui/extern/extern-pass-TwoU8s.rs b/src/test/ui/abi/extern/extern-pass-TwoU8s.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-TwoU8s.rs
rename to src/test/ui/abi/extern/extern-pass-TwoU8s.rs
diff --git a/src/test/ui/extern/extern-pass-char.rs b/src/test/ui/abi/extern/extern-pass-char.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-char.rs
rename to src/test/ui/abi/extern/extern-pass-char.rs
diff --git a/src/test/ui/extern/extern-pass-double.rs b/src/test/ui/abi/extern/extern-pass-double.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-double.rs
rename to src/test/ui/abi/extern/extern-pass-double.rs
diff --git a/src/test/ui/extern/extern-pass-empty.rs b/src/test/ui/abi/extern/extern-pass-empty.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-empty.rs
rename to src/test/ui/abi/extern/extern-pass-empty.rs
diff --git a/src/test/ui/extern/extern-pass-u32.rs b/src/test/ui/abi/extern/extern-pass-u32.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-u32.rs
rename to src/test/ui/abi/extern/extern-pass-u32.rs
diff --git a/src/test/ui/extern/extern-pass-u64.rs b/src/test/ui/abi/extern/extern-pass-u64.rs
similarity index 100%
rename from src/test/ui/extern/extern-pass-u64.rs
rename to src/test/ui/abi/extern/extern-pass-u64.rs
diff --git a/src/test/ui/extern/extern-return-TwoU16s.rs b/src/test/ui/abi/extern/extern-return-TwoU16s.rs
similarity index 100%
rename from src/test/ui/extern/extern-return-TwoU16s.rs
rename to src/test/ui/abi/extern/extern-return-TwoU16s.rs
diff --git a/src/test/ui/extern/extern-return-TwoU32s.rs b/src/test/ui/abi/extern/extern-return-TwoU32s.rs
similarity index 100%
rename from src/test/ui/extern/extern-return-TwoU32s.rs
rename to src/test/ui/abi/extern/extern-return-TwoU32s.rs
diff --git a/src/test/ui/extern/extern-return-TwoU64s.rs b/src/test/ui/abi/extern/extern-return-TwoU64s.rs
similarity index 100%
rename from src/test/ui/extern/extern-return-TwoU64s.rs
rename to src/test/ui/abi/extern/extern-return-TwoU64s.rs
diff --git a/src/test/ui/extern/extern-return-TwoU8s.rs b/src/test/ui/abi/extern/extern-return-TwoU8s.rs
similarity index 100%
rename from src/test/ui/extern/extern-return-TwoU8s.rs
rename to src/test/ui/abi/extern/extern-return-TwoU8s.rs
diff --git a/src/test/ui/foreign/auxiliary/foreign_lib.rs b/src/test/ui/abi/foreign/auxiliary/foreign_lib.rs
similarity index 100%
rename from src/test/ui/foreign/auxiliary/foreign_lib.rs
rename to src/test/ui/abi/foreign/auxiliary/foreign_lib.rs
diff --git a/src/test/ui/foreign/foreign-call-no-runtime.rs b/src/test/ui/abi/foreign/foreign-call-no-runtime.rs
similarity index 100%
rename from src/test/ui/foreign/foreign-call-no-runtime.rs
rename to src/test/ui/abi/foreign/foreign-call-no-runtime.rs
diff --git a/src/test/ui/foreign/foreign-dupe.rs b/src/test/ui/abi/foreign/foreign-dupe.rs
similarity index 100%
rename from src/test/ui/foreign/foreign-dupe.rs
rename to src/test/ui/abi/foreign/foreign-dupe.rs
diff --git a/src/test/ui/foreign/foreign-fn-with-byval.rs b/src/test/ui/abi/foreign/foreign-fn-with-byval.rs
similarity index 100%
rename from src/test/ui/foreign/foreign-fn-with-byval.rs
rename to src/test/ui/abi/foreign/foreign-fn-with-byval.rs
diff --git a/src/test/ui/foreign/foreign-no-abi.rs b/src/test/ui/abi/foreign/foreign-no-abi.rs
similarity index 100%
rename from src/test/ui/foreign/foreign-no-abi.rs
rename to src/test/ui/abi/foreign/foreign-no-abi.rs
diff --git a/src/test/ui/invoke-external-foreign.rs b/src/test/ui/abi/invoke-external-foreign.rs
similarity index 100%
rename from src/test/ui/invoke-external-foreign.rs
rename to src/test/ui/abi/invoke-external-foreign.rs
diff --git a/src/test/ui/lib-defaults.rs b/src/test/ui/abi/lib-defaults.rs
similarity index 100%
rename from src/test/ui/lib-defaults.rs
rename to src/test/ui/abi/lib-defaults.rs
diff --git a/src/test/ui/macros/macros-in-extern.rs b/src/test/ui/abi/macros/macros-in-extern.rs
similarity index 100%
rename from src/test/ui/macros/macros-in-extern.rs
rename to src/test/ui/abi/macros/macros-in-extern.rs
diff --git a/src/test/ui/macros/macros-in-extern.stderr b/src/test/ui/abi/macros/macros-in-extern.stderr
similarity index 100%
rename from src/test/ui/macros/macros-in-extern.stderr
rename to src/test/ui/abi/macros/macros-in-extern.stderr
diff --git a/src/test/ui/mir/mir_codegen_calls_variadic.rs b/src/test/ui/abi/mir/mir_codegen_calls_variadic.rs
similarity index 100%
rename from src/test/ui/mir/mir_codegen_calls_variadic.rs
rename to src/test/ui/abi/mir/mir_codegen_calls_variadic.rs
diff --git a/src/test/ui/numbers-arithmetic/i128-ffi.rs b/src/test/ui/abi/numbers-arithmetic/i128-ffi.rs
similarity index 100%
rename from src/test/ui/numbers-arithmetic/i128-ffi.rs
rename to src/test/ui/abi/numbers-arithmetic/i128-ffi.rs
diff --git a/src/test/ui/abi/proc-macro/auxiliary/test-macros.rs b/src/test/ui/abi/proc-macro/auxiliary/test-macros.rs
new file mode 100644
index 0000000..27efa44
--- /dev/null
+++ b/src/test/ui/abi/proc-macro/auxiliary/test-macros.rs
@@ -0,0 +1,112 @@
+// force-host
+// no-prefer-dynamic
+
+// Proc macros commonly used by tests.
+// `panic`/`print` -> `panic_bang`/`print_bang` to avoid conflicts with standard macros.
+
+#![crate_type = "proc-macro"]
+
+extern crate proc_macro;
+use proc_macro::TokenStream;
+
+// Macro that return empty token stream.
+
+#[proc_macro]
+pub fn empty(_: TokenStream) -> TokenStream {
+ TokenStream::new()
+}
+
+#[proc_macro_attribute]
+pub fn empty_attr(_: TokenStream, _: TokenStream) -> TokenStream {
+ TokenStream::new()
+}
+
+#[proc_macro_derive(Empty, attributes(empty_helper))]
+pub fn empty_derive(_: TokenStream) -> TokenStream {
+ TokenStream::new()
+}
+
+// Macro that panics.
+
+#[proc_macro]
+pub fn panic_bang(_: TokenStream) -> TokenStream {
+ panic!("panic-bang");
+}
+
+#[proc_macro_attribute]
+pub fn panic_attr(_: TokenStream, _: TokenStream) -> TokenStream {
+ panic!("panic-attr");
+}
+
+#[proc_macro_derive(Panic, attributes(panic_helper))]
+pub fn panic_derive(_: TokenStream) -> TokenStream {
+ panic!("panic-derive");
+}
+
+// Macros that return the input stream.
+
+#[proc_macro]
+pub fn identity(input: TokenStream) -> TokenStream {
+ input
+}
+
+#[proc_macro_attribute]
+pub fn identity_attr(_: TokenStream, input: TokenStream) -> TokenStream {
+ input
+}
+
+#[proc_macro_derive(Identity, attributes(identity_helper))]
+pub fn identity_derive(input: TokenStream) -> TokenStream {
+ input
+}
+
+// Macros that iterate and re-collect the input stream.
+
+#[proc_macro]
+pub fn recollect(input: TokenStream) -> TokenStream {
+ input.into_iter().collect()
+}
+
+#[proc_macro_attribute]
+pub fn recollect_attr(_: TokenStream, input: TokenStream) -> TokenStream {
+ input.into_iter().collect()
+}
+
+#[proc_macro_derive(Recollect, attributes(recollect_helper))]
+pub fn recollect_derive(input: TokenStream) -> TokenStream {
+ input.into_iter().collect()
+}
+
+// Macros that print their input in the original and re-collected forms (if they differ).
+
+fn print_helper(input: TokenStream, kind: &str) -> TokenStream {
+ let input_display = format!("{}", input);
+ let input_debug = format!("{:#?}", input);
+ let recollected = input.into_iter().collect();
+ let recollected_display = format!("{}", recollected);
+ let recollected_debug = format!("{:#?}", recollected);
+ println!("PRINT-{} INPUT (DISPLAY): {}", kind, input_display);
+ if recollected_display != input_display {
+ println!("PRINT-{} RE-COLLECTED (DISPLAY): {}", kind, recollected_display);
+ }
+ println!("PRINT-{} INPUT (DEBUG): {}", kind, input_debug);
+ if recollected_debug != input_debug {
+ println!("PRINT-{} RE-COLLECTED (DEBUG): {}", kind, recollected_debug);
+ }
+ recollected
+}
+
+#[proc_macro]
+pub fn print_bang(input: TokenStream) -> TokenStream {
+ print_helper(input, "BANG")
+}
+
+#[proc_macro_attribute]
+pub fn print_attr(_: TokenStream, input: TokenStream) -> TokenStream {
+ print_helper(input, "ATTR")
+}
+
+#[proc_macro_derive(Print, attributes(print_helper))]
+pub fn print_derive(input: TokenStream) -> TokenStream {
+ print_helper(input, "DERIVE")
+}
diff --git a/src/test/ui/proc-macro/macros-in-extern.rs b/src/test/ui/abi/proc-macro/macros-in-extern.rs
similarity index 100%
rename from src/test/ui/proc-macro/macros-in-extern.rs
rename to src/test/ui/abi/proc-macro/macros-in-extern.rs
diff --git a/src/test/ui/proc-macro/macros-in-extern.stderr b/src/test/ui/abi/proc-macro/macros-in-extern.stderr
similarity index 100%
rename from src/test/ui/proc-macro/macros-in-extern.stderr
rename to src/test/ui/abi/proc-macro/macros-in-extern.stderr
diff --git a/src/test/ui/segfault-no-out-of-stack.rs b/src/test/ui/abi/segfault-no-out-of-stack.rs
similarity index 100%
rename from src/test/ui/segfault-no-out-of-stack.rs
rename to src/test/ui/abi/segfault-no-out-of-stack.rs
diff --git a/src/test/ui/stack-probes-lto.rs b/src/test/ui/abi/stack-probes-lto.rs
similarity index 100%
rename from src/test/ui/stack-probes-lto.rs
rename to src/test/ui/abi/stack-probes-lto.rs
diff --git a/src/test/ui/stack-probes.rs b/src/test/ui/abi/stack-probes.rs
similarity index 100%
rename from src/test/ui/stack-probes.rs
rename to src/test/ui/abi/stack-probes.rs
diff --git a/src/test/ui/statics/static-mut-foreign.rs b/src/test/ui/abi/statics/static-mut-foreign.rs
similarity index 100%
rename from src/test/ui/statics/static-mut-foreign.rs
rename to src/test/ui/abi/statics/static-mut-foreign.rs
diff --git a/src/test/ui/structs-enums/struct-return.rs b/src/test/ui/abi/struct-enums/struct-return.rs
similarity index 100%
rename from src/test/ui/structs-enums/struct-return.rs
rename to src/test/ui/abi/struct-enums/struct-return.rs
diff --git a/src/test/ui/union/union-c-interop.rs b/src/test/ui/abi/union/union-c-interop.rs
similarity index 100%
rename from src/test/ui/union/union-c-interop.rs
rename to src/test/ui/abi/union/union-c-interop.rs
diff --git a/src/test/ui/variadic-ffi.rs b/src/test/ui/abi/variadic-ffi.rs
similarity index 100%
rename from src/test/ui/variadic-ffi.rs
rename to src/test/ui/abi/variadic-ffi.rs
diff --git a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
index fab5892..64fd1a4 100644
--- a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
+++ b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
@@ -4,7 +4,7 @@
LL | ) -> &dyn Foo
| ^^^^^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#27r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#22r
error: lifetime may not live long enough
--> $DIR/issue-63388-1.rs:15:5
diff --git a/src/test/ui/async-await/suggest-switching-edition-on-await.rs b/src/test/ui/async-await/suggest-switching-edition-on-await.rs
new file mode 100644
index 0000000..1402f1c
--- /dev/null
+++ b/src/test/ui/async-await/suggest-switching-edition-on-await.rs
@@ -0,0 +1,45 @@
+use std::pin::Pin;
+use std::future::Future;
+
+fn main() {}
+
+fn await_on_struct_missing() {
+ struct S;
+ let x = S;
+ x.await;
+ //~^ ERROR no field `await` on type
+ //~| NOTE unknown field
+ //~| NOTE to `.await` a `Future`, switch to Rust 2018
+ //~| HELP set `edition = "2018"` in `Cargo.toml`
+ //~| NOTE for more on editions, read https://doc.rust-lang.org/edition-guide
+}
+
+fn await_on_struct_similar() {
+ struct S {
+ awai: u8,
+ }
+ let x = S { awai: 42 };
+ x.await;
+ //~^ ERROR no field `await` on type
+ //~| HELP a field with a similar name exists
+ //~| NOTE to `.await` a `Future`, switch to Rust 2018
+ //~| HELP set `edition = "2018"` in `Cargo.toml`
+ //~| NOTE for more on editions, read https://doc.rust-lang.org/edition-guide
+}
+
+fn await_on_63533(x: Pin<&mut dyn Future<Output = ()>>) {
+ x.await;
+ //~^ ERROR no field `await` on type
+ //~| NOTE unknown field
+ //~| NOTE to `.await` a `Future`, switch to Rust 2018
+ //~| HELP set `edition = "2018"` in `Cargo.toml`
+ //~| NOTE for more on editions, read https://doc.rust-lang.org/edition-guide
+}
+
+fn await_on_apit(x: impl Future<Output = ()>) {
+ x.await;
+ //~^ ERROR no field `await` on type
+ //~| NOTE to `.await` a `Future`, switch to Rust 2018
+ //~| HELP set `edition = "2018"` in `Cargo.toml`
+ //~| NOTE for more on editions, read https://doc.rust-lang.org/edition-guide
+}
diff --git a/src/test/ui/async-await/suggest-switching-edition-on-await.stderr b/src/test/ui/async-await/suggest-switching-edition-on-await.stderr
new file mode 100644
index 0000000..f623511
--- /dev/null
+++ b/src/test/ui/async-await/suggest-switching-edition-on-await.stderr
@@ -0,0 +1,43 @@
+error[E0609]: no field `await` on type `await_on_struct_missing::S`
+ --> $DIR/suggest-switching-edition-on-await.rs:9:7
+ |
+LL | x.await;
+ | ^^^^^ unknown field
+ |
+ = note: to `.await` a `Future`, switch to Rust 2018
+ = help: set `edition = "2018"` in `Cargo.toml`
+ = note: for more on editions, read https://doc.rust-lang.org/edition-guide
+
+error[E0609]: no field `await` on type `await_on_struct_similar::S`
+ --> $DIR/suggest-switching-edition-on-await.rs:22:7
+ |
+LL | x.await;
+ | ^^^^^ help: a field with a similar name exists: `awai`
+ |
+ = note: to `.await` a `Future`, switch to Rust 2018
+ = help: set `edition = "2018"` in `Cargo.toml`
+ = note: for more on editions, read https://doc.rust-lang.org/edition-guide
+
+error[E0609]: no field `await` on type `std::pin::Pin<&mut dyn std::future::Future<Output = ()>>`
+ --> $DIR/suggest-switching-edition-on-await.rs:31:7
+ |
+LL | x.await;
+ | ^^^^^ unknown field
+ |
+ = note: to `.await` a `Future`, switch to Rust 2018
+ = help: set `edition = "2018"` in `Cargo.toml`
+ = note: for more on editions, read https://doc.rust-lang.org/edition-guide
+
+error[E0609]: no field `await` on type `impl Future<Output = ()>`
+ --> $DIR/suggest-switching-edition-on-await.rs:40:7
+ |
+LL | x.await;
+ | ^^^^^
+ |
+ = note: to `.await` a `Future`, switch to Rust 2018
+ = help: set `edition = "2018"` in `Cargo.toml`
+ = note: for more on editions, read https://doc.rust-lang.org/edition-guide
+
+error: aborting due to 4 previous errors
+
+For more information about this error, try `rustc --explain E0609`.
diff --git a/src/test/ui/derives/derive-hygiene.rs b/src/test/ui/derives/derive-hygiene.rs
new file mode 100644
index 0000000..4fa83c4
--- /dev/null
+++ b/src/test/ui/derives/derive-hygiene.rs
@@ -0,0 +1,121 @@
+// Make sure that built-in derives don't rely on the user not declaring certain
+// names to work properly.
+
+// check-pass
+
+#![allow(nonstandard_style)]
+#![feature(decl_macro)]
+
+use std::prelude::v1::test as inline;
+
+static f: () = ();
+static cmp: () = ();
+static other: () = ();
+static state: () = ();
+static __self_0_0: () = ();
+static __self_1_0: () = ();
+static __self_vi: () = ();
+static __arg_1_0: () = ();
+static debug_trait_builder: () = ();
+
+struct isize;
+trait i16 {}
+
+trait MethodsInDerives: Sized {
+ fn debug_tuple(self) {}
+ fn debug_struct(self) {}
+ fn field(self) {}
+ fn finish(self) {}
+ fn clone(self) {}
+ fn cmp(self) {}
+ fn partial_cmp(self) {}
+ fn eq(self) {}
+ fn ne(self) {}
+ fn le(self) {}
+ fn lt(self) {}
+ fn ge(self) {}
+ fn gt(self) {}
+ fn hash(self) {}
+}
+
+trait GenericAny<T, U> {}
+impl<S, T, U> GenericAny<T, U> for S {}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+enum __H { V(i32), }
+
+#[repr(i16)]
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+enum W { A, B }
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+struct X<A: GenericAny<A, self::X<i32>>> {
+ A: A,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+struct Y<B>(B)
+where
+ B: From<B>;
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+enum Z<C> {
+ C(C),
+ B { C: C },
+}
+
+// Make sure that we aren't using `self::` in paths, since it doesn't work in
+// non-module scopes.
+const NON_MODULE: () = {
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum __H { V(i32), }
+
+ #[repr(i16)]
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum W { A, B }
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+ struct X<A: Fn(A) -> self::X<i32>> {
+ A: A,
+ }
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+ struct Y<B>(B)
+ where
+ B: From<B>;
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum Z<C> {
+ C(C),
+ B { C: C },
+ }
+};
+
+macro m() {
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum __H { V(i32), }
+
+ #[repr(i16)]
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum W { A, B }
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+ struct X<A: GenericAny<A, self::X<i32>>> {
+ A: A,
+ }
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
+ struct Y<B>(B)
+ where
+ B: From<B>;
+
+ #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
+ enum Z<C> {
+ C(C),
+ B { C: C },
+ }
+}
+
+m!();
+
+fn main() {}
diff --git a/src/test/ui/dropck/dropck_trait_cycle_checked.stderr b/src/test/ui/dropck/dropck_trait_cycle_checked.stderr
index 1e77920..dc3fbed 100644
--- a/src/test/ui/dropck/dropck_trait_cycle_checked.stderr
+++ b/src/test/ui/dropck/dropck_trait_cycle_checked.stderr
@@ -2,7 +2,7 @@
--> $DIR/dropck_trait_cycle_checked.rs:111:13
|
LL | let (o1, o2, o3): (Box<dyn Obj>, Box<dyn Obj>, Box<dyn Obj>) = (O::new(), O::new(), O::new());
- | -------- cast requires that `o2` is borrowed for `'static`
+ | -------- cast requires that `o2` is borrowed for `'static`
LL | o1.set0(&o2);
| ^^^ borrowed value does not live long enough
...
@@ -13,7 +13,7 @@
--> $DIR/dropck_trait_cycle_checked.rs:112:13
|
LL | let (o1, o2, o3): (Box<dyn Obj>, Box<dyn Obj>, Box<dyn Obj>) = (O::new(), O::new(), O::new());
- | -------- cast requires that `o3` is borrowed for `'static`
+ | -------- cast requires that `o3` is borrowed for `'static`
LL | o1.set0(&o2);
LL | o1.set1(&o3);
| ^^^ borrowed value does not live long enough
@@ -37,7 +37,7 @@
--> $DIR/dropck_trait_cycle_checked.rs:114:13
|
LL | let (o1, o2, o3): (Box<dyn Obj>, Box<dyn Obj>, Box<dyn Obj>) = (O::new(), O::new(), O::new());
- | -------- cast requires that `o3` is borrowed for `'static`
+ | -------- cast requires that `o3` is borrowed for `'static`
...
LL | o2.set1(&o3);
| ^^^ borrowed value does not live long enough
@@ -49,7 +49,7 @@
--> $DIR/dropck_trait_cycle_checked.rs:115:13
|
LL | let (o1, o2, o3): (Box<dyn Obj>, Box<dyn Obj>, Box<dyn Obj>) = (O::new(), O::new(), O::new());
- | -------- cast requires that `o1` is borrowed for `'static`
+ | -------- cast requires that `o1` is borrowed for `'static`
...
LL | o3.set0(&o1);
| ^^^ borrowed value does not live long enough
@@ -61,7 +61,7 @@
--> $DIR/dropck_trait_cycle_checked.rs:116:13
|
LL | let (o1, o2, o3): (Box<dyn Obj>, Box<dyn Obj>, Box<dyn Obj>) = (O::new(), O::new(), O::new());
- | -------- cast requires that `o2` is borrowed for `'static`
+ | -------- cast requires that `o2` is borrowed for `'static`
...
LL | o3.set1(&o2);
| ^^^ borrowed value does not live long enough
diff --git a/src/test/ui/duplicate/duplicate-type-parameter.stderr b/src/test/ui/duplicate/duplicate-type-parameter.stderr
index 8606479..6754574 100644
--- a/src/test/ui/duplicate/duplicate-type-parameter.stderr
+++ b/src/test/ui/duplicate/duplicate-type-parameter.stderr
@@ -1,4 +1,4 @@
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:1:12
|
LL | type Foo<T,T> = Option<T>;
@@ -6,7 +6,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:4:14
|
LL | struct Bar<T,T>(T);
@@ -14,7 +14,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:7:14
|
LL | struct Baz<T,T> {
@@ -22,7 +22,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:12:12
|
LL | enum Boo<T,T> {
@@ -30,7 +30,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:18:11
|
LL | fn quux<T,T>(x: T) {}
@@ -38,7 +38,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:21:13
|
LL | trait Qux<T,T> {}
@@ -46,7 +46,7 @@
| |
| first use of `T`
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/duplicate-type-parameter.rs:24:8
|
LL | impl<T,T> Qux<T,T> for Option<T> {}
diff --git a/src/test/ui/error-codes/E0194.rs b/src/test/ui/error-codes/E0194.rs
index 71eff0e..8a43f38 100644
--- a/src/test/ui/error-codes/E0194.rs
+++ b/src/test/ui/error-codes/E0194.rs
@@ -1,7 +1,7 @@
trait Foo<T> {
fn do_something(&self) -> T;
fn do_something_else<T: Clone>(&self, bar: T);
- //~^ ERROR E0194
+ //~^ ERROR E0403
}
fn main() {
diff --git a/src/test/ui/error-codes/E0194.stderr b/src/test/ui/error-codes/E0194.stderr
index ab4918a..f2c908e 100644
--- a/src/test/ui/error-codes/E0194.stderr
+++ b/src/test/ui/error-codes/E0194.stderr
@@ -1,12 +1,12 @@
-error[E0194]: type parameter `T` shadows another type parameter of the same name
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/E0194.rs:3:26
|
LL | trait Foo<T> {
- | - first `T` declared here
+ | - first use of `T`
LL | fn do_something(&self) -> T;
LL | fn do_something_else<T: Clone>(&self, bar: T);
- | ^ shadows another type parameter
+ | ^ already used
error: aborting due to previous error
-For more information about this error, try `rustc --explain E0194`.
+For more information about this error, try `rustc --explain E0403`.
diff --git a/src/test/ui/error-codes/E0403.stderr b/src/test/ui/error-codes/E0403.stderr
index 2bd7de6..d76a58a 100644
--- a/src/test/ui/error-codes/E0403.stderr
+++ b/src/test/ui/error-codes/E0403.stderr
@@ -1,4 +1,4 @@
-error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/E0403.rs:1:11
|
LL | fn foo<T, T>(s: T, u: T) {}
diff --git a/src/test/ui/feature-gates/feature-gate-generators.rs b/src/test/ui/feature-gates/feature-gate-generators.rs
index cee930f..382d891 100644
--- a/src/test/ui/feature-gates/feature-gate-generators.rs
+++ b/src/test/ui/feature-gates/feature-gate-generators.rs
@@ -2,3 +2,9 @@
yield true; //~ ERROR yield syntax is experimental
//~^ ERROR yield statement outside of generator literal
}
+
+#[cfg(FALSE)]
+fn foo() {
+ yield; //~ ERROR yield syntax is experimental
+ yield 0; //~ ERROR yield syntax is experimental
+}
diff --git a/src/test/ui/feature-gates/feature-gate-generators.stderr b/src/test/ui/feature-gates/feature-gate-generators.stderr
index cdb0560..24b814b 100644
--- a/src/test/ui/feature-gates/feature-gate-generators.stderr
+++ b/src/test/ui/feature-gates/feature-gate-generators.stderr
@@ -7,12 +7,30 @@
= note: for more information, see https://github.com/rust-lang/rust/issues/43122
= help: add `#![feature(generators)]` to the crate attributes to enable
+error[E0658]: yield syntax is experimental
+ --> $DIR/feature-gate-generators.rs:8:5
+ |
+LL | yield;
+ | ^^^^^
+ |
+ = note: for more information, see https://github.com/rust-lang/rust/issues/43122
+ = help: add `#![feature(generators)]` to the crate attributes to enable
+
+error[E0658]: yield syntax is experimental
+ --> $DIR/feature-gate-generators.rs:9:5
+ |
+LL | yield 0;
+ | ^^^^^^^
+ |
+ = note: for more information, see https://github.com/rust-lang/rust/issues/43122
+ = help: add `#![feature(generators)]` to the crate attributes to enable
+
error[E0627]: yield statement outside of generator literal
--> $DIR/feature-gate-generators.rs:2:5
|
LL | yield true;
| ^^^^^^^^^^
-error: aborting due to 2 previous errors
+error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0658`.
diff --git a/src/test/ui/feature-gates/feature-gate-rustc-diagnostic-macros.stderr b/src/test/ui/feature-gates/feature-gate-rustc-diagnostic-macros.stderr
index 478bc09..676b8b9 100644
--- a/src/test/ui/feature-gates/feature-gate-rustc-diagnostic-macros.stderr
+++ b/src/test/ui/feature-gates/feature-gate-rustc-diagnostic-macros.stderr
@@ -4,17 +4,17 @@
LL | __build_diagnostic_array!(DIAGNOSTICS);
| ^^^^^^^^^^^^^^^^^^^^^^^^
-error: cannot find macro `__register_diagnostic!` in this scope
- --> $DIR/feature-gate-rustc-diagnostic-macros.rs:4:1
- |
-LL | __register_diagnostic!(E0001);
- | ^^^^^^^^^^^^^^^^^^^^^
-
error: cannot find macro `__diagnostic_used!` in this scope
--> $DIR/feature-gate-rustc-diagnostic-macros.rs:8:5
|
LL | __diagnostic_used!(E0001);
| ^^^^^^^^^^^^^^^^^
+error: cannot find macro `__register_diagnostic!` in this scope
+ --> $DIR/feature-gate-rustc-diagnostic-macros.rs:4:1
+ |
+LL | __register_diagnostic!(E0001);
+ | ^^^^^^^^^^^^^^^^^^^^^
+
error: aborting due to 3 previous errors
diff --git a/src/test/ui/hygiene/auxiliary/codegen-attrs.rs b/src/test/ui/hygiene/auxiliary/codegen-attrs.rs
new file mode 100644
index 0000000..74afedb
--- /dev/null
+++ b/src/test/ui/hygiene/auxiliary/codegen-attrs.rs
@@ -0,0 +1,10 @@
+#![feature(decl_macro)]
+
+macro m($f:ident) {
+ #[export_name = "export_function_name"]
+ pub fn $f() -> i32 {
+ 2
+ }
+}
+
+m!(rust_function_name);
diff --git a/src/test/ui/hygiene/cross-crate-codegen-attrs.rs b/src/test/ui/hygiene/cross-crate-codegen-attrs.rs
new file mode 100644
index 0000000..af6b133
--- /dev/null
+++ b/src/test/ui/hygiene/cross-crate-codegen-attrs.rs
@@ -0,0 +1,12 @@
+// Make sure that macro expanded codegen attributes work across crates.
+// We used to gensym the identifiers in attributes, which stopped dependent
+// crates from seeing them, resulting in linker errors in cases like this one.
+
+// run-pass
+// aux-build:codegen-attrs.rs
+
+extern crate codegen_attrs;
+
+fn main() {
+ assert_eq!(codegen_attrs::rust_function_name(), 2);
+}
diff --git a/src/test/ui/hygiene/no_implicit_prelude.stderr b/src/test/ui/hygiene/no_implicit_prelude.stderr
index a89176f..643f803 100644
--- a/src/test/ui/hygiene/no_implicit_prelude.stderr
+++ b/src/test/ui/hygiene/no_implicit_prelude.stderr
@@ -1,3 +1,11 @@
+error: cannot find macro `panic!` in this scope
+ --> $DIR/no_implicit_prelude.rs:16:9
+ |
+LL | assert_eq!(0, 0);
+ | ^^^^^^^^^^^^^^^^^
+ |
+ = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
+
error[E0433]: failed to resolve: use of undeclared type or module `Vec`
--> $DIR/no_implicit_prelude.rs:11:9
|
@@ -7,14 +15,6 @@
LL | Vec::new();
| ^^^ use of undeclared type or module `Vec`
-error: cannot find macro `panic!` in this scope
- --> $DIR/no_implicit_prelude.rs:16:9
- |
-LL | assert_eq!(0, 0);
- | ^^^^^^^^^^^^^^^^^
- |
- = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
-
error[E0599]: no method named `clone` found for type `()` in the current scope
--> $DIR/no_implicit_prelude.rs:12:12
|
diff --git a/src/test/ui/imports/local-modularized-tricky-fail-1.stderr b/src/test/ui/imports/local-modularized-tricky-fail-1.stderr
index 5afdd88..7d01382 100644
--- a/src/test/ui/imports/local-modularized-tricky-fail-1.stderr
+++ b/src/test/ui/imports/local-modularized-tricky-fail-1.stderr
@@ -21,25 +21,6 @@
| ^^^^^^^^^
= help: consider adding an explicit import of `exported` to disambiguate
-error[E0659]: `include` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
- --> $DIR/local-modularized-tricky-fail-1.rs:46:1
- |
-LL | include!();
- | ^^^^^^^ ambiguous name
- |
- = note: `include` could refer to a macro from prelude
-note: `include` could also refer to the macro defined here
- --> $DIR/local-modularized-tricky-fail-1.rs:17:5
- |
-LL | / macro_rules! include {
-LL | | () => ()
-LL | | }
- | |_____^
-...
-LL | define_include!();
- | ------------------ in this macro invocation
- = help: use `crate::include` to refer to this macro unambiguously
-
error[E0659]: `panic` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
--> $DIR/local-modularized-tricky-fail-1.rs:35:5
|
@@ -59,6 +40,25 @@
| ---------------- in this macro invocation
= help: use `crate::panic` to refer to this macro unambiguously
+error[E0659]: `include` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
+ --> $DIR/local-modularized-tricky-fail-1.rs:46:1
+ |
+LL | include!();
+ | ^^^^^^^ ambiguous name
+ |
+ = note: `include` could refer to a macro from prelude
+note: `include` could also refer to the macro defined here
+ --> $DIR/local-modularized-tricky-fail-1.rs:17:5
+ |
+LL | / macro_rules! include {
+LL | | () => ()
+LL | | }
+ | |_____^
+...
+LL | define_include!();
+ | ------------------ in this macro invocation
+ = help: use `crate::include` to refer to this macro unambiguously
+
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0659`.
diff --git a/src/test/ui/imports/shadow_builtin_macros.stderr b/src/test/ui/imports/shadow_builtin_macros.stderr
index c84226e..2f2ab20 100644
--- a/src/test/ui/imports/shadow_builtin_macros.stderr
+++ b/src/test/ui/imports/shadow_builtin_macros.stderr
@@ -14,20 +14,6 @@
= help: or use `self::panic` to refer to this macro unambiguously
error[E0659]: `panic` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
- --> $DIR/shadow_builtin_macros.rs:20:14
- |
-LL | fn f() { panic!(); }
- | ^^^^^ ambiguous name
- |
- = note: `panic` could refer to a macro from prelude
-note: `panic` could also refer to the macro imported here
- --> $DIR/shadow_builtin_macros.rs:19:26
- |
-LL | ::two_macros::m!(use foo::panic;);
- | ^^^^^^^^^^
- = help: use `self::panic` to refer to this macro unambiguously
-
-error[E0659]: `panic` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
--> $DIR/shadow_builtin_macros.rs:33:5
|
LL | panic!();
@@ -62,6 +48,20 @@
LL | #[macro_use(n)]
| ^
+error[E0659]: `panic` is ambiguous (macro-expanded name vs less macro-expanded name from outer scope during import/macro resolution)
+ --> $DIR/shadow_builtin_macros.rs:20:14
+ |
+LL | fn f() { panic!(); }
+ | ^^^^^ ambiguous name
+ |
+ = note: `panic` could refer to a macro from prelude
+note: `panic` could also refer to the macro imported here
+ --> $DIR/shadow_builtin_macros.rs:19:26
+ |
+LL | ::two_macros::m!(use foo::panic;);
+ | ^^^^^^^^^^
+ = help: use `self::panic` to refer to this macro unambiguously
+
error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0659`.
diff --git a/src/test/ui/include-macros/data.bin b/src/test/ui/include-macros/data.bin
new file mode 100644
index 0000000..ce4e0b8
--- /dev/null
+++ b/src/test/ui/include-macros/data.bin
@@ -0,0 +1,2 @@
+This file starts with BOM.
+Lines are separated by \r\n.
diff --git a/src/test/ui/include-macros/normalization.rs b/src/test/ui/include-macros/normalization.rs
new file mode 100644
index 0000000..889f08e
--- /dev/null
+++ b/src/test/ui/include-macros/normalization.rs
@@ -0,0 +1,12 @@
+// run-pass
+
+fn main() {
+ assert_eq!(
+ &include_bytes!("data.bin")[..],
+ &b"\xEF\xBB\xBFThis file starts with BOM.\r\nLines are separated by \\r\\n.\r\n"[..],
+ );
+ assert_eq!(
+ include_str!("data.bin"),
+ "\u{FEFF}This file starts with BOM.\r\nLines are separated by \\r\\n.\r\n",
+ );
+}
diff --git a/src/test/ui/issues/issue-49074.stderr b/src/test/ui/issues/issue-49074.stderr
index c557255..e0d3bb3 100644
--- a/src/test/ui/issues/issue-49074.stderr
+++ b/src/test/ui/issues/issue-49074.stderr
@@ -1,9 +1,3 @@
-error: cannot find attribute macro `marco_use` in this scope
- --> $DIR/issue-49074.rs:3:3
- |
-LL | #[marco_use] // typo
- | ^^^^^^^^^ help: a built-in attribute with a similar name exists: `macro_use`
-
error: cannot find macro `bar!` in this scope
--> $DIR/issue-49074.rs:12:4
|
@@ -12,5 +6,11 @@
|
= help: have you added the `#[macro_use]` on the module/import?
+error: cannot find attribute macro `marco_use` in this scope
+ --> $DIR/issue-49074.rs:3:3
+ |
+LL | #[marco_use] // typo
+ | ^^^^^^^^^ help: a built-in attribute with a similar name exists: `macro_use`
+
error: aborting due to 2 previous errors
diff --git a/src/test/ui/macros/trace-macro.stderr b/src/test/ui/macros/trace-macro.stderr
index 287f7b2..202a923 100644
--- a/src/test/ui/macros/trace-macro.stderr
+++ b/src/test/ui/macros/trace-macro.stderr
@@ -5,5 +5,5 @@
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: expanding `println! { "Hello, World!" }`
- = note: to `{ $crate :: io :: _print (format_args_nl ! ("Hello, World!")) ; }`
+ = note: to `{ $crate :: io :: _print ($crate :: format_args_nl ! ("Hello, World!")) ; }`
diff --git a/src/test/ui/proc-macro/macro-namespace-reserved-2.stderr b/src/test/ui/proc-macro/macro-namespace-reserved-2.stderr
index b2f1247..0c863e9 100644
--- a/src/test/ui/proc-macro/macro-namespace-reserved-2.stderr
+++ b/src/test/ui/proc-macro/macro-namespace-reserved-2.stderr
@@ -88,18 +88,6 @@
LL | #[derive(crate::my_macro)]
| ^^^^^^^^^^^^^^^ not a derive macro
-error: cannot find attribute macro `my_macro` in this scope
- --> $DIR/macro-namespace-reserved-2.rs:38:3
- |
-LL | #[my_macro]
- | ^^^^^^^^
-
-error: cannot find derive macro `my_macro` in this scope
- --> $DIR/macro-namespace-reserved-2.rs:48:10
- |
-LL | #[derive(my_macro)]
- | ^^^^^^^^
-
error: cannot find macro `my_macro_attr!` in this scope
--> $DIR/macro-namespace-reserved-2.rs:28:5
|
@@ -112,5 +100,17 @@
LL | MyTrait!();
| ^^^^^^^
+error: cannot find attribute macro `my_macro` in this scope
+ --> $DIR/macro-namespace-reserved-2.rs:38:3
+ |
+LL | #[my_macro]
+ | ^^^^^^^^
+
+error: cannot find derive macro `my_macro` in this scope
+ --> $DIR/macro-namespace-reserved-2.rs:48:10
+ |
+LL | #[derive(my_macro)]
+ | ^^^^^^^^
+
error: aborting due to 19 previous errors
diff --git a/src/test/ui/reserved/reserved-attr-on-macro.stderr b/src/test/ui/reserved/reserved-attr-on-macro.stderr
index d4b97d2..856162b 100644
--- a/src/test/ui/reserved/reserved-attr-on-macro.stderr
+++ b/src/test/ui/reserved/reserved-attr-on-macro.stderr
@@ -7,12 +7,6 @@
= note: for more information, see https://github.com/rust-lang/rust/issues/29642
= help: add `#![feature(rustc_attrs)]` to the crate attributes to enable
-error: cannot find attribute macro `rustc_attribute_should_be_reserved` in this scope
- --> $DIR/reserved-attr-on-macro.rs:1:3
- |
-LL | #[rustc_attribute_should_be_reserved]
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
error: cannot determine resolution for the macro `foo`
--> $DIR/reserved-attr-on-macro.rs:10:5
|
@@ -21,6 +15,12 @@
|
= note: import resolution is stuck, try simplifying macro imports
+error: cannot find attribute macro `rustc_attribute_should_be_reserved` in this scope
+ --> $DIR/reserved-attr-on-macro.rs:1:3
+ |
+LL | #[rustc_attribute_should_be_reserved]
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0658`.
diff --git a/src/test/ui/rfc1598-generic-associated-types/shadowing.rs b/src/test/ui/rfc1598-generic-associated-types/shadowing.rs
index 0349263..f5197fd 100644
--- a/src/test/ui/rfc1598-generic-associated-types/shadowing.rs
+++ b/src/test/ui/rfc1598-generic-associated-types/shadowing.rs
@@ -1,12 +1,9 @@
+#![allow(incomplete_features)]
#![feature(generic_associated_types)]
-//FIXME(#44265): The lifetime shadowing and type parameter shadowing
-// should cause an error. Now it compiles (erroneously) and this will be addressed
-// by a future PR. Then remove the following:
-// build-pass (FIXME(62277): could be check-pass?)
-
trait Shadow<'a> {
- type Bar<'a>; // Error: shadowed lifetime
+ //FIXME(#44265): The lifetime parameter shadowing should cause an error.
+ type Bar<'a>;
}
trait NoShadow<'a> {
@@ -14,11 +11,12 @@
}
impl<'a> NoShadow<'a> for &'a u32 {
- type Bar<'a> = i32; // Error: shadowed lifetime
+ //FIXME(#44265): The lifetime parameter shadowing should cause an error.
+ type Bar<'a> = i32;
}
trait ShadowT<T> {
- type Bar<T>; // Error: shadowed type parameter
+ type Bar<T>; //~ ERROR the name `T` is already used
}
trait NoShadowT<T> {
@@ -26,7 +24,7 @@
}
impl<T> NoShadowT<T> for Option<T> {
- type Bar<T> = i32; // Error: shadowed type parameter
+ type Bar<T> = i32; //~ ERROR the name `T` is already used
}
fn main() {}
diff --git a/src/test/ui/rfc1598-generic-associated-types/shadowing.stderr b/src/test/ui/rfc1598-generic-associated-types/shadowing.stderr
index 9526df2..a06c635 100644
--- a/src/test/ui/rfc1598-generic-associated-types/shadowing.stderr
+++ b/src/test/ui/rfc1598-generic-associated-types/shadowing.stderr
@@ -1,8 +1,19 @@
-warning: the feature `generic_associated_types` is incomplete and may cause the compiler to crash
- --> $DIR/shadowing.rs:1:12
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
+ --> $DIR/shadowing.rs:19:14
|
-LL | #![feature(generic_associated_types)]
- | ^^^^^^^^^^^^^^^^^^^^^^^^
- |
- = note: `#[warn(incomplete_features)]` on by default
+LL | trait ShadowT<T> {
+ | - first use of `T`
+LL | type Bar<T>;
+ | ^ already used
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
+ --> $DIR/shadowing.rs:27:14
+ |
+LL | impl<T> NoShadowT<T> for Option<T> {
+ | - first use of `T`
+LL | type Bar<T> = i32;
+ | ^ already used
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0403`.
diff --git a/src/test/ui/rust-unstable-column-gated.rs b/src/test/ui/rust-unstable-column-gated.rs
deleted file mode 100644
index 053806e..0000000
--- a/src/test/ui/rust-unstable-column-gated.rs
+++ /dev/null
@@ -1,4 +0,0 @@
-fn main() {
- println!("{}", __rust_unstable_column!());
- //~^ ERROR use of unstable library feature '__rust_unstable_column'
-}
diff --git a/src/test/ui/rust-unstable-column-gated.stderr b/src/test/ui/rust-unstable-column-gated.stderr
deleted file mode 100644
index 7db1b01..0000000
--- a/src/test/ui/rust-unstable-column-gated.stderr
+++ /dev/null
@@ -1,11 +0,0 @@
-error[E0658]: use of unstable library feature '__rust_unstable_column': internal implementation detail of the `panic` macro
- --> $DIR/rust-unstable-column-gated.rs:2:20
- |
-LL | println!("{}", __rust_unstable_column!());
- | ^^^^^^^^^^^^^^^^^^^^^^
- |
- = help: add `#![feature(__rust_unstable_column)]` to the crate attributes to enable
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0658`.
diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
index 94646c2..e33001b9 100644
--- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
+++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn a(self: Pin<&Foo>, f: &Foo) -> &Foo { f }
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:10:50
@@ -30,7 +30,7 @@
LL | async fn bar<'a>(self: Alias<&Self>, arg: &'a ()) -> &() { arg }
| ^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:19:62
diff --git a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
index 779b21e..3e58c97 100644
--- a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
+++ b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn ref_self(&self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:15:47
@@ -24,7 +24,7 @@
LL | async fn ref_Self(self: &Self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:21:53
@@ -44,7 +44,7 @@
LL | async fn box_ref_Self(self: Box<&Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:25:62
@@ -64,7 +64,7 @@
LL | async fn pin_ref_Self(self: Pin<&Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:29:62
@@ -84,7 +84,7 @@
LL | async fn box_box_ref_Self(self: Box<Box<&Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:33:71
@@ -104,7 +104,7 @@
LL | async fn box_pin_Self(self: Box<Pin<&Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#28r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#23r
error: lifetime may not live long enough
--> $DIR/lt-ref-self-async.rs:37:67
diff --git a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
index cfe91dd..b8a5380 100644
--- a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn ref_self(&mut self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:15:51
@@ -24,7 +24,7 @@
LL | async fn ref_Self(self: &mut Self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:21:57
@@ -44,7 +44,7 @@
LL | async fn box_ref_Self(self: Box<&mut Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:25:66
@@ -64,7 +64,7 @@
LL | async fn pin_ref_Self(self: Pin<&mut Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:29:66
@@ -84,7 +84,7 @@
LL | async fn box_box_ref_Self(self: Box<Box<&mut Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:33:75
@@ -104,7 +104,7 @@
LL | async fn box_pin_ref_Self(self: Box<Pin<&mut Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-self-async.rs:37:75
diff --git a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
index 98fa5e2..cee008d 100644
--- a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn ref_Struct(self: &mut Struct, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-struct-async.rs:15:61
@@ -24,7 +24,7 @@
LL | async fn box_ref_Struct(self: Box<&mut Struct>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-struct-async.rs:19:70
@@ -44,7 +44,7 @@
LL | async fn pin_ref_Struct(self: Pin<&mut Struct>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-struct-async.rs:23:70
@@ -64,7 +64,7 @@
LL | async fn box_box_ref_Struct(self: Box<Box<&mut Struct>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-struct-async.rs:27:79
@@ -84,7 +84,7 @@
LL | async fn box_pin_ref_Struct(self: Box<Pin<&mut Struct>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-mut-struct-async.rs:31:79
diff --git a/src/test/ui/self/elision/ref-self-async.nll.stderr b/src/test/ui/self/elision/ref-self-async.nll.stderr
index f991f6d..c3c1548 100644
--- a/src/test/ui/self/elision/ref-self-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-self-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn ref_self(&self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:24:47
@@ -24,7 +24,7 @@
LL | async fn ref_Self(self: &Self, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:30:53
@@ -44,7 +44,7 @@
LL | async fn box_ref_Self(self: Box<&Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:34:62
@@ -64,7 +64,7 @@
LL | async fn pin_ref_Self(self: Pin<&Self>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:38:62
@@ -84,7 +84,7 @@
LL | async fn box_box_ref_Self(self: Box<Box<&Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:42:71
@@ -104,7 +104,7 @@
LL | async fn box_pin_ref_Self(self: Box<Pin<&Self>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:46:71
@@ -124,7 +124,7 @@
LL | async fn wrap_ref_Self_Self(self: Wrap<&Self, Self>, f: &u8) -> &u8 {
| ^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-self-async.rs:50:73
diff --git a/src/test/ui/self/elision/ref-struct-async.nll.stderr b/src/test/ui/self/elision/ref-struct-async.nll.stderr
index 437d403..ff50f68 100644
--- a/src/test/ui/self/elision/ref-struct-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-struct-async.nll.stderr
@@ -4,7 +4,7 @@
LL | async fn ref_Struct(self: &Struct, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-struct-async.rs:15:57
@@ -24,7 +24,7 @@
LL | async fn box_ref_Struct(self: Box<&Struct>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-struct-async.rs:19:66
@@ -44,7 +44,7 @@
LL | async fn pin_ref_Struct(self: Pin<&Struct>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-struct-async.rs:23:66
@@ -64,7 +64,7 @@
LL | async fn box_box_ref_Struct(self: Box<Box<&Struct>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-struct-async.rs:27:75
@@ -84,7 +84,7 @@
LL | async fn box_pin_Struct(self: Box<Pin<&Struct>>, f: &u32) -> &u32 {
| ^^^^
|
- = note: hidden type `impl std::future::Future` captures lifetime '_#18r
+ = note: hidden type `impl std::future::Future` captures lifetime '_#15r
error: lifetime may not live long enough
--> $DIR/ref-struct-async.rs:31:71
diff --git a/src/test/ui/shadowed/shadowed-type-parameter.rs b/src/test/ui/shadowed/shadowed-type-parameter.rs
index ba9f3ab..e74620f 100644
--- a/src/test/ui/shadowed/shadowed-type-parameter.rs
+++ b/src/test/ui/shadowed/shadowed-type-parameter.rs
@@ -6,7 +6,7 @@
impl<T> Foo<T> {
fn shadow_in_method<T>(&self) {}
- //~^ ERROR type parameter `T` shadows another type parameter
+ //~^ ERROR the name `T` is already used
fn not_shadow_in_item<U>(&self) {
struct Bar<T, U>(T,U); // not a shadow, separate item
@@ -18,10 +18,10 @@
fn dummy(&self) -> T;
fn shadow_in_required<T>(&self);
- //~^ ERROR type parameter `T` shadows another type parameter
+ //~^ ERROR the name `T` is already used
fn shadow_in_provided<T>(&self) {}
- //~^ ERROR type parameter `T` shadows another type parameter
+ //~^ ERROR the name `T` is already used
fn not_shadow_in_required<U>(&self);
fn not_shadow_in_provided<U>(&self) {}
diff --git a/src/test/ui/shadowed/shadowed-type-parameter.stderr b/src/test/ui/shadowed/shadowed-type-parameter.stderr
index 6b4d1fa..0ea82f9 100644
--- a/src/test/ui/shadowed/shadowed-type-parameter.stderr
+++ b/src/test/ui/shadowed/shadowed-type-parameter.stderr
@@ -1,29 +1,29 @@
-error[E0194]: type parameter `T` shadows another type parameter of the same name
- --> $DIR/shadowed-type-parameter.rs:20:27
- |
-LL | trait Bar<T> {
- | - first `T` declared here
-...
-LL | fn shadow_in_required<T>(&self);
- | ^ shadows another type parameter
-
-error[E0194]: type parameter `T` shadows another type parameter of the same name
- --> $DIR/shadowed-type-parameter.rs:23:27
- |
-LL | trait Bar<T> {
- | - first `T` declared here
-...
-LL | fn shadow_in_provided<T>(&self) {}
- | ^ shadows another type parameter
-
-error[E0194]: type parameter `T` shadows another type parameter of the same name
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
--> $DIR/shadowed-type-parameter.rs:8:25
|
LL | impl<T> Foo<T> {
- | - first `T` declared here
+ | - first use of `T`
LL | fn shadow_in_method<T>(&self) {}
- | ^ shadows another type parameter
+ | ^ already used
+
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
+ --> $DIR/shadowed-type-parameter.rs:20:27
+ |
+LL | trait Bar<T> {
+ | - first use of `T`
+...
+LL | fn shadow_in_required<T>(&self);
+ | ^ already used
+
+error[E0403]: the name `T` is already used for a generic parameter in this item's generic parameters
+ --> $DIR/shadowed-type-parameter.rs:23:27
+ |
+LL | trait Bar<T> {
+ | - first use of `T`
+...
+LL | fn shadow_in_provided<T>(&self) {}
+ | ^ already used
error: aborting due to 3 previous errors
-For more information about this error, try `rustc --explain E0194`.
+For more information about this error, try `rustc --explain E0403`.
diff --git a/src/test/ui/suggestions/dont-suggest-try_into-in-macros.rs b/src/test/ui/suggestions/dont-suggest-try_into-in-macros.rs
new file mode 100644
index 0000000..d625199
--- /dev/null
+++ b/src/test/ui/suggestions/dont-suggest-try_into-in-macros.rs
@@ -0,0 +1,3 @@
+fn main() {
+ assert_eq!(10u64, 10usize); //~ ERROR mismatched types
+}
diff --git a/src/test/ui/suggestions/dont-suggest-try_into-in-macros.stderr b/src/test/ui/suggestions/dont-suggest-try_into-in-macros.stderr
new file mode 100644
index 0000000..f043069
--- /dev/null
+++ b/src/test/ui/suggestions/dont-suggest-try_into-in-macros.stderr
@@ -0,0 +1,11 @@
+error[E0308]: mismatched types
+ --> $DIR/dont-suggest-try_into-in-macros.rs:2:5
+ |
+LL | assert_eq!(10u64, 10usize);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected u64, found usize
+ |
+ = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0308`.
diff --git a/src/test/ui/symbol-names/impl1.rs b/src/test/ui/symbol-names/impl1.rs
index 52bb118..137b72d 100644
--- a/src/test/ui/symbol-names/impl1.rs
+++ b/src/test/ui/symbol-names/impl1.rs
@@ -64,9 +64,9 @@
//[legacy]~^ ERROR symbol-name(_ZN198_$LT$$u5b$$RF$dyn$u20$impl1..Foo$u2b$Assoc$u20$$u3d$$u20$extern$u20$$u22$C$u22$$u20$fn$LP$$RF$u8$RP$$u2b$impl1..AutoTrait$u3b$$u20$_$u5d$$u20$as$u20$impl1..main..$u7b$$u7b$closure$u7d$$u7d$..Bar$GT$6method
//[legacy]~| ERROR demangling(<[&dyn impl1::Foo+Assoc = extern "C" fn(&u8)+impl1::AutoTrait; _] as impl1::main::{{closure}}::Bar>::method
//[legacy]~| ERROR demangling-alt(<[&dyn impl1::Foo+Assoc = extern "C" fn(&u8)+impl1::AutoTrait; _] as impl1::main::{{closure}}::Bar>::method)
- //[v0]~^^^^ ERROR symbol-name(_RNvXNCNvCs4fqI2P2rA04_5impl14mains_0ARDNtB6_3Foop5AssocFG0_KCRL0_hEuNtB6_9AutoTraitEL_j3_NtB2_3Bar6method)
- //[v0]~| ERROR demangling(<[&dyn impl1[317d481089b8c8fe]::Foo<Assoc = for<'a, 'b> extern "C" fn(&'b u8)> + impl1[317d481089b8c8fe]::AutoTrait; 3: usize] as impl1[317d481089b8c8fe]::main::{closure#1}::Bar>::method)
- //[v0]~| ERROR demangling-alt(<[&dyn impl1::Foo<Assoc = for<'a, 'b> extern "C" fn(&'b u8)> + impl1::AutoTrait; 3] as impl1::main::{closure#1}::Bar>::method)
+ //[v0]~^^^^ ERROR symbol-name(_RNvXNCNvCs4fqI2P2rA04_5impl14mains_0ARDNtB6_3Foop5AssocFG_KCRL0_hEuNtB6_9AutoTraitEL_j3_NtB2_3Bar6method)
+ //[v0]~| ERROR demangling(<[&dyn impl1[317d481089b8c8fe]::Foo<Assoc = for<'a> extern "C" fn(&'a u8)> + impl1[317d481089b8c8fe]::AutoTrait; 3: usize] as impl1[317d481089b8c8fe]::main::{closure#1}::Bar>::method)
+ //[v0]~| ERROR demangling-alt(<[&dyn impl1::Foo<Assoc = for<'a> extern "C" fn(&'a u8)> + impl1::AutoTrait; 3] as impl1::main::{closure#1}::Bar>::method)
#[rustc_def_path]
//[legacy]~^ ERROR def-path(<[&dyn Foo<Assoc = for<'r> extern "C" fn(&'r u8)> + AutoTrait; _] as main::{{closure}}#1::Bar>::method)
//[v0]~^^ ERROR def-path(<[&dyn Foo<Assoc = for<'r> extern "C" fn(&'r u8)> + AutoTrait; _] as main::{{closure}}#1::Bar>::method)
diff --git a/src/test/ui/symbol-names/impl1.v0.stderr b/src/test/ui/symbol-names/impl1.v0.stderr
index 1c4b256..e024799 100644
--- a/src/test/ui/symbol-names/impl1.v0.stderr
+++ b/src/test/ui/symbol-names/impl1.v0.stderr
@@ -46,19 +46,19 @@
LL | #[rustc_def_path]
| ^^^^^^^^^^^^^^^^^
-error: symbol-name(_RNvXNCNvCs4fqI2P2rA04_5impl14mains_0ARDNtB6_3Foop5AssocFG0_KCRL0_hEuNtB6_9AutoTraitEL_j3_NtB2_3Bar6method)
+error: symbol-name(_RNvXNCNvCs4fqI2P2rA04_5impl14mains_0ARDNtB6_3Foop5AssocFG_KCRL0_hEuNtB6_9AutoTraitEL_j3_NtB2_3Bar6method)
--> $DIR/impl1.rs:63:13
|
LL | #[rustc_symbol_name]
| ^^^^^^^^^^^^^^^^^^^^
-error: demangling(<[&dyn impl1[317d481089b8c8fe]::Foo<Assoc = for<'a, 'b> extern "C" fn(&'b u8)> + impl1[317d481089b8c8fe]::AutoTrait; 3: usize] as impl1[317d481089b8c8fe]::main::{closure#1}::Bar>::method)
+error: demangling(<[&dyn impl1[317d481089b8c8fe]::Foo<Assoc = for<'a> extern "C" fn(&'a u8)> + impl1[317d481089b8c8fe]::AutoTrait; 3: usize] as impl1[317d481089b8c8fe]::main::{closure#1}::Bar>::method)
--> $DIR/impl1.rs:63:13
|
LL | #[rustc_symbol_name]
| ^^^^^^^^^^^^^^^^^^^^
-error: demangling-alt(<[&dyn impl1::Foo<Assoc = for<'a, 'b> extern "C" fn(&'b u8)> + impl1::AutoTrait; 3] as impl1::main::{closure#1}::Bar>::method)
+error: demangling-alt(<[&dyn impl1::Foo<Assoc = for<'a> extern "C" fn(&'a u8)> + impl1::AutoTrait; 3] as impl1::main::{closure#1}::Bar>::method)
--> $DIR/impl1.rs:63:13
|
LL | #[rustc_symbol_name]
diff --git a/src/test/ui/symbol-names/issue-60925.legacy.stderr b/src/test/ui/symbol-names/issue-60925.legacy.stderr
index 7fcd2ed..de8efdd 100644
--- a/src/test/ui/symbol-names/issue-60925.legacy.stderr
+++ b/src/test/ui/symbol-names/issue-60925.legacy.stderr
@@ -4,13 +4,13 @@
LL | #[rustc_symbol_name]
| ^^^^^^^^^^^^^^^^^^^^
-error: demangling(issue_60925::foo::Foo<issue_60925::llv$u6d$..Foo$GT$::foo::h059a991a004536ad)
+error: demangling(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo::h059a991a004536ad)
--> $DIR/issue-60925.rs:21:9
|
LL | #[rustc_symbol_name]
| ^^^^^^^^^^^^^^^^^^^^
-error: demangling-alt(issue_60925::foo::Foo<issue_60925::llv$u6d$..Foo$GT$::foo)
+error: demangling-alt(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo)
--> $DIR/issue-60925.rs:21:9
|
LL | #[rustc_symbol_name]
diff --git a/src/test/ui/symbol-names/issue-60925.rs b/src/test/ui/symbol-names/issue-60925.rs
index 89de15c..0243835 100644
--- a/src/test/ui/symbol-names/issue-60925.rs
+++ b/src/test/ui/symbol-names/issue-60925.rs
@@ -20,8 +20,8 @@
impl Foo<::llvm::Foo> {
#[rustc_symbol_name]
//[legacy]~^ ERROR symbol-name(_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo
- //[legacy]~| ERROR demangling(issue_60925::foo::Foo<issue_60925::llv$u6d$..Foo$GT$::foo
- //[legacy]~| ERROR demangling-alt(issue_60925::foo::Foo<issue_60925::llv$u6d$..Foo$GT$::foo)
+ //[legacy]~| ERROR demangling(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo
+ //[legacy]~| ERROR demangling-alt(issue_60925::foo::Foo<issue_60925::llvm::Foo>::foo)
//[v0]~^^^^ ERROR symbol-name(_RNvMNtCs4fqI2P2rA04_11issue_609253fooINtB2_3FooNtNtB4_4llvm3FooE3foo)
//[v0]~| ERROR demangling(<issue_60925[317d481089b8c8fe]::foo::Foo<issue_60925[317d481089b8c8fe]::llvm::Foo>>::foo)
//[v0]~| ERROR demangling-alt(<issue_60925::foo::Foo<issue_60925::llvm::Foo>>::foo)
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index 05cfdf1..3da6be7 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -1659,10 +1659,10 @@
_ if self.config.target.contains("vxworks") => {
let aux_dir = self.aux_output_dir_name();
let ProcArgs { prog, args } = self.make_run_args();
- let mut vx_run = Command::new("vx-run");
- vx_run.args(&[&prog]).args(args).envs(env.clone());
+ let mut wr_run = Command::new("wr-run");
+ wr_run.args(&[&prog]).args(args).envs(env.clone());
self.compose_and_run(
- vx_run,
+ wr_run,
self.config.run_lib_path.to_str().unwrap(),
Some(aux_dir.to_str().unwrap()),
None,
diff --git a/src/tools/miri b/src/tools/miri
index c1cb249..4f6f264 160000
--- a/src/tools/miri
+++ b/src/tools/miri
@@ -1 +1 @@
-Subproject commit c1cb24969e84dfaded2769ab5575effc8d4f5c30
+Subproject commit 4f6f264c305ea30f1de90ad0c2f341e84d972b2e
diff --git a/src/tools/rls b/src/tools/rls
index 7b0a20b..496c892 160000
--- a/src/tools/rls
+++ b/src/tools/rls
@@ -1 +1 @@
-Subproject commit 7b0a20bf13b7061b1eb31a058117ac5517ff8cc9
+Subproject commit 496c89275221303a4b0c2779cb8203fb3ce2a136