Rollup merge of #56808 - jrvidal:broken-links, r=kennytm
Fixes broken links
Just a few broken links.
Not sure what to do about this one: https://github.com/rust-lang/rust/blame/master/src/doc/unstable-book/src/language-features/plugin.md#L135 (regex macros were removed a while ago in https://github.com/rust-lang/regex/commit/037595438947eeb4c63a0185065b0143a7f2ac2c).
diff --git a/Cargo.lock b/Cargo.lock
index d22a910..be4a1c2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -81,7 +81,7 @@
[[package]]
name = "backtrace"
-version = "0.3.9"
+version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -728,7 +728,7 @@
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
+ "backtrace 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -736,7 +736,7 @@
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
+ "backtrace 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -751,7 +751,7 @@
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
+ "backtrace 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)",
"failure_derive 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -2060,7 +2060,7 @@
version = "0.0.0"
dependencies = [
"arena 0.0.0",
- "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)",
+ "backtrace 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
"chalk-engine 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -3380,7 +3380,7 @@
"checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef"
"checksum assert_cli 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "98589b0e465a6c510d95fceebd365bb79bedece7f6e18a480897f2015f85ec51"
"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652"
-"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a"
+"checksum backtrace 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)" = "18b65ea1161bfb2dd6da6fade5edd4dbd08fba85012123dd333d2fd1b90b2782"
"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0"
"checksum bit-set 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6f1efcc46c18245a69c38fcc5cc650f16d3a59d034f3106e9ed63748f695730a"
"checksum bit-vec 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4440d5cb623bb7390ae27fec0bb6c61111969860f8e3ae198bfa0663645e67cf"
diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs
index 32f3e57..c1d5686 100644
--- a/src/bootstrap/builder.rs
+++ b/src/bootstrap/builder.rs
@@ -416,6 +416,7 @@
test::Rustfmt,
test::Miri,
test::Clippy,
+ test::CompiletestTest,
test::RustdocJS,
test::RustdocTheme,
// Run bootstrap close to the end as it's unlikely to fail
diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs
index c84abe42..689d053 100644
--- a/src/bootstrap/compile.rs
+++ b/src/bootstrap/compile.rs
@@ -155,7 +155,9 @@
cargo
.args(&["-p", "alloc"])
.arg("--manifest-path")
- .arg(builder.src.join("src/liballoc/Cargo.toml"));
+ .arg(builder.src.join("src/liballoc/Cargo.toml"))
+ .arg("--features")
+ .arg("compiler-builtins-mem");
} else {
let features = builder.std_features();
diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs
index dc061fe..87d5737 100644
--- a/src/bootstrap/test.rs
+++ b/src/bootstrap/test.rs
@@ -430,6 +430,45 @@
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub struct CompiletestTest {
+ stage: u32,
+ host: Interned<String>,
+}
+
+impl Step for CompiletestTest {
+ type Output = ();
+
+ fn should_run(run: ShouldRun) -> ShouldRun {
+ run.path("src/tools/compiletest")
+ }
+
+ fn make_run(run: RunConfig) {
+ run.builder.ensure(CompiletestTest {
+ stage: run.builder.top_stage,
+ host: run.target,
+ });
+ }
+
+ /// Runs `cargo test` for compiletest.
+ fn run(self, builder: &Builder) {
+ let stage = self.stage;
+ let host = self.host;
+ let compiler = builder.compiler(stage, host);
+
+ let mut cargo = tool::prepare_tool_cargo(builder,
+ compiler,
+ Mode::ToolBootstrap,
+ host,
+ "test",
+ "src/tools/compiletest",
+ SourceType::InTree,
+ &[]);
+
+ try_run(builder, &mut cargo);
+ }
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Clippy {
stage: u32,
host: Interned<String>,
diff --git a/src/ci/docker/dist-various-1/Dockerfile b/src/ci/docker/dist-various-1/Dockerfile
index c7e6af2..4f8a3c0 100644
--- a/src/ci/docker/dist-various-1/Dockerfile
+++ b/src/ci/docker/dist-various-1/Dockerfile
@@ -52,8 +52,8 @@
CXX=arm-linux-gnueabi-g++ CXXFLAGS="-march=armv6 -marm" \
bash musl.sh arm && \
env \
- CC=arm-linux-gnueabihf-gcc CFLAGS="-march=armv6 -marm" \
- CXX=arm-linux-gnueabihf-g++ CXXFLAGS="-march=armv6 -marm" \
+ CC=arm-linux-gnueabihf-gcc CFLAGS="-march=armv6 -marm -mfpu=vfp" \
+ CXX=arm-linux-gnueabihf-g++ CXXFLAGS="-march=armv6 -marm -mfpu=vfp" \
bash musl.sh armhf && \
env \
CC=arm-linux-gnueabihf-gcc CFLAGS="-march=armv7-a" \
diff --git a/src/etc/gdb_rust_pretty_printing.py b/src/etc/gdb_rust_pretty_printing.py
index a376c85..f02c7d8 100755
--- a/src/etc/gdb_rust_pretty_printing.py
+++ b/src/etc/gdb_rust_pretty_printing.py
@@ -9,6 +9,7 @@
# except according to those terms.
import gdb
+import re
import sys
import debugger_pretty_printers_common as rustpp
@@ -20,6 +21,16 @@
rust_enabled = 'set language rust' in gdb.execute('complete set language ru', to_string = True)
+# The btree pretty-printers fail in a confusing way unless
+# https://sourceware.org/bugzilla/show_bug.cgi?id=21763 is fixed.
+# This fix went in 8.1, so check for that.
+# See https://github.com/rust-lang/rust/issues/56730
+gdb_81 = False
+_match = re.match('([0-9]+)\\.([0-9]+)', gdb.VERSION)
+if _match:
+ if int(_match.group(1)) > 8 or (int(_match.group(1)) == 8 and int(_match.group(2)) >= 1):
+ gdb_81 = True
+
#===============================================================================
# GDB Pretty Printing Module for Rust
#===============================================================================
@@ -110,10 +121,10 @@
if type_kind == rustpp.TYPE_KIND_STD_VECDEQUE:
return RustStdVecDequePrinter(val)
- if type_kind == rustpp.TYPE_KIND_STD_BTREESET:
+ if type_kind == rustpp.TYPE_KIND_STD_BTREESET and gdb_81:
return RustStdBTreeSetPrinter(val)
- if type_kind == rustpp.TYPE_KIND_STD_BTREEMAP:
+ if type_kind == rustpp.TYPE_KIND_STD_BTREEMAP and gdb_81:
return RustStdBTreeMapPrinter(val)
if type_kind == rustpp.TYPE_KIND_STD_STRING:
diff --git a/src/liballoc/Cargo.toml b/src/liballoc/Cargo.toml
index b7faee1..b2eb356 100644
--- a/src/liballoc/Cargo.toml
+++ b/src/liballoc/Cargo.toml
@@ -28,3 +28,6 @@
name = "vec_deque_append_bench"
path = "../liballoc/benches/vec_deque_append.rs"
harness = false
+
+[features]
+compiler-builtins-mem = ['compiler_builtins/mem']
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs
index f61e582..79ca600 100644
--- a/src/libcore/ptr.rs
+++ b/src/libcore/ptr.rs
@@ -2544,7 +2544,7 @@
/// assert_eq!(actual, expected);
/// ```
#[unstable(feature = "ptr_hash", reason = "newly added", issue = "56286")]
-pub fn hash<T, S: hash::Hasher>(hashee: *const T, into: &mut S) {
+pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
use hash::Hash;
hashee.hash(into);
}
diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs
index 7d997a0..d213a5c 100644
--- a/src/librustc/infer/error_reporting/mod.rs
+++ b/src/librustc/infer/error_reporting/mod.rs
@@ -1095,7 +1095,8 @@
let sp = hir.span(id);
// `sp` only covers `T`, change it so that it covers
// `T:` when appropriate
- let sp = if has_bounds {
+ let is_impl_trait = bound_kind.to_string().starts_with("impl ");
+ let sp = if has_bounds && !is_impl_trait {
sp.to(self.tcx
.sess
.source_map()
@@ -1103,7 +1104,7 @@
} else {
sp
};
- (sp, has_bounds)
+ (sp, has_bounds, is_impl_trait)
})
} else {
None
@@ -1136,25 +1137,33 @@
fn binding_suggestion<'tcx, S: fmt::Display>(
err: &mut DiagnosticBuilder<'tcx>,
- type_param_span: Option<(Span, bool)>,
+ type_param_span: Option<(Span, bool, bool)>,
bound_kind: GenericKind<'tcx>,
sub: S,
) {
- let consider = &format!(
- "consider adding an explicit lifetime bound `{}: {}`...",
- bound_kind, sub
+ let consider = format!(
+ "consider adding an explicit lifetime bound {}",
+ if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
+ format!(" `{}` to `{}`...", sub, bound_kind)
+ } else {
+ format!("`{}: {}`...", bound_kind, sub)
+ },
);
- if let Some((sp, has_lifetimes)) = type_param_span {
- let tail = if has_lifetimes { " + " } else { "" };
- let suggestion = format!("{}: {}{}", bound_kind, sub, tail);
+ if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
+ let suggestion = if is_impl_trait {
+ format!("{} + {}", bound_kind, sub)
+ } else {
+ let tail = if has_lifetimes { " + " } else { "" };
+ format!("{}: {}{}", bound_kind, sub, tail)
+ };
err.span_suggestion_short_with_applicability(
sp,
- consider,
+ &consider,
suggestion,
Applicability::MaybeIncorrect, // Issue #41966
);
} else {
- err.help(consider);
+ err.help(&consider);
}
}
diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs
index 289f693..8b16aaf 100644
--- a/src/librustc/mir/interpret/error.rs
+++ b/src/librustc/mir/interpret/error.rs
@@ -183,50 +183,14 @@
impl<'tcx> EvalError<'tcx> {
pub fn print_backtrace(&mut self) {
if let Some(ref mut backtrace) = self.backtrace {
- eprintln!("{}", print_backtrace(&mut *backtrace));
+ print_backtrace(&mut *backtrace);
}
}
}
-fn print_backtrace(backtrace: &mut Backtrace) -> String {
- use std::fmt::Write;
-
+fn print_backtrace(backtrace: &mut Backtrace) {
backtrace.resolve();
-
- let mut trace_text = "\n\nAn error occurred in miri:\n".to_string();
- write!(trace_text, "backtrace frames: {}\n", backtrace.frames().len()).unwrap();
- 'frames: for (i, frame) in backtrace.frames().iter().enumerate() {
- if frame.symbols().is_empty() {
- write!(trace_text, " {}: no symbols\n", i).unwrap();
- }
- let mut first = true;
- for symbol in frame.symbols() {
- if first {
- write!(trace_text, " {}: ", i).unwrap();
- first = false;
- } else {
- let len = i.to_string().len();
- write!(trace_text, " {} ", " ".repeat(len)).unwrap();
- }
- if let Some(name) = symbol.name() {
- write!(trace_text, "{}\n", name).unwrap();
- } else {
- write!(trace_text, "<unknown>\n").unwrap();
- }
- write!(trace_text, " at ").unwrap();
- if let Some(file_path) = symbol.filename() {
- write!(trace_text, "{}", file_path.display()).unwrap();
- } else {
- write!(trace_text, "<unknown_file>").unwrap();
- }
- if let Some(line) = symbol.lineno() {
- write!(trace_text, ":{}\n", line).unwrap();
- } else {
- write!(trace_text, "\n").unwrap();
- }
- }
- }
- trace_text
+ eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace);
}
impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> {
@@ -238,7 +202,7 @@
if val == "immediate" {
// Print it now
- eprintln!("{}", print_backtrace(&mut backtrace));
+ print_backtrace(&mut backtrace);
None
} else {
Some(Box::new(backtrace))
diff --git a/src/librustc/traits/specialize/specialization_graph.rs b/src/librustc/traits/specialize/specialization_graph.rs
index 22221e0..b0ca2f6 100644
--- a/src/librustc/traits/specialize/specialization_graph.rs
+++ b/src/librustc/traits/specialize/specialization_graph.rs
@@ -132,10 +132,12 @@
simplified_self,
);
- for possible_sibling in match simplified_self {
- Some(sty) => self.filtered(sty),
- None => self.iter(),
- } {
+ let possible_siblings = match simplified_self {
+ Some(sty) => PotentialSiblings::Filtered(self.filtered(sty)),
+ None => PotentialSiblings::Unfiltered(self.iter()),
+ };
+
+ for possible_sibling in possible_siblings {
debug!(
"insert: impl_def_id={:?}, simplified_self={:?}, possible_sibling={:?}",
impl_def_id,
@@ -222,14 +224,37 @@
Ok(Inserted::BecameNewSibling(last_lint))
}
- fn iter(&mut self) -> Box<dyn Iterator<Item = DefId> + '_> {
+ fn iter(&mut self) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = self.nonblanket_impls.iter_mut().flat_map(|(_, v)| v.iter());
- Box::new(self.blanket_impls.iter().chain(nonblanket).cloned())
+ self.blanket_impls.iter().chain(nonblanket).cloned()
}
- fn filtered(&mut self, sty: SimplifiedType) -> Box<dyn Iterator<Item = DefId> + '_> {
+ fn filtered(&mut self, sty: SimplifiedType) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = self.nonblanket_impls.entry(sty).or_default().iter();
- Box::new(self.blanket_impls.iter().chain(nonblanket).cloned())
+ self.blanket_impls.iter().chain(nonblanket).cloned()
+ }
+}
+
+// A custom iterator used by Children::insert
+enum PotentialSiblings<I, J>
+ where I: Iterator<Item = DefId>,
+ J: Iterator<Item = DefId>
+{
+ Unfiltered(I),
+ Filtered(J)
+}
+
+impl<I, J> Iterator for PotentialSiblings<I, J>
+ where I: Iterator<Item = DefId>,
+ J: Iterator<Item = DefId>
+{
+ type Item = DefId;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ match *self {
+ PotentialSiblings::Unfiltered(ref mut iter) => iter.next(),
+ PotentialSiblings::Filtered(ref mut iter) => iter.next()
+ }
}
}
diff --git a/src/librustc/util/profiling.rs b/src/librustc/util/profiling.rs
index 1e648c4..c2bfa62 100644
--- a/src/librustc/util/profiling.rs
+++ b/src/librustc/util/profiling.rs
@@ -62,11 +62,15 @@
}
fn print(&self, lock: &mut StderrLock<'_>) {
- writeln!(lock, "| Phase | Time (ms) | Queries | Hits (%) |")
+ writeln!(lock, "| Phase | Time (ms) \
+ | Time (%) | Queries | Hits (%)")
.unwrap();
- writeln!(lock, "| ---------------- | -------------- | -------------- | -------- |")
+ writeln!(lock, "| ---------------- | -------------- \
+ | -------- | -------------- | --------")
.unwrap();
+ let total_time = ($(self.times.$name + )* 0) as f32;
+
$(
let (hits, total) = self.query_counts.$name;
let (hits, total) = if total > 0 {
@@ -78,11 +82,12 @@
writeln!(
lock,
- "| {0: <16} | {1: <14} | {2: <14} | {3: <8} |",
+ "| {0: <16} | {1: <14} | {2: <8.2} | {3: <14} | {4: <8}",
stringify!($name),
self.times.$name / 1_000_000,
+ ((self.times.$name as f32) / total_time) * 100.0,
total,
- hits
+ hits,
).unwrap();
)*
}
diff --git a/src/librustc_codegen_llvm/attributes.rs b/src/librustc_codegen_llvm/attributes.rs
index 30edc47..48e0a3a 100644
--- a/src/librustc_codegen_llvm/attributes.rs
+++ b/src/librustc_codegen_llvm/attributes.rs
@@ -18,6 +18,7 @@
use rustc::ty::{self, TyCtxt, PolyFnSig};
use rustc::ty::layout::HasTyCtxt;
use rustc::ty::query::Providers;
+use rustc_data_structures::small_c_str::SmallCStr;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::fx::FxHashMap;
use rustc_target::spec::PanicStrategy;
@@ -130,8 +131,7 @@
}
pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
- let cpu = llvm_util::target_cpu(cx.tcx.sess);
- let target_cpu = CString::new(cpu).unwrap();
+ let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
llvm::AddFunctionAttrStringValue(
llfn,
llvm::AttributePlace::Function,
@@ -231,11 +231,7 @@
// Always annotate functions with the target-cpu they are compiled for.
// Without this, ThinLTO won't inline Rust functions into Clang generated
// functions (because Clang annotates functions this way too).
- // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
- // it introduce a little overhead and isn't really necessary otherwise.
- if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
- apply_target_cpu_attr(cx, llfn);
- }
+ apply_target_cpu_attr(cx, llfn);
let features = llvm_target_features(cx.tcx.sess)
.map(|s| s.to_string())
diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs
index 2b82ebe..8b26ada 100644
--- a/src/librustc_codegen_llvm/intrinsic.rs
+++ b/src/librustc_codegen_llvm/intrinsic.rs
@@ -1171,6 +1171,27 @@
);
let arg_tys = sig.inputs();
+ if name == "simd_select_bitmask" {
+ let in_ty = arg_tys[0];
+ let m_len = match in_ty.sty {
+ // Note that this `.unwrap()` crashes for isize/usize, that's sort
+ // of intentional as there's not currently a use case for that.
+ ty::Int(i) => i.bit_width().unwrap(),
+ ty::Uint(i) => i.bit_width().unwrap(),
+ _ => return_error!("`{}` is not an integral type", in_ty),
+ };
+ require_simd!(arg_tys[1], "argument");
+ let v_len = arg_tys[1].simd_size(tcx);
+ require!(m_len == v_len,
+ "mismatched lengths: mask length `{}` != other vector length `{}`",
+ m_len, v_len
+ );
+ let i1 = bx.type_i1();
+ let i1xn = bx.type_vector(i1, m_len as u64);
+ let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
+ return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
+ }
+
// every intrinsic takes a SIMD vector as its first argument
require_simd!(arg_tys[0], "input");
let in_ty = arg_tys[0];
diff --git a/src/librustc_codegen_llvm/llvm_util.rs b/src/librustc_codegen_llvm/llvm_util.rs
index fdb6373..12109ae 100644
--- a/src/librustc_codegen_llvm/llvm_util.rs
+++ b/src/librustc_codegen_llvm/llvm_util.rs
@@ -124,6 +124,7 @@
];
const X86_WHITELIST: &[(&str, Option<&str>)] = &[
+ ("adx", Some("adx_target_feature")),
("aes", None),
("avx", None),
("avx2", None),
diff --git a/src/librustc_codegen_ssa/Cargo.toml b/src/librustc_codegen_ssa/Cargo.toml
index 7b1c7cf..5099449 100644
--- a/src/librustc_codegen_ssa/Cargo.toml
+++ b/src/librustc_codegen_ssa/Cargo.toml
@@ -16,7 +16,7 @@
rustc-demangle = "0.1.4"
memmap = "0.6"
log = "0.4.5"
-libc = "0.2.43"
+libc = "0.2.44"
jobserver = "0.1.11"
serialize = { path = "../libserialize" }
diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs
index b1e44ea..66364ff 100644
--- a/src/librustc_lint/lib.rs
+++ b/src/librustc_lint/lib.rs
@@ -376,7 +376,7 @@
store.register_removed("resolve_trait_on_defaulted_unit",
"converted into hard error, see https://github.com/rust-lang/rust/issues/48950");
store.register_removed("private_no_mangle_fns",
- "no longer an warning, #[no_mangle] functions always exported");
+ "no longer a warning, #[no_mangle] functions always exported");
store.register_removed("private_no_mangle_statics",
- "no longer an warning, #[no_mangle] statics always exported");
+ "no longer a warning, #[no_mangle] statics always exported");
}
diff --git a/src/librustc_mir/build/matches/simplify.rs b/src/librustc_mir/build/matches/simplify.rs
index cfea357..328b330 100644
--- a/src/librustc_mir/build/matches/simplify.rs
+++ b/src/librustc_mir/build/matches/simplify.rs
@@ -26,6 +26,10 @@
use build::matches::{Ascription, Binding, MatchPair, Candidate};
use hair::*;
use rustc::mir::*;
+use rustc::ty;
+use rustc::ty::layout::{Integer, IntegerExt, Size};
+use syntax::attr::{SignedInt, UnsignedInt};
+use rustc::hir::RangeEnd;
use std::mem;
@@ -62,6 +66,7 @@
match_pair: MatchPair<'pat, 'tcx>,
candidate: &mut Candidate<'pat, 'tcx>)
-> Result<(), MatchPair<'pat, 'tcx>> {
+ let tcx = self.hir.tcx();
match *match_pair.pattern.kind {
PatternKind::AscribeUserType { ref subpattern, ref user_ty, user_ty_span } => {
candidate.ascriptions.push(Ascription {
@@ -104,7 +109,34 @@
Err(match_pair)
}
- PatternKind::Range { .. } => {
+ PatternKind::Range { lo, hi, ty, end } => {
+ let range = match ty.sty {
+ ty::Char => {
+ Some(('\u{0000}' as u128, '\u{10FFFF}' as u128, Size::from_bits(32)))
+ }
+ ty::Int(ity) => {
+ // FIXME(49937): refactor these bit manipulations into interpret.
+ let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
+ let min = 1u128 << (size.bits() - 1);
+ let max = (1u128 << (size.bits() - 1)) - 1;
+ Some((min, max, size))
+ }
+ ty::Uint(uty) => {
+ // FIXME(49937): refactor these bit manipulations into interpret.
+ let size = Integer::from_attr(&tcx, UnsignedInt(uty)).size();
+ let max = !0u128 >> (128 - size.bits());
+ Some((0, max, size))
+ }
+ _ => None,
+ };
+ if let Some((min, max, sz)) = range {
+ if let (Some(lo), Some(hi)) = (lo.val.try_to_bits(sz), hi.val.try_to_bits(sz)) {
+ if lo <= min && (hi > max || hi == max && end == RangeEnd::Included) {
+ // Irrefutable pattern match.
+ return Ok(());
+ }
+ }
+ }
Err(match_pair)
}
diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs
index 4c77350..5cfcc16 100644
--- a/src/librustc_mir/hair/pattern/_match.rs
+++ b/src/librustc_mir/hair/pattern/_match.rs
@@ -178,11 +178,11 @@
use rustc::hir::def_id::DefId;
use rustc::hir::RangeEnd;
-use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
-use rustc::ty::layout::{Integer, IntegerExt, VariantIdx};
+use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Const};
+use rustc::ty::layout::{Integer, IntegerExt, VariantIdx, Size};
use rustc::mir::Field;
-use rustc::mir::interpret::ConstValue;
+use rustc::mir::interpret::{ConstValue, Pointer, Scalar};
use rustc::util::common::ErrorReported;
use syntax::attr::{SignedInt, UnsignedInt};
@@ -200,14 +200,60 @@
pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
-> &'a Pattern<'tcx>
{
- cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
+ cx.pattern_arena.alloc(LiteralExpander { tcx: cx.tcx }.fold_pattern(&pat))
}
-struct LiteralExpander;
-impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
+struct LiteralExpander<'a, 'tcx> {
+ tcx: TyCtxt<'a, 'tcx, 'tcx>
+}
+
+impl<'a, 'tcx> LiteralExpander<'a, 'tcx> {
+ /// Derefs `val` and potentially unsizes the value if `crty` is an array and `rty` a slice.
+ ///
+ /// `crty` and `rty` can differ because you can use array constants in the presence of slice
+ /// patterns. So the pattern may end up being a slice, but the constant is an array. We convert
+ /// the array to a slice in that case.
+ fn fold_const_value_deref(
+ &mut self,
+ val: ConstValue<'tcx>,
+ // the pattern's pointee type
+ rty: Ty<'tcx>,
+ // the constant's pointee type
+ crty: Ty<'tcx>,
+ ) -> ConstValue<'tcx> {
+ match (val, &crty.sty, &rty.sty) {
+ // the easy case, deref a reference
+ (ConstValue::Scalar(Scalar::Ptr(p)), x, y) if x == y => ConstValue::ByRef(
+ p.alloc_id,
+ self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id),
+ p.offset,
+ ),
+ // unsize array to slice if pattern is array but match value or other patterns are slice
+ (ConstValue::Scalar(Scalar::Ptr(p)), ty::Array(t, n), ty::Slice(u)) => {
+ assert_eq!(t, u);
+ ConstValue::ScalarPair(
+ Scalar::Ptr(p),
+ n.val.try_to_scalar().unwrap(),
+ )
+ },
+ // fat pointers stay the same
+ (ConstValue::ScalarPair(..), _, _) => val,
+ // FIXME(oli-obk): this is reachable for `const FOO: &&&u32 = &&&42;` being used
+ _ => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty),
+ }
+ }
+}
+
+impl<'a, 'tcx> PatternFolder<'tcx> for LiteralExpander<'a, 'tcx> {
fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
match (&pat.ty.sty, &*pat.kind) {
- (&ty::Ref(_, rty, _), &PatternKind::Constant { ref value }) => {
+ (
+ &ty::Ref(_, rty, _),
+ &PatternKind::Constant { value: Const {
+ val,
+ ty: ty::TyS { sty: ty::Ref(_, crty, _), .. },
+ } },
+ ) => {
Pattern {
ty: pat.ty,
span: pat.span,
@@ -215,7 +261,11 @@
subpattern: Pattern {
ty: rty,
span: pat.span,
- kind: box PatternKind::Constant { value: value.clone() },
+ kind: box PatternKind::Constant { value: Const::from_const_value(
+ self.tcx,
+ self.fold_const_value_deref(*val, rty, crty),
+ rty,
+ ) },
}
}
}
@@ -732,15 +782,17 @@
for row in patterns {
match *row.kind {
PatternKind::Constant { value } => {
- if let Some(ptr) = value.to_ptr() {
- let is_array_ptr = value.ty
- .builtin_deref(true)
- .and_then(|t| t.ty.builtin_index())
- .map_or(false, |t| t == cx.tcx.types.u8);
- if is_array_ptr {
- let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
- max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
- }
+ // extract the length of an array/slice from a constant
+ match (value.val, &value.ty.sty) {
+ (_, ty::Array(_, n)) => max_fixed_len = cmp::max(
+ max_fixed_len,
+ n.unwrap_usize(cx.tcx),
+ ),
+ (ConstValue::ScalarPair(_, n), ty::Slice(_)) => max_fixed_len = cmp::max(
+ max_fixed_len,
+ n.to_usize(&cx.tcx).unwrap(),
+ ),
+ _ => {},
}
}
PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
@@ -1348,28 +1400,62 @@
}
}
-fn slice_pat_covered_by_constructor<'tcx>(
+// checks whether a constant is equal to a user-written slice pattern. Only supports byte slices,
+// meaning all other types will compare unequal and thus equal patterns often do not cause the
+// second pattern to lint about unreachable match arms.
+fn slice_pat_covered_by_const<'tcx>(
tcx: TyCtxt<'_, 'tcx, '_>,
_span: Span,
- ctor: &Constructor,
+ const_val: &ty::Const<'tcx>,
prefix: &[Pattern<'tcx>],
slice: &Option<Pattern<'tcx>>,
suffix: &[Pattern<'tcx>]
) -> Result<bool, ErrorReported> {
- let data: &[u8] = match *ctor {
- ConstantValue(const_val) => {
- let val = match const_val.val {
- ConstValue::Unevaluated(..) |
- ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
- ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
- };
- if let Ok(ptr) = val.to_ptr() {
- tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
- } else {
- bug!("unexpected non-ptr ConstantValue")
+ let data: &[u8] = match (const_val.val, &const_val.ty.sty) {
+ (ConstValue::ByRef(id, alloc, offset), ty::Array(t, n)) => {
+ if *t != tcx.types.u8 {
+ // FIXME(oli-obk): can't mix const patterns with slice patterns and get
+ // any sort of exhaustiveness/unreachable check yet
+ // This solely means that we don't lint about unreachable patterns, even if some
+ // are definitely unreachable.
+ return Ok(false);
}
- }
- _ => bug!()
+ let ptr = Pointer::new(id, offset);
+ let n = n.assert_usize(tcx).unwrap();
+ alloc.get_bytes(&tcx, ptr, Size::from_bytes(n)).unwrap()
+ },
+ // a slice fat pointer to a zero length slice
+ (ConstValue::ScalarPair(Scalar::Bits { .. }, n), ty::Slice(t)) => {
+ if *t != tcx.types.u8 {
+ // FIXME(oli-obk): can't mix const patterns with slice patterns and get
+ // any sort of exhaustiveness/unreachable check yet
+ // This solely means that we don't lint about unreachable patterns, even if some
+ // are definitely unreachable.
+ return Ok(false);
+ }
+ assert_eq!(n.to_usize(&tcx).unwrap(), 0);
+ &[]
+ },
+ //
+ (ConstValue::ScalarPair(Scalar::Ptr(ptr), n), ty::Slice(t)) => {
+ if *t != tcx.types.u8 {
+ // FIXME(oli-obk): can't mix const patterns with slice patterns and get
+ // any sort of exhaustiveness/unreachable check yet
+ // This solely means that we don't lint about unreachable patterns, even if some
+ // are definitely unreachable.
+ return Ok(false);
+ }
+ let n = n.to_usize(&tcx).unwrap();
+ tcx.alloc_map
+ .lock()
+ .unwrap_memory(ptr.alloc_id)
+ .get_bytes(&tcx, ptr, Size::from_bytes(n))
+ .unwrap()
+ },
+ _ => bug!(
+ "slice_pat_covered_by_const: {:#?}, {:#?}, {:#?}, {:#?}",
+ const_val, prefix, slice, suffix,
+ ),
};
let pat_len = prefix.len() + suffix.len();
@@ -1675,22 +1761,23 @@
// necessarily point to memory, they are usually just integers. The only time
// they should be pointing to memory is when they are subslices of nonzero
// slices
- let (opt_ptr, n, ty) = match value.ty.builtin_deref(false).unwrap().ty.sty {
- ty::TyKind::Array(t, n) => (value.to_ptr(), n.unwrap_usize(cx.tcx), t),
- ty::TyKind::Slice(t) => {
- match value.val {
- ConstValue::ScalarPair(ptr, n) => (
- ptr.to_ptr().ok(),
- n.to_bits(cx.tcx.data_layout.pointer_size).unwrap() as u64,
- t,
- ),
- _ => span_bug!(
- pat.span,
- "slice pattern constant must be scalar pair but is {:?}",
- value,
- ),
- }
- },
+ let (opt_ptr, n, ty) = match (value.val, &value.ty.sty) {
+ (ConstValue::ByRef(id, alloc, offset), ty::TyKind::Array(t, n)) => (
+ Some((
+ Pointer::new(id, offset),
+ alloc,
+ )),
+ n.unwrap_usize(cx.tcx),
+ t,
+ ),
+ (ConstValue::ScalarPair(ptr, n), ty::TyKind::Slice(t)) => (
+ ptr.to_ptr().ok().map(|ptr| (
+ ptr,
+ cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
+ )),
+ n.to_bits(cx.tcx.data_layout.pointer_size).unwrap() as u64,
+ t,
+ ),
_ => span_bug!(
pat.span,
"unexpected const-val {:?} with ctor {:?}",
@@ -1702,8 +1789,7 @@
// convert a constant slice/array pattern to a list of patterns.
match (n, opt_ptr) {
(0, _) => Some(SmallVec::new()),
- (_, Some(ptr)) => {
- let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
+ (_, Some((ptr, alloc))) => {
let layout = cx.tcx.layout_of(cx.param_env.and(ty)).ok()?;
(0..n).map(|i| {
let ptr = ptr.offset(layout.size * i, &cx.tcx).ok()?;
@@ -1766,10 +1852,8 @@
None
}
}
- ConstantValue(..) => {
- match slice_pat_covered_by_constructor(
- cx.tcx, pat.span, constructor, prefix, slice, suffix
- ) {
+ ConstantValue(cv) => {
+ match slice_pat_covered_by_const(cx.tcx, pat.span, cv, prefix, slice, suffix) {
Ok(true) => Some(smallvec![]),
Ok(false) => None,
Err(ErrorReported) => None
diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs
index d695a64..ddd6a70 100644
--- a/src/librustc_mir/hair/pattern/mod.rs
+++ b/src/librustc_mir/hair/pattern/mod.rs
@@ -1259,34 +1259,32 @@
}
}
- if let ty::Ref(_, rty, _) = ty.value.sty {
- if let ty::Str = rty.sty {
- match (a.val, b.val) {
- (
- ConstValue::ScalarPair(
- Scalar::Ptr(ptr_a),
- len_a,
- ),
- ConstValue::ScalarPair(
- Scalar::Ptr(ptr_b),
- len_b,
- ),
- ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
- if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
- if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
- if len_a == len_b {
- let map = tcx.alloc_map.lock();
- let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
- let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
- if alloc_a.bytes.len() as u128 == len_a {
- return from_bool(alloc_a == alloc_b);
- }
+ if let ty::Str = ty.value.sty {
+ match (a.val, b.val) {
+ (
+ ConstValue::ScalarPair(
+ Scalar::Ptr(ptr_a),
+ len_a,
+ ),
+ ConstValue::ScalarPair(
+ Scalar::Ptr(ptr_b),
+ len_b,
+ ),
+ ) if ptr_a.offset.bytes() == 0 && ptr_b.offset.bytes() == 0 => {
+ if let Ok(len_a) = len_a.to_bits(tcx.data_layout.pointer_size) {
+ if let Ok(len_b) = len_b.to_bits(tcx.data_layout.pointer_size) {
+ if len_a == len_b {
+ let map = tcx.alloc_map.lock();
+ let alloc_a = map.unwrap_memory(ptr_a.alloc_id);
+ let alloc_b = map.unwrap_memory(ptr_b.alloc_id);
+ if alloc_a.bytes.len() as u128 == len_a {
+ return from_bool(alloc_a == alloc_b);
}
}
}
}
- _ => (),
}
+ _ => (),
}
}
diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs
index ebd2c87..e449fec 100644
--- a/src/librustc_resolve/lib.rs
+++ b/src/librustc_resolve/lib.rs
@@ -3010,6 +3010,7 @@
// Visit all direct subpatterns of this pattern.
let outer_pat_id = pat.id;
pat.walk(&mut |pat| {
+ debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
match pat.node {
PatKind::Ident(bmode, ident, ref opt_pat) => {
// First try to resolve the identifier as some existing
@@ -3166,6 +3167,7 @@
format!("not found in {}", mod_str),
item_span)
};
+
let code = DiagnosticId::Error(code.into());
let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
@@ -3189,11 +3191,22 @@
return (err, Vec::new());
}
if is_self_value(path, ns) {
+ debug!("smart_resolve_path_fragment E0424 source:{:?}", source);
+
__diagnostic_used!(E0424);
err.code(DiagnosticId::Error("E0424".into()));
- err.span_label(span, format!("`self` value is a keyword \
- only available in \
- methods with `self` parameter"));
+ err.span_label(span, match source {
+ PathSource::Pat => {
+ format!("`self` value is a keyword \
+ and may not be bound to \
+ variables or shadowed")
+ }
+ _ => {
+ format!("`self` value is a keyword \
+ only available in methods \
+ with `self` parameter")
+ }
+ });
return (err, Vec::new());
}
diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs
index d8e8477..aef8770 100644
--- a/src/librustc_target/spec/mod.rs
+++ b/src/librustc_target/spec/mod.rs
@@ -68,6 +68,7 @@
mod openbsd_base;
mod netbsd_base;
mod solaris_base;
+mod uefi_base;
mod windows_base;
mod windows_msvc_base;
mod thumb_base;
@@ -254,12 +255,12 @@
}
}
- pub fn get_targets() -> Box<dyn Iterator<Item=String>> {
- Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
+ pub fn get_targets() -> impl Iterator<Item = String> {
+ TARGETS.iter().filter_map(|t| -> Option<String> {
load_specific(t)
.and(Ok(t.to_string()))
.ok()
- }))
+ })
}
#[cfg(test)]
@@ -419,6 +420,8 @@
("aarch64-unknown-none", aarch64_unknown_none),
("x86_64-fortanix-unknown-sgx", x86_64_fortanix_unknown_sgx),
+
+ ("x86_64-unknown-uefi", x86_64_unknown_uefi),
}
/// Everything `rustc` knows about how to compile for a specific target.
diff --git a/src/librustc_target/spec/uefi_base.rs b/src/librustc_target/spec/uefi_base.rs
new file mode 100644
index 0000000..9b05158
--- /dev/null
+++ b/src/librustc_target/spec/uefi_base.rs
@@ -0,0 +1,74 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This defines a base target-configuration for native UEFI systems. The UEFI specification has
+// quite detailed sections on the ABI of all the supported target architectures. In almost all
+// cases it simply follows what Microsoft Windows does. Hence, whenever in doubt, see the MSDN
+// documentation.
+// UEFI uses COFF/PE32+ format for binaries. All binaries must be statically linked. No dynamic
+// linker is supported. As native to COFF, binaries are position-dependent, but will be relocated
+// by the loader if the pre-chosen memory location is already in use.
+// UEFI forbids running code on anything but the boot-CPU. Not interrupts are allowed other than
+// the timer-interrupt. Device-drivers are required to use polling-based models. Furthermore, all
+// code runs in the same environment, no process separation is supported.
+
+use spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions};
+use std::default::Default;
+
+pub fn opts() -> TargetOptions {
+ let mut pre_link_args = LinkArgs::new();
+
+ pre_link_args.insert(LinkerFlavor::Lld(LldFlavor::Link), vec![
+ // Suppress the verbose logo and authorship debugging output, which would needlessly
+ // clog any log files.
+ "/NOLOGO".to_string(),
+
+ // UEFI is fully compatible to non-executable data pages. Tell the compiler that
+ // non-code sections can be marked as non-executable, including stack pages.
+ "/NXCOMPAT".to_string(),
+
+ // There is no runtime for UEFI targets, prevent them from being linked. UEFI targets
+ // must be freestanding.
+ "/nodefaultlib".to_string(),
+
+ // Non-standard subsystems have no default entry-point in PE+ files. We have to define
+ // one. "efi_main" seems to be a common choice amongst other implementations and the
+ // spec.
+ "/entry:efi_main".to_string(),
+
+ // COFF images have a "Subsystem" field in their header, which defines what kind of
+ // program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION,
+ // EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION,
+ // which is very likely the most common option. Individual projects can override this
+ // with custom linker flags.
+ // The subsystem-type only has minor effects on the application. It defines the memory
+ // regions the application is loaded into (runtime-drivers need to be put into
+ // reserved areas), as well as whether a return from the entry-point is treated as
+ // exit (default for applications).
+ "/subsystem:efi_application".to_string(),
+ ]);
+
+ TargetOptions {
+ dynamic_linking: false,
+ executables: true,
+ disable_redzone: true,
+ exe_suffix: ".efi".to_string(),
+ allows_weak_linkage: false,
+ panic_strategy: PanicStrategy::Abort,
+ singlethread: true,
+ emit_debug_gdb_scripts: false,
+
+ linker: Some("lld-link".to_string()),
+ lld_flavor: LldFlavor::Link,
+ pre_link_args,
+
+ .. Default::default()
+ }
+}
diff --git a/src/librustc_target/spec/x86_64_unknown_uefi.rs b/src/librustc_target/spec/x86_64_unknown_uefi.rs
new file mode 100644
index 0000000..ea68afa
--- /dev/null
+++ b/src/librustc_target/spec/x86_64_unknown_uefi.rs
@@ -0,0 +1,58 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// This defines the amd64 target for UEFI systems as described in the UEFI specification. See the
+// uefi-base module for generic UEFI options. On x86_64 systems (mostly called "x64" in the spec)
+// UEFI systems always run in long-mode, have the interrupt-controller pre-configured and force a
+// single-CPU execution.
+// The win64 ABI is used. It differs from the sysv64 ABI, so we must use a windows target with
+// LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features.
+
+use spec::{LinkerFlavor, LldFlavor, Target, TargetResult};
+
+pub fn target() -> TargetResult {
+ let mut base = super::uefi_base::opts();
+ base.cpu = "x86-64".to_string();
+ base.max_atomic_width = Some(64);
+
+ // We disable MMX and SSE for now. UEFI does not prevent these from being used, but there have
+ // been reports to GRUB that some firmware does not initialize the FP exception handlers
+ // properly. Therefore, using FP coprocessors will end you up at random memory locations when
+ // you throw FP exceptions.
+ // To be safe, we disable them for now and force soft-float. This can be revisited when we
+ // have more test coverage. Disabling FP served GRUB well so far, so it should be good for us
+ // as well.
+ base.features = "-mmx,-sse,+soft-float".to_string();
+
+ // UEFI systems run without a host OS, hence we cannot assume any code locality. We must tell
+ // LLVM to expect code to reference any address in the address-space. The "large" code-model
+ // places no locality-restrictions, so it fits well here.
+ base.code_model = Some("large".to_string());
+
+ // UEFI mostly mirrors the calling-conventions used on windows. In case of x86-64 this means
+ // small structs will be returned as int. This shouldn't matter much, since the restrictions
+ // placed by the UEFI specifications forbid any ABI to return structures.
+ base.abi_return_struct_as_int = true;
+
+ Ok(Target {
+ llvm_target: "x86_64-unknown-windows".to_string(),
+ target_endian: "little".to_string(),
+ target_pointer_width: "64".to_string(),
+ target_c_int_width: "32".to_string(),
+ data_layout: "e-m:w-i64:64-f80:128-n8:16:32:64-S128".to_string(),
+ target_os: "uefi".to_string(),
+ target_env: "".to_string(),
+ target_vendor: "unknown".to_string(),
+ arch: "x86_64".to_string(),
+ linker_flavor: LinkerFlavor::Lld(LldFlavor::Link),
+
+ options: base,
+ })
+}
diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs
index 5c0eef5..a40e56d 100644
--- a/src/librustc_typeck/check/intrinsic.rs
+++ b/src/librustc_typeck/check/intrinsic.rs
@@ -435,7 +435,8 @@
"simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
"simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
"simd_cast" => (2, vec![param(0)], param(1)),
- "simd_select" => (2, vec![param(0), param(1), param(1)], param(1)),
+ "simd_select" |
+ "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
"simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
"simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
=> (2, vec![param(0), param(1)], param(1)),
diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs
index b76c910..0906357 100644
--- a/src/librustc_typeck/check/method/suggest.rs
+++ b/src/librustc_typeck/check/method/suggest.rs
@@ -424,10 +424,12 @@
}
if !unsatisfied_predicates.is_empty() {
- let bound_list = unsatisfied_predicates.iter()
+ let mut bound_list = unsatisfied_predicates.iter()
.map(|p| format!("`{} : {}`", p.self_ty(), p))
- .collect::<Vec<_>>()
- .join("\n");
+ .collect::<Vec<_>>();
+ bound_list.sort();
+ bound_list.dedup(); // #35677
+ let bound_list = bound_list.join("\n");
err.note(&format!("the method `{}` exists but the following trait bounds \
were not satisfied:\n{}",
item_name,
diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs
index 6ce02c3..37ff693 100644
--- a/src/librustdoc/html/layout.rs
+++ b/src/librustdoc/html/layout.rs
@@ -54,6 +54,7 @@
<link rel=\"stylesheet\" type=\"text/css\" href=\"{root_path}light{suffix}.css\" \
id=\"themeStyle\">\
<script src=\"{root_path}storage{suffix}.js\"></script>\
+ <noscript><link rel=\"stylesheet\" href=\"{root_path}noscript{suffix}.css\"></noscript>\
{css_extension}\
{favicon}\
{in_header}\
diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs
index 00ca4fe..536ea39 100644
--- a/src/librustdoc/html/markdown.rs
+++ b/src/librustdoc/html/markdown.rs
@@ -806,6 +806,10 @@
}
pub fn plain_summary_line(md: &str) -> String {
+ plain_summary_line_full(md, false)
+}
+
+pub fn plain_summary_line_full(md: &str, limit_length: bool) -> String {
struct ParserWrapper<'a> {
inner: Parser<'a>,
is_in: isize,
@@ -852,7 +856,21 @@
s.push_str(&t);
}
}
- s
+ if limit_length && s.chars().count() > 60 {
+ let mut len = 0;
+ let mut ret = s.split_whitespace()
+ .take_while(|p| {
+ // + 1 for the added character after the word.
+ len += p.chars().count() + 1;
+ len < 60
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+ ret.push('…');
+ ret
+ } else {
+ s
+ }
}
pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 8d7942a..c9f3aa0 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -698,7 +698,7 @@
ty: item.type_(),
name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].join("::"),
- desc: plain_summary_line(item.doc_value()),
+ desc: plain_summary_line_short(item.doc_value()),
parent: Some(did),
parent_idx: None,
search_type: get_index_search_type(&item),
@@ -736,7 +736,7 @@
}
let crate_doc = krate.module.as_ref().map(|module| {
- plain_summary_line(module.doc_value())
+ plain_summary_line_short(module.doc_value())
}).unwrap_or(String::new());
let mut crate_data = BTreeMap::new();
@@ -772,6 +772,9 @@
write_minify(cx.dst.join(&format!("settings{}.css", cx.shared.resource_suffix)),
static_files::SETTINGS_CSS,
options.enable_minification)?;
+ write_minify(cx.dst.join(&format!("noscript{}.css", cx.shared.resource_suffix)),
+ static_files::NOSCRIPT_CSS,
+ options.enable_minification)?;
// To avoid "light.css" to be overwritten, we'll first run over the received themes and only
// then we'll run over the "official" styles.
@@ -865,9 +868,8 @@
}
{
- let mut data = format!("var resourcesSuffix = \"{}\";\n",
- cx.shared.resource_suffix);
- data.push_str(static_files::STORAGE_JS);
+ let mut data = static_files::STORAGE_JS.to_owned();
+ data.push_str(&format!("var resourcesSuffix = \"{}\";", cx.shared.resource_suffix));
write_minify(cx.dst.join(&format!("storage{}.js", cx.shared.resource_suffix)),
&data,
options.enable_minification)?;
@@ -1481,7 +1483,7 @@
ty: item.type_(),
name: s.to_string(),
path: path.join("::"),
- desc: plain_summary_line(item.doc_value()),
+ desc: plain_summary_line_short(item.doc_value()),
parent,
parent_idx: None,
search_type: get_index_search_type(&item),
@@ -1512,7 +1514,8 @@
clean::FunctionItem(..) | clean::ModuleItem(..) |
clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
clean::ConstantItem(..) | clean::StaticItem(..) |
- clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
+ clean::UnionItem(..) | clean::ForeignTypeItem |
+ clean::MacroItem(..) | clean::ProcMacroItem(..)
if !self.stripped_mod => {
// Re-exported items mean that the same id can show up twice
// in the rustdoc ast that we're looking at. We know,
@@ -1673,7 +1676,7 @@
ty: item.type_(),
name: item_name.to_string(),
path: path.clone(),
- desc: plain_summary_line(item.doc_value()),
+ desc: plain_summary_line_short(item.doc_value()),
parent: None,
parent_idx: None,
search_type: get_index_search_type(&item),
@@ -2388,7 +2391,13 @@
#[inline]
fn plain_summary_line(s: Option<&str>) -> String {
let line = shorter(s).replace("\n", " ");
- markdown::plain_summary_line(&line[..])
+ markdown::plain_summary_line_full(&line[..], false)
+}
+
+#[inline]
+fn plain_summary_line_short(s: Option<&str>) -> String {
+ let line = shorter(s).replace("\n", " ");
+ markdown::plain_summary_line_full(&line[..], true)
}
fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
@@ -3006,6 +3015,22 @@
// Trait documentation
document(w, cx, it)?;
+ fn write_small_section_header(
+ w: &mut fmt::Formatter,
+ id: &str,
+ title: &str,
+ extra_content: &str,
+ ) -> fmt::Result {
+ write!(w, "
+ <h2 id='{0}' class='small-section-header'>\
+ {1}<a href='#{0}' class='anchor'></a>\
+ </h2>{2}", id, title, extra_content)
+ }
+
+ fn write_loading_content(w: &mut fmt::Formatter, extra_content: &str) -> fmt::Result {
+ write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
+ }
+
fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
-> fmt::Result {
let name = m.name.as_ref().unwrap();
@@ -3026,74 +3051,45 @@
}
if !types.is_empty() {
- write!(w, "
- <h2 id='associated-types' class='small-section-header'>
- Associated Types<a href='#associated-types' class='anchor'></a>
- </h2>
- <div class='methods'>
- ")?;
+ write_small_section_header(w, "associated-types", "Associated Types",
+ "<div class='methods'>")?;
for t in &types {
trait_item(w, cx, *t, it)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
}
if !consts.is_empty() {
- write!(w, "
- <h2 id='associated-const' class='small-section-header'>
- Associated Constants<a href='#associated-const' class='anchor'></a>
- </h2>
- <div class='methods'>
- ")?;
+ write_small_section_header(w, "associated-const", "Associated Constants",
+ "<div class='methods'>")?;
for t in &consts {
trait_item(w, cx, *t, it)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
}
// Output the documentation for each function individually
if !required.is_empty() {
- write!(w, "
- <h2 id='required-methods' class='small-section-header'>
- Required Methods<a href='#required-methods' class='anchor'></a>
- </h2>
- <div class='methods'>
- ")?;
+ write_small_section_header(w, "required-methods", "Required methods",
+ "<div class='methods'>")?;
for m in &required {
trait_item(w, cx, *m, it)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
}
if !provided.is_empty() {
- write!(w, "
- <h2 id='provided-methods' class='small-section-header'>
- Provided Methods<a href='#provided-methods' class='anchor'></a>
- </h2>
- <div class='methods'>
- ")?;
+ write_small_section_header(w, "provided-methods", "Provided methods",
+ "<div class='methods'>")?;
for m in &provided {
trait_item(w, cx, *m, it)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
}
// If there are methods directly on this trait object, render them here.
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
let cache = cache();
- let impl_header = "\
- <h2 id='implementors' class='small-section-header'>\
- Implementors<a href='#implementors' class='anchor'></a>\
- </h2>\
- <div class='item-list' id='implementors-list'>\
- ";
-
- let synthetic_impl_header = "\
- <h2 id='synthetic-implementors' class='small-section-header'>\
- Auto implementors<a href='#synthetic-implementors' class='anchor'></a>\
- </h2>\
- <div class='item-list' id='synthetic-implementors-list'>\
- ";
let mut synthetic_types = Vec::new();
@@ -3130,11 +3126,7 @@
concrete.sort_by(compare_impl);
if !foreign.is_empty() {
- write!(w, "
- <h2 id='foreign-impls' class='small-section-header'>
- Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
- </h2>
- ")?;
+ write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "")?;
for implementor in foreign {
let assoc_link = AssocItemLink::GotoSource(
@@ -3145,33 +3137,38 @@
RenderMode::Normal, implementor.impl_item.stable_since(), false,
None)?;
}
+ write_loading_content(w, "")?;
}
- write!(w, "{}", impl_header)?;
+ write_small_section_header(w, "implementors", "Implementors",
+ "<div class='item-list' id='implementors-list'>")?;
for implementor in concrete {
render_implementor(cx, implementor, w, &implementor_dups)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
if t.auto {
- write!(w, "{}", synthetic_impl_header)?;
+ write_small_section_header(w, "synthetic-implementors", "Auto implementors",
+ "<div class='item-list' id='synthetic-implementors-list'>")?;
for implementor in synthetic {
synthetic_types.extend(
collect_paths_for_type(implementor.inner_impl().for_.clone())
);
render_implementor(cx, implementor, w, &implementor_dups)?;
}
- write!(w, "</div>")?;
+ write_loading_content(w, "</div>")?;
}
} else {
// even without any implementations to write in, we still want the heading and list, so the
// implementors javascript file pulled in below has somewhere to write the impls into
- write!(w, "{}", impl_header)?;
- write!(w, "</div>")?;
+ write_small_section_header(w, "implementors", "Implementors",
+ "<div class='item-list' id='implementors-list'>")?;
+ write_loading_content(w, "</div>")?;
if t.auto {
- write!(w, "{}", synthetic_impl_header)?;
- write!(w, "</div>")?;
+ write_small_section_header(w, "synthetic-implementors", "Auto implementors",
+ "<div class='item-list' id='synthetic-implementors-list'>")?;
+ write_loading_content(w, "</div>")?;
}
}
write!(w, r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index 1869969..51714c3 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -30,6 +30,27 @@
};
}
+if (!DOMTokenList.prototype.add) {
+ DOMTokenList.prototype.add = function(className) {
+ if (className && !hasClass(this, className)) {
+ if (this.className && this.className.length > 0) {
+ this.className += " " + className;
+ } else {
+ this.className = className;
+ }
+ }
+ };
+}
+
+if (!DOMTokenList.prototype.remove) {
+ DOMTokenList.prototype.remove = function(className) {
+ if (className && this.className) {
+ this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
+ .trim();
+ }
+ };
+}
+
(function() {
"use strict";
@@ -61,7 +82,7 @@
"attr",
"derive"];
- var search_input = document.getElementsByClassName('search-input')[0];
+ var search_input = document.getElementsByClassName("search-input")[0];
// On the search screen, so you remain on the last tab you opened.
//
@@ -75,9 +96,9 @@
var titleBeforeSearch = document.title;
function getPageId() {
- var id = document.location.href.split('#')[1];
+ var id = document.location.href.split("#")[1];
if (id) {
- return id.split('?')[0].split('&')[0];
+ return id.split("?")[0].split("&")[0];
}
return null;
}
@@ -87,9 +108,9 @@
if (elems) {
addClass(elems, "show-it");
}
- var sidebar = document.getElementsByClassName('sidebar')[0];
+ var sidebar = document.getElementsByClassName("sidebar")[0];
if (sidebar) {
- addClass(sidebar, 'mobile');
+ addClass(sidebar, "mobile");
var filler = document.getElementById("sidebar-filler");
if (!filler) {
var div = document.createElement("div");
@@ -108,13 +129,13 @@
if (elems) {
removeClass(elems, "show-it");
}
- var sidebar = document.getElementsByClassName('sidebar')[0];
- removeClass(sidebar, 'mobile');
+ var sidebar = document.getElementsByClassName("sidebar")[0];
+ removeClass(sidebar, "mobile");
var filler = document.getElementById("sidebar-filler");
if (filler) {
filler.remove();
}
- document.getElementsByTagName("body")[0].style.marginTop = '';
+ document.getElementsByTagName("body")[0].style.marginTop = "";
var themePicker = document.getElementsByClassName("theme-picker");
if (themePicker && themePicker.length > 0) {
themePicker[0].style.display = null;
@@ -125,8 +146,8 @@
var TY_PRIMITIVE = itemTypes.indexOf("primitive");
var TY_KEYWORD = itemTypes.indexOf("keyword");
- onEach(document.getElementsByClassName('js-only'), function(e) {
- removeClass(e, 'js-only');
+ onEachLazy(document.getElementsByClassName("js-only"), function(e) {
+ removeClass(e, "js-only");
});
function getQueryStringParams() {
@@ -145,16 +166,19 @@
window.history && typeof window.history.pushState === "function";
}
+ var main = document.getElementById("main");
+
function highlightSourceLines(ev) {
// If we're in mobile mode, we should add the sidebar in any case.
hideSidebar();
+ var elem;
var search = document.getElementById("search");
var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
if (match) {
from = parseInt(match[1], 10);
to = Math.min(50000, parseInt(match[2] || match[1], 10));
from = Math.min(from, to);
- var elem = document.getElementById(from);
+ elem = document.getElementById(from);
if (!elem) {
return;
}
@@ -164,22 +188,22 @@
x.scrollIntoView();
}
}
- onEach(document.getElementsByClassName('line-numbers'), function(e) {
- onEach(e.getElementsByTagName('span'), function(i_e) {
- removeClass(i_e, 'line-highlighted');
+ onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
+ onEachLazy(e.getElementsByTagName("span"), function(i_e) {
+ removeClass(i_e, "line-highlighted");
});
});
for (i = from; i <= to; ++i) {
- addClass(document.getElementById(i), 'line-highlighted');
+ addClass(document.getElementById(i), "line-highlighted");
}
} else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
addClass(search, "hidden");
- removeClass(document.getElementById("main"), "hidden");
- var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
+ removeClass(main, "hidden");
+ var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
if (browserSupportsHistoryApi()) {
history.replaceState(hash, "", "?search=#" + hash);
}
- var elem = document.getElementById(hash);
+ elem = document.getElementById(hash);
if (elem) {
elem.scrollIntoView();
}
@@ -190,7 +214,7 @@
var elem = document.getElementById(id);
if (elem && isHidden(elem)) {
var h3 = elem.parentNode.previousSibling;
- if (h3 && h3.tagName !== 'H3') {
+ if (h3 && h3.tagName !== "H3") {
h3 = h3.previousSibling; // skip div.docblock
}
@@ -236,7 +260,7 @@
removeClass(help, "hidden");
addClass(document.body, "blur");
}
- } else if (!hasClass(help, "hidden")) {
+ } else if (hasClass(help, "hidden") === false) {
ev.preventDefault();
addClass(help, "hidden");
removeClass(document.body, "blur");
@@ -246,12 +270,12 @@
function handleEscape(ev, help) {
hideModal();
var search = document.getElementById("search");
- if (!hasClass(help, "hidden")) {
+ if (hasClass(help, "hidden") === false) {
displayHelp(false, ev);
- } else if (!hasClass(search, "hidden")) {
+ } else if (hasClass(search, "hidden") === false) {
ev.preventDefault();
addClass(search, "hidden");
- removeClass(document.getElementById("main"), "hidden");
+ removeClass(main, "hidden");
document.title = titleBeforeSearch;
}
defocusSearchBar();
@@ -305,26 +329,27 @@
if (elem && elem.tagName === tagName) {
return elem;
}
- } while (elem = elem.parentNode);
+ elem = elem.parentNode;
+ } while (elem);
return null;
}
document.onkeypress = handleShortcut;
document.onkeydown = handleShortcut;
document.onclick = function(ev) {
- if (hasClass(ev.target, 'collapse-toggle')) {
+ if (hasClass(ev.target, "collapse-toggle")) {
collapseDocs(ev.target, "toggle");
- } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
+ } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
collapseDocs(ev.target.parentNode, "toggle");
- } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
+ } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
var prev_id = 0;
var set_fragment = function(name) {
if (browserSupportsHistoryApi()) {
- history.replaceState(null, null, '#' + name);
+ history.replaceState(null, null, "#" + name);
window.hashchange();
} else {
- location.replace('#' + name);
+ location.replace("#" + name);
}
};
@@ -337,31 +362,31 @@
cur_id = tmp;
}
- set_fragment(prev_id + '-' + cur_id);
+ set_fragment(prev_id + "-" + cur_id);
} else {
prev_id = cur_id;
set_fragment(cur_id);
}
- } else if (!hasClass(document.getElementById("help"), "hidden")) {
+ } else if (hasClass(document.getElementById("help"), "hidden") === false) {
addClass(document.getElementById("help"), "hidden");
removeClass(document.body, "blur");
} else {
// Making a collapsed element visible on onhashchange seems
// too late
- var a = findParentElement(ev.target, 'A');
+ var a = findParentElement(ev.target, "A");
if (a && a.hash) {
- expandSection(a.hash.replace(/^#/, ''));
+ expandSection(a.hash.replace(/^#/, ""));
}
}
};
- var x = document.getElementsByClassName('version-selector');
+ var x = document.getElementsByClassName("version-selector");
if (x.length > 0) {
x[0].onchange = function() {
var i, match,
url = document.location.href,
- stripped = '',
+ stripped = "",
len = rootPath.match(/\.\.\//g).length + 1;
for (i = 0; i < len; ++i) {
@@ -372,7 +397,7 @@
url = url.substring(0, url.length - match[0].length);
}
- url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
+ url += "/" + document.getElementsByClassName("version-selector")[0].value + stripped;
document.location.href = url;
};
@@ -428,7 +453,7 @@
// where you start trying to do a search, and the index loads, and
// suddenly your search is gone!
if (search_input.value === "") {
- search_input.value = params.search || '';
+ search_input.value = params.search || "";
}
/**
@@ -441,7 +466,8 @@
*/
function execQuery(query, searchWords, filterCrates) {
function itemTypeFromName(typename) {
- for (var i = 0; i < itemTypes.length; ++i) {
+ var length = itemTypes.length;
+ for (var i = 0; i < length; ++i) {
if (itemTypes[i] === typename) {
return i;
}
@@ -455,7 +481,8 @@
results = {}, results_in_args = {}, results_returned = {},
split = valLower.split("::");
- for (var z = 0; z < split.length; ++z) {
+ var length = split.length;
+ for (var z = 0; z < length; ++z) {
if (split[z] === "") {
split.splice(z, 1);
z -= 1;
@@ -464,7 +491,8 @@
function transformResults(results, isType) {
var out = [];
- for (i = 0; i < results.length; ++i) {
+ var length = results.length;
+ for (var i = 0; i < length; ++i) {
if (results[i].id > -1) {
var obj = searchIndex[results[i].id];
obj.lev = results[i].lev;
@@ -473,7 +501,7 @@
obj.displayPath = pathSplitter(res[0]);
obj.fullPath = obj.displayPath + obj.name;
// To be sure than it some items aren't considered as duplicate.
- obj.fullPath += '|' + obj.ty;
+ obj.fullPath += "|" + obj.ty;
obj.href = res[1];
out.push(obj);
if (out.length >= MAX_RESULTS) {
@@ -493,8 +521,9 @@
}
}
results = ar;
+ var i;
var nresults = results.length;
- for (var i = 0; i < nresults; ++i) {
+ for (i = 0; i < nresults; ++i) {
results[i].word = searchWords[results[i].id];
results[i].item = searchIndex[results[i].id] || {};
}
@@ -552,8 +581,8 @@
}
// sort by description (no description goes later)
- a = (aaa.item.desc === '');
- b = (bbb.item.desc === '');
+ a = (aaa.item.desc === "");
+ b = (bbb.item.desc === "");
if (a !== b) { return a - b; }
// sort by type (later occurrence in `itemTypes` goes later)
@@ -570,7 +599,8 @@
return 0;
});
- for (var i = 0; i < results.length; ++i) {
+ var length = results.length;
+ for (i = 0; i < length; ++i) {
var result = results[i];
// this validation does not make sense when searching by types
@@ -592,10 +622,10 @@
function extractGenerics(val) {
val = val.toLowerCase();
- if (val.indexOf('<') !== -1) {
- var values = val.substring(val.indexOf('<') + 1, val.lastIndexOf('>'));
+ if (val.indexOf("<") !== -1) {
+ var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
return {
- name: val.substring(0, val.indexOf('<')),
+ name: val.substring(0, val.indexOf("<")),
generics: values.split(/\s*,\s*/),
};
}
@@ -617,9 +647,11 @@
var done = 0;
// We need to find the type that matches the most to remove it in order
// to move forward.
- for (var y = 0; y < val.generics.length; ++y) {
+ var vlength = val.generics.length;
+ for (var y = 0; y < vlength; ++y) {
var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
- for (var x = 0; x < elems.length; ++x) {
+ var elength = elems.length;
+ for (var x = 0; x < elength; ++x) {
var tmp_lev = levenshtein(elems[x], val.generics[y]);
if (tmp_lev < lev.lev) {
lev.lev = tmp_lev;
@@ -644,6 +676,7 @@
// Check for type name and type generics (if any).
function checkType(obj, val, literalSearch) {
var lev_distance = MAX_LEV_DISTANCE + 1;
+ var x;
if (obj[NAME] === val.name) {
if (literalSearch === true) {
if (val.generics && val.generics.length !== 0) {
@@ -651,7 +684,6 @@
obj[GENERICS_DATA].length >= val.generics.length) {
var elems = obj[GENERICS_DATA].slice(0);
var allFound = true;
- var x;
for (var y = 0; allFound === true && y < val.generics.length; ++y) {
allFound = false;
@@ -685,7 +717,8 @@
// Names didn't match so let's check if one of the generic types could.
if (literalSearch === true) {
if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
- for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
+ var length = obj[GENERICS_DATA].length;
+ for (x = 0; x < length; ++x) {
if (obj[GENERICS_DATA][x] === val.name) {
return true;
}
@@ -693,13 +726,13 @@
}
return false;
}
- var lev_distance = Math.min(levenshtein(obj[NAME], val.name),
- lev_distance);
+ lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
if (lev_distance <= MAX_LEV_DISTANCE) {
lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
} else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
// We can check if the type we're looking for is inside the generics!
- for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
+ var olength = obj[GENERICS_DATA].length;
+ for (x = 0; x < olength; ++x) {
lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
lev_distance);
}
@@ -714,7 +747,8 @@
if (obj && obj.type && obj.type[INPUTS_DATA] &&
obj.type[INPUTS_DATA].length > 0) {
- for (var i = 0; i < obj.type[INPUTS_DATA].length; i++) {
+ var length = obj.type[INPUTS_DATA].length;
+ for (var i = 0; i < length; i++) {
var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
if (literalSearch === true && tmp === true) {
return true;
@@ -755,16 +789,18 @@
path.push(ty.parent.name.toLowerCase());
}
- if (contains.length > path.length) {
+ var length = path.length;
+ var clength = contains.length;
+ if (clength > length) {
return MAX_LEV_DISTANCE + 1;
}
- for (var i = 0; i < path.length; ++i) {
- if (i + contains.length > path.length) {
+ for (var i = 0; i < length; ++i) {
+ if (i + clength > length) {
break;
}
var lev_total = 0;
var aborted = false;
- for (var x = 0; x < contains.length; ++x) {
+ for (var x = 0; x < clength; ++x) {
var lev = levenshtein(path[i + x], contains[x]);
if (lev > MAX_LEV_DISTANCE) {
aborted = true;
@@ -773,7 +809,7 @@
lev_total += lev;
}
if (aborted === false) {
- ret_lev = Math.min(ret_lev, Math.round(lev_total / contains.length));
+ ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
}
}
return ret_lev;
@@ -810,18 +846,23 @@
// quoted values mean literal search
var nSearchWords = searchWords.length;
+ var i;
+ var ty;
+ var fullId;
+ var returned;
+ var in_args;
if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
val.charAt(val.length - 1) === val.charAt(0))
{
val = extractGenerics(val.substr(1, val.length - 2));
- for (var i = 0; i < nSearchWords; ++i) {
+ for (i = 0; i < nSearchWords; ++i) {
if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
continue;
}
- var in_args = findArg(searchIndex[i], val, true);
- var returned = checkReturned(searchIndex[i], val, true);
- var ty = searchIndex[i];
- var fullId = generateId(ty);
+ in_args = findArg(searchIndex[i], val, true);
+ returned = checkReturned(searchIndex[i], val, true);
+ ty = searchIndex[i];
+ fullId = generateId(ty);
if (searchWords[i] === val.name) {
// filter type: ... queries
@@ -866,27 +907,27 @@
var input = parts[0];
// sort inputs so that order does not matter
var inputs = input.split(",").map(trimmer).sort();
- for (var i = 0; i < inputs.length; ++i) {
+ for (i = 0; i < inputs.length; ++i) {
inputs[i] = extractGenerics(inputs[i]);
}
var output = extractGenerics(parts[1]);
- for (var i = 0; i < nSearchWords; ++i) {
+ for (i = 0; i < nSearchWords; ++i) {
if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
continue;
}
var type = searchIndex[i].type;
- var ty = searchIndex[i];
+ ty = searchIndex[i];
if (!type) {
continue;
}
- var fullId = generateId(ty);
+ fullId = generateId(ty);
// allow searching for void (no output) functions as well
var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
- var returned = checkReturned(ty, output, true);
+ returned = checkReturned(ty, output, true);
if (output.name === "*" || returned === true) {
- var in_args = false;
+ in_args = false;
var module = false;
if (input === "*") {
@@ -946,14 +987,16 @@
var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
for (j = 0; j < nSearchWords; ++j) {
- var ty = searchIndex[j];
+ var lev;
+ var lev_distance;
+ ty = searchIndex[j];
if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
continue;
}
var lev_distance;
var lev_add = 0;
if (paths.length > 1) {
- var lev = checkPath(contains, paths[paths.length - 1], ty);
+ lev = checkPath(contains, paths[paths.length - 1], ty);
if (lev > MAX_LEV_DISTANCE) {
continue;
} else if (lev > 0) {
@@ -961,12 +1004,12 @@
}
}
- var returned = MAX_LEV_DISTANCE + 1;
- var in_args = MAX_LEV_DISTANCE + 1;
+ returned = MAX_LEV_DISTANCE + 1;
+ in_args = MAX_LEV_DISTANCE + 1;
var index = -1;
// we want lev results to go lower than others
- var lev = MAX_LEV_DISTANCE + 1;
- var fullId = generateId(ty);
+ lev = MAX_LEV_DISTANCE + 1;
+ fullId = generateId(ty);
if (searchWords[j].indexOf(split[i]) > -1 ||
searchWords[j].indexOf(val) > -1 ||
@@ -1042,14 +1085,14 @@
}
var ret = {
- 'in_args': sortResults(results_in_args, true),
- 'returned': sortResults(results_returned, true),
- 'others': sortResults(results),
+ "in_args": sortResults(results_in_args, true),
+ "returned": sortResults(results_returned, true),
+ "others": sortResults(results),
};
if (ALIASES && ALIASES[window.currentCrate] &&
ALIASES[window.currentCrate][query.raw]) {
var aliases = ALIASES[window.currentCrate][query.raw];
- for (var i = 0; i < aliases.length; ++i) {
+ for (i = 0; i < aliases.length; ++i) {
aliases[i].is_alias = true;
aliases[i].alias = query.raw;
aliases[i].path = aliases[i].p;
@@ -1057,9 +1100,9 @@
aliases[i].displayPath = pathSplitter(res[0]);
aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
aliases[i].href = res[1];
- ret['others'].unshift(aliases[i]);
- if (ret['others'].length > MAX_RESULTS) {
- ret['others'].pop();
+ ret.others.unshift(aliases[i]);
+ if (ret.others.length > MAX_RESULTS) {
+ ret.others.pop();
}
}
}
@@ -1106,7 +1149,7 @@
matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
if (matches) {
- type = matches[1].replace(/^const$/, 'constant');
+ type = matches[1].replace(/^const$/, "constant");
query = query.substring(matches[0].length);
}
@@ -1124,38 +1167,38 @@
var click_func = function(e) {
var el = e.target;
// to retrieve the real "owner" of the event.
- while (el.tagName !== 'TR') {
+ while (el.tagName !== "TR") {
el = el.parentNode;
}
- var dst = e.target.getElementsByTagName('a');
+ var dst = e.target.getElementsByTagName("a");
if (dst.length < 1) {
return;
}
dst = dst[0];
if (window.location.pathname === dst.pathname) {
- addClass(document.getElementById('search'), 'hidden');
- removeClass(document.getElementById('main'), 'hidden');
+ addClass(document.getElementById("search"), "hidden");
+ removeClass(main, "hidden");
document.location.href = dst.href;
}
};
var mouseover_func = function(e) {
var el = e.target;
// to retrieve the real "owner" of the event.
- while (el.tagName !== 'TR') {
+ while (el.tagName !== "TR") {
el = el.parentNode;
}
clearTimeout(hoverTimeout);
hoverTimeout = setTimeout(function() {
- onEach(document.getElementsByClassName('search-results'), function(e) {
- onEach(e.getElementsByClassName('result'), function(i_e) {
- removeClass(i_e, 'highlighted');
+ onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+ onEachLazy(e.getElementsByClassName("result"), function(i_e) {
+ removeClass(i_e, "highlighted");
});
});
- addClass(el, 'highlighted');
+ addClass(el, "highlighted");
}, 20);
};
- onEach(document.getElementsByClassName('search-results'), function(e) {
- onEach(e.getElementsByClassName('result'), function(i_e) {
+ onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+ onEachLazy(e.getElementsByClassName("result"), function(i_e) {
i_e.onclick = click_func;
i_e.onmouseover = mouseover_func;
});
@@ -1167,8 +1210,8 @@
var actives = [[], [], []];
// "current" is used to know which tab we're looking into.
var current = 0;
- onEach(document.getElementsByClassName('search-results'), function(e) {
- onEach(e.getElementsByClassName('highlighted'), function(e) {
+ onEachLazy(document.getElementsByClassName("search-results"), function(e) {
+ onEachLazy(e.getElementsByClassName("highlighted"), function(e) {
actives[current].push(e);
});
current += 1;
@@ -1180,25 +1223,25 @@
return;
}
- addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
- removeClass(actives[currentTab][0], 'highlighted');
+ addClass(actives[currentTab][0].previousElementSibling, "highlighted");
+ removeClass(actives[currentTab][0], "highlighted");
} else if (e.which === 40) { // down
if (!actives[currentTab].length) {
- var results = document.getElementsByClassName('search-results');
+ var results = document.getElementsByClassName("search-results");
if (results.length > 0) {
- var res = results[currentTab].getElementsByClassName('result');
+ var res = results[currentTab].getElementsByClassName("result");
if (res.length > 0) {
- addClass(res[0], 'highlighted');
+ addClass(res[0], "highlighted");
}
}
} else if (actives[currentTab][0].nextElementSibling) {
- addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
- removeClass(actives[currentTab][0], 'highlighted');
+ addClass(actives[currentTab][0].nextElementSibling, "highlighted");
+ removeClass(actives[currentTab][0], "highlighted");
}
} else if (e.which === 13) { // return
if (actives[currentTab].length) {
document.location.href =
- actives[currentTab][0].getElementsByTagName('a')[0].href;
+ actives[currentTab][0].getElementsByTagName("a")[0].href;
}
} else if (e.which === 9) { // tab
if (e.shiftKey) {
@@ -1210,11 +1253,11 @@
} else if (e.which === 16) { // shift
// Does nothing, it's just to avoid losing "focus" on the highlighted element.
} else if (e.which === 27) { // escape
- removeClass(actives[currentTab][0], 'highlighted');
- search_input.value = '';
+ removeClass(actives[currentTab][0], "highlighted");
+ search_input.value = "";
defocusSearchBar();
} else if (actives[currentTab].length > 0) {
- removeClass(actives[currentTab][0], 'highlighted');
+ removeClass(actives[currentTab][0], "highlighted");
}
};
}
@@ -1225,46 +1268,46 @@
var type = itemTypes[item.ty];
var name = item.name;
- if (type === 'mod') {
- displayPath = item.path + '::';
- href = rootPath + item.path.replace(/::/g, '/') + '/' +
- name + '/index.html';
+ if (type === "mod") {
+ displayPath = item.path + "::";
+ href = rootPath + item.path.replace(/::/g, "/") + "/" +
+ name + "/index.html";
} else if (type === "primitive" || type === "keyword") {
displayPath = "";
- href = rootPath + item.path.replace(/::/g, '/') +
- '/' + type + '.' + name + '.html';
+ href = rootPath + item.path.replace(/::/g, "/") +
+ "/" + type + "." + name + ".html";
} else if (type === "externcrate") {
displayPath = "";
- href = rootPath + name + '/index.html';
+ href = rootPath + name + "/index.html";
} else if (item.parent !== undefined) {
var myparent = item.parent;
- var anchor = '#' + type + '.' + name;
+ var anchor = "#" + type + "." + name;
var parentType = itemTypes[myparent.ty];
if (parentType === "primitive") {
- displayPath = myparent.name + '::';
+ displayPath = myparent.name + "::";
} else {
- displayPath = item.path + '::' + myparent.name + '::';
+ displayPath = item.path + "::" + myparent.name + "::";
}
- href = rootPath + item.path.replace(/::/g, '/') +
- '/' + parentType +
- '.' + myparent.name +
- '.html' + anchor;
+ href = rootPath + item.path.replace(/::/g, "/") +
+ "/" + parentType +
+ "." + myparent.name +
+ ".html" + anchor;
} else {
- displayPath = item.path + '::';
- href = rootPath + item.path.replace(/::/g, '/') +
- '/' + type + '.' + name + '.html';
+ displayPath = item.path + "::";
+ href = rootPath + item.path.replace(/::/g, "/") +
+ "/" + type + "." + name + ".html";
}
return [displayPath, href];
}
function escape(content) {
- var h1 = document.createElement('h1');
+ var h1 = document.createElement("h1");
h1.textContent = content;
return h1.innerHTML;
}
function pathSplitter(path) {
- var tmp = '<span>' + path.replace(/::/g, '::</span><span>');
+ var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
if (tmp.endsWith("<span>")) {
return tmp.slice(0, tmp.length - 6);
}
@@ -1272,16 +1315,16 @@
}
function addTab(array, query, display) {
- var extraStyle = '';
+ var extraStyle = "";
if (display === false) {
- extraStyle = ' style="display: none;"';
+ extraStyle = " style=\"display: none;\"";
}
- var output = '';
+ var output = "";
var duplicates = {};
var length = 0;
if (array.length > 0) {
- output = '<table class="search-results"' + extraStyle + '>';
+ output = "<table class=\"search-results\"" + extraStyle + ">";
array.forEach(function(item) {
var name, type;
@@ -1297,50 +1340,50 @@
}
length += 1;
- output += '<tr class="' + type + ' result"><td>' +
- '<a href="' + item.href + '">' +
+ output += "<tr class=\"" + type + " result\"><td>" +
+ "<a href=\"" + item.href + "\">" +
(item.is_alias === true ?
- ('<span class="alias"><b>' + item.alias + ' </b></span><span ' +
- 'class="grey"><i> - see </i></span>') : '') +
- item.displayPath + '<span class="' + type + '">' +
- name + '</span></a></td><td>' +
- '<a href="' + item.href + '">' +
- '<span class="desc">' + escape(item.desc) +
- ' </span></a></td></tr>';
+ ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
+ "class=\"grey\"><i> - see </i></span>") : "") +
+ item.displayPath + "<span class=\"" + type + "\">" +
+ name + "</span></a></td><td>" +
+ "<a href=\"" + item.href + "\">" +
+ "<span class=\"desc\">" + escape(item.desc) +
+ " </span></a></td></tr>";
});
- output += '</table>';
+ output += "</table>";
} else {
- output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
- 'Try on <a href="https://duckduckgo.com/?q=' +
- encodeURIComponent('rust ' + query.query) +
- '">DuckDuckGo</a>?<br/><br/>' +
- 'Or try looking in one of these:<ul><li>The <a ' +
- 'href="https://doc.rust-lang.org/reference/index.html">Rust Reference</a> for' +
- ' technical details about the language.</li><li><a ' +
- 'href="https://doc.rust-lang.org/rust-by-example/index.html">Rust By Example' +
- '</a> for expository code examples.</a></li><li>The <a ' +
- 'href="https://doc.rust-lang.org/book/index.html">Rust Book</a> for ' +
- 'introductions to language features and the language itself.</li><li><a ' +
- 'href="https://docs.rs">Docs.rs</a> for documentation of crates released on ' +
- '<a href="https://crates.io/">crates.io</a>.</li></ul></div>';
+ output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
+ "Try on <a href=\"https://duckduckgo.com/?q=" +
+ encodeURIComponent("rust " + query.query) +
+ "\">DuckDuckGo</a>?<br/><br/>" +
+ "Or try looking in one of these:<ul><li>The <a " +
+ "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
+ " for technical details about the language.</li><li><a " +
+ "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
+ "Example</a> for expository code examples.</a></li><li>The <a " +
+ "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
+ "introductions to language features and the language itself.</li><li><a " +
+ "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
+ " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
}
return [output, length];
}
function makeTabHeader(tabNb, text, nbElems) {
if (currentTab === tabNb) {
- return '<div class="selected">' + text +
- ' <div class="count">(' + nbElems + ')</div></div>';
+ return "<div class=\"selected\">" + text +
+ " <div class=\"count\">(" + nbElems + ")</div></div>";
}
- return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
+ return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
}
- function showResults(results, filterCrates) {
- if (results['others'].length === 1 &&
- getCurrentValue('rustdoc-go-to-only-result') === "true") {
- var elem = document.createElement('a');
- elem.href = results['others'][0].href;
- elem.style.display = 'none';
+ function showResults(results) {
+ if (results.others.length === 1 &&
+ getCurrentValue("rustdoc-go-to-only-result") === "true") {
+ var elem = document.createElement("a");
+ elem.href = results.others[0].href;
+ elem.style.display = "none";
// For firefox, we need the element to be in the DOM so it can be clicked.
document.body.appendChild(elem);
elem.click();
@@ -1349,39 +1392,34 @@
currentResults = query.id;
- var ret_others = addTab(results['others'], query);
- var ret_in_args = addTab(results['in_args'], query, false);
- var ret_returned = addTab(results['returned'], query, false);
+ var ret_others = addTab(results.others, query);
+ var ret_in_args = addTab(results.in_args, query, false);
+ var ret_returned = addTab(results.returned, query, false);
- var filter = "";
- if (filterCrates !== undefined) {
- filter = " (in <b>" + filterCrates + "</b> crate)";
- }
-
- var output = '<h1>Results for ' + escape(query.query) +
- (query.type ? ' (type: ' + escape(query.type) + ')' : '') + filter + '</h1>' +
- '<div id="titles">' +
+ var output = "<h1>Results for " + escape(query.query) +
+ (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
+ "<div id=\"titles\">" +
makeTabHeader(0, "In Names", ret_others[1]) +
makeTabHeader(1, "In Parameters", ret_in_args[1]) +
makeTabHeader(2, "In Return Types", ret_returned[1]) +
- '</div><div id="results">' +
- ret_others[0] + ret_in_args[0] + ret_returned[0] + '</div>';
+ "</div><div id=\"results\">" +
+ ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
- addClass(document.getElementById('main'), 'hidden');
- var search = document.getElementById('search');
- removeClass(search, 'hidden');
+ addClass(main, "hidden");
+ var search = document.getElementById("search");
+ removeClass(search, "hidden");
search.innerHTML = output;
- var tds = search.getElementsByTagName('td');
+ var tds = search.getElementsByTagName("td");
var td_width = 0;
if (tds.length > 0) {
td_width = tds[0].offsetWidth;
}
var width = search.offsetWidth - 40 - td_width;
- onEach(search.getElementsByClassName('desc'), function(e) {
- e.style.width = width + 'px';
+ onEachLazy(search.getElementsByClassName("desc"), function(e) {
+ e.style.width = width + "px";
});
initSearchNav();
- var elems = document.getElementById('titles').childNodes;
+ var elems = document.getElementById("titles").childNodes;
elems[0].onclick = function() { printTab(0); };
elems[1].onclick = function() { printTab(1); };
elems[2].onclick = function() { printTab(2); };
@@ -1389,74 +1427,74 @@
}
function execSearch(query, searchWords, filterCrates) {
+ function getSmallest(arrays, positions, notDuplicates) {
+ var start = null;
+
+ for (var it = 0; it < positions.length; ++it) {
+ if (arrays[it].length > positions[it] &&
+ (start === null || start > arrays[it][positions[it]].lev) &&
+ !notDuplicates[arrays[it][positions[it]].fullPath]) {
+ start = arrays[it][positions[it]].lev;
+ }
+ }
+ return start;
+ }
+
+ function mergeArrays(arrays) {
+ var ret = [];
+ var positions = [];
+ var notDuplicates = {};
+
+ for (var x = 0; x < arrays.length; ++x) {
+ positions.push(0);
+ }
+ while (ret.length < MAX_RESULTS) {
+ var smallest = getSmallest(arrays, positions, notDuplicates);
+
+ if (smallest === null) {
+ break;
+ }
+ for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
+ if (arrays[x].length > positions[x] &&
+ arrays[x][positions[x]].lev === smallest &&
+ !notDuplicates[arrays[x][positions[x]].fullPath]) {
+ ret.push(arrays[x][positions[x]]);
+ notDuplicates[arrays[x][positions[x]].fullPath] = true;
+ positions[x] += 1;
+ }
+ }
+ }
+ return ret;
+ }
+
var queries = query.raw.split(",");
var results = {
- 'in_args': [],
- 'returned': [],
- 'others': [],
+ "in_args": [],
+ "returned": [],
+ "others": [],
};
for (var i = 0; i < queries.length; ++i) {
- var query = queries[i].trim();
+ query = queries[i].trim();
if (query.length !== 0) {
var tmp = execQuery(getQuery(query), searchWords, filterCrates);
- results['in_args'].push(tmp['in_args']);
- results['returned'].push(tmp['returned']);
- results['others'].push(tmp['others']);
+ results.in_args.push(tmp.in_args);
+ results.returned.push(tmp.returned);
+ results.others.push(tmp.others);
}
}
if (queries.length > 1) {
- function getSmallest(arrays, positions, notDuplicates) {
- var start = null;
-
- for (var it = 0; it < positions.length; ++it) {
- if (arrays[it].length > positions[it] &&
- (start === null || start > arrays[it][positions[it]].lev) &&
- !notDuplicates[arrays[it][positions[it]].fullPath]) {
- start = arrays[it][positions[it]].lev;
- }
- }
- return start;
- }
-
- function mergeArrays(arrays) {
- var ret = [];
- var positions = [];
- var notDuplicates = {};
-
- for (var x = 0; x < arrays.length; ++x) {
- positions.push(0);
- }
- while (ret.length < MAX_RESULTS) {
- var smallest = getSmallest(arrays, positions, notDuplicates);
-
- if (smallest === null) {
- break;
- }
- for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
- if (arrays[x].length > positions[x] &&
- arrays[x][positions[x]].lev === smallest &&
- !notDuplicates[arrays[x][positions[x]].fullPath]) {
- ret.push(arrays[x][positions[x]]);
- notDuplicates[arrays[x][positions[x]].fullPath] = true;
- positions[x] += 1;
- }
- }
- }
- return ret;
- }
-
return {
- 'in_args': mergeArrays(results['in_args']),
- 'returned': mergeArrays(results['returned']),
- 'others': mergeArrays(results['others']),
+ "in_args": mergeArrays(results.in_args),
+ "returned": mergeArrays(results.returned),
+ "others": mergeArrays(results.others),
};
} else {
return {
- 'in_args': results['in_args'][0],
- 'returned': results['returned'][0],
- 'others': results['others'][0],
+ "in_args": results.in_args[0],
+ "returned": results.returned[0],
+ "others": results.others[0],
};
}
}
@@ -1508,6 +1546,8 @@
function buildIndex(rawSearchIndex) {
searchIndex = [];
var searchWords = [];
+ var i;
+
for (var crate in rawSearchIndex) {
if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
@@ -1534,7 +1574,7 @@
// convert `paths` into an object form
var len = paths.length;
- for (var i = 0; i < len; ++i) {
+ for (i = 0; i < len; ++i) {
paths[i] = {ty: paths[i][0], name: paths[i][1]};
}
@@ -1545,9 +1585,9 @@
// operation that is cached for the life of the page state so that
// all other search operations have access to this cached data for
// faster analysis operations
- var len = items.length;
+ len = items.length;
var lastPath = "";
- for (var i = 0; i < len; ++i) {
+ for (i = 0; i < len; ++i) {
var rawRow = items[i];
var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
path: rawRow[2] || lastPath, desc: rawRow[3],
@@ -1573,13 +1613,12 @@
if (browserSupportsHistoryApi()) {
history.replaceState("", "std - Rust", "?search=");
}
- var main = document.getElementById('main');
- if (hasClass(main, 'content')) {
- removeClass(main, 'hidden');
+ if (hasClass(main, "content")) {
+ removeClass(main, "hidden");
}
- var search_c = document.getElementById('search');
- if (hasClass(search_c, 'content')) {
- addClass(search_c, 'hidden');
+ var search_c = document.getElementById("search");
+ if (hasClass(search_c, "content")) {
+ addClass(search_c, "hidden");
}
} else {
searchTimeout = setTimeout(search, 500);
@@ -1620,13 +1659,12 @@
// When browsing back from search results the main page
// visibility must be reset.
if (!params.search) {
- var main = document.getElementById('main');
- if (hasClass(main, 'content')) {
- removeClass(main, 'hidden');
+ if (hasClass(main, "content")) {
+ removeClass(main, "hidden");
}
- var search_c = document.getElementById('search');
- if (hasClass(search_c, 'content')) {
- addClass(search_c, 'hidden');
+ var search_c = document.getElementById("search");
+ if (hasClass(search_c, "content")) {
+ addClass(search_c, "hidden");
}
}
// Revert to the previous title manually since the History
@@ -1643,9 +1681,9 @@
if (params.search) {
search_input.value = params.search;
} else {
- search_input.value = '';
+ search_input.value = "";
}
- // Some browsers fire 'onpopstate' for every page load
+ // Some browsers fire "onpopstate" for every page load
// (Chrome), while others fire the event only when actually
// popping a state (Firefox), which is why search() is
// called both here and at the end of the startSearch()
@@ -1660,13 +1698,13 @@
startSearch();
// Draw a convenient sidebar of known crates if we have a listing
- if (rootPath === '../' || rootPath === "./") {
- var sidebar = document.getElementsByClassName('sidebar-elems')[0];
+ if (rootPath === "../" || rootPath === "./") {
+ var sidebar = document.getElementsByClassName("sidebar-elems")[0];
if (sidebar) {
- var div = document.createElement('div');
- div.className = 'block crate';
- div.innerHTML = '<h3>Crates</h3>';
- var ul = document.createElement('ul');
+ var div = document.createElement("div");
+ div.className = "block crate";
+ div.innerHTML = "<h3>Crates</h3>";
+ var ul = document.createElement("ul");
div.appendChild(ul);
var crates = [];
@@ -1678,17 +1716,17 @@
}
crates.sort();
for (var i = 0; i < crates.length; ++i) {
- var klass = 'crate';
+ var klass = "crate";
if (rootPath !== "./" && crates[i] === window.currentCrate) {
- klass += ' current';
+ klass += " current";
}
- var link = document.createElement('a');
- link.href = rootPath + crates[i] + '/index.html';
+ var link = document.createElement("a");
+ link.href = rootPath + crates[i] + "/index.html";
link.title = rawSearchIndex[crates[i]].doc;
link.className = klass;
link.textContent = crates[i];
- var li = document.createElement('li');
+ var li = document.createElement("li");
li.appendChild(link);
ul.appendChild(li);
}
@@ -1701,41 +1739,44 @@
// delayed sidebar rendering.
function initSidebarItems(items) {
- var sidebar = document.getElementsByClassName('sidebar-elems')[0];
+ var sidebar = document.getElementsByClassName("sidebar-elems")[0];
var current = window.sidebarCurrent;
function block(shortty, longty) {
var filtered = items[shortty];
- if (!filtered) { return; }
+ if (!filtered) {
+ return;
+ }
- var div = document.createElement('div');
- div.className = 'block ' + shortty;
- var h3 = document.createElement('h3');
+ var div = document.createElement("div");
+ div.className = "block " + shortty;
+ var h3 = document.createElement("h3");
h3.textContent = longty;
div.appendChild(h3);
- var ul = document.createElement('ul');
+ var ul = document.createElement("ul");
- for (var i = 0; i < filtered.length; ++i) {
+ var length = filtered.length;
+ for (var i = 0; i < length; ++i) {
var item = filtered[i];
var name = item[0];
var desc = item[1]; // can be null
var klass = shortty;
if (name === current.name && shortty === current.ty) {
- klass += ' current';
+ klass += " current";
}
var path;
- if (shortty === 'mod') {
- path = name + '/index.html';
+ if (shortty === "mod") {
+ path = name + "/index.html";
} else {
- path = shortty + '.' + name + '.html';
+ path = shortty + "." + name + ".html";
}
- var link = document.createElement('a');
+ var link = document.createElement("a");
link.href = current.relpath + path;
link.title = desc;
link.className = klass;
link.textContent = name;
- var li = document.createElement('li');
+ var li = document.createElement("li");
li.appendChild(link);
ul.appendChild(li);
}
@@ -1763,22 +1804,25 @@
window.initSidebarItems = initSidebarItems;
window.register_implementors = function(imp) {
- var implementors = document.getElementById('implementors-list');
- var synthetic_implementors = document.getElementById('synthetic-implementors-list');
+ var implementors = document.getElementById("implementors-list");
+ var synthetic_implementors = document.getElementById("synthetic-implementors-list");
var libs = Object.getOwnPropertyNames(imp);
- for (var i = 0; i < libs.length; ++i) {
+ var llength = libs.length;
+ for (var i = 0; i < llength; ++i) {
if (libs[i] === currentCrate) { continue; }
var structs = imp[libs[i]];
+ var slength = structs.length;
struct_loop:
- for (var j = 0; j < structs.length; ++j) {
+ for (var j = 0; j < slength; ++j) {
var struct = structs[j];
var list = struct.synthetic ? synthetic_implementors : implementors;
if (struct.synthetic) {
- for (var k = 0; k < struct.types.length; k++) {
+ var stlength = struct.types.length;
+ for (var k = 0; k < stlength; k++) {
if (window.inlined_types.has(struct.types[k])) {
continue struct_loop;
}
@@ -1786,21 +1830,22 @@
}
}
- var code = document.createElement('code');
+ var code = document.createElement("code");
code.innerHTML = struct.text;
- var x = code.getElementsByTagName('a');
- for (var k = 0; k < x.length; k++) {
- var href = x[k].getAttribute('href');
- if (href && href.indexOf('http') !== 0) {
- x[k].setAttribute('href', rootPath + href);
+ var x = code.getElementsByTagName("a");
+ var xlength = x.length;
+ for (var it = 0; it < xlength; it++) {
+ var href = x[it].getAttribute("href");
+ if (href && href.indexOf("http") !== 0) {
+ x[it].setAttribute("href", rootPath + href);
}
}
- var display = document.createElement('h3');
+ var display = document.createElement("h3");
addClass(display, "impl");
- display.innerHTML = '<span class="in-band"><table class="table-display"><tbody>\
- <tr><td><code>' + code.outerHTML + '</code></td><td></td></tr></tbody></table>\
- </span>';
+ display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
+ "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
+ "</tbody></table></span>";
list.appendChild(display);
}
}
@@ -1816,47 +1861,49 @@
}
// button will collapse the section
// note that this text is also set in the HTML template in render.rs
- return "\u2212"; // "\u2212" is '−' minus sign
+ return "\u2212"; // "\u2212" is "−" minus sign
}
function onEveryMatchingChild(elem, className, func) {
if (elem && className && func) {
- for (var i = 0; i < elem.childNodes.length; i++) {
- if (hasClass(elem.childNodes[i], className)) {
- func(elem.childNodes[i]);
+ var length = elem.childNodes.length;
+ var nodes = elem.childNodes;
+ for (var i = 0; i < length; ++i) {
+ if (hasClass(nodes[i], className)) {
+ func(nodes[i]);
} else {
- onEveryMatchingChild(elem.childNodes[i], className, func);
+ onEveryMatchingChild(nodes[i], className, func);
}
}
}
}
function toggleAllDocs(pageId, fromAutoCollapse) {
- var toggle = document.getElementById("toggle-all-docs");
- if (!toggle) {
+ var innerToggle = document.getElementById("toggle-all-docs");
+ if (!innerToggle) {
return;
}
- if (hasClass(toggle, "will-expand")) {
+ if (hasClass(innerToggle, "will-expand")) {
updateLocalStorage("rustdoc-collapse", "false");
- removeClass(toggle, "will-expand");
- onEveryMatchingChild(toggle, "inner", function(e) {
+ removeClass(innerToggle, "will-expand");
+ onEveryMatchingChild(innerToggle, "inner", function(e) {
e.innerHTML = labelForToggleButton(false);
});
- toggle.title = "collapse all docs";
+ innerToggle.title = "collapse all docs";
if (fromAutoCollapse !== true) {
- onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+ onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
collapseDocs(e, "show");
});
}
} else {
updateLocalStorage("rustdoc-collapse", "true");
- addClass(toggle, "will-expand");
- onEveryMatchingChild(toggle, "inner", function(e) {
+ addClass(innerToggle, "will-expand");
+ onEveryMatchingChild(innerToggle, "inner", function(e) {
e.innerHTML = labelForToggleButton(true);
});
- toggle.title = "expand all docs";
+ innerToggle.title = "expand all docs";
if (fromAutoCollapse !== true) {
- onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
+ onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
collapseDocs(e, "hide", pageId);
});
}
@@ -1870,27 +1917,58 @@
function adjustToggle(arg) {
return function(e) {
- if (hasClass(e, 'toggle-label')) {
+ if (hasClass(e, "toggle-label")) {
if (arg) {
- e.style.display = 'inline-block';
+ e.style.display = "inline-block";
} else {
- e.style.display = 'none';
+ e.style.display = "none";
}
}
- if (hasClass(e, 'inner')) {
+ if (hasClass(e, "inner")) {
e.innerHTML = labelForToggleButton(arg);
}
};
- };
+ }
- if (!hasClass(toggle.parentNode, "impl")) {
- var relatedDoc = toggle.parentNode.nextElementSibling;
+ function implHider(addOrRemove) {
+ return function(n) {
+ var is_method = hasClass(n, "method");
+ if (is_method || hasClass(n, "type")) {
+ if (is_method === true) {
+ if (addOrRemove) {
+ addClass(n, "hidden-by-impl-hider");
+ } else {
+ removeClass(n, "hidden-by-impl-hider");
+ }
+ }
+ var ns = n.nextElementSibling;
+ while (true) {
+ if (ns && (
+ hasClass(ns, "docblock") ||
+ hasClass(ns, "stability"))) {
+ if (addOrRemove) {
+ addClass(ns, "hidden-by-impl-hider");
+ } else {
+ removeClass(ns, "hidden-by-impl-hider");
+ }
+ ns = ns.nextElementSibling;
+ continue;
+ }
+ break;
+ }
+ }
+ };
+ }
+
+ var relatedDoc;
+ var action = mode;
+ if (hasClass(toggle.parentNode, "impl") === false) {
+ relatedDoc = toggle.parentNode.nextElementSibling;
if (hasClass(relatedDoc, "stability")) {
relatedDoc = relatedDoc.nextElementSibling;
}
if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
- var action = mode;
- if (action === "toggle") {
+ if (mode === "toggle") {
if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
action = "show";
} else {
@@ -1899,67 +1977,35 @@
}
if (action === "hide") {
addClass(relatedDoc, "hidden-by-usual-hider");
- onEach(toggle.childNodes, adjustToggle(true));
- addClass(toggle.parentNode, 'collapsed');
+ onEachLazy(toggle.childNodes, adjustToggle(true));
+ addClass(toggle.parentNode, "collapsed");
} else if (action === "show") {
removeClass(relatedDoc, "hidden-by-usual-hider");
- removeClass(toggle.parentNode, 'collapsed');
- onEach(toggle.childNodes, adjustToggle(false));
+ removeClass(toggle.parentNode, "collapsed");
+ onEachLazy(toggle.childNodes, adjustToggle(false));
}
}
} else {
// we are collapsing the impl block
- function implHider(addOrRemove) {
- return function(n) {
- var is_method = hasClass(n, "method");
- if (is_method || hasClass(n, "type")) {
- if (is_method === true) {
- if (addOrRemove) {
- addClass(n, "hidden-by-impl-hider");
- } else {
- removeClass(n, "hidden-by-impl-hider");
- }
- }
- var ns = n.nextElementSibling;
- while (true) {
- if (ns && (
- hasClass(ns, "docblock") ||
- hasClass(ns, "stability"))) {
- if (addOrRemove) {
- addClass(ns, "hidden-by-impl-hider");
- } else {
- removeClass(ns, "hidden-by-impl-hider");
- }
- ns = ns.nextElementSibling;
- continue;
- }
- break;
- }
- }
- }
- }
var parentElem = toggle.parentNode;
- var relatedDoc = parentElem;
+ relatedDoc = parentElem;
var docblock = relatedDoc.nextElementSibling;
- while (!hasClass(relatedDoc, "impl-items")) {
+ while (hasClass(relatedDoc, "impl-items") === false) {
relatedDoc = relatedDoc.nextElementSibling;
}
- if ((!relatedDoc && !hasClass(docblock, "docblock")) ||
- (pageId && onEach(relatedDoc.childNodes, function(e) {
- return e.id === pageId;
- }) === true)) {
+ if ((!relatedDoc && hasClass(docblock, "docblock") === false) ||
+ (pageId && document.getElementById(pageId))) {
return;
}
// Hide all functions, but not associated types/consts
- var action = mode;
- if (action === "toggle") {
+ if (mode === "toggle") {
if (hasClass(relatedDoc, "fns-now-collapsed") ||
- hasClass(docblock, "hidden-by-impl-hider")) {
+ hasClass(docblock, "hidden-by-impl-hider")) {
action = "show";
} else {
action = "hide";
@@ -1969,13 +2015,25 @@
if (action === "show") {
removeClass(relatedDoc, "fns-now-collapsed");
removeClass(docblock, "hidden-by-usual-hider");
- onEach(toggle.childNodes, adjustToggle(false));
- onEach(relatedDoc.childNodes, implHider(false));
+ onEachLazy(toggle.childNodes, adjustToggle(false));
+ onEachLazy(relatedDoc.childNodes, implHider(false));
} else if (action === "hide") {
addClass(relatedDoc, "fns-now-collapsed");
addClass(docblock, "hidden-by-usual-hider");
- onEach(toggle.childNodes, adjustToggle(true));
- onEach(relatedDoc.childNodes, implHider(true));
+ onEachLazy(toggle.childNodes, adjustToggle(true));
+ onEachLazy(relatedDoc.childNodes, implHider(true));
+ }
+ }
+ }
+
+ function collapser(e, collapse) {
+ // inherent impl ids are like "impl" or impl-<number>'.
+ // they will never be hidden by default.
+ var n = e.parentElement;
+ if (n.id.match(/^impl(?:-\d+)?$/) === null) {
+ // Automatically minimize all non-inherent impls
+ if (collapse || hasClass(n, "impl")) {
+ collapseDocs(e, "hide", pageId);
}
}
}
@@ -1983,88 +2041,112 @@
function autoCollapse(pageId, collapse) {
if (collapse) {
toggleAllDocs(pageId, true);
- }
- var collapser = function(e) {
- // inherent impl ids are like 'impl' or impl-<number>'.
- // they will never be hidden by default.
- var n = e.parentElement;
- if (n.id.match(/^impl(?:-\d+)?$/) === null) {
- // Automatically minimize all non-inherent impls
- if (collapse || hasClass(n, 'impl')) {
- collapseDocs(e, "hide", pageId);
- }
- }
- };
- if (getCurrentValue('rustdoc-trait-implementations') !== "false") {
- var impl_list = document.getElementById('implementations-list');
+ } else if (getCurrentValue("rustdoc-trait-implementations") !== "false") {
+ var impl_list = document.getElementById("implementations-list");
if (impl_list !== null) {
- onEach(impl_list.getElementsByClassName("collapse-toggle"), collapser);
- }
- }
- if (getCurrentValue('rustdoc-method-docs') !== "false") {
- var implItems = document.getElementsByClassName('impl-items');
-
- if (implItems && implItems.length > 0) {
- onEach(implItems, function(elem) {
- onEach(elem.getElementsByClassName("collapse-toggle"), collapser);
+ onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
+ collapser(e, collapse);
});
}
}
}
- var x = document.getElementById('toggle-all-docs');
- if (x) {
- x.onclick = toggleAllDocs;
+ var toggles = document.getElementById("toggle-all-docs");
+ if (toggles) {
+ toggles.onclick = toggleAllDocs;
}
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
- function checkIfThereAreMethods(elems) {
- var areThereMethods = false;
-
- onEach(elems, function(e) {
- if (hasClass(e, "method")) {
- areThereMethods = true;
- return true;
- }
- });
- return areThereMethods;
+ function createSimpleToggle(sectionIsCollapsed) {
+ var toggle = document.createElement("a");
+ toggle.href = "javascript:void(0)";
+ toggle.className = "collapse-toggle";
+ toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
+ "</span>]";
+ return toggle;
}
- var toggle = document.createElement('a');
- toggle.href = 'javascript:void(0)';
- toggle.className = 'collapse-toggle';
- toggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) + "</span>]";
+ var toggle = createSimpleToggle(false);
var func = function(e) {
var next = e.nextElementSibling;
- if (hasClass(e, 'impl') && next && hasClass(next, 'docblock')) {
+ if (!next) {
+ return;
+ }
+ if (hasClass(next, "docblock") ||
+ (hasClass(next, "stability") &&
+ hasClass(next.nextElementSibling, "docblock"))) {
+ insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
+ }
+ };
+
+ var funcImpl = function(e) {
+ var next = e.nextElementSibling;
+ if (next && hasClass(next, "docblock")) {
next = next.nextElementSibling;
}
if (!next) {
return;
}
- if ((hasClass(e, 'method') || hasClass(e, 'associatedconstant') ||
- checkIfThereAreMethods(next.childNodes)) &&
- (hasClass(next, 'docblock') ||
- hasClass(e, 'impl') ||
- (hasClass(next, 'stability') &&
- hasClass(next.nextElementSibling, 'docblock')))) {
+ if (next.getElementsByClassName("method").length > 0 && hasClass(e, "impl")) {
insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
}
};
- onEach(document.getElementsByClassName('method'), func);
- onEach(document.getElementsByClassName('associatedconstant'), func);
- onEach(document.getElementsByClassName('impl'), func);
- onEach(document.getElementsByClassName('impl-items'), function(e) {
- onEach(e.getElementsByClassName('associatedconstant'), func);
- var hiddenElems = e.getElementsByClassName('hidden');
+
+ onEachLazy(document.getElementsByClassName("method"), func);
+ onEachLazy(document.getElementsByClassName("associatedconstant"), func);
+ onEachLazy(document.getElementsByClassName("impl"), funcImpl);
+ var impl_call = function() {};
+ if (getCurrentValue("rustdoc-method-docs") !== "false") {
+ impl_call = function(e, newToggle, pageId) {
+ if (e.id.match(/^impl(?:-\d+)?$/) === null) {
+ // Automatically minimize all non-inherent impls
+ if (hasClass(e, "impl")) {
+ collapseDocs(newToggle, "hide", pageId);
+ }
+ }
+ };
+ }
+ var pageId = getPageId();
+ var newToggle = document.createElement("a");
+ newToggle.href = "javascript:void(0)";
+ newToggle.className = "collapse-toggle hidden-default collapsed";
+ newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
+ "</span>] Show hidden undocumented items";
+ function toggleClicked() {
+ if (hasClass(this, "collapsed")) {
+ removeClass(this, "collapsed");
+ onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
+ if (hasClass(x, "content") === false) {
+ removeClass(x, "hidden");
+ addClass(x, "x");
+ }
+ }, true);
+ this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
+ "</span>] Hide undocumented items";
+ } else {
+ addClass(this, "collapsed");
+ onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
+ if (hasClass(x, "content") === false) {
+ addClass(x, "hidden");
+ removeClass(x, "x");
+ }
+ }, true);
+ this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
+ "</span>] Show hidden undocumented items";
+ }
+ }
+ onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
+ onEachLazy(e.getElementsByClassName("associatedconstant"), func);
+ var hiddenElems = e.getElementsByClassName("hidden");
var needToggle = false;
- for (var i = 0; i < hiddenElems.length; ++i) {
+ var hlength = hiddenElems.length;
+ for (var i = 0; i < hlength; ++i) {
if (hasClass(hiddenElems[i], "content") === false &&
hasClass(hiddenElems[i], "docblock") === false) {
needToggle = true;
@@ -2072,46 +2154,21 @@
}
}
if (needToggle === true) {
- var newToggle = document.createElement('a');
- newToggle.href = 'javascript:void(0)';
- newToggle.className = 'collapse-toggle hidden-default collapsed';
- newToggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(true) + "</span>" +
- "] Show hidden undocumented items";
- newToggle.onclick = function() {
- if (hasClass(this, "collapsed")) {
- removeClass(this, "collapsed");
- onEach(this.parentNode.getElementsByClassName("hidden"), function(x) {
- if (hasClass(x, "content") === false) {
- removeClass(x, "hidden");
- addClass(x, "x");
- }
- }, true);
- this.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) +
- "</span>] Hide undocumented items"
- } else {
- addClass(this, "collapsed");
- onEach(this.parentNode.getElementsByClassName("x"), function(x) {
- if (hasClass(x, "content") === false) {
- addClass(x, "hidden");
- removeClass(x, "x");
- }
- }, true);
- this.innerHTML = "[<span class='inner'>" + labelForToggleButton(true) +
- "</span>] Show hidden undocumented items";
- }
- };
- e.insertBefore(newToggle, e.firstChild);
+ var inner_toggle = newToggle.cloneNode(true);
+ inner_toggle.onclick = toggleClicked;
+ e.insertBefore(inner_toggle, e.firstChild);
+ impl_call(e, inner_toggle, pageId);
}
});
function createToggle(otherMessage, fontSize, extraClass, show) {
- var span = document.createElement('span');
- span.className = 'toggle-label';
+ var span = document.createElement("span");
+ span.className = "toggle-label";
if (show) {
- span.style.display = 'none';
+ span.style.display = "none";
}
if (!otherMessage) {
- span.innerHTML = ' Expand description';
+ span.innerHTML = " Expand description";
} else {
span.innerHTML = otherMessage;
}
@@ -2123,13 +2180,13 @@
var mainToggle = toggle.cloneNode(true);
mainToggle.appendChild(span);
- var wrapper = document.createElement('div');
- wrapper.className = 'toggle-wrapper';
+ var wrapper = document.createElement("div");
+ wrapper.className = "toggle-wrapper";
if (!show) {
- addClass(wrapper, 'collapsed');
- var inner = mainToggle.getElementsByClassName('inner');
+ addClass(wrapper, "collapsed");
+ var inner = mainToggle.getElementsByClassName("inner");
if (inner && inner.length > 0) {
- inner[0].innerHTML = '+';
+ inner[0].innerHTML = "+";
}
}
if (extraClass) {
@@ -2139,21 +2196,21 @@
return wrapper;
}
- var showItemDeclarations = getCurrentValue('rustdoc-item-declarations') === "false";
+ var showItemDeclarations = getCurrentValue("rustdoc-item-declarations") === "false";
function buildToggleWrapper(e) {
- if (hasClass(e, 'autohide')) {
+ if (hasClass(e, "autohide")) {
var wrap = e.previousElementSibling;
- if (wrap && hasClass(wrap, 'toggle-wrapper')) {
- var toggle = wrap.childNodes[0];
- var extra = e.childNodes[0].tagName === 'H3';
+ if (wrap && hasClass(wrap, "toggle-wrapper")) {
+ var inner_toggle = wrap.childNodes[0];
+ var extra = e.childNodes[0].tagName === "H3";
- e.style.display = 'none';
- addClass(wrap, 'collapsed');
- onEach(toggle.getElementsByClassName('inner'), function(e) {
+ e.style.display = "none";
+ addClass(wrap, "collapsed");
+ onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
e.innerHTML = labelForToggleButton(true);
});
- onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
- e.style.display = 'inline-block';
+ onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
+ e.style.display = "inline-block";
if (extra === true) {
i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
}
@@ -2161,28 +2218,28 @@
}
}
if (e.parentNode.id === "main") {
- var otherMessage = '';
+ var otherMessage = "";
var fontSize;
var extraClass;
if (hasClass(e, "type-decl")) {
fontSize = "20px";
- otherMessage = ' Show declaration';
+ otherMessage = " Show declaration";
if (showItemDeclarations === false) {
- extraClass = 'collapsed';
+ extraClass = "collapsed";
}
} else if (hasClass(e, "sub-variant")) {
- otherMessage = ' Show fields';
+ otherMessage = " Show fields";
} else if (hasClass(e, "non-exhaustive")) {
- otherMessage = ' This ';
+ otherMessage = " This ";
if (hasClass(e, "non-exhaustive-struct")) {
- otherMessage += 'struct';
+ otherMessage += "struct";
} else if (hasClass(e, "non-exhaustive-enum")) {
- otherMessage += 'enum';
+ otherMessage += "enum";
} else if (hasClass(e, "non-exhaustive-type")) {
- otherMessage += 'type';
+ otherMessage += "type";
}
- otherMessage += ' is marked as non-exhaustive';
+ otherMessage += " is marked as non-exhaustive";
} else if (hasClass(e.childNodes[0], "impl-items")) {
extraClass = "marg-left";
}
@@ -2199,21 +2256,8 @@
}
}
- onEach(document.getElementsByClassName('docblock'), buildToggleWrapper);
- onEach(document.getElementsByClassName('sub-variant'), buildToggleWrapper);
-
- function createToggleWrapper(tog) {
- var span = document.createElement('span');
- span.className = 'toggle-label';
- span.style.display = 'none';
- span.innerHTML = ' Expand attributes';
- tog.appendChild(span);
-
- var wrapper = document.createElement('div');
- wrapper.className = 'toggle-wrapper toggle-attributes';
- wrapper.appendChild(tog);
- return wrapper;
- }
+ onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
+ onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
// In the search display, allows to switch between tabs.
function printTab(nb) {
@@ -2221,24 +2265,37 @@
currentTab = nb;
}
var nb_copy = nb;
- onEach(document.getElementById('titles').childNodes, function(elem) {
+ onEachLazy(document.getElementById("titles").childNodes, function(elem) {
if (nb_copy === 0) {
- addClass(elem, 'selected');
+ addClass(elem, "selected");
} else {
- removeClass(elem, 'selected');
+ removeClass(elem, "selected");
}
nb_copy -= 1;
});
- onEach(document.getElementById('results').childNodes, function(elem) {
+ onEachLazy(document.getElementById("results").childNodes, function(elem) {
if (nb === 0) {
- elem.style.display = '';
+ elem.style.display = "";
} else {
- elem.style.display = 'none';
+ elem.style.display = "none";
}
nb -= 1;
});
}
+ function createToggleWrapper(tog) {
+ var span = document.createElement("span");
+ span.className = "toggle-label";
+ span.style.display = "none";
+ span.innerHTML = " Expand attributes";
+ tog.appendChild(span);
+
+ var wrapper = document.createElement("div");
+ wrapper.className = "toggle-wrapper toggle-attributes";
+ wrapper.appendChild(tog);
+ return wrapper;
+ }
+
// To avoid checking on "rustdoc-item-attributes" value on every loop...
var itemAttributesFunc = function() {};
if (getCurrentValue("rustdoc-item-attributes") !== "false") {
@@ -2246,8 +2303,9 @@
collapseDocs(x.previousSibling.childNodes[0], "toggle");
};
}
- onEach(document.getElementById('main').getElementsByClassName('attributes'), function(i_e) {
- i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
+ var attributesToggle = createToggleWrapper(createSimpleToggle(false));
+ onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
+ i_e.parentNode.insertBefore(attributesToggle.cloneNode(true), i_e);
itemAttributesFunc(i_e);
});
@@ -2255,45 +2313,45 @@
var lineNumbersFunc = function() {};
if (getCurrentValue("rustdoc-line-numbers") === "true") {
lineNumbersFunc = function(x) {
- var count = x.textContent.split('\n').length;
+ var count = x.textContent.split("\n").length;
var elems = [];
for (var i = 0; i < count; ++i) {
elems.push(i + 1);
}
- var node = document.createElement('pre');
- addClass(node, 'line-number');
- node.innerHTML = elems.join('\n');
+ var node = document.createElement("pre");
+ addClass(node, "line-number");
+ node.innerHTML = elems.join("\n");
x.parentNode.insertBefore(node, x);
};
}
- onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
- if (hasClass(e, 'compile_fail')) {
+ onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
+ if (hasClass(e, "compile_fail")) {
e.addEventListener("mouseover", function(event) {
- this.parentElement.previousElementSibling.childNodes[0].style.color = '#f00';
+ this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
});
e.addEventListener("mouseout", function(event) {
- this.parentElement.previousElementSibling.childNodes[0].style.color = '';
+ this.parentElement.previousElementSibling.childNodes[0].style.color = "";
});
- } else if (hasClass(e, 'ignore')) {
+ } else if (hasClass(e, "ignore")) {
e.addEventListener("mouseover", function(event) {
- this.parentElement.previousElementSibling.childNodes[0].style.color = '#ff9200';
+ this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
});
e.addEventListener("mouseout", function(event) {
- this.parentElement.previousElementSibling.childNodes[0].style.color = '';
+ this.parentElement.previousElementSibling.childNodes[0].style.color = "";
});
}
lineNumbersFunc(e);
});
function showModal(content) {
- var modal = document.createElement('div');
+ var modal = document.createElement("div");
modal.id = "important";
- addClass(modal, 'modal');
- modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
- '<div class="whiter"></div><span class="docblock">' + content +
- '</span></div>';
- document.getElementsByTagName('body')[0].appendChild(modal);
- document.getElementById('modal-close').onclick = hideModal;
+ addClass(modal, "modal");
+ modal.innerHTML = "<div class=\"modal-content\"><div class=\"close\" id=\"modal-close\">✕" +
+ "</div><div class=\"whiter\"></div><span class=\"docblock\">" + content +
+ "</span></div>";
+ document.getElementsByTagName("body")[0].appendChild(modal);
+ document.getElementById("modal-close").onclick = hideModal;
modal.onclick = hideModal;
}
@@ -2304,7 +2362,7 @@
}
}
- onEach(document.getElementsByClassName('important-traits'), function(e) {
+ onEachLazy(document.getElementsByClassName("important-traits"), function(e) {
e.onclick = function() {
showModal(e.lastElementChild.innerHTML);
};
@@ -2312,7 +2370,7 @@
function putBackSearch(search_input) {
if (search_input.value !== "") {
- addClass(document.getElementById("main"), "hidden");
+ addClass(main, "hidden");
removeClass(document.getElementById("search"), "hidden");
if (browserSupportsHistoryApi()) {
history.replaceState(search_input.value,
@@ -2330,16 +2388,16 @@
var params = getQueryStringParams();
if (params && params.search) {
- addClass(document.getElementById("main"), "hidden");
+ addClass(main, "hidden");
var search = document.getElementById("search");
removeClass(search, "hidden");
- search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
+ search.innerHTML = "<h3 style=\"text-align: center;\">Loading search results...</h3>";
}
var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
if (sidebar_menu) {
sidebar_menu.onclick = function() {
- var sidebar = document.getElementsByClassName('sidebar')[0];
+ var sidebar = document.getElementsByClassName("sidebar")[0];
if (hasClass(sidebar, "mobile") === true) {
hideSidebar();
} else {
@@ -2355,7 +2413,18 @@
autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
if (window.location.hash && window.location.hash.length > 0) {
- expandSection(window.location.hash.replace(/^#/, ''));
+ expandSection(window.location.hash.replace(/^#/, ""));
+ }
+
+ if (main) {
+ onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
+ e.remove();
+ });
+ onEachLazy(main.childNodes, function(e) {
+ if (e.tagName === "H2" || e.tagName === "H3") {
+ e.nextElementSibling.style.display = "block";
+ }
+ });
}
function addSearchOptions(crates) {
@@ -2394,10 +2463,10 @@
// Sets the focus on the search bar at the top of the page
function focusSearchBar() {
- document.getElementsByClassName('search-input')[0].focus();
+ document.getElementsByClassName("search-input")[0].focus();
}
// Removes the focus from the search bar
function defocusSearchBar() {
- document.getElementsByClassName('search-input')[0].blur();
+ document.getElementsByClassName("search-input")[0].blur();
}
diff --git a/src/librustdoc/html/static/noscript.css b/src/librustdoc/html/static/noscript.css
new file mode 100644
index 0000000..f4de75f
--- /dev/null
+++ b/src/librustdoc/html/static/noscript.css
@@ -0,0 +1,19 @@
+/**
+ * Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+ * file at the top-level directory of this distribution and at
+ * http://rust-lang.org/COPYRIGHT.
+ *
+ * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+ * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+ * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+ * option. This file may not be copied, modified, or distributed
+ * except according to those terms.
+ */
+
+#main > h2 + div, #main > h2 + h3, #main > h3 + div {
+ display: block;
+}
+
+.loading-content {
+ display: none;
+}
diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css
index cd5a8a7..d1336b1 100644
--- a/src/librustdoc/html/static/rustdoc.css
+++ b/src/librustdoc/html/static/rustdoc.css
@@ -368,6 +368,10 @@
#main > .docblock h2 { font-size: 1.15em; }
#main > .docblock h3, #main > .docblock h4, #main > .docblock h5 { font-size: 1em; }
+#main > h2 + div, #main > h2 + h3, #main > h3 + div {
+ display: none;
+}
+
.docblock h1 { font-size: 1em; }
.docblock h2 { font-size: 0.95em; }
.docblock h3, .docblock h4, .docblock h5 { font-size: 0.9em; }
diff --git a/src/librustdoc/html/static/storage.js b/src/librustdoc/html/static/storage.js
index e8f0c03..d1c377b 100644
--- a/src/librustdoc/html/static/storage.js
+++ b/src/librustdoc/html/static/storage.js
@@ -19,55 +19,38 @@
var savedHref = [];
function hasClass(elem, className) {
- if (elem && className && elem.className) {
- var elemClass = elem.className;
- var start = elemClass.indexOf(className);
- if (start === -1) {
- return false;
- } else if (elemClass.length === className.length) {
- return true;
- } else {
- if (start > 0 && elemClass[start - 1] !== ' ') {
- return false;
- }
- var end = start + className.length;
- return !(end < elemClass.length && elemClass[end] !== ' ');
- }
- }
- return false;
+ return elem && elem.classList && elem.classList.contains(className);
}
function addClass(elem, className) {
- if (elem && className && !hasClass(elem, className)) {
- if (elem.className && elem.className.length > 0) {
- elem.className += ' ' + className;
- } else {
- elem.className = className;
- }
+ if (!elem || !elem.classList) {
+ return;
}
+ elem.classList.add(className);
}
function removeClass(elem, className) {
- if (elem && className && elem.className) {
- elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
- .trim();
+ if (!elem || !elem.classList) {
+ return;
}
+ elem.classList.remove(className);
}
function isHidden(elem) {
- return (elem.offsetParent === null)
+ return elem.offsetParent === null;
}
function onEach(arr, func, reversed) {
if (arr && arr.length > 0 && func) {
+ var length = arr.length;
if (reversed !== true) {
- for (var i = 0; i < arr.length; ++i) {
+ for (var i = 0; i < length; ++i) {
if (func(arr[i]) === true) {
return true;
}
}
} else {
- for (var i = arr.length - 1; i >= 0; --i) {
+ for (var i = length - 1; i >= 0; --i) {
if (func(arr[i]) === true) {
return true;
}
@@ -77,6 +60,13 @@
return false;
}
+function onEachLazy(lazyArray, func, reversed) {
+ return onEach(
+ Array.prototype.slice.call(lazyArray),
+ func,
+ reversed);
+}
+
function usableLocalStorage() {
// Check if the browser supports localStorage at all:
if (typeof(Storage) === "undefined") {
@@ -133,8 +123,8 @@
});
if (found === true) {
styleElem.href = newHref;
- updateLocalStorage('rustdoc-theme', newTheme);
+ updateLocalStorage("rustdoc-theme", newTheme);
}
}
-switchTheme(currentTheme, mainTheme, getCurrentValue('rustdoc-theme') || 'light');
+switchTheme(currentTheme, mainTheme, getCurrentValue("rustdoc-theme") || "light");
diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs
index a485fac..f71b2a8 100644
--- a/src/librustdoc/html/static_files.rs
+++ b/src/librustdoc/html/static_files.rs
@@ -23,6 +23,9 @@
/// The file contents of `settings.css`, responsible for the items on the settings page.
pub static SETTINGS_CSS: &'static str = include_str!("static/settings.css");
+/// The file contents of the `noscript.css` file, used in case JS isn't supported or is disabled.
+pub static NOSCRIPT_CSS: &'static str = include_str!("static/noscript.css");
+
/// The file contents of `normalize.css`, included to even out standard elements between browser
/// implementations.
pub static NORMALIZE_CSS: &'static str = include_str!("static/normalize.css");
diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs
index 004be1c..287984c 100644
--- a/src/librustdoc/visit_ast.rs
+++ b/src/librustdoc/visit_ast.rs
@@ -424,10 +424,11 @@
hir::ItemKind::Use(ref path, kind) => {
let is_glob = kind == hir::UseKind::Glob;
- // Struct and variant constructors always show up alongside their definitions, we've
- // already processed them so just discard these.
+ // Struct and variant constructors and proc macro stubs always show up alongside
+ // their definitions, we've already processed them so just discard these.
match path.def {
- Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return,
+ Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) |
+ Def::Macro(_, MacroKind::ProcMacroStub) => return,
_ => {}
}
diff --git a/src/libstd/build.rs b/src/libstd/build.rs
index 2386f13..7143de5 100644
--- a/src/libstd/build.rs
+++ b/src/libstd/build.rs
@@ -68,7 +68,6 @@
println!("cargo:rustc-link-lib=advapi32");
println!("cargo:rustc-link-lib=ws2_32");
println!("cargo:rustc-link-lib=userenv");
- println!("cargo:rustc-link-lib=shell32");
} else if target.contains("fuchsia") {
println!("cargo:rustc-link-lib=zircon");
println!("cargo:rustc-link-lib=fdio");
diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs
index f46c4f2..7e15539 100644
--- a/src/libstd/ffi/mod.rs
+++ b/src/libstd/ffi/mod.rs
@@ -72,32 +72,32 @@
//!
//! * **From Rust to C:** [`CString`] represents an owned, C-friendly
//! string: it is nul-terminated, and has no internal nul characters.
-//! Rust code can create a `CString` out of a normal string (provided
+//! Rust code can create a [`CString`] out of a normal string (provided
//! that the string doesn't have nul characters in the middle), and
-//! then use a variety of methods to obtain a raw `*mut u8` that can
+//! then use a variety of methods to obtain a raw `*mut `[`u8`] that can
//! then be passed as an argument to functions which use the C
//! conventions for strings.
//!
//! * **From C to Rust:** [`CStr`] represents a borrowed C string; it
-//! is what you would use to wrap a raw `*const u8` that you got from
-//! a C function. A `CStr` is guaranteed to be a nul-terminated array
-//! of bytes. Once you have a `CStr`, you can convert it to a Rust
-//! `&str` if it's valid UTF-8, or lossily convert it by adding
+//! is what you would use to wrap a raw `*const `[`u8`] that you got from
+//! a C function. A [`CStr`] is guaranteed to be a nul-terminated array
+//! of bytes. Once you have a [`CStr`], you can convert it to a Rust
+//! [`&str`][`str`] if it's valid UTF-8, or lossily convert it by adding
//! replacement characters.
//!
//! [`OsString`] and [`OsStr`] are useful when you need to transfer
//! strings to and from the operating system itself, or when capturing
-//! the output of external commands. Conversions between `OsString`,
-//! `OsStr` and Rust strings work similarly to those for [`CString`]
+//! the output of external commands. Conversions between [`OsString`],
+//! [`OsStr`] and Rust strings work similarly to those for [`CString`]
//! and [`CStr`].
//!
//! * [`OsString`] represents an owned string in whatever
//! representation the operating system prefers. In the Rust standard
//! library, various APIs that transfer strings to/from the operating
-//! system use `OsString` instead of plain strings. For example,
+//! system use [`OsString`] instead of plain strings. For example,
//! [`env::var_os()`] is used to query environment variables; it
-//! returns an `Option<OsString>`. If the environment variable exists
-//! you will get a `Some(os_string)`, which you can *then* try to
+//! returns an [`Option`]`<`[`OsString`]`>`. If the environment variable
+//! exists you will get a [`Some`]`(os_string)`, which you can *then* try to
//! convert to a Rust string. This yields a [`Result<>`], so that
//! your code can detect errors in case the environment variable did
//! not in fact contain valid Unicode data.
@@ -105,7 +105,7 @@
//! * [`OsStr`] represents a borrowed reference to a string in a
//! format that can be passed to the operating system. It can be
//! converted into an UTF-8 Rust string slice in a similar way to
-//! `OsString`.
+//! [`OsString`].
//!
//! # Conversions
//!
@@ -131,7 +131,7 @@
//! Additionally, on Windows [`OsString`] implements the
//! `std::os::windows:ffi::`[`OsStringExt`][windows.OsStringExt]
//! trait, which provides a [`from_wide`] method. The result of this
-//! method is an `OsString` which can be round-tripped to a Windows
+//! method is an [`OsString`] which can be round-tripped to a Windows
//! string losslessly.
//!
//! [`String`]: ../string/struct.String.html
@@ -160,6 +160,8 @@
//! [`collect`]: ../iter/trait.Iterator.html#method.collect
//! [windows.OsStringExt]: ../os/windows/ffi/trait.OsStringExt.html
//! [`from_wide`]: ../os/windows/ffi/trait.OsStringExt.html#tymethod.from_wide
+//! [`Option`]: ../option/enum.Option.html
+//! [`Some`]: ../option/enum.Option.html#variant.Some
#![stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs
index c2aaeb9..24965ff 100644
--- a/src/libstd/io/lazy.rs
+++ b/src/libstd/io/lazy.rs
@@ -26,7 +26,6 @@
unsafe impl<T> Sync for Lazy<T> {}
impl<T> Lazy<T> {
- #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Lazy<T> {
Lazy {
lock: Mutex::new(),
diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs
index 7c43ba5..0febbe5 100644
--- a/src/libstd/lib.rs
+++ b/src/libstd/lib.rs
@@ -271,6 +271,7 @@
#![feature(libc)]
#![feature(link_args)]
#![feature(linkage)]
+#![cfg_attr(not(stage0), feature(min_const_unsafe_fn))]
#![feature(needs_panic_runtime)]
#![feature(never_type)]
#![feature(nll)]
diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs
index 6b47ba6..b6180fb 100644
--- a/src/libstd/panicking.rs
+++ b/src/libstd/panicking.rs
@@ -209,7 +209,8 @@
if let Some(format) = log_backtrace {
let _ = backtrace::print(err, format);
} else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
- let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
+ let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` \
+ environment variable to display a backtrace.");
}
}
};
diff --git a/src/libstd/sys/cloudabi/condvar.rs b/src/libstd/sys/cloudabi/condvar.rs
index ccf848a..3229d98 100644
--- a/src/libstd/sys/cloudabi/condvar.rs
+++ b/src/libstd/sys/cloudabi/condvar.rs
@@ -13,7 +13,7 @@
use sync::atomic::{AtomicU32, Ordering};
use sys::cloudabi::abi;
use sys::mutex::{self, Mutex};
-use sys::time::dur2intervals;
+use sys::time::checked_dur2intervals;
use time::Duration;
extern "C" {
@@ -114,6 +114,8 @@
// Call into the kernel to wait on the condition variable.
let condvar = self.condvar.get();
+ let timeout = checked_dur2intervals(&dur)
+ .expect("overflow converting duration to nanoseconds");
let subscriptions = [
abi::subscription {
type_: abi::eventtype::CONDVAR,
@@ -132,7 +134,7 @@
union: abi::subscription_union {
clock: abi::subscription_clock {
clock_id: abi::clockid::MONOTONIC,
- timeout: dur2intervals(&dur),
+ timeout,
..mem::zeroed()
},
},
diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs
index a76e1fa..1773214 100644
--- a/src/libstd/sys/cloudabi/thread.rs
+++ b/src/libstd/sys/cloudabi/thread.rs
@@ -16,7 +16,7 @@
use mem;
use ptr;
use sys::cloudabi::abi;
-use sys::time::dur2intervals;
+use sys::time::checked_dur2intervals;
use sys_common::thread::*;
use time::Duration;
@@ -70,13 +70,15 @@
}
pub fn sleep(dur: Duration) {
+ let timeout = checked_dur2intervals(&dur)
+ .expect("overflow converting duration to nanoseconds");
unsafe {
let subscription = abi::subscription {
type_: abi::eventtype::CLOCK,
union: abi::subscription_union {
clock: abi::subscription_clock {
clock_id: abi::clockid::MONOTONIC,
- timeout: dur2intervals(&dur),
+ timeout,
..mem::zeroed()
},
},
diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs
index a442d1e..c9fea18 100644
--- a/src/libstd/sys/cloudabi/time.rs
+++ b/src/libstd/sys/cloudabi/time.rs
@@ -19,15 +19,10 @@
t: abi::timestamp,
}
-fn checked_dur2intervals(dur: &Duration) -> Option<abi::timestamp> {
+pub fn checked_dur2intervals(dur: &Duration) -> Option<abi::timestamp> {
dur.as_secs()
- .checked_mul(NSEC_PER_SEC)
- .and_then(|nanos| nanos.checked_add(dur.subsec_nanos() as abi::timestamp))
-}
-
-pub fn dur2intervals(dur: &Duration) -> abi::timestamp {
- checked_dur2intervals(dur)
- .expect("overflow converting duration to nanoseconds")
+ .checked_mul(NSEC_PER_SEC)?
+ .checked_add(dur.subsec_nanos() as abi::timestamp)
}
impl Instant {
@@ -47,20 +42,16 @@
Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32)
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant {
- t: self.t
- .checked_add(dur2intervals(other))
- .expect("overflow when adding duration to instant"),
- }
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant {
+ t: self.t.checked_add(checked_dur2intervals(other)?)?,
+ })
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant {
- t: self.t
- .checked_sub(dur2intervals(other))
- .expect("overflow when subtracting duration from instant"),
- }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant {
+ t: self.t.checked_sub(checked_dur2intervals(other)?)?,
+ })
}
}
@@ -95,23 +86,16 @@
}
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- self.checked_add_duration(other)
- .expect("overflow when adding duration to instant")
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- checked_dur2intervals(other)
- .and_then(|d| self.t.checked_add(d))
- .map(|t| SystemTime {t})
+ Some(SystemTime {
+ t: self.t.checked_add(checked_dur2intervals(other)?)?,
+ })
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime {
- t: self.t
- .checked_sub(dur2intervals(other))
- .expect("overflow when subtracting duration from instant"),
- }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime {
+ t: self.t.checked_sub(checked_dur2intervals(other)?)?,
+ })
}
}
diff --git a/src/libstd/sys/redox/time.rs b/src/libstd/sys/redox/time.rs
index beff8d2..cb2eab5 100644
--- a/src/libstd/sys/redox/time.rs
+++ b/src/libstd/sys/redox/time.rs
@@ -41,10 +41,6 @@
}
}
- fn add_duration(&self, other: &Duration) -> Timespec {
- self.checked_add_duration(other).expect("overflow when adding duration to time")
- }
-
fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
let mut secs = other
.as_secs()
@@ -67,27 +63,25 @@
})
}
- fn sub_duration(&self, other: &Duration) -> Timespec {
+ fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
let mut secs = other
.as_secs()
.try_into() // <- target type would be `i64`
.ok()
- .and_then(|secs| self.t.tv_sec.checked_sub(secs))
- .expect("overflow when subtracting duration from time");
+ .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
// Similar to above, nanos can't overflow.
let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
if nsec < 0 {
nsec += NSEC_PER_SEC as i32;
- secs = secs.checked_sub(1).expect("overflow when subtracting \
- duration from time");
+ secs = secs.checked_sub(1)?;
}
- Timespec {
+ Some(Timespec {
t: syscall::TimeSpec {
tv_sec: secs,
tv_nsec: nsec as i32,
},
- }
+ })
}
}
@@ -150,12 +144,12 @@
})
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant { t: self.t.add_duration(other) }
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_add_duration(other)? })
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant { t: self.t.sub_duration(other) }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_sub_duration(other)? })
}
}
@@ -178,16 +172,12 @@
self.t.sub_timespec(&other.t)
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.add_duration(other) }
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- self.t.checked_add_duration(other).map(|t| SystemTime { t })
+ Some(SystemTime { t: self.t.checked_add_duration(other)? })
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.sub_duration(other) }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime { t: self.t.checked_sub_duration(other)? })
}
}
diff --git a/src/libstd/sys/sgx/abi/mem.rs b/src/libstd/sys/sgx/abi/mem.rs
index 508f2ff..bf32c71 100644
--- a/src/libstd/sys/sgx/abi/mem.rs
+++ b/src/libstd/sys/sgx/abi/mem.rs
@@ -34,13 +34,6 @@
base
}
-pub fn is_enclave_range(p: *const u8, len: usize) -> bool {
- let start=p as u64;
- let end=start + (len as u64);
- start >= image_base() &&
- end <= image_base() + (unsafe { ENCLAVE_SIZE } as u64) // unsafe ok: link-time constant
-}
-
pub fn is_user_range(p: *const u8, len: usize) -> bool {
let start=p as u64;
let end=start + (len as u64);
diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs
index 2bc32c9..d1d180e 100644
--- a/src/libstd/sys/sgx/abi/usercalls/mod.rs
+++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs
@@ -33,14 +33,6 @@
}
}
-pub fn read_alloc(fd: Fd) -> IoResult<Vec<u8>> {
- unsafe {
- let mut userbuf = alloc::User::<ByteBuffer>::uninitialized();
- raw::read_alloc(fd, userbuf.as_raw_mut_ptr()).from_sgx_result()?;
- Ok(copy_user_buffer(&userbuf))
- }
-}
-
pub fn write(fd: Fd, buf: &[u8]) -> IoResult<usize> {
unsafe {
let userbuf = alloc::User::new_from_enclave(buf);
diff --git a/src/libstd/sys/sgx/condvar.rs b/src/libstd/sys/sgx/condvar.rs
index d3e8165..940f50f 100644
--- a/src/libstd/sys/sgx/condvar.rs
+++ b/src/libstd/sys/sgx/condvar.rs
@@ -18,7 +18,6 @@
}
impl Condvar {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Condvar {
Condvar { inner: SpinMutex::new(WaitVariable::new(())) }
}
diff --git a/src/libstd/sys/sgx/mutex.rs b/src/libstd/sys/sgx/mutex.rs
index 6633611..994cf91 100644
--- a/src/libstd/sys/sgx/mutex.rs
+++ b/src/libstd/sys/sgx/mutex.rs
@@ -20,7 +20,6 @@
// Implementation according to “Operating Systems: Three Easy Pieces”, chapter 28
impl Mutex {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Mutex {
Mutex { inner: SpinMutex::new(WaitVariable::new(false)) }
}
@@ -79,7 +78,6 @@
}
impl ReentrantMutex {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn uninitialized() -> ReentrantMutex {
ReentrantMutex {
inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 }))
diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs
index 7b6970b..a1551db 100644
--- a/src/libstd/sys/sgx/rwlock.rs
+++ b/src/libstd/sys/sgx/rwlock.rs
@@ -21,7 +21,6 @@
//unsafe impl Sync for RWLock {} // FIXME
impl RWLock {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> RWLock {
RWLock {
readers: SpinMutex::new(WaitVariable::new(None)),
diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs
index b01c992..196e1a9 100644
--- a/src/libstd/sys/sgx/time.rs
+++ b/src/libstd/sys/sgx/time.rs
@@ -28,12 +28,12 @@
self.0 - other.0
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant(self.0 + *other)
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant(self.0.checked_add(*other)?))
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant(self.0 - *other)
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant(self.0.checked_sub(*other)?))
}
}
@@ -47,15 +47,11 @@
self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- SystemTime(self.0 + *other)
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- self.0.checked_add(*other).map(|d| SystemTime(d))
+ Some(SystemTime(self.0.checked_add(*other)?))
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime(self.0 - *other)
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime(self.0.checked_sub(*other)?))
}
}
diff --git a/src/libstd/sys/sgx/waitqueue.rs b/src/libstd/sys/sgx/waitqueue.rs
index ec1135b..ef0def1 100644
--- a/src/libstd/sys/sgx/waitqueue.rs
+++ b/src/libstd/sys/sgx/waitqueue.rs
@@ -50,7 +50,6 @@
}
impl<T> WaitVariable<T> {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new(var: T) -> Self {
WaitVariable {
queue: WaitQueue::new(),
@@ -137,7 +136,6 @@
}
impl WaitQueue {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Self {
WaitQueue {
inner: UnsafeList::new()
@@ -255,7 +253,6 @@
}
impl<T> UnsafeList<T> {
- #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Self {
unsafe {
UnsafeList {
diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs
index 1f9539c..8f8aaa8 100644
--- a/src/libstd/sys/unix/time.rs
+++ b/src/libstd/sys/unix/time.rs
@@ -42,10 +42,6 @@
}
}
- fn add_duration(&self, other: &Duration) -> Timespec {
- self.checked_add_duration(other).expect("overflow when adding duration to time")
- }
-
fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
let mut secs = other
.as_secs()
@@ -68,27 +64,25 @@
})
}
- fn sub_duration(&self, other: &Duration) -> Timespec {
+ fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
let mut secs = other
.as_secs()
.try_into() // <- target type would be `libc::time_t`
.ok()
- .and_then(|secs| self.t.tv_sec.checked_sub(secs))
- .expect("overflow when subtracting duration from time");
+ .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
// Similar to above, nanos can't overflow.
let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
if nsec < 0 {
nsec += NSEC_PER_SEC as i32;
- secs = secs.checked_sub(1).expect("overflow when subtracting \
- duration from time");
+ secs = secs.checked_sub(1)?;
}
- Timespec {
+ Some(Timespec {
t: libc::timespec {
tv_sec: secs,
tv_nsec: nsec as _,
},
- }
+ })
}
}
@@ -165,18 +159,16 @@
Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32)
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant {
- t: self.t.checked_add(dur2intervals(other))
- .expect("overflow when adding duration to instant"),
- }
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant {
+ t: self.t.checked_add(checked_dur2intervals(other)?)?,
+ })
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant {
- t: self.t.checked_sub(dur2intervals(other))
- .expect("overflow when subtracting duration from instant"),
- }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant {
+ t: self.t.checked_sub(checked_dur2intervals(other)?)?,
+ })
}
}
@@ -199,16 +191,12 @@
self.t.sub_timespec(&other.t)
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.add_duration(other) }
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- self.t.checked_add_duration(other).map(|t| SystemTime { t })
+ Some(SystemTime { t: self.t.checked_add_duration(other)? })
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.sub_duration(other) }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime { t: self.t.checked_sub_duration(other)? })
}
}
@@ -236,12 +224,12 @@
}
}
- fn dur2intervals(dur: &Duration) -> u64 {
+ fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
+ let nanos = dur.as_secs()
+ .checked_mul(NSEC_PER_SEC)?
+ .checked_add(dur.subsec_nanos() as u64)?;
let info = info();
- let nanos = dur.as_secs().checked_mul(NSEC_PER_SEC).and_then(|nanos| {
- nanos.checked_add(dur.subsec_nanos() as u64)
- }).expect("overflow converting duration to nanoseconds");
- mul_div_u64(nanos, info.denom as u64, info.numer as u64)
+ Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
}
fn info() -> &'static libc::mach_timebase_info {
@@ -299,12 +287,12 @@
})
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant { t: self.t.add_duration(other) }
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_add_duration(other)? })
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant { t: self.t.sub_duration(other) }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant { t: self.t.checked_sub_duration(other)? })
}
}
@@ -327,16 +315,12 @@
self.t.sub_timespec(&other.t)
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.add_duration(other) }
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- self.t.checked_add_duration(other).map(|t| SystemTime { t })
+ Some(SystemTime { t: self.t.checked_add_duration(other)? })
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime { t: self.t.sub_duration(other) }
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime { t: self.t.checked_sub_duration(other)? })
}
}
diff --git a/src/libstd/sys/wasm/time.rs b/src/libstd/sys/wasm/time.rs
index 991e817..cc56773 100644
--- a/src/libstd/sys/wasm/time.rs
+++ b/src/libstd/sys/wasm/time.rs
@@ -28,12 +28,12 @@
self.0 - other.0
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
- Instant(self.0 + *other)
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant(self.0.checked_add(*other)?))
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
- Instant(self.0 - *other)
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
+ Some(Instant(self.0.checked_sub(*other)?))
}
}
@@ -47,15 +47,11 @@
self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- SystemTime(self.0 + *other)
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- self.0.checked_add(*other).map(|d| SystemTime(d))
+ Some(SystemTime(self.0.checked_add(*other)?))
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- SystemTime(self.0 - *other)
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ Some(SystemTime(self.0.checked_sub(*other)?))
}
}
diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs
index 4784633..9e9198e 100644
--- a/src/libstd/sys/windows/args.rs
+++ b/src/libstd/sys/windows/args.rs
@@ -11,12 +11,14 @@
#![allow(dead_code)] // runtime init functions not used during testing
use os::windows::prelude::*;
+use sys::windows::os::current_exe;
use sys::c;
-use slice;
-use ops::Range;
use ffi::OsString;
-use libc::{c_int, c_void};
use fmt;
+use vec;
+use core::iter;
+use slice;
+use path::PathBuf;
pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }
@@ -24,20 +26,146 @@
pub fn args() -> Args {
unsafe {
- let mut nArgs: c_int = 0;
- let lpCmdLine = c::GetCommandLineW();
- let szArgList = c::CommandLineToArgvW(lpCmdLine, &mut nArgs);
+ let lp_cmd_line = c::GetCommandLineW();
+ let parsed_args_list = parse_lp_cmd_line(
+ lp_cmd_line as *const u16,
+ || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new()));
- // szArcList can be NULL if CommandLinToArgvW failed,
- // but in that case nArgs is 0 so we won't actually
- // try to read a null pointer
- Args { cur: szArgList, range: 0..(nArgs as isize) }
+ Args { parsed_args_list: parsed_args_list.into_iter() }
}
}
+/// Implements the Windows command-line argument parsing algorithm.
+///
+/// Microsoft's documentation for the Windows CLI argument format can be found at
+/// <https://docs.microsoft.com/en-us/previous-versions//17w5ykft(v=vs.85)>.
+///
+/// Windows includes a function to do this in shell32.dll,
+/// but linking with that DLL causes the process to be registered as a GUI application.
+/// GUI applications add a bunch of overhead, even if no windows are drawn. See
+/// <https://randomascii.wordpress.com/2018/12/03/a-not-called-function-can-cause-a-5x-slowdown/>.
+///
+/// This function was tested for equivalence to the shell32.dll implementation in
+/// Windows 10 Pro v1803, using an exhaustive test suite available at
+/// <https://gist.github.com/notriddle/dde431930c392e428055b2dc22e638f5> or
+/// <https://paste.gg/p/anonymous/47d6ed5f5bd549168b1c69c799825223>.
+unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_name: F)
+ -> Vec<OsString> {
+ const BACKSLASH: u16 = '\\' as u16;
+ const QUOTE: u16 = '"' as u16;
+ const TAB: u16 = '\t' as u16;
+ const SPACE: u16 = ' ' as u16;
+ let mut ret_val = Vec::new();
+ if lp_cmd_line.is_null() || *lp_cmd_line == 0 {
+ ret_val.push(exe_name());
+ return ret_val;
+ }
+ let mut cmd_line = {
+ let mut end = 0;
+ while *lp_cmd_line.offset(end) != 0 {
+ end += 1;
+ }
+ slice::from_raw_parts(lp_cmd_line, end as usize)
+ };
+ // The executable name at the beginning is special.
+ cmd_line = match cmd_line[0] {
+ // The executable name ends at the next quote mark,
+ // no matter what.
+ QUOTE => {
+ let args = {
+ let mut cut = cmd_line[1..].splitn(2, |&c| c == QUOTE);
+ if let Some(exe) = cut.next() {
+ ret_val.push(OsString::from_wide(exe));
+ }
+ cut.next()
+ };
+ if let Some(args) = args {
+ args
+ } else {
+ return ret_val;
+ }
+ }
+ // Implement quirk: when they say whitespace here,
+ // they include the entire ASCII control plane:
+ // "However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW
+ // will consider the first argument to be an empty string. Excess whitespace at the
+ // end of lpCmdLine is ignored."
+ 0...SPACE => {
+ ret_val.push(OsString::new());
+ &cmd_line[1..]
+ },
+ // The executable name ends at the next whitespace,
+ // no matter what.
+ _ => {
+ let args = {
+ let mut cut = cmd_line.splitn(2, |&c| c > 0 && c <= SPACE);
+ if let Some(exe) = cut.next() {
+ ret_val.push(OsString::from_wide(exe));
+ }
+ cut.next()
+ };
+ if let Some(args) = args {
+ args
+ } else {
+ return ret_val;
+ }
+ }
+ };
+ let mut cur = Vec::new();
+ let mut in_quotes = false;
+ let mut was_in_quotes = false;
+ let mut backslash_count: usize = 0;
+ for &c in cmd_line {
+ match c {
+ // backslash
+ BACKSLASH => {
+ backslash_count += 1;
+ was_in_quotes = false;
+ },
+ QUOTE if backslash_count % 2 == 0 => {
+ cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
+ backslash_count = 0;
+ if was_in_quotes {
+ cur.push('"' as u16);
+ was_in_quotes = false;
+ } else {
+ was_in_quotes = in_quotes;
+ in_quotes = !in_quotes;
+ }
+ }
+ QUOTE if backslash_count % 2 != 0 => {
+ cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2));
+ backslash_count = 0;
+ was_in_quotes = false;
+ cur.push(b'"' as u16);
+ }
+ SPACE | TAB if !in_quotes => {
+ cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
+ if !cur.is_empty() || was_in_quotes {
+ ret_val.push(OsString::from_wide(&cur[..]));
+ cur.truncate(0);
+ }
+ backslash_count = 0;
+ was_in_quotes = false;
+ }
+ _ => {
+ cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
+ backslash_count = 0;
+ was_in_quotes = false;
+ cur.push(c);
+ }
+ }
+ }
+ cur.extend(iter::repeat(b'\\' as u16).take(backslash_count));
+ // include empty quoted strings at the end of the arguments list
+ if !cur.is_empty() || was_in_quotes || in_quotes {
+ ret_val.push(OsString::from_wide(&cur[..]));
+ }
+ ret_val
+}
+
pub struct Args {
- range: Range<isize>,
- cur: *mut *mut u16,
+ parsed_args_list: vec::IntoIter<OsString>,
}
pub struct ArgsInnerDebug<'a> {
@@ -46,19 +174,7 @@
impl<'a> fmt::Debug for ArgsInnerDebug<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.write_str("[")?;
- let mut first = true;
- for i in self.args.range.clone() {
- if !first {
- f.write_str(", ")?;
- }
- first = false;
-
- // Here we do allocation which could be avoided.
- fmt::Debug::fmt(&unsafe { os_string_from_ptr(*self.args.cur.offset(i)) }, f)?;
- }
- f.write_str("]")?;
- Ok(())
+ self.args.parsed_args_list.as_slice().fmt(f)
}
}
@@ -70,38 +186,82 @@
}
}
-unsafe fn os_string_from_ptr(ptr: *mut u16) -> OsString {
- let mut len = 0;
- while *ptr.offset(len) != 0 { len += 1; }
-
- // Push it onto the list.
- let ptr = ptr as *const u16;
- let buf = slice::from_raw_parts(ptr, len as usize);
- OsStringExt::from_wide(buf)
-}
-
impl Iterator for Args {
type Item = OsString;
- fn next(&mut self) -> Option<OsString> {
- self.range.next().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } )
- }
- fn size_hint(&self) -> (usize, Option<usize>) { self.range.size_hint() }
+ fn next(&mut self) -> Option<OsString> { self.parsed_args_list.next() }
+ fn size_hint(&self) -> (usize, Option<usize>) { self.parsed_args_list.size_hint() }
}
impl DoubleEndedIterator for Args {
- fn next_back(&mut self) -> Option<OsString> {
- self.range.next_back().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } )
- }
+ fn next_back(&mut self) -> Option<OsString> { self.parsed_args_list.next_back() }
}
impl ExactSizeIterator for Args {
- fn len(&self) -> usize { self.range.len() }
+ fn len(&self) -> usize { self.parsed_args_list.len() }
}
-impl Drop for Args {
- fn drop(&mut self) {
- // self.cur can be null if CommandLineToArgvW previously failed,
- // but LocalFree ignores NULL pointers
- unsafe { c::LocalFree(self.cur as *mut c_void); }
+#[cfg(test)]
+mod tests {
+ use sys::windows::args::*;
+ use ffi::OsString;
+
+ fn chk(string: &str, parts: &[&str]) {
+ let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
+ wide.push(0);
+ let parsed = unsafe {
+ parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE"))
+ };
+ let expected: Vec<OsString> = parts.iter().map(|k| OsString::from(k)).collect();
+ assert_eq!(parsed.as_slice(), expected.as_slice());
+ }
+
+ #[test]
+ fn empty() {
+ chk("", &["TEST.EXE"]);
+ chk("\0", &["TEST.EXE"]);
+ }
+
+ #[test]
+ fn single_words() {
+ chk("EXE one_word", &["EXE", "one_word"]);
+ chk("EXE a", &["EXE", "a"]);
+ chk("EXE 😅", &["EXE", "😅"]);
+ chk("EXE 😅🤦", &["EXE", "😅🤦"]);
+ }
+
+ #[test]
+ fn official_examples() {
+ chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]);
+ chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r#"a\\\b"#, "de fg", "h"]);
+ chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]);
+ chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r#"a\\b c"#, "d", "e"]);
+ }
+
+ #[test]
+ fn whitespace_behavior() {
+ chk(r#" test"#, &["", "test"]);
+ chk(r#" test"#, &["", "test"]);
+ chk(r#" test test2"#, &["", "test", "test2"]);
+ chk(r#" test test2"#, &["", "test", "test2"]);
+ chk(r#"test test2 "#, &["test", "test2"]);
+ chk(r#"test test2 "#, &["test", "test2"]);
+ chk(r#"test "#, &["test"]);
+ }
+
+ #[test]
+ fn genius_quotes() {
+ chk(r#"EXE "" """#, &["EXE", "", ""]);
+ chk(r#"EXE "" """"#, &["EXE", "", "\""]);
+ chk(
+ r#"EXE "this is """all""" in the same argument""#,
+ &["EXE", "this is \"all\" in the same argument"]
+ );
+ chk(r#"EXE "a"""#, &["EXE", "a\""]);
+ chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]);
+ // quotes cannot be escaped in command names
+ chk(r#""EXE" check"#, &["EXE", "check"]);
+ chk(r#""EXE check""#, &["EXE check"]);
+ chk(r#""EXE """for""" check"#, &["EXE ", r#"for""#, "check"]);
+ chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#, "check"]);
}
}
diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs
index c84874a..fa21f45 100644
--- a/src/libstd/sys/windows/c.rs
+++ b/src/libstd/sys/windows/c.rs
@@ -1035,9 +1035,6 @@
pub fn SetLastError(dwErrCode: DWORD);
pub fn GetCommandLineW() -> *mut LPCWSTR;
- pub fn LocalFree(ptr: *mut c_void);
- pub fn CommandLineToArgvW(lpCmdLine: *mut LPCWSTR,
- pNumArgs: *mut c_int) -> *mut *mut u16;
pub fn GetTempPathW(nBufferLength: DWORD,
lpBuffer: LPCWSTR) -> DWORD;
pub fn OpenProcessToken(ProcessHandle: HANDLE,
diff --git a/src/libstd/sys/windows/time.rs b/src/libstd/sys/windows/time.rs
index c809a0b..bb2c97e 100644
--- a/src/libstd/sys/windows/time.rs
+++ b/src/libstd/sys/windows/time.rs
@@ -68,30 +68,27 @@
Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32)
}
- pub fn add_duration(&self, other: &Duration) -> Instant {
+ pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
let freq = frequency() as u64;
- let t = other.as_secs().checked_mul(freq).and_then(|i| {
- (self.t as u64).checked_add(i)
- }).and_then(|i| {
- i.checked_add(mul_div_u64(other.subsec_nanos() as u64, freq,
- NANOS_PER_SEC))
- }).expect("overflow when adding duration to time");
- Instant {
+ let t = other.as_secs()
+ .checked_mul(freq)?
+ .checked_add(mul_div_u64(other.subsec_nanos() as u64, freq, NANOS_PER_SEC))?
+ .checked_add(self.t as u64)?;
+ Some(Instant {
t: t as c::LARGE_INTEGER,
- }
+ })
}
- pub fn sub_duration(&self, other: &Duration) -> Instant {
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
let freq = frequency() as u64;
let t = other.as_secs().checked_mul(freq).and_then(|i| {
(self.t as u64).checked_sub(i)
}).and_then(|i| {
- i.checked_sub(mul_div_u64(other.subsec_nanos() as u64, freq,
- NANOS_PER_SEC))
- }).expect("overflow when subtracting duration from time");
- Instant {
+ i.checked_sub(mul_div_u64(other.subsec_nanos() as u64, freq, NANOS_PER_SEC))
+ })?;
+ Some(Instant {
t: t as c::LARGE_INTEGER,
- }
+ })
}
}
@@ -127,20 +124,14 @@
}
}
- pub fn add_duration(&self, other: &Duration) -> SystemTime {
- self.checked_add_duration(other).expect("overflow when adding duration to time")
- }
-
pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
- checked_dur2intervals(other)
- .and_then(|d| self.intervals().checked_add(d))
- .map(|i| SystemTime::from_intervals(i))
+ let intervals = self.intervals().checked_add(checked_dur2intervals(other)?)?;
+ Some(SystemTime::from_intervals(intervals))
}
- pub fn sub_duration(&self, other: &Duration) -> SystemTime {
- let intervals = self.intervals().checked_sub(dur2intervals(other))
- .expect("overflow when subtracting from time");
- SystemTime::from_intervals(intervals)
+ pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
+ let intervals = self.intervals().checked_sub(checked_dur2intervals(other)?)?;
+ Some(SystemTime::from_intervals(intervals))
}
}
@@ -184,16 +175,12 @@
}
}
-fn checked_dur2intervals(d: &Duration) -> Option<i64> {
- d.as_secs()
- .checked_mul(INTERVALS_PER_SEC)
- .and_then(|i| i.checked_add(d.subsec_nanos() as u64 / 100))
- .and_then(|i| i.try_into().ok())
-}
-
-fn dur2intervals(d: &Duration) -> i64 {
- checked_dur2intervals(d)
- .expect("overflow when converting duration to intervals")
+fn checked_dur2intervals(dur: &Duration) -> Option<i64> {
+ dur.as_secs()
+ .checked_mul(INTERVALS_PER_SEC)?
+ .checked_add(dur.subsec_nanos() as u64 / 100)?
+ .try_into()
+ .ok()
}
fn intervals2dur(intervals: u64) -> Duration {
diff --git a/src/libstd/sys_common/condvar.rs b/src/libstd/sys_common/condvar.rs
index 16bf080..b6f29dd 100644
--- a/src/libstd/sys_common/condvar.rs
+++ b/src/libstd/sys_common/condvar.rs
@@ -25,7 +25,6 @@
///
/// Behavior is undefined if the condition variable is moved after it is
/// first used with any of the functions below.
- #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Condvar { Condvar(imp::Condvar::new()) }
/// Prepares the condition variable for use.
diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs
index 8768423..c6d531c 100644
--- a/src/libstd/sys_common/mutex.rs
+++ b/src/libstd/sys_common/mutex.rs
@@ -27,7 +27,6 @@
/// Also, until `init` is called, behavior is undefined if this
/// mutex is ever used reentrantly, i.e., `raw_lock` or `try_lock`
/// are called by the thread currently holding the lock.
- #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) }
/// Prepare the mutex for use.
diff --git a/src/libstd/sys_common/rwlock.rs b/src/libstd/sys_common/rwlock.rs
index a430c25..71a4f01 100644
--- a/src/libstd/sys_common/rwlock.rs
+++ b/src/libstd/sys_common/rwlock.rs
@@ -22,7 +22,6 @@
///
/// Behavior is undefined if the reader-writer lock is moved after it is
/// first used with any of the functions below.
- #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn
pub const fn new() -> RWLock { RWLock(imp::RWLock::new()) }
/// Acquires shared access to the underlying lock, blocking the current
diff --git a/src/libstd/time.rs b/src/libstd/time.rs
index 6678104..63cede7 100644
--- a/src/libstd/time.rs
+++ b/src/libstd/time.rs
@@ -208,6 +208,22 @@
pub fn elapsed(&self) -> Duration {
Instant::now() - *self
}
+
+ /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
+ /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
+ /// otherwise.
+ #[unstable(feature = "time_checked_add", issue = "55940")]
+ pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
+ self.0.checked_add_duration(&duration).map(|t| Instant(t))
+ }
+
+ /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
+ /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
+ /// otherwise.
+ #[unstable(feature = "time_checked_add", issue = "55940")]
+ pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
+ self.0.checked_sub_duration(&duration).map(|t| Instant(t))
+ }
}
#[stable(feature = "time2", since = "1.8.0")]
@@ -215,7 +231,8 @@
type Output = Instant;
fn add(self, other: Duration) -> Instant {
- Instant(self.0.add_duration(&other))
+ self.checked_add(other)
+ .expect("overflow when adding duration to instant")
}
}
@@ -231,7 +248,8 @@
type Output = Instant;
fn sub(self, other: Duration) -> Instant {
- Instant(self.0.sub_duration(&other))
+ self.checked_sub(other)
+ .expect("overflow when subtracting duration from instant")
}
}
@@ -365,6 +383,14 @@
pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
self.0.checked_add_duration(&duration).map(|t| SystemTime(t))
}
+
+ /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
+ /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
+ /// otherwise.
+ #[unstable(feature = "time_checked_add", issue = "55940")]
+ pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
+ self.0.checked_sub_duration(&duration).map(|t| SystemTime(t))
+ }
}
#[stable(feature = "time2", since = "1.8.0")]
@@ -372,7 +398,8 @@
type Output = SystemTime;
fn add(self, dur: Duration) -> SystemTime {
- SystemTime(self.0.add_duration(&dur))
+ self.checked_add(dur)
+ .expect("overflow when adding duration to instant")
}
}
@@ -388,7 +415,8 @@
type Output = SystemTime;
fn sub(self, dur: Duration) -> SystemTime {
- SystemTime(self.0.sub_duration(&dur))
+ self.checked_sub(dur)
+ .expect("overflow when subtracting duration from instant")
}
}
@@ -521,6 +549,20 @@
let second = Duration::new(1, 0);
assert_almost_eq!(a - second + second, a);
+ assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
+
+ // checked_add_duration will not panic on overflow
+ let mut maybe_t = Some(Instant::now());
+ let max_duration = Duration::from_secs(u64::max_value());
+ // in case `Instant` can store `>= now + max_duration`.
+ for _ in 0..2 {
+ maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
+ }
+ assert_eq!(maybe_t, None);
+
+ // checked_add_duration calculates the right time and will work for another year
+ let year = Duration::from_secs(60 * 60 * 24 * 365);
+ assert_eq!(a + year, a.checked_add(year).unwrap());
}
#[test]
@@ -557,6 +599,7 @@
.duration(), second);
assert_almost_eq!(a - second + second, a);
+ assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
// A difference of 80 and 800 years cannot fit inside a 32-bit time_t
if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs
index eb71003..10c451e 100644
--- a/src/libsyntax/parse/mod.rs
+++ b/src/libsyntax/parse/mod.rs
@@ -15,7 +15,7 @@
use early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
use source_map::{SourceMap, FilePathMapping};
use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
-use errors::{Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
+use errors::{FatalError, Level, Handler, ColorConfig, Diagnostic, DiagnosticBuilder};
use feature_gate::UnstableFeatures;
use parse::parser::Parser;
use ptr::P;
@@ -192,6 +192,14 @@
source_file_to_parser(sess, file_to_source_file(sess, path, None))
}
+/// Create a new parser, returning buffered diagnostics if the file doesn't
+/// exist or from lexing the initial token stream.
+pub fn maybe_new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path)
+ -> Result<Parser<'a>, Vec<Diagnostic>> {
+ let file = try_file_to_source_file(sess, path, None).map_err(|db| vec![db])?;
+ maybe_source_file_to_parser(sess, file)
+}
+
/// Given a session, a crate config, a path, and a span, add
/// the file at the given path to the source_map, and return a parser.
/// On an error, use the given span as the source of the problem.
@@ -237,17 +245,30 @@
// base abstractions
/// Given a session and a path and an optional span (for error reporting),
+/// add the path to the session's source_map and return the new source_file or
+/// error when a file can't be read.
+fn try_file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
+ -> Result<Lrc<SourceFile>, Diagnostic> {
+ sess.source_map().load_file(path)
+ .map_err(|e| {
+ let msg = format!("couldn't read {}: {}", path.display(), e);
+ let mut diag = Diagnostic::new(Level::Fatal, &msg);
+ if let Some(sp) = spanopt {
+ diag.set_span(sp);
+ }
+ diag
+ })
+}
+
+/// Given a session and a path and an optional span (for error reporting),
/// add the path to the session's source_map and return the new source_file.
fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>)
-> Lrc<SourceFile> {
- match sess.source_map().load_file(path) {
+ match try_file_to_source_file(sess, path, spanopt) {
Ok(source_file) => source_file,
- Err(e) => {
- let msg = format!("couldn't read {}: {}", path.display(), e);
- match spanopt {
- Some(sp) => sess.span_diagnostic.span_fatal(sp, &msg).raise(),
- None => sess.span_diagnostic.fatal(&msg).raise()
- }
+ Err(d) => {
+ DiagnosticBuilder::new_diagnostic(&sess.span_diagnostic, d).emit();
+ FatalError.raise();
}
}
}
diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs
index 8e4d3c0..ed74665 100644
--- a/src/libsyntax/parse/token.rs
+++ b/src/libsyntax/parse/token.rs
@@ -207,6 +207,10 @@
Eof,
}
+// `Token` is used a lot. Make sure it doesn't unintentionally get bigger.
+#[cfg(target_arch = "x86_64")]
+static_assert!(MEM_SIZE_OF_STATEMENT: mem::size_of::<Token>() == 16);
+
impl Token {
pub fn interpolated(nt: Nonterminal) -> Token {
Token::Interpolated(Lrc::new((nt, LazyTokenStream::new())))
diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs
index 8b7ffa4..9aafb9f 100644
--- a/src/libsyntax_pos/lib.rs
+++ b/src/libsyntax_pos/lib.rs
@@ -24,10 +24,13 @@
#![feature(nll)]
#![feature(non_exhaustive)]
#![feature(optin_builtin_traits)]
+#![feature(rustc_attrs)]
#![feature(specialization)]
+#![feature(step_trait)]
#![cfg_attr(not(stage0), feature(stdsimd))]
extern crate arena;
+#[macro_use]
extern crate rustc_data_structures;
#[macro_use]
diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs
index f1adb9d..b720db8 100644
--- a/src/libsyntax_pos/symbol.rs
+++ b/src/libsyntax_pos/symbol.rs
@@ -14,6 +14,7 @@
use arena::DroplessArena;
use rustc_data_structures::fx::FxHashMap;
+use rustc_data_structures::indexed_vec::Idx;
use serialize::{Decodable, Decoder, Encodable, Encoder};
use std::fmt;
@@ -143,9 +144,18 @@
}
}
-/// A symbol is an interned or gensymed string.
+/// A symbol is an interned or gensymed string. The use of newtype_index! means
+/// that Option<Symbol> only takes up 4 bytes, because newtype_index! reserves
+/// the last 256 values for tagging purposes.
+///
+/// Note that Symbol cannot be a newtype_index! directly because it implements
+/// fmt::Debug, Encodable, and Decodable in special ways.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct Symbol(u32);
+pub struct Symbol(SymbolIndex);
+
+newtype_index! {
+ pub struct SymbolIndex { .. }
+}
// The interner is pointed to by a thread local value which is only set on the main thread
// with parallelization is disabled. So we don't allow `Symbol` to transfer between threads
@@ -156,6 +166,10 @@
impl !Sync for Symbol { }
impl Symbol {
+ const fn new(n: u32) -> Self {
+ Symbol(SymbolIndex::from_u32_const(n))
+ }
+
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
@@ -189,7 +203,7 @@
}
pub fn as_u32(self) -> u32 {
- self.0
+ self.0.as_u32()
}
}
@@ -197,7 +211,7 @@
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let is_gensymed = with_interner(|interner| interner.is_gensymed(*self));
if is_gensymed {
- write!(f, "{}({})", self, self.0)
+ write!(f, "{}({:?})", self, self.0)
} else {
write!(f, "{}", self)
}
@@ -229,6 +243,9 @@
}
// The `&'static str`s in this type actually point into the arena.
+//
+// Note that normal symbols are indexed upward from 0, and gensyms are indexed
+// downward from SymbolIndex::MAX_AS_U32.
#[derive(Default)]
pub struct Interner {
arena: DroplessArena,
@@ -243,7 +260,7 @@
for &string in init {
if string == "" {
// We can't allocate empty strings in the arena, so handle this here.
- let name = Symbol(this.strings.len() as u32);
+ let name = Symbol::new(this.strings.len() as u32);
this.names.insert("", name);
this.strings.push("");
} else {
@@ -258,7 +275,7 @@
return name;
}
- let name = Symbol(self.strings.len() as u32);
+ let name = Symbol::new(self.strings.len() as u32);
// `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
// UTF-8.
@@ -276,10 +293,10 @@
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
- if (symbol.0 as usize) < self.strings.len() {
+ if (symbol.0.as_usize()) < self.strings.len() {
symbol
} else {
- self.interned(self.gensyms[(!0 - symbol.0) as usize])
+ self.interned(self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize])
}
}
@@ -290,17 +307,17 @@
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
- Symbol(!0 - self.gensyms.len() as u32 + 1)
+ Symbol::new(SymbolIndex::MAX_AS_U32 - self.gensyms.len() as u32 + 1)
}
fn is_gensymed(&mut self, symbol: Symbol) -> bool {
- symbol.0 as usize >= self.strings.len()
+ symbol.0.as_usize() >= self.strings.len()
}
pub fn get(&self, symbol: Symbol) -> &str {
- match self.strings.get(symbol.0 as usize) {
+ match self.strings.get(symbol.0.as_usize()) {
Some(string) => string,
- None => self.get(self.gensyms[(!0 - symbol.0) as usize]),
+ None => self.get(self.gensyms[(SymbolIndex::MAX_AS_U32 - symbol.0.as_u32()) as usize]),
}
}
}
@@ -324,7 +341,7 @@
$(
#[allow(non_upper_case_globals)]
pub const $konst: Keyword = Keyword {
- ident: Ident::with_empty_ctxt(super::Symbol($index))
+ ident: Ident::with_empty_ctxt(super::Symbol::new($index))
};
)*
@@ -709,19 +726,19 @@
fn interner_tests() {
let mut i: Interner = Interner::default();
// first one is zero:
- assert_eq!(i.intern("dog"), Symbol(0));
+ assert_eq!(i.intern("dog"), Symbol::new(0));
// re-use gets the same entry:
- assert_eq!(i.intern("dog"), Symbol(0));
+ assert_eq!(i.intern("dog"), Symbol::new(0));
// different string gets a different #:
- assert_eq!(i.intern("cat"), Symbol(1));
- assert_eq!(i.intern("cat"), Symbol(1));
+ assert_eq!(i.intern("cat"), Symbol::new(1));
+ assert_eq!(i.intern("cat"), Symbol::new(1));
// dog is still at zero
- assert_eq!(i.intern("dog"), Symbol(0));
- assert_eq!(i.gensym("zebra"), Symbol(4294967295));
- // gensym of same string gets new number :
- assert_eq!(i.gensym("zebra"), Symbol(4294967294));
+ assert_eq!(i.intern("dog"), Symbol::new(0));
+ assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32));
+ // gensym of same string gets new number:
+ assert_eq!(i.gensym("zebra"), Symbol::new(SymbolIndex::MAX_AS_U32 - 1));
// gensym of *existing* string gets new number:
- assert_eq!(i.gensym("dog"), Symbol(4294967293));
+ assert_eq!(i.gensym("dog"), Symbol::new(SymbolIndex::MAX_AS_U32 - 2));
}
#[test]
diff --git a/src/test/codegen/simd-intrinsic-generic-select.rs b/src/test/codegen/simd-intrinsic-generic-select.rs
index 8a64d74..24a4b2b 100644
--- a/src/test/codegen/simd-intrinsic-generic-select.rs
+++ b/src/test/codegen/simd-intrinsic-generic-select.rs
@@ -21,10 +21,15 @@
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
+pub struct f32x8(f32, f32, f32, f32, f32, f32, f32, f32);
+
+#[repr(simd)]
+#[derive(Copy, Clone, PartialEq, Debug)]
pub struct b8x4(pub i8, pub i8, pub i8, pub i8);
extern "platform-intrinsic" {
fn simd_select<T, U>(x: T, a: U, b: U) -> U;
+ fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U;
}
// CHECK-LABEL: @select
@@ -33,3 +38,10 @@
// CHECK: select <4 x i1>
simd_select(m, a, b)
}
+
+// CHECK-LABEL: @select_bitmask
+#[no_mangle]
+pub unsafe fn select_bitmask(m: i8, a: f32x8, b: f32x8) -> f32x8 {
+ // CHECK: select <8 x i1>
+ simd_select_bitmask(m, a, b)
+}
diff --git a/src/test/debuginfo/pretty-std-collections.rs b/src/test/debuginfo/pretty-std-collections.rs
index a51be37..350b30d 100644
--- a/src/test/debuginfo/pretty-std-collections.rs
+++ b/src/test/debuginfo/pretty-std-collections.rs
@@ -13,7 +13,11 @@
// ignore-freebsd: gdb package too new
// ignore-android: FIXME(#10381)
// compile-flags:-g
-// min-gdb-version 7.7
+
+// The pretty printers being tested here require the patch from
+// https://sourceware.org/bugzilla/show_bug.cgi?id=21763
+// min-gdb-version 8.1
+
// min-lldb-version: 310
// === GDB TESTS ===================================================================================
diff --git a/src/test/run-make-fulldeps/libtest-json/output.json b/src/test/run-make-fulldeps/libtest-json/output.json
index 80e75c8..2b831ea 100644
--- a/src/test/run-make-fulldeps/libtest-json/output.json
+++ b/src/test/run-make-fulldeps/libtest-json/output.json
@@ -2,7 +2,7 @@
{ "type": "test", "event": "started", "name": "a" }
{ "type": "test", "name": "a", "event": "ok" }
{ "type": "test", "event": "started", "name": "b" }
-{ "type": "test", "name": "b", "event": "failed", "stdout": "thread 'main' panicked at 'assertion failed: false', f.rs:18:5\nnote: Run with `RUST_BACKTRACE=1` for a backtrace.\n" }
+{ "type": "test", "name": "b", "event": "failed", "stdout": "thread 'main' panicked at 'assertion failed: false', f.rs:18:5\nnote: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.\n" }
{ "type": "test", "event": "started", "name": "c" }
{ "type": "test", "name": "c", "event": "ok" }
{ "type": "test", "event": "started", "name": "d" }
diff --git a/src/test/run-make-fulldeps/tools.mk b/src/test/run-make-fulldeps/tools.mk
index 3de358f..7939928 100644
--- a/src/test/run-make-fulldeps/tools.mk
+++ b/src/test/run-make-fulldeps/tools.mk
@@ -76,7 +76,7 @@
# Extra flags needed to compile a working executable with the standard library
ifdef IS_WINDOWS
ifdef IS_MSVC
- EXTRACFLAGS := ws2_32.lib userenv.lib shell32.lib advapi32.lib
+ EXTRACFLAGS := ws2_32.lib userenv.lib advapi32.lib
else
EXTRACFLAGS := -lws2_32 -luserenv
endif
diff --git a/src/test/run-pass/ctfe/references.rs b/src/test/run-pass/ctfe/references.rs
index 946ed24..421f354 100644
--- a/src/test/run-pass/ctfe/references.rs
+++ b/src/test/run-pass/ctfe/references.rs
@@ -28,6 +28,7 @@
_ => panic!("c"),
}
+ #[allow(unreachable_patterns)]
match &43 {
&42 => panic!(),
BOO => panic!(),
diff --git a/src/test/run-pass/multi-panic.rs b/src/test/run-pass/multi-panic.rs
index 2e6e109..03e58fc 100644
--- a/src/test/run-pass/multi-panic.rs
+++ b/src/test/run-pass/multi-panic.rs
@@ -17,7 +17,8 @@
let mut it = err.lines();
assert_eq!(it.next().map(|l| l.starts_with("thread '<unnamed>' panicked at")), Some(true));
- assert_eq!(it.next(), Some("note: Run with `RUST_BACKTRACE=1` for a backtrace."));
+ assert_eq!(it.next(), Some("note: Run with `RUST_BACKTRACE=1` \
+ environment variable to display a backtrace."));
assert_eq!(it.next().map(|l| l.starts_with("thread 'main' panicked at")), Some(true));
assert_eq!(it.next(), None);
}
diff --git a/src/test/run-pass/simd/simd-intrinsic-generic-select.rs b/src/test/run-pass/simd/simd-intrinsic-generic-select.rs
index 590a299..74b99ca 100644
--- a/src/test/run-pass/simd/simd-intrinsic-generic-select.rs
+++ b/src/test/run-pass/simd/simd-intrinsic-generic-select.rs
@@ -28,6 +28,10 @@
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
+struct u32x8(u32, u32, u32, u32, u32, u32, u32, u32);
+
+#[repr(simd)]
+#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);
#[repr(simd)]
@@ -36,6 +40,7 @@
extern "platform-intrinsic" {
fn simd_select<T, U>(x: T, a: U, b: U) -> U;
+ fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U;
}
fn main() {
@@ -146,4 +151,29 @@
let e = b8x4(t, f, t, t);
assert_eq!(r, e);
}
+
+ unsafe {
+ let a = u32x8(0, 1, 2, 3, 4, 5, 6, 7);
+ let b = u32x8(8, 9, 10, 11, 12, 13, 14, 15);
+
+ let r: u32x8 = simd_select_bitmask(0u8, a, b);
+ let e = b;
+ assert_eq!(r, e);
+
+ let r: u32x8 = simd_select_bitmask(0xffu8, a, b);
+ let e = a;
+ assert_eq!(r, e);
+
+ let r: u32x8 = simd_select_bitmask(0b01010101u8, a, b);
+ let e = u32x8(0, 9, 2, 11, 4, 13, 6, 15);
+ assert_eq!(r, e);
+
+ let r: u32x8 = simd_select_bitmask(0b10101010u8, a, b);
+ let e = u32x8(8, 1, 10, 3, 12, 5, 14, 7);
+ assert_eq!(r, e);
+
+ let r: u32x8 = simd_select_bitmask(0b11110000u8, a, b);
+ let e = u32x8(8, 9, 10, 11, 4, 5, 6, 7);
+ assert_eq!(r, e);
+ }
}
diff --git a/src/test/rustdoc-ui/failed-doctest-output.stdout b/src/test/rustdoc-ui/failed-doctest-output.stdout
index cd19099..bd6fa1f 100644
--- a/src/test/rustdoc-ui/failed-doctest-output.stdout
+++ b/src/test/rustdoc-ui/failed-doctest-output.stdout
@@ -13,13 +13,13 @@
| ^^ not found in this scope
thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:326:13
-note: Run with `RUST_BACKTRACE=1` for a backtrace.
+note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
---- $DIR/failed-doctest-output.rs - SomeStruct (line 21) stdout ----
thread '$DIR/failed-doctest-output.rs - SomeStruct (line 21)' panicked at 'test executable failed:
thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1
-note: Run with `RUST_BACKTRACE=1` for a backtrace.
+note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
', src/librustdoc/test.rs:361:17
diff --git a/src/test/rustdoc/proc-macro.rs b/src/test/rustdoc/proc-macro.rs
index 23d0d00..05d64f8 100644
--- a/src/test/rustdoc/proc-macro.rs
+++ b/src/test/rustdoc/proc-macro.rs
@@ -61,3 +61,16 @@
pub fn some_derive(_item: TokenStream) -> TokenStream {
TokenStream::new()
}
+
+// @has some_macros/foo/index.html
+pub mod foo {
+ // @has - '//code' 'pub use some_proc_macro;'
+ // @has - '//a/@href' '../../some_macros/macro.some_proc_macro.html'
+ pub use some_proc_macro;
+ // @has - '//code' 'pub use some_proc_attr;'
+ // @has - '//a/@href' '../../some_macros/attr.some_proc_attr.html'
+ pub use some_proc_attr;
+ // @has - '//code' 'pub use some_derive;'
+ // @has - '//a/@href' '../../some_macros/derive.SomeDerive.html'
+ pub use some_derive;
+}
diff --git a/src/test/ui/error-codes/E0424.rs b/src/test/ui/error-codes/E0424.rs
index 445d0c5..20d42da 100644
--- a/src/test/ui/error-codes/E0424.rs
+++ b/src/test/ui/error-codes/E0424.rs
@@ -19,4 +19,5 @@
}
fn main () {
+ let self = "self"; //~ ERROR E0424
}
diff --git a/src/test/ui/error-codes/E0424.stderr b/src/test/ui/error-codes/E0424.stderr
index a1b7a5f..5eccd7d 100644
--- a/src/test/ui/error-codes/E0424.stderr
+++ b/src/test/ui/error-codes/E0424.stderr
@@ -4,6 +4,12 @@
LL | self.bar(); //~ ERROR E0424
| ^^^^ `self` value is a keyword only available in methods with `self` parameter
-error: aborting due to previous error
+error[E0424]: expected unit struct/variant or constant, found module `self`
+ --> $DIR/E0424.rs:22:9
+ |
+LL | let self = "self"; //~ ERROR E0424
+ | ^^^^ `self` value is a keyword and may not be bound to variables or shadowed
+
+error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0424`.
diff --git a/src/test/ui/issues/issue-31173.stderr b/src/test/ui/issues/issue-31173.stderr
index e2630b5..ed6b325 100644
--- a/src/test/ui/issues/issue-31173.stderr
+++ b/src/test/ui/issues/issue-31173.stderr
@@ -14,8 +14,8 @@
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied:
- `std::iter::Cloned<std::iter::TakeWhile<&mut std::vec::IntoIter<u8>, [closure@$DIR/issue-31173.rs:16:39: 19:6 found_e:_]>> : std::iter::Iterator`
`&mut std::iter::Cloned<std::iter::TakeWhile<&mut std::vec::IntoIter<u8>, [closure@$DIR/issue-31173.rs:16:39: 19:6 found_e:_]>> : std::iter::Iterator`
+ `std::iter::Cloned<std::iter::TakeWhile<&mut std::vec::IntoIter<u8>, [closure@$DIR/issue-31173.rs:16:39: 19:6 found_e:_]>> : std::iter::Iterator`
error: aborting due to 2 previous errors
diff --git a/src/test/ui/issues/issue-35677.rs b/src/test/ui/issues/issue-35677.rs
new file mode 100644
index 0000000..46d3f7e
--- /dev/null
+++ b/src/test/ui/issues/issue-35677.rs
@@ -0,0 +1,5 @@
+use std::collections::HashMap;
+fn intersect_map<K, V>(this: &mut HashMap<K, V>, other: HashMap<K, V>) -> bool {
+ this.drain()
+ //~^ ERROR no method named
+}
diff --git a/src/test/ui/issues/issue-35677.stderr b/src/test/ui/issues/issue-35677.stderr
new file mode 100644
index 0000000..dca096b
--- /dev/null
+++ b/src/test/ui/issues/issue-35677.stderr
@@ -0,0 +1,18 @@
+error[E0601]: `main` function not found in crate `issue_35677`
+ |
+ = note: consider adding a `main` function to `$DIR/issue-35677.rs`
+
+error[E0599]: no method named `drain` found for type `&mut std::collections::HashMap<K, V>` in the current scope
+ --> $DIR/issue-35677.rs:3:10
+ |
+LL | this.drain()
+ | ^^^^^
+ |
+ = note: the method `drain` exists but the following trait bounds were not satisfied:
+ `K : std::cmp::Eq`
+ `K : std::hash::Hash`
+
+error: aborting due to 2 previous errors
+
+Some errors occurred: E0599, E0601.
+For more information about an error, try `rustc --explain E0599`.
diff --git a/src/test/ui/lint/lint-unexported-no-mangle.stderr b/src/test/ui/lint/lint-unexported-no-mangle.stderr
index 063915d..1df2d7b 100644
--- a/src/test/ui/lint/lint-unexported-no-mangle.stderr
+++ b/src/test/ui/lint/lint-unexported-no-mangle.stderr
@@ -1,8 +1,8 @@
-warning: lint `private_no_mangle_fns` has been removed: `no longer an warning, #[no_mangle] functions always exported`
+warning: lint `private_no_mangle_fns` has been removed: `no longer a warning, #[no_mangle] functions always exported`
|
= note: requested on the command line with `-F private_no_mangle_fns`
-warning: lint `private_no_mangle_statics` has been removed: `no longer an warning, #[no_mangle] statics always exported`
+warning: lint `private_no_mangle_statics` has been removed: `no longer a warning, #[no_mangle] statics always exported`
|
= note: requested on the command line with `-F private_no_mangle_statics`
diff --git a/src/test/ui/mismatched_types/issue-36053-2.stderr b/src/test/ui/mismatched_types/issue-36053-2.stderr
index 86a92a7..1fbac9d 100644
--- a/src/test/ui/mismatched_types/issue-36053-2.stderr
+++ b/src/test/ui/mismatched_types/issue-36053-2.stderr
@@ -5,8 +5,8 @@
| ^^^^^
|
= note: the method `count` exists but the following trait bounds were not satisfied:
- `std::iter::Filter<std::iter::Fuse<std::iter::Once<&str>>, [closure@$DIR/issue-36053-2.rs:17:39: 17:53]> : std::iter::Iterator`
`&mut std::iter::Filter<std::iter::Fuse<std::iter::Once<&str>>, [closure@$DIR/issue-36053-2.rs:17:39: 17:53]> : std::iter::Iterator`
+ `std::iter::Filter<std::iter::Fuse<std::iter::Once<&str>>, [closure@$DIR/issue-36053-2.rs:17:39: 17:53]> : std::iter::Iterator`
error[E0631]: type mismatch in closure arguments
--> $DIR/issue-36053-2.rs:17:32
diff --git a/src/test/ui/pattern/const-pat-ice.rs b/src/test/ui/pattern/const-pat-ice.rs
new file mode 100644
index 0000000..6496a2a
--- /dev/null
+++ b/src/test/ui/pattern/const-pat-ice.rs
@@ -0,0 +1,13 @@
+// failure-status: 101
+
+// This is a repro test for an ICE in our pattern handling of constants.
+
+const FOO: &&&u32 = &&&42;
+
+fn main() {
+ match unimplemented!() {
+ &&&42 => {},
+ FOO => {},
+ _ => {},
+ }
+}
diff --git a/src/test/ui/pattern/irrefutable-exhaustive-integer-binding.rs b/src/test/ui/pattern/irrefutable-exhaustive-integer-binding.rs
new file mode 100644
index 0000000..ff06588
--- /dev/null
+++ b/src/test/ui/pattern/irrefutable-exhaustive-integer-binding.rs
@@ -0,0 +1,8 @@
+// run-pass
+
+fn main() {
+ let -2147483648..=2147483647 = 1;
+ let 0..=255 = 0u8;
+ let -128..=127 = 0i8;
+ let '\u{0000}'..='\u{10FFFF}' = 'v';
+}
diff --git a/src/test/ui/pattern/slice-pattern-const-2.rs b/src/test/ui/pattern/slice-pattern-const-2.rs
index 6f9501d..6cfef11 100644
--- a/src/test/ui/pattern/slice-pattern-const-2.rs
+++ b/src/test/ui/pattern/slice-pattern-const-2.rs
@@ -1,4 +1,4 @@
-// compile-pass
+#![deny(unreachable_patterns)]
fn main() {
let s = &[0x00; 4][..]; //Slice of any value
@@ -6,19 +6,26 @@
match s {
MAGIC_TEST => (),
[0x00, 0x00, 0x00, 0x00] => (),
- [4, 5, 6, 7] => (), // this should warn
+ [4, 5, 6, 7] => (), //~ ERROR unreachable pattern
_ => (),
}
match s {
[0x00, 0x00, 0x00, 0x00] => (),
MAGIC_TEST => (),
- [4, 5, 6, 7] => (), // this should warn
+ [4, 5, 6, 7] => (), //~ ERROR unreachable pattern
_ => (),
}
match s {
[0x00, 0x00, 0x00, 0x00] => (),
[4, 5, 6, 7] => (),
- MAGIC_TEST => (), // this should warn
+ MAGIC_TEST => (), // FIXME(oli-obk): this should warn, but currently does not
+ _ => (),
+ }
+ const FOO: [u32; 1] = [4];
+ match [99] {
+ [0x00] => (),
+ [4] => (),
+ FOO => (), //~ ERROR unreachable pattern
_ => (),
}
}
diff --git a/src/test/ui/pattern/slice-pattern-const-2.stderr b/src/test/ui/pattern/slice-pattern-const-2.stderr
new file mode 100644
index 0000000..95651cc
--- /dev/null
+++ b/src/test/ui/pattern/slice-pattern-const-2.stderr
@@ -0,0 +1,26 @@
+error: unreachable pattern
+ --> $DIR/slice-pattern-const-2.rs:9:9
+ |
+LL | [4, 5, 6, 7] => (), //~ ERROR unreachable pattern
+ | ^^^^^^^^^^^^
+ |
+note: lint level defined here
+ --> $DIR/slice-pattern-const-2.rs:1:9
+ |
+LL | #![deny(unreachable_patterns)]
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const-2.rs:15:9
+ |
+LL | [4, 5, 6, 7] => (), //~ ERROR unreachable pattern
+ | ^^^^^^^^^^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const-2.rs:28:9
+ |
+LL | FOO => (), //~ ERROR unreachable pattern
+ | ^^^
+
+error: aborting due to 3 previous errors
+
diff --git a/src/test/ui/pattern/slice-pattern-const-3.rs b/src/test/ui/pattern/slice-pattern-const-3.rs
index e7a30ce..8805c43 100644
--- a/src/test/ui/pattern/slice-pattern-const-3.rs
+++ b/src/test/ui/pattern/slice-pattern-const-3.rs
@@ -1,4 +1,4 @@
-// compile-pass
+#![deny(unreachable_patterns)]
fn main() {
let s = &["0x00"; 4][..]; //Slice of any value
@@ -6,19 +6,26 @@
match s {
MAGIC_TEST => (),
["0x00", "0x00", "0x00", "0x00"] => (),
- ["4", "5", "6", "7"] => (), // this should warn
+ ["4", "5", "6", "7"] => (), // FIXME(oli-obk): this should warn, but currently does not
_ => (),
}
match s {
["0x00", "0x00", "0x00", "0x00"] => (),
MAGIC_TEST => (),
- ["4", "5", "6", "7"] => (), // this should warn
+ ["4", "5", "6", "7"] => (), // FIXME(oli-obk): this should warn, but currently does not
_ => (),
}
match s {
["0x00", "0x00", "0x00", "0x00"] => (),
["4", "5", "6", "7"] => (),
- MAGIC_TEST => (), // this should warn
+ MAGIC_TEST => (), // FIXME(oli-obk): this should warn, but currently does not
+ _ => (),
+ }
+ const FOO: [&str; 1] = ["boo"];
+ match ["baa"] {
+ ["0x00"] => (),
+ ["boo"] => (),
+ FOO => (), //~ ERROR unreachable pattern
_ => (),
}
}
diff --git a/src/test/ui/pattern/slice-pattern-const-3.stderr b/src/test/ui/pattern/slice-pattern-const-3.stderr
new file mode 100644
index 0000000..531bbbc
--- /dev/null
+++ b/src/test/ui/pattern/slice-pattern-const-3.stderr
@@ -0,0 +1,14 @@
+error: unreachable pattern
+ --> $DIR/slice-pattern-const-3.rs:28:9
+ |
+LL | FOO => (), //~ ERROR unreachable pattern
+ | ^^^
+ |
+note: lint level defined here
+ --> $DIR/slice-pattern-const-3.rs:1:9
+ |
+LL | #![deny(unreachable_patterns)]
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to previous error
+
diff --git a/src/test/ui/pattern/slice-pattern-const.rs b/src/test/ui/pattern/slice-pattern-const.rs
index d353f6c..f0a0451 100644
--- a/src/test/ui/pattern/slice-pattern-const.rs
+++ b/src/test/ui/pattern/slice-pattern-const.rs
@@ -1,4 +1,4 @@
-//compile-pass
+#![deny(unreachable_patterns)]
fn main() {
let s = &[0x00; 4][..]; //Slice of any value
@@ -6,19 +6,42 @@
match s {
MAGIC_TEST => (),
[0x00, 0x00, 0x00, 0x00] => (),
- [84, 69, 83, 84] => (), // this should warn
+ [84, 69, 83, 84] => (), //~ ERROR unreachable pattern
_ => (),
}
match s {
[0x00, 0x00, 0x00, 0x00] => (),
MAGIC_TEST => (),
- [84, 69, 83, 84] => (), // this should warn
+ [84, 69, 83, 84] => (), //~ ERROR unreachable pattern
_ => (),
}
match s {
[0x00, 0x00, 0x00, 0x00] => (),
[84, 69, 83, 84] => (),
- MAGIC_TEST => (), // this should warn
+ MAGIC_TEST => (), //~ ERROR unreachable pattern
_ => (),
}
+ const FOO: [u8; 1] = [4];
+ match [99] {
+ [0x00] => (),
+ [4] => (),
+ FOO => (), //~ ERROR unreachable pattern
+ _ => (),
+ }
+ const BAR: &[u8; 1] = &[4];
+ match &[99] {
+ [0x00] => (),
+ [4] => (),
+ BAR => (), //~ ERROR unreachable pattern
+ b"a" => (),
+ _ => (),
+ }
+
+ const BOO: &[u8; 0] = &[];
+ match &[] {
+ [] => (),
+ BOO => (), //~ ERROR unreachable pattern
+ b"" => (), //~ ERROR unreachable pattern
+ _ => (), //~ ERROR unreachable pattern
+ }
}
diff --git a/src/test/ui/pattern/slice-pattern-const.stderr b/src/test/ui/pattern/slice-pattern-const.stderr
new file mode 100644
index 0000000..412e015
--- /dev/null
+++ b/src/test/ui/pattern/slice-pattern-const.stderr
@@ -0,0 +1,56 @@
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:9:9
+ |
+LL | [84, 69, 83, 84] => (), //~ ERROR unreachable pattern
+ | ^^^^^^^^^^^^^^^^
+ |
+note: lint level defined here
+ --> $DIR/slice-pattern-const.rs:1:9
+ |
+LL | #![deny(unreachable_patterns)]
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:15:9
+ |
+LL | [84, 69, 83, 84] => (), //~ ERROR unreachable pattern
+ | ^^^^^^^^^^^^^^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:21:9
+ |
+LL | MAGIC_TEST => (), //~ ERROR unreachable pattern
+ | ^^^^^^^^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:28:9
+ |
+LL | FOO => (), //~ ERROR unreachable pattern
+ | ^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:35:9
+ |
+LL | BAR => (), //~ ERROR unreachable pattern
+ | ^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:43:9
+ |
+LL | BOO => (), //~ ERROR unreachable pattern
+ | ^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:44:9
+ |
+LL | b"" => (), //~ ERROR unreachable pattern
+ | ^^^
+
+error: unreachable pattern
+ --> $DIR/slice-pattern-const.rs:45:9
+ |
+LL | _ => (), //~ ERROR unreachable pattern
+ | ^
+
+error: aborting due to 8 previous errors
+
diff --git a/src/test/ui/regions/issue-56537-closure-uses-region-from-container.rs b/src/test/ui/regions/issue-56537-closure-uses-region-from-container.rs
new file mode 100644
index 0000000..24676fe
--- /dev/null
+++ b/src/test/ui/regions/issue-56537-closure-uses-region-from-container.rs
@@ -0,0 +1,74 @@
+// This is a collection of examples where a function's formal
+// parameter has an explicit lifetime and a closure within that
+// function returns that formal parameter. The closure's return type,
+// to be correctly inferred, needs to include the lifetime introduced
+// by the function.
+//
+// This works today, which precludes changing things so that closures
+// follow the same lifetime-elision rules used elsehwere. See
+// rust-lang/rust#56537
+
+// compile-pass
+// We are already testing NLL explicitly via the revision system below.
+// ignore-compare-mode-nll
+
+// revisions: ll nll migrate
+//[ll] compile-flags:-Zborrowck=ast
+//[nll] compile-flags:-Zborrowck=mir -Z two-phase-borrows
+//[migrate] compile-flags:-Zborrowck=migrate -Z two-phase-borrows
+
+fn willy_no_annot<'w>(p: &'w str, q: &str) -> &'w str {
+ let free_dumb = |_x| { p }; // no type annotation at all
+ let hello = format!("Hello");
+ free_dumb(&hello)
+}
+
+fn willy_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
+ let free_dumb = |_x| -> &str { p }; // type annotation on the return type
+ let hello = format!("Hello");
+ free_dumb(&hello)
+}
+
+fn willy_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
+ let free_dumb = |_x| -> &'w str { p }; // type+region annotation on return type
+ let hello = format!("Hello");
+ free_dumb(&hello)
+}
+
+fn willy_arg_type_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
+ let free_dumb = |_x: &str| -> &str { p }; // type annotation on arg and return types
+ let hello = format!("Hello");
+ free_dumb(&hello)
+}
+
+fn willy_arg_type_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
+ let free_dumb = |_x: &str| -> &'w str { p }; // fully annotated
+ let hello = format!("Hello");
+ free_dumb(&hello)
+}
+
+fn main() {
+ let world = format!("World");
+ let w1: &str = {
+ let hello = format!("He11o");
+ willy_no_annot(&world, &hello)
+ };
+ let w2: &str = {
+ let hello = format!("He22o");
+ willy_ret_type_annot(&world, &hello)
+ };
+ let w3: &str = {
+ let hello = format!("He33o");
+ willy_ret_region_annot(&world, &hello)
+ };
+ let w4: &str = {
+ let hello = format!("He44o");
+ willy_arg_type_ret_type_annot(&world, &hello)
+ };
+ let w5: &str = {
+ let hello = format!("He55o");
+ willy_arg_type_ret_region_annot(&world, &hello)
+ };
+ assert_eq!((w1, w2, w3, w4, w5),
+ ("World","World","World","World","World"));
+}
diff --git a/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.rs b/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.rs
index d74d681..2a2d35e 100644
--- a/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.rs
+++ b/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.rs
@@ -33,6 +33,7 @@
extern "platform-intrinsic" {
fn simd_select<T, U>(x: T, a: U, b: U) -> U;
+ fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U;
}
fn main() {
@@ -52,5 +53,14 @@
simd_select(z, z, z);
//~^ ERROR mask element type is `f32`, expected `i_`
+
+ simd_select_bitmask(0u8, x, x);
+ //~^ ERROR mask length `8` != other vector length `4`
+
+ simd_select_bitmask(0.0f32, x, x);
+ //~^ ERROR `f32` is not an integral type
+
+ simd_select_bitmask("x", x, x);
+ //~^ ERROR `&str` is not an integral type
}
}
diff --git a/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.stderr b/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.stderr
index 61e4202..584f3d5 100644
--- a/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.stderr
+++ b/src/test/ui/simd-intrinsic/simd-intrinsic-generic-select.stderr
@@ -1,21 +1,39 @@
error[E0511]: invalid monomorphization of `simd_select` intrinsic: mismatched lengths: mask length `8` != other vector length `4`
- --> $DIR/simd-intrinsic-generic-select.rs:47:9
+ --> $DIR/simd-intrinsic-generic-select.rs:48:9
|
LL | simd_select(m8, x, x);
| ^^^^^^^^^^^^^^^^^^^^^
error[E0511]: invalid monomorphization of `simd_select` intrinsic: mask element type is `u32`, expected `i_`
- --> $DIR/simd-intrinsic-generic-select.rs:50:9
+ --> $DIR/simd-intrinsic-generic-select.rs:51:9
|
LL | simd_select(x, x, x);
| ^^^^^^^^^^^^^^^^^^^^
error[E0511]: invalid monomorphization of `simd_select` intrinsic: mask element type is `f32`, expected `i_`
- --> $DIR/simd-intrinsic-generic-select.rs:53:9
+ --> $DIR/simd-intrinsic-generic-select.rs:54:9
|
LL | simd_select(z, z, z);
| ^^^^^^^^^^^^^^^^^^^^
-error: aborting due to 3 previous errors
+error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: mismatched lengths: mask length `8` != other vector length `4`
+ --> $DIR/simd-intrinsic-generic-select.rs:57:9
+ |
+LL | simd_select_bitmask(0u8, x, x);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: `f32` is not an integral type
+ --> $DIR/simd-intrinsic-generic-select.rs:60:9
+ |
+LL | simd_select_bitmask(0.0f32, x, x);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: `&str` is not an integral type
+ --> $DIR/simd-intrinsic-generic-select.rs:63:9
+ |
+LL | simd_select_bitmask("x", x, x);
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to 6 previous errors
For more information about this error, try `rustc --explain E0511`.
diff --git a/src/test/ui/suggestions/suggest-impl-trait-lifetime.fixed b/src/test/ui/suggestions/suggest-impl-trait-lifetime.fixed
new file mode 100644
index 0000000..8592af1
--- /dev/null
+++ b/src/test/ui/suggestions/suggest-impl-trait-lifetime.fixed
@@ -0,0 +1,18 @@
+// run-rustfix
+
+use std::fmt::Debug;
+
+fn foo(d: impl Debug + 'static) {
+//~^ HELP consider adding an explicit lifetime bound `'static` to `impl Debug`
+ bar(d);
+//~^ ERROR the parameter type `impl Debug` may not live long enough
+//~| NOTE ...so that the type `impl Debug` will meet its required lifetime bounds
+}
+
+fn bar(d: impl Debug + 'static) {
+ println!("{:?}", d)
+}
+
+fn main() {
+ foo("hi");
+}
diff --git a/src/test/ui/suggestions/suggest-impl-trait-lifetime.rs b/src/test/ui/suggestions/suggest-impl-trait-lifetime.rs
new file mode 100644
index 0000000..c67d78e
--- /dev/null
+++ b/src/test/ui/suggestions/suggest-impl-trait-lifetime.rs
@@ -0,0 +1,18 @@
+// run-rustfix
+
+use std::fmt::Debug;
+
+fn foo(d: impl Debug) {
+//~^ HELP consider adding an explicit lifetime bound `'static` to `impl Debug`
+ bar(d);
+//~^ ERROR the parameter type `impl Debug` may not live long enough
+//~| NOTE ...so that the type `impl Debug` will meet its required lifetime bounds
+}
+
+fn bar(d: impl Debug + 'static) {
+ println!("{:?}", d)
+}
+
+fn main() {
+ foo("hi");
+}
diff --git a/src/test/ui/suggestions/suggest-impl-trait-lifetime.stderr b/src/test/ui/suggestions/suggest-impl-trait-lifetime.stderr
new file mode 100644
index 0000000..cba231d
--- /dev/null
+++ b/src/test/ui/suggestions/suggest-impl-trait-lifetime.stderr
@@ -0,0 +1,19 @@
+error[E0310]: the parameter type `impl Debug` may not live long enough
+ --> $DIR/suggest-impl-trait-lifetime.rs:7:5
+ |
+LL | bar(d);
+ | ^^^
+ |
+note: ...so that the type `impl Debug` will meet its required lifetime bounds
+ --> $DIR/suggest-impl-trait-lifetime.rs:7:5
+ |
+LL | bar(d);
+ | ^^^
+help: consider adding an explicit lifetime bound `'static` to `impl Debug`...
+ |
+LL | fn foo(d: impl Debug + 'static) {
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0310`.
diff --git a/src/tools/publish_toolstate.py b/src/tools/publish_toolstate.py
index 4ade87f..a65d263 100755
--- a/src/tools/publish_toolstate.py
+++ b/src/tools/publish_toolstate.py
@@ -34,6 +34,16 @@
'rust-by-example': '@steveklabnik @marioidival @projektir',
}
+EMOJI = {
+ 'miri': '🛰️',
+ 'clippy-driver': '📎',
+ 'rls': '💻',
+ 'rustfmt': '📝',
+ 'book': '📖',
+ 'nomicon': '👿',
+ 'reference': '📚',
+ 'rust-by-example': '👩🏫',
+}
def read_current_status(current_commit, path):
'''Reads build status of `current_commit` from content of `history/*.tsv`
@@ -63,13 +73,12 @@
}
slug = 'rust-lang/rust'
- message = textwrap.dedent('''\
- 📣 Toolstate changed by {}!
-
+ long_message = textwrap.dedent('''\
Tested on commit {}@{}.
Direct link to PR: <{}>
- ''').format(relevant_pr_number, slug, current_commit, relevant_pr_url)
+ ''').format(slug, current_commit, relevant_pr_url)
+ emoji_status = []
anything_changed = False
for status in latest:
tool = status['tool']
@@ -81,12 +90,18 @@
status[os] = new
if new > old:
changed = True
- message += '🎉 {} on {}: {} → {} (cc {}, @rust-lang/infra).\n' \
- .format(tool, os, old, new, MAINTAINERS.get(tool))
+ long_message += '🎉 {} on {}: {} → {}.\n' \
+ .format(tool, os, old, new)
+ emoji = "{}🎉".format(EMOJI.get(tool))
+ if msg not in emoji_status:
+ emoji_status += [msg]
elif new < old:
changed = True
- message += '💔 {} on {}: {} → {} (cc {}, @rust-lang/infra).\n' \
+ long_message += '💔 {} on {}: {} → {} (cc {}, @rust-lang/infra).\n' \
.format(tool, os, old, new, MAINTAINERS.get(tool))
+ emoji = "{}💔".format(EMOJI.get(tool))
+ if msg not in emoji_status:
+ emoji_status += [msg]
if changed:
status['commit'] = current_commit
@@ -96,6 +111,9 @@
if not anything_changed:
return ''
+ short_message = "📣 Toolstate changed by {}! ({})"
+ .format(relevant_pr_number, '/'.join(emoji_status))
+ message = short_message + "\n\n" + long_message
f.seek(0)
f.truncate(0)
json.dump(latest, f, indent=4, separators=(',', ': '))