diff --git a/config.toml.example b/config.toml.example index 848147c2974c1..2e3b714f9228a 100644 --- a/config.toml.example +++ b/config.toml.example @@ -377,6 +377,7 @@ # but you can also optionally enable the "emscripten" backend for asm.js or # make this an empty array (but that probably won't get too far in the # bootstrap) +# FIXME: remove the obsolete emscripten backend option. #codegen-backends = ["llvm"] # This is the name of the directory in which codegen backends will get installed diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index b7ce9c7b39709..673ce0053ca12 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1046,11 +1046,9 @@ impl Step for Compiletest { // Also provide `rust_test_helpers` for the host. builder.ensure(native::TestHelpers { target: compiler.host }); + // As well as the target + builder.ensure(native::TestHelpers { target }); - // wasm32 can't build the test helpers - if !target.contains("wasm32") { - builder.ensure(native::TestHelpers { target }); - } builder.ensure(RemoteCopyLibs { compiler, target }); let mut cmd = builder.tool_cmd(Tool::Compiletest); diff --git a/src/ci/docker/asmjs/Dockerfile b/src/ci/docker/asmjs/Dockerfile index 3abaab6b34ef0..cbb9b25705109 100644 --- a/src/ci/docker/asmjs/Dockerfile +++ b/src/ci/docker/asmjs/Dockerfile @@ -11,7 +11,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ cmake \ sudo \ gdb \ - xz-utils + xz-utils \ + bzip2 COPY scripts/emscripten.sh /scripts/ RUN bash /scripts/emscripten.sh @@ -20,28 +21,17 @@ COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV PATH=$PATH:/emsdk-portable -ENV PATH=$PATH:/emsdk-portable/clang/e1.38.15_64bit/ -ENV PATH=$PATH:/emsdk-portable/emscripten/1.38.15/ -ENV PATH=$PATH:/emsdk-portable/node/8.9.1_64bit/bin/ -ENV EMSCRIPTEN=/emsdk-portable/emscripten/1.38.15/ -ENV BINARYEN_ROOT=/emsdk-portable/clang/e1.38.15_64bit/binaryen/ +ENV PATH=$PATH:/emsdk-portable/upstream/emscripten/ +ENV PATH=$PATH:/emsdk-portable/node/12.9.1_64bit/bin/ +ENV BINARYEN_ROOT=/emsdk-portable/upstream/ ENV EM_CONFIG=/emsdk-portable/.emscripten ENV TARGETS=asmjs-unknown-emscripten -ENV RUST_CONFIGURE_ARGS --enable-emscripten --disable-optimize-tests +# TODO: Run run-fail, libcore, libstd, etc. once exceptions are enabled +ENV SCRIPT python2.7 ../x.py test --target $TARGETS src/test/ui -ENV SCRIPT python2.7 ../x.py test --target $TARGETS \ - src/test/ui \ - src/test/run-fail \ - src/libstd \ - src/liballoc \ - src/libcore - -# Debug assertions in rustc are largely covered by other builders, and LLVM -# assertions cause this builder to slow down by quite a large amount and don't -# buy us a huge amount over other builders (not sure if we've ever seen an -# asmjs-specific backend assertion trip), so disable assertions for these -# tests. -ENV NO_LLVM_ASSERTIONS=1 +# This is almost identical to the wasm32-unknown-emscripten target, so +# running with assertions again is not useful ENV NO_DEBUG_ASSERTIONS=1 +ENV NO_LLVM_ASSERTIONS=1 diff --git a/src/ci/docker/disabled/wasm32-exp/Dockerfile b/src/ci/docker/disabled/wasm32-exp/Dockerfile deleted file mode 100644 index 420d47b314c0f..0000000000000 --- a/src/ci/docker/disabled/wasm32-exp/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -FROM ubuntu:16.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - g++ \ - make \ - file \ - curl \ - ca-certificates \ - python \ - git \ - cmake \ - sudo \ - gdb \ - xz-utils \ - jq \ - bzip2 - -# emscripten -COPY scripts/emscripten-wasm.sh /scripts/ -COPY wasm32-exp/node.sh /usr/local/bin/node -RUN bash /scripts/emscripten-wasm.sh - -# cache -COPY scripts/sccache.sh /scripts/ -RUN sh /scripts/sccache.sh - -# env -ENV PATH=/wasm-install/emscripten:/wasm-install/bin:$PATH -ENV EM_CONFIG=/root/.emscripten - -ENV TARGETS=wasm32-experimental-emscripten - -ENV RUST_CONFIGURE_ARGS --experimental-targets=WebAssembly - -ENV SCRIPT python2.7 ../x.py test --target $TARGETS diff --git a/src/ci/docker/disabled/wasm32-exp/node.sh b/src/ci/docker/disabled/wasm32-exp/node.sh deleted file mode 100755 index aa938971c702f..0000000000000 --- a/src/ci/docker/disabled/wasm32-exp/node.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -path="$(dirname $1)" -file="$(basename $1)" - -shift - -cd "$path" -exec /node-v8.0.0-linux-x64/bin/node "$file" "$@" diff --git a/src/ci/docker/disabled/wasm32/Dockerfile b/src/ci/docker/disabled/wasm32/Dockerfile index 0d2bd39303ef8..5d91691f6ee1c 100644 --- a/src/ci/docker/disabled/wasm32/Dockerfile +++ b/src/ci/docker/disabled/wasm32/Dockerfile @@ -11,9 +11,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ cmake \ sudo \ gdb \ - xz-utils + xz-utils \ + bzip2 -# emscripten COPY scripts/emscripten.sh /scripts/ RUN bash /scripts/emscripten.sh @@ -21,12 +21,12 @@ COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV PATH=$PATH:/emsdk-portable -ENV PATH=$PATH:/emsdk-portable/clang/e1.38.15_64bit/ -ENV PATH=$PATH:/emsdk-portable/emscripten/1.38.15/ -ENV PATH=$PATH:/emsdk-portable/node/8.9.1_64bit/bin/ -ENV EMSCRIPTEN=/emsdk-portable/emscripten/1.38.15/ -ENV BINARYEN_ROOT=/emsdk-portable/clang/e1.38.15_64bit/binaryen/ +ENV PATH=$PATH:/emsdk-portable/upstream/emscripten/ +ENV PATH=$PATH:/emsdk-portable/node/12.9.1_64bit/bin/ +ENV BINARYEN_ROOT=/emsdk-portable/upstream/ ENV EM_CONFIG=/emsdk-portable/.emscripten ENV TARGETS=wasm32-unknown-emscripten -ENV SCRIPT python2.7 ../x.py test --target $TARGETS + +# TODO: Run run-fail, libcore, libstd, etc. once exceptions are enabled +ENV SCRIPT python2.7 ../x.py test --target $TARGETS src/test/ui diff --git a/src/ci/docker/scripts/emscripten-wasm.sh b/src/ci/docker/scripts/emscripten-wasm.sh deleted file mode 100644 index e4a93d7a10092..0000000000000 --- a/src/ci/docker/scripts/emscripten-wasm.sh +++ /dev/null @@ -1,37 +0,0 @@ -set -ex - -hide_output() { - set +x - on_err=" -echo ERROR: An error was encountered with the build. -cat /tmp/build.log -exit 1 -" - trap "$on_err" ERR - bash -c "while true; do sleep 30; echo \$(date) - building ...; done" & - PING_LOOP_PID=$! - $@ &> /tmp/build.log - trap - ERR - kill $PING_LOOP_PID - rm -f /tmp/build.log - set -x -} - -# Download last known good emscripten from WebAssembly waterfall -BUILD=$(curl -fL https://storage.googleapis.com/wasm-llvm/builds/linux/lkgr.json | \ - jq '.build | tonumber') -curl -sL https://storage.googleapis.com/wasm-llvm/builds/linux/$BUILD/wasm-binaries.tbz2 | \ - hide_output tar xvkj - -# node 8 is required to run wasm -cd / -curl -sL https://nodejs.org/dist/v8.0.0/node-v8.0.0-linux-x64.tar.xz | \ - tar -xJ - -# Make emscripten use wasm-ready node and LLVM tools -echo "EMSCRIPTEN_ROOT = '/wasm-install/emscripten'" >> /root/.emscripten -echo "NODE_JS='/usr/local/bin/node'" >> /root/.emscripten -echo "LLVM_ROOT='/wasm-install/bin'" >> /root/.emscripten -echo "BINARYEN_ROOT = '/wasm-install'" >> /root/.emscripten -echo "COMPILER_ENGINE = NODE_JS" >> /root/.emscripten -echo "JS_ENGINES = [NODE_JS]" >> /root/.emscripten diff --git a/src/ci/docker/scripts/emscripten.sh b/src/ci/docker/scripts/emscripten.sh index 47196e8939626..9c7a09e227a47 100644 --- a/src/ci/docker/scripts/emscripten.sh +++ b/src/ci/docker/scripts/emscripten.sh @@ -17,20 +17,15 @@ exit 1 set -x } -cd / -curl -fL https://mozilla-games.s3.amazonaws.com/emscripten/releases/emsdk-portable.tar.gz | \ - tar -xz - +git clone https://github.com/emscripten-core/emsdk.git /emsdk-portable cd /emsdk-portable -./emsdk update -hide_output ./emsdk install sdk-1.38.15-64bit -./emsdk activate sdk-1.38.15-64bit +hide_output ./emsdk install 1.38.46-upstream +./emsdk activate 1.38.46-upstream # Compile and cache libc source ./emsdk_env.sh echo "main(){}" > a.c HOME=/emsdk-portable/ emcc a.c -HOME=/emsdk-portable/ emcc -s BINARYEN=1 a.c rm -f a.* # Make emsdk usable by any user diff --git a/src/libcore/ffi.rs b/src/libcore/ffi.rs index eda0e7c518c58..0ea4187ccd482 100644 --- a/src/libcore/ffi.rs +++ b/src/libcore/ffi.rs @@ -49,8 +49,10 @@ impl fmt::Debug for c_void { /// Basic implementation of a `va_list`. // The name is WIP, using `VaListImpl` for now. #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), - not(target_arch = "x86_64"), not(target_arch = "asmjs")), + not(target_arch = "x86_64")), all(target_arch = "aarch64", target_os = "ios"), + target_arch = "wasm32", + target_arch = "asmjs", windows))] #[repr(transparent)] #[unstable(feature = "c_variadic", @@ -67,8 +69,10 @@ pub struct VaListImpl<'f> { } #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), - not(target_arch = "x86_64"), not(target_arch = "asmjs")), + not(target_arch = "x86_64")), all(target_arch = "aarch64", target_os = "ios"), + target_arch = "wasm32", + target_arch = "asmjs", windows))] #[unstable(feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ @@ -137,38 +141,6 @@ pub struct VaListImpl<'f> { _marker: PhantomData<&'f mut &'f c_void>, } -/// asm.js ABI implementation of a `va_list`. -// asm.js uses the PNaCl ABI, which specifies that a `va_list` is -// an array of 4 32-bit integers, according to the old PNaCl docs at -// https://web.archive.org/web/20130518054430/https://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Derived-Types -// and clang does the same in `CreatePNaClABIBuiltinVaListDecl` from `lib/AST/ASTContext.cpp` -#[cfg(all(target_arch = "asmjs", not(windows)))] -#[repr(C)] -#[unstable(feature = "c_variadic", - reason = "the `c_variadic` feature has not been properly tested on \ - all supported platforms", - issue = "44930")] -#[lang = "va_list"] -pub struct VaListImpl<'f> { - inner: [crate::mem::MaybeUninit; 4], - _marker: PhantomData<&'f mut &'f c_void>, -} - -#[cfg(all(target_arch = "asmjs", not(windows)))] -#[unstable(feature = "c_variadic", - reason = "the `c_variadic` feature has not been properly tested on \ - all supported platforms", - issue = "44930")] -impl<'f> fmt::Debug for VaListImpl<'f> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe { - write!(f, "va_list* [{:#x}, {:#x}, {:#x}, {:#x}]", - self.inner[0].read(), self.inner[1].read(), - self.inner[2].read(), self.inner[3].read()) - } - } -} - /// A wrapper for a `va_list` #[repr(transparent)] #[derive(Debug)] @@ -178,14 +150,18 @@ impl<'f> fmt::Debug for VaListImpl<'f> { issue = "44930")] pub struct VaList<'a, 'f: 'a> { #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), - not(target_arch = "x86_64"), not(target_arch = "asmjs")), + not(target_arch = "x86_64")), all(target_arch = "aarch64", target_os = "ios"), + target_arch = "wasm32", + target_arch = "asmjs", windows))] inner: VaListImpl<'f>, #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", - target_arch = "x86_64", target_arch = "asmjs"), + target_arch = "x86_64"), any(not(target_arch = "aarch64"), not(target_os = "ios")), + not(target_arch = "wasm32"), + not(target_arch = "asmjs"), not(windows)))] inner: &'a mut VaListImpl<'f>, @@ -193,8 +169,10 @@ pub struct VaList<'a, 'f: 'a> { } #[cfg(any(all(not(target_arch = "aarch64"), not(target_arch = "powerpc"), - not(target_arch = "x86_64"), not(target_arch = "asmjs")), + not(target_arch = "x86_64")), all(target_arch = "aarch64", target_os = "ios"), + target_arch = "wasm32", + target_arch = "asmjs", windows))] #[unstable(feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ @@ -212,8 +190,10 @@ impl<'f> VaListImpl<'f> { } #[cfg(all(any(target_arch = "aarch64", target_arch = "powerpc", - target_arch = "x86_64", target_arch = "asmjs"), + target_arch = "x86_64"), any(not(target_arch = "aarch64"), not(target_os = "ios")), + not(target_arch = "wasm32"), + not(target_arch = "asmjs"), not(windows)))] #[unstable(feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ diff --git a/src/libcore/hint.rs b/src/libcore/hint.rs index ee4be6c915119..368a2f16b281e 100644 --- a/src/libcore/hint.rs +++ b/src/libcore/hint.rs @@ -114,24 +114,8 @@ pub fn black_box(dummy: T) -> T { // this. LLVM's intepretation of inline assembly is that it's, well, a black // box. This isn't the greatest implementation since it probably deoptimizes // more than we want, but it's so far good enough. - #[cfg(not(any( - target_arch = "asmjs", - all( - target_arch = "wasm32", - target_os = "emscripten" - ) - )))] unsafe { asm!("" : : "r"(&dummy)); return dummy; } - - // Not all platforms support inline assembly so try to do something without - // inline assembly which in theory still hinders at least some optimizations - // on those targets. This is the "best effort" scenario. - unsafe { - let ret = crate::ptr::read_volatile(&dummy); - crate::mem::forget(dummy); - ret - } } diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index f9c1be20b8bc1..d22420e76dcd4 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -410,7 +410,7 @@ impl<'a> Parser<'a> { &self.input[start..self.input.len()] } - /// Parses an Argument structure, or what's contained within braces inside the format string + /// Parses an `Argument` structure, or what's contained within braces inside the format string. fn argument(&mut self) -> Argument<'a> { let pos = self.position(); let format = self.format(); @@ -464,7 +464,7 @@ impl<'a> Parser<'a> { } /// Parses a format specifier at the current position, returning all of the - /// relevant information in the FormatSpec struct. + /// relevant information in the `FormatSpec` struct. fn format(&mut self) -> FormatSpec<'a> { let mut spec = FormatSpec { fill: None, @@ -571,7 +571,7 @@ impl<'a> Parser<'a> { spec } - /// Parses a Count parameter at the current position. This does not check + /// Parses a `Count` parameter at the current position. This does not check /// for 'CountIsNextParam' because that is only used in precision, not /// width. fn count(&mut self, start: usize) -> (Count, Option) { diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4310bafd7812a..2238a56b29d04 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -988,10 +988,12 @@ impl<'a> LoweringContext<'a> { // lower attributes (we use the AST version) there is nowhere to keep // the `HirId`s. We don't actually need HIR version of attributes anyway. Attribute { + item: AttrItem { + path: attr.path.clone(), + tokens: self.lower_token_stream(attr.tokens.clone()), + }, id: attr.id, style: attr.style, - path: attr.path.clone(), - tokens: self.lower_token_stream(attr.tokens.clone()), is_sugared_doc: attr.is_sugared_doc, span: attr.span, } diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs index bdcf9e42ac2a8..23a2f115e05e2 100644 --- a/src/librustc/ich/impls_syntax.rs +++ b/src/librustc/ich/impls_syntax.rs @@ -196,6 +196,11 @@ impl<'a> HashStable> for ast::Path { } } +impl_stable_hash_for!(struct ::syntax::ast::AttrItem { + path, + tokens, +}); + impl<'a> HashStable> for ast::Attribute { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { // Make sure that these have been filtered out. @@ -203,19 +208,15 @@ impl<'a> HashStable> for ast::Attribute { debug_assert!(!self.is_sugared_doc); let ast::Attribute { + ref item, id: _, style, - ref path, - ref tokens, is_sugared_doc: _, span, } = *self; + item.hash_stable(hcx, hasher); style.hash_stable(hcx, hasher); - path.hash_stable(hcx, hasher); - for tt in tokens.trees() { - tt.hash_stable(hcx, hasher); - } span.hash_stable(hcx, hasher); } } diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs index 750ca4e32a64e..b06b63455ba4b 100644 --- a/src/librustc/infer/mod.rs +++ b/src/librustc/infer/mod.rs @@ -23,7 +23,7 @@ use crate::ty::relate::RelateResult; use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef}; use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt, InferConst}; use crate::ty::{FloatVid, IntVid, TyVid, ConstVid}; -use crate::util::nodemap::FxHashMap; +use crate::util::nodemap::{FxHashMap, FxHashSet}; use errors::DiagnosticBuilder; use rustc_data_structures::sync::Lrc; @@ -155,6 +155,8 @@ pub struct InferCtxt<'a, 'tcx> { /// avoid reporting the same error twice. pub reported_trait_errors: RefCell>>>, + pub reported_closure_mismatch: RefCell)>>, + /// When an error occurs, we want to avoid reporting "derived" /// errors that are due to this original failure. Normally, we /// handle this with the `err_count_on_creation` count, which @@ -538,6 +540,7 @@ impl<'tcx> InferCtxtBuilder<'tcx> { selection_cache: Default::default(), evaluation_cache: Default::default(), reported_trait_errors: Default::default(), + reported_closure_mismatch: Default::default(), tainted_by_errors_flag: Cell::new(false), err_count_on_creation: tcx.sess.err_count(), in_snapshot: Cell::new(false), diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs index c2d531793372a..956fcdfd2d87c 100644 --- a/src/librustc/traits/error_reporting.rs +++ b/src/librustc/traits/error_reporting.rs @@ -885,6 +885,14 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { self.tcx.hir().span_if_local(did) ).map(|sp| self.tcx.sess.source_map().def_span(sp)); // the sp could be an fn def + if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) { + // We check closures twice, with obligations flowing in different directions, + // but we want to complain about them only once. + return; + } + + self.reported_closure_mismatch.borrow_mut().insert((span, found_span)); + let found = match found_trait_ref.skip_binder().substs.type_at(1).kind { ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()], _ => vec![ArgKind::empty()], diff --git a/src/librustc_codegen_llvm/llvm_util.rs b/src/librustc_codegen_llvm/llvm_util.rs index 541d3d98b79bd..2dce9b04c9e9e 100644 --- a/src/librustc_codegen_llvm/llvm_util.rs +++ b/src/librustc_codegen_llvm/llvm_util.rs @@ -257,8 +257,7 @@ pub fn target_feature_whitelist(sess: &Session) "hexagon" => HEXAGON_WHITELIST, "mips" | "mips64" => MIPS_WHITELIST, "powerpc" | "powerpc64" => POWERPC_WHITELIST, - // wasm32 on emscripten does not support these target features - "wasm32" if !sess.target.target.options.is_like_emscripten => WASM_WHITELIST, + "wasm32" => WASM_WHITELIST, _ => &[], } } diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs index 3c5fbfd0f866f..e0b161f24049b 100644 --- a/src/librustc_codegen_ssa/back/write.rs +++ b/src/librustc_codegen_ssa/back/write.rs @@ -143,15 +143,12 @@ impl ModuleConfig { // Copy what clang does by turning on loop vectorization at O2 and // slp vectorization at O3. Otherwise configure other optimization aspects // of this pass manager builder. - // Turn off vectorization for emscripten, as it's not very well supported. self.vectorize_loop = !sess.opts.cg.no_vectorize_loops && (sess.opts.optimize == config::OptLevel::Default || - sess.opts.optimize == config::OptLevel::Aggressive) && - !sess.target.target.options.is_like_emscripten; + sess.opts.optimize == config::OptLevel::Aggressive); self.vectorize_slp = !sess.opts.cg.no_vectorize_slp && - sess.opts.optimize == config::OptLevel::Aggressive && - !sess.target.target.options.is_like_emscripten; + sess.opts.optimize == config::OptLevel::Aggressive; // Some targets (namely, NVPTX) interact badly with the MergeFunctions // pass. This is because MergeFunctions can generate new function calls diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 2a89c94652a24..0c7aa3582ac23 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -99,8 +99,8 @@ impl Margin { // ``` let mut m = Margin { - whitespace_left: if whitespace_left >= 6 { whitespace_left - 6 } else { 0 }, - span_left: if span_left >= 6 { span_left - 6 } else { 0 }, + whitespace_left: whitespace_left.saturating_sub(6), + span_left: span_left.saturating_sub(6), span_right: span_right + 6, computed_left: 0, computed_right: 0, @@ -125,7 +125,7 @@ impl Margin { } else { self.computed_right }; - right < line_len && line_len > self.computed_left + self.column_width + right < line_len && self.computed_left + self.column_width < line_len } fn compute(&mut self, max_line_len: usize) { @@ -167,12 +167,10 @@ impl Margin { } fn right(&self, line_len: usize) -> usize { - if max(line_len, self.computed_left) - self.computed_left <= self.column_width { - line_len - } else if self.computed_right > line_len { + if line_len.saturating_sub(self.computed_left) <= self.column_width { line_len } else { - self.computed_right + min(line_len, self.computed_right) } } } @@ -297,81 +295,82 @@ pub trait Emitter { source_map: &Option>, span: &mut MultiSpan, always_backtrace: bool) -> bool { - let mut spans_updated = false; + let sm = match source_map { + Some(ref sm) => sm, + None => return false, + }; - if let Some(ref sm) = source_map { - let mut before_after: Vec<(Span, Span)> = vec![]; - let mut new_labels: Vec<(Span, String)> = vec![]; + let mut before_after: Vec<(Span, Span)> = vec![]; + let mut new_labels: Vec<(Span, String)> = vec![]; - // First, find all the spans in <*macros> and point instead at their use site - for sp in span.primary_spans() { - if sp.is_dummy() { + // First, find all the spans in <*macros> and point instead at their use site + for sp in span.primary_spans() { + if sp.is_dummy() { + continue; + } + let call_sp = sm.call_span_if_macro(*sp); + if call_sp != *sp && !always_backtrace { + before_after.push((*sp, call_sp)); + } + let backtrace_len = sp.macro_backtrace().len(); + for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() { + // Only show macro locations that are local + // and display them like a span_note + if trace.def_site_span.is_dummy() { continue; } - let call_sp = sm.call_span_if_macro(*sp); - if call_sp != *sp && !always_backtrace { - before_after.push((*sp, call_sp)); + if always_backtrace { + new_labels.push((trace.def_site_span, + format!("in this expansion of `{}`{}", + trace.macro_decl_name, + if backtrace_len > 2 { + // if backtrace_len == 1 it'll be pointed + // at by "in this macro invocation" + format!(" (#{})", i + 1) + } else { + String::new() + }))); } - let backtrace_len = sp.macro_backtrace().len(); - for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() { - // Only show macro locations that are local - // and display them like a span_note - if trace.def_site_span.is_dummy() { - continue; - } - if always_backtrace { - new_labels.push((trace.def_site_span, - format!("in this expansion of `{}`{}", - trace.macro_decl_name, - if backtrace_len > 2 { - // if backtrace_len == 1 it'll be pointed - // at by "in this macro invocation" - format!(" (#{})", i + 1) - } else { - String::new() - }))); - } - // Check to make sure we're not in any <*macros> - if !sm.span_to_filename(trace.def_site_span).is_macros() && - !trace.macro_decl_name.starts_with("desugaring of ") && - !trace.macro_decl_name.starts_with("#[") || - always_backtrace { - new_labels.push((trace.call_site, - format!("in this macro invocation{}", - if backtrace_len > 2 && always_backtrace { - // only specify order when the macro - // backtrace is multiple levels deep - format!(" (#{})", i + 1) - } else { - String::new() - }))); - if !always_backtrace { - break; - } + // Check to make sure we're not in any <*macros> + if !sm.span_to_filename(trace.def_site_span).is_macros() && + !trace.macro_decl_name.starts_with("desugaring of ") && + !trace.macro_decl_name.starts_with("#[") || + always_backtrace { + new_labels.push((trace.call_site, + format!("in this macro invocation{}", + if backtrace_len > 2 && always_backtrace { + // only specify order when the macro + // backtrace is multiple levels deep + format!(" (#{})", i + 1) + } else { + String::new() + }))); + if !always_backtrace { + break; } } } - for (label_span, label_text) in new_labels { - span.push_span_label(label_span, label_text); + } + for (label_span, label_text) in new_labels { + span.push_span_label(label_span, label_text); + } + for sp_label in span.span_labels() { + if sp_label.span.is_dummy() { + continue; } - for sp_label in span.span_labels() { - if sp_label.span.is_dummy() { - continue; - } - if sm.span_to_filename(sp_label.span.clone()).is_macros() && - !always_backtrace - { - let v = sp_label.span.macro_backtrace(); - if let Some(use_site) = v.last() { - before_after.push((sp_label.span.clone(), use_site.call_site.clone())); - } + if sm.span_to_filename(sp_label.span.clone()).is_macros() && + !always_backtrace + { + let v = sp_label.span.macro_backtrace(); + if let Some(use_site) = v.last() { + before_after.push((sp_label.span.clone(), use_site.call_site.clone())); } } - // After we have them, make sure we replace these 'bad' def sites with their use sites - for (before, after) in before_after { - span.replace(before, after); - spans_updated = true; - } + } + // After we have them, make sure we replace these 'bad' def sites with their use sites + let spans_updated = !before_after.is_empty(); + for (before, after) in before_after { + span.replace(before, after); } spans_updated @@ -593,9 +592,9 @@ impl EmitterWriter { let left = margin.left(source_string.len()); // Left trim // Account for unicode characters of width !=0 that were removed. - let left = source_string.chars().take(left).fold(0, |acc, ch| { - acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1) - }); + let left = source_string.chars().take(left) + .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) + .sum(); self.draw_line( buffer, @@ -623,18 +622,16 @@ impl EmitterWriter { // 3 | | // 4 | | } // | |_^ test - if line.annotations.len() == 1 { - if let Some(ref ann) = line.annotations.get(0) { - if let AnnotationType::MultilineStart(depth) = ann.annotation_type { - if source_string.chars().take(ann.start_col).all(|c| c.is_whitespace()) { - let style = if ann.is_primary { - Style::UnderlinePrimary - } else { - Style::UnderlineSecondary - }; - buffer.putc(line_offset, width_offset + depth - 1, '/', style); - return vec![(depth, style)]; - } + if let [ann] = &line.annotations[..] { + if let AnnotationType::MultilineStart(depth) = ann.annotation_type { + if source_string.chars().take(ann.start_col).all(|c| c.is_whitespace()) { + let style = if ann.is_primary { + Style::UnderlinePrimary + } else { + Style::UnderlineSecondary + }; + buffer.putc(line_offset, width_offset + depth - 1, '/', style); + return vec![(depth, style)]; } } } @@ -763,11 +760,7 @@ impl EmitterWriter { annotations_position.push((p, annotation)); for (j, next) in annotations.iter().enumerate() { if j > i { - let l = if let Some(ref label) = next.label { - label.len() + 2 - } else { - 0 - }; + let l = next.label.as_ref().map_or(0, |label| label.len() + 2); if (overlaps(next, annotation, l) // Do not allow two labels to be in the same // line if they overlap including padding, to // avoid situations like: @@ -797,9 +790,7 @@ impl EmitterWriter { } } } - if line_len < p { - line_len = p; - } + line_len = max(line_len, p); } if line_len != 0 { @@ -941,17 +932,9 @@ impl EmitterWriter { Style::LabelSecondary }; let (pos, col) = if pos == 0 { - (pos + 1, if annotation.end_col + 1 > left { - annotation.end_col + 1 - left - } else { - 0 - }) + (pos + 1, (annotation.end_col + 1).saturating_sub(left)) } else { - (pos + 2, if annotation.start_col > left { - annotation.start_col - left - } else { - 0 - }) + (pos + 2, annotation.start_col.saturating_sub(left)) }; if let Some(ref label) = annotation.label { buffer.puts(line_offset + pos, code_offset + col, &label, style); @@ -966,9 +949,9 @@ impl EmitterWriter { // | | | // | | something about `foo` // | something about `fn foo()` - annotations_position.sort_by(|a, b| { - // Decreasing order. When `a` and `b` are the same length, prefer `Primary`. - (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse() + annotations_position.sort_by_key(|(_, ann)| { + // Decreasing order. When annotations share the same length, prefer `Primary`. + (Reverse(ann.len()), ann.is_primary) }); // Write the underlines. @@ -991,11 +974,7 @@ impl EmitterWriter { for p in annotation.start_col..annotation.end_col { buffer.putc( line_offset + 1, - if code_offset + p > left { - code_offset + p - left - } else { - 0 - }, + (code_offset + p).saturating_sub(left), underline, style, ); @@ -1018,40 +997,36 @@ impl EmitterWriter { } fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize { + let sm = match self.sm { + Some(ref sm) => sm, + None => return 0, + }; + let mut max = 0; - if let Some(ref sm) = self.sm { - for primary_span in msp.primary_spans() { - if !primary_span.is_dummy() { - let hi = sm.lookup_char_pos(primary_span.hi()); - if hi.line > max { - max = hi.line; - } - } + for primary_span in msp.primary_spans() { + if !primary_span.is_dummy() { + let hi = sm.lookup_char_pos(primary_span.hi()); + max = (hi.line).max(max); } - if !self.short_message { - for span_label in msp.span_labels() { - if !span_label.span.is_dummy() { - let hi = sm.lookup_char_pos(span_label.span.hi()); - if hi.line > max { - max = hi.line; - } - } + } + if !self.short_message { + for span_label in msp.span_labels() { + if !span_label.span.is_dummy() { + let hi = sm.lookup_char_pos(span_label.span.hi()); + max = (hi.line).max(max); } } } + max } fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize { - let primary = self.get_multispan_max_line_num(span); - let mut max = primary; - - for sub in children { - let sub_result = self.get_multispan_max_line_num(&sub.span); - max = std::cmp::max(sub_result, max); - } - max + children.iter() + .map(|sub| self.get_multispan_max_line_num(&sub.span)) + .max() + .unwrap_or(primary) } /// Adds a left margin to every line but the first, given a padding length and the label being @@ -1081,14 +1056,12 @@ impl EmitterWriter { // `max_line_num_len` let padding = " ".repeat(padding + label.len() + 5); - /// Returns `true` if `style`, or the override if present and the style is `NoStyle`. - fn style_or_override(style: Style, override_style: Option