about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--CONTRIBUTING.md6
-rw-r--r--Cargo.lock59
-rw-r--r--src/doc/rustc/src/lints/listing/warn-by-default.md12
-rw-r--r--src/doc/unstable-book/src/language-features/cfg-sanitize.md36
-rw-r--r--src/doc/unstable-book/src/language-features/plugin.md7
-rwxr-xr-x[-rw-r--r--]src/etc/dec2flt_table.py15
-rw-r--r--src/liballoc/alloc/tests.rs6
-rw-r--r--src/liballoc/benches/btree/map.rs38
-rw-r--r--src/liballoc/benches/slice.rs63
-rw-r--r--src/liballoc/benches/str.rs35
-rw-r--r--src/liballoc/benches/vec_deque.rs2
-rw-r--r--src/liballoc/benches/vec_deque_append.rs5
-rw-r--r--src/liballoc/collections/btree/mod.rs2
-rw-r--r--src/liballoc/collections/btree/search.rs42
-rw-r--r--src/liballoc/collections/linked_list/tests.rs17
-rw-r--r--src/liballoc/collections/vec_deque/tests.rs12
-rw-r--r--src/liballoc/fmt.rs22
-rw-r--r--src/liballoc/prelude/v1.rs12
-rw-r--r--src/liballoc/raw_vec/tests.rs9
-rw-r--r--src/liballoc/slice.rs173
-rw-r--r--src/liballoc/tests.rs6
-rw-r--r--src/liballoc/tests/arc.rs39
-rw-r--r--src/liballoc/tests/binary_heap.rs5
-rw-r--r--src/liballoc/tests/boxed.rs2
-rw-r--r--src/liballoc/tests/btree/mod.rs7
-rw-r--r--src/liballoc/tests/linked_list.rs75
-rw-r--r--src/liballoc/tests/rc.rs41
-rw-r--r--src/liballoc/tests/slice.rs28
-rw-r--r--src/liballoc/tests/vec.rs5
-rw-r--r--src/liballoc/tests/vec_deque.rs166
-rw-r--r--src/liballoc/vec.rs3
-rw-r--r--src/libcore/any.rs2
-rw-r--r--src/libcore/intrinsics.rs4
-rw-r--r--src/libcore/num/dec2flt/table.rs2456
-rw-r--r--src/libcore/num/f32.rs2
-rw-r--r--src/libcore/num/f64.rs2
-rw-r--r--src/libcore/panic.rs12
-rw-r--r--src/libcore/panicking.rs9
-rw-r--r--src/libcore/ptr/mod.rs38
-rw-r--r--src/libcore/sync/atomic.rs74
-rw-r--r--src/libcore/tests/num/bignum.rs1
-rw-r--r--src/libcore/tests/num/flt2dec/mod.rs1
-rw-r--r--src/libcore/tests/num/flt2dec/strategy/dragon.rs1
-rwxr-xr-x[-rw-r--r--]src/libcore/unicode/printable.py6
-rw-r--r--src/libcore/unicode/printable.rs9
-rw-r--r--src/libcore/unicode/tables.rs29
-rwxr-xr-xsrc/libcore/unicode/unicode.py36
-rw-r--r--src/libfmt_macros/lib.rs33
-rw-r--r--src/libpanic_unwind/lib.rs16
-rw-r--r--src/libpanic_unwind/miri.rs42
-rw-r--r--src/librustc/Cargo.toml1
-rw-r--r--src/librustc/arena.rs3
-rw-r--r--src/librustc/hir/map/mod.rs10
-rw-r--r--src/librustc/ich/impls_syntax.rs3
-rw-r--r--src/librustc/infer/error_reporting/mod.rs16
-rw-r--r--src/librustc/infer/error_reporting/nice_region_error/placeholder_error.rs8
-rw-r--r--src/librustc/infer/mod.rs2
-rw-r--r--src/librustc/lib.rs2
-rw-r--r--src/librustc/lint/context.rs12
-rw-r--r--src/librustc/lint/levels.rs6
-rw-r--r--src/librustc/middle/cstore.rs12
-rw-r--r--src/librustc/middle/mem_categorization.rs1508
-rw-r--r--src/librustc/middle/stability.rs24
-rw-r--r--src/librustc/mir/interpret/error.rs48
-rw-r--r--src/librustc/mir/interpret/mod.rs5
-rw-r--r--src/librustc/mir/mod.rs47
-rw-r--r--src/librustc/mir/visit.rs3
-rw-r--r--src/librustc/query/mod.rs2
-rw-r--r--src/librustc/session/config.rs23
-rw-r--r--src/librustc/session/mod.rs17
-rw-r--r--src/librustc/traits/coherence.rs48
-rw-r--r--src/librustc/traits/error_reporting.rs172
-rw-r--r--src/librustc/traits/select.rs4
-rw-r--r--src/librustc/traits/specialize/mod.rs2
-rw-r--r--src/librustc/traits/specialize/specialization_graph.rs2
-rw-r--r--src/librustc/ty/context.rs24
-rw-r--r--src/librustc/ty/layout.rs9
-rw-r--r--src/librustc/ty/print/pretty.rs44
-rw-r--r--src/librustc/ty/query/mod.rs1
-rw-r--r--src/librustc/ty/structural_impls.rs13
-rw-r--r--src/librustc/ty/sty.rs51
-rw-r--r--src/librustc/ty/util.rs17
-rw-r--r--src/librustc_codegen_llvm/back/lto.rs2
-rw-r--r--src/librustc_codegen_llvm/back/write.rs20
-rw-r--r--src/librustc_codegen_llvm/lib.rs1
-rw-r--r--src/librustc_codegen_llvm/llvm/ffi.rs3
-rw-r--r--src/librustc_codegen_llvm/llvm_util.rs4
-rw-r--r--src/librustc_codegen_ssa/back/write.rs3
-rw-r--r--src/librustc_codegen_ssa/mir/block.rs15
-rw-r--r--src/librustc_driver/Cargo.toml1
-rw-r--r--src/librustc_driver/lib.rs235
-rw-r--r--src/librustc_error_codes/error_codes.rs3
-rw-r--r--src/librustc_error_codes/error_codes/E0080.md12
-rw-r--r--src/librustc_error_codes/error_codes/E0081.md18
-rw-r--r--src/librustc_error_codes/error_codes/E0091.md5
-rw-r--r--src/librustc_error_codes/error_codes/E0203.md18
-rw-r--r--src/librustc_errors/emitter.rs6
-rw-r--r--src/librustc_feature/Cargo.toml15
-rw-r--r--src/librustc_feature/accepted.rs (renamed from src/libsyntax/feature_gate/accepted.rs)2
-rw-r--r--src/librustc_feature/active.rs (renamed from src/libsyntax/feature_gate/active.rs)22
-rw-r--r--src/librustc_feature/builtin_attrs.rs (renamed from src/libsyntax/feature_gate/builtin_attrs.rs)74
-rw-r--r--src/librustc_feature/lib.rs137
-rw-r--r--src/librustc_feature/removed.rs (renamed from src/libsyntax/feature_gate/removed.rs)2
-rw-r--r--src/librustc_interface/interface.rs3
-rw-r--r--src/librustc_interface/lib.rs1
-rw-r--r--src/librustc_interface/passes.rs151
-rw-r--r--src/librustc_interface/queries.rs211
-rw-r--r--src/librustc_interface/tests.rs4
-rw-r--r--src/librustc_lint/Cargo.toml1
-rw-r--r--src/librustc_lint/builtin.rs50
-rw-r--r--src/librustc_lint/lib.rs3
-rw-r--r--src/librustc_lint/unused.rs5
-rw-r--r--src/librustc_metadata/creader.rs302
-rw-r--r--src/librustc_metadata/cstore.rs99
-rw-r--r--src/librustc_metadata/dependency_format.rs6
-rw-r--r--src/librustc_metadata/lib.rs3
-rw-r--r--src/librustc_metadata/locator.rs31
-rw-r--r--src/librustc_metadata/native_libs.rs36
-rw-r--r--src/librustc_metadata/rmeta/decoder.rs105
-rw-r--r--src/librustc_metadata/rmeta/decoder/cstore_impl.rs37
-rw-r--r--src/librustc_metadata/rmeta/encoder.rs3
-rw-r--r--src/librustc_metadata/rmeta/mod.rs24
-rw-r--r--src/librustc_mir/borrow_check/conflict_errors.rs18
-rw-r--r--src/librustc_mir/borrow_check/mod.rs67
-rw-r--r--src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs15
-rw-r--r--src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs83
-rw-r--r--src/librustc_mir/build/matches/test.rs8
-rw-r--r--src/librustc_mir/build/mod.rs24
-rw-r--r--src/librustc_mir/build/scope.rs63
-rw-r--r--src/librustc_mir/const_eval.rs11
-rw-r--r--src/librustc_mir/hair/cx/expr.rs9
-rw-r--r--src/librustc_mir/hair/pattern/_match.rs126
-rw-r--r--src/librustc_mir/interpret/eval_context.rs6
-rw-r--r--src/librustc_mir/interpret/intern.rs2
-rw-r--r--src/librustc_mir/interpret/intrinsics/caller_location.rs2
-rw-r--r--src/librustc_mir/interpret/memory.rs10
-rw-r--r--src/librustc_mir/interpret/place.rs38
-rw-r--r--src/librustc_mir/interpret/terminator.rs39
-rw-r--r--src/librustc_mir/lib.rs1
-rw-r--r--src/librustc_mir/shim.rs62
-rw-r--r--src/librustc_mir/transform/check_consts/ops.rs48
-rw-r--r--src/librustc_mir/transform/check_consts/qualifs.rs37
-rw-r--r--src/librustc_mir/transform/check_consts/validation.rs195
-rw-r--r--src/librustc_mir/transform/check_unsafety.rs33
-rw-r--r--src/librustc_mir/transform/const_prop.rs87
-rw-r--r--src/librustc_mir/transform/generator.rs19
-rw-r--r--src/librustc_mir/transform/inline.rs5
-rw-r--r--src/librustc_mir/transform/promote_consts.rs106
-rw-r--r--src/librustc_mir/transform/qualify_min_const_fn.rs2
-rw-r--r--src/librustc_mir/transform/simplify_try.rs8
-rw-r--r--src/librustc_parse/Cargo.toml1
-rw-r--r--src/librustc_parse/config.rs14
-rw-r--r--src/librustc_parse/validate_attr.rs18
-rw-r--r--src/librustc_passes/Cargo.toml1
-rw-r--r--src/librustc_passes/ast_validation.rs3
-rw-r--r--src/librustc_passes/check_const.rs11
-rw-r--r--src/librustc_plugin_impl/lib.rs16
-rw-r--r--src/librustc_plugin_impl/load.rs164
-rw-r--r--src/librustc_plugin_impl/registry.rs70
-rw-r--r--src/librustc_privacy/lib.rs2
-rw-r--r--src/librustc_resolve/Cargo.toml1
-rw-r--r--src/librustc_resolve/build_reduced_graph.rs6
-rw-r--r--src/librustc_resolve/diagnostics.rs2
-rw-r--r--src/librustc_resolve/lib.rs3
-rw-r--r--src/librustc_resolve/macros.rs15
-rw-r--r--src/librustc_target/abi/call/mod.rs2
-rw-r--r--src/librustc_typeck/astconv.rs17
-rw-r--r--src/librustc_typeck/check/coercion.rs12
-rw-r--r--src/librustc_typeck/check/generator_interior.rs13
-rw-r--r--src/librustc_typeck/check/method/suggest.rs2
-rw-r--r--src/librustc_typeck/check/mod.rs38
-rw-r--r--src/librustc_typeck/check/regionck.rs269
-rw-r--r--src/librustc_typeck/check/upvar.rs237
-rw-r--r--src/librustc_typeck/check/wfcheck.rs6
-rw-r--r--src/librustc_typeck/coherence/unsafety.rs4
-rw-r--r--src/librustc_typeck/collect.rs26
-rw-r--r--src/librustc_typeck/expr_use_visitor.rs (renamed from src/librustc/middle/expr_use_visitor.rs)193
-rw-r--r--src/librustc_typeck/lib.rs4
-rw-r--r--src/librustc_typeck/mem_categorization.rs707
-rw-r--r--src/librustdoc/clean/cfg.rs2
-rw-r--r--src/librustdoc/clean/inline.rs2
-rw-r--r--src/librustdoc/core.rs23
-rw-r--r--src/librustdoc/externalfiles.rs2
-rw-r--r--src/librustdoc/html/render.rs2
-rw-r--r--src/librustdoc/lib.rs1
-rw-r--r--src/librustdoc/markdown.rs2
-rw-r--r--src/librustdoc/passes/collect_intra_doc_links.rs2
-rw-r--r--src/librustdoc/test.rs18
-rw-r--r--src/libstd/ascii.rs2
-rw-r--r--src/libstd/backtrace.rs4
-rw-r--r--src/libstd/benches/hash/map.rs2
-rw-r--r--src/libstd/collections/mod.rs10
-rw-r--r--src/libstd/env.rs171
-rw-r--r--src/libstd/f32.rs82
-rw-r--r--src/libstd/f64.rs78
-rw-r--r--src/libstd/ffi/mod.rs18
-rw-r--r--src/libstd/fs.rs335
-rw-r--r--src/libstd/io/buffered.rs147
-rw-r--r--src/libstd/io/error.rs65
-rw-r--r--src/libstd/io/impls.rs64
-rw-r--r--src/libstd/io/mod.rs168
-rw-r--r--src/libstd/io/prelude.rs2
-rw-r--r--src/libstd/io/util.rs52
-rw-r--r--src/libstd/lib.rs1
-rw-r--r--src/libstd/macros.rs7
-rw-r--r--src/libstd/net/addr.rs91
-rw-r--r--src/libstd/net/parser.rs75
-rw-r--r--src/libstd/net/tcp.rs239
-rw-r--r--src/libstd/net/test.rs29
-rw-r--r--src/libstd/net/udp.rs72
-rw-r--r--src/libstd/num.rs119
-rw-r--r--src/libstd/os/android/fs.rs13
-rw-r--r--src/libstd/os/android/mod.rs2
-rw-r--r--src/libstd/os/android/raw.rs26
-rw-r--r--src/libstd/os/dragonfly/fs.rs13
-rw-r--r--src/libstd/os/dragonfly/mod.rs2
-rw-r--r--src/libstd/os/dragonfly/raw.rs39
-rw-r--r--src/libstd/os/emscripten/fs.rs13
-rw-r--r--src/libstd/os/emscripten/mod.rs2
-rw-r--r--src/libstd/os/emscripten/raw.rs36
-rw-r--r--src/libstd/os/fortanix_sgx/mod.rs19
-rw-r--r--src/libstd/os/freebsd/fs.rs13
-rw-r--r--src/libstd/os/freebsd/mod.rs2
-rw-r--r--src/libstd/os/freebsd/raw.rs39
-rw-r--r--src/libstd/os/fuchsia/mod.rs2
-rw-r--r--src/libstd/os/fuchsia/raw.rs117
-rw-r--r--src/libstd/os/haiku/fs.rs13
-rw-r--r--src/libstd/os/haiku/mod.rs2
-rw-r--r--src/libstd/os/haiku/raw.rs32
-rw-r--r--src/libstd/os/ios/fs.rs13
-rw-r--r--src/libstd/os/ios/mod.rs2
-rw-r--r--src/libstd/os/ios/raw.rs36
-rw-r--r--src/libstd/os/linux/fs.rs10
-rw-r--r--src/libstd/os/linux/mod.rs2
-rw-r--r--src/libstd/os/linux/raw.rs147
-rw-r--r--src/libstd/os/macos/fs.rs13
-rw-r--r--src/libstd/os/macos/mod.rs2
-rw-r--r--src/libstd/os/macos/raw.rs36
-rw-r--r--src/libstd/os/mod.rs45
-rw-r--r--src/libstd/os/netbsd/fs.rs13
-rw-r--r--src/libstd/os/netbsd/mod.rs2
-rw-r--r--src/libstd/os/netbsd/raw.rs41
-rw-r--r--src/libstd/os/openbsd/fs.rs13
-rw-r--r--src/libstd/os/openbsd/mod.rs2
-rw-r--r--src/libstd/os/openbsd/raw.rs39
-rw-r--r--src/libstd/os/raw/mod.rs170
-rw-r--r--src/libstd/os/redox/fs.rs13
-rw-r--r--src/libstd/os/redox/mod.rs2
-rw-r--r--src/libstd/os/redox/raw.rs42
-rw-r--r--src/libstd/os/solaris/fs.rs13
-rw-r--r--src/libstd/os/solaris/mod.rs2
-rw-r--r--src/libstd/os/solaris/raw.rs43
-rw-r--r--src/libstd/os/vxworks/mod.rs2
-rw-r--r--src/libstd/os/vxworks/raw.rs2
-rw-r--r--src/libstd/panic.rs44
-rw-r--r--src/libstd/panicking.rs48
-rw-r--r--src/libstd/path.rs1628
-rw-r--r--src/libstd/prelude/v1.rs58
-rw-r--r--src/libstd/process.rs219
-rw-r--r--src/libstd/rt.rs26
-rw-r--r--src/libstd/sync/barrier.rs22
-rw-r--r--src/libstd/sync/mpsc/blocking.rs17
-rw-r--r--src/libstd/sync/mpsc/cache_aligned.rs14
-rw-r--r--src/libstd/sync/mpsc/mod.rs510
-rw-r--r--src/libstd/sync/mpsc/mpsc_queue.rs28
-rw-r--r--src/libstd/sync/mpsc/oneshot.rs56
-rw-r--r--src/libstd/sync/mpsc/shared.rs57
-rw-r--r--src/libstd/sync/mpsc/spsc_queue.rs47
-rw-r--r--src/libstd/sync/mpsc/stream.rs112
-rw-r--r--src/libstd/sync/mpsc/sync.rs121
-rw-r--r--src/libstd/sys/cloudabi/os.rs4
-rw-r--r--src/libstd/sys/cloudabi/shims/fs.rs2
-rw-r--r--src/libstd/sys/cloudabi/shims/mod.rs7
-rw-r--r--src/libstd/sys/cloudabi/shims/net.rs4
-rw-r--r--src/libstd/sys/cloudabi/shims/process.rs4
-rw-r--r--src/libstd/sys/cloudabi/thread.rs10
-rw-r--r--src/libstd/sys/cloudabi/time.rs30
-rw-r--r--src/libstd/sys/hermit/alloc.rs6
-rw-r--r--src/libstd/sys/hermit/args.rs45
-rw-r--r--src/libstd/sys/hermit/cmath.rs2
-rw-r--r--src/libstd/sys/hermit/condvar.rs4
-rw-r--r--src/libstd/sys/hermit/fd.rs10
-rw-r--r--src/libstd/sys/hermit/fs.rs84
-rw-r--r--src/libstd/sys/hermit/mod.rs46
-rw-r--r--src/libstd/sys/hermit/mutex.rs6
-rw-r--r--src/libstd/sys/hermit/net.rs19
-rw-r--r--src/libstd/sys/hermit/os.rs49
-rw-r--r--src/libstd/sys/hermit/path.rs2
-rw-r--r--src/libstd/sys/hermit/pipe.rs5
-rw-r--r--src/libstd/sys/hermit/process.rs29
-rw-r--r--src/libstd/sys/hermit/rwlock.rs6
-rw-r--r--src/libstd/sys/hermit/stack_overflow.rs6
-rw-r--r--src/libstd/sys/hermit/stdio.rs17
-rw-r--r--src/libstd/sys/hermit/thread.rs42
-rw-r--r--src/libstd/sys/hermit/thread_local.rs8
-rw-r--r--src/libstd/sys/hermit/time.rs45
-rw-r--r--src/libstd/sys/sgx/abi/mod.rs18
-rw-r--r--src/libstd/sys/sgx/abi/panic.rs12
-rw-r--r--src/libstd/sys/sgx/abi/reloc.rs12
-rw-r--r--src/libstd/sys/sgx/abi/thread.rs4
-rw-r--r--src/libstd/sys/sgx/abi/tls.rs29
-rw-r--r--src/libstd/sys/sgx/abi/usercalls/alloc.rs99
-rw-r--r--src/libstd/sys/sgx/abi/usercalls/mod.rs67
-rw-r--r--src/libstd/sys/sgx/abi/usercalls/raw.rs32
-rw-r--r--src/libstd/sys/sgx/args.rs13
-rw-r--r--src/libstd/sys/sgx/cmath.rs2
-rw-r--r--src/libstd/sys/sgx/ext/io.rs10
-rw-r--r--src/libstd/sys/sgx/ext/mod.rs2
-rw-r--r--src/libstd/sys/sgx/fd.rs10
-rw-r--r--src/libstd/sys/sgx/fs.rs28
-rw-r--r--src/libstd/sys/sgx/net.rs81
-rw-r--r--src/libstd/sys/sgx/os.rs27
-rw-r--r--src/libstd/sys/sgx/path.rs2
-rw-r--r--src/libstd/sys/sgx/process.rs29
-rw-r--r--src/libstd/sys/sgx/stack_overflow.rs6
-rw-r--r--src/libstd/sys/sgx/stdio.rs14
-rw-r--r--src/libstd/sys/sgx/thread.rs16
-rw-r--r--src/libstd/sys/sgx/thread_local.rs4
-rw-r--r--src/libstd/sys/sgx/time.rs5
-rw-r--r--src/libstd/sys/unix/alloc.rs20
-rw-r--r--src/libstd/sys/unix/android.rs51
-rw-r--r--src/libstd/sys/unix/args.rs36
-rw-r--r--src/libstd/sys/unix/cmath.rs4
-rw-r--r--src/libstd/sys/unix/ext/fs.rs108
-rw-r--r--src/libstd/sys/unix/ext/io.rs26
-rw-r--r--src/libstd/sys/unix/ext/mod.rs6
-rw-r--r--src/libstd/sys/unix/ext/net.rs434
-rw-r--r--src/libstd/sys/unix/ext/process.rs19
-rw-r--r--src/libstd/sys/unix/ext/raw.rs25
-rw-r--r--src/libstd/sys/unix/fast_thread_local.rs40
-rw-r--r--src/libstd/sys/unix/fd.rs131
-rw-r--r--src/libstd/sys/unix/io.rs24
-rw-r--r--src/libstd/sys/unix/l4re.rs74
-rw-r--r--src/libstd/sys/unix/memchr.rs23
-rw-r--r--src/libstd/sys/unix/net.rs112
-rw-r--r--src/libstd/sys/unix/path.rs2
-rw-r--r--src/libstd/sys/unix/pipe.rs38
-rw-r--r--src/libstd/sys/unix/process/process_common.rs64
-rw-r--r--src/libstd/sys/unix/process/process_fuchsia.rs102
-rw-r--r--src/libstd/sys/unix/process/zircon.rs173
-rw-r--r--src/libstd/sys/unix/rand.rs63
-rw-r--r--src/libstd/sys/unix/stack_overflow.rs87
-rw-r--r--src/libstd/sys/unix/stdio.rs14
-rw-r--r--src/libstd/sys/unix/thread.rs172
-rw-r--r--src/libstd/sys/unix/thread_local.rs2
-rw-r--r--src/libstd/sys/unix/weak.rs6
-rw-r--r--src/libstd/sys/vxworks/alloc.rs10
-rw-r--r--src/libstd/sys/vxworks/args.rs47
-rw-r--r--src/libstd/sys/vxworks/cmath.rs4
-rw-r--r--src/libstd/sys/vxworks/condvar.rs19
-rw-r--r--src/libstd/sys/vxworks/ext/fs.rs94
-rw-r--r--src/libstd/sys/vxworks/ext/io.rs40
-rw-r--r--src/libstd/sys/vxworks/ext/mod.rs17
-rw-r--r--src/libstd/sys/vxworks/ext/process.rs13
-rw-r--r--src/libstd/sys/vxworks/fast_thread_local.rs2
-rw-r--r--src/libstd/sys/vxworks/fd.rs81
-rw-r--r--src/libstd/sys/vxworks/fs.rs216
-rw-r--r--src/libstd/sys/vxworks/io.rs24
-rw-r--r--src/libstd/sys/vxworks/memchr.rs9
-rw-r--r--src/libstd/sys/vxworks/mod.rs22
-rw-r--r--src/libstd/sys/vxworks/mutex.rs12
-rw-r--r--src/libstd/sys/vxworks/net.rs113
-rw-r--r--src/libstd/sys/vxworks/path.rs2
-rw-r--r--src/libstd/sys/vxworks/pipe.rs35
-rw-r--r--src/libstd/sys/vxworks/process/mod.rs2
-rw-r--r--src/libstd/sys/vxworks/process/process_common.rs58
-rw-r--r--src/libstd/sys/vxworks/rand.rs7
-rw-r--r--src/libstd/sys/vxworks/rwlock.rs18
-rw-r--r--src/libstd/sys/vxworks/stack_overflow.rs13
-rw-r--r--src/libstd/sys/vxworks/stdio.rs12
-rw-r--r--src/libstd/sys/vxworks/thread.rs43
-rw-r--r--src/libstd/sys/vxworks/thread_local.rs2
-rw-r--r--src/libstd/sys/vxworks/time.rs81
-rw-r--r--src/libstd/sys/vxworks/weak.rs8
-rw-r--r--src/libstd/sys/wasi/alloc.rs2
-rw-r--r--src/libstd/sys/wasi/ext/mod.rs18
-rw-r--r--src/libstd/sys/wasi/net.rs55
-rw-r--r--src/libstd/sys/wasi/os.rs42
-rw-r--r--src/libstd/sys/wasi/path.rs2
-rw-r--r--src/libstd/sys/wasi/pipe.rs5
-rw-r--r--src/libstd/sys/wasi/process.rs31
-rw-r--r--src/libstd/sys/wasm/alloc.rs4
-rw-r--r--src/libstd/sys/wasm/args.rs8
-rw-r--r--src/libstd/sys/wasm/cmath.rs2
-rw-r--r--src/libstd/sys/wasm/condvar_atomics.rs2
-rw-r--r--src/libstd/sys/wasm/fs.rs28
-rw-r--r--src/libstd/sys/wasm/mutex_atomics.rs4
-rw-r--r--src/libstd/sys/wasm/net.rs21
-rw-r--r--src/libstd/sys/wasm/os.rs6
-rw-r--r--src/libstd/sys/wasm/path.rs2
-rw-r--r--src/libstd/sys/wasm/pipe.rs5
-rw-r--r--src/libstd/sys/wasm/process.rs29
-rw-r--r--src/libstd/sys/wasm/stack_overflow.rs6
-rw-r--r--src/libstd/sys/wasm/thread.rs16
-rw-r--r--src/libstd/sys/wasm/thread_local.rs2
-rw-r--r--src/libstd/sys/wasm/time.rs3
-rw-r--r--src/libstd/sys/windows/alloc.rs16
-rw-r--r--src/libstd/sys/windows/args.rs56
-rw-r--r--src/libstd/sys/windows/cmath.rs6
-rw-r--r--src/libstd/sys/windows/compat.rs3
-rw-r--r--src/libstd/sys/windows/ext/ffi.rs4
-rw-r--r--src/libstd/sys/windows/ext/fs.rs65
-rw-r--r--src/libstd/sys/windows/ext/io.rs6
-rw-r--r--src/libstd/sys/windows/ext/mod.rs23
-rw-r--r--src/libstd/sys/windows/ext/process.rs4
-rw-r--r--src/libstd/sys/windows/ext/raw.rs9
-rw-r--r--src/libstd/sys/windows/ext/thread.rs6
-rw-r--r--src/libstd/sys/windows/fs.rs361
-rw-r--r--src/libstd/sys/windows/handle.rs104
-rw-r--r--src/libstd/sys/windows/io.rs17
-rw-r--r--src/libstd/sys/windows/os.rs144
-rw-r--r--src/libstd/sys/windows/os_str.rs13
-rw-r--r--src/libstd/sys/windows/path.rs9
-rw-r--r--src/libstd/sys/windows/pipe.rs99
-rw-r--r--src/libstd/sys/windows/rand.rs23
-rw-r--r--src/libstd/sys/windows/stack_overflow.rs5
-rw-r--r--src/libstd/sys/windows/stdio.rs72
-rw-r--r--src/libstd/sys/windows/stdio_uwp.rs7
-rw-r--r--src/libstd/sys/windows/thread.rs54
-rw-r--r--src/libstd/sys/windows/thread_local.rs25
-rw-r--r--src/libstd/sys_common/alloc.rs30
-rw-r--r--src/libstd/sys_common/bytestring.rs4
-rw-r--r--src/libstd/sys_common/fs.rs14
-rw-r--r--src/libstd/sys_common/io.rs2
-rw-r--r--src/libstd/sys_common/net.rs256
-rw-r--r--src/libstd/sys_common/os_str_bytes.rs15
-rw-r--r--src/libstd/sys_common/poison.rs44
-rw-r--r--src/libstd/sys_common/process.rs14
-rw-r--r--src/libstd/sys_common/thread_info.rs28
-rw-r--r--src/libstd/sys_common/util.rs10
-rw-r--r--src/libstd/sys_common/wtf8.rs243
-rw-r--r--src/libstd/tests/env.rs15
-rw-r--r--src/libstd/thread/local.rs103
-rw-r--r--src/libsyntax/Cargo.toml1
-rw-r--r--src/libsyntax/attr/builtin.rs57
-rw-r--r--src/libsyntax/expand/allocator.rs6
-rw-r--r--src/libsyntax/feature_gate/check.rs126
-rw-r--r--src/libsyntax/feature_gate/mod.rs71
-rw-r--r--src/libsyntax/lib.rs5
-rw-r--r--src/libsyntax/sess.rs4
-rw-r--r--src/libsyntax_expand/Cargo.toml1
-rw-r--r--src/libsyntax_expand/expand.rs33
-rw-r--r--src/libsyntax_expand/mbe/macro_rules.rs2
-rw-r--r--src/libsyntax_ext/Cargo.toml1
-rw-r--r--src/libsyntax_ext/test_harness.rs2
-rw-r--r--src/libsyntax_ext/util.rs2
-rw-r--r--src/libsyntax_pos/symbol.rs2
-rw-r--r--src/libtest/test_result.rs32
-rw-r--r--src/libtest/tests.rs47
-rw-r--r--src/rustllvm/PassWrapper.cpp11
-rw-r--r--src/test/codegen/function-arguments.rs4
-rw-r--r--src/test/mir-opt/inline-closure-borrows-arg.rs6
-rw-r--r--src/test/mir-opt/inline-closure-captures.rs6
-rw-r--r--src/test/mir-opt/inline-closure.rs6
-rw-r--r--src/test/mir-opt/retag.rs2
-rw-r--r--src/test/mir-opt/simplify-arm-identity.rs75
-rw-r--r--src/test/run-make-fulldeps/glibc-staticlib-args/Makefile12
-rw-r--r--src/test/run-make-fulldeps/glibc-staticlib-args/library.rs4
-rw-r--r--src/test/run-make-fulldeps/glibc-staticlib-args/program.c7
-rw-r--r--src/test/run-make-fulldeps/issue-19371/foo.rs7
-rw-r--r--src/test/ui-fulldeps/auxiliary/llvm-pass-plugin.rs19
-rw-r--r--src/test/ui-fulldeps/feature-gate-plugin.rs (renamed from src/test/ui/feature-gates/feature-gate-plugin.rs)5
-rw-r--r--src/test/ui-fulldeps/feature-gate-plugin.stderr (renamed from src/test/ui/feature-gates/feature-gate-plugin.stderr)12
-rw-r--r--src/test/ui-fulldeps/lint-plugin-cmdline-load.rs6
-rw-r--r--src/test/ui-fulldeps/lint-plugin-cmdline-load.stderr8
-rw-r--r--src/test/ui-fulldeps/llvm-pass-plugin.rs8
-rw-r--r--src/test/ui-fulldeps/llvm-pass-plugin.stderr8
-rw-r--r--src/test/ui-fulldeps/macro-crate-multi-decorator.rs7
-rw-r--r--src/test/ui-fulldeps/plugin-args-1.rs8
-rw-r--r--src/test/ui-fulldeps/plugin-args-1.stderr8
-rw-r--r--src/test/ui-fulldeps/plugin-args-2.rs8
-rw-r--r--src/test/ui-fulldeps/plugin-args-2.stderr8
-rw-r--r--src/test/ui-fulldeps/plugin-args-3.rs8
-rw-r--r--src/test/ui-fulldeps/plugin-args-3.stderr8
-rw-r--r--src/test/ui-fulldeps/plugin-args.rs9
-rw-r--r--src/test/ui-fulldeps/plugin-args.stderr16
-rw-r--r--src/test/ui-fulldeps/plugin-as-extern-crate.rs7
-rw-r--r--src/test/ui-fulldeps/plugin-as-extern-crate.stderr14
-rw-r--r--src/test/ui/allocator/two-allocators3.stderr2
-rw-r--r--src/test/ui/async-await/issues/issue-63388-1.nll.stderr4
-rw-r--r--src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-completion.rs46
-rw-r--r--src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-panic.rs52
-rw-r--r--src/test/ui/async-await/issues/issue-65419/issue-65419-generator-resume-after-completion.rs25
-rw-r--r--src/test/ui/async-await/issues/issue-66695-static-refs.rs24
-rw-r--r--src/test/ui/binop/binop-consume-args.stderr60
-rw-r--r--src/test/ui/binop/binop-move-semantics.stderr8
-rw-r--r--src/test/ui/borrowck/borrowck-unboxed-closures.stderr4
-rw-r--r--src/test/ui/consts/const-fn-zst-args.rs14
-rw-r--r--src/test/ui/consts/const-multi-ref.rs19
-rw-r--r--src/test/ui/consts/const-multi-ref.stderr13
-rw-r--r--src/test/ui/consts/const-size_of-cycle.stderr5
-rw-r--r--src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.rs26
-rw-r--r--src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-const.rs23
-rw-r--r--src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.rs18
-rw-r--r--src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.stderr (renamed from src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.stderr)6
-rw-r--r--src/test/ui/consts/uninhabited-const-issue-61744.rs6
-rw-r--r--src/test/ui/consts/uninhabited-const-issue-61744.stderr80
-rw-r--r--src/test/ui/error-codes/E0017.rs3
-rw-r--r--src/test/ui/error-codes/E0017.stderr24
-rw-r--r--src/test/ui/error-codes/E0388.rs9
-rw-r--r--src/test/ui/error-codes/E0388.stderr28
-rw-r--r--src/test/ui/feature-gates/feature-gate-cfg_sanitize.rs3
-rw-r--r--src/test/ui/feature-gates/feature-gate-cfg_sanitize.stderr12
-rw-r--r--src/test/ui/fmt/format-string-error.rs6
-rw-r--r--src/test/ui/fmt/format-string-error.stderr44
-rw-r--r--src/test/ui/generator/static-reference-across-yield.rs16
-rw-r--r--src/test/ui/hrtb/hrtb-higher-ranker-supertraits-transitive.stderr2
-rw-r--r--src/test/ui/hrtb/hrtb-higher-ranker-supertraits.stderr4
-rw-r--r--src/test/ui/ifmt.rs2
-rw-r--r--src/test/ui/infinite/infinite-recursion-const-fn.rs2
-rw-r--r--src/test/ui/infinite/infinite-recursion-const-fn.stderr69
-rw-r--r--src/test/ui/invalid_const_promotion.rs8
-rw-r--r--src/test/ui/issues/issue-27033.stderr4
-rw-r--r--src/test/ui/issues/issue-34721.fixed34
-rw-r--r--src/test/ui/issues/issue-34721.rs2
-rw-r--r--src/test/ui/issues/issue-34721.stderr6
-rw-r--r--src/test/ui/issues/issue-4335.rs3
-rw-r--r--src/test/ui/issues/issue-4335.stderr23
-rw-r--r--src/test/ui/issues/issue-66851.rs20
-rw-r--r--src/test/ui/malformed/malformed-plugin-1.stderr2
-rw-r--r--src/test/ui/malformed/malformed-plugin-2.stderr2
-rw-r--r--src/test/ui/malformed/malformed-plugin-3.stderr4
-rw-r--r--src/test/ui/maybe-bounds-where.stderr1
-rw-r--r--src/test/ui/moves/moves-based-on-type-no-recursive-stack-closure.stderr6
-rw-r--r--src/test/ui/nll/closure-requirements/escape-argument-callee.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/escape-argument.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-ref.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr4
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-approximated-val.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr2
-rw-r--r--src/test/ui/nll/closure-requirements/return-wrong-bound-region.stderr2
-rw-r--r--src/test/ui/nll/ty-outlives/projection-one-region-closure.stderr2
-rw-r--r--src/test/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr2
-rw-r--r--src/test/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr6
-rw-r--r--src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr4
-rw-r--r--src/test/ui/once-cant-call-twice-on-heap.stderr4
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-non-exhaustive.rs26
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-non-exhaustive.stderr33
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-pass.rs40
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-pass.stderr8
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.rs51
-rw-r--r--src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.stderr80
-rw-r--r--src/test/ui/pattern/usefulness/65413-constants-and-slices-exhaustiveness.rs15
-rw-r--r--src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr8
-rw-r--r--src/test/ui/pattern/usefulness/slice-pattern-const.rs7
-rw-r--r--src/test/ui/pattern/usefulness/slice-pattern-const.stderr8
-rw-r--r--src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs22
-rw-r--r--src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr26
-rw-r--r--src/test/ui/pattern/usefulness/slice-patterns-reachability.rs2
-rw-r--r--src/test/ui/regions/regions-addr-of-upvar-self.stderr2
-rw-r--r--src/test/ui/sanitize-cfg.rs26
-rw-r--r--src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr6
-rw-r--r--src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr21
-rw-r--r--src/test/ui/self/elision/lt-ref-self-async.nll.stderr42
-rw-r--r--src/test/ui/self/elision/ref-mut-self-async.nll.stderr42
-rw-r--r--src/test/ui/self/elision/ref-mut-struct-async.nll.stderr35
-rw-r--r--src/test/ui/self/elision/ref-struct-async.nll.stderr35
-rw-r--r--src/test/ui/terminal-width/non-1-width-unicode-multiline-label.rs7
-rw-r--r--src/test/ui/terminal-width/non-1-width-unicode-multiline-label.stderr17
-rw-r--r--src/test/ui/terminal-width/non-whitespace-trimming-unicode.stderr2
-rw-r--r--src/test/ui/type-alias-impl-trait/issue-66580-closure-coherence.rs19
-rw-r--r--src/test/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr2
-rw-r--r--src/test/ui/unop-move-semantics.stderr4
m---------src/tools/miri16
-rw-r--r--src/tools/tidy/src/features.rs2
570 files changed, 12672 insertions, 12025 deletions
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bd1d49fb24d..8fbbd7c4a2e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -150,13 +150,13 @@ All pull requests are reviewed by another person. We have a bot,
 request.
 
 If you want to request that a specific person reviews your pull request,
-you can add an `r?` to the message. For example, [Steve][steveklabnik] usually reviews
+you can add an `r?` to the pull request description. For example, [Steve][steveklabnik] usually reviews
 documentation changes. So if you were to make a documentation change, add
 
     r? @steveklabnik
 
-to the end of the message, and @rust-highfive will assign [@steveklabnik][steveklabnik] instead
-of a random person. This is entirely optional.
+to the end of the pull request description, and [@rust-highfive][rust-highfive] will assign
+[@steveklabnik][steveklabnik] instead of a random person. This is entirely optional.
 
 After someone has reviewed your pull request, they will leave an annotation
 on the pull request with an `r+`. It will look something like this:
diff --git a/Cargo.lock b/Cargo.lock
index 6e152e96070..67259aed8eb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -466,7 +466,7 @@ dependencies = [
  "cargo_metadata 0.9.0",
  "clippy-mini-macro-test",
  "clippy_lints",
- "compiletest_rs 0.4.0",
+ "compiletest_rs",
  "derive-new",
  "lazy_static 1.3.0",
  "regex",
@@ -474,7 +474,7 @@ dependencies = [
  "rustc_tools_util 0.2.0",
  "semver",
  "serde",
- "tester 0.7.0",
+ "tester",
 ]
 
 [[package]]
@@ -597,28 +597,6 @@ dependencies = [
 
 [[package]]
 name = "compiletest_rs"
-version = "0.3.26"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7d8975604ebad8b6660796802377eb6495045c5606168fc1b8d19a4dd9bfa46"
-dependencies = [
- "diff",
- "filetime",
- "getopts",
- "libc",
- "log",
- "miow 0.3.3",
- "regex",
- "rustfix",
- "serde",
- "serde_derive",
- "serde_json",
- "tempfile",
- "tester 0.6.0",
- "winapi 0.3.8",
-]
-
-[[package]]
-name = "compiletest_rs"
 version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d7b678957210a00ba0fbeacc23d38cbfbf29895564da1616564634351e1dac5e"
@@ -635,7 +613,7 @@ dependencies = [
  "serde_derive",
  "serde_json",
  "tempfile",
- "tester 0.7.0",
+ "tester",
  "winapi 0.3.8",
 ]
 
@@ -2223,7 +2201,7 @@ dependencies = [
  "byteorder",
  "cargo_metadata 0.9.0",
  "colored",
- "compiletest_rs 0.3.26",
+ "compiletest_rs",
  "directories",
  "env_logger 0.7.1",
  "getrandom",
@@ -3221,6 +3199,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_fs_util",
  "rustc_index",
  "rustc_macros",
@@ -3596,6 +3575,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_interface",
  "rustc_lint",
  "rustc_metadata",
@@ -3630,6 +3610,15 @@ dependencies = [
 ]
 
 [[package]]
+name = "rustc_feature"
+version = "0.0.0"
+dependencies = [
+ "lazy_static 1.3.0",
+ "rustc_data_structures",
+ "syntax_pos",
+]
+
+[[package]]
 name = "rustc_fs_util"
 version = "0.0.0"
 
@@ -3704,6 +3693,7 @@ dependencies = [
  "rustc",
  "rustc_data_structures",
  "rustc_error_codes",
+ "rustc_feature",
  "rustc_index",
  "rustc_target",
  "syntax",
@@ -3808,6 +3798,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_lexer",
  "rustc_target",
  "smallvec 1.0.0",
@@ -3824,6 +3815,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_index",
  "rustc_parse",
  "rustc_target",
@@ -3866,6 +3858,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_metadata",
  "smallvec 1.0.0",
  "syntax",
@@ -4464,6 +4457,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_index",
  "rustc_lexer",
  "rustc_macros",
@@ -4480,6 +4474,7 @@ dependencies = [
  "log",
  "rustc_data_structures",
  "rustc_errors",
+ "rustc_feature",
  "rustc_lexer",
  "rustc_parse",
  "serialize",
@@ -4497,6 +4492,7 @@ dependencies = [
  "rustc_data_structures",
  "rustc_error_codes",
  "rustc_errors",
+ "rustc_feature",
  "rustc_parse",
  "rustc_target",
  "smallvec 1.0.0",
@@ -4623,17 +4619,6 @@ dependencies = [
 
 [[package]]
 name = "tester"
-version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7647e6d732eb84375d8e7abda37818f81861ddbfc7235e33f4983cb254b71e4f"
-dependencies = [
- "getopts",
- "libc",
- "term 0.6.0",
-]
-
-[[package]]
-name = "tester"
 version = "0.7.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ee72ec31009a42b53de9a6b7d8f462b493ab3b1e4767bda1fcdbb52127f13b6c"
diff --git a/src/doc/rustc/src/lints/listing/warn-by-default.md b/src/doc/rustc/src/lints/listing/warn-by-default.md
index 77642a850fa..386f6008d06 100644
--- a/src/doc/rustc/src/lints/listing/warn-by-default.md
+++ b/src/doc/rustc/src/lints/listing/warn-by-default.md
@@ -307,18 +307,6 @@ warning: path statement with no effect
   |
 ```
 
-## plugin-as-library
-
-This lint detects when compiler plugins are used as ordinary library in
-non-plugin crate. Some example code that triggers this lint:
-
-```rust,ignore
-#![feature(plugin)]
-#![plugin(macro_crate_test)]
-
-extern crate macro_crate_test;
-```
-
 ## private-in-public
 
 This lint detects private items in public interfaces not caught by the old implementation. Some
diff --git a/src/doc/unstable-book/src/language-features/cfg-sanitize.md b/src/doc/unstable-book/src/language-features/cfg-sanitize.md
new file mode 100644
index 00000000000..949f24ab9c1
--- /dev/null
+++ b/src/doc/unstable-book/src/language-features/cfg-sanitize.md
@@ -0,0 +1,36 @@
+# `cfg_sanitize`
+
+The tracking issue for this feature is: [#39699]
+
+[#39699]: https://github.com/rust-lang/rust/issues/39699
+
+------------------------
+
+The `cfg_sanitize` feature makes it possible to execute different code
+depending on whether a particular sanitizer is enabled or not.
+
+## Examples
+
+``` rust
+#![feature(cfg_sanitize)]
+
+#[cfg(sanitize = "thread")]
+fn a() {
+  // ...
+}
+
+#[cfg(not(sanitize = "thread"))]
+fn a() {
+  // ...
+}
+
+fn b() {
+  if cfg!(sanitize = "leak") {
+    // ...
+  } else {
+    // ...
+  }
+}
+
+```
+
diff --git a/src/doc/unstable-book/src/language-features/plugin.md b/src/doc/unstable-book/src/language-features/plugin.md
index cd1137e762e..495cdee62c8 100644
--- a/src/doc/unstable-book/src/language-features/plugin.md
+++ b/src/doc/unstable-book/src/language-features/plugin.md
@@ -21,15 +21,10 @@ the crate attribute `#![plugin(...)]`.  See the
 `rustc_driver::plugin` documentation for more about the
 mechanics of defining and loading a plugin.
 
-If present, arguments passed as `#![plugin(foo(... args ...))]` are not
-interpreted by rustc itself.  They are provided to the plugin through the
-`Registry`'s `args` method.
-
 In the vast majority of cases, a plugin should *only* be used through
 `#![plugin]` and not through an `extern crate` item.  Linking a plugin would
 pull in all of libsyntax and librustc as dependencies of your crate.  This is
-generally unwanted unless you are building another plugin.  The
-`plugin_as_library` lint checks these guidelines.
+generally unwanted unless you are building another plugin.
 
 The usual practice is to put compiler plugins in their own crate, separate from
 any `macro_rules!` macros or ordinary Rust code meant to be used by consumers
diff --git a/src/etc/dec2flt_table.py b/src/etc/dec2flt_table.py
index 2ffaf13dc8f..85395d2ecdf 100644..100755
--- a/src/etc/dec2flt_table.py
+++ b/src/etc/dec2flt_table.py
@@ -111,14 +111,18 @@ def print_proper_powers():
     print("pub const MIN_E: i16 = {};".format(MIN_E))
     print("pub const MAX_E: i16 = {};".format(MAX_E))
     print()
+    print("#[rustfmt::skip]")
     typ = "([u64; {0}], [i16; {0}])".format(len(powers))
-    print("pub const POWERS: ", typ, " = ([", sep='')
+    print("pub const POWERS: ", typ, " = (", sep='')
+    print("    [")
     for z in powers:
-        print("    0x{:x},".format(z.sig))
-    print("], [")
+        print("        0x{:x},".format(z.sig))
+    print("    ],")
+    print("    [")
     for z in powers:
-        print("    {},".format(z.exp))
-    print("]);")
+        print("        {},".format(z.exp))
+    print("    ],")
+    print(");")
 
 
 def print_short_powers(num_bits, significand_size):
@@ -127,6 +131,7 @@ def print_short_powers(num_bits, significand_size):
     max_e = int(ceil(log(max_sig, 5)))
     e_range = range(max_e)
     typ = "[f{}; {}]".format(num_bits, len(e_range))
+    print("#[rustfmt::skip]")
     print("pub const F", num_bits, "_SHORT_POWERS: ", typ, " = [", sep='')
     for e in e_range:
         print("    1e{},".format(e))
diff --git a/src/liballoc/alloc/tests.rs b/src/liballoc/alloc/tests.rs
index c69f4e49ee1..956298d7836 100644
--- a/src/liballoc/alloc/tests.rs
+++ b/src/liballoc/alloc/tests.rs
@@ -1,15 +1,15 @@
 use super::*;
 
 extern crate test;
-use test::Bencher;
 use crate::boxed::Box;
+use test::Bencher;
 
 #[test]
 fn allocate_zeroed() {
     unsafe {
         let layout = Layout::from_size_align(1024, 1).unwrap();
-        let ptr = Global.alloc_zeroed(layout.clone())
-            .unwrap_or_else(|_| handle_alloc_error(layout));
+        let ptr =
+            Global.alloc_zeroed(layout.clone()).unwrap_or_else(|_| handle_alloc_error(layout));
 
         let mut i = ptr.cast::<u8>().as_ptr();
         let end = i.add(layout.size());
diff --git a/src/liballoc/benches/btree/map.rs b/src/liballoc/benches/btree/map.rs
index b541fa94e95..eb5f51d9adc 100644
--- a/src/liballoc/benches/btree/map.rs
+++ b/src/liballoc/benches/btree/map.rs
@@ -1,12 +1,12 @@
+use std::collections::BTreeMap;
 use std::iter::Iterator;
 use std::vec::Vec;
-use std::collections::BTreeMap;
 
-use rand::{Rng, seq::SliceRandom, thread_rng};
-use test::{Bencher, black_box};
+use rand::{seq::SliceRandom, thread_rng, Rng};
+use test::{black_box, Bencher};
 
 macro_rules! map_insert_rand_bench {
-    ($name: ident, $n: expr, $map: ident) => (
+    ($name: ident, $n: expr, $map: ident) => {
         #[bench]
         pub fn $name(b: &mut Bencher) {
             let n: usize = $n;
@@ -27,11 +27,11 @@ macro_rules! map_insert_rand_bench {
             });
             black_box(map);
         }
-    )
+    };
 }
 
 macro_rules! map_insert_seq_bench {
-    ($name: ident, $n: expr, $map: ident) => (
+    ($name: ident, $n: expr, $map: ident) => {
         #[bench]
         pub fn $name(b: &mut Bencher) {
             let mut map = $map::new();
@@ -50,11 +50,11 @@ macro_rules! map_insert_seq_bench {
             });
             black_box(map);
         }
-    )
+    };
 }
 
 macro_rules! map_find_rand_bench {
-    ($name: ident, $n: expr, $map: ident) => (
+    ($name: ident, $n: expr, $map: ident) => {
         #[bench]
         pub fn $name(b: &mut Bencher) {
             let mut map = $map::new();
@@ -78,11 +78,11 @@ macro_rules! map_find_rand_bench {
                 black_box(t);
             })
         }
-    )
+    };
 }
 
 macro_rules! map_find_seq_bench {
-    ($name: ident, $n: expr, $map: ident) => (
+    ($name: ident, $n: expr, $map: ident) => {
         #[bench]
         pub fn $name(b: &mut Bencher) {
             let mut map = $map::new();
@@ -101,20 +101,20 @@ macro_rules! map_find_seq_bench {
                 black_box(x);
             })
         }
-    )
+    };
 }
 
-map_insert_rand_bench!{insert_rand_100,    100,    BTreeMap}
-map_insert_rand_bench!{insert_rand_10_000, 10_000, BTreeMap}
+map_insert_rand_bench! {insert_rand_100,    100,    BTreeMap}
+map_insert_rand_bench! {insert_rand_10_000, 10_000, BTreeMap}
 
-map_insert_seq_bench!{insert_seq_100,    100,    BTreeMap}
-map_insert_seq_bench!{insert_seq_10_000, 10_000, BTreeMap}
+map_insert_seq_bench! {insert_seq_100,    100,    BTreeMap}
+map_insert_seq_bench! {insert_seq_10_000, 10_000, BTreeMap}
 
-map_find_rand_bench!{find_rand_100,    100,    BTreeMap}
-map_find_rand_bench!{find_rand_10_000, 10_000, BTreeMap}
+map_find_rand_bench! {find_rand_100,    100,    BTreeMap}
+map_find_rand_bench! {find_rand_10_000, 10_000, BTreeMap}
 
-map_find_seq_bench!{find_seq_100,    100,    BTreeMap}
-map_find_seq_bench!{find_seq_10_000, 10_000, BTreeMap}
+map_find_seq_bench! {find_seq_100,    100,    BTreeMap}
+map_find_seq_bench! {find_seq_10_000, 10_000, BTreeMap}
 
 fn bench_iter(b: &mut Bencher, size: i32) {
     let mut map = BTreeMap::<i32, i32>::new();
diff --git a/src/liballoc/benches/slice.rs b/src/liballoc/benches/slice.rs
index ef91d801dc7..e20c043286e 100644
--- a/src/liballoc/benches/slice.rs
+++ b/src/liballoc/benches/slice.rs
@@ -1,9 +1,9 @@
 use std::{mem, ptr};
 
+use rand::distributions::{Alphanumeric, Standard};
 use rand::{thread_rng, Rng, SeedableRng};
-use rand::distributions::{Standard, Alphanumeric};
 use rand_xorshift::XorShiftRng;
-use test::{Bencher, black_box};
+use test::{black_box, Bencher};
 
 #[bench]
 fn iterator(b: &mut Bencher) {
@@ -239,7 +239,7 @@ macro_rules! sort {
             b.iter(|| v.clone().$f());
             b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
         }
-    }
+    };
 }
 
 macro_rules! sort_strings {
@@ -251,7 +251,7 @@ macro_rules! sort_strings {
             b.iter(|| v.clone().$f());
             b.bytes = $len * mem::size_of::<&str>() as u64;
         }
-    }
+    };
 }
 
 macro_rules! sort_expensive {
@@ -273,7 +273,7 @@ macro_rules! sort_expensive {
             });
             b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
         }
-    }
+    };
 }
 
 macro_rules! sort_lexicographic {
@@ -284,7 +284,7 @@ macro_rules! sort_lexicographic {
             b.iter(|| v.clone().$f(|x| x.to_string()));
             b.bytes = $len * mem::size_of_val(&$gen(1)[0]) as u64;
         }
-    }
+    };
 }
 
 sort!(sort, sort_small_ascending, gen_ascending, 10);
@@ -325,24 +325,25 @@ macro_rules! reverse {
         fn $name(b: &mut Bencher) {
             // odd length and offset by 1 to be as unaligned as possible
             let n = 0xFFFFF;
-            let mut v: Vec<_> =
-                (0..1+(n / mem::size_of::<$ty>() as u64))
-                .map($f)
-                .collect();
+            let mut v: Vec<_> = (0..1 + (n / mem::size_of::<$ty>() as u64)).map($f).collect();
             b.iter(|| black_box(&mut v[1..]).reverse());
             b.bytes = n;
         }
-    }
+    };
 }
 
 reverse!(reverse_u8, u8, |x| x as u8);
 reverse!(reverse_u16, u16, |x| x as u16);
-reverse!(reverse_u8x3, [u8;3], |x| [x as u8, (x>>8) as u8, (x>>16) as u8]);
+reverse!(reverse_u8x3, [u8; 3], |x| [x as u8, (x >> 8) as u8, (x >> 16) as u8]);
 reverse!(reverse_u32, u32, |x| x as u32);
 reverse!(reverse_u64, u64, |x| x as u64);
 reverse!(reverse_u128, u128, |x| x as u128);
-#[repr(simd)] struct F64x4(f64, f64, f64, f64);
-reverse!(reverse_simd_f64x4, F64x4, |x| { let x = x as f64; F64x4(x,x,x,x) });
+#[repr(simd)]
+struct F64x4(f64, f64, f64, f64);
+reverse!(reverse_simd_f64x4, F64x4, |x| {
+    let x = x as f64;
+    F64x4(x, x, x, x)
+});
 
 macro_rules! rotate {
     ($name:ident, $gen:expr, $len:expr, $mid:expr) => {
@@ -350,32 +351,32 @@ macro_rules! rotate {
         fn $name(b: &mut Bencher) {
             let size = mem::size_of_val(&$gen(1)[0]);
             let mut v = $gen($len * 8 / size);
-            b.iter(|| black_box(&mut v).rotate_left(($mid*8+size-1)/size));
+            b.iter(|| black_box(&mut v).rotate_left(($mid * 8 + size - 1) / size));
             b.bytes = (v.len() * size) as u64;
         }
-    }
+    };
 }
 
 rotate!(rotate_tiny_by1, gen_random, 16, 1);
-rotate!(rotate_tiny_half, gen_random, 16, 16/2);
-rotate!(rotate_tiny_half_plus_one, gen_random, 16, 16/2+1);
+rotate!(rotate_tiny_half, gen_random, 16, 16 / 2);
+rotate!(rotate_tiny_half_plus_one, gen_random, 16, 16 / 2 + 1);
 
 rotate!(rotate_medium_by1, gen_random, 9158, 1);
 rotate!(rotate_medium_by727_u64, gen_random, 9158, 727);
 rotate!(rotate_medium_by727_bytes, gen_random_bytes, 9158, 727);
 rotate!(rotate_medium_by727_strings, gen_strings, 9158, 727);
-rotate!(rotate_medium_half, gen_random, 9158, 9158/2);
-rotate!(rotate_medium_half_plus_one, gen_random, 9158, 9158/2+1);
+rotate!(rotate_medium_half, gen_random, 9158, 9158 / 2);
+rotate!(rotate_medium_half_plus_one, gen_random, 9158, 9158 / 2 + 1);
 
 // Intended to use more RAM than the machine has cache
-rotate!(rotate_huge_by1, gen_random, 5*1024*1024, 1);
-rotate!(rotate_huge_by9199_u64, gen_random, 5*1024*1024, 9199);
-rotate!(rotate_huge_by9199_bytes, gen_random_bytes, 5*1024*1024, 9199);
-rotate!(rotate_huge_by9199_strings, gen_strings, 5*1024*1024, 9199);
-rotate!(rotate_huge_by9199_big, gen_big_random, 5*1024*1024, 9199);
-rotate!(rotate_huge_by1234577_u64, gen_random, 5*1024*1024, 1234577);
-rotate!(rotate_huge_by1234577_bytes, gen_random_bytes, 5*1024*1024, 1234577);
-rotate!(rotate_huge_by1234577_strings, gen_strings, 5*1024*1024, 1234577);
-rotate!(rotate_huge_by1234577_big, gen_big_random, 5*1024*1024, 1234577);
-rotate!(rotate_huge_half, gen_random, 5*1024*1024, 5*1024*1024/2);
-rotate!(rotate_huge_half_plus_one, gen_random, 5*1024*1024, 5*1024*1024/2+1);
+rotate!(rotate_huge_by1, gen_random, 5 * 1024 * 1024, 1);
+rotate!(rotate_huge_by9199_u64, gen_random, 5 * 1024 * 1024, 9199);
+rotate!(rotate_huge_by9199_bytes, gen_random_bytes, 5 * 1024 * 1024, 9199);
+rotate!(rotate_huge_by9199_strings, gen_strings, 5 * 1024 * 1024, 9199);
+rotate!(rotate_huge_by9199_big, gen_big_random, 5 * 1024 * 1024, 9199);
+rotate!(rotate_huge_by1234577_u64, gen_random, 5 * 1024 * 1024, 1234577);
+rotate!(rotate_huge_by1234577_bytes, gen_random_bytes, 5 * 1024 * 1024, 1234577);
+rotate!(rotate_huge_by1234577_strings, gen_strings, 5 * 1024 * 1024, 1234577);
+rotate!(rotate_huge_by1234577_big, gen_big_random, 5 * 1024 * 1024, 1234577);
+rotate!(rotate_huge_half, gen_random, 5 * 1024 * 1024, 5 * 1024 * 1024 / 2);
+rotate!(rotate_huge_half_plus_one, gen_random, 5 * 1024 * 1024, 5 * 1024 * 1024 / 2 + 1);
diff --git a/src/liballoc/benches/str.rs b/src/liballoc/benches/str.rs
index 7f8661bd968..391475bc0c7 100644
--- a/src/liballoc/benches/str.rs
+++ b/src/liballoc/benches/str.rs
@@ -1,4 +1,4 @@
-use test::{Bencher, black_box};
+use test::{black_box, Bencher};
 
 #[bench]
 fn char_iterator(b: &mut Bencher) {
@@ -12,7 +12,9 @@ fn char_iterator_for(b: &mut Bencher) {
     let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
 
     b.iter(|| {
-        for ch in s.chars() { black_box(ch); }
+        for ch in s.chars() {
+            black_box(ch);
+        }
     });
 }
 
@@ -40,7 +42,9 @@ fn char_iterator_rev_for(b: &mut Bencher) {
     let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb";
 
     b.iter(|| {
-        for ch in s.chars().rev() { black_box(ch); }
+        for ch in s.chars().rev() {
+            black_box(ch);
+        }
     });
 }
 
@@ -79,7 +83,9 @@ fn split_ascii(b: &mut Bencher) {
 fn split_extern_fn(b: &mut Bencher) {
     let s = "Mary had a little lamb, Little lamb, little-lamb.";
     let len = s.split(' ').count();
-    fn pred(c: char) -> bool { c == ' ' }
+    fn pred(c: char) -> bool {
+        c == ' '
+    }
 
     b.iter(|| assert_eq!(s.split(pred).count(), len));
 }
@@ -185,16 +191,19 @@ fn bench_contains_equal(b: &mut Bencher) {
     })
 }
 
-
 macro_rules! make_test_inner {
     ($s:ident, $code:expr, $name:ident, $str:expr, $iters:expr) => {
         #[bench]
         fn $name(bencher: &mut Bencher) {
             let mut $s = $str;
             black_box(&mut $s);
-            bencher.iter(|| for _ in 0..$iters { black_box($code); });
+            bencher.iter(|| {
+                for _ in 0..$iters {
+                    black_box($code);
+                }
+            });
         }
-    }
+    };
 }
 
 macro_rules! make_test {
@@ -261,15 +270,9 @@ make_test!(match_indices_a_str, s, s.match_indices("a").count());
 
 make_test!(split_a_str, s, s.split("a").count());
 
-make_test!(trim_ascii_char, s, {
-    s.trim_matches(|c: char| c.is_ascii())
-});
-make_test!(trim_start_ascii_char, s, {
-    s.trim_start_matches(|c: char| c.is_ascii())
-});
-make_test!(trim_end_ascii_char, s, {
-    s.trim_end_matches(|c: char| c.is_ascii())
-});
+make_test!(trim_ascii_char, s, { s.trim_matches(|c: char| c.is_ascii()) });
+make_test!(trim_start_ascii_char, s, { s.trim_start_matches(|c: char| c.is_ascii()) });
+make_test!(trim_end_ascii_char, s, { s.trim_end_matches(|c: char| c.is_ascii()) });
 
 make_test!(find_underscore_char, s, s.find('_'));
 make_test!(rfind_underscore_char, s, s.rfind('_'));
diff --git a/src/liballoc/benches/vec_deque.rs b/src/liballoc/benches/vec_deque.rs
index 7d2d3cfa612..bf2dffd1e93 100644
--- a/src/liballoc/benches/vec_deque.rs
+++ b/src/liballoc/benches/vec_deque.rs
@@ -1,5 +1,5 @@
 use std::collections::VecDeque;
-use test::{Bencher, black_box};
+use test::{black_box, Bencher};
 
 #[bench]
 fn bench_new(b: &mut Bencher) {
diff --git a/src/liballoc/benches/vec_deque_append.rs b/src/liballoc/benches/vec_deque_append.rs
index 78ec91d9e3e..5825bdc355f 100644
--- a/src/liballoc/benches/vec_deque_append.rs
+++ b/src/liballoc/benches/vec_deque_append.rs
@@ -30,8 +30,5 @@ fn main() {
 
     assert!(BENCH_N % 2 == 0);
     let median = (durations[(l / 2) - 1] + durations[l / 2]) / 2;
-    println!(
-        "\ncustom-bench vec_deque_append {:?} ns/iter\n",
-        median.as_nanos()
-    );
+    println!("\ncustom-bench vec_deque_append {:?} ns/iter\n", median.as_nanos());
 }
diff --git a/src/liballoc/collections/btree/mod.rs b/src/liballoc/collections/btree/mod.rs
index 8b7dc07063b..f73a24d0991 100644
--- a/src/liballoc/collections/btree/mod.rs
+++ b/src/liballoc/collections/btree/mod.rs
@@ -1,6 +1,6 @@
+pub mod map;
 mod node;
 mod search;
-pub mod map;
 pub mod set;
 
 #[doc(hidden)]
diff --git a/src/liballoc/collections/btree/search.rs b/src/liballoc/collections/btree/search.rs
index dfb67d2ea57..3f3c49a2ef8 100644
--- a/src/liballoc/collections/btree/search.rs
+++ b/src/liballoc/collections/btree/search.rs
@@ -1,21 +1,23 @@
 use core::borrow::Borrow;
 use core::cmp::Ordering;
 
-use super::node::{Handle, NodeRef, marker, ForceResult::*};
+use super::node::{marker, ForceResult::*, Handle, NodeRef};
 
 use SearchResult::*;
 
 pub enum SearchResult<BorrowType, K, V, FoundType, GoDownType> {
     Found(Handle<NodeRef<BorrowType, K, V, FoundType>, marker::KV>),
-    GoDown(Handle<NodeRef<BorrowType, K, V, GoDownType>, marker::Edge>)
+    GoDown(Handle<NodeRef<BorrowType, K, V, GoDownType>, marker::Edge>),
 }
 
 pub fn search_tree<BorrowType, K, V, Q: ?Sized>(
     mut node: NodeRef<BorrowType, K, V, marker::LeafOrInternal>,
-    key: &Q
+    key: &Q,
 ) -> SearchResult<BorrowType, K, V, marker::LeafOrInternal, marker::Leaf>
-        where Q: Ord, K: Borrow<Q> {
-
+where
+    Q: Ord,
+    K: Borrow<Q>,
+{
     loop {
         match search_node(node, key) {
             Found(handle) => return Found(handle),
@@ -25,38 +27,38 @@ pub fn search_tree<BorrowType, K, V, Q: ?Sized>(
                     node = internal.descend();
                     continue;
                 }
-            }
+            },
         }
     }
 }
 
 pub fn search_node<BorrowType, K, V, Type, Q: ?Sized>(
     node: NodeRef<BorrowType, K, V, Type>,
-    key: &Q
+    key: &Q,
 ) -> SearchResult<BorrowType, K, V, Type, Type>
-        where Q: Ord, K: Borrow<Q> {
-
+where
+    Q: Ord,
+    K: Borrow<Q>,
+{
     match search_linear(&node, key) {
-        (idx, true) => Found(
-            Handle::new_kv(node, idx)
-        ),
-        (idx, false) => SearchResult::GoDown(
-            Handle::new_edge(node, idx)
-        )
+        (idx, true) => Found(Handle::new_kv(node, idx)),
+        (idx, false) => SearchResult::GoDown(Handle::new_edge(node, idx)),
     }
 }
 
 pub fn search_linear<BorrowType, K, V, Type, Q: ?Sized>(
     node: &NodeRef<BorrowType, K, V, Type>,
-    key: &Q
+    key: &Q,
 ) -> (usize, bool)
-        where Q: Ord, K: Borrow<Q> {
-
+where
+    Q: Ord,
+    K: Borrow<Q>,
+{
     for (i, k) in node.keys().iter().enumerate() {
         match key.cmp(k.borrow()) {
-            Ordering::Greater => {},
+            Ordering::Greater => {}
             Ordering::Equal => return (i, true),
-            Ordering::Less => return (i, false)
+            Ordering::Less => return (i, false),
         }
     }
     (node.keys().len(), false)
diff --git a/src/liballoc/collections/linked_list/tests.rs b/src/liballoc/collections/linked_list/tests.rs
index 1001f6bba3b..94b92df1294 100644
--- a/src/liballoc/collections/linked_list/tests.rs
+++ b/src/liballoc/collections/linked_list/tests.rs
@@ -177,8 +177,7 @@ fn test_insert_prev() {
     }
     check_links(&m);
     assert_eq!(m.len(), 3 + len * 2);
-    assert_eq!(m.into_iter().collect::<Vec<_>>(),
-                [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
+    assert_eq!(m.into_iter().collect::<Vec<_>>(), [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
 }
 
 #[test]
@@ -187,13 +186,13 @@ fn test_insert_prev() {
 fn test_send() {
     let n = list_from(&[1, 2, 3]);
     thread::spawn(move || {
-            check_links(&n);
-            let a: &[_] = &[&1, &2, &3];
-            assert_eq!(a, &*n.iter().collect::<Vec<_>>());
-        })
-        .join()
-        .ok()
-        .unwrap();
+        check_links(&n);
+        let a: &[_] = &[&1, &2, &3];
+        assert_eq!(a, &*n.iter().collect::<Vec<_>>());
+    })
+    .join()
+    .ok()
+    .unwrap();
 }
 
 #[test]
diff --git a/src/liballoc/collections/vec_deque/tests.rs b/src/liballoc/collections/vec_deque/tests.rs
index 09009ff516a..8dc097cc088 100644
--- a/src/liballoc/collections/vec_deque/tests.rs
+++ b/src/liballoc/collections/vec_deque/tests.rs
@@ -66,11 +66,8 @@ fn test_swap_front_back_remove() {
         let final_len = usable_cap / 2;
 
         for len in 0..final_len {
-            let expected: VecDeque<_> = if back {
-                (0..len).collect()
-            } else {
-                (0..len).rev().collect()
-            };
+            let expected: VecDeque<_> =
+                if back { (0..len).collect() } else { (0..len).rev().collect() };
             for tail_pos in 0..usable_cap {
                 tester.tail = tail_pos;
                 tester.head = tail_pos;
@@ -111,7 +108,6 @@ fn test_insert() {
     // this test isn't covering what it wants to
     let cap = tester.capacity();
 
-
     // len is the length *after* insertion
     for len in 1..cap {
         // 0, 1, 2, .., len - 1
@@ -198,9 +194,7 @@ fn test_drain() {
                     assert!(tester.head < tester.cap());
 
                     // We should see the correct values in the VecDeque
-                    let expected: VecDeque<_> = (0..drain_start)
-                        .chain(drain_end..len)
-                        .collect();
+                    let expected: VecDeque<_> = (0..drain_start).chain(drain_end..len).collect();
                     assert_eq!(expected, tester);
                 }
             }
diff --git a/src/liballoc/fmt.rs b/src/liballoc/fmt.rs
index cbfc55233a1..18ebae33309 100644
--- a/src/liballoc/fmt.rs
+++ b/src/liballoc/fmt.rs
@@ -516,24 +516,24 @@
 
 #[unstable(feature = "fmt_internals", issue = "0")]
 pub use core::fmt::rt;
+#[stable(feature = "fmt_flags_align", since = "1.28.0")]
+pub use core::fmt::Alignment;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::{Formatter, Result, Write};
+pub use core::fmt::Error;
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use core::fmt::{write, ArgumentV1, Arguments};
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use core::fmt::{Binary, Octal};
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use core::fmt::{Debug, Display};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::{LowerHex, Pointer, UpperHex};
-#[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::{LowerExp, UpperExp};
+pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::Error;
+pub use core::fmt::{Formatter, Result, Write};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::{write, ArgumentV1, Arguments};
+pub use core::fmt::{LowerExp, UpperExp};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple};
-#[stable(feature = "fmt_flags_align", since = "1.28.0")]
-pub use core::fmt::{Alignment};
+pub use core::fmt::{LowerHex, Pointer, UpperHex};
 
 use crate::string;
 
@@ -568,8 +568,6 @@ use crate::string;
 pub fn format(args: Arguments<'_>) -> string::String {
     let capacity = args.estimated_capacity();
     let mut output = string::String::with_capacity(capacity);
-    output
-        .write_fmt(args)
-        .expect("a formatting trait implementation returned an error");
+    output.write_fmt(args).expect("a formatting trait implementation returned an error");
     output
 }
diff --git a/src/liballoc/prelude/v1.rs b/src/liballoc/prelude/v1.rs
index 3cb285bf049..6a53b4ca1f6 100644
--- a/src/liballoc/prelude/v1.rs
+++ b/src/liballoc/prelude/v1.rs
@@ -4,7 +4,11 @@
 
 #![unstable(feature = "alloc_prelude", issue = "58935")]
 
-#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::borrow::ToOwned;
-#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::boxed::Box;
-#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::string::{String, ToString};
-#[unstable(feature = "alloc_prelude", issue = "58935")] pub use crate::vec::Vec;
+#[unstable(feature = "alloc_prelude", issue = "58935")]
+pub use crate::borrow::ToOwned;
+#[unstable(feature = "alloc_prelude", issue = "58935")]
+pub use crate::boxed::Box;
+#[unstable(feature = "alloc_prelude", issue = "58935")]
+pub use crate::string::{String, ToString};
+#[unstable(feature = "alloc_prelude", issue = "58935")]
+pub use crate::vec::Vec;
diff --git a/src/liballoc/raw_vec/tests.rs b/src/liballoc/raw_vec/tests.rs
index d35b62fc1ef..b214cef3011 100644
--- a/src/liballoc/raw_vec/tests.rs
+++ b/src/liballoc/raw_vec/tests.rs
@@ -16,7 +16,9 @@ fn allocator_param() {
 
     // A dumb allocator that consumes a fixed amount of fuel
     // before allocation attempts start failing.
-    struct BoundedAlloc { fuel: usize }
+    struct BoundedAlloc {
+        fuel: usize,
+    }
     unsafe impl Alloc for BoundedAlloc {
         unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
             let size = layout.size();
@@ -24,7 +26,10 @@ fn allocator_param() {
                 return Err(AllocErr);
             }
             match Global.alloc(layout) {
-                ok @ Ok(_) => { self.fuel -= size; ok }
+                ok @ Ok(_) => {
+                    self.fuel -= size;
+                    ok
+                }
                 err @ Err(_) => err,
             }
         }
diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs
index 08243ef7c51..2f6d10c027b 100644
--- a/src/liballoc/slice.rs
+++ b/src/liballoc/slice.rs
@@ -82,7 +82,6 @@
 //! [`.chunks`]: ../../std/primitive.slice.html#method.chunks
 //! [`.windows`]: ../../std/primitive.slice.html#method.windows
 #![stable(feature = "rust1", since = "1.0.0")]
-
 // Many of the usings in this module are only used in the test configuration.
 // It's cleaner to just turn off the unused_imports warning than to fix them.
 #![cfg_attr(test, allow(unused_imports, dead_code))]
@@ -91,32 +90,32 @@ use core::borrow::{Borrow, BorrowMut};
 use core::cmp::Ordering::{self, Less};
 use core::mem::{self, size_of};
 use core::ptr;
-use core::{u8, u16, u32};
+use core::{u16, u32, u8};
 
 use crate::borrow::ToOwned;
 use crate::boxed::Box;
 use crate::vec::Vec;
 
+#[stable(feature = "slice_get_slice", since = "1.28.0")]
+pub use core::slice::SliceIndex;
+#[stable(feature = "from_ref", since = "1.28.0")]
+pub use core::slice::{from_mut, from_ref};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::slice::{Chunks, Windows};
+pub use core::slice::{from_raw_parts, from_raw_parts_mut};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::slice::{Iter, IterMut};
+pub use core::slice::{Chunks, Windows};
+#[stable(feature = "chunks_exact", since = "1.31.0")]
+pub use core::slice::{ChunksExact, ChunksExactMut};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::slice::{SplitMut, ChunksMut, Split};
+pub use core::slice::{ChunksMut, Split, SplitMut};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
+pub use core::slice::{Iter, IterMut};
+#[stable(feature = "rchunks", since = "1.31.0")]
+pub use core::slice::{RChunks, RChunksExact, RChunksExactMut, RChunksMut};
 #[stable(feature = "slice_rsplit", since = "1.27.0")]
 pub use core::slice::{RSplit, RSplitMut};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::slice::{from_raw_parts, from_raw_parts_mut};
-#[stable(feature = "from_ref", since = "1.28.0")]
-pub use core::slice::{from_ref, from_mut};
-#[stable(feature = "slice_get_slice", since = "1.28.0")]
-pub use core::slice::SliceIndex;
-#[stable(feature = "chunks_exact", since = "1.31.0")]
-pub use core::slice::{ChunksExact, ChunksExactMut};
-#[stable(feature = "rchunks", since = "1.31.0")]
-pub use core::slice::{RChunks, RChunksMut, RChunksExact, RChunksExactMut};
+pub use core::slice::{RSplitN, RSplitNMut, SplitN, SplitNMut};
 
 ////////////////////////////////////////////////////////////////////////////////
 // Basic slice extension methods
@@ -138,9 +137,9 @@ pub use hack::to_vec;
 // `test_permutations` test
 mod hack {
     use crate::boxed::Box;
-    use crate::vec::Vec;
     #[cfg(test)]
     use crate::string::ToString;
+    use crate::vec::Vec;
 
     pub fn into_vec<T>(b: Box<[T]>) -> Vec<T> {
         unsafe {
@@ -153,7 +152,8 @@ mod hack {
 
     #[inline]
     pub fn to_vec<T>(s: &[T]) -> Vec<T>
-        where T: Clone
+    where
+        T: Clone,
     {
         let mut vector = Vec::with_capacity(s.len());
         vector.extend_from_slice(s);
@@ -193,7 +193,8 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn sort(&mut self)
-        where T: Ord
+    where
+        T: Ord,
     {
         merge_sort(self, |a, b| a.lt(b));
     }
@@ -246,7 +247,8 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn sort_by<F>(&mut self, mut compare: F)
-        where F: FnMut(&T, &T) -> Ordering
+    where
+        F: FnMut(&T, &T) -> Ordering,
     {
         merge_sort(self, |a, b| compare(a, b) == Less);
     }
@@ -285,7 +287,9 @@ impl<T> [T] {
     #[stable(feature = "slice_sort_by_key", since = "1.7.0")]
     #[inline]
     pub fn sort_by_key<K, F>(&mut self, mut f: F)
-        where F: FnMut(&T) -> K, K: Ord
+    where
+        F: FnMut(&T) -> K,
+        K: Ord,
     {
         merge_sort(self, |a, b| f(a).lt(&f(b)));
     }
@@ -325,11 +329,13 @@ impl<T> [T] {
     #[stable(feature = "slice_sort_by_cached_key", since = "1.34.0")]
     #[inline]
     pub fn sort_by_cached_key<K, F>(&mut self, f: F)
-        where F: FnMut(&T) -> K, K: Ord
+    where
+        F: FnMut(&T) -> K,
+        K: Ord,
     {
         // Helper macro for indexing our vector by the smallest possible type, to reduce allocation.
         macro_rules! sort_by_key {
-            ($t:ty, $slice:ident, $f:ident) => ({
+            ($t:ty, $slice:ident, $f:ident) => {{
                 let mut indices: Vec<_> =
                     $slice.iter().map($f).enumerate().map(|(i, k)| (k, i as $t)).collect();
                 // The elements of `indices` are unique, as they are indexed, so any sort will be
@@ -344,19 +350,27 @@ impl<T> [T] {
                     indices[i].1 = index;
                     $slice.swap(i, index as usize);
                 }
-            })
+            }};
         }
 
-        let sz_u8    = mem::size_of::<(K, u8)>();
-        let sz_u16   = mem::size_of::<(K, u16)>();
-        let sz_u32   = mem::size_of::<(K, u32)>();
+        let sz_u8 = mem::size_of::<(K, u8)>();
+        let sz_u16 = mem::size_of::<(K, u16)>();
+        let sz_u32 = mem::size_of::<(K, u32)>();
         let sz_usize = mem::size_of::<(K, usize)>();
 
         let len = self.len();
-        if len < 2 { return }
-        if sz_u8  < sz_u16   && len <= ( u8::MAX as usize) { return sort_by_key!( u8, self, f) }
-        if sz_u16 < sz_u32   && len <= (u16::MAX as usize) { return sort_by_key!(u16, self, f) }
-        if sz_u32 < sz_usize && len <= (u32::MAX as usize) { return sort_by_key!(u32, self, f) }
+        if len < 2 {
+            return;
+        }
+        if sz_u8 < sz_u16 && len <= (u8::MAX as usize) {
+            return sort_by_key!(u8, self, f);
+        }
+        if sz_u16 < sz_u32 && len <= (u16::MAX as usize) {
+            return sort_by_key!(u16, self, f);
+        }
+        if sz_u32 < sz_usize && len <= (u32::MAX as usize) {
+            return sort_by_key!(u32, self, f);
+        }
         sort_by_key!(usize, self, f)
     }
 
@@ -373,7 +387,8 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn to_vec(&self) -> Vec<T>
-        where T: Clone
+    where
+        T: Clone,
     {
         // N.B., see the `hack` module in this file for more details.
         hack::to_vec(self)
@@ -421,7 +436,10 @@ impl<T> [T] {
     /// b"0123456789abcdef".repeat(usize::max_value());
     /// ```
     #[stable(feature = "repeat_generic_slice", since = "1.40.0")]
-    pub fn repeat(&self, n: usize) -> Vec<T> where T: Copy {
+    pub fn repeat(&self, n: usize) -> Vec<T>
+    where
+        T: Copy,
+    {
         if n == 0 {
             return Vec::new();
         }
@@ -486,7 +504,8 @@ impl<T> [T] {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn concat<Item: ?Sized>(&self) -> <Self as Concat<Item>>::Output
-        where Self: Concat<Item>
+    where
+        Self: Concat<Item>,
     {
         Concat::concat(self)
     }
@@ -503,7 +522,8 @@ impl<T> [T] {
     /// ```
     #[stable(feature = "rename_connect_to_join", since = "1.3.0")]
     pub fn join<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
-        where Self: Join<Separator>
+    where
+        Self: Join<Separator>,
     {
         Join::join(self, sep)
     }
@@ -521,11 +541,11 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[rustc_deprecated(since = "1.3.0", reason = "renamed to join")]
     pub fn connect<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
-        where Self: Join<Separator>
+    where
+        Self: Join<Separator>,
     {
         Join::join(self, sep)
     }
-
 }
 
 #[lang = "slice_u8_alloc"]
@@ -668,8 +688,8 @@ impl<T: Clone, V: Borrow<[T]>> Join<&[T]> for [V] {
             Some(first) => first,
             None => return vec![],
         };
-        let size = slice.iter().map(|v| v.borrow().len()).sum::<usize>() +
-            sep.len() * (slice.len() - 1);
+        let size =
+            slice.iter().map(|v| v.borrow().len()).sum::<usize>() + sep.len() * (slice.len() - 1);
         let mut result = Vec::with_capacity(size);
         result.extend_from_slice(first.borrow());
 
@@ -734,7 +754,8 @@ impl<T: Clone> ToOwned for [T] {
 ///
 /// This is the integral subroutine of insertion sort.
 fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
-    where F: FnMut(&T, &T) -> bool
+where
+    F: FnMut(&T, &T) -> bool,
 {
     if v.len() >= 2 && is_less(&v[1], &v[0]) {
         unsafe {
@@ -767,10 +788,7 @@ fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
             // If `is_less` panics at any point during the process, `hole` will get dropped and
             // fill the hole in `v` with `tmp`, thus ensuring that `v` still holds every object it
             // initially held exactly once.
-            let mut hole = InsertionHole {
-                src: &mut *tmp,
-                dest: &mut v[1],
-            };
+            let mut hole = InsertionHole { src: &mut *tmp, dest: &mut v[1] };
             ptr::copy_nonoverlapping(&v[1], &mut v[0], 1);
 
             for i in 2..v.len() {
@@ -792,7 +810,9 @@ fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
 
     impl<T> Drop for InsertionHole<T> {
         fn drop(&mut self) {
-            unsafe { ptr::copy_nonoverlapping(self.src, self.dest, 1); }
+            unsafe {
+                ptr::copy_nonoverlapping(self.src, self.dest, 1);
+            }
         }
     }
 }
@@ -805,7 +825,8 @@ fn insert_head<T, F>(v: &mut [T], is_less: &mut F)
 /// The two slices must be non-empty and `mid` must be in bounds. Buffer `buf` must be long enough
 /// to hold a copy of the shorter slice. Also, `T` must not be a zero-sized type.
 unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
-    where F: FnMut(&T, &T) -> bool
+where
+    F: FnMut(&T, &T) -> bool,
 {
     let len = v.len();
     let v = v.as_mut_ptr();
@@ -834,11 +855,7 @@ unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
     if mid <= len - mid {
         // The left run is shorter.
         ptr::copy_nonoverlapping(v, buf, mid);
-        hole = MergeHole {
-            start: buf,
-            end: buf.add(mid),
-            dest: v,
-        };
+        hole = MergeHole { start: buf, end: buf.add(mid), dest: v };
 
         // Initially, these pointers point to the beginnings of their arrays.
         let left = &mut hole.start;
@@ -858,11 +875,7 @@ unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
     } else {
         // The right run is shorter.
         ptr::copy_nonoverlapping(v_mid, buf, len - mid);
-        hole = MergeHole {
-            start: buf,
-            end: buf.add(len - mid),
-            dest: v_mid,
-        };
+        hole = MergeHole { start: buf, end: buf.add(len - mid), dest: v_mid };
 
         // Initially, these pointers point past the ends of their arrays.
         let left = &mut hole.dest;
@@ -905,7 +918,9 @@ unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
         fn drop(&mut self) {
             // `T` is not a zero-sized type, so it's okay to divide by its size.
             let len = (self.end as usize - self.start as usize) / mem::size_of::<T>();
-            unsafe { ptr::copy_nonoverlapping(self.start, self.dest, len); }
+            unsafe {
+                ptr::copy_nonoverlapping(self.start, self.dest, len);
+            }
         }
     }
 }
@@ -923,7 +938,8 @@ unsafe fn merge<T, F>(v: &mut [T], mid: usize, buf: *mut T, is_less: &mut F)
 ///
 /// The invariants ensure that the total running time is `O(n log n)` worst-case.
 fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
-    where F: FnMut(&T, &T) -> bool
+where
+    F: FnMut(&T, &T) -> bool,
 {
     // Slices of up to this length get sorted using insertion sort.
     const MAX_INSERTION: usize = 20;
@@ -940,7 +956,7 @@ fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
     // Short arrays get sorted in-place via insertion sort to avoid allocations.
     if len <= MAX_INSERTION {
         if len >= 2 {
-            for i in (0..len-1).rev() {
+            for i in (0..len - 1).rev() {
                 insert_head(&mut v[i..], &mut is_less);
             }
         }
@@ -966,14 +982,13 @@ fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
             start -= 1;
             unsafe {
                 if is_less(v.get_unchecked(start + 1), v.get_unchecked(start)) {
-                    while start > 0 && is_less(v.get_unchecked(start),
-                                               v.get_unchecked(start - 1)) {
+                    while start > 0 && is_less(v.get_unchecked(start), v.get_unchecked(start - 1)) {
                         start -= 1;
                     }
                     v[start..end].reverse();
                 } else {
-                    while start > 0 && !is_less(v.get_unchecked(start),
-                                                v.get_unchecked(start - 1)) {
+                    while start > 0 && !is_less(v.get_unchecked(start), v.get_unchecked(start - 1))
+                    {
                         start -= 1;
                     }
                 }
@@ -988,10 +1003,7 @@ fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
         }
 
         // Push this run onto the stack.
-        runs.push(Run {
-            start,
-            len: end - start,
-        });
+        runs.push(Run { start, len: end - start });
         end = start;
 
         // Merge some pairs of adjacent runs to satisfy the invariants.
@@ -999,13 +1011,14 @@ fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
             let left = runs[r + 1];
             let right = runs[r];
             unsafe {
-                merge(&mut v[left.start .. right.start + right.len], left.len, buf.as_mut_ptr(),
-                      &mut is_less);
+                merge(
+                    &mut v[left.start..right.start + right.len],
+                    left.len,
+                    buf.as_mut_ptr(),
+                    &mut is_less,
+                );
             }
-            runs[r] = Run {
-                start: left.start,
-                len: left.len + right.len,
-            };
+            runs[r] = Run { start: left.start, len: left.len + right.len };
             runs.remove(r + 1);
         }
     }
@@ -1030,15 +1043,13 @@ fn merge_sort<T, F>(v: &mut [T], mut is_less: F)
     #[inline]
     fn collapse(runs: &[Run]) -> Option<usize> {
         let n = runs.len();
-        if n >= 2 && (runs[n - 1].start == 0 ||
-                      runs[n - 2].len <= runs[n - 1].len ||
-                      (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len) ||
-                      (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len)) {
-            if n >= 3 && runs[n - 3].len < runs[n - 1].len {
-                Some(n - 3)
-            } else {
-                Some(n - 2)
-            }
+        if n >= 2
+            && (runs[n - 1].start == 0
+                || runs[n - 2].len <= runs[n - 1].len
+                || (n >= 3 && runs[n - 3].len <= runs[n - 2].len + runs[n - 1].len)
+                || (n >= 4 && runs[n - 4].len <= runs[n - 3].len + runs[n - 2].len))
+        {
+            if n >= 3 && runs[n - 3].len < runs[n - 1].len { Some(n - 3) } else { Some(n - 2) }
         } else {
             None
         }
diff --git a/src/liballoc/tests.rs b/src/liballoc/tests.rs
index ed46ba8a1b9..1b6e0bb291c 100644
--- a/src/liballoc/tests.rs
+++ b/src/liballoc/tests.rs
@@ -1,12 +1,12 @@
 //! Test for `boxed` mod.
 
 use core::any::Any;
-use core::convert::TryInto;
-use core::ops::Deref;
-use core::result::Result::{Err, Ok};
 use core::clone::Clone;
+use core::convert::TryInto;
 use core::f64;
 use core::i64;
+use core::ops::Deref;
+use core::result::Result::{Err, Ok};
 
 use std::boxed::Box;
 
diff --git a/src/liballoc/tests/arc.rs b/src/liballoc/tests/arc.rs
index cf2ad2a8e60..2fbb59b0419 100644
--- a/src/liballoc/tests/arc.rs
+++ b/src/liballoc/tests/arc.rs
@@ -1,9 +1,9 @@
 use std::any::Any;
-use std::sync::{Arc, Weak};
 use std::cell::RefCell;
 use std::cmp::PartialEq;
 use std::iter::TrustedLen;
 use std::mem;
+use std::sync::{Arc, Weak};
 
 #[test]
 fn uninhabited() {
@@ -12,7 +12,7 @@ fn uninhabited() {
     a = a.clone();
     assert!(a.upgrade().is_none());
 
-    let mut a: Weak<dyn Any> = a;  // Unsizing
+    let mut a: Weak<dyn Any> = a; // Unsizing
     a = a.clone();
     assert!(a.upgrade().is_none());
 }
@@ -20,8 +20,8 @@ fn uninhabited() {
 #[test]
 fn slice() {
     let a: Arc<[u32; 3]> = Arc::new([3, 2, 1]);
-    let a: Arc<[u32]> = a;  // Unsizing
-    let b: Arc<[u32]> = Arc::from(&[3, 2, 1][..]);  // Conversion
+    let a: Arc<[u32]> = a; // Unsizing
+    let b: Arc<[u32]> = Arc::from(&[3, 2, 1][..]); // Conversion
     assert_eq!(a, b);
 
     // Exercise is_dangling() with a DST
@@ -33,7 +33,7 @@ fn slice() {
 #[test]
 fn trait_object() {
     let a: Arc<u32> = Arc::new(4);
-    let a: Arc<dyn Any> = a;  // Unsizing
+    let a: Arc<dyn Any> = a; // Unsizing
 
     // Exercise is_dangling() with a DST
     let mut a = Arc::downgrade(&a);
@@ -43,7 +43,7 @@ fn trait_object() {
     let mut b = Weak::<u32>::new();
     b = b.clone();
     assert!(b.upgrade().is_none());
-    let mut b: Weak<dyn Any> = b;  // Unsizing
+    let mut b: Weak<dyn Any> = b; // Unsizing
     b = b.clone();
     assert!(b.upgrade().is_none());
 }
@@ -57,7 +57,7 @@ fn float_nan_ne() {
 
 #[test]
 fn partial_eq() {
-    struct TestPEq (RefCell<usize>);
+    struct TestPEq(RefCell<usize>);
     impl PartialEq for TestPEq {
         fn eq(&self, other: &TestPEq) -> bool {
             *self.0.borrow_mut() += 1;
@@ -74,7 +74,7 @@ fn partial_eq() {
 #[test]
 fn eq() {
     #[derive(Eq)]
-    struct TestEq (RefCell<usize>);
+    struct TestEq(RefCell<usize>);
     impl PartialEq for TestEq {
         fn eq(&self, other: &TestEq) -> bool {
             *self.0.borrow_mut() += 1;
@@ -160,13 +160,10 @@ fn shared_from_iter_trustedlen_normal() {
 fn shared_from_iter_trustedlen_panic() {
     // Exercise the `TrustedLen` implementation when `size_hint()` matches
     // `(_, Some(exact_len))` but where `.next()` drops before the last iteration.
-    let iter = (0..SHARED_ITER_MAX)
-        .map(|val| {
-            match val {
-                98 => panic!("I've almost got 99 problems."),
-                _ => Box::new(val),
-            }
-        });
+    let iter = (0..SHARED_ITER_MAX).map(|val| match val {
+        98 => panic!("I've almost got 99 problems."),
+        _ => Box::new(val),
+    });
     assert_trusted_len(&iter);
     let _ = iter.collect::<Rc<[_]>>();
 
@@ -193,16 +190,8 @@ fn shared_from_iter_trustedlen_no_fuse() {
         }
     }
 
-    let vec = vec![
-        Some(Box::new(42)),
-        Some(Box::new(24)),
-        None,
-        Some(Box::new(12)),
-    ];
+    let vec = vec![Some(Box::new(42)), Some(Box::new(24)), None, Some(Box::new(12))];
     let iter = Iter(vec.into_iter());
     assert_trusted_len(&iter);
-    assert_eq!(
-        &[Box::new(42), Box::new(24)],
-        &*iter.collect::<Rc<[_]>>()
-    );
+    assert_eq!(&[Box::new(42), Box::new(24)], &*iter.collect::<Rc<[_]>>());
 }
diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs
index a44cf1eaf6d..a896a1064d9 100644
--- a/src/liballoc/tests/binary_heap.rs
+++ b/src/liballoc/tests/binary_heap.rs
@@ -347,7 +347,7 @@ fn assert_covariance() {
 // Destructors must be called exactly once per element.
 // FIXME: re-enable emscripten once it can unwind again
 #[test]
-#[cfg(not(any(miri, target_os = "emscripten")))] // Miri does not support catching panics
+#[cfg(not(target_os = "emscripten"))]
 fn panic_safe() {
     use std::cmp;
     use std::panic::{self, AssertUnwindSafe};
@@ -376,7 +376,10 @@ fn panic_safe() {
     }
     let mut rng = thread_rng();
     const DATASZ: usize = 32;
+    #[cfg(not(miri))] // Miri is too slow
     const NTEST: usize = 10;
+    #[cfg(miri)]
+    const NTEST: usize = 1;
 
     // don't use 0 in the data -- we want to catch the zeroed-out case.
     let data = (1..=DATASZ).collect::<Vec<_>>();
diff --git a/src/liballoc/tests/boxed.rs b/src/liballoc/tests/boxed.rs
index bc3d53bf30d..66782ecbeb7 100644
--- a/src/liballoc/tests/boxed.rs
+++ b/src/liballoc/tests/boxed.rs
@@ -1,5 +1,5 @@
-use std::ptr::NonNull;
 use std::mem::MaybeUninit;
+use std::ptr::NonNull;
 
 #[test]
 fn unitialized_zero_size_box() {
diff --git a/src/liballoc/tests/btree/mod.rs b/src/liballoc/tests/btree/mod.rs
index 4c704d0f8c2..1d08ae13e05 100644
--- a/src/liballoc/tests/btree/mod.rs
+++ b/src/liballoc/tests/btree/mod.rs
@@ -11,12 +11,7 @@ struct DeterministicRng {
 
 impl DeterministicRng {
     fn new() -> Self {
-        DeterministicRng {
-            x: 0x193a6754,
-            y: 0xa8a7d469,
-            z: 0x97830e05,
-            w: 0x113ba7bb,
-        }
+        DeterministicRng { x: 0x193a6754, y: 0xa8a7d469, z: 0x97830e05, w: 0x113ba7bb }
     }
 
     fn next(&mut self) -> u32 {
diff --git a/src/liballoc/tests/linked_list.rs b/src/liballoc/tests/linked_list.rs
index 8a26454c389..daa49c48c6a 100644
--- a/src/liballoc/tests/linked_list.rs
+++ b/src/liballoc/tests/linked_list.rs
@@ -102,7 +102,6 @@ fn test_split_off() {
         assert_eq!(m.back(), Some(&1));
         assert_eq!(m.front(), Some(&1));
     }
-
 }
 
 #[test]
@@ -305,8 +304,7 @@ fn test_show() {
     assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
 
     let list: LinkedList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
-    assert_eq!(format!("{:?}", list),
-               "[\"just\", \"one\", \"test\", \"more\"]");
+    assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]");
 }
 
 #[test]
@@ -446,19 +444,14 @@ fn drain_filter_true() {
 
 #[test]
 fn drain_filter_complex() {
-
-    {   //                [+xxx++++++xxxxx++++x+x++]
+    {
+        //                [+xxx++++++xxxxx++++x+x++]
         let mut list = vec![
-            1,
-            2, 4, 6,
-            7, 9, 11, 13, 15, 17,
-            18, 20, 22, 24, 26,
-            27, 29, 31, 33,
-            34,
-            35,
-            36,
-            37, 39
-        ].into_iter().collect::<LinkedList<_>>();
+            1, 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37,
+            39,
+        ]
+        .into_iter()
+        .collect::<LinkedList<_>>();
 
         let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
         assert_eq!(removed.len(), 10);
@@ -471,17 +464,13 @@ fn drain_filter_complex() {
         );
     }
 
-    {   // [xxx++++++xxxxx++++x+x++]
+    {
+        // [xxx++++++xxxxx++++x+x++]
         let mut list = vec![
-            2, 4, 6,
-            7, 9, 11, 13, 15, 17,
-            18, 20, 22, 24, 26,
-            27, 29, 31, 33,
-            34,
-            35,
-            36,
-            37, 39
-        ].into_iter().collect::<LinkedList<_>>();
+            2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39,
+        ]
+        .into_iter()
+        .collect::<LinkedList<_>>();
 
         let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
         assert_eq!(removed.len(), 10);
@@ -494,16 +483,12 @@ fn drain_filter_complex() {
         );
     }
 
-    {   // [xxx++++++xxxxx++++x+x]
-        let mut list = vec![
-            2, 4, 6,
-            7, 9, 11, 13, 15, 17,
-            18, 20, 22, 24, 26,
-            27, 29, 31, 33,
-            34,
-            35,
-            36
-        ].into_iter().collect::<LinkedList<_>>();
+    {
+        // [xxx++++++xxxxx++++x+x]
+        let mut list =
+            vec![2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36]
+                .into_iter()
+                .collect::<LinkedList<_>>();
 
         let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
         assert_eq!(removed.len(), 10);
@@ -516,11 +501,11 @@ fn drain_filter_complex() {
         );
     }
 
-    {   // [xxxxxxxxxx+++++++++++]
-        let mut list = vec![
-            2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
-            1, 3, 5, 7, 9, 11, 13, 15, 17, 19
-        ].into_iter().collect::<LinkedList<_>>();
+    {
+        // [xxxxxxxxxx+++++++++++]
+        let mut list = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
+            .into_iter()
+            .collect::<LinkedList<_>>();
 
         let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
         assert_eq!(removed.len(), 10);
@@ -530,11 +515,11 @@ fn drain_filter_complex() {
         assert_eq!(list.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]);
     }
 
-    {   // [+++++++++++xxxxxxxxxx]
-        let mut list = vec![
-            1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
-            2, 4, 6, 8, 10, 12, 14, 16, 18, 20
-        ].into_iter().collect::<LinkedList<_>>();
+    {
+        // [+++++++++++xxxxxxxxxx]
+        let mut list = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
+            .into_iter()
+            .collect::<LinkedList<_>>();
 
         let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
         assert_eq!(removed.len(), 10);
diff --git a/src/liballoc/tests/rc.rs b/src/liballoc/tests/rc.rs
index 7854ca0fc16..e77c57d9a5a 100644
--- a/src/liballoc/tests/rc.rs
+++ b/src/liballoc/tests/rc.rs
@@ -1,9 +1,9 @@
 use std::any::Any;
-use std::rc::{Rc, Weak};
 use std::cell::RefCell;
 use std::cmp::PartialEq;
-use std::mem;
 use std::iter::TrustedLen;
+use std::mem;
+use std::rc::{Rc, Weak};
 
 #[test]
 fn uninhabited() {
@@ -12,7 +12,7 @@ fn uninhabited() {
     a = a.clone();
     assert!(a.upgrade().is_none());
 
-    let mut a: Weak<dyn Any> = a;  // Unsizing
+    let mut a: Weak<dyn Any> = a; // Unsizing
     a = a.clone();
     assert!(a.upgrade().is_none());
 }
@@ -20,8 +20,8 @@ fn uninhabited() {
 #[test]
 fn slice() {
     let a: Rc<[u32; 3]> = Rc::new([3, 2, 1]);
-    let a: Rc<[u32]> = a;  // Unsizing
-    let b: Rc<[u32]> = Rc::from(&[3, 2, 1][..]);  // Conversion
+    let a: Rc<[u32]> = a; // Unsizing
+    let b: Rc<[u32]> = Rc::from(&[3, 2, 1][..]); // Conversion
     assert_eq!(a, b);
 
     // Exercise is_dangling() with a DST
@@ -33,7 +33,7 @@ fn slice() {
 #[test]
 fn trait_object() {
     let a: Rc<u32> = Rc::new(4);
-    let a: Rc<dyn Any> = a;  // Unsizing
+    let a: Rc<dyn Any> = a; // Unsizing
 
     // Exercise is_dangling() with a DST
     let mut a = Rc::downgrade(&a);
@@ -43,7 +43,7 @@ fn trait_object() {
     let mut b = Weak::<u32>::new();
     b = b.clone();
     assert!(b.upgrade().is_none());
-    let mut b: Weak<dyn Any> = b;  // Unsizing
+    let mut b: Weak<dyn Any> = b; // Unsizing
     b = b.clone();
     assert!(b.upgrade().is_none());
 }
@@ -57,7 +57,7 @@ fn float_nan_ne() {
 
 #[test]
 fn partial_eq() {
-    struct TestPEq (RefCell<usize>);
+    struct TestPEq(RefCell<usize>);
     impl PartialEq for TestPEq {
         fn eq(&self, other: &TestPEq) -> bool {
             *self.0.borrow_mut() += 1;
@@ -74,7 +74,7 @@ fn partial_eq() {
 #[test]
 fn eq() {
     #[derive(Eq)]
-    struct TestEq (RefCell<usize>);
+    struct TestEq(RefCell<usize>);
     impl PartialEq for TestEq {
         fn eq(&self, other: &TestEq) -> bool {
             *self.0.borrow_mut() += 1;
@@ -156,13 +156,10 @@ fn shared_from_iter_trustedlen_normal() {
 fn shared_from_iter_trustedlen_panic() {
     // Exercise the `TrustedLen` implementation when `size_hint()` matches
     // `(_, Some(exact_len))` but where `.next()` drops before the last iteration.
-    let iter = (0..SHARED_ITER_MAX)
-        .map(|val| {
-            match val {
-                98 => panic!("I've almost got 99 problems."),
-                _ => Box::new(val),
-            }
-        });
+    let iter = (0..SHARED_ITER_MAX).map(|val| match val {
+        98 => panic!("I've almost got 99 problems."),
+        _ => Box::new(val),
+    });
     assert_trusted_len(&iter);
     let _ = iter.collect::<Rc<[_]>>();
 
@@ -189,16 +186,8 @@ fn shared_from_iter_trustedlen_no_fuse() {
         }
     }
 
-    let vec = vec![
-        Some(Box::new(42)),
-        Some(Box::new(24)),
-        None,
-        Some(Box::new(12)),
-    ];
+    let vec = vec![Some(Box::new(42)), Some(Box::new(24)), None, Some(Box::new(12))];
     let iter = Iter(vec.into_iter());
     assert_trusted_len(&iter);
-    assert_eq!(
-        &[Box::new(42), Box::new(24)],
-        &*iter.collect::<Rc<[_]>>()
-    );
+    assert_eq!(&[Box::new(42), Box::new(24)], &*iter.collect::<Rc<[_]>>());
 }
diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs
index ad2cd7c95eb..d9707b95740 100644
--- a/src/liballoc/tests/slice.rs
+++ b/src/liballoc/tests/slice.rs
@@ -4,7 +4,6 @@ use std::mem;
 use std::panic;
 use std::rc::Rc;
 use std::sync::atomic::{Ordering::Relaxed, AtomicUsize};
-use std::thread;
 
 use rand::{Rng, RngCore, thread_rng};
 use rand::seq::SliceRandom;
@@ -1406,11 +1405,9 @@ fn test_box_slice_clone() {
 #[test]
 #[allow(unused_must_use)] // here, we care about the side effects of `.clone()`
 #[cfg_attr(target_os = "emscripten", ignore)]
-#[cfg(not(miri))] // Miri does not support threads
 fn test_box_slice_clone_panics() {
     use std::sync::Arc;
     use std::sync::atomic::{AtomicUsize, Ordering};
-    use std::thread::spawn;
 
     struct Canary {
         count: Arc<AtomicUsize>,
@@ -1446,7 +1443,7 @@ fn test_box_slice_clone_panics() {
         panics: true,
     };
 
-    spawn(move || {
+    std::panic::catch_unwind(move || {
             // When xs is dropped, +5.
             let xs = vec![canary.clone(), canary.clone(), canary.clone(), panic, canary]
                 .into_boxed_slice();
@@ -1454,7 +1451,6 @@ fn test_box_slice_clone_panics() {
             // When panic is cloned, +3.
             xs.clone();
         })
-        .join()
         .unwrap_err();
 
     // Total = 8
@@ -1566,7 +1562,7 @@ macro_rules! test {
             }
 
             let v = $input.to_owned();
-            let _ = thread::spawn(move || {
+            let _ = std::panic::catch_unwind(move || {
                 let mut v = v;
                 let mut panic_countdown = panic_countdown;
                 v.$func(|a, b| {
@@ -1577,7 +1573,7 @@ macro_rules! test {
                     panic_countdown -= 1;
                     a.cmp(b)
                 })
-            }).join();
+            });
 
             // Check that the number of things dropped is exactly
             // what we expect (i.e., the contents of `v`).
@@ -1598,7 +1594,6 @@ thread_local!(static SILENCE_PANIC: Cell<bool> = Cell::new(false));
 
 #[test]
 #[cfg_attr(target_os = "emscripten", ignore)] // no threads
-#[cfg(not(miri))] // Miri does not support threads
 fn panic_safe() {
     let prev = panic::take_hook();
     panic::set_hook(Box::new(move |info| {
@@ -1609,8 +1604,18 @@ fn panic_safe() {
 
     let mut rng = thread_rng();
 
-    for len in (1..20).chain(70..MAX_LEN) {
-        for &modulus in &[5, 20, 50] {
+    #[cfg(not(miri))] // Miri is too slow
+    let lens = (1..20).chain(70..MAX_LEN);
+    #[cfg(not(miri))] // Miri is too slow
+    let moduli = &[5, 20, 50];
+
+    #[cfg(miri)]
+    let lens = (1..13);
+    #[cfg(miri)]
+    let moduli = &[10];
+
+    for len in lens {
+        for &modulus in moduli {
             for &has_runs in &[false, true] {
                 let mut input = (0..len)
                     .map(|id| {
@@ -1643,6 +1648,9 @@ fn panic_safe() {
             }
         }
     }
+
+    // Set default panic hook again.
+    drop(panic::take_hook());
 }
 
 #[test]
diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs
index 0cc8da096f3..9ee254f99ac 100644
--- a/src/liballoc/tests/vec.rs
+++ b/src/liballoc/tests/vec.rs
@@ -944,10 +944,9 @@ fn drain_filter_complex() {
     }
 }
 
-// Miri does not support catching panics
 // FIXME: re-enable emscripten once it can unwind again
 #[test]
-#[cfg(not(any(miri, target_os = "emscripten")))]
+#[cfg(not(target_os = "emscripten"))]
 fn drain_filter_consumed_panic() {
     use std::rc::Rc;
     use std::sync::Mutex;
@@ -999,7 +998,7 @@ fn drain_filter_consumed_panic() {
 
 // FIXME: Re-enable emscripten once it can catch panics
 #[test]
-#[cfg(not(any(miri, target_os = "emscripten")))] // Miri does not support catching panics
+#[cfg(not(target_os = "emscripten"))]
 fn drain_filter_unconsumed_panic() {
     use std::rc::Rc;
     use std::sync::Mutex;
diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs
index d49b553fc02..5a0162a5361 100644
--- a/src/liballoc/tests/vec_deque.rs
+++ b/src/liballoc/tests/vec_deque.rs
@@ -1,8 +1,8 @@
-use std::fmt::Debug;
-use std::collections::{VecDeque, vec_deque::Drain};
 use std::collections::TryReserveError::*;
+use std::collections::{vec_deque::Drain, VecDeque};
+use std::fmt::Debug;
 use std::mem::size_of;
-use std::{usize, isize};
+use std::{isize, usize};
 
 use crate::hash;
 
@@ -148,34 +148,20 @@ fn test_param_taggy() {
 
 #[test]
 fn test_param_taggypar() {
-    test_parameterized::<Taggypar<i32>>(Onepar::<i32>(1),
-                                        Twopar::<i32>(1, 2),
-                                        Threepar::<i32>(1, 2, 3),
-                                        Twopar::<i32>(17, 42));
+    test_parameterized::<Taggypar<i32>>(
+        Onepar::<i32>(1),
+        Twopar::<i32>(1, 2),
+        Threepar::<i32>(1, 2, 3),
+        Twopar::<i32>(17, 42),
+    );
 }
 
 #[test]
 fn test_param_reccy() {
-    let reccy1 = RecCy {
-        x: 1,
-        y: 2,
-        t: One(1),
-    };
-    let reccy2 = RecCy {
-        x: 345,
-        y: 2,
-        t: Two(1, 2),
-    };
-    let reccy3 = RecCy {
-        x: 1,
-        y: 777,
-        t: Three(1, 2, 3),
-    };
-    let reccy4 = RecCy {
-        x: 19,
-        y: 252,
-        t: Two(17, 42),
-    };
+    let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
+    let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
+    let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
+    let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
     test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
 }
 
@@ -320,8 +306,7 @@ fn test_mut_rev_iter_wrap() {
     assert_eq!(d.pop_front(), Some(1));
     d.push_back(4);
 
-    assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<_>>(),
-               vec![4, 3, 2]);
+    assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<_>>(), vec![4, 3, 2]);
 }
 
 #[test]
@@ -372,7 +357,6 @@ fn test_mut_rev_iter() {
 
 #[test]
 fn test_into_iter() {
-
     // Empty iter
     {
         let d: VecDeque<i32> = VecDeque::new();
@@ -431,7 +415,6 @@ fn test_into_iter() {
 
 #[test]
 fn test_drain() {
-
     // Empty iter
     {
         let mut d: VecDeque<i32> = VecDeque::new();
@@ -650,12 +633,8 @@ fn test_show() {
     let ringbuf: VecDeque<_> = (0..10).collect();
     assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
 
-    let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"]
-        .iter()
-        .cloned()
-        .collect();
-    assert_eq!(format!("{:?}", ringbuf),
-               "[\"just\", \"one\", \"test\", \"more\"]");
+    let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
+    assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]");
 }
 
 #[test]
@@ -955,7 +934,6 @@ fn test_append_permutations() {
             // doesn't pop more values than are pushed
             for src_pop_back in 0..(src_push_back + src_push_front) {
                 for src_pop_front in 0..(src_push_back + src_push_front - src_pop_back) {
-
                     let src = construct_vec_deque(
                         src_push_back,
                         src_pop_back,
@@ -966,8 +944,8 @@ fn test_append_permutations() {
                     for dst_push_back in 0..MAX {
                         for dst_push_front in 0..MAX {
                             for dst_pop_back in 0..(dst_push_back + dst_push_front) {
-                                for dst_pop_front
-                                    in 0..(dst_push_back + dst_push_front - dst_pop_back)
+                                for dst_pop_front in
+                                    0..(dst_push_back + dst_push_front - dst_pop_back)
                                 {
                                     let mut dst = construct_vec_deque(
                                         dst_push_back,
@@ -1124,7 +1102,6 @@ fn test_reserve_exact_2() {
 #[test]
 #[cfg(not(miri))] // Miri does not support signalling OOM
 fn test_try_reserve() {
-
     // These are the interesting cases:
     // * exactly isize::MAX should never trigger a CapacityOverflow (can be OOM)
     // * > isize::MAX should always fail
@@ -1158,22 +1135,27 @@ fn test_try_reserve() {
         if guards_against_isize {
             // Check isize::MAX + 1 does count as overflow
             if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP + 1) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!")
+            }
 
             // Check usize::MAX does count as overflow
             if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_USIZE) {
-            } else { panic!("usize::MAX should trigger an overflow!") }
+            } else {
+                panic!("usize::MAX should trigger an overflow!")
+            }
         } else {
             // Check isize::MAX is an OOM
             // VecDeque starts with capacity 7, always adds 1 to the capacity
             // and also rounds the number to next power of 2 so this is the
             // furthest we can go without triggering CapacityOverflow
             if let Err(AllocError { .. }) = empty_bytes.try_reserve(MAX_CAP) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
     }
 
-
     {
         // Same basic idea, but with non-zero len
         let mut ten_bytes: VecDeque<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect();
@@ -1186,33 +1168,42 @@ fn test_try_reserve() {
         }
         if guards_against_isize {
             if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!"); }
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!");
+            }
         } else {
             if let Err(AllocError { .. }) = ten_bytes.try_reserve(MAX_CAP - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
         // Should always overflow in the add-to-len
         if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_USIZE) {
-        } else { panic!("usize::MAX should trigger an overflow!") }
+        } else {
+            panic!("usize::MAX should trigger an overflow!")
+        }
     }
 
-
     {
         // Same basic idea, but with interesting type size
         let mut ten_u32s: VecDeque<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect();
 
-        if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) {
+        if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10) {
             panic!("isize::MAX shouldn't trigger an overflow!");
         }
-        if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 10) {
+        if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10) {
             panic!("isize::MAX shouldn't trigger an overflow!");
         }
         if guards_against_isize {
-            if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!"); }
+            if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 9) {
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!");
+            }
         } else {
-            if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP/4 - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            if let Err(AllocError { .. }) = ten_u32s.try_reserve(MAX_CAP / 4 - 9) {
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
         // Should fail in the mul-by-size
         if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_USIZE - 20) {
@@ -1220,13 +1211,11 @@ fn test_try_reserve() {
             panic!("usize::MAX should trigger an overflow!");
         }
     }
-
 }
 
 #[test]
 #[cfg(not(miri))] // Miri does not support signalling OOM
 fn test_try_reserve_exact() {
-
     // This is exactly the same as test_try_reserve with the method changed.
     // See that test for comments.
 
@@ -1247,21 +1236,26 @@ fn test_try_reserve_exact() {
 
         if guards_against_isize {
             if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP + 1) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!")
+            }
 
             if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_USIZE) {
-            } else { panic!("usize::MAX should trigger an overflow!") }
+            } else {
+                panic!("usize::MAX should trigger an overflow!")
+            }
         } else {
             // Check isize::MAX is an OOM
             // VecDeque starts with capacity 7, always adds 1 to the capacity
             // and also rounds the number to next power of 2 so this is the
             // furthest we can go without triggering CapacityOverflow
             if let Err(AllocError { .. }) = empty_bytes.try_reserve_exact(MAX_CAP) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
     }
 
-
     {
         let mut ten_bytes: VecDeque<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect();
 
@@ -1273,36 +1267,46 @@ fn test_try_reserve_exact() {
         }
         if guards_against_isize {
             if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!"); }
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!");
+            }
         } else {
             if let Err(AllocError { .. }) = ten_bytes.try_reserve_exact(MAX_CAP - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
         if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_USIZE) {
-        } else { panic!("usize::MAX should trigger an overflow!") }
+        } else {
+            panic!("usize::MAX should trigger an overflow!")
+        }
     }
 
-
     {
         let mut ten_u32s: VecDeque<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect();
 
-        if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) {
+        if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10) {
             panic!("isize::MAX shouldn't trigger an overflow!");
         }
-        if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 10) {
+        if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10) {
             panic!("isize::MAX shouldn't trigger an overflow!");
         }
         if guards_against_isize {
-            if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an overflow!"); }
+            if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 9) {
+            } else {
+                panic!("isize::MAX + 1 should trigger an overflow!");
+            }
         } else {
-            if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP/4 - 9) {
-            } else { panic!("isize::MAX + 1 should trigger an OOM!") }
+            if let Err(AllocError { .. }) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 9) {
+            } else {
+                panic!("isize::MAX + 1 should trigger an OOM!")
+            }
         }
         if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_USIZE - 20) {
-        } else { panic!("usize::MAX should trigger an overflow!") }
+        } else {
+            panic!("usize::MAX should trigger an overflow!")
+        }
     }
-
 }
 
 #[test]
@@ -1404,9 +1408,8 @@ fn test_rotate_right_parts() {
 #[test]
 fn test_rotate_left_random() {
     let shifts = [
-        6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1,
-        4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11,
-        9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2,
+        6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, 9, 4, 12, 3,
+        12, 9, 11, 1, 7, 9, 7, 2,
     ];
     let n = 12;
     let mut v: VecDeque<_> = (0..n).collect();
@@ -1423,9 +1426,8 @@ fn test_rotate_left_random() {
 #[test]
 fn test_rotate_right_random() {
     let shifts = [
-        6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1,
-        4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11,
-        9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2,
+        6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, 9, 4, 12, 3,
+        12, 9, 11, 1, 7, 9, 7, 2,
     ];
     let n = 12;
     let mut v: VecDeque<_> = (0..n).collect();
@@ -1447,8 +1449,7 @@ fn test_try_fold_empty() {
 #[test]
 fn test_try_fold_none() {
     let v: VecDeque<u32> = (0..12).collect();
-    assert_eq!(None, v.into_iter().try_fold(0, |a, b|
-        if b < 11 { Some(a + b) } else { None }));
+    assert_eq!(None, v.into_iter().try_fold(0, |a, b| if b < 11 { Some(a + b) } else { None }));
 }
 
 #[test]
@@ -1463,7 +1464,6 @@ fn test_try_fold_unit() {
     assert_eq!(Some(()), v.into_iter().try_fold((), |(), ()| Some(())));
 }
 
-
 #[test]
 fn test_try_fold_unit_none() {
     let v: std::collections::VecDeque<()> = [(); 10].iter().cloned().collect();
@@ -1534,7 +1534,7 @@ fn test_try_rfold_rotated() {
 
 #[test]
 fn test_try_rfold_moves_iter() {
-    let v : VecDeque<_> = [10, 20, 30, 40, 100, 60, 70, 80, 90].iter().collect();
+    let v: VecDeque<_> = [10, 20, 30, 40, 100, 60, 70, 80, 90].iter().collect();
     let mut iter = v.into_iter();
     assert_eq!(iter.try_rfold(0_i8, |acc, &x| acc.checked_add(x)), None);
     assert_eq!(iter.next_back(), Some(&70));
diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs
index 8892e186d0a..1a700b99056 100644
--- a/src/liballoc/vec.rs
+++ b/src/liballoc/vec.rs
@@ -2703,6 +2703,9 @@ impl<T> ExactSizeIterator for Drain<'_, T> {
     }
 }
 
+#[unstable(feature = "trusted_len", issue = "37572")]
+unsafe impl<T> TrustedLen for Drain<'_, T> {}
+
 #[stable(feature = "fused", since = "1.26.0")]
 impl<T> FusedIterator for Drain<'_, T> {}
 
diff --git a/src/libcore/any.rs b/src/libcore/any.rs
index 57a2aecd8be..466750fc7d2 100644
--- a/src/libcore/any.rs
+++ b/src/libcore/any.rs
@@ -68,7 +68,7 @@ use crate::intrinsics;
 // Any trait
 ///////////////////////////////////////////////////////////////////////////////
 
-/// A type to emulate dynamic typing.
+/// A trait to emulate dynamic typing.
 ///
 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
 /// See the [module-level documentation][mod] for more details.
diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs
index e3dc5630c94..d4952f53bf7 100644
--- a/src/libcore/intrinsics.rs
+++ b/src/libcore/intrinsics.rs
@@ -1348,9 +1348,11 @@ extern "rust-intrinsic" {
     pub fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
 
     /// Internal hook used by Miri to implement unwinding.
+    /// Compiles to a NOP during non-Miri codegen.
+    ///
     /// Perma-unstable: do not use
     #[cfg(not(bootstrap))]
-    pub fn miri_start_panic(data: *mut (dyn crate::any::Any + crate::marker::Send)) -> !;
+    pub fn miri_start_panic(data: *mut (dyn crate::any::Any + crate::marker::Send)) -> ();
 }
 
 // Some functions are defined here because they accidentally got made
diff --git a/src/libcore/num/dec2flt/table.rs b/src/libcore/num/dec2flt/table.rs
index 345ac830aaa..1bd94ffa04e 100644
--- a/src/libcore/num/dec2flt/table.rs
+++ b/src/libcore/num/dec2flt/table.rs
@@ -4,1232 +4,1237 @@
 pub const MIN_E: i16 = -305;
 pub const MAX_E: i16 = 305;
 
-pub const POWERS: ([u64; 611], [i16; 611]) = ([
-    0xe0b62e2929aba83c,
-    0x8c71dcd9ba0b4926,
-    0xaf8e5410288e1b6f,
-    0xdb71e91432b1a24b,
-    0x892731ac9faf056f,
-    0xab70fe17c79ac6ca,
-    0xd64d3d9db981787d,
-    0x85f0468293f0eb4e,
-    0xa76c582338ed2622,
-    0xd1476e2c07286faa,
-    0x82cca4db847945ca,
-    0xa37fce126597973d,
-    0xcc5fc196fefd7d0c,
-    0xff77b1fcbebcdc4f,
-    0x9faacf3df73609b1,
-    0xc795830d75038c1e,
-    0xf97ae3d0d2446f25,
-    0x9becce62836ac577,
-    0xc2e801fb244576d5,
-    0xf3a20279ed56d48a,
-    0x9845418c345644d7,
-    0xbe5691ef416bd60c,
-    0xedec366b11c6cb8f,
-    0x94b3a202eb1c3f39,
-    0xb9e08a83a5e34f08,
-    0xe858ad248f5c22ca,
-    0x91376c36d99995be,
-    0xb58547448ffffb2e,
-    0xe2e69915b3fff9f9,
-    0x8dd01fad907ffc3c,
-    0xb1442798f49ffb4b,
-    0xdd95317f31c7fa1d,
-    0x8a7d3eef7f1cfc52,
-    0xad1c8eab5ee43b67,
-    0xd863b256369d4a41,
-    0x873e4f75e2224e68,
-    0xa90de3535aaae202,
-    0xd3515c2831559a83,
-    0x8412d9991ed58092,
-    0xa5178fff668ae0b6,
-    0xce5d73ff402d98e4,
-    0x80fa687f881c7f8e,
-    0xa139029f6a239f72,
-    0xc987434744ac874f,
-    0xfbe9141915d7a922,
-    0x9d71ac8fada6c9b5,
-    0xc4ce17b399107c23,
-    0xf6019da07f549b2b,
-    0x99c102844f94e0fb,
-    0xc0314325637a193a,
-    0xf03d93eebc589f88,
-    0x96267c7535b763b5,
-    0xbbb01b9283253ca3,
-    0xea9c227723ee8bcb,
-    0x92a1958a7675175f,
-    0xb749faed14125d37,
-    0xe51c79a85916f485,
-    0x8f31cc0937ae58d3,
-    0xb2fe3f0b8599ef08,
-    0xdfbdcece67006ac9,
-    0x8bd6a141006042be,
-    0xaecc49914078536d,
-    0xda7f5bf590966849,
-    0x888f99797a5e012d,
-    0xaab37fd7d8f58179,
-    0xd5605fcdcf32e1d7,
-    0x855c3be0a17fcd26,
-    0xa6b34ad8c9dfc070,
-    0xd0601d8efc57b08c,
-    0x823c12795db6ce57,
-    0xa2cb1717b52481ed,
-    0xcb7ddcdda26da269,
-    0xfe5d54150b090b03,
-    0x9efa548d26e5a6e2,
-    0xc6b8e9b0709f109a,
-    0xf867241c8cc6d4c1,
-    0x9b407691d7fc44f8,
-    0xc21094364dfb5637,
-    0xf294b943e17a2bc4,
-    0x979cf3ca6cec5b5b,
-    0xbd8430bd08277231,
-    0xece53cec4a314ebe,
-    0x940f4613ae5ed137,
-    0xb913179899f68584,
-    0xe757dd7ec07426e5,
-    0x9096ea6f3848984f,
-    0xb4bca50b065abe63,
-    0xe1ebce4dc7f16dfc,
-    0x8d3360f09cf6e4bd,
-    0xb080392cc4349ded,
-    0xdca04777f541c568,
-    0x89e42caaf9491b61,
-    0xac5d37d5b79b6239,
-    0xd77485cb25823ac7,
-    0x86a8d39ef77164bd,
-    0xa8530886b54dbdec,
-    0xd267caa862a12d67,
-    0x8380dea93da4bc60,
-    0xa46116538d0deb78,
-    0xcd795be870516656,
-    0x806bd9714632dff6,
-    0xa086cfcd97bf97f4,
-    0xc8a883c0fdaf7df0,
-    0xfad2a4b13d1b5d6c,
-    0x9cc3a6eec6311a64,
-    0xc3f490aa77bd60fd,
-    0xf4f1b4d515acb93c,
-    0x991711052d8bf3c5,
-    0xbf5cd54678eef0b7,
-    0xef340a98172aace5,
-    0x9580869f0e7aac0f,
-    0xbae0a846d2195713,
-    0xe998d258869facd7,
-    0x91ff83775423cc06,
-    0xb67f6455292cbf08,
-    0xe41f3d6a7377eeca,
-    0x8e938662882af53e,
-    0xb23867fb2a35b28e,
-    0xdec681f9f4c31f31,
-    0x8b3c113c38f9f37f,
-    0xae0b158b4738705f,
-    0xd98ddaee19068c76,
-    0x87f8a8d4cfa417ca,
-    0xa9f6d30a038d1dbc,
-    0xd47487cc8470652b,
-    0x84c8d4dfd2c63f3b,
-    0xa5fb0a17c777cf0a,
-    0xcf79cc9db955c2cc,
-    0x81ac1fe293d599c0,
-    0xa21727db38cb0030,
-    0xca9cf1d206fdc03c,
-    0xfd442e4688bd304b,
-    0x9e4a9cec15763e2f,
-    0xc5dd44271ad3cdba,
-    0xf7549530e188c129,
-    0x9a94dd3e8cf578ba,
-    0xc13a148e3032d6e8,
-    0xf18899b1bc3f8ca2,
-    0x96f5600f15a7b7e5,
-    0xbcb2b812db11a5de,
-    0xebdf661791d60f56,
-    0x936b9fcebb25c996,
-    0xb84687c269ef3bfb,
-    0xe65829b3046b0afa,
-    0x8ff71a0fe2c2e6dc,
-    0xb3f4e093db73a093,
-    0xe0f218b8d25088b8,
-    0x8c974f7383725573,
-    0xafbd2350644eead0,
-    0xdbac6c247d62a584,
-    0x894bc396ce5da772,
-    0xab9eb47c81f5114f,
-    0xd686619ba27255a3,
-    0x8613fd0145877586,
-    0xa798fc4196e952e7,
-    0xd17f3b51fca3a7a1,
-    0x82ef85133de648c5,
-    0xa3ab66580d5fdaf6,
-    0xcc963fee10b7d1b3,
-    0xffbbcfe994e5c620,
-    0x9fd561f1fd0f9bd4,
-    0xc7caba6e7c5382c9,
-    0xf9bd690a1b68637b,
-    0x9c1661a651213e2d,
-    0xc31bfa0fe5698db8,
-    0xf3e2f893dec3f126,
-    0x986ddb5c6b3a76b8,
-    0xbe89523386091466,
-    0xee2ba6c0678b597f,
-    0x94db483840b717f0,
-    0xba121a4650e4ddec,
-    0xe896a0d7e51e1566,
-    0x915e2486ef32cd60,
-    0xb5b5ada8aaff80b8,
-    0xe3231912d5bf60e6,
-    0x8df5efabc5979c90,
-    0xb1736b96b6fd83b4,
-    0xddd0467c64bce4a1,
-    0x8aa22c0dbef60ee4,
-    0xad4ab7112eb3929e,
-    0xd89d64d57a607745,
-    0x87625f056c7c4a8b,
-    0xa93af6c6c79b5d2e,
-    0xd389b47879823479,
-    0x843610cb4bf160cc,
-    0xa54394fe1eedb8ff,
-    0xce947a3da6a9273e,
-    0x811ccc668829b887,
-    0xa163ff802a3426a9,
-    0xc9bcff6034c13053,
-    0xfc2c3f3841f17c68,
-    0x9d9ba7832936edc1,
-    0xc5029163f384a931,
-    0xf64335bcf065d37d,
-    0x99ea0196163fa42e,
-    0xc06481fb9bcf8d3a,
-    0xf07da27a82c37088,
-    0x964e858c91ba2655,
-    0xbbe226efb628afeb,
-    0xeadab0aba3b2dbe5,
-    0x92c8ae6b464fc96f,
-    0xb77ada0617e3bbcb,
-    0xe55990879ddcaabe,
-    0x8f57fa54c2a9eab7,
-    0xb32df8e9f3546564,
-    0xdff9772470297ebd,
-    0x8bfbea76c619ef36,
-    0xaefae51477a06b04,
-    0xdab99e59958885c5,
-    0x88b402f7fd75539b,
-    0xaae103b5fcd2a882,
-    0xd59944a37c0752a2,
-    0x857fcae62d8493a5,
-    0xa6dfbd9fb8e5b88f,
-    0xd097ad07a71f26b2,
-    0x825ecc24c8737830,
-    0xa2f67f2dfa90563b,
-    0xcbb41ef979346bca,
-    0xfea126b7d78186bd,
-    0x9f24b832e6b0f436,
-    0xc6ede63fa05d3144,
-    0xf8a95fcf88747d94,
-    0x9b69dbe1b548ce7d,
-    0xc24452da229b021c,
-    0xf2d56790ab41c2a3,
-    0x97c560ba6b0919a6,
-    0xbdb6b8e905cb600f,
-    0xed246723473e3813,
-    0x9436c0760c86e30c,
-    0xb94470938fa89bcf,
-    0xe7958cb87392c2c3,
-    0x90bd77f3483bb9ba,
-    0xb4ecd5f01a4aa828,
-    0xe2280b6c20dd5232,
-    0x8d590723948a535f,
-    0xb0af48ec79ace837,
-    0xdcdb1b2798182245,
-    0x8a08f0f8bf0f156b,
-    0xac8b2d36eed2dac6,
-    0xd7adf884aa879177,
-    0x86ccbb52ea94baeb,
-    0xa87fea27a539e9a5,
-    0xd29fe4b18e88640f,
-    0x83a3eeeef9153e89,
-    0xa48ceaaab75a8e2b,
-    0xcdb02555653131b6,
-    0x808e17555f3ebf12,
-    0xa0b19d2ab70e6ed6,
-    0xc8de047564d20a8c,
-    0xfb158592be068d2f,
-    0x9ced737bb6c4183d,
-    0xc428d05aa4751e4d,
-    0xf53304714d9265e0,
-    0x993fe2c6d07b7fac,
-    0xbf8fdb78849a5f97,
-    0xef73d256a5c0f77d,
-    0x95a8637627989aae,
-    0xbb127c53b17ec159,
-    0xe9d71b689dde71b0,
-    0x9226712162ab070e,
-    0xb6b00d69bb55c8d1,
-    0xe45c10c42a2b3b06,
-    0x8eb98a7a9a5b04e3,
-    0xb267ed1940f1c61c,
-    0xdf01e85f912e37a3,
-    0x8b61313bbabce2c6,
-    0xae397d8aa96c1b78,
-    0xd9c7dced53c72256,
-    0x881cea14545c7575,
-    0xaa242499697392d3,
-    0xd4ad2dbfc3d07788,
-    0x84ec3c97da624ab5,
-    0xa6274bbdd0fadd62,
-    0xcfb11ead453994ba,
-    0x81ceb32c4b43fcf5,
-    0xa2425ff75e14fc32,
-    0xcad2f7f5359a3b3e,
-    0xfd87b5f28300ca0e,
-    0x9e74d1b791e07e48,
-    0xc612062576589ddb,
-    0xf79687aed3eec551,
-    0x9abe14cd44753b53,
-    0xc16d9a0095928a27,
-    0xf1c90080baf72cb1,
-    0x971da05074da7bef,
-    0xbce5086492111aeb,
-    0xec1e4a7db69561a5,
-    0x9392ee8e921d5d07,
-    0xb877aa3236a4b449,
-    0xe69594bec44de15b,
-    0x901d7cf73ab0acd9,
-    0xb424dc35095cd80f,
-    0xe12e13424bb40e13,
-    0x8cbccc096f5088cc,
-    0xafebff0bcb24aaff,
-    0xdbe6fecebdedd5bf,
-    0x89705f4136b4a597,
-    0xabcc77118461cefd,
-    0xd6bf94d5e57a42bc,
-    0x8637bd05af6c69b6,
-    0xa7c5ac471b478423,
-    0xd1b71758e219652c,
-    0x83126e978d4fdf3b,
-    0xa3d70a3d70a3d70a,
-    0xcccccccccccccccd,
-    0x8000000000000000,
-    0xa000000000000000,
-    0xc800000000000000,
-    0xfa00000000000000,
-    0x9c40000000000000,
-    0xc350000000000000,
-    0xf424000000000000,
-    0x9896800000000000,
-    0xbebc200000000000,
-    0xee6b280000000000,
-    0x9502f90000000000,
-    0xba43b74000000000,
-    0xe8d4a51000000000,
-    0x9184e72a00000000,
-    0xb5e620f480000000,
-    0xe35fa931a0000000,
-    0x8e1bc9bf04000000,
-    0xb1a2bc2ec5000000,
-    0xde0b6b3a76400000,
-    0x8ac7230489e80000,
-    0xad78ebc5ac620000,
-    0xd8d726b7177a8000,
-    0x878678326eac9000,
-    0xa968163f0a57b400,
-    0xd3c21bcecceda100,
-    0x84595161401484a0,
-    0xa56fa5b99019a5c8,
-    0xcecb8f27f4200f3a,
-    0x813f3978f8940984,
-    0xa18f07d736b90be5,
-    0xc9f2c9cd04674edf,
-    0xfc6f7c4045812296,
-    0x9dc5ada82b70b59e,
-    0xc5371912364ce305,
-    0xf684df56c3e01bc7,
-    0x9a130b963a6c115c,
-    0xc097ce7bc90715b3,
-    0xf0bdc21abb48db20,
-    0x96769950b50d88f4,
-    0xbc143fa4e250eb31,
-    0xeb194f8e1ae525fd,
-    0x92efd1b8d0cf37be,
-    0xb7abc627050305ae,
-    0xe596b7b0c643c719,
-    0x8f7e32ce7bea5c70,
-    0xb35dbf821ae4f38c,
-    0xe0352f62a19e306f,
-    0x8c213d9da502de45,
-    0xaf298d050e4395d7,
-    0xdaf3f04651d47b4c,
-    0x88d8762bf324cd10,
-    0xab0e93b6efee0054,
-    0xd5d238a4abe98068,
-    0x85a36366eb71f041,
-    0xa70c3c40a64e6c52,
-    0xd0cf4b50cfe20766,
-    0x82818f1281ed44a0,
-    0xa321f2d7226895c8,
-    0xcbea6f8ceb02bb3a,
-    0xfee50b7025c36a08,
-    0x9f4f2726179a2245,
-    0xc722f0ef9d80aad6,
-    0xf8ebad2b84e0d58c,
-    0x9b934c3b330c8577,
-    0xc2781f49ffcfa6d5,
-    0xf316271c7fc3908b,
-    0x97edd871cfda3a57,
-    0xbde94e8e43d0c8ec,
-    0xed63a231d4c4fb27,
-    0x945e455f24fb1cf9,
-    0xb975d6b6ee39e437,
-    0xe7d34c64a9c85d44,
-    0x90e40fbeea1d3a4b,
-    0xb51d13aea4a488dd,
-    0xe264589a4dcdab15,
-    0x8d7eb76070a08aed,
-    0xb0de65388cc8ada8,
-    0xdd15fe86affad912,
-    0x8a2dbf142dfcc7ab,
-    0xacb92ed9397bf996,
-    0xd7e77a8f87daf7fc,
-    0x86f0ac99b4e8dafd,
-    0xa8acd7c0222311bd,
-    0xd2d80db02aabd62c,
-    0x83c7088e1aab65db,
-    0xa4b8cab1a1563f52,
-    0xcde6fd5e09abcf27,
-    0x80b05e5ac60b6178,
-    0xa0dc75f1778e39d6,
-    0xc913936dd571c84c,
-    0xfb5878494ace3a5f,
-    0x9d174b2dcec0e47b,
-    0xc45d1df942711d9a,
-    0xf5746577930d6501,
-    0x9968bf6abbe85f20,
-    0xbfc2ef456ae276e9,
-    0xefb3ab16c59b14a3,
-    0x95d04aee3b80ece6,
-    0xbb445da9ca61281f,
-    0xea1575143cf97227,
-    0x924d692ca61be758,
-    0xb6e0c377cfa2e12e,
-    0xe498f455c38b997a,
-    0x8edf98b59a373fec,
-    0xb2977ee300c50fe7,
-    0xdf3d5e9bc0f653e1,
-    0x8b865b215899f46d,
-    0xae67f1e9aec07188,
-    0xda01ee641a708dea,
-    0x884134fe908658b2,
-    0xaa51823e34a7eedf,
-    0xd4e5e2cdc1d1ea96,
-    0x850fadc09923329e,
-    0xa6539930bf6bff46,
-    0xcfe87f7cef46ff17,
-    0x81f14fae158c5f6e,
-    0xa26da3999aef774a,
-    0xcb090c8001ab551c,
-    0xfdcb4fa002162a63,
-    0x9e9f11c4014dda7e,
-    0xc646d63501a1511e,
-    0xf7d88bc24209a565,
-    0x9ae757596946075f,
-    0xc1a12d2fc3978937,
-    0xf209787bb47d6b85,
-    0x9745eb4d50ce6333,
-    0xbd176620a501fc00,
-    0xec5d3fa8ce427b00,
-    0x93ba47c980e98ce0,
-    0xb8a8d9bbe123f018,
-    0xe6d3102ad96cec1e,
-    0x9043ea1ac7e41393,
-    0xb454e4a179dd1877,
-    0xe16a1dc9d8545e95,
-    0x8ce2529e2734bb1d,
-    0xb01ae745b101e9e4,
-    0xdc21a1171d42645d,
-    0x899504ae72497eba,
-    0xabfa45da0edbde69,
-    0xd6f8d7509292d603,
-    0x865b86925b9bc5c2,
-    0xa7f26836f282b733,
-    0xd1ef0244af2364ff,
-    0x8335616aed761f1f,
-    0xa402b9c5a8d3a6e7,
-    0xcd036837130890a1,
-    0x802221226be55a65,
-    0xa02aa96b06deb0fe,
-    0xc83553c5c8965d3d,
-    0xfa42a8b73abbf48d,
-    0x9c69a97284b578d8,
-    0xc38413cf25e2d70e,
-    0xf46518c2ef5b8cd1,
-    0x98bf2f79d5993803,
-    0xbeeefb584aff8604,
-    0xeeaaba2e5dbf6785,
-    0x952ab45cfa97a0b3,
-    0xba756174393d88e0,
-    0xe912b9d1478ceb17,
-    0x91abb422ccb812ef,
-    0xb616a12b7fe617aa,
-    0xe39c49765fdf9d95,
-    0x8e41ade9fbebc27d,
-    0xb1d219647ae6b31c,
-    0xde469fbd99a05fe3,
-    0x8aec23d680043bee,
-    0xada72ccc20054aea,
-    0xd910f7ff28069da4,
-    0x87aa9aff79042287,
-    0xa99541bf57452b28,
-    0xd3fa922f2d1675f2,
-    0x847c9b5d7c2e09b7,
-    0xa59bc234db398c25,
-    0xcf02b2c21207ef2f,
-    0x8161afb94b44f57d,
-    0xa1ba1ba79e1632dc,
-    0xca28a291859bbf93,
-    0xfcb2cb35e702af78,
-    0x9defbf01b061adab,
-    0xc56baec21c7a1916,
-    0xf6c69a72a3989f5c,
-    0x9a3c2087a63f6399,
-    0xc0cb28a98fcf3c80,
-    0xf0fdf2d3f3c30b9f,
-    0x969eb7c47859e744,
-    0xbc4665b596706115,
-    0xeb57ff22fc0c795a,
-    0x9316ff75dd87cbd8,
-    0xb7dcbf5354e9bece,
-    0xe5d3ef282a242e82,
-    0x8fa475791a569d11,
-    0xb38d92d760ec4455,
-    0xe070f78d3927556b,
-    0x8c469ab843b89563,
-    0xaf58416654a6babb,
-    0xdb2e51bfe9d0696a,
-    0x88fcf317f22241e2,
-    0xab3c2fddeeaad25b,
-    0xd60b3bd56a5586f2,
-    0x85c7056562757457,
-    0xa738c6bebb12d16d,
-    0xd106f86e69d785c8,
-    0x82a45b450226b39d,
-    0xa34d721642b06084,
-    0xcc20ce9bd35c78a5,
-    0xff290242c83396ce,
-    0x9f79a169bd203e41,
-    0xc75809c42c684dd1,
-    0xf92e0c3537826146,
-    0x9bbcc7a142b17ccc,
-    0xc2abf989935ddbfe,
-    0xf356f7ebf83552fe,
-    0x98165af37b2153df,
-    0xbe1bf1b059e9a8d6,
-    0xeda2ee1c7064130c,
-    0x9485d4d1c63e8be8,
-    0xb9a74a0637ce2ee1,
-    0xe8111c87c5c1ba9a,
-    0x910ab1d4db9914a0,
-    0xb54d5e4a127f59c8,
-    0xe2a0b5dc971f303a,
-    0x8da471a9de737e24,
-    0xb10d8e1456105dad,
-    0xdd50f1996b947519,
-    0x8a5296ffe33cc930,
-    0xace73cbfdc0bfb7b,
-    0xd8210befd30efa5a,
-    0x8714a775e3e95c78,
-    0xa8d9d1535ce3b396,
-    0xd31045a8341ca07c,
-    0x83ea2b892091e44e,
-    0xa4e4b66b68b65d61,
-    0xce1de40642e3f4b9,
-    0x80d2ae83e9ce78f4,
-    0xa1075a24e4421731,
-    0xc94930ae1d529cfd,
-    0xfb9b7cd9a4a7443c,
-    0x9d412e0806e88aa6,
-    0xc491798a08a2ad4f,
-    0xf5b5d7ec8acb58a3,
-    0x9991a6f3d6bf1766,
-    0xbff610b0cc6edd3f,
-    0xeff394dcff8a948f,
-    0x95f83d0a1fb69cd9,
-    0xbb764c4ca7a44410,
-    0xea53df5fd18d5514,
-    0x92746b9be2f8552c,
-    0xb7118682dbb66a77,
-    0xe4d5e82392a40515,
-    0x8f05b1163ba6832d,
-    0xb2c71d5bca9023f8,
-    0xdf78e4b2bd342cf7,
-    0x8bab8eefb6409c1a,
-    0xae9672aba3d0c321,
-    0xda3c0f568cc4f3e9,
-    0x8865899617fb1871,
-    0xaa7eebfb9df9de8e,
-    0xd51ea6fa85785631,
-    0x8533285c936b35df,
-    0xa67ff273b8460357,
-    0xd01fef10a657842c,
-    0x8213f56a67f6b29c,
-    0xa298f2c501f45f43,
-    0xcb3f2f7642717713,
-    0xfe0efb53d30dd4d8,
-    0x9ec95d1463e8a507,
-    0xc67bb4597ce2ce49,
-    0xf81aa16fdc1b81db,
-    0x9b10a4e5e9913129,
-    0xc1d4ce1f63f57d73,
-    0xf24a01a73cf2dcd0,
-    0x976e41088617ca02,
-    0xbd49d14aa79dbc82,
-    0xec9c459d51852ba3,
-    0x93e1ab8252f33b46,
-    0xb8da1662e7b00a17,
-    0xe7109bfba19c0c9d,
-    0x906a617d450187e2,
-    0xb484f9dc9641e9db,
-    0xe1a63853bbd26451,
-    0x8d07e33455637eb3,
-    0xb049dc016abc5e60,
-    0xdc5c5301c56b75f7,
-    0x89b9b3e11b6329bb,
-    0xac2820d9623bf429,
-    0xd732290fbacaf134,
-    0x867f59a9d4bed6c0,
-    0xa81f301449ee8c70,
-    0xd226fc195c6a2f8c,
-    0x83585d8fd9c25db8,
-    0xa42e74f3d032f526,
-    0xcd3a1230c43fb26f,
-    0x80444b5e7aa7cf85,
-    0xa0555e361951c367,
-    0xc86ab5c39fa63441,
-    0xfa856334878fc151,
-    0x9c935e00d4b9d8d2,
-    0xc3b8358109e84f07,
-    0xf4a642e14c6262c9,
-    0x98e7e9cccfbd7dbe,
-    0xbf21e44003acdd2d,
-    0xeeea5d5004981478,
-    0x95527a5202df0ccb,
-    0xbaa718e68396cffe,
-    0xe950df20247c83fd,
-    0x91d28b7416cdd27e,
-], [
-    -1077,
-    -1073,
-    -1070,
-    -1067,
-    -1063,
-    -1060,
-    -1057,
-    -1053,
-    -1050,
-    -1047,
-    -1043,
-    -1040,
-    -1037,
-    -1034,
-    -1030,
-    -1027,
-    -1024,
-    -1020,
-    -1017,
-    -1014,
-    -1010,
-    -1007,
-    -1004,
-    -1000,
-    -997,
-    -994,
-    -990,
-    -987,
-    -984,
-    -980,
-    -977,
-    -974,
-    -970,
-    -967,
-    -964,
-    -960,
-    -957,
-    -954,
-    -950,
-    -947,
-    -944,
-    -940,
-    -937,
-    -934,
-    -931,
-    -927,
-    -924,
-    -921,
-    -917,
-    -914,
-    -911,
-    -907,
-    -904,
-    -901,
-    -897,
-    -894,
-    -891,
-    -887,
-    -884,
-    -881,
-    -877,
-    -874,
-    -871,
-    -867,
-    -864,
-    -861,
-    -857,
-    -854,
-    -851,
-    -847,
-    -844,
-    -841,
-    -838,
-    -834,
-    -831,
-    -828,
-    -824,
-    -821,
-    -818,
-    -814,
-    -811,
-    -808,
-    -804,
-    -801,
-    -798,
-    -794,
-    -791,
-    -788,
-    -784,
-    -781,
-    -778,
-    -774,
-    -771,
-    -768,
-    -764,
-    -761,
-    -758,
-    -754,
-    -751,
-    -748,
-    -744,
-    -741,
-    -738,
-    -735,
-    -731,
-    -728,
-    -725,
-    -721,
-    -718,
-    -715,
-    -711,
-    -708,
-    -705,
-    -701,
-    -698,
-    -695,
-    -691,
-    -688,
-    -685,
-    -681,
-    -678,
-    -675,
-    -671,
-    -668,
-    -665,
-    -661,
-    -658,
-    -655,
-    -651,
-    -648,
-    -645,
-    -642,
-    -638,
-    -635,
-    -632,
-    -628,
-    -625,
-    -622,
-    -618,
-    -615,
-    -612,
-    -608,
-    -605,
-    -602,
-    -598,
-    -595,
-    -592,
-    -588,
-    -585,
-    -582,
-    -578,
-    -575,
-    -572,
-    -568,
-    -565,
-    -562,
-    -558,
-    -555,
-    -552,
-    -549,
-    -545,
-    -542,
-    -539,
-    -535,
-    -532,
-    -529,
-    -525,
-    -522,
-    -519,
-    -515,
-    -512,
-    -509,
-    -505,
-    -502,
-    -499,
-    -495,
-    -492,
-    -489,
-    -485,
-    -482,
-    -479,
-    -475,
-    -472,
-    -469,
-    -465,
-    -462,
-    -459,
-    -455,
-    -452,
-    -449,
-    -446,
-    -442,
-    -439,
-    -436,
-    -432,
-    -429,
-    -426,
-    -422,
-    -419,
-    -416,
-    -412,
-    -409,
-    -406,
-    -402,
-    -399,
-    -396,
-    -392,
-    -389,
-    -386,
-    -382,
-    -379,
-    -376,
-    -372,
-    -369,
-    -366,
-    -362,
-    -359,
-    -356,
-    -353,
-    -349,
-    -346,
-    -343,
-    -339,
-    -336,
-    -333,
-    -329,
-    -326,
-    -323,
-    -319,
-    -316,
-    -313,
-    -309,
-    -306,
-    -303,
-    -299,
-    -296,
-    -293,
-    -289,
-    -286,
-    -283,
-    -279,
-    -276,
-    -273,
-    -269,
-    -266,
-    -263,
-    -259,
-    -256,
-    -253,
-    -250,
-    -246,
-    -243,
-    -240,
-    -236,
-    -233,
-    -230,
-    -226,
-    -223,
-    -220,
-    -216,
-    -213,
-    -210,
-    -206,
-    -203,
-    -200,
-    -196,
-    -193,
-    -190,
-    -186,
-    -183,
-    -180,
-    -176,
-    -173,
-    -170,
-    -166,
-    -163,
-    -160,
-    -157,
-    -153,
-    -150,
-    -147,
-    -143,
-    -140,
-    -137,
-    -133,
-    -130,
-    -127,
-    -123,
-    -120,
-    -117,
-    -113,
-    -110,
-    -107,
-    -103,
-    -100,
-    -97,
-    -93,
-    -90,
-    -87,
-    -83,
-    -80,
-    -77,
-    -73,
-    -70,
-    -67,
-    -63,
-    -60,
-    -57,
-    -54,
-    -50,
-    -47,
-    -44,
-    -40,
-    -37,
-    -34,
-    -30,
-    -27,
-    -24,
-    -20,
-    -17,
-    -14,
-    -10,
-    -7,
-    -4,
-    0,
-    3,
-    6,
-    10,
-    13,
-    16,
-    20,
-    23,
-    26,
-    30,
-    33,
-    36,
-    39,
-    43,
-    46,
-    49,
-    53,
-    56,
-    59,
-    63,
-    66,
-    69,
-    73,
-    76,
-    79,
-    83,
-    86,
-    89,
-    93,
-    96,
-    99,
-    103,
-    106,
-    109,
-    113,
-    116,
-    119,
-    123,
-    126,
-    129,
-    132,
-    136,
-    139,
-    142,
-    146,
-    149,
-    152,
-    156,
-    159,
-    162,
-    166,
-    169,
-    172,
-    176,
-    179,
-    182,
-    186,
-    189,
-    192,
-    196,
-    199,
-    202,
-    206,
-    209,
-    212,
-    216,
-    219,
-    222,
-    226,
-    229,
-    232,
-    235,
-    239,
-    242,
-    245,
-    249,
-    252,
-    255,
-    259,
-    262,
-    265,
-    269,
-    272,
-    275,
-    279,
-    282,
-    285,
-    289,
-    292,
-    295,
-    299,
-    302,
-    305,
-    309,
-    312,
-    315,
-    319,
-    322,
-    325,
-    328,
-    332,
-    335,
-    338,
-    342,
-    345,
-    348,
-    352,
-    355,
-    358,
-    362,
-    365,
-    368,
-    372,
-    375,
-    378,
-    382,
-    385,
-    388,
-    392,
-    395,
-    398,
-    402,
-    405,
-    408,
-    412,
-    415,
-    418,
-    422,
-    425,
-    428,
-    431,
-    435,
-    438,
-    441,
-    445,
-    448,
-    451,
-    455,
-    458,
-    461,
-    465,
-    468,
-    471,
-    475,
-    478,
-    481,
-    485,
-    488,
-    491,
-    495,
-    498,
-    501,
-    505,
-    508,
-    511,
-    515,
-    518,
-    521,
-    524,
-    528,
-    531,
-    534,
-    538,
-    541,
-    544,
-    548,
-    551,
-    554,
-    558,
-    561,
-    564,
-    568,
-    571,
-    574,
-    578,
-    581,
-    584,
-    588,
-    591,
-    594,
-    598,
-    601,
-    604,
-    608,
-    611,
-    614,
-    617,
-    621,
-    624,
-    627,
-    631,
-    634,
-    637,
-    641,
-    644,
-    647,
-    651,
-    654,
-    657,
-    661,
-    664,
-    667,
-    671,
-    674,
-    677,
-    681,
-    684,
-    687,
-    691,
-    694,
-    697,
-    701,
-    704,
-    707,
-    711,
-    714,
-    717,
-    720,
-    724,
-    727,
-    730,
-    734,
-    737,
-    740,
-    744,
-    747,
-    750,
-    754,
-    757,
-    760,
-    764,
-    767,
-    770,
-    774,
-    777,
-    780,
-    784,
-    787,
-    790,
-    794,
-    797,
-    800,
-    804,
-    807,
-    810,
-    813,
-    817,
-    820,
-    823,
-    827,
-    830,
-    833,
-    837,
-    840,
-    843,
-    847,
-    850,
-    853,
-    857,
-    860,
-    863,
-    867,
-    870,
-    873,
-    877,
-    880,
-    883,
-    887,
-    890,
-    893,
-    897,
-    900,
-    903,
-    907,
-    910,
-    913,
-    916,
-    920,
-    923,
-    926,
-    930,
-    933,
-    936,
-    940,
-    943,
-    946,
-    950,
-]);
+#[rustfmt::skip]
+pub const POWERS: ([u64; 611], [i16; 611]) = (
+    [
+        0xe0b62e2929aba83c,
+        0x8c71dcd9ba0b4926,
+        0xaf8e5410288e1b6f,
+        0xdb71e91432b1a24b,
+        0x892731ac9faf056f,
+        0xab70fe17c79ac6ca,
+        0xd64d3d9db981787d,
+        0x85f0468293f0eb4e,
+        0xa76c582338ed2622,
+        0xd1476e2c07286faa,
+        0x82cca4db847945ca,
+        0xa37fce126597973d,
+        0xcc5fc196fefd7d0c,
+        0xff77b1fcbebcdc4f,
+        0x9faacf3df73609b1,
+        0xc795830d75038c1e,
+        0xf97ae3d0d2446f25,
+        0x9becce62836ac577,
+        0xc2e801fb244576d5,
+        0xf3a20279ed56d48a,
+        0x9845418c345644d7,
+        0xbe5691ef416bd60c,
+        0xedec366b11c6cb8f,
+        0x94b3a202eb1c3f39,
+        0xb9e08a83a5e34f08,
+        0xe858ad248f5c22ca,
+        0x91376c36d99995be,
+        0xb58547448ffffb2e,
+        0xe2e69915b3fff9f9,
+        0x8dd01fad907ffc3c,
+        0xb1442798f49ffb4b,
+        0xdd95317f31c7fa1d,
+        0x8a7d3eef7f1cfc52,
+        0xad1c8eab5ee43b67,
+        0xd863b256369d4a41,
+        0x873e4f75e2224e68,
+        0xa90de3535aaae202,
+        0xd3515c2831559a83,
+        0x8412d9991ed58092,
+        0xa5178fff668ae0b6,
+        0xce5d73ff402d98e4,
+        0x80fa687f881c7f8e,
+        0xa139029f6a239f72,
+        0xc987434744ac874f,
+        0xfbe9141915d7a922,
+        0x9d71ac8fada6c9b5,
+        0xc4ce17b399107c23,
+        0xf6019da07f549b2b,
+        0x99c102844f94e0fb,
+        0xc0314325637a193a,
+        0xf03d93eebc589f88,
+        0x96267c7535b763b5,
+        0xbbb01b9283253ca3,
+        0xea9c227723ee8bcb,
+        0x92a1958a7675175f,
+        0xb749faed14125d37,
+        0xe51c79a85916f485,
+        0x8f31cc0937ae58d3,
+        0xb2fe3f0b8599ef08,
+        0xdfbdcece67006ac9,
+        0x8bd6a141006042be,
+        0xaecc49914078536d,
+        0xda7f5bf590966849,
+        0x888f99797a5e012d,
+        0xaab37fd7d8f58179,
+        0xd5605fcdcf32e1d7,
+        0x855c3be0a17fcd26,
+        0xa6b34ad8c9dfc070,
+        0xd0601d8efc57b08c,
+        0x823c12795db6ce57,
+        0xa2cb1717b52481ed,
+        0xcb7ddcdda26da269,
+        0xfe5d54150b090b03,
+        0x9efa548d26e5a6e2,
+        0xc6b8e9b0709f109a,
+        0xf867241c8cc6d4c1,
+        0x9b407691d7fc44f8,
+        0xc21094364dfb5637,
+        0xf294b943e17a2bc4,
+        0x979cf3ca6cec5b5b,
+        0xbd8430bd08277231,
+        0xece53cec4a314ebe,
+        0x940f4613ae5ed137,
+        0xb913179899f68584,
+        0xe757dd7ec07426e5,
+        0x9096ea6f3848984f,
+        0xb4bca50b065abe63,
+        0xe1ebce4dc7f16dfc,
+        0x8d3360f09cf6e4bd,
+        0xb080392cc4349ded,
+        0xdca04777f541c568,
+        0x89e42caaf9491b61,
+        0xac5d37d5b79b6239,
+        0xd77485cb25823ac7,
+        0x86a8d39ef77164bd,
+        0xa8530886b54dbdec,
+        0xd267caa862a12d67,
+        0x8380dea93da4bc60,
+        0xa46116538d0deb78,
+        0xcd795be870516656,
+        0x806bd9714632dff6,
+        0xa086cfcd97bf97f4,
+        0xc8a883c0fdaf7df0,
+        0xfad2a4b13d1b5d6c,
+        0x9cc3a6eec6311a64,
+        0xc3f490aa77bd60fd,
+        0xf4f1b4d515acb93c,
+        0x991711052d8bf3c5,
+        0xbf5cd54678eef0b7,
+        0xef340a98172aace5,
+        0x9580869f0e7aac0f,
+        0xbae0a846d2195713,
+        0xe998d258869facd7,
+        0x91ff83775423cc06,
+        0xb67f6455292cbf08,
+        0xe41f3d6a7377eeca,
+        0x8e938662882af53e,
+        0xb23867fb2a35b28e,
+        0xdec681f9f4c31f31,
+        0x8b3c113c38f9f37f,
+        0xae0b158b4738705f,
+        0xd98ddaee19068c76,
+        0x87f8a8d4cfa417ca,
+        0xa9f6d30a038d1dbc,
+        0xd47487cc8470652b,
+        0x84c8d4dfd2c63f3b,
+        0xa5fb0a17c777cf0a,
+        0xcf79cc9db955c2cc,
+        0x81ac1fe293d599c0,
+        0xa21727db38cb0030,
+        0xca9cf1d206fdc03c,
+        0xfd442e4688bd304b,
+        0x9e4a9cec15763e2f,
+        0xc5dd44271ad3cdba,
+        0xf7549530e188c129,
+        0x9a94dd3e8cf578ba,
+        0xc13a148e3032d6e8,
+        0xf18899b1bc3f8ca2,
+        0x96f5600f15a7b7e5,
+        0xbcb2b812db11a5de,
+        0xebdf661791d60f56,
+        0x936b9fcebb25c996,
+        0xb84687c269ef3bfb,
+        0xe65829b3046b0afa,
+        0x8ff71a0fe2c2e6dc,
+        0xb3f4e093db73a093,
+        0xe0f218b8d25088b8,
+        0x8c974f7383725573,
+        0xafbd2350644eead0,
+        0xdbac6c247d62a584,
+        0x894bc396ce5da772,
+        0xab9eb47c81f5114f,
+        0xd686619ba27255a3,
+        0x8613fd0145877586,
+        0xa798fc4196e952e7,
+        0xd17f3b51fca3a7a1,
+        0x82ef85133de648c5,
+        0xa3ab66580d5fdaf6,
+        0xcc963fee10b7d1b3,
+        0xffbbcfe994e5c620,
+        0x9fd561f1fd0f9bd4,
+        0xc7caba6e7c5382c9,
+        0xf9bd690a1b68637b,
+        0x9c1661a651213e2d,
+        0xc31bfa0fe5698db8,
+        0xf3e2f893dec3f126,
+        0x986ddb5c6b3a76b8,
+        0xbe89523386091466,
+        0xee2ba6c0678b597f,
+        0x94db483840b717f0,
+        0xba121a4650e4ddec,
+        0xe896a0d7e51e1566,
+        0x915e2486ef32cd60,
+        0xb5b5ada8aaff80b8,
+        0xe3231912d5bf60e6,
+        0x8df5efabc5979c90,
+        0xb1736b96b6fd83b4,
+        0xddd0467c64bce4a1,
+        0x8aa22c0dbef60ee4,
+        0xad4ab7112eb3929e,
+        0xd89d64d57a607745,
+        0x87625f056c7c4a8b,
+        0xa93af6c6c79b5d2e,
+        0xd389b47879823479,
+        0x843610cb4bf160cc,
+        0xa54394fe1eedb8ff,
+        0xce947a3da6a9273e,
+        0x811ccc668829b887,
+        0xa163ff802a3426a9,
+        0xc9bcff6034c13053,
+        0xfc2c3f3841f17c68,
+        0x9d9ba7832936edc1,
+        0xc5029163f384a931,
+        0xf64335bcf065d37d,
+        0x99ea0196163fa42e,
+        0xc06481fb9bcf8d3a,
+        0xf07da27a82c37088,
+        0x964e858c91ba2655,
+        0xbbe226efb628afeb,
+        0xeadab0aba3b2dbe5,
+        0x92c8ae6b464fc96f,
+        0xb77ada0617e3bbcb,
+        0xe55990879ddcaabe,
+        0x8f57fa54c2a9eab7,
+        0xb32df8e9f3546564,
+        0xdff9772470297ebd,
+        0x8bfbea76c619ef36,
+        0xaefae51477a06b04,
+        0xdab99e59958885c5,
+        0x88b402f7fd75539b,
+        0xaae103b5fcd2a882,
+        0xd59944a37c0752a2,
+        0x857fcae62d8493a5,
+        0xa6dfbd9fb8e5b88f,
+        0xd097ad07a71f26b2,
+        0x825ecc24c8737830,
+        0xa2f67f2dfa90563b,
+        0xcbb41ef979346bca,
+        0xfea126b7d78186bd,
+        0x9f24b832e6b0f436,
+        0xc6ede63fa05d3144,
+        0xf8a95fcf88747d94,
+        0x9b69dbe1b548ce7d,
+        0xc24452da229b021c,
+        0xf2d56790ab41c2a3,
+        0x97c560ba6b0919a6,
+        0xbdb6b8e905cb600f,
+        0xed246723473e3813,
+        0x9436c0760c86e30c,
+        0xb94470938fa89bcf,
+        0xe7958cb87392c2c3,
+        0x90bd77f3483bb9ba,
+        0xb4ecd5f01a4aa828,
+        0xe2280b6c20dd5232,
+        0x8d590723948a535f,
+        0xb0af48ec79ace837,
+        0xdcdb1b2798182245,
+        0x8a08f0f8bf0f156b,
+        0xac8b2d36eed2dac6,
+        0xd7adf884aa879177,
+        0x86ccbb52ea94baeb,
+        0xa87fea27a539e9a5,
+        0xd29fe4b18e88640f,
+        0x83a3eeeef9153e89,
+        0xa48ceaaab75a8e2b,
+        0xcdb02555653131b6,
+        0x808e17555f3ebf12,
+        0xa0b19d2ab70e6ed6,
+        0xc8de047564d20a8c,
+        0xfb158592be068d2f,
+        0x9ced737bb6c4183d,
+        0xc428d05aa4751e4d,
+        0xf53304714d9265e0,
+        0x993fe2c6d07b7fac,
+        0xbf8fdb78849a5f97,
+        0xef73d256a5c0f77d,
+        0x95a8637627989aae,
+        0xbb127c53b17ec159,
+        0xe9d71b689dde71b0,
+        0x9226712162ab070e,
+        0xb6b00d69bb55c8d1,
+        0xe45c10c42a2b3b06,
+        0x8eb98a7a9a5b04e3,
+        0xb267ed1940f1c61c,
+        0xdf01e85f912e37a3,
+        0x8b61313bbabce2c6,
+        0xae397d8aa96c1b78,
+        0xd9c7dced53c72256,
+        0x881cea14545c7575,
+        0xaa242499697392d3,
+        0xd4ad2dbfc3d07788,
+        0x84ec3c97da624ab5,
+        0xa6274bbdd0fadd62,
+        0xcfb11ead453994ba,
+        0x81ceb32c4b43fcf5,
+        0xa2425ff75e14fc32,
+        0xcad2f7f5359a3b3e,
+        0xfd87b5f28300ca0e,
+        0x9e74d1b791e07e48,
+        0xc612062576589ddb,
+        0xf79687aed3eec551,
+        0x9abe14cd44753b53,
+        0xc16d9a0095928a27,
+        0xf1c90080baf72cb1,
+        0x971da05074da7bef,
+        0xbce5086492111aeb,
+        0xec1e4a7db69561a5,
+        0x9392ee8e921d5d07,
+        0xb877aa3236a4b449,
+        0xe69594bec44de15b,
+        0x901d7cf73ab0acd9,
+        0xb424dc35095cd80f,
+        0xe12e13424bb40e13,
+        0x8cbccc096f5088cc,
+        0xafebff0bcb24aaff,
+        0xdbe6fecebdedd5bf,
+        0x89705f4136b4a597,
+        0xabcc77118461cefd,
+        0xd6bf94d5e57a42bc,
+        0x8637bd05af6c69b6,
+        0xa7c5ac471b478423,
+        0xd1b71758e219652c,
+        0x83126e978d4fdf3b,
+        0xa3d70a3d70a3d70a,
+        0xcccccccccccccccd,
+        0x8000000000000000,
+        0xa000000000000000,
+        0xc800000000000000,
+        0xfa00000000000000,
+        0x9c40000000000000,
+        0xc350000000000000,
+        0xf424000000000000,
+        0x9896800000000000,
+        0xbebc200000000000,
+        0xee6b280000000000,
+        0x9502f90000000000,
+        0xba43b74000000000,
+        0xe8d4a51000000000,
+        0x9184e72a00000000,
+        0xb5e620f480000000,
+        0xe35fa931a0000000,
+        0x8e1bc9bf04000000,
+        0xb1a2bc2ec5000000,
+        0xde0b6b3a76400000,
+        0x8ac7230489e80000,
+        0xad78ebc5ac620000,
+        0xd8d726b7177a8000,
+        0x878678326eac9000,
+        0xa968163f0a57b400,
+        0xd3c21bcecceda100,
+        0x84595161401484a0,
+        0xa56fa5b99019a5c8,
+        0xcecb8f27f4200f3a,
+        0x813f3978f8940984,
+        0xa18f07d736b90be5,
+        0xc9f2c9cd04674edf,
+        0xfc6f7c4045812296,
+        0x9dc5ada82b70b59e,
+        0xc5371912364ce305,
+        0xf684df56c3e01bc7,
+        0x9a130b963a6c115c,
+        0xc097ce7bc90715b3,
+        0xf0bdc21abb48db20,
+        0x96769950b50d88f4,
+        0xbc143fa4e250eb31,
+        0xeb194f8e1ae525fd,
+        0x92efd1b8d0cf37be,
+        0xb7abc627050305ae,
+        0xe596b7b0c643c719,
+        0x8f7e32ce7bea5c70,
+        0xb35dbf821ae4f38c,
+        0xe0352f62a19e306f,
+        0x8c213d9da502de45,
+        0xaf298d050e4395d7,
+        0xdaf3f04651d47b4c,
+        0x88d8762bf324cd10,
+        0xab0e93b6efee0054,
+        0xd5d238a4abe98068,
+        0x85a36366eb71f041,
+        0xa70c3c40a64e6c52,
+        0xd0cf4b50cfe20766,
+        0x82818f1281ed44a0,
+        0xa321f2d7226895c8,
+        0xcbea6f8ceb02bb3a,
+        0xfee50b7025c36a08,
+        0x9f4f2726179a2245,
+        0xc722f0ef9d80aad6,
+        0xf8ebad2b84e0d58c,
+        0x9b934c3b330c8577,
+        0xc2781f49ffcfa6d5,
+        0xf316271c7fc3908b,
+        0x97edd871cfda3a57,
+        0xbde94e8e43d0c8ec,
+        0xed63a231d4c4fb27,
+        0x945e455f24fb1cf9,
+        0xb975d6b6ee39e437,
+        0xe7d34c64a9c85d44,
+        0x90e40fbeea1d3a4b,
+        0xb51d13aea4a488dd,
+        0xe264589a4dcdab15,
+        0x8d7eb76070a08aed,
+        0xb0de65388cc8ada8,
+        0xdd15fe86affad912,
+        0x8a2dbf142dfcc7ab,
+        0xacb92ed9397bf996,
+        0xd7e77a8f87daf7fc,
+        0x86f0ac99b4e8dafd,
+        0xa8acd7c0222311bd,
+        0xd2d80db02aabd62c,
+        0x83c7088e1aab65db,
+        0xa4b8cab1a1563f52,
+        0xcde6fd5e09abcf27,
+        0x80b05e5ac60b6178,
+        0xa0dc75f1778e39d6,
+        0xc913936dd571c84c,
+        0xfb5878494ace3a5f,
+        0x9d174b2dcec0e47b,
+        0xc45d1df942711d9a,
+        0xf5746577930d6501,
+        0x9968bf6abbe85f20,
+        0xbfc2ef456ae276e9,
+        0xefb3ab16c59b14a3,
+        0x95d04aee3b80ece6,
+        0xbb445da9ca61281f,
+        0xea1575143cf97227,
+        0x924d692ca61be758,
+        0xb6e0c377cfa2e12e,
+        0xe498f455c38b997a,
+        0x8edf98b59a373fec,
+        0xb2977ee300c50fe7,
+        0xdf3d5e9bc0f653e1,
+        0x8b865b215899f46d,
+        0xae67f1e9aec07188,
+        0xda01ee641a708dea,
+        0x884134fe908658b2,
+        0xaa51823e34a7eedf,
+        0xd4e5e2cdc1d1ea96,
+        0x850fadc09923329e,
+        0xa6539930bf6bff46,
+        0xcfe87f7cef46ff17,
+        0x81f14fae158c5f6e,
+        0xa26da3999aef774a,
+        0xcb090c8001ab551c,
+        0xfdcb4fa002162a63,
+        0x9e9f11c4014dda7e,
+        0xc646d63501a1511e,
+        0xf7d88bc24209a565,
+        0x9ae757596946075f,
+        0xc1a12d2fc3978937,
+        0xf209787bb47d6b85,
+        0x9745eb4d50ce6333,
+        0xbd176620a501fc00,
+        0xec5d3fa8ce427b00,
+        0x93ba47c980e98ce0,
+        0xb8a8d9bbe123f018,
+        0xe6d3102ad96cec1e,
+        0x9043ea1ac7e41393,
+        0xb454e4a179dd1877,
+        0xe16a1dc9d8545e95,
+        0x8ce2529e2734bb1d,
+        0xb01ae745b101e9e4,
+        0xdc21a1171d42645d,
+        0x899504ae72497eba,
+        0xabfa45da0edbde69,
+        0xd6f8d7509292d603,
+        0x865b86925b9bc5c2,
+        0xa7f26836f282b733,
+        0xd1ef0244af2364ff,
+        0x8335616aed761f1f,
+        0xa402b9c5a8d3a6e7,
+        0xcd036837130890a1,
+        0x802221226be55a65,
+        0xa02aa96b06deb0fe,
+        0xc83553c5c8965d3d,
+        0xfa42a8b73abbf48d,
+        0x9c69a97284b578d8,
+        0xc38413cf25e2d70e,
+        0xf46518c2ef5b8cd1,
+        0x98bf2f79d5993803,
+        0xbeeefb584aff8604,
+        0xeeaaba2e5dbf6785,
+        0x952ab45cfa97a0b3,
+        0xba756174393d88e0,
+        0xe912b9d1478ceb17,
+        0x91abb422ccb812ef,
+        0xb616a12b7fe617aa,
+        0xe39c49765fdf9d95,
+        0x8e41ade9fbebc27d,
+        0xb1d219647ae6b31c,
+        0xde469fbd99a05fe3,
+        0x8aec23d680043bee,
+        0xada72ccc20054aea,
+        0xd910f7ff28069da4,
+        0x87aa9aff79042287,
+        0xa99541bf57452b28,
+        0xd3fa922f2d1675f2,
+        0x847c9b5d7c2e09b7,
+        0xa59bc234db398c25,
+        0xcf02b2c21207ef2f,
+        0x8161afb94b44f57d,
+        0xa1ba1ba79e1632dc,
+        0xca28a291859bbf93,
+        0xfcb2cb35e702af78,
+        0x9defbf01b061adab,
+        0xc56baec21c7a1916,
+        0xf6c69a72a3989f5c,
+        0x9a3c2087a63f6399,
+        0xc0cb28a98fcf3c80,
+        0xf0fdf2d3f3c30b9f,
+        0x969eb7c47859e744,
+        0xbc4665b596706115,
+        0xeb57ff22fc0c795a,
+        0x9316ff75dd87cbd8,
+        0xb7dcbf5354e9bece,
+        0xe5d3ef282a242e82,
+        0x8fa475791a569d11,
+        0xb38d92d760ec4455,
+        0xe070f78d3927556b,
+        0x8c469ab843b89563,
+        0xaf58416654a6babb,
+        0xdb2e51bfe9d0696a,
+        0x88fcf317f22241e2,
+        0xab3c2fddeeaad25b,
+        0xd60b3bd56a5586f2,
+        0x85c7056562757457,
+        0xa738c6bebb12d16d,
+        0xd106f86e69d785c8,
+        0x82a45b450226b39d,
+        0xa34d721642b06084,
+        0xcc20ce9bd35c78a5,
+        0xff290242c83396ce,
+        0x9f79a169bd203e41,
+        0xc75809c42c684dd1,
+        0xf92e0c3537826146,
+        0x9bbcc7a142b17ccc,
+        0xc2abf989935ddbfe,
+        0xf356f7ebf83552fe,
+        0x98165af37b2153df,
+        0xbe1bf1b059e9a8d6,
+        0xeda2ee1c7064130c,
+        0x9485d4d1c63e8be8,
+        0xb9a74a0637ce2ee1,
+        0xe8111c87c5c1ba9a,
+        0x910ab1d4db9914a0,
+        0xb54d5e4a127f59c8,
+        0xe2a0b5dc971f303a,
+        0x8da471a9de737e24,
+        0xb10d8e1456105dad,
+        0xdd50f1996b947519,
+        0x8a5296ffe33cc930,
+        0xace73cbfdc0bfb7b,
+        0xd8210befd30efa5a,
+        0x8714a775e3e95c78,
+        0xa8d9d1535ce3b396,
+        0xd31045a8341ca07c,
+        0x83ea2b892091e44e,
+        0xa4e4b66b68b65d61,
+        0xce1de40642e3f4b9,
+        0x80d2ae83e9ce78f4,
+        0xa1075a24e4421731,
+        0xc94930ae1d529cfd,
+        0xfb9b7cd9a4a7443c,
+        0x9d412e0806e88aa6,
+        0xc491798a08a2ad4f,
+        0xf5b5d7ec8acb58a3,
+        0x9991a6f3d6bf1766,
+        0xbff610b0cc6edd3f,
+        0xeff394dcff8a948f,
+        0x95f83d0a1fb69cd9,
+        0xbb764c4ca7a44410,
+        0xea53df5fd18d5514,
+        0x92746b9be2f8552c,
+        0xb7118682dbb66a77,
+        0xe4d5e82392a40515,
+        0x8f05b1163ba6832d,
+        0xb2c71d5bca9023f8,
+        0xdf78e4b2bd342cf7,
+        0x8bab8eefb6409c1a,
+        0xae9672aba3d0c321,
+        0xda3c0f568cc4f3e9,
+        0x8865899617fb1871,
+        0xaa7eebfb9df9de8e,
+        0xd51ea6fa85785631,
+        0x8533285c936b35df,
+        0xa67ff273b8460357,
+        0xd01fef10a657842c,
+        0x8213f56a67f6b29c,
+        0xa298f2c501f45f43,
+        0xcb3f2f7642717713,
+        0xfe0efb53d30dd4d8,
+        0x9ec95d1463e8a507,
+        0xc67bb4597ce2ce49,
+        0xf81aa16fdc1b81db,
+        0x9b10a4e5e9913129,
+        0xc1d4ce1f63f57d73,
+        0xf24a01a73cf2dcd0,
+        0x976e41088617ca02,
+        0xbd49d14aa79dbc82,
+        0xec9c459d51852ba3,
+        0x93e1ab8252f33b46,
+        0xb8da1662e7b00a17,
+        0xe7109bfba19c0c9d,
+        0x906a617d450187e2,
+        0xb484f9dc9641e9db,
+        0xe1a63853bbd26451,
+        0x8d07e33455637eb3,
+        0xb049dc016abc5e60,
+        0xdc5c5301c56b75f7,
+        0x89b9b3e11b6329bb,
+        0xac2820d9623bf429,
+        0xd732290fbacaf134,
+        0x867f59a9d4bed6c0,
+        0xa81f301449ee8c70,
+        0xd226fc195c6a2f8c,
+        0x83585d8fd9c25db8,
+        0xa42e74f3d032f526,
+        0xcd3a1230c43fb26f,
+        0x80444b5e7aa7cf85,
+        0xa0555e361951c367,
+        0xc86ab5c39fa63441,
+        0xfa856334878fc151,
+        0x9c935e00d4b9d8d2,
+        0xc3b8358109e84f07,
+        0xf4a642e14c6262c9,
+        0x98e7e9cccfbd7dbe,
+        0xbf21e44003acdd2d,
+        0xeeea5d5004981478,
+        0x95527a5202df0ccb,
+        0xbaa718e68396cffe,
+        0xe950df20247c83fd,
+        0x91d28b7416cdd27e,
+    ],
+    [
+        -1077,
+        -1073,
+        -1070,
+        -1067,
+        -1063,
+        -1060,
+        -1057,
+        -1053,
+        -1050,
+        -1047,
+        -1043,
+        -1040,
+        -1037,
+        -1034,
+        -1030,
+        -1027,
+        -1024,
+        -1020,
+        -1017,
+        -1014,
+        -1010,
+        -1007,
+        -1004,
+        -1000,
+        -997,
+        -994,
+        -990,
+        -987,
+        -984,
+        -980,
+        -977,
+        -974,
+        -970,
+        -967,
+        -964,
+        -960,
+        -957,
+        -954,
+        -950,
+        -947,
+        -944,
+        -940,
+        -937,
+        -934,
+        -931,
+        -927,
+        -924,
+        -921,
+        -917,
+        -914,
+        -911,
+        -907,
+        -904,
+        -901,
+        -897,
+        -894,
+        -891,
+        -887,
+        -884,
+        -881,
+        -877,
+        -874,
+        -871,
+        -867,
+        -864,
+        -861,
+        -857,
+        -854,
+        -851,
+        -847,
+        -844,
+        -841,
+        -838,
+        -834,
+        -831,
+        -828,
+        -824,
+        -821,
+        -818,
+        -814,
+        -811,
+        -808,
+        -804,
+        -801,
+        -798,
+        -794,
+        -791,
+        -788,
+        -784,
+        -781,
+        -778,
+        -774,
+        -771,
+        -768,
+        -764,
+        -761,
+        -758,
+        -754,
+        -751,
+        -748,
+        -744,
+        -741,
+        -738,
+        -735,
+        -731,
+        -728,
+        -725,
+        -721,
+        -718,
+        -715,
+        -711,
+        -708,
+        -705,
+        -701,
+        -698,
+        -695,
+        -691,
+        -688,
+        -685,
+        -681,
+        -678,
+        -675,
+        -671,
+        -668,
+        -665,
+        -661,
+        -658,
+        -655,
+        -651,
+        -648,
+        -645,
+        -642,
+        -638,
+        -635,
+        -632,
+        -628,
+        -625,
+        -622,
+        -618,
+        -615,
+        -612,
+        -608,
+        -605,
+        -602,
+        -598,
+        -595,
+        -592,
+        -588,
+        -585,
+        -582,
+        -578,
+        -575,
+        -572,
+        -568,
+        -565,
+        -562,
+        -558,
+        -555,
+        -552,
+        -549,
+        -545,
+        -542,
+        -539,
+        -535,
+        -532,
+        -529,
+        -525,
+        -522,
+        -519,
+        -515,
+        -512,
+        -509,
+        -505,
+        -502,
+        -499,
+        -495,
+        -492,
+        -489,
+        -485,
+        -482,
+        -479,
+        -475,
+        -472,
+        -469,
+        -465,
+        -462,
+        -459,
+        -455,
+        -452,
+        -449,
+        -446,
+        -442,
+        -439,
+        -436,
+        -432,
+        -429,
+        -426,
+        -422,
+        -419,
+        -416,
+        -412,
+        -409,
+        -406,
+        -402,
+        -399,
+        -396,
+        -392,
+        -389,
+        -386,
+        -382,
+        -379,
+        -376,
+        -372,
+        -369,
+        -366,
+        -362,
+        -359,
+        -356,
+        -353,
+        -349,
+        -346,
+        -343,
+        -339,
+        -336,
+        -333,
+        -329,
+        -326,
+        -323,
+        -319,
+        -316,
+        -313,
+        -309,
+        -306,
+        -303,
+        -299,
+        -296,
+        -293,
+        -289,
+        -286,
+        -283,
+        -279,
+        -276,
+        -273,
+        -269,
+        -266,
+        -263,
+        -259,
+        -256,
+        -253,
+        -250,
+        -246,
+        -243,
+        -240,
+        -236,
+        -233,
+        -230,
+        -226,
+        -223,
+        -220,
+        -216,
+        -213,
+        -210,
+        -206,
+        -203,
+        -200,
+        -196,
+        -193,
+        -190,
+        -186,
+        -183,
+        -180,
+        -176,
+        -173,
+        -170,
+        -166,
+        -163,
+        -160,
+        -157,
+        -153,
+        -150,
+        -147,
+        -143,
+        -140,
+        -137,
+        -133,
+        -130,
+        -127,
+        -123,
+        -120,
+        -117,
+        -113,
+        -110,
+        -107,
+        -103,
+        -100,
+        -97,
+        -93,
+        -90,
+        -87,
+        -83,
+        -80,
+        -77,
+        -73,
+        -70,
+        -67,
+        -63,
+        -60,
+        -57,
+        -54,
+        -50,
+        -47,
+        -44,
+        -40,
+        -37,
+        -34,
+        -30,
+        -27,
+        -24,
+        -20,
+        -17,
+        -14,
+        -10,
+        -7,
+        -4,
+        0,
+        3,
+        6,
+        10,
+        13,
+        16,
+        20,
+        23,
+        26,
+        30,
+        33,
+        36,
+        39,
+        43,
+        46,
+        49,
+        53,
+        56,
+        59,
+        63,
+        66,
+        69,
+        73,
+        76,
+        79,
+        83,
+        86,
+        89,
+        93,
+        96,
+        99,
+        103,
+        106,
+        109,
+        113,
+        116,
+        119,
+        123,
+        126,
+        129,
+        132,
+        136,
+        139,
+        142,
+        146,
+        149,
+        152,
+        156,
+        159,
+        162,
+        166,
+        169,
+        172,
+        176,
+        179,
+        182,
+        186,
+        189,
+        192,
+        196,
+        199,
+        202,
+        206,
+        209,
+        212,
+        216,
+        219,
+        222,
+        226,
+        229,
+        232,
+        235,
+        239,
+        242,
+        245,
+        249,
+        252,
+        255,
+        259,
+        262,
+        265,
+        269,
+        272,
+        275,
+        279,
+        282,
+        285,
+        289,
+        292,
+        295,
+        299,
+        302,
+        305,
+        309,
+        312,
+        315,
+        319,
+        322,
+        325,
+        328,
+        332,
+        335,
+        338,
+        342,
+        345,
+        348,
+        352,
+        355,
+        358,
+        362,
+        365,
+        368,
+        372,
+        375,
+        378,
+        382,
+        385,
+        388,
+        392,
+        395,
+        398,
+        402,
+        405,
+        408,
+        412,
+        415,
+        418,
+        422,
+        425,
+        428,
+        431,
+        435,
+        438,
+        441,
+        445,
+        448,
+        451,
+        455,
+        458,
+        461,
+        465,
+        468,
+        471,
+        475,
+        478,
+        481,
+        485,
+        488,
+        491,
+        495,
+        498,
+        501,
+        505,
+        508,
+        511,
+        515,
+        518,
+        521,
+        524,
+        528,
+        531,
+        534,
+        538,
+        541,
+        544,
+        548,
+        551,
+        554,
+        558,
+        561,
+        564,
+        568,
+        571,
+        574,
+        578,
+        581,
+        584,
+        588,
+        591,
+        594,
+        598,
+        601,
+        604,
+        608,
+        611,
+        614,
+        617,
+        621,
+        624,
+        627,
+        631,
+        634,
+        637,
+        641,
+        644,
+        647,
+        651,
+        654,
+        657,
+        661,
+        664,
+        667,
+        671,
+        674,
+        677,
+        681,
+        684,
+        687,
+        691,
+        694,
+        697,
+        701,
+        704,
+        707,
+        711,
+        714,
+        717,
+        720,
+        724,
+        727,
+        730,
+        734,
+        737,
+        740,
+        744,
+        747,
+        750,
+        754,
+        757,
+        760,
+        764,
+        767,
+        770,
+        774,
+        777,
+        780,
+        784,
+        787,
+        790,
+        794,
+        797,
+        800,
+        804,
+        807,
+        810,
+        813,
+        817,
+        820,
+        823,
+        827,
+        830,
+        833,
+        837,
+        840,
+        843,
+        847,
+        850,
+        853,
+        857,
+        860,
+        863,
+        867,
+        870,
+        873,
+        877,
+        880,
+        883,
+        887,
+        890,
+        893,
+        897,
+        900,
+        903,
+        907,
+        910,
+        913,
+        916,
+        920,
+        923,
+        926,
+        930,
+        933,
+        936,
+        940,
+        943,
+        946,
+        950,
+    ],
+);
 
+#[rustfmt::skip]
 pub const F32_SHORT_POWERS: [f32; 11] = [
     1e0,
     1e1,
@@ -1244,6 +1249,7 @@ pub const F32_SHORT_POWERS: [f32; 11] = [
     1e10,
 ];
 
+#[rustfmt::skip]
 pub const F64_SHORT_POWERS: [f64; 23] = [
     1e0,
     1e1,
diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs
index 38b3fab6d75..913c0f96d11 100644
--- a/src/libcore/num/f32.rs
+++ b/src/libcore/num/f32.rs
@@ -26,7 +26,7 @@ pub const DIGITS: u32 = 6;
 
 /// [Machine epsilon] value for `f32`.
 ///
-/// This is the difference between `1.0` and the next largest representable number.
+/// This is the difference between `1.0` and the next larger representable number.
 ///
 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs
index f093bae9590..6ca830b1f38 100644
--- a/src/libcore/num/f64.rs
+++ b/src/libcore/num/f64.rs
@@ -26,7 +26,7 @@ pub const DIGITS: u32 = 15;
 
 /// [Machine epsilon] value for `f64`.
 ///
-/// This is the difference between `1.0` and the next largest representable number.
+/// This is the difference between `1.0` and the next larger representable number.
 ///
 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/libcore/panic.rs b/src/libcore/panic.rs
index cdd38449a1b..99b372d92c8 100644
--- a/src/libcore/panic.rs
+++ b/src/libcore/panic.rs
@@ -266,6 +266,16 @@ impl fmt::Display for Location<'_> {
 #[unstable(feature = "std_internals", issue = "0")]
 #[doc(hidden)]
 pub unsafe trait BoxMeUp {
-    fn box_me_up(&mut self) -> *mut (dyn Any + Send);
+    /// Take full ownership of the contents.
+    /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
+    ///
+    /// After this method got called, only some dummy default value is left in `self`.
+    /// Calling this method twice, or calling `get` after calling this method, is an error.
+    ///
+    /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
+    /// gets a borrowed `dyn BoxMeUp`.
+    fn take_box(&mut self) -> *mut (dyn Any + Send);
+
+    /// Just borrow the contents.
     fn get(&mut self) -> &(dyn Any + Send);
 }
diff --git a/src/libcore/panicking.rs b/src/libcore/panicking.rs
index 4833194be37..5a8d647396d 100644
--- a/src/libcore/panicking.rs
+++ b/src/libcore/panicking.rs
@@ -11,13 +11,13 @@
 //! ```
 //!
 //! This definition allows for panicking with any general message, but it does not
-//! allow for failing with a `Box<Any>` value. The reason for this is that libcore
-//! is not allowed to allocate.
+//! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&(dyn Any + Send)`,
+//! for which we fill in a dummy value in `PanicInfo::internal_constructor`.)
+//! The reason for this is that libcore is not allowed to allocate.
 //!
 //! This module contains a few other panicking functions, but these are just the
 //! necessary lang items for the compiler. All panics are funneled through this
-//! one function. Currently, the actual symbol is declared in the standard
-//! library, but the location of this may change over time.
+//! one function. The actual symbol is declared through the `#[panic_handler]` attribute.
 
 // ignore-tidy-undocumented-unsafe
 
@@ -72,6 +72,7 @@ pub fn panic_fmt(fmt: fmt::Arguments<'_>, location: &Location<'_>) -> ! {
     }
 
     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
+    // that gets resolved to the `#[panic_handler]` function.
     extern "Rust" {
         #[lang = "panic_impl"]
         fn panic_impl(pi: &PanicInfo<'_>) -> !;
diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs
index 39d56958f5d..1e051dbebca 100644
--- a/src/libcore/ptr/mod.rs
+++ b/src/libcore/ptr/mod.rs
@@ -1074,17 +1074,22 @@ impl<T: ?Sized> *const T {
     /// operation because the returned value could be pointing to invalid
     /// memory.
     ///
-    /// When calling this method, you have to ensure that if the pointer is
-    /// non-NULL, then it is properly aligned, dereferencable (for the whole
-    /// size of `T`) and points to an initialized instance of `T`. This applies
-    /// even if the result of this method is unused!
+    /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
+    /// all of the following is true:
+    /// - it is properly aligned
+    /// - it must point to an initialized instance of T; in particular, the pointer must be
+    ///   "dereferencable" in the sense defined [here].
+    ///
+    /// This applies even if the result of this method is unused!
     /// (The part about being initialized is not yet fully decided, but until
     /// it is, the only safe approach is to ensure that they are indeed initialized.)
     ///
     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
-    /// not necessarily reflect the actual lifetime of the data. It is up to the
-    /// caller to ensure that for the duration of this lifetime, the memory this
-    /// pointer points to does not get written to outside of `UnsafeCell<U>`.
+    /// not necessarily reflect the actual lifetime of the data. *You* must enforce
+    /// Rust's aliasing rules. In particular, for the duration of this lifetime,
+    /// the memory the pointer points to must not get mutated (except inside `UnsafeCell`).
+    ///
+    /// [here]: crate::ptr#safety
     ///
     /// # Examples
     ///
@@ -1929,18 +1934,23 @@ impl<T: ?Sized> *mut T {
     /// of the returned pointer, nor can it ensure that the lifetime `'a`
     /// returned is indeed a valid lifetime for the contained data.
     ///
-    /// When calling this method, you have to ensure that if the pointer is
-    /// non-NULL, then it is properly aligned, dereferencable (for the whole
-    /// size of `T`) and points to an initialized instance of `T`. This applies
-    /// even if the result of this method is unused!
+    /// When calling this method, you have to ensure that *either* the pointer is NULL *or*
+    /// all of the following is true:
+    /// - it is properly aligned
+    /// - it must point to an initialized instance of T; in particular, the pointer must be
+    ///   "dereferencable" in the sense defined [here].
+    ///
+    /// This applies even if the result of this method is unused!
     /// (The part about being initialized is not yet fully decided, but until
     /// it is the only safe approach is to ensure that they are indeed initialized.)
     ///
     /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
-    /// not necessarily reflect the actual lifetime of the data. It is up to the
-    /// caller to ensure that for the duration of this lifetime, the memory this
-    /// pointer points to does not get accessed through any other pointer.
+    /// not necessarily reflect the actual lifetime of the data. *You* must enforce
+    /// Rust's aliasing rules. In particular, for the duration of this lifetime,
+    /// the memory this pointer points to must not get accessed (read or written)
+    /// through any other pointer.
     ///
+    /// [here]: crate::ptr#safety
     /// [`as_ref`]: #method.as_ref
     ///
     /// # Examples
diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs
index 820c1edf930..251d49db062 100644
--- a/src/libcore/sync/atomic.rs
+++ b/src/libcore/sync/atomic.rs
@@ -802,6 +802,43 @@ impl AtomicBool {
     pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
         unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
     }
+
+    /// Returns a mutable pointer to the underlying [`bool`].
+    ///
+    /// Doing non-atomic reads and writes on the resulting integer can be a data race.
+    /// This method is mostly useful for FFI, where the function signature may use
+    /// `*mut bool` instead of `&AtomicBool`.
+    ///
+    /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
+    /// atomic types work with interior mutability. All modifications of an atomic change the value
+    /// through a shared reference, and can do so safely as long as they use atomic operations. Any
+    /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
+    /// restriction: operations on it must be atomic.
+    ///
+    /// [`bool`]: ../../../std/primitive.bool.html
+    ///
+    /// # Examples
+    ///
+    /// ```ignore (extern-declaration)
+    /// # fn main() {
+    /// use std::sync::atomic::AtomicBool;
+    /// extern {
+    ///     fn my_atomic_op(arg: *mut bool);
+    /// }
+    ///
+    /// let mut atomic = AtomicBool::new(true);
+    /// unsafe {
+    ///     my_atomic_op(atomic.as_mut_ptr());
+    /// }
+    /// # }
+    /// ```
+    #[inline]
+    #[unstable(feature = "atomic_mut_ptr",
+           reason = "recently added",
+           issue = "66893")]
+    pub fn as_mut_ptr(&self) -> *mut bool {
+        self.v.get() as *mut bool
+    }
 }
 
 #[cfg(target_has_atomic_load_store = "ptr")]
@@ -1891,6 +1928,43 @@ assert_eq!(min_foo, 12);
                 }
             }
 
+            doc_comment! {
+                concat!("Returns a mutable pointer to the underlying integer.
+
+Doing non-atomic reads and writes on the resulting integer can be a data race.
+This method is mostly useful for FFI, where the function signature may use
+`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.
+
+Returning an `*mut` pointer from a shared reference to this atomic is safe because the
+atomic types work with interior mutability. All modifications of an atomic change the value
+through a shared reference, and can do so safely as long as they use atomic operations. Any
+use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
+restriction: operations on it must be atomic.
+
+# Examples
+
+```ignore (extern-declaration)
+# fn main() {
+", $extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";
+
+extern {
+    fn my_atomic_op(arg: *mut ", stringify!($int_type), ");
+}
+
+let mut atomic = ", stringify!($atomic_type), "::new(1);
+unsafe {
+    my_atomic_op(atomic.as_mut_ptr());
+}
+# }
+```"),
+                #[inline]
+                #[unstable(feature = "atomic_mut_ptr",
+                       reason = "recently added",
+                       issue = "66893")]
+                pub fn as_mut_ptr(&self) -> *mut $int_type {
+                    self.v.get()
+                }
+            }
         }
     }
 }
diff --git a/src/libcore/tests/num/bignum.rs b/src/libcore/tests/num/bignum.rs
index b9e15ec5c07..50a3ec046ad 100644
--- a/src/libcore/tests/num/bignum.rs
+++ b/src/libcore/tests/num/bignum.rs
@@ -1,4 +1,3 @@
-use std::prelude::v1::*;
 use core::num::bignum::tests::Big8x3 as Big;
 
 #[test]
diff --git a/src/libcore/tests/num/flt2dec/mod.rs b/src/libcore/tests/num/flt2dec/mod.rs
index a35897e9bc1..f85369ce40b 100644
--- a/src/libcore/tests/num/flt2dec/mod.rs
+++ b/src/libcore/tests/num/flt2dec/mod.rs
@@ -1,4 +1,3 @@
-use std::prelude::v1::*;
 use std::{str, i16, f32, f64, fmt};
 
 use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded};
diff --git a/src/libcore/tests/num/flt2dec/strategy/dragon.rs b/src/libcore/tests/num/flt2dec/strategy/dragon.rs
index dc4d78bfae1..0c545b4d887 100644
--- a/src/libcore/tests/num/flt2dec/strategy/dragon.rs
+++ b/src/libcore/tests/num/flt2dec/strategy/dragon.rs
@@ -1,4 +1,3 @@
-use std::prelude::v1::*;
 use super::super::*;
 use core::num::bignum::Big32x40 as Big;
 use core::num::flt2dec::strategy::dragon::*;
diff --git a/src/libcore/unicode/printable.py b/src/libcore/unicode/printable.py
index 4e8b4ecad02..91db6381c9b 100644..100755
--- a/src/libcore/unicode/printable.py
+++ b/src/libcore/unicode/printable.py
@@ -111,16 +111,19 @@ def compress_normal(normal):
     return compressed
 
 def print_singletons(uppers, lowers, uppersname, lowersname):
+    print("#[rustfmt::skip]")
     print("const {}: &[(u8, u8)] = &[".format(uppersname))
     for u, c in uppers:
         print("    ({:#04x}, {}),".format(u, c))
     print("];")
+    print("#[rustfmt::skip]")
     print("const {}: &[u8] = &[".format(lowersname))
     for i in range(0, len(lowers), 8):
         print("    {}".format(" ".join("{:#04x},".format(l) for l in lowers[i:i+8])))
     print("];")
 
 def print_normal(normal, normalname):
+    print("#[rustfmt::skip]")
     print("const {}: &[u8] = &[".format(normalname))
     for v in normal:
         print("    {}".format(" ".join("{:#04x},".format(i) for i in v)))
@@ -170,8 +173,7 @@ def main():
 // NOTE: The following code was generated by "src/libcore/unicode/printable.py",
 //       do not edit directly!
 
-fn check(x: u16, singletonuppers: &[(u8, u8)], singletonlowers: &[u8],
-         normal: &[u8]) -> bool {
+fn check(x: u16, singletonuppers: &[(u8, u8)], singletonlowers: &[u8], normal: &[u8]) -> bool {
     let xupper = (x >> 8) as u8;
     let mut lowerstart = 0;
     for &(upper, lowercount) in singletonuppers {
diff --git a/src/libcore/unicode/printable.rs b/src/libcore/unicode/printable.rs
index d411dda7dc1..eee9ea52ef0 100644
--- a/src/libcore/unicode/printable.rs
+++ b/src/libcore/unicode/printable.rs
@@ -1,8 +1,7 @@
 // NOTE: The following code was generated by "src/libcore/unicode/printable.py",
 //       do not edit directly!
 
-fn check(x: u16, singletonuppers: &[(u8, u8)], singletonlowers: &[u8],
-         normal: &[u8]) -> bool {
+fn check(x: u16, singletonuppers: &[(u8, u8)], singletonlowers: &[u8], normal: &[u8]) -> bool {
     let xupper = (x >> 8) as u8;
     let mut lowerstart = 0;
     for &(upper, lowercount) in singletonuppers {
@@ -70,6 +69,7 @@ pub(crate) fn is_printable(x: char) -> bool {
     }
 }
 
+#[rustfmt::skip]
 const SINGLETONS0U: &[(u8, u8)] = &[
     (0x00, 1),
     (0x03, 5),
@@ -113,6 +113,7 @@ const SINGLETONS0U: &[(u8, u8)] = &[
     (0xfe, 3),
     (0xff, 9),
 ];
+#[rustfmt::skip]
 const SINGLETONS0L: &[u8] = &[
     0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57,
     0x58, 0x8b, 0x8c, 0x90, 0x1c, 0x1d, 0xdd, 0x0e,
@@ -152,6 +153,7 @@ const SINGLETONS0L: &[u8] = &[
     0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1,
     0xd8, 0xd9, 0xe7, 0xfe, 0xff,
 ];
+#[rustfmt::skip]
 const SINGLETONS1U: &[(u8, u8)] = &[
     (0x00, 6),
     (0x01, 1),
@@ -189,6 +191,7 @@ const SINGLETONS1U: &[(u8, u8)] = &[
     (0xf9, 6),
     (0xfa, 2),
 ];
+#[rustfmt::skip]
 const SINGLETONS1L: &[u8] = &[
     0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e,
     0x9e, 0x9f, 0x06, 0x07, 0x09, 0x36, 0x3d, 0x3e,
@@ -212,6 +215,7 @@ const SINGLETONS1L: &[u8] = &[
     0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0, 0x0c, 0x72,
     0xa3, 0xa4, 0xcb, 0xcc, 0x6e, 0x6f,
 ];
+#[rustfmt::skip]
 const NORMAL0: &[u8] = &[
     0x00, 0x20,
     0x5f, 0x22,
@@ -355,6 +359,7 @@ const NORMAL0: &[u8] = &[
     0x1b, 0x03,
     0x0f, 0x0d,
 ];
+#[rustfmt::skip]
 const NORMAL1: &[u8] = &[
     0x5e, 0x22,
     0x7b, 0x05,
diff --git a/src/libcore/unicode/tables.rs b/src/libcore/unicode/tables.rs
index 5b5be485431..3fa125e8fea 100644
--- a/src/libcore/unicode/tables.rs
+++ b/src/libcore/unicode/tables.rs
@@ -2,19 +2,16 @@
 
 #![allow(missing_docs, non_upper_case_globals, non_snake_case, clippy::unreadable_literal)]
 
-use crate::unicode::version::UnicodeVersion;
 use crate::unicode::bool_trie::{BoolTrie, SmallBoolTrie};
+use crate::unicode::version::UnicodeVersion;
 
 /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
 /// `char` and `str` methods are based on.
 #[unstable(feature = "unicode_version", issue = "49726")]
-pub const UNICODE_VERSION: UnicodeVersion = UnicodeVersion {
-    major: 12,
-    minor: 1,
-    micro: 0,
-    _priv: (),
-};
+pub const UNICODE_VERSION: UnicodeVersion =
+    UnicodeVersion { major: 12, minor: 1, micro: 0, _priv: () };
 pub(crate) mod general_category {
+    #[rustfmt::skip]
     const Cc_table: &super::SmallBoolTrie = &super::SmallBoolTrie {
         r1: &[
             0, 1, 0
@@ -28,6 +25,7 @@ pub(crate) mod general_category {
         Cc_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const N_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x03ff000000000000, 0x0000000000000000, 0x720c000000000000, 0x0000000000000000,
@@ -138,10 +136,10 @@ pub(crate) mod general_category {
     pub fn N(c: char) -> bool {
         N_table.lookup(c)
     }
-
 }
 
 pub(crate) mod derived_property {
+    #[rustfmt::skip]
     const Alphabetic_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0000000000000000, 0x07fffffe07fffffe, 0x0420040000000000, 0xff7fffffff7fffff,
@@ -327,6 +325,7 @@ pub(crate) mod derived_property {
         Alphabetic_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const Case_Ignorable_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0400408000000000, 0x0000000140000000, 0x0190a10000000000, 0x0000000000000000,
@@ -464,6 +463,7 @@ pub(crate) mod derived_property {
         Case_Ignorable_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const Cased_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0000000000000000, 0x07fffffe07fffffe, 0x0420040000000000, 0xff7fffffff7fffff,
@@ -565,6 +565,7 @@ pub(crate) mod derived_property {
         Cased_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const Grapheme_Extend_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000,
@@ -689,6 +690,7 @@ pub(crate) mod derived_property {
         Grapheme_Extend_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const Lowercase_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0000000000000000, 0x07fffffe00000000, 0x0420040000000000, 0xff7fffff80000000,
@@ -789,6 +791,7 @@ pub(crate) mod derived_property {
         Lowercase_table.lookup(c)
     }
 
+    #[rustfmt::skip]
     const Uppercase_table: &super::BoolTrie = &super::BoolTrie {
         r1: [
             0x0000000000000000, 0x0000000007fffffe, 0x0000000000000000, 0x000000007f7fffff,
@@ -889,10 +892,10 @@ pub(crate) mod derived_property {
     pub fn Uppercase(c: char) -> bool {
         Uppercase_table.lookup(c)
     }
-
 }
 
 pub(crate) mod property {
+    #[rustfmt::skip]
     const White_Space_table: &super::SmallBoolTrie = &super::SmallBoolTrie {
         r1: &[
             0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -912,20 +915,19 @@ pub(crate) mod property {
     pub fn White_Space(c: char) -> bool {
         White_Space_table.lookup(c)
     }
-
 }
 
 pub(crate) mod conversions {
     pub fn to_lower(c: char) -> [char; 3] {
         match bsearch_case_table(c, to_lowercase_table) {
-            None        => [c, '\0', '\0'],
+            None => [c, '\0', '\0'],
             Some(index) => to_lowercase_table[index].1,
         }
     }
 
     pub fn to_upper(c: char) -> [char; 3] {
         match bsearch_case_table(c, to_uppercase_table) {
-            None        => [c, '\0', '\0'],
+            None => [c, '\0', '\0'],
             Some(index) => to_uppercase_table[index].1,
         }
     }
@@ -934,6 +936,7 @@ pub(crate) mod conversions {
         table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
     }
 
+    #[rustfmt::skip]
     const to_lowercase_table: &[(char, [char; 3])] = &[
         ('\u{41}', ['\u{61}', '\0', '\0']), ('\u{42}', ['\u{62}', '\0', '\0']), ('\u{43}',
         ['\u{63}', '\0', '\0']), ('\u{44}', ['\u{64}', '\0', '\0']), ('\u{45}', ['\u{65}', '\0',
@@ -1558,6 +1561,7 @@ pub(crate) mod conversions {
         ('\u{1e920}', ['\u{1e942}', '\0', '\0']), ('\u{1e921}', ['\u{1e943}', '\0', '\0'])
     ];
 
+    #[rustfmt::skip]
     const to_uppercase_table: &[(char, [char; 3])] = &[
         ('\u{61}', ['\u{41}', '\0', '\0']), ('\u{62}', ['\u{42}', '\0', '\0']), ('\u{63}',
         ['\u{43}', '\0', '\0']), ('\u{64}', ['\u{44}', '\0', '\0']), ('\u{65}', ['\u{45}', '\0',
@@ -2228,5 +2232,4 @@ pub(crate) mod conversions {
         ('\u{1e940}', ['\u{1e91e}', '\0', '\0']), ('\u{1e941}', ['\u{1e91f}', '\0', '\0']),
         ('\u{1e942}', ['\u{1e920}', '\0', '\0']), ('\u{1e943}', ['\u{1e921}', '\0', '\0'])
     ];
-
 }
diff --git a/src/libcore/unicode/unicode.py b/src/libcore/unicode/unicode.py
index 89894f7932d..97df92a56da 100755
--- a/src/libcore/unicode/unicode.py
+++ b/src/libcore/unicode/unicode.py
@@ -81,8 +81,8 @@ PREAMBLE = """\
 
 #![allow(missing_docs, non_upper_case_globals, non_snake_case, clippy::unreadable_literal)]
 
-use crate::unicode::version::UnicodeVersion;
 use crate::unicode::bool_trie::{{BoolTrie, SmallBoolTrie}};
+use crate::unicode::version::UnicodeVersion;
 """.format(year=datetime.datetime.now().year)
 
 # Mapping taken from Table 12 from:
@@ -555,6 +555,8 @@ def generate_table(
     if is_pub:
         pub_string = "pub "
 
+    yield "\n"
+    yield "    #[rustfmt::skip]\n"
     yield "    %sconst %s: %s = &[\n" % (pub_string, name, decl_type)
 
     data = []
@@ -568,7 +570,7 @@ def generate_table(
     for table_line in generate_table_lines("".join(data).split(","), 8):
         yield table_line
 
-    yield "\n    ];\n\n"
+    yield "\n    ];\n"
 
 
 def compute_trie(raw_data, chunk_size):
@@ -634,6 +636,9 @@ def generate_bool_trie(name, codepoint_ranges, is_pub=False):
     pub_string = ""
     if is_pub:
         pub_string = "pub "
+
+    yield "\n"
+    yield "    #[rustfmt::skip]\n"
     yield "    %sconst %s: &super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name)
     yield "        r1: [\n"
     data = ("0x%016x" % chunk for chunk in chunks[:0x800 // chunk_size])
@@ -678,7 +683,7 @@ def generate_bool_trie(name, codepoint_ranges, is_pub=False):
         yield fragment
     yield "\n        ],\n"
 
-    yield "    };\n\n"
+    yield "    };\n"
 
 
 def generate_small_bool_trie(name, codepoint_ranges, is_pub=False):
@@ -700,6 +705,8 @@ def generate_small_bool_trie(name, codepoint_ranges, is_pub=False):
     if is_pub:
         pub_string = "pub "
 
+    yield "\n"
+    yield "    #[rustfmt::skip]\n"
     yield ("    %sconst %s: &super::SmallBoolTrie = &super::SmallBoolTrie {\n"
            % (pub_string, name))
 
@@ -717,7 +724,7 @@ def generate_small_bool_trie(name, codepoint_ranges, is_pub=False):
         yield fragment
     yield "\n        ],\n"
 
-    yield "    };\n\n"
+    yield "    };\n"
 
 
 def generate_property_module(mod, grouped_categories, category_subset):
@@ -726,7 +733,7 @@ def generate_property_module(mod, grouped_categories, category_subset):
     Generate Rust code for module defining properties.
     """
 
-    yield "pub(crate) mod %s {\n" % mod
+    yield "pub(crate) mod %s {" % mod
     for cat in sorted(category_subset):
         if cat in ("Cc", "White_Space"):
             generator = generate_small_bool_trie("%s_table" % cat, grouped_categories[cat])
@@ -736,9 +743,10 @@ def generate_property_module(mod, grouped_categories, category_subset):
         for fragment in generator:
             yield fragment
 
+        yield "\n"
         yield "    pub fn %s(c: char) -> bool {\n" % cat
         yield "        %s_table.lookup(c)\n" % cat
-        yield "    }\n\n"
+        yield "    }\n"
 
     yield "}\n\n"
 
@@ -753,21 +761,21 @@ def generate_conversions_module(unicode_data):
     yield """
     pub fn to_lower(c: char) -> [char; 3] {
         match bsearch_case_table(c, to_lowercase_table) {
-            None        => [c, '\\0', '\\0'],
+            None => [c, '\\0', '\\0'],
             Some(index) => to_lowercase_table[index].1,
         }
     }
 
     pub fn to_upper(c: char) -> [char; 3] {
         match bsearch_case_table(c, to_uppercase_table) {
-            None        => [c, '\\0', '\\0'],
+            None => [c, '\\0', '\\0'],
             Some(index) => to_uppercase_table[index].1,
         }
     }
 
     fn bsearch_case_table(c: char, table: &[(char, [char; 3])]) -> Option<usize> {
         table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
-    }\n\n"""
+    }\n"""
 
     decl_type = "&[(char, [char; 3])]"
     format_conversion = lambda x: "({},[{},{},{}])".format(*(
@@ -827,13 +835,9 @@ def main():
     /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
     /// `char` and `str` methods are based on.
     #[unstable(feature = "unicode_version", issue = "49726")]
-    pub const UNICODE_VERSION: UnicodeVersion = UnicodeVersion {{
-        major: {version.major},
-        minor: {version.minor},
-        micro: {version.micro},
-        _priv: (),
-    }};
-    """).format(version=unicode_version)
+    pub const UNICODE_VERSION: UnicodeVersion =
+        UnicodeVersion {{ major: {v.major}, minor: {v.minor}, micro: {v.micro}, _priv: () }};
+    """).format(v=unicode_version)
     buf.write(unicode_version_notice)
 
     get_path = lambda f: get_unicode_file_path(unicode_version, f)
diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs
index 24b19028ac1..900c6ed5ff3 100644
--- a/src/libfmt_macros/lib.rs
+++ b/src/libfmt_macros/lib.rs
@@ -442,20 +442,9 @@ impl<'a> Parser<'a> {
             Some(ArgumentIs(i))
         } else {
             match self.cur.peek() {
-                Some(&(_, c)) if c.is_alphabetic() => {
+                Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
                     Some(ArgumentNamed(Symbol::intern(self.word())))
                 }
-                Some(&(pos, c)) if c == '_' => {
-                    let invalid_name = self.string(pos);
-                    self.err_with_note(format!("invalid argument name `{}`", invalid_name),
-                                       "invalid argument name",
-                                       "argument names cannot start with an underscore",
-                                        self.to_span_index(pos).to(
-                                            self.to_span_index(pos + invalid_name.len())
-                                        ),
-                                        );
-                    Some(ArgumentNamed(Symbol::intern(invalid_name)))
-                },
 
                 // This is an `ArgumentNext`.
                 // Record the fact and do the resolution after parsing the
@@ -611,22 +600,34 @@ impl<'a> Parser<'a> {
     /// Rust identifier, except that it can't start with `_` character.
     fn word(&mut self) -> &'a str {
         let start = match self.cur.peek() {
-            Some(&(pos, c)) if c != '_' && rustc_lexer::is_id_start(c) => {
+            Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
                 self.cur.next();
                 pos
             }
             _ => {
-                return &self.input[..0];
+                return "";
             }
         };
+        let mut end = None;
         while let Some(&(pos, c)) = self.cur.peek() {
             if rustc_lexer::is_id_continue(c) {
                 self.cur.next();
             } else {
-                return &self.input[start..pos];
+                end = Some(pos);
+                break;
             }
         }
-        &self.input[start..self.input.len()]
+        let end = end.unwrap_or(self.input.len());
+        let word = &self.input[start..end];
+        if word == "_" {
+            self.err_with_note(
+                "invalid argument name `_`",
+                "invalid argument name",
+                "argument name cannot be a single underscore",
+                self.to_span_index(start).to(self.to_span_index(end)),
+            );
+        }
+        word
     }
 
     /// Optionally parses an integer at the current position. This doesn't deal
diff --git a/src/libpanic_unwind/lib.rs b/src/libpanic_unwind/lib.rs
index d97a7a8a87d..3a14197c77b 100644
--- a/src/libpanic_unwind/lib.rs
+++ b/src/libpanic_unwind/lib.rs
@@ -36,10 +36,7 @@ use core::raw;
 use core::panic::BoxMeUp;
 
 cfg_if::cfg_if! {
-    if #[cfg(miri)] {
-        #[path = "miri.rs"]
-        mod imp;
-    } else if #[cfg(target_os = "emscripten")] {
+    if #[cfg(target_os = "emscripten")] {
         #[path = "emcc.rs"]
         mod imp;
     } else if #[cfg(target_arch = "wasm32")] {
@@ -94,5 +91,14 @@ pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8),
 #[unwind(allowed)]
 pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 {
     let payload = payload as *mut &mut dyn BoxMeUp;
-    imp::panic(Box::from_raw((*payload).box_me_up()))
+    let payload = (*payload).take_box();
+
+    // Miri panic support: cfg'd out of normal builds just to be sure.
+    // When going through normal codegen, `miri_start_panic` is a NOP, so the
+    // Miri-enabled sysroot still supports normal unwinding. But when executed in
+    // Miri, this line initiates unwinding.
+    #[cfg(miri)]
+    core::intrinsics::miri_start_panic(payload);
+
+    imp::panic(Box::from_raw(payload))
 }
diff --git a/src/libpanic_unwind/miri.rs b/src/libpanic_unwind/miri.rs
deleted file mode 100644
index f26c42fd4bc..00000000000
--- a/src/libpanic_unwind/miri.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-#![allow(nonstandard_style)]
-
-use core::any::Any;
-use alloc::boxed::Box;
-
-pub fn payload() -> *mut u8 {
-    core::ptr::null_mut()
-}
-
-pub unsafe fn panic(data: Box<dyn Any + Send>) -> ! {
-    core::intrinsics::miri_start_panic(Box::into_raw(data))
-}
-
-pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
-    Box::from_raw(ptr)
-}
-
-// This is required by the compiler to exist (e.g., it's a lang item),
-// but is never used by Miri. Therefore, we just use a stub here
-#[lang = "eh_personality"]
-#[cfg(not(test))]
-fn rust_eh_personality() {
-    unsafe { core::intrinsics::abort() }
-}
-
-// The rest is required on *some* targets to exist (specifically, MSVC targets that use SEH).
-// We just add it on all targets. Copied from `seh.rs`.
-#[repr(C)]
-pub struct _TypeDescriptor {
-    pub pVFTable: *const u8,
-    pub spare: *mut u8,
-    pub name: [u8; 11],
-}
-
-const TYPE_NAME: [u8; 11] = *b"rust_panic\0";
-
-#[cfg_attr(not(test), lang = "eh_catch_typeinfo")]
-static mut TYPE_DESCRIPTOR: _TypeDescriptor = _TypeDescriptor {
-    pVFTable: core::ptr::null(),
-    spare: core::ptr::null_mut(),
-    name: TYPE_NAME,
-};
diff --git a/src/librustc/Cargo.toml b/src/librustc/Cargo.toml
index 6c1695a4eac..fb30d6c519c 100644
--- a/src/librustc/Cargo.toml
+++ b/src/librustc/Cargo.toml
@@ -22,6 +22,7 @@ rustc-rayon = "0.3.0"
 rustc-rayon-core = "0.3.0"
 polonius-engine  = "0.10.0"
 rustc_apfloat = { path = "../librustc_apfloat" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_target = { path = "../librustc_target" }
 rustc_macros = { path = "../librustc_macros" }
 rustc_data_structures = { path = "../librustc_data_structures" }
diff --git a/src/librustc/arena.rs b/src/librustc/arena.rs
index 9b13a910c61..1d6a3420ed9 100644
--- a/src/librustc/arena.rs
+++ b/src/librustc/arena.rs
@@ -93,6 +93,7 @@ macro_rules! arena_types {
                         rustc::hir::def_id::CrateNum
                     >
                 >,
+            [few] hir_forest: rustc::hir::map::Forest,
             [few] diagnostic_items: rustc_data_structures::fx::FxHashMap<
                 syntax::symbol::Symbol,
                 rustc::hir::def_id::DefId,
@@ -100,7 +101,7 @@ macro_rules! arena_types {
             [few] resolve_lifetimes: rustc::middle::resolve_lifetime::ResolveLifetimes,
             [few] lint_levels: rustc::lint::LintLevelMap,
             [few] stability_index: rustc::middle::stability::Index<'tcx>,
-            [few] features: syntax::feature_gate::Features,
+            [few] features: rustc_feature::Features,
             [few] all_traits: Vec<rustc::hir::def_id::DefId>,
             [few] privacy_access_levels: rustc::middle::privacy::AccessLevels,
             [few] target_features_whitelist: rustc_data_structures::fx::FxHashMap<
diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs
index fc754c5e675..5bf5a93ad01 100644
--- a/src/librustc/hir/map/mod.rs
+++ b/src/librustc/hir/map/mod.rs
@@ -200,7 +200,7 @@ pub struct Map<'hir> {
 
     map: HirEntryMap<'hir>,
 
-    definitions: &'hir Definitions,
+    definitions: Definitions,
 
     /// The reverse mapping of `node_to_hir_id`.
     hir_to_node_id: FxHashMap<HirId, NodeId>,
@@ -267,8 +267,8 @@ impl<'hir> Map<'hir> {
     }
 
     #[inline]
-    pub fn definitions(&self) -> &'hir Definitions {
-        self.definitions
+    pub fn definitions(&self) -> &Definitions {
+        &self.definitions
     }
 
     pub fn def_key(&self, def_id: DefId) -> DefKey {
@@ -1251,7 +1251,7 @@ impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
 pub fn map_crate<'hir>(sess: &crate::session::Session,
                        cstore: &CrateStoreDyn,
                        forest: &'hir Forest,
-                       definitions: &'hir Definitions)
+                       definitions: Definitions)
                        -> Map<'hir> {
     let _prof_timer = sess.prof.generic_activity("build_hir_map");
 
@@ -1260,7 +1260,7 @@ pub fn map_crate<'hir>(sess: &crate::session::Session,
         .map(|(node_id, &hir_id)| (hir_id, node_id)).collect();
 
     let (map, crate_hash) = {
-        let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore);
+        let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, &definitions, cstore);
 
         let mut collector = NodeCollector::root(sess,
                                                 &forest.krate,
diff --git a/src/librustc/ich/impls_syntax.rs b/src/librustc/ich/impls_syntax.rs
index 144980c53eb..6499e56325a 100644
--- a/src/librustc/ich/impls_syntax.rs
+++ b/src/librustc/ich/impls_syntax.rs
@@ -4,7 +4,6 @@
 use crate::ich::StableHashingContext;
 
 use syntax::ast;
-use syntax::feature_gate;
 use syntax_pos::SourceFile;
 
 use crate::hir::def_id::{DefId, CrateNum, CRATE_DEF_INDEX};
@@ -156,7 +155,7 @@ fn stable_normalized_pos(np: ::syntax_pos::NormalizedPos,
 }
 
 
-impl<'tcx> HashStable<StableHashingContext<'tcx>> for feature_gate::Features {
+impl<'tcx> HashStable<StableHashingContext<'tcx>> for rustc_feature::Features {
     fn hash_stable(&self, hcx: &mut StableHashingContext<'tcx>, hasher: &mut StableHasher) {
         // Unfortunately we cannot exhaustively list fields here, since the
         // struct is macro generated.
diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs
index b670658a10a..5a940f2f80a 100644
--- a/src/librustc/infer/error_reporting/mod.rs
+++ b/src/librustc/infer/error_reporting/mod.rs
@@ -1545,8 +1545,20 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
             infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
             infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
             infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
-            infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
-            infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
+            infer::TraitRefs(ref exp_found) => {
+                let pretty_exp_found = ty::error::ExpectedFound {
+                    expected: exp_found.expected.print_only_trait_path(),
+                    found: exp_found.found.print_only_trait_path()
+                };
+                self.expected_found_str(&pretty_exp_found)
+            },
+            infer::PolyTraitRefs(ref exp_found) => {
+                let pretty_exp_found = ty::error::ExpectedFound {
+                    expected: exp_found.expected.print_only_trait_path(),
+                    found: exp_found.found.print_only_trait_path()
+                };
+                self.expected_found_str(&pretty_exp_found)
+            },
         }
     }
 
diff --git a/src/librustc/infer/error_reporting/nice_region_error/placeholder_error.rs b/src/librustc/infer/error_reporting/nice_region_error/placeholder_error.rs
index bfa8353ca34..3b4d06aab27 100644
--- a/src/librustc/infer/error_reporting/nice_region_error/placeholder_error.rs
+++ b/src/librustc/infer/error_reporting/nice_region_error/placeholder_error.rs
@@ -401,7 +401,7 @@ impl NiceRegionError<'me, 'tcx> {
                 format!(
                     "{}`{}` would have to be implemented for the type `{}`",
                     if leading_ellipsis { "..." } else { "" },
-                    expected_trait_ref,
+                    expected_trait_ref.map(|tr| tr.print_only_trait_path()),
                     expected_trait_ref.map(|tr| tr.self_ty()),
                 )
             } else {
@@ -409,7 +409,7 @@ impl NiceRegionError<'me, 'tcx> {
                     "{}`{}` must implement `{}`",
                     if leading_ellipsis { "..." } else { "" },
                     expected_trait_ref.map(|tr| tr.self_ty()),
-                    expected_trait_ref,
+                    expected_trait_ref.map(|tr| tr.print_only_trait_path()),
                 )
             };
 
@@ -449,14 +449,14 @@ impl NiceRegionError<'me, 'tcx> {
             let mut note = if passive_voice {
                 format!(
                     "...but `{}` is actually implemented for the type `{}`",
-                    actual_trait_ref,
+                    actual_trait_ref.map(|tr| tr.print_only_trait_path()),
                     actual_trait_ref.map(|tr| tr.self_ty()),
                 )
             } else {
                 format!(
                     "...but `{}` actually implements `{}`",
                     actual_trait_ref.map(|tr| tr.self_ty()),
-                    actual_trait_ref,
+                    actual_trait_ref.map(|tr| tr.print_only_trait_path()),
                 )
             };
 
diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs
index 5e204d83aef..b3ddffc8b12 100644
--- a/src/librustc/infer/mod.rs
+++ b/src/librustc/infer/mod.rs
@@ -1292,7 +1292,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
     }
 
     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
-        self.resolve_vars_if_possible(t).to_string()
+        self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
     }
 
     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs
index 1fc157eca3e..481ae3b9329 100644
--- a/src/librustc/lib.rs
+++ b/src/librustc/lib.rs
@@ -96,7 +96,6 @@ pub mod infer;
 pub mod lint;
 
 pub mod middle {
-    pub mod expr_use_visitor;
     pub mod cstore;
     pub mod dependency_format;
     pub mod diagnostic_items;
@@ -104,7 +103,6 @@ pub mod middle {
     pub mod free_region;
     pub mod lib_features;
     pub mod lang_items;
-    pub mod mem_categorization;
     pub mod privacy;
     pub mod reachable;
     pub mod region;
diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs
index 2f865f1f8b5..7f72154e42c 100644
--- a/src/librustc/lint/context.rs
+++ b/src/librustc/lint/context.rs
@@ -47,8 +47,7 @@ use rustc_error_codes::*;
 /// This is basically the subset of `Context` that we can
 /// build early in the compile pipeline.
 pub struct LintStore {
-    /// Registered lints. The bool is true if the lint was
-    /// added by a plugin.
+    /// Registered lints.
     lints: Vec<&'static Lint>,
 
     /// Constructor functions for each variety of lint pass.
@@ -800,8 +799,13 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> {
                 // This shouldn't ever be needed, but just in case:
                 path.push(match trait_ref {
                     Some(trait_ref) => {
-                        Symbol::intern(&format!("<impl {} for {}>", trait_ref,
-                                                    self_ty))
+                        Symbol::intern(
+                            &format!(
+                                "<impl {} for {}>",
+                                trait_ref.print_only_trait_path(),
+                                self_ty
+                            )
+                        )
                     },
                     None => Symbol::intern(&format!("<impl {}>", self_ty)),
                 });
diff --git a/src/librustc/lint/levels.rs b/src/librustc/lint/levels.rs
index 27bf9649324..619ca724214 100644
--- a/src/librustc/lint/levels.rs
+++ b/src/librustc/lint/levels.rs
@@ -232,13 +232,13 @@ impl<'a> LintLevelsBuilder<'a> {
                             // don't have any lint names (`#[level(reason = "foo")]`)
                             if let ast::LitKind::Str(rationale, _) = name_value.kind {
                                 if !self.sess.features_untracked().lint_reasons {
-                                    feature_gate::emit_feature_err(
+                                    feature_gate::feature_err(
                                         &self.sess.parse_sess,
                                         sym::lint_reasons,
                                         item.span,
-                                        feature_gate::GateIssue::Language,
                                         "lint reasons are experimental"
-                                    );
+                                    )
+                                    .emit();
                                 }
                                 reason = Some(rationale);
                             } else {
diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs
index e5c80c35894..44c6f6b07f5 100644
--- a/src/librustc/middle/cstore.rs
+++ b/src/librustc/middle/cstore.rs
@@ -146,6 +146,13 @@ impl ExternCrate {
     pub fn is_direct(&self) -> bool {
         self.dependency_of == LOCAL_CRATE
     }
+
+    pub fn rank(&self) -> impl PartialOrd {
+        // Prefer:
+        // - direct extern crate to indirect
+        // - shorter paths to longer
+        (self.is_direct(), !self.path_len)
+    }
 }
 
 #[derive(Copy, Clone, Debug, HashStable)]
@@ -204,7 +211,7 @@ pub type MetadataLoaderDyn = dyn MetadataLoader + Sync;
 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
 /// during resolve)
 pub trait CrateStore {
-    fn crate_data_as_any(&self, cnum: CrateNum) -> &dyn Any;
+    fn as_any(&self) -> &dyn Any;
 
     // resolve
     fn def_key(&self, def: DefId) -> DefKey;
@@ -217,9 +224,7 @@ pub trait CrateStore {
     fn crate_is_private_dep_untracked(&self, cnum: CrateNum) -> bool;
     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
-    fn crate_host_hash_untracked(&self, cnum: CrateNum) -> Option<Svh>;
     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
-    fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
 
     // This is basically a 1-based range of ints, which is a little
     // silly - I may fix that.
@@ -228,7 +233,6 @@ pub trait CrateStore {
     // utility functions
     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata;
     fn metadata_encoding_version(&self) -> &[u8];
-    fn injected_panic_runtime(&self) -> Option<CrateNum>;
     fn allocator_kind(&self) -> Option<AllocatorKind>;
 }
 
diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs
deleted file mode 100644
index 3510fe4d123..00000000000
--- a/src/librustc/middle/mem_categorization.rs
+++ /dev/null
@@ -1,1508 +0,0 @@
-//! # Categorization
-//!
-//! The job of the categorization module is to analyze an expression to
-//! determine what kind of memory is used in evaluating it (for example,
-//! where dereferences occur and what kind of pointer is dereferenced;
-//! whether the memory is mutable, etc.).
-//!
-//! Categorization effectively transforms all of our expressions into
-//! expressions of the following forms (the actual enum has many more
-//! possibilities, naturally, but they are all variants of these base
-//! forms):
-//!
-//!     E = rvalue    // some computed rvalue
-//!       | x         // address of a local variable or argument
-//!       | *E        // deref of a ptr
-//!       | E.comp    // access to an interior component
-//!
-//! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
-//! address where the result is to be found. If Expr is a place, then this
-//! is the address of the place. If `Expr` is an rvalue, this is the address of
-//! some temporary spot in memory where the result is stored.
-//!
-//! Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
-//! as follows:
-//!
-//! - `cat`: what kind of expression was this? This is a subset of the
-//!   full expression forms which only includes those that we care about
-//!   for the purpose of the analysis.
-//! - `mutbl`: mutability of the address `A`.
-//! - `ty`: the type of data found at the address `A`.
-//!
-//! The resulting categorization tree differs somewhat from the expressions
-//! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
-//! decomposed into two operations: a dereference to reach the array data and
-//! then an index to jump forward to the relevant item.
-//!
-//! ## By-reference upvars
-//!
-//! One part of the codegen which may be non-obvious is that we translate
-//! closure upvars into the dereference of a borrowed pointer; this more closely
-//! resembles the runtime codegen. So, for example, if we had:
-//!
-//!     let mut x = 3;
-//!     let y = 5;
-//!     let inc = || x += y;
-//!
-//! Then when we categorize `x` (*within* the closure) we would yield a
-//! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
-//! tied to `x`. The type of `x'` will be a borrowed pointer.
-
-#![allow(non_camel_case_types)]
-
-pub use self::PointerKind::*;
-pub use self::InteriorKind::*;
-pub use self::MutabilityCategory::*;
-pub use self::AliasableReason::*;
-pub use self::Note::*;
-
-use self::Aliasability::*;
-
-use crate::middle::region;
-use crate::hir::def_id::{DefId, LocalDefId};
-use crate::hir::Node;
-use crate::infer::InferCtxt;
-use crate::hir::def::{CtorOf, Res, DefKind, CtorKind};
-use crate::ty::adjustment;
-use crate::ty::{self, DefIdTree, Ty, TyCtxt};
-use crate::ty::fold::TypeFoldable;
-
-use crate::hir::{Mutability, PatKind};
-use crate::hir::pat_util::EnumerateAndAdjustIterator;
-use crate::hir;
-use syntax::ast::{self, Name};
-use syntax::symbol::sym;
-use syntax_pos::Span;
-
-use std::borrow::Cow;
-use std::fmt;
-use std::hash::{Hash, Hasher};
-use rustc_data_structures::fx::FxIndexMap;
-use std::rc::Rc;
-
-#[derive(Clone, Debug, PartialEq)]
-pub enum Categorization<'tcx> {
-    Rvalue,                              // temporary val
-    ThreadLocal,                         // value that cannot move, but still restricted in scope
-    StaticItem,
-    Upvar(Upvar),                        // upvar referenced by closure env
-    Local(hir::HirId),                   // local variable
-    Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
-    Interior(cmt<'tcx>, InteriorKind),   // something interior: field, tuple, etc
-    Downcast(cmt<'tcx>, DefId),          // selects a particular enum variant (*1)
-
-    // (*1) downcast is only required if the enum has more than one variant
-}
-
-// Represents any kind of upvar
-#[derive(Clone, Copy, PartialEq)]
-pub struct Upvar {
-    pub id: ty::UpvarId,
-    pub kind: ty::ClosureKind
-}
-
-// different kinds of pointers:
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum PointerKind<'tcx> {
-    /// `Box<T>`
-    Unique,
-
-    /// `&T`
-    BorrowedPtr(ty::BorrowKind, ty::Region<'tcx>),
-
-    /// `*T`
-    UnsafePtr(hir::Mutability),
-}
-
-// We use the term "interior" to mean "something reachable from the
-// base without a pointer dereference", e.g., a field
-#[derive(Clone, PartialEq)]
-pub enum InteriorKind {
-    InteriorField(FieldIndex),
-    InteriorElement(InteriorOffsetKind),
-}
-
-// Contains index of a field that is actually used for loan path comparisons and
-// string representation of the field that should be used only for diagnostics.
-#[derive(Clone, Copy, Eq)]
-pub struct FieldIndex(pub usize, pub Name);
-
-impl PartialEq for FieldIndex {
-    fn eq(&self, rhs: &Self) -> bool {
-        self.0 == rhs.0
-    }
-}
-
-impl Hash for FieldIndex {
-    fn hash<H: Hasher>(&self, h: &mut H) {
-        self.0.hash(h)
-    }
-}
-
-#[derive(Clone, PartialEq)]
-pub enum InteriorOffsetKind {
-    Index,   // e.g., `array_expr[index_expr]`
-    Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }`
-}
-
-#[derive(Clone, Copy, PartialEq, Debug)]
-pub enum MutabilityCategory {
-    McImmutable, // Immutable.
-    McDeclared,  // Directly declared as mutable.
-    McInherited, // Inherited from the fact that owner is mutable.
-}
-
-// A note about the provenance of a `cmt`.  This is used for
-// special-case handling of upvars such as mutability inference.
-// Upvar categorization can generate a variable number of nested
-// derefs.  The note allows detecting them without deep pattern
-// matching on the categorization.
-#[derive(Clone, Copy, PartialEq, Debug)]
-pub enum Note {
-    NoteClosureEnv(ty::UpvarId), // Deref through closure env
-    NoteUpvarRef(ty::UpvarId),   // Deref through by-ref upvar
-    NoteIndex,                   // Deref as part of desugaring `x[]` into its two components
-    NoteNone                     // Nothing special
-}
-
-// `cmt`: "Category, Mutability, and Type".
-//
-// a complete categorization of a value indicating where it originated
-// and how it is located, as well as the mutability of the memory in
-// which the value is stored.
-//
-// *WARNING* The field `cmt.type` is NOT necessarily the same as the
-// result of `node_type(cmt.id)`.
-//
-// (FIXME: rewrite the following comment given that `@x` managed
-// pointers have been obsolete for quite some time.)
-//
-// This is because the `id` is always the `id` of the node producing the
-// type; in an expression like `*x`, the type of this deref node is the
-// deref'd type (`T`), but in a pattern like `@x`, the `@x` pattern is
-// again a dereference, but its type is the type *before* the
-// dereference (`@T`). So use `cmt.ty` to find the type of the value in
-// a consistent fashion. For more details, see the method `cat_pattern`
-#[derive(Clone, Debug, PartialEq)]
-pub struct cmt_<'tcx> {
-    pub hir_id: hir::HirId,        // HIR id of expr/pat producing this value
-    pub span: Span,                // span of same expr/pat
-    pub cat: Categorization<'tcx>, // categorization of expr
-    pub mutbl: MutabilityCategory, // mutability of expr as place
-    pub ty: Ty<'tcx>,              // type of the expr (*see WARNING above*)
-    pub note: Note,                // Note about the provenance of this cmt
-}
-
-pub type cmt<'tcx> = Rc<cmt_<'tcx>>;
-
-pub trait HirNode {
-    fn hir_id(&self) -> hir::HirId;
-    fn span(&self) -> Span;
-}
-
-impl HirNode for hir::Expr {
-    fn hir_id(&self) -> hir::HirId { self.hir_id }
-    fn span(&self) -> Span { self.span }
-}
-
-impl HirNode for hir::Pat {
-    fn hir_id(&self) -> hir::HirId { self.hir_id }
-    fn span(&self) -> Span { self.span }
-}
-
-#[derive(Clone)]
-pub struct MemCategorizationContext<'a, 'tcx> {
-    pub tcx: TyCtxt<'tcx>,
-    param_env: ty::ParamEnv<'tcx>,
-    pub body_owner: DefId,
-    pub upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
-    pub region_scope_tree: &'a region::ScopeTree,
-    pub tables: &'a ty::TypeckTables<'tcx>,
-    infcx: Option<&'a InferCtxt<'a, 'tcx>>,
-}
-
-pub type McResult<T> = Result<T, ()>;
-
-impl MutabilityCategory {
-    pub fn from_mutbl(m: hir::Mutability) -> MutabilityCategory {
-        let ret = match m {
-            Mutability::Immutable => McImmutable,
-            Mutability::Mutable => McDeclared
-        };
-        debug!("MutabilityCategory::{}({:?}) => {:?}",
-               "from_mutbl", m, ret);
-        ret
-    }
-
-    pub fn from_borrow_kind(borrow_kind: ty::BorrowKind) -> MutabilityCategory {
-        let ret = match borrow_kind {
-            ty::ImmBorrow => McImmutable,
-            ty::UniqueImmBorrow => McImmutable,
-            ty::MutBorrow => McDeclared,
-        };
-        debug!("MutabilityCategory::{}({:?}) => {:?}",
-               "from_borrow_kind", borrow_kind, ret);
-        ret
-    }
-
-    fn from_pointer_kind(base_mutbl: MutabilityCategory,
-                         ptr: PointerKind<'_>) -> MutabilityCategory {
-        let ret = match ptr {
-            Unique => {
-                base_mutbl.inherit()
-            }
-            BorrowedPtr(borrow_kind, _) => {
-                MutabilityCategory::from_borrow_kind(borrow_kind)
-            }
-            UnsafePtr(m) => {
-                MutabilityCategory::from_mutbl(m)
-            }
-        };
-        debug!("MutabilityCategory::{}({:?}, {:?}) => {:?}",
-               "from_pointer_kind", base_mutbl, ptr, ret);
-        ret
-    }
-
-    fn from_local(
-        tcx: TyCtxt<'_>,
-        tables: &ty::TypeckTables<'_>,
-        id: hir::HirId,
-    ) -> MutabilityCategory {
-        let ret = match tcx.hir().get(id) {
-            Node::Binding(p) => match p.kind {
-                PatKind::Binding(..) => {
-                    let bm = *tables.pat_binding_modes()
-                                    .get(p.hir_id)
-                                    .expect("missing binding mode");
-                    if bm == ty::BindByValue(Mutability::Mutable) {
-                        McDeclared
-                    } else {
-                        McImmutable
-                    }
-                }
-                _ => span_bug!(p.span, "expected identifier pattern")
-            },
-            _ => span_bug!(tcx.hir().span(id), "expected identifier pattern")
-        };
-        debug!("MutabilityCategory::{}(tcx, id={:?}) => {:?}",
-               "from_local", id, ret);
-        ret
-    }
-
-    pub fn inherit(&self) -> MutabilityCategory {
-        let ret = match *self {
-            McImmutable => McImmutable,
-            McDeclared => McInherited,
-            McInherited => McInherited,
-        };
-        debug!("{:?}.inherit() => {:?}", self, ret);
-        ret
-    }
-
-    pub fn is_mutable(&self) -> bool {
-        let ret = match *self {
-            McImmutable => false,
-            McInherited => true,
-            McDeclared => true,
-        };
-        debug!("{:?}.is_mutable() => {:?}", self, ret);
-        ret
-    }
-
-    pub fn is_immutable(&self) -> bool {
-        let ret = match *self {
-            McImmutable => true,
-            McDeclared | McInherited => false
-        };
-        debug!("{:?}.is_immutable() => {:?}", self, ret);
-        ret
-    }
-
-    pub fn to_user_str(&self) -> &'static str {
-        match *self {
-            McDeclared | McInherited => "mutable",
-            McImmutable => "immutable",
-        }
-    }
-}
-
-impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
-    pub fn new(
-        tcx: TyCtxt<'tcx>,
-        param_env: ty::ParamEnv<'tcx>,
-        body_owner: DefId,
-        region_scope_tree: &'a region::ScopeTree,
-        tables: &'a ty::TypeckTables<'tcx>,
-    ) -> MemCategorizationContext<'a, 'tcx> {
-        MemCategorizationContext {
-            tcx,
-            body_owner,
-            upvars: tcx.upvars(body_owner),
-            region_scope_tree,
-            tables,
-            infcx: None,
-            param_env,
-        }
-    }
-}
-
-impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
-    /// Creates a `MemCategorizationContext` during type inference.
-    /// This is used during upvar analysis and a few other places.
-    /// Because the typeck tables are not yet complete, the results
-    /// from the analysis must be used with caution:
-    ///
-    /// - rvalue promotions are not known, so the lifetimes of
-    ///   temporaries may be overly conservative;
-    /// - similarly, as the results of upvar analysis are not yet
-    ///   known, the results around upvar accesses may be incorrect.
-    pub fn with_infer(
-        infcx: &'a InferCtxt<'a, 'tcx>,
-        param_env: ty::ParamEnv<'tcx>,
-        body_owner: DefId,
-        region_scope_tree: &'a region::ScopeTree,
-        tables: &'a ty::TypeckTables<'tcx>,
-    ) -> MemCategorizationContext<'a, 'tcx> {
-        let tcx = infcx.tcx;
-
-        MemCategorizationContext {
-            tcx,
-            body_owner,
-            upvars: tcx.upvars(body_owner),
-            region_scope_tree,
-            tables,
-            infcx: Some(infcx),
-            param_env,
-        }
-    }
-
-    pub fn type_is_copy_modulo_regions(
-        &self,
-        param_env: ty::ParamEnv<'tcx>,
-        ty: Ty<'tcx>,
-        span: Span,
-    ) -> bool {
-        self.infcx.map(|infcx| infcx.type_is_copy_modulo_regions(param_env, ty, span))
-            .or_else(|| {
-                if (param_env, ty).has_local_value() {
-                    None
-                } else {
-                    Some(ty.is_copy_modulo_regions(self.tcx, param_env, span))
-                }
-            })
-            .unwrap_or(true)
-    }
-
-    fn resolve_vars_if_possible<T>(&self, value: &T) -> T
-        where T: TypeFoldable<'tcx>
-    {
-        self.infcx.map(|infcx| infcx.resolve_vars_if_possible(value))
-            .unwrap_or_else(|| value.clone())
-    }
-
-    fn is_tainted_by_errors(&self) -> bool {
-        self.infcx.map_or(false, |infcx| infcx.is_tainted_by_errors())
-    }
-
-    fn resolve_type_vars_or_error(&self,
-                                  id: hir::HirId,
-                                  ty: Option<Ty<'tcx>>)
-                                  -> McResult<Ty<'tcx>> {
-        match ty {
-            Some(ty) => {
-                let ty = self.resolve_vars_if_possible(&ty);
-                if ty.references_error() || ty.is_ty_var() {
-                    debug!("resolve_type_vars_or_error: error from {:?}", ty);
-                    Err(())
-                } else {
-                    Ok(ty)
-                }
-            }
-            // FIXME
-            None if self.is_tainted_by_errors() => Err(()),
-            None => {
-                bug!("no type for node {}: {} in mem_categorization",
-                     id, self.tcx.hir().node_to_string(id));
-            }
-        }
-    }
-
-    pub fn node_ty(&self,
-                   hir_id: hir::HirId)
-                   -> McResult<Ty<'tcx>> {
-        self.resolve_type_vars_or_error(hir_id,
-                                        self.tables.node_type_opt(hir_id))
-    }
-
-    pub fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
-        self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
-    }
-
-    pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
-        self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
-    }
-
-    /// Returns the type of value that this pattern matches against.
-    /// Some non-obvious cases:
-    ///
-    /// - a `ref x` binding matches against a value of type `T` and gives
-    ///   `x` the type `&T`; we return `T`.
-    /// - a pattern with implicit derefs (thanks to default binding
-    ///   modes #42640) may look like `Some(x)` but in fact have
-    ///   implicit deref patterns attached (e.g., it is really
-    ///   `&Some(x)`). In that case, we return the "outermost" type
-    ///   (e.g., `&Option<T>).
-    pub fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
-        // Check for implicit `&` types wrapping the pattern; note
-        // that these are never attached to binding patterns, so
-        // actually this is somewhat "disjoint" from the code below
-        // that aims to account for `ref x`.
-        if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
-            if let Some(first_ty) = vec.first() {
-                debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
-                return Ok(first_ty);
-            }
-        }
-
-        self.pat_ty_unadjusted(pat)
-    }
-
-
-    /// Like `pat_ty`, but ignores implicit `&` patterns.
-    fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
-        let base_ty = self.node_ty(pat.hir_id)?;
-        debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
-
-        // This code detects whether we are looking at a `ref x`,
-        // and if so, figures out what the type *being borrowed* is.
-        let ret_ty = match pat.kind {
-            PatKind::Binding(..) => {
-                let bm = *self.tables
-                              .pat_binding_modes()
-                              .get(pat.hir_id)
-                              .expect("missing binding mode");
-
-                if let ty::BindByReference(_) = bm {
-                    // a bind-by-ref means that the base_ty will be the type of the ident itself,
-                    // but what we want here is the type of the underlying value being borrowed.
-                    // So peel off one-level, turning the &T into T.
-                    match base_ty.builtin_deref(false) {
-                        Some(t) => t.ty,
-                        None => {
-                            debug!("By-ref binding of non-derefable type {:?}", base_ty);
-                            return Err(());
-                        }
-                    }
-                } else {
-                    base_ty
-                }
-            }
-            _ => base_ty,
-        };
-        debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
-
-        Ok(ret_ty)
-    }
-
-    pub fn cat_expr(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
-        // This recursion helper avoids going through *too many*
-        // adjustments, since *only* non-overloaded deref recurses.
-        fn helper<'a, 'tcx>(
-            mc: &MemCategorizationContext<'a, 'tcx>,
-            expr: &hir::Expr,
-            adjustments: &[adjustment::Adjustment<'tcx>],
-        ) -> McResult<cmt_<'tcx>> {
-            match adjustments.split_last() {
-                None => mc.cat_expr_unadjusted(expr),
-                Some((adjustment, previous)) => {
-                    mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
-                }
-            }
-        }
-
-        helper(self, expr, self.tables.expr_adjustments(expr))
-    }
-
-    pub fn cat_expr_adjusted(&self, expr: &hir::Expr,
-                             previous: cmt_<'tcx>,
-                             adjustment: &adjustment::Adjustment<'tcx>)
-                             -> McResult<cmt_<'tcx>> {
-        self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
-    }
-
-    fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
-                                 previous: F,
-                                 adjustment: &adjustment::Adjustment<'tcx>)
-                                 -> McResult<cmt_<'tcx>>
-        where F: FnOnce() -> McResult<cmt_<'tcx>>
-    {
-        debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
-        let target = self.resolve_vars_if_possible(&adjustment.target);
-        match adjustment.kind {
-            adjustment::Adjust::Deref(overloaded) => {
-                // Equivalent to *expr or something similar.
-                let base = Rc::new(if let Some(deref) = overloaded {
-                    let ref_ty = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
-                        ty: target,
-                        mutbl: deref.mutbl,
-                    });
-                    self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty)
-                } else {
-                    previous()?
-                });
-                self.cat_deref(expr, base, NoteNone)
-            }
-
-            adjustment::Adjust::NeverToAny |
-            adjustment::Adjust::Pointer(_) |
-            adjustment::Adjust::Borrow(_) => {
-                // Result is an rvalue.
-                Ok(self.cat_rvalue_node(expr.hir_id, expr.span, target))
-            }
-        }
-    }
-
-    pub fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<cmt_<'tcx>> {
-        debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
-
-        let expr_ty = self.expr_ty(expr)?;
-        match expr.kind {
-            hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
-                if self.tables.is_method_call(expr) {
-                    self.cat_overloaded_place(expr, e_base, NoteNone)
-                } else {
-                    let base_cmt = Rc::new(self.cat_expr(&e_base)?);
-                    self.cat_deref(expr, base_cmt, NoteNone)
-                }
-            }
-
-            hir::ExprKind::Field(ref base, f_ident) => {
-                let base_cmt = Rc::new(self.cat_expr(&base)?);
-                debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
-                       expr.hir_id,
-                       expr,
-                       base_cmt);
-                let f_index = self.tcx.field_index(expr.hir_id, self.tables);
-                Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
-            }
-
-            hir::ExprKind::Index(ref base, _) => {
-                if self.tables.is_method_call(expr) {
-                    // If this is an index implemented by a method call, then it
-                    // will include an implicit deref of the result.
-                    // The call to index() returns a `&T` value, which
-                    // is an rvalue. That is what we will be
-                    // dereferencing.
-                    self.cat_overloaded_place(expr, base, NoteIndex)
-                } else {
-                    let base_cmt = Rc::new(self.cat_expr(&base)?);
-                    self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
-                }
-            }
-
-            hir::ExprKind::Path(ref qpath) => {
-                let res = self.tables.qpath_res(qpath, expr.hir_id);
-                self.cat_res(expr.hir_id, expr.span, expr_ty, res)
-            }
-
-            hir::ExprKind::Type(ref e, _) => {
-                self.cat_expr(&e)
-            }
-
-            hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
-            hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
-            hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
-            hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
-            hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) |
-            hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) |
-            hir::ExprKind::Binary(..) |
-            hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
-            hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
-            hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
-            hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Err => {
-                Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
-            }
-        }
-    }
-
-    pub fn cat_res(&self,
-                   hir_id: hir::HirId,
-                   span: Span,
-                   expr_ty: Ty<'tcx>,
-                   res: Res)
-                   -> McResult<cmt_<'tcx>> {
-        debug!("cat_res: id={:?} expr={:?} def={:?}",
-               hir_id, expr_ty, res);
-
-        match res {
-            Res::Def(DefKind::Ctor(..), _)
-            | Res::Def(DefKind::Const, _)
-            | Res::Def(DefKind::ConstParam, _)
-            | Res::Def(DefKind::AssocConst, _)
-            | Res::Def(DefKind::Fn, _)
-            | Res::Def(DefKind::Method, _)
-            | Res::SelfCtor(..) => {
-                Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
-            }
-
-            Res::Def(DefKind::Static, def_id) => {
-                // `#[thread_local]` statics may not outlive the current function, but
-                // they also cannot be moved out of.
-                let is_thread_local = self.tcx.get_attrs(def_id)[..]
-                    .iter()
-                    .any(|attr| attr.check_name(sym::thread_local));
-
-                let cat = if is_thread_local {
-                    Categorization::ThreadLocal
-                } else {
-                    Categorization::StaticItem
-                };
-
-                Ok(cmt_ {
-                    hir_id,
-                    span,
-                    cat,
-                    mutbl: match self.tcx.static_mutability(def_id).unwrap() {
-                        Mutability::Immutable => McImmutable,
-                        Mutability::Mutable => McDeclared,
-                    },
-                    ty:expr_ty,
-                    note: NoteNone
-                })
-            }
-
-            Res::Local(var_id) => {
-                if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
-                    self.cat_upvar(hir_id, span, var_id)
-                } else {
-                    Ok(cmt_ {
-                        hir_id,
-                        span,
-                        cat: Categorization::Local(var_id),
-                        mutbl: MutabilityCategory::from_local(self.tcx, self.tables, var_id),
-                        ty: expr_ty,
-                        note: NoteNone
-                    })
-                }
-            }
-
-            def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
-        }
-    }
-
-    // Categorize an upvar, complete with invisible derefs of closure
-    // environment and upvar reference as appropriate.
-    fn cat_upvar(
-        &self,
-        hir_id: hir::HirId,
-        span: Span,
-        var_id: hir::HirId,
-    ) -> McResult<cmt_<'tcx>> {
-        // An upvar can have up to 3 components. We translate first to a
-        // `Categorization::Upvar`, which is itself a fiction -- it represents the reference to the
-        // field from the environment.
-        //
-        // `Categorization::Upvar`.  Next, we add a deref through the implicit
-        // environment pointer with an anonymous free region 'env and
-        // appropriate borrow kind for closure kinds that take self by
-        // reference.  Finally, if the upvar was captured
-        // by-reference, we add a deref through that reference.  The
-        // region of this reference is an inference variable 'up that
-        // was previously generated and recorded in the upvar borrow
-        // map.  The borrow kind bk is inferred by based on how the
-        // upvar is used.
-        //
-        // This results in the following table for concrete closure
-        // types:
-        //
-        //                | move                 | ref
-        // ---------------+----------------------+-------------------------------
-        // Fn             | copied -> &'env      | upvar -> &'env -> &'up bk
-        // FnMut          | copied -> &'env mut  | upvar -> &'env mut -> &'up bk
-        // FnOnce         | copied               | upvar -> &'up bk
-
-        let closure_expr_def_id = self.body_owner;
-        let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(
-            LocalDefId::from_def_id(closure_expr_def_id),
-        );
-        let ty = self.node_ty(fn_hir_id)?;
-        let kind = match ty.kind {
-            ty::Generator(..) => ty::ClosureKind::FnOnce,
-            ty::Closure(closure_def_id, substs) => {
-                match self.infcx {
-                    // During upvar inference we may not know the
-                    // closure kind, just use the LATTICE_BOTTOM value.
-                    Some(infcx) =>
-                        infcx.closure_kind(
-                            closure_def_id,
-                            substs
-                        ).unwrap_or(ty::ClosureKind::LATTICE_BOTTOM),
-
-                    None =>
-                        substs.as_closure().kind(closure_def_id, self.tcx),
-                }
-            }
-            _ => span_bug!(span, "unexpected type for fn in mem_categorization: {:?}", ty),
-        };
-
-        let upvar_id = ty::UpvarId {
-            var_path: ty::UpvarPath { hir_id: var_id },
-            closure_expr_id: closure_expr_def_id.to_local(),
-        };
-
-        let var_ty = self.node_ty(var_id)?;
-
-        // Mutability of original variable itself
-        let var_mutbl = MutabilityCategory::from_local(self.tcx, self.tables, var_id);
-
-        // Construct the upvar. This represents access to the field
-        // from the environment (perhaps we should eventually desugar
-        // this field further, but it will do for now).
-        let cmt_result = cmt_ {
-            hir_id,
-            span,
-            cat: Categorization::Upvar(Upvar {id: upvar_id, kind: kind}),
-            mutbl: var_mutbl,
-            ty: var_ty,
-            note: NoteNone
-        };
-
-        // If this is a `FnMut` or `Fn` closure, then the above is
-        // conceptually a `&mut` or `&` reference, so we have to add a
-        // deref.
-        let cmt_result = match kind {
-            ty::ClosureKind::FnOnce => {
-                cmt_result
-            }
-            ty::ClosureKind::FnMut => {
-                self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::MutBorrow, cmt_result)
-            }
-            ty::ClosureKind::Fn => {
-                self.env_deref(hir_id, span, upvar_id, var_mutbl, ty::ImmBorrow, cmt_result)
-            }
-        };
-
-        // If this is a by-ref capture, then the upvar we loaded is
-        // actually a reference, so we have to add an implicit deref
-        // for that.
-        let upvar_capture = self.tables.upvar_capture(upvar_id);
-        let cmt_result = match upvar_capture {
-            ty::UpvarCapture::ByValue => {
-                cmt_result
-            }
-            ty::UpvarCapture::ByRef(upvar_borrow) => {
-                let ptr = BorrowedPtr(upvar_borrow.kind, upvar_borrow.region);
-                cmt_ {
-                    hir_id,
-                    span,
-                    cat: Categorization::Deref(Rc::new(cmt_result), ptr),
-                    mutbl: MutabilityCategory::from_borrow_kind(upvar_borrow.kind),
-                    ty: var_ty,
-                    note: NoteUpvarRef(upvar_id)
-                }
-            }
-        };
-
-        let ret = cmt_result;
-        debug!("cat_upvar ret={:?}", ret);
-        Ok(ret)
-    }
-
-    fn env_deref(&self,
-                 hir_id: hir::HirId,
-                 span: Span,
-                 upvar_id: ty::UpvarId,
-                 upvar_mutbl: MutabilityCategory,
-                 env_borrow_kind: ty::BorrowKind,
-                 cmt_result: cmt_<'tcx>)
-                 -> cmt_<'tcx>
-    {
-        // Region of environment pointer
-        let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
-            // The environment of a closure is guaranteed to
-            // outlive any bindings introduced in the body of the
-            // closure itself.
-            scope: upvar_id.closure_expr_id.to_def_id(),
-            bound_region: ty::BrEnv
-        }));
-
-        let env_ptr = BorrowedPtr(env_borrow_kind, env_region);
-
-        let var_ty = cmt_result.ty;
-
-        // We need to add the env deref.  This means
-        // that the above is actually immutable and
-        // has a ref type.  However, nothing should
-        // actually look at the type, so we can get
-        // away with stuffing a `Error` in there
-        // instead of bothering to construct a proper
-        // one.
-        let cmt_result = cmt_ {
-            mutbl: McImmutable,
-            ty: self.tcx.types.err,
-            ..cmt_result
-        };
-
-        let mut deref_mutbl = MutabilityCategory::from_borrow_kind(env_borrow_kind);
-
-        // Issue #18335. If variable is declared as immutable, override the
-        // mutability from the environment and substitute an `&T` anyway.
-        match upvar_mutbl {
-            McImmutable => { deref_mutbl = McImmutable; }
-            McDeclared | McInherited => { }
-        }
-
-        let ret = cmt_ {
-            hir_id,
-            span,
-            cat: Categorization::Deref(Rc::new(cmt_result), env_ptr),
-            mutbl: deref_mutbl,
-            ty: var_ty,
-            note: NoteClosureEnv(upvar_id)
-        };
-
-        debug!("env_deref ret {:?}", ret);
-
-        ret
-    }
-
-    pub fn cat_rvalue_node(&self,
-                           hir_id: hir::HirId,
-                           span: Span,
-                           expr_ty: Ty<'tcx>)
-                           -> cmt_<'tcx> {
-        debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
-               hir_id, span, expr_ty);
-
-        let ret = self.cat_rvalue(hir_id, span, expr_ty);
-        debug!("cat_rvalue_node ret {:?}", ret);
-        ret
-    }
-
-    pub fn cat_rvalue(&self,
-                      cmt_hir_id: hir::HirId,
-                      span: Span,
-                      expr_ty: Ty<'tcx>) -> cmt_<'tcx> {
-        let ret = cmt_ {
-            hir_id: cmt_hir_id,
-            span:span,
-            cat:Categorization::Rvalue,
-            mutbl:McDeclared,
-            ty:expr_ty,
-            note: NoteNone
-        };
-        debug!("cat_rvalue ret {:?}", ret);
-        ret
-    }
-
-    pub fn cat_field<N: HirNode>(&self,
-                                 node: &N,
-                                 base_cmt: cmt<'tcx>,
-                                 f_index: usize,
-                                 f_ident: ast::Ident,
-                                 f_ty: Ty<'tcx>)
-                                 -> cmt_<'tcx> {
-        let ret = cmt_ {
-            hir_id: node.hir_id(),
-            span: node.span(),
-            mutbl: base_cmt.mutbl.inherit(),
-            cat: Categorization::Interior(base_cmt,
-                                          InteriorField(FieldIndex(f_index, f_ident.name))),
-            ty: f_ty,
-            note: NoteNone
-        };
-        debug!("cat_field ret {:?}", ret);
-        ret
-    }
-
-    fn cat_overloaded_place(
-        &self,
-        expr: &hir::Expr,
-        base: &hir::Expr,
-        note: Note,
-    ) -> McResult<cmt_<'tcx>> {
-        debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
-               expr,
-               base,
-               note);
-
-        // Reconstruct the output assuming it's a reference with the
-        // same region and mutability as the receiver. This holds for
-        // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
-        let place_ty = self.expr_ty(expr)?;
-        let base_ty = self.expr_ty_adjusted(base)?;
-
-        let (region, mutbl) = match base_ty.kind {
-            ty::Ref(region, _, mutbl) => (region, mutbl),
-            _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
-        };
-        let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
-            ty: place_ty,
-            mutbl,
-        });
-
-        let base_cmt = Rc::new(self.cat_rvalue_node(expr.hir_id, expr.span, ref_ty));
-        self.cat_deref(expr, base_cmt, note)
-    }
-
-    pub fn cat_deref(
-        &self,
-        node: &impl HirNode,
-        base_cmt: cmt<'tcx>,
-        note: Note,
-    ) -> McResult<cmt_<'tcx>> {
-        debug!("cat_deref: base_cmt={:?}", base_cmt);
-
-        let base_cmt_ty = base_cmt.ty;
-        let deref_ty = match base_cmt_ty.builtin_deref(true) {
-            Some(mt) => mt.ty,
-            None => {
-                debug!("explicit deref of non-derefable type: {:?}", base_cmt_ty);
-                return Err(());
-            }
-        };
-
-        let ptr = match base_cmt.ty.kind {
-            ty::Adt(def, ..) if def.is_box() => Unique,
-            ty::RawPtr(ref mt) => UnsafePtr(mt.mutbl),
-            ty::Ref(r, _, mutbl) => {
-                let bk = ty::BorrowKind::from_mutbl(mutbl);
-                BorrowedPtr(bk, r)
-            }
-            _ => bug!("unexpected type in cat_deref: {:?}", base_cmt.ty)
-        };
-        let ret = cmt_ {
-            hir_id: node.hir_id(),
-            span: node.span(),
-            // For unique ptrs, we inherit mutability from the owning reference.
-            mutbl: MutabilityCategory::from_pointer_kind(base_cmt.mutbl, ptr),
-            cat: Categorization::Deref(base_cmt, ptr),
-            ty: deref_ty,
-            note: note,
-        };
-        debug!("cat_deref ret {:?}", ret);
-        Ok(ret)
-    }
-
-    fn cat_index<N: HirNode>(&self,
-                             elt: &N,
-                             base_cmt: cmt<'tcx>,
-                             element_ty: Ty<'tcx>,
-                             context: InteriorOffsetKind)
-                             -> McResult<cmt_<'tcx>> {
-        //! Creates a cmt for an indexing operation (`[]`).
-        //!
-        //! One subtle aspect of indexing that may not be
-        //! immediately obvious: for anything other than a fixed-length
-        //! vector, an operation like `x[y]` actually consists of two
-        //! disjoint (from the point of view of borrowck) operations.
-        //! The first is a deref of `x` to create a pointer `p` that points
-        //! at the first element in the array. The second operation is
-        //! an index which adds `y*sizeof(T)` to `p` to obtain the
-        //! pointer to `x[y]`. `cat_index` will produce a resulting
-        //! cmt containing both this deref and the indexing,
-        //! presuming that `base_cmt` is not of fixed-length type.
-        //!
-        //! # Parameters
-        //! - `elt`: the HIR node being indexed
-        //! - `base_cmt`: the cmt of `elt`
-
-        let interior_elem = InteriorElement(context);
-        let ret = self.cat_imm_interior(elt, base_cmt, element_ty, interior_elem);
-        debug!("cat_index ret {:?}", ret);
-        return Ok(ret);
-    }
-
-    pub fn cat_imm_interior<N:HirNode>(&self,
-                                       node: &N,
-                                       base_cmt: cmt<'tcx>,
-                                       interior_ty: Ty<'tcx>,
-                                       interior: InteriorKind)
-                                       -> cmt_<'tcx> {
-        let ret = cmt_ {
-            hir_id: node.hir_id(),
-            span: node.span(),
-            mutbl: base_cmt.mutbl.inherit(),
-            cat: Categorization::Interior(base_cmt, interior),
-            ty: interior_ty,
-            note: NoteNone
-        };
-        debug!("cat_imm_interior ret={:?}", ret);
-        ret
-    }
-
-    pub fn cat_downcast_if_needed<N:HirNode>(&self,
-                                             node: &N,
-                                             base_cmt: cmt<'tcx>,
-                                             variant_did: DefId)
-                                             -> cmt<'tcx> {
-        // univariant enums do not need downcasts
-        let base_did = self.tcx.parent(variant_did).unwrap();
-        if self.tcx.adt_def(base_did).variants.len() != 1 {
-            let base_ty = base_cmt.ty;
-            let ret = Rc::new(cmt_ {
-                hir_id: node.hir_id(),
-                span: node.span(),
-                mutbl: base_cmt.mutbl.inherit(),
-                cat: Categorization::Downcast(base_cmt, variant_did),
-                ty: base_ty,
-                note: NoteNone
-            });
-            debug!("cat_downcast ret={:?}", ret);
-            ret
-        } else {
-            debug!("cat_downcast univariant={:?}", base_cmt);
-            base_cmt
-        }
-    }
-
-    pub fn cat_pattern<F>(&self, cmt: cmt<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
-        where F: FnMut(cmt<'tcx>, &hir::Pat),
-    {
-        self.cat_pattern_(cmt, pat, &mut op)
-    }
-
-    // FIXME(#19596) This is a workaround, but there should be a better way to do this
-    fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
-        where F : FnMut(cmt<'tcx>, &hir::Pat)
-    {
-        // Here, `cmt` is the categorization for the value being
-        // matched and pat is the pattern it is being matched against.
-        //
-        // In general, the way that this works is that we walk down
-        // the pattern, constructing a cmt that represents the path
-        // that will be taken to reach the value being matched.
-        //
-        // When we encounter named bindings, we take the cmt that has
-        // been built up and pass it off to guarantee_valid() so that
-        // we can be sure that the binding will remain valid for the
-        // duration of the arm.
-        //
-        // (*2) There is subtlety concerning the correspondence between
-        // pattern ids and types as compared to *expression* ids and
-        // types. This is explained briefly. on the definition of the
-        // type `cmt`, so go off and read what it says there, then
-        // come back and I'll dive into a bit more detail here. :) OK,
-        // back?
-        //
-        // In general, the id of the cmt should be the node that
-        // "produces" the value---patterns aren't executable code
-        // exactly, but I consider them to "execute" when they match a
-        // value, and I consider them to produce the value that was
-        // matched. So if you have something like:
-        //
-        // (FIXME: `@@3` is not legal code anymore!)
-        //
-        //     let x = @@3;
-        //     match x {
-        //       @@y { ... }
-        //     }
-        //
-        // In this case, the cmt and the relevant ids would be:
-        //
-        //     CMT             Id                  Type of Id Type of cmt
-        //
-        //     local(x)->@->@
-        //     ^~~~~~~^        `x` from discr      @@int      @@int
-        //     ^~~~~~~~~~^     `@@y` pattern node  @@int      @int
-        //     ^~~~~~~~~~~~~^  `@y` pattern node   @int       int
-        //
-        // You can see that the types of the id and the cmt are in
-        // sync in the first line, because that id is actually the id
-        // of an expression. But once we get to pattern ids, the types
-        // step out of sync again. So you'll see below that we always
-        // get the type of the *subpattern* and use that.
-
-        debug!("cat_pattern(pat={:?}, cmt={:?})", pat, cmt);
-
-        // If (pattern) adjustments are active for this pattern, adjust the `cmt` correspondingly.
-        // `cmt`s are constructed differently from patterns. For example, in
-        //
-        // ```
-        // match foo {
-        //     &&Some(x, ) => { ... },
-        //     _ => { ... },
-        // }
-        // ```
-        //
-        // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
-        // corresponding `cmt` we start with a `cmt` for `foo`, and then, by traversing the
-        // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
-        //
-        // `&&Some(x,)` `cmt_foo`
-        //  `&Some(x,)` `deref { cmt_foo}`
-        //   `Some(x,)` `deref { deref { cmt_foo }}`
-        //        (x,)` `field0 { deref { deref { cmt_foo }}}` <- resulting cmt
-        //
-        // The above example has no adjustments. If the code were instead the (after adjustments,
-        // equivalent) version
-        //
-        // ```
-        // match foo {
-        //     Some(x, ) => { ... },
-        //     _ => { ... },
-        // }
-        // ```
-        //
-        // Then we see that to get the same result, we must start with `deref { deref { cmt_foo }}`
-        // instead of `cmt_foo` since the pattern is now `Some(x,)` and not `&&Some(x,)`, even
-        // though its assigned type is that of `&&Some(x,)`.
-        for _ in 0..self.tables
-                        .pat_adjustments()
-                        .get(pat.hir_id)
-                        .map(|v| v.len())
-                        .unwrap_or(0)
-        {
-            debug!("cat_pattern: applying adjustment to cmt={:?}", cmt);
-            cmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
-        }
-        let cmt = cmt; // lose mutability
-        debug!("cat_pattern: applied adjustment derefs to get cmt={:?}", cmt);
-
-        // Invoke the callback, but only now, after the `cmt` has adjusted.
-        //
-        // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
-        // case, the initial `cmt` will be that for `&Some(3)` and the pattern is `Some(x)`. We
-        // don't want to call `op` with these incompatible values. As written, what happens instead
-        // is that `op` is called with the adjusted cmt (that for `*&Some(3)`) and the pattern
-        // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
-        // result in the cmt `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
-        // that (where the `ref` on `x` is implied).
-        op(cmt.clone(), pat);
-
-        match pat.kind {
-            PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
-                let res = self.tables.qpath_res(qpath, pat.hir_id);
-                let (cmt, expected_len) = match res {
-                    Res::Err => {
-                        debug!("access to unresolvable pattern {:?}", pat);
-                        return Err(())
-                    }
-                    Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), variant_ctor_did) => {
-                        let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
-                        let enum_did = self.tcx.parent(variant_did).unwrap();
-                        (self.cat_downcast_if_needed(pat, cmt, variant_did),
-                         self.tcx.adt_def(enum_did)
-                             .variant_with_ctor_id(variant_ctor_did).fields.len())
-                    }
-                    Res::Def(DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), _)
-                    | Res::SelfCtor(..) => {
-                        let ty = self.pat_ty_unadjusted(&pat)?;
-                        match ty.kind {
-                            ty::Adt(adt_def, _) => {
-                                (cmt, adt_def.non_enum_variant().fields.len())
-                            }
-                            _ => {
-                                span_bug!(pat.span,
-                                          "tuple struct pattern unexpected type {:?}", ty);
-                            }
-                        }
-                    }
-                    def => {
-                        debug!(
-                            "tuple struct pattern didn't resolve to variant or struct {:?} at {:?}",
-                            def,
-                            pat.span,
-                        );
-                        self.tcx.sess.delay_span_bug(pat.span, &format!(
-                            "tuple struct pattern didn't resolve to variant or struct {:?}",
-                            def,
-                        ));
-                        return Err(());
-                    }
-                };
-
-                for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
-                    let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
-                    let interior = InteriorField(FieldIndex(i, sym::integer(i)));
-                    let subcmt = Rc::new(
-                        self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
-                    self.cat_pattern_(subcmt, &subpat, op)?;
-                }
-            }
-
-            PatKind::Struct(ref qpath, ref field_pats, _) => {
-                // {f1: p1, ..., fN: pN}
-                let res = self.tables.qpath_res(qpath, pat.hir_id);
-                let cmt = match res {
-                    Res::Err => {
-                        debug!("access to unresolvable pattern {:?}", pat);
-                        return Err(())
-                    }
-                    Res::Def(DefKind::Ctor(CtorOf::Variant, _), variant_ctor_did) => {
-                        let variant_did = self.tcx.parent(variant_ctor_did).unwrap();
-                        self.cat_downcast_if_needed(pat, cmt, variant_did)
-                    }
-                    Res::Def(DefKind::Variant, variant_did) => {
-                        self.cat_downcast_if_needed(pat, cmt, variant_did)
-                    }
-                    _ => cmt,
-                };
-
-                for fp in field_pats {
-                    let field_ty = self.pat_ty_adjusted(&fp.pat)?; // see (*2)
-                    let f_index = self.tcx.field_index(fp.hir_id, self.tables);
-                    let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
-                                                           fp.ident, field_ty));
-                    self.cat_pattern_(cmt_field, &fp.pat, op)?;
-                }
-            }
-
-            PatKind::Or(ref pats) => {
-                for pat in pats {
-                    self.cat_pattern_(cmt.clone(), &pat, op)?;
-                }
-            }
-
-            PatKind::Binding(.., Some(ref subpat)) => {
-                self.cat_pattern_(cmt, &subpat, op)?;
-            }
-
-            PatKind::Tuple(ref subpats, ddpos) => {
-                // (p1, ..., pN)
-                let ty = self.pat_ty_unadjusted(&pat)?;
-                let expected_len = match ty.kind {
-                    ty::Tuple(ref tys) => tys.len(),
-                    _ => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
-                };
-                for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
-                    let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
-                    let interior = InteriorField(FieldIndex(i, sym::integer(i)));
-                    let subcmt = Rc::new(
-                        self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
-                    self.cat_pattern_(subcmt, &subpat, op)?;
-                }
-            }
-
-            PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
-                // box p1, &p1, &mut p1.  we can ignore the mutability of
-                // PatKind::Ref since that information is already contained
-                // in the type.
-                let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
-                self.cat_pattern_(subcmt, &subpat, op)?;
-            }
-
-            PatKind::Slice(ref before, ref slice, ref after) => {
-                let element_ty = match cmt.ty.builtin_index() {
-                    Some(ty) => ty,
-                    None => {
-                        debug!("explicit index of non-indexable type {:?}", cmt);
-                        return Err(());
-                    }
-                };
-                let context = InteriorOffsetKind::Pattern;
-                let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
-                for before_pat in before {
-                    self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
-                }
-                if let Some(ref slice_pat) = *slice {
-                    self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
-                }
-                for after_pat in after {
-                    self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
-                }
-            }
-
-            PatKind::Path(_) | PatKind::Binding(.., None) |
-            PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
-                // always ok
-            }
-        }
-
-        Ok(())
-    }
-}
-
-#[derive(Clone, Debug)]
-pub enum Aliasability {
-    FreelyAliasable(AliasableReason),
-    NonAliasable,
-    ImmutableUnique(Box<Aliasability>),
-}
-
-#[derive(Copy, Clone, Debug)]
-pub enum AliasableReason {
-    AliasableBorrowed,
-    AliasableStatic,
-    AliasableStaticMut,
-}
-
-impl<'tcx> cmt_<'tcx> {
-    pub fn guarantor(&self) -> cmt_<'tcx> {
-        //! Returns `self` after stripping away any derefs or
-        //! interior content. The return value is basically the `cmt` which
-        //! determines how long the value in `self` remains live.
-
-        match self.cat {
-            Categorization::Rvalue |
-            Categorization::StaticItem |
-            Categorization::ThreadLocal |
-            Categorization::Local(..) |
-            Categorization::Deref(_, UnsafePtr(..)) |
-            Categorization::Deref(_, BorrowedPtr(..)) |
-            Categorization::Upvar(..) => {
-                (*self).clone()
-            }
-            Categorization::Downcast(ref b, _) |
-            Categorization::Interior(ref b, _) |
-            Categorization::Deref(ref b, Unique) => {
-                b.guarantor()
-            }
-        }
-    }
-
-    /// Returns `FreelyAliasable(_)` if this place represents a freely aliasable pointer type.
-    pub fn freely_aliasable(&self) -> Aliasability {
-        // Maybe non-obvious: copied upvars can only be considered
-        // non-aliasable in once closures, since any other kind can be
-        // aliased and eventually recused.
-
-        match self.cat {
-            Categorization::Deref(ref b, BorrowedPtr(ty::MutBorrow, _)) |
-            Categorization::Deref(ref b, BorrowedPtr(ty::UniqueImmBorrow, _)) |
-            Categorization::Deref(ref b, Unique) |
-            Categorization::Downcast(ref b, _) |
-            Categorization::Interior(ref b, _) => {
-                // Aliasability depends on base cmt
-                b.freely_aliasable()
-            }
-
-            Categorization::Rvalue |
-            Categorization::ThreadLocal |
-            Categorization::Local(..) |
-            Categorization::Upvar(..) |
-            Categorization::Deref(_, UnsafePtr(..)) => { // yes, it's aliasable, but...
-                NonAliasable
-            }
-
-            Categorization::StaticItem => {
-                if self.mutbl.is_mutable() {
-                    FreelyAliasable(AliasableStaticMut)
-                } else {
-                    FreelyAliasable(AliasableStatic)
-                }
-            }
-
-            Categorization::Deref(_, BorrowedPtr(ty::ImmBorrow, _)) => {
-                FreelyAliasable(AliasableBorrowed)
-            }
-        }
-    }
-
-    // Digs down through one or two layers of deref and grabs the
-    // Categorization of the cmt for the upvar if a note indicates there is
-    // one.
-    pub fn upvar_cat(&self) -> Option<&Categorization<'tcx>> {
-        match self.note {
-            NoteClosureEnv(..) | NoteUpvarRef(..) => {
-                Some(match self.cat {
-                    Categorization::Deref(ref inner, _) => {
-                        match inner.cat {
-                            Categorization::Deref(ref inner, _) => &inner.cat,
-                            Categorization::Upvar(..) => &inner.cat,
-                            _ => bug!()
-                        }
-                    }
-                    _ => bug!()
-                })
-            }
-            NoteIndex | NoteNone => None
-        }
-    }
-
-    pub fn descriptive_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
-        match self.cat {
-            Categorization::StaticItem => {
-                "static item".into()
-            }
-            Categorization::ThreadLocal => {
-                "thread-local static item".into()
-            }
-            Categorization::Rvalue => {
-                "non-place".into()
-            }
-            Categorization::Local(vid) => {
-                if tcx.hir().is_argument(vid) {
-                    "argument"
-                } else {
-                    "local variable"
-                }.into()
-            }
-            Categorization::Deref(_, pk) => {
-                match self.upvar_cat() {
-                    Some(&Categorization::Upvar(ref var)) => {
-                        var.to_string().into()
-                    }
-                    Some(_) => bug!(),
-                    None => {
-                        match pk {
-                            Unique => {
-                                "`Box` content"
-                            }
-                            UnsafePtr(..) => {
-                                "dereference of raw pointer"
-                            }
-                            BorrowedPtr(..) => {
-                                match self.note {
-                                    NoteIndex => "indexed content",
-                                    _ => "borrowed content"
-                                }
-                            }
-                        }.into()
-                    }
-                }
-            }
-            Categorization::Interior(_, InteriorField(..)) => {
-                "field".into()
-            }
-            Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
-                "indexed content".into()
-            }
-            Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
-                "pattern-bound indexed content".into()
-            }
-            Categorization::Upvar(ref var) => {
-                var.to_string().into()
-            }
-            Categorization::Downcast(ref cmt, _) => {
-                cmt.descriptive_string(tcx).into()
-            }
-        }
-    }
-}
-
-pub fn ptr_sigil(ptr: PointerKind<'_>) -> &'static str {
-    match ptr {
-        Unique => "Box",
-        BorrowedPtr(ty::ImmBorrow, _) => "&",
-        BorrowedPtr(ty::MutBorrow, _) => "&mut",
-        BorrowedPtr(ty::UniqueImmBorrow, _) => "&unique",
-        UnsafePtr(_) => "*",
-    }
-}
-
-impl fmt::Debug for InteriorKind {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        match *self {
-            InteriorField(FieldIndex(_, info)) => write!(f, "{}", info),
-            InteriorElement(..) => write!(f, "[]"),
-        }
-    }
-}
-
-impl fmt::Debug for Upvar {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "{:?}/{:?}", self.id, self.kind)
-    }
-}
-
-impl fmt::Display for Upvar {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        let kind = match self.kind {
-            ty::ClosureKind::Fn => "Fn",
-            ty::ClosureKind::FnMut => "FnMut",
-            ty::ClosureKind::FnOnce => "FnOnce",
-        };
-        write!(f, "captured outer variable in an `{}` closure", kind)
-    }
-}
diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs
index 411a47423c5..54aafe2114d 100644
--- a/src/librustc/middle/stability.rs
+++ b/src/librustc/middle/stability.rs
@@ -13,11 +13,12 @@ use crate::ty::query::Providers;
 use crate::middle::privacy::AccessLevels;
 use crate::session::{DiagnosticMessageId, Session};
 use errors::DiagnosticBuilder;
+use rustc_feature::GateIssue;
 use syntax::symbol::{Symbol, sym};
 use syntax_pos::{Span, MultiSpan};
 use syntax::ast::{Attribute, CRATE_NODE_ID};
 use syntax::errors::Applicability;
-use syntax::feature_gate::{GateIssue, emit_feature_err};
+use syntax::feature_gate::{feature_err, feature_err_issue};
 use syntax::attr::{self, Stability, Deprecation, RustcDeprecation};
 use crate::ty::{self, TyCtxt};
 use crate::util::nodemap::{FxHashSet, FxHashMap};
@@ -512,9 +513,8 @@ pub fn report_unstable(
         if is_soft {
             soft_handler(lint::builtin::SOFT_UNSTABLE, span, &msg)
         } else {
-            emit_feature_err(
-                &sess.parse_sess, feature, span, GateIssue::Library(issue), &msg
-            );
+            feature_err_issue(&sess.parse_sess, feature, span, GateIssue::Library(issue), &msg)
+                .emit();
         }
     }
 }
@@ -842,15 +842,19 @@ impl Visitor<'tcx> for Checker<'tcx> {
                 let ty = self.tcx.type_of(def_id);
 
                 if adt_def.has_dtor(self.tcx) {
-                    emit_feature_err(&self.tcx.sess.parse_sess,
-                                     sym::untagged_unions, item.span, GateIssue::Language,
-                                     "unions with `Drop` implementations are unstable");
+                    feature_err(
+                        &self.tcx.sess.parse_sess, sym::untagged_unions, item.span,
+                        "unions with `Drop` implementations are unstable"
+                    )
+                    .emit();
                 } else {
                     let param_env = self.tcx.param_env(def_id);
                     if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
-                        emit_feature_err(&self.tcx.sess.parse_sess,
-                                         sym::untagged_unions, item.span, GateIssue::Language,
-                                         "unions with non-`Copy` fields are unstable");
+                        feature_err(
+                            &self.tcx.sess.parse_sess, sym::untagged_unions, item.span,
+                            "unions with non-`Copy` fields are unstable"
+                        )
+                        .emit();
                     }
                 }
             }
diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs
index 7fb669314eb..557310650fa 100644
--- a/src/librustc/mir/interpret/error.rs
+++ b/src/librustc/mir/interpret/error.rs
@@ -13,8 +13,8 @@ use rustc_macros::HashStable;
 use rustc_target::spec::abi::Abi;
 use syntax_pos::{Pos, Span};
 use syntax::symbol::Symbol;
-
-use std::{fmt, env};
+use hir::GeneratorKind;
+use std::{fmt, env, any::Any};
 
 use rustc_error_codes::*;
 
@@ -44,14 +44,14 @@ CloneTypeFoldableImpls! {
 pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>;
 pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>;
 
-#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
+#[derive(Debug)]
 pub struct ConstEvalErr<'tcx> {
     pub span: Span,
     pub error: crate::mir::interpret::InterpError<'tcx>,
     pub stacktrace: Vec<FrameInfo<'tcx>>,
 }
 
-#[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
+#[derive(Debug)]
 pub struct FrameInfo<'tcx> {
     /// This span is in the caller.
     pub call_site: Span,
@@ -138,6 +138,7 @@ impl<'tcx> ConstEvalErr<'tcx> {
         lint_root: Option<hir::HirId>,
     ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
         let must_error = match self.error {
+            InterpError::MachineStop(_) => bug!("CTFE does not stop"),
             err_inval!(Layout(LayoutError::Unknown(_))) |
             err_inval!(TooGeneric) =>
                 return Err(ErrorHandled::TooGeneric),
@@ -189,7 +190,7 @@ pub fn struct_error<'tcx>(tcx: TyCtxtAt<'tcx>, msg: &str) -> DiagnosticBuilder<'
 /// Thsese should always be constructed by calling `.into()` on
 /// a `InterpError`. In `librustc_mir::interpret`, we have `throw_err_*`
 /// macros for this.
-#[derive(Debug, Clone)]
+#[derive(Debug)]
 pub struct InterpErrorInfo<'tcx> {
     pub kind: InterpError<'tcx>,
     backtrace: Option<Box<Backtrace>>,
@@ -264,8 +265,8 @@ pub enum PanicInfo<O> {
     OverflowNeg,
     DivisionByZero,
     RemainderByZero,
-    GeneratorResumedAfterReturn,
-    GeneratorResumedAfterPanic,
+    ResumedAfterReturn(GeneratorKind),
+    ResumedAfterPanic(GeneratorKind),
 }
 
 /// Type for MIR `Assert` terminator error messages.
@@ -300,10 +301,14 @@ impl<O> PanicInfo<O> {
                 "attempt to divide by zero",
             RemainderByZero =>
                 "attempt to calculate the remainder with a divisor of zero",
-            GeneratorResumedAfterReturn =>
+            ResumedAfterReturn(GeneratorKind::Gen) =>
                 "generator resumed after completion",
-            GeneratorResumedAfterPanic =>
+            ResumedAfterReturn(GeneratorKind::Async(_)) =>
+                "`async fn` resumed after completion",
+            ResumedAfterPanic(GeneratorKind::Gen) =>
                 "generator resumed after panicking",
+            ResumedAfterPanic(GeneratorKind::Async(_)) =>
+                "`async fn` resumed after panicking",
             Panic { .. } | BoundsCheck { .. } =>
                 bug!("Unexpected PanicInfo"),
         }
@@ -327,7 +332,6 @@ impl<O: fmt::Debug> fmt::Debug for PanicInfo<O> {
 /// Error information for when the program we executed turned out not to actually be a valid
 /// program. This cannot happen in stand-alone Miri, but it can happen during CTFE/ConstProp
 /// where we work on generic code or execution does not have all information available.
-#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
 pub enum InvalidProgramInfo<'tcx> {
     /// Resolution can fail if we are in a too generic context.
     TooGeneric,
@@ -357,7 +361,6 @@ impl fmt::Debug for InvalidProgramInfo<'tcx> {
 }
 
 /// Error information for when the program caused Undefined Behavior.
-#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
 pub enum UndefinedBehaviorInfo {
     /// Free-form case. Only for errors that are never caught!
     Ub(String),
@@ -390,11 +393,14 @@ impl fmt::Debug for UndefinedBehaviorInfo {
 ///
 /// Currently, we also use this as fall-back error kind for errors that have not been
 /// categorized yet.
-#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
 pub enum UnsupportedOpInfo<'tcx> {
     /// Free-form case. Only for errors that are never caught!
     Unsupported(String),
 
+    /// When const-prop encounters a situation it does not support, it raises this error.
+    /// This must not allocate for performance reasons.
+    ConstPropUnsupported(&'tcx str),
+
     // -- Everything below is not categorized yet --
     FunctionAbiMismatch(Abi, Abi),
     FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),
@@ -555,13 +561,14 @@ impl fmt::Debug for UnsupportedOpInfo<'tcx> {
                     not a power of two"),
             Unsupported(ref msg) =>
                 write!(f, "{}", msg),
+            ConstPropUnsupported(ref msg) =>
+                write!(f, "Constant propagation encountered an unsupported situation: {}", msg),
         }
     }
 }
 
 /// Error information for when the program exhausted the resources granted to it
 /// by the interpreter.
-#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
 pub enum ResourceExhaustionInfo {
     /// The stack grew too big.
     StackFrameLimitReached,
@@ -582,7 +589,6 @@ impl fmt::Debug for ResourceExhaustionInfo {
     }
 }
 
-#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
 pub enum InterpError<'tcx> {
     /// The program panicked.
     Panic(PanicInfo<u64>),
@@ -591,14 +597,14 @@ pub enum InterpError<'tcx> {
     /// The program did something the interpreter does not support (some of these *might* be UB
     /// but the interpreter is not sure).
     Unsupported(UnsupportedOpInfo<'tcx>),
-    /// The program was invalid (ill-typed, not sufficiently monomorphized, ...).
+    /// The program was invalid (ill-typed, bad MIR, not sufficiently monomorphized, ...).
     InvalidProgram(InvalidProgramInfo<'tcx>),
     /// The program exhausted the interpreter's resources (stack/heap too big,
-    /// execution takes too long, ..).
+    /// execution takes too long, ...).
     ResourceExhaustion(ResourceExhaustionInfo),
-    /// Not actually an interpreter error -- used to signal that execution has exited
-    /// with the given status code.  Used by Miri, but not by CTFE.
-    Exit(i32),
+    /// Stop execution for a machine-controlled reason. This is never raised by
+    /// the core engine itself.
+    MachineStop(Box<dyn Any + Send>),
 }
 
 pub type InterpResult<'tcx, T = ()> = Result<T, InterpErrorInfo<'tcx>>;
@@ -624,8 +630,8 @@ impl fmt::Debug for InterpError<'_> {
                 write!(f, "{:?}", msg),
             Panic(ref msg) =>
                 write!(f, "{:?}", msg),
-            Exit(code) =>
-                write!(f, "exited with status code {}", code),
+            MachineStop(_) =>
+                write!(f, "machine caused execution to stop"),
         }
     }
 }
diff --git a/src/librustc/mir/interpret/mod.rs b/src/librustc/mir/interpret/mod.rs
index 31c50610ac4..65f4ee88a9c 100644
--- a/src/librustc/mir/interpret/mod.rs
+++ b/src/librustc/mir/interpret/mod.rs
@@ -123,7 +123,10 @@ use rustc_data_structures::tiny_list::TinyList;
 use rustc_macros::HashStable;
 use byteorder::{WriteBytesExt, ReadBytesExt, LittleEndian, BigEndian};
 
-/// Uniquely identifies a specific constant or static.
+/// Uniquely identifies one of the following:
+/// - A constant
+/// - A static
+/// - A const fn where all arguments (if any) are zero-sized types
 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, RustcEncodable, RustcDecodable)]
 #[derive(HashStable, Lift)]
 pub struct GlobalId<'tcx> {
diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs
index c745dd9444c..300b0363e2d 100644
--- a/src/librustc/mir/mod.rs
+++ b/src/librustc/mir/mod.rs
@@ -6,7 +6,7 @@
 
 use crate::hir::def::{CtorKind, Namespace};
 use crate::hir::def_id::DefId;
-use crate::hir;
+use crate::hir::{self, GeneratorKind};
 use crate::mir::interpret::{GlobalAlloc, PanicInfo, Scalar};
 use crate::mir::visit::MirVisitable;
 use crate::ty::adjustment::PointerCast;
@@ -104,10 +104,6 @@ pub struct Body<'tcx> {
     /// and used for debuginfo. Indexed by a `SourceScope`.
     pub source_scopes: IndexVec<SourceScope, SourceScopeData>,
 
-    /// Crate-local information for each source scope, that can't (and
-    /// needn't) be tracked across crates.
-    pub source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
-
     /// The yield type of the function, if it is a generator.
     pub yield_ty: Option<Ty<'tcx>>,
 
@@ -117,6 +113,10 @@ pub struct Body<'tcx> {
     /// The layout of a generator. Produced by the state transformation.
     pub generator_layout: Option<GeneratorLayout<'tcx>>,
 
+    /// If this is a generator then record the type of source expression that caused this generator
+    /// to be created.
+    pub generator_kind: Option<GeneratorKind>,
+
     /// Declarations of locals.
     ///
     /// The first local is the return value pointer, followed by `arg_count`
@@ -163,13 +163,13 @@ impl<'tcx> Body<'tcx> {
     pub fn new(
         basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
         source_scopes: IndexVec<SourceScope, SourceScopeData>,
-        source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
         local_decls: LocalDecls<'tcx>,
         user_type_annotations: CanonicalUserTypeAnnotations<'tcx>,
         arg_count: usize,
         var_debug_info: Vec<VarDebugInfo<'tcx>>,
         span: Span,
         control_flow_destroyed: Vec<(Span, String)>,
+        generator_kind : Option<GeneratorKind>,
     ) -> Self {
         // We need `arg_count` locals, and one for the return place.
         assert!(
@@ -183,10 +183,10 @@ impl<'tcx> Body<'tcx> {
             phase: MirPhase::Build,
             basic_blocks,
             source_scopes,
-            source_scope_local_data,
             yield_ty: None,
             generator_drop: None,
             generator_layout: None,
+            generator_kind,
             local_decls,
             user_type_annotations,
             arg_count,
@@ -429,6 +429,13 @@ pub enum ClearCrossCrate<T> {
 }
 
 impl<T> ClearCrossCrate<T> {
+    pub fn as_ref(&'a self) -> ClearCrossCrate<&'a T> {
+        match self {
+            ClearCrossCrate::Clear => ClearCrossCrate::Clear,
+            ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v),
+        }
+    }
+
     pub fn assert_crate_local(self) -> T {
         match self {
             ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
@@ -2021,6 +2028,10 @@ rustc_index::newtype_index! {
 pub struct SourceScopeData {
     pub span: Span,
     pub parent_scope: Option<SourceScope>,
+
+    /// Crate-local information for this source scope, that can't (and
+    /// needn't) be tracked across crates.
+    pub local_data: ClearCrossCrate<SourceScopeLocalData>,
 }
 
 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
@@ -2302,10 +2313,14 @@ impl<'tcx> Debug for Rvalue<'tcx> {
                         }
                     }
 
-                    AggregateKind::Closure(def_id, _) => ty::tls::with(|tcx| {
+                    AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
                         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
-                                format!("[closure@{:?}]", hir_id)
+                                let substs = tcx.lift(&substs).unwrap();
+                                format!(
+                                    "[closure@{}]",
+                                    tcx.def_path_str_with_substs(def_id, substs),
+                                )
                             } else {
                                 format!("[closure@{:?}]", tcx.hir().span(hir_id))
                             };
@@ -2975,7 +2990,7 @@ impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
                             index: index.fold_with(folder),
                         },
                     Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
-                    GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
+                    ResumedAfterReturn(_) | ResumedAfterPanic(_)  =>
                         msg.clone(),
                 };
                 Assert { cond: cond.fold_with(folder), expected, msg, target, cleanup }
@@ -3021,7 +3036,7 @@ impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
                             len.visit_with(visitor) || index.visit_with(visitor),
                         Panic { .. } | Overflow(_) | OverflowNeg |
                         DivisionByZero | RemainderByZero |
-                        GeneratorResumedAfterReturn | GeneratorResumedAfterPanic =>
+                        ResumedAfterReturn(_) | ResumedAfterPanic(_) =>
                             false
                     }
                 } else {
@@ -3040,6 +3055,16 @@ impl<'tcx> TypeFoldable<'tcx> for Terminator<'tcx> {
     }
 }
 
+impl<'tcx> TypeFoldable<'tcx> for GeneratorKind {
+    fn super_fold_with<F: TypeFolder<'tcx>>(&self, _: &mut F) -> Self {
+        *self
+    }
+
+    fn super_visit_with<V: TypeVisitor<'tcx>>(&self, _: &mut V) -> bool {
+        false
+    }
+}
+
 impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
     fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
         Place {
diff --git a/src/librustc/mir/visit.rs b/src/librustc/mir/visit.rs
index 464d4c74366..145593f1c4d 100644
--- a/src/librustc/mir/visit.rs
+++ b/src/librustc/mir/visit.rs
@@ -317,6 +317,7 @@ macro_rules! make_mir_visitor {
                 let SourceScopeData {
                     span,
                     parent_scope,
+                    local_data: _,
                 } = scope_data;
 
                 self.visit_span(span);
@@ -517,7 +518,7 @@ macro_rules! make_mir_visitor {
                         self.visit_operand(index, location);
                     }
                     Panic { .. } | Overflow(_) | OverflowNeg | DivisionByZero | RemainderByZero |
-                    GeneratorResumedAfterReturn | GeneratorResumedAfterPanic => {
+                    ResumedAfterReturn(_) | ResumedAfterPanic(_) => {
                         // Nothing to visit
                     }
                 }
diff --git a/src/librustc/query/mod.rs b/src/librustc/query/mod.rs
index cd93fed8e1e..d715ddb1b81 100644
--- a/src/librustc/query/mod.rs
+++ b/src/librustc/query/mod.rs
@@ -1130,7 +1130,7 @@ rustc_queries! {
             desc { |tcx| "estimating size for `{}`", tcx.def_path_str(def.def_id()) }
         }
 
-        query features_query(_: CrateNum) -> &'tcx feature_gate::Features {
+        query features_query(_: CrateNum) -> &'tcx rustc_feature::Features {
             eval_always
             desc { "looking up enabled feature gates" }
         }
diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs
index 6733250e1e8..9a242d9d076 100644
--- a/src/librustc/session/config.rs
+++ b/src/librustc/session/config.rs
@@ -7,6 +7,7 @@ use crate::session::{early_error, early_warn, Session};
 use crate::session::search_paths::SearchPath;
 
 use rustc_data_structures::fx::FxHashSet;
+use rustc_feature::UnstableFeatures;
 
 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
 use rustc_target::spec::{Target, TargetTriple};
@@ -16,7 +17,6 @@ use syntax::ast;
 use syntax::source_map::{FileName, FilePathMapping};
 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
 use syntax::symbol::{sym, Symbol};
-use syntax::feature_gate::UnstableFeatures;
 
 use errors::emitter::HumanReadableErrorType;
 use errors::{ColorConfig, FatalError, Handler};
@@ -47,6 +47,17 @@ pub enum Sanitizer {
     Thread,
 }
 
+impl fmt::Display for Sanitizer {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match *self {
+            Sanitizer::Address => "address".fmt(f),
+            Sanitizer::Leak => "leak".fmt(f),
+            Sanitizer::Memory => "memory".fmt(f),
+            Sanitizer::Thread => "thread".fmt(f),
+        }
+    }
+}
+
 impl FromStr for Sanitizer {
     type Err = ();
     fn from_str(s: &str) -> Result<Sanitizer, ()> {
@@ -1364,8 +1375,6 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
         "enable queries of the dependency graph for regression testing"),
     no_analysis: bool = (false, parse_bool, [UNTRACKED],
         "parse and expand the source, but run no analysis"),
-    extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
-        "load extra plugins"),
     unstable_options: bool = (false, parse_bool, [UNTRACKED],
         "adds unstable command line options to rustc interface"),
     force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
@@ -1582,6 +1591,10 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
             }
         }
     }
+    if let Some(s) = &sess.opts.debugging_opts.sanitizer {
+        let symbol = Symbol::intern(&s.to_string());
+        ret.insert((sym::sanitize, Some(symbol)));
+    }
     if sess.opts.debug_assertions {
         ret.insert((Symbol::intern("debug_assertions"), None));
     }
@@ -2701,7 +2714,7 @@ pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateTy
 
 pub mod nightly_options {
     use getopts;
-    use syntax::feature_gate::UnstableFeatures;
+    use rustc_feature::UnstableFeatures;
     use super::{ErrorOutputType, OptionStability, RustcOptGroup};
     use crate::session::early_error;
 
@@ -2850,9 +2863,9 @@ mod dep_tracking {
     use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
                 Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
                 SymbolManglingVersion};
+    use rustc_feature::UnstableFeatures;
     use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
     use syntax::edition::Edition;
-    use syntax::feature_gate::UnstableFeatures;
 
     pub trait DepTrackingHash {
         fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs
index af6522df61e..f673ea3e771 100644
--- a/src/librustc/session/mod.rs
+++ b/src/librustc/session/mod.rs
@@ -21,7 +21,6 @@ use errors::emitter::{Emitter, EmitterWriter};
 use errors::emitter::HumanReadableErrorType;
 use errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
 use syntax::edition::Edition;
-use syntax::feature_gate;
 use errors::json::JsonEmitter;
 use syntax::source_map;
 use syntax::sess::ParseSess;
@@ -77,7 +76,6 @@ pub struct Session {
     /// (sub)diagnostics that have been set once, but should not be set again,
     /// in order to avoid redundantly verbose output (Issue #24690, #44953).
     pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
-    pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
     pub crate_types: Once<Vec<config::CrateType>>,
     /// The `crate_disambiguator` is constructed out of all the `-C metadata`
     /// arguments passed to the compiler. Its value together with the crate-name
@@ -86,7 +84,7 @@ pub struct Session {
     /// `rustc_codegen_llvm::back::symbol_names` module for more information.
     pub crate_disambiguator: Once<CrateDisambiguator>,
 
-    features: Once<feature_gate::Features>,
+    features: Once<rustc_feature::Features>,
 
     /// The maximum recursion limit for potentially infinitely recursive
     /// operations such as auto-dereference and monomorphization.
@@ -95,9 +93,6 @@ pub struct Session {
     /// The maximum length of types during monomorphization.
     pub type_length_limit: Once<usize>,
 
-    /// The maximum number of stackframes allowed in const eval.
-    pub const_eval_stack_frame_limit: usize,
-
     /// Map from imported macro spans (which consist of
     /// the localized span for the macro body) to the
     /// macro name and definition span in the source crate.
@@ -133,9 +128,6 @@ pub struct Session {
     /// false positives about a job server in our environment.
     pub jobserver: Client,
 
-    /// Metadata about the allocators for the current crate being compiled.
-    pub has_global_allocator: Once<bool>,
-
     /// Cap lint level specified by a driver specifically.
     pub driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
 
@@ -473,11 +465,11 @@ impl Session {
     /// DO NOT USE THIS METHOD if there is a TyCtxt available, as it circumvents
     /// dependency tracking. Use tcx.features() instead.
     #[inline]
-    pub fn features_untracked(&self) -> &feature_gate::Features {
+    pub fn features_untracked(&self) -> &rustc_feature::Features {
         self.features.get()
     }
 
-    pub fn init_features(&self, features: feature_gate::Features) {
+    pub fn init_features(&self, features: rustc_feature::Features) {
         self.features.set(features);
     }
 
@@ -1156,13 +1148,11 @@ fn build_session_(
         local_crate_source_file,
         working_dir,
         one_time_diagnostics: Default::default(),
-        plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
         crate_types: Once::new(),
         crate_disambiguator: Once::new(),
         features: Once::new(),
         recursion_limit: Once::new(),
         type_length_limit: Once::new(),
-        const_eval_stack_frame_limit: 100,
         imported_macro_spans: OneThread::new(RefCell::new(FxHashMap::default())),
         incr_comp_session: OneThread::new(RefCell::new(IncrCompSession::NotInitialized)),
         cgu_reuse_tracker,
@@ -1180,7 +1170,6 @@ fn build_session_(
         print_fuel_crate,
         print_fuel,
         jobserver: jobserver::client(),
-        has_global_allocator: Once::new(),
         driver_lint_caps,
         trait_methods_not_found: Lock::new(Default::default()),
         confused_type_with_std_module: Lock::new(Default::default()),
diff --git a/src/librustc/traits/coherence.rs b/src/librustc/traits/coherence.rs
index 778bba1eef6..933bc06c21e 100644
--- a/src/librustc/traits/coherence.rs
+++ b/src/librustc/traits/coherence.rs
@@ -382,7 +382,7 @@ fn orphan_check_trait_ref<'tcx>(
         ty: Ty<'tcx>,
         in_crate: InCrate,
     ) -> Vec<Ty<'tcx>> {
-        if fundamental_ty(ty) && ty_is_non_local(tcx, ty, in_crate).is_some() {
+        if fundamental_ty(ty) && ty_is_non_local(ty, in_crate).is_some() {
             ty.walk_shallow().flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate)).collect()
         } else {
             vec![ty]
@@ -396,7 +396,7 @@ fn orphan_check_trait_ref<'tcx>(
         .enumerate()
     {
         debug!("orphan_check_trait_ref: check ty `{:?}`", input_ty);
-        let non_local_tys = ty_is_non_local(tcx, input_ty, in_crate);
+        let non_local_tys = ty_is_non_local(input_ty, in_crate);
         if non_local_tys.is_none() {
             debug!("orphan_check_trait_ref: ty_is_local `{:?}`", input_ty);
             return Ok(());
@@ -405,7 +405,7 @@ fn orphan_check_trait_ref<'tcx>(
             let local_type = trait_ref
                 .input_types()
                 .flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
-                .filter(|ty| ty_is_non_local_constructor(tcx, ty, in_crate).is_none())
+                .filter(|ty| ty_is_non_local_constructor(ty, in_crate).is_none())
                 .next();
 
             debug!("orphan_check_trait_ref: uncovered ty local_type: `{:?}`", local_type);
@@ -423,13 +423,13 @@ fn orphan_check_trait_ref<'tcx>(
     Err(OrphanCheckErr::NonLocalInputType(non_local_spans))
 }
 
-fn ty_is_non_local<'t>(tcx: TyCtxt<'t>, ty: Ty<'t>, in_crate: InCrate) -> Option<Vec<Ty<'t>>> {
-    match ty_is_non_local_constructor(tcx, ty, in_crate) {
+fn ty_is_non_local<'t>(ty: Ty<'t>, in_crate: InCrate) -> Option<Vec<Ty<'t>>> {
+    match ty_is_non_local_constructor(ty, in_crate) {
         Some(ty) => if !fundamental_ty(ty) {
             Some(vec![ty])
         } else {
             let tys: Vec<_> = ty.walk_shallow()
-                .filter_map(|t| ty_is_non_local(tcx, t, in_crate))
+                .filter_map(|t| ty_is_non_local(t, in_crate))
                 .flat_map(|i| i)
                 .collect();
             if tys.is_empty() {
@@ -460,7 +460,6 @@ fn def_id_is_local(def_id: DefId, in_crate: InCrate) -> bool {
 }
 
 fn ty_is_non_local_constructor<'tcx>(
-    tcx: TyCtxt<'tcx>,
     ty: Ty<'tcx>,
     in_crate: InCrate,
 ) -> Option<Ty<'tcx>> {
@@ -503,14 +502,33 @@ fn ty_is_non_local_constructor<'tcx>(
         } else {
             Some(ty)
         },
-        ty::Opaque(did, _) => {
-            // Check the underlying type that this opaque
-            // type resolves to.
-            // This recursion will eventually terminate,
-            // since we've already managed to successfully
-            // resolve all opaque types by this point
-            let real_ty = tcx.type_of(did);
-            ty_is_non_local_constructor(tcx, real_ty, in_crate)
+        ty::Opaque(..) => {
+            // This merits some explanation.
+            // Normally, opaque types are not involed when performing
+            // coherence checking, since it is illegal to directly
+            // implement a trait on an opaque type. However, we might
+            // end up looking at an opaque type during coherence checking
+            // if an opaque type gets used within another type (e.g. as
+            // a type parameter). This requires us to decide whether or
+            // not an opaque type should be considered 'local' or not.
+            //
+            // We choose to treat all opaque types as non-local, even
+            // those that appear within the same crate. This seems
+            // somewhat suprising at first, but makes sense when
+            // you consider that opaque types are supposed to hide
+            // the underlying type *within the same crate*. When an
+            // opaque type is used from outside the module
+            // where it is declared, it should be impossible to observe
+            // anyything about it other than the traits that it implements.
+            //
+            // The alternative would be to look at the underlying type
+            // to determine whether or not the opaque type itself should
+            // be considered local. However, this could make it a breaking change
+            // to switch the underlying ('defining') type from a local type
+            // to a remote type. This would violate the rule that opaque
+            // types should be completely opaque apart from the traits
+            // that they implement, so we don't use this behavior.
+            Some(ty)
         }
 
         ty::Dynamic(ref tt, ..) => {
diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs
index 65d08ab03aa..90db1fe3195 100644
--- a/src/librustc/traits/error_reporting.rs
+++ b/src/librustc/traits/error_reporting.rs
@@ -39,6 +39,7 @@ use syntax::ast;
 use syntax::symbol::{sym, kw};
 use syntax_pos::{DUMMY_SP, Span, ExpnKind, MultiSpan};
 use rustc::hir::def_id::LOCAL_CRATE;
+use syntax_pos::source_map::SourceMap;
 
 use rustc_error_codes::*;
 
@@ -736,7 +737,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                         let is_try = self.tcx.sess.source_map().span_to_snippet(span)
                             .map(|s| &s == "?")
                             .unwrap_or(false);
-                        let is_from = format!("{}", trait_ref).starts_with("std::convert::From<");
+                        let is_from =
+                            format!("{}", trait_ref.print_only_trait_path())
+                            .starts_with("std::convert::From<");
                         let (message, note) = if is_try && is_from {
                             (Some(format!(
                                 "`?` couldn't convert the error to `{}`",
@@ -767,7 +770,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                                 format!(
                                     "{}the trait `{}` is not implemented for `{}`",
                                     pre_message,
-                                    trait_ref,
+                                    trait_ref.print_only_trait_path(),
                                     trait_ref.self_ty(),
                                 )
                             };
@@ -1091,7 +1094,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
     }
     fn suggest_restricting_param_bound(
         &self,
-        err: &mut DiagnosticBuilder<'_>,
+        mut err: &mut DiagnosticBuilder<'_>,
         trait_ref: &ty::PolyTraitRef<'_>,
         body_id: hir::HirId,
     ) {
@@ -1102,7 +1105,11 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
             _ => return,
         };
 
-        let mut suggest_restriction = |generics: &hir::Generics, msg| {
+        let suggest_restriction = |
+            generics: &hir::Generics,
+            msg,
+            err: &mut DiagnosticBuilder<'_>,
+        | {
             let span = generics.where_clause.span_for_predicates_or_empty_place();
             if !span.from_expansion() && span.desugaring_kind().is_none() {
                 err.span_suggestion(
@@ -1132,7 +1139,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     kind: hir::TraitItemKind::Method(..), ..
                 }) if param_ty && self_ty == self.tcx.types.self_param => {
                     // Restricting `Self` for a single method.
-                    suggest_restriction(&generics, "`Self`");
+                    suggest_restriction(&generics, "`Self`", err);
                     return;
                 }
 
@@ -1154,7 +1161,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     kind: hir::ItemKind::Impl(_, _, _, generics, ..), ..
                 }) if projection.is_some() => {
                     // Missing associated type bound.
-                    suggest_restriction(&generics, "the associated type");
+                    suggest_restriction(&generics, "the associated type", err);
                     return;
                 }
 
@@ -1183,68 +1190,16 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                 hir::Node::ImplItem(hir::ImplItem { generics, span, .. })
                 if param_ty => {
                     // Missing generic type parameter bound.
-                    let restrict_msg = "consider further restricting this bound";
                     let param_name = self_ty.to_string();
-                    for param in generics.params.iter().filter(|p| {
-                        p.name.ident().as_str() == param_name
-                    }) {
-                        if param_name.starts_with("impl ") {
-                            // `impl Trait` in argument:
-                            // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
-                            err.span_suggestion(
-                                param.span,
-                                restrict_msg,
-                                // `impl CurrentTrait + MissingTrait`
-                                format!("{} + {}", param.name.ident(), trait_ref),
-                                Applicability::MachineApplicable,
-                            );
-                        } else if generics.where_clause.predicates.is_empty() &&
-                                param.bounds.is_empty()
-                        {
-                            // If there are no bounds whatsoever, suggest adding a constraint
-                            // to the type parameter:
-                            // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
-                            err.span_suggestion(
-                                param.span,
-                                "consider restricting this bound",
-                                format!("{}", trait_ref.to_predicate()),
-                                Applicability::MachineApplicable,
-                            );
-                        } else if !generics.where_clause.predicates.is_empty() {
-                            // There is a `where` clause, so suggest expanding it:
-                            // `fn foo<T>(t: T) where T: Debug {}` →
-                            // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
-                            err.span_suggestion(
-                                generics.where_clause.span().unwrap().shrink_to_hi(),
-                                &format!(
-                                    "consider further restricting type parameter `{}`",
-                                    param_name,
-                                ),
-                                format!(", {}", trait_ref.to_predicate()),
-                                Applicability::MachineApplicable,
-                            );
-                        } else {
-                            // If there is no `where` clause lean towards constraining to the
-                            // type parameter:
-                            // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
-                            // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
-                            let sp = param.span.with_hi(span.hi());
-                            let span = self.tcx.sess.source_map()
-                                .span_through_char(sp, ':');
-                            if sp != param.span && sp != span {
-                                // Only suggest if we have high certainty that the span
-                                // covers the colon in `foo<T: Trait>`.
-                                err.span_suggestion(span, restrict_msg, format!(
-                                    "{} + ",
-                                    trait_ref.to_predicate(),
-                                ), Applicability::MachineApplicable);
-                            } else {
-                                err.span_label(param.span, &format!(
-                                    "consider adding a `where {}` bound",
-                                    trait_ref.to_predicate(),
-                                ));
-                            }
-                        }
+                    let constraint = trait_ref.print_only_trait_path().to_string();
+                    if suggest_constraining_type_param(
+                        generics,
+                        &mut err,
+                        &param_name,
+                        &constraint,
+                        self.tcx.sess.source_map(),
+                        *span,
+                    ) {
                         return;
                     }
                 }
@@ -1463,7 +1418,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     let msg = format!(
                         "the trait bound `{}: {}` is not satisfied",
                         found,
-                        obligation.parent_trait_ref.skip_binder(),
+                        obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
                     );
                     if has_custom_message {
                         err.note(&msg);
@@ -1477,7 +1432,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     }
                     err.span_label(span, &format!(
                         "expected an implementor of trait `{}`",
-                        obligation.parent_trait_ref.skip_binder(),
+                        obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
                     ));
                     err.span_suggestion(
                         span,
@@ -1609,7 +1564,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     } else {
                         err.note(&format!(
                             "`{}` is implemented for `{:?}`, but not for `{:?}`",
-                            trait_ref,
+                            trait_ref.print_only_trait_path(),
                             trait_type,
                             trait_ref.skip_binder().self_ty(),
                         ));
@@ -2273,7 +2228,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
 
             err.span_note(span, &format!(
                 "future does not implement `{}` as this value is used across an await",
-                trait_ref,
+                trait_ref.print_only_trait_path(),
             ));
 
             // Add a note for the item obligation that remains - normally a note pointing to the
@@ -2456,7 +2411,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                 let parent_trait_ref = self.resolve_vars_if_possible(&data.parent_trait_ref);
                 err.note(
                     &format!("required because of the requirements on the impl of `{}` for `{}`",
-                             parent_trait_ref,
+                             parent_trait_ref.print_only_trait_path(),
                              parent_trait_ref.skip_binder().self_ty()));
                 let parent_predicate = parent_trait_ref.to_predicate();
                 self.note_obligation_cause_code(err,
@@ -2546,3 +2501,76 @@ impl ArgKind {
         }
     }
 }
+
+/// Suggest restricting a type param with a new bound.
+pub fn suggest_constraining_type_param(
+    generics: &hir::Generics,
+    err: &mut DiagnosticBuilder<'_>,
+    param_name: &str,
+    constraint: &str,
+    source_map: &SourceMap,
+    span: Span,
+) -> bool {
+    let restrict_msg = "consider further restricting this bound";
+    if let Some(param) = generics.params.iter().filter(|p| {
+        p.name.ident().as_str() == param_name
+    }).next() {
+        if param_name.starts_with("impl ") {
+            // `impl Trait` in argument:
+            // `fn foo(x: impl Trait) {}` → `fn foo(t: impl Trait + Trait2) {}`
+            err.span_suggestion(
+                param.span,
+                restrict_msg,
+                // `impl CurrentTrait + MissingTrait`
+                format!("{} + {}", param_name, constraint),
+                Applicability::MachineApplicable,
+            );
+        } else if generics.where_clause.predicates.is_empty() &&
+                param.bounds.is_empty()
+        {
+            // If there are no bounds whatsoever, suggest adding a constraint
+            // to the type parameter:
+            // `fn foo<T>(t: T) {}` → `fn foo<T: Trait>(t: T) {}`
+            err.span_suggestion(
+                param.span,
+                "consider restricting this bound",
+                format!("{}: {}", param_name, constraint),
+                Applicability::MachineApplicable,
+            );
+        } else if !generics.where_clause.predicates.is_empty() {
+            // There is a `where` clause, so suggest expanding it:
+            // `fn foo<T>(t: T) where T: Debug {}` →
+            // `fn foo<T>(t: T) where T: Debug, T: Trait {}`
+            err.span_suggestion(
+                generics.where_clause.span().unwrap().shrink_to_hi(),
+                &format!("consider further restricting type parameter `{}`", param_name),
+                format!(", {}: {}", param_name, constraint),
+                Applicability::MachineApplicable,
+            );
+        } else {
+            // If there is no `where` clause lean towards constraining to the
+            // type parameter:
+            // `fn foo<X: Bar, T>(t: T, x: X) {}` → `fn foo<T: Trait>(t: T) {}`
+            // `fn foo<T: Bar>(t: T) {}` → `fn foo<T: Bar + Trait>(t: T) {}`
+            let sp = param.span.with_hi(span.hi());
+            let span = source_map.span_through_char(sp, ':');
+            if sp != param.span && sp != span {
+                // Only suggest if we have high certainty that the span
+                // covers the colon in `foo<T: Trait>`.
+                err.span_suggestion(
+                    span,
+                    restrict_msg,
+                    format!("{}: {} + ", param_name, constraint),
+                    Applicability::MachineApplicable,
+                );
+            } else {
+                err.span_label(
+                    param.span,
+                    &format!("consider adding a `where {}: {}` bound", param_name, constraint),
+                );
+            }
+        }
+        return true;
+    }
+    false
+}
diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs
index 283fa56d11f..5f324527a27 100644
--- a/src/librustc/traits/select.rs
+++ b/src/librustc/traits/select.rs
@@ -1044,7 +1044,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
                         let self_ty = trait_ref.self_ty();
                         let cause = IntercrateAmbiguityCause::DownstreamCrate {
-                            trait_desc: trait_ref.to_string(),
+                            trait_desc: trait_ref.print_only_trait_path().to_string(),
                             self_desc: if self_ty.has_concrete_skeleton() {
                                 Some(self_ty.to_string())
                             } else {
@@ -1386,7 +1386,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
                     if !candidate_set.ambiguous && no_candidates_apply {
                         let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
                         let self_ty = trait_ref.self_ty();
-                        let trait_desc = trait_ref.to_string();
+                        let trait_desc = trait_ref.print_only_trait_path().to_string();
                         let self_desc = if self_ty.has_concrete_skeleton() {
                             Some(self_ty.to_string())
                         } else {
diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs
index 475037f54ba..88a2db3dc62 100644
--- a/src/librustc/traits/specialize/mod.rs
+++ b/src/librustc/traits/specialize/mod.rs
@@ -417,7 +417,7 @@ fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String>
         w.push('>');
     }
 
-    write!(w, " {} for {}", trait_ref, tcx.type_of(impl_def_id)).unwrap();
+    write!(w, " {} for {}", trait_ref.print_only_trait_path(), tcx.type_of(impl_def_id)).unwrap();
 
     // The predicates will contain default bounds like `T: Sized`. We need to
     // remove these bounds, and add `T: ?Sized` to any untouched type parameters.
diff --git a/src/librustc/traits/specialize/specialization_graph.rs b/src/librustc/traits/specialize/specialization_graph.rs
index d945c756f66..b8ddf6078bd 100644
--- a/src/librustc/traits/specialize/specialization_graph.rs
+++ b/src/librustc/traits/specialize/specialization_graph.rs
@@ -146,7 +146,7 @@ impl<'tcx> Children {
                 let self_ty = trait_ref.self_ty();
                 OverlapError {
                     with_impl: possible_sibling,
-                    trait_desc: trait_ref.to_string(),
+                    trait_desc: trait_ref.print_only_trait_path().to_string(),
                     // Only report the `Self` type if it has at least
                     // some outer concrete shell; otherwise, it's
                     // not adding much information.
diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs
index 95456581169..776ae7dc141 100644
--- a/src/librustc/ty/context.rs
+++ b/src/librustc/ty/context.rs
@@ -72,7 +72,6 @@ use rustc_macros::HashStable;
 use syntax::ast;
 use syntax::attr;
 use syntax::source_map::MultiSpan;
-use syntax::feature_gate;
 use syntax::symbol::{Symbol, kw, sym};
 use syntax_pos::Span;
 use syntax::expand::allocator::AllocatorKind;
@@ -995,7 +994,7 @@ impl<'tcx> Deref for TyCtxt<'tcx> {
 }
 
 pub struct GlobalCtxt<'tcx> {
-    pub arena: WorkerLocal<Arena<'tcx>>,
+    pub arena: &'tcx WorkerLocal<Arena<'tcx>>,
 
     interners: CtxtInterners<'tcx>,
 
@@ -1170,6 +1169,7 @@ impl<'tcx> TyCtxt<'tcx> {
         local_providers: ty::query::Providers<'tcx>,
         extern_providers: ty::query::Providers<'tcx>,
         arenas: &'tcx AllArenas,
+        arena: &'tcx WorkerLocal<Arena<'tcx>>,
         resolutions: ty::ResolverOutputs,
         hir: hir_map::Map<'tcx>,
         on_disk_query_result_cache: query::OnDiskCache<'tcx>,
@@ -1225,7 +1225,7 @@ impl<'tcx> TyCtxt<'tcx> {
             sess: s,
             lint_store,
             cstore,
-            arena: WorkerLocal::new(|_| Arena::default()),
+            arena,
             interners,
             dep_graph,
             prof: s.prof.clone(),
@@ -1307,15 +1307,11 @@ impl<'tcx> TyCtxt<'tcx> {
         self.all_crate_nums(LOCAL_CRATE)
     }
 
-    pub fn injected_panic_runtime(self) -> Option<CrateNum> {
-        self.cstore.injected_panic_runtime()
-    }
-
     pub fn allocator_kind(self) -> Option<AllocatorKind> {
         self.cstore.allocator_kind()
     }
 
-    pub fn features(self) -> &'tcx feature_gate::Features {
+    pub fn features(self) -> &'tcx rustc_feature::Features {
         self.features_query(LOCAL_CRATE)
     }
 
@@ -1391,8 +1387,8 @@ impl<'tcx> TyCtxt<'tcx> {
 
     // Note that this is *untracked* and should only be used within the query
     // system if the result is otherwise tracked through queries
-    pub fn crate_data_as_any(self, cnum: CrateNum) -> &'tcx dyn Any {
-        self.cstore.crate_data_as_any(cnum)
+    pub fn cstore_as_any(self) -> &'tcx dyn Any {
+        self.cstore.as_any()
     }
 
     #[inline(always)]
@@ -2999,14 +2995,6 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) {
         assert_eq!(cnum, LOCAL_CRATE);
         tcx.arena.alloc_slice(&tcx.cstore.crates_untracked())
     };
-    providers.crate_host_hash = |tcx, cnum| {
-        assert_ne!(cnum, LOCAL_CRATE);
-        tcx.cstore.crate_host_hash_untracked(cnum)
-    };
-    providers.postorder_cnums = |tcx, cnum| {
-        assert_eq!(cnum, LOCAL_CRATE);
-        tcx.arena.alloc_slice(&tcx.cstore.postorder_cnums_untracked())
-    };
     providers.output_filenames = |tcx, cnum| {
         assert_eq!(cnum, LOCAL_CRATE);
         tcx.output_filenames.clone()
diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs
index b6050a5caf1..c67e6a0a13e 100644
--- a/src/librustc/ty/layout.rs
+++ b/src/librustc/ty/layout.rs
@@ -2526,9 +2526,16 @@ where
 
             if let Some(pointee) = layout.pointee_info_at(cx, offset) {
                 if let Some(kind) = pointee.safe {
-                    attrs.pointee_size = pointee.size;
                     attrs.pointee_align = Some(pointee.align);
 
+                    // `Box` (`UniqueBorrowed`) are not necessarily dereferencable
+                    // for the entire duration of the function as they can be deallocated
+                    // any time. Set their valid size to 0.
+                    attrs.pointee_size = match kind {
+                        PointerKind::UniqueOwned => Size::ZERO,
+                        _ => pointee.size
+                    };
+
                     // `Box` pointer parameters never alias because ownership is transferred
                     // `&mut` pointer parameters never alias other parameters,
                     // or mutable global data
diff --git a/src/librustc/ty/print/pretty.rs b/src/librustc/ty/print/pretty.rs
index 2a311ea9624..fff2f06e87b 100644
--- a/src/librustc/ty/print/pretty.rs
+++ b/src/librustc/ty/print/pretty.rs
@@ -449,7 +449,7 @@ pub trait PrettyPrinter<'tcx>:
 
             p!(print(self_ty));
             if let Some(trait_ref) = trait_ref {
-                p!(write(" as "), print(trait_ref));
+                p!(write(" as "), print(trait_ref.print_only_trait_path()));
             }
             Ok(cx)
         })
@@ -468,7 +468,7 @@ pub trait PrettyPrinter<'tcx>:
 
             p!(write("impl "));
             if let Some(trait_ref) = trait_ref {
-                p!(print(trait_ref), write(" for "));
+                p!(print(trait_ref.print_only_trait_path()), write(" for "));
             }
             p!(print(self_ty));
 
@@ -619,7 +619,7 @@ pub trait PrettyPrinter<'tcx>:
 
                             p!(
                                     write("{}", if first { " " } else { "+" }),
-                                    print(trait_ref));
+                                    print(trait_ref.print_only_trait_path()));
                             first = false;
                         }
                     }
@@ -682,7 +682,7 @@ pub trait PrettyPrinter<'tcx>:
                 // FIXME(eddyb) should use `def_span`.
                 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
                     if self.tcx().sess.opts.debugging_opts.span_free_formats {
-                        p!(write("@{:?}", hir_id));
+                        p!(write("@"), print_def_path(did, substs));
                     } else {
                         p!(write("@{:?}", self.tcx().hir().span(hir_id)));
                     }
@@ -1696,6 +1696,30 @@ impl fmt::Display for ty::RegionKind {
     }
 }
 
+/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
+/// the trait path. That is, it will print `Trait<U>` instead of
+/// `<T as Trait<U>>`.
+#[derive(Copy, Clone, TypeFoldable, Lift)]
+pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
+
+impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(self, f)
+    }
+}
+
+impl ty::TraitRef<'tcx> {
+    pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
+        TraitRefPrintOnlyTraitPath(self)
+    }
+}
+
+impl ty::Binder<ty::TraitRef<'tcx>> {
+    pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
+        self.map_bound(|tr| tr.print_only_trait_path())
+    }
+}
+
 forward_display_to_print! {
     Ty<'tcx>,
     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
@@ -1705,6 +1729,7 @@ forward_display_to_print! {
     // because `for<'tcx>` isn't possible yet.
     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
     ty::Binder<ty::TraitRef<'tcx>>,
+    ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
     ty::Binder<ty::FnSig<'tcx>>,
     ty::Binder<ty::TraitPredicate<'tcx>>,
     ty::Binder<ty::SubtypePredicate<'tcx>>,
@@ -1739,7 +1764,7 @@ define_print_and_forward_display! {
         // Use a type that can't appear in defaults of type parameters.
         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
-        p!(print(trait_ref))
+        p!(print(trait_ref.print_only_trait_path()))
     }
 
     ty::ExistentialProjection<'tcx> {
@@ -1783,7 +1808,11 @@ define_print_and_forward_display! {
     }
 
     ty::TraitRef<'tcx> {
-        p!(print_def_path(self.def_id, self.substs));
+        p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
+    }
+
+    TraitRefPrintOnlyTraitPath<'tcx> {
+        p!(print_def_path(self.0.def_id, self.0.substs));
     }
 
     ty::ParamTy {
@@ -1799,7 +1828,8 @@ define_print_and_forward_display! {
     }
 
     ty::TraitPredicate<'tcx> {
-        p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
+        p!(print(self.trait_ref.self_ty()), write(": "),
+           print(self.trait_ref.print_only_trait_path()))
     }
 
     ty::ProjectionPredicate<'tcx> {
diff --git a/src/librustc/ty/query/mod.rs b/src/librustc/ty/query/mod.rs
index a1eb1c43335..5b4a6ac8a2d 100644
--- a/src/librustc/ty/query/mod.rs
+++ b/src/librustc/ty/query/mod.rs
@@ -56,7 +56,6 @@ use std::any::type_name;
 use syntax_pos::{Span, DUMMY_SP};
 use syntax::attr;
 use syntax::ast;
-use syntax::feature_gate;
 use syntax::symbol::Symbol;
 
 #[macro_use]
diff --git a/src/librustc/ty/structural_impls.rs b/src/librustc/ty/structural_impls.rs
index a0e66d340ae..ce76a4c831b 100644
--- a/src/librustc/ty/structural_impls.rs
+++ b/src/librustc/ty/structural_impls.rs
@@ -3,6 +3,7 @@
 //! hand, though we've recently added some macros and proc-macros to help with the tedium.
 
 use crate::hir::def::Namespace;
+use crate::hir::def_id::CRATE_DEF_INDEX;
 use crate::mir::ProjectionKind;
 use crate::mir::interpret;
 use crate::ty::{self, Lift, Ty, TyCtxt, InferConst};
@@ -95,8 +96,11 @@ impl fmt::Debug for ty::BoundRegion {
         match *self {
             ty::BrAnon(n) => write!(f, "BrAnon({:?})", n),
             ty::BrNamed(did, name) => {
-                write!(f, "BrNamed({:?}:{:?}, {})",
-                        did.krate, did.index, name)
+                if did.index == CRATE_DEF_INDEX {
+                    write!(f, "BrNamed({})", name)
+                } else {
+                    write!(f, "BrNamed({:?}, {})", did, name)
+                }
             }
             ty::BrEnv => write!(f, "BrEnv"),
         }
@@ -223,10 +227,7 @@ impl fmt::Debug for ty::FloatVarValue {
 
 impl fmt::Debug for ty::TraitRef<'tcx> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        // FIXME(#59188) this is used across the compiler to print
-        // a `TraitRef` qualified (with the Self type explicit),
-        // instead of having a different way to make that choice.
-        write!(f, "<{} as {}>", self.self_ty(), self)
+        fmt::Display::fmt(self, f)
     }
 }
 
diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs
index b72468a6ff9..6cb0d1e9946 100644
--- a/src/librustc/ty/sty.rs
+++ b/src/librustc/ty/sty.rs
@@ -69,7 +69,7 @@ pub enum BoundRegion {
 impl BoundRegion {
     pub fn is_named(&self) -> bool {
         match *self {
-            BoundRegion::BrNamed(..) => true,
+            BoundRegion::BrNamed(_, name) => name != kw::UnderscoreLifetime,
             _ => false,
         }
     }
@@ -2330,22 +2330,43 @@ impl<'tcx> Const<'tcx> {
         tcx: TyCtxt<'tcx>,
         param_env: ParamEnv<'tcx>,
     ) -> &Const<'tcx> {
-        // FIXME(const_generics): this doesn't work right now,
-        // because it tries to relate an `Infer` to a `Param`.
+        let try_const_eval = |did, param_env: ParamEnv<'tcx>, substs| {
+            let param_env_and_substs = param_env.with_reveal_all().and(substs);
+
+            // Avoid querying `tcx.const_eval(...)` with any e.g. inference vars.
+            if param_env_and_substs.has_local_value() {
+                return None;
+            }
+
+            let (param_env, substs) = param_env_and_substs.into_parts();
+
+            // try to resolve e.g. associated constants to their definition on an impl
+            let instance = ty::Instance::resolve(tcx, param_env, did, substs)?;
+            let gid = GlobalId {
+                instance,
+                promoted: None,
+            };
+            tcx.const_eval(param_env.and(gid)).ok()
+        };
+
         match self.val {
             ConstKind::Unevaluated(did, substs) => {
-                // if `substs` has no unresolved components, use and empty param_env
-                let (param_env, substs) = param_env.with_reveal_all().and(substs).into_parts();
-                // try to resolve e.g. associated constants to their definition on an impl
-                let instance = match ty::Instance::resolve(tcx, param_env, did, substs) {
-                    Some(instance) => instance,
-                    None => return self,
-                };
-                let gid = GlobalId {
-                    instance,
-                    promoted: None,
-                };
-                tcx.const_eval(param_env.and(gid)).unwrap_or(self)
+                // HACK(eddyb) when substs contain e.g. inference variables,
+                // attempt using identity substs instead, that will succeed
+                // when the expression doesn't depend on any parameters.
+                // FIXME(eddyb) make `const_eval` a canonical query instead,
+                // that would properly handle inference variables in `substs`.
+                if substs.has_local_value() {
+                    let identity_substs = InternalSubsts::identity_for_item(tcx, did);
+                    // The `ParamEnv` needs to match the `identity_substs`.
+                    let identity_param_env = tcx.param_env(did);
+                    match try_const_eval(did, identity_param_env, identity_substs) {
+                        Some(ct) => ct.subst(tcx, substs),
+                        None => self,
+                    }
+                } else {
+                    try_const_eval(did, param_env, substs).unwrap_or(self)
+                }
             },
             _ => self,
         }
diff --git a/src/librustc/ty/util.rs b/src/librustc/ty/util.rs
index 0c9fbfe6641..0b11a9efd81 100644
--- a/src/librustc/ty/util.rs
+++ b/src/librustc/ty/util.rs
@@ -682,6 +682,23 @@ impl<'tcx> TyCtxt<'tcx> {
         self.static_mutability(def_id) == Some(hir::Mutability::Mutable)
     }
 
+    /// Get the type of the pointer to the static that we use in MIR.
+    pub fn static_ptr_ty(&self, def_id: DefId) -> Ty<'tcx> {
+        // Make sure that any constants in the static's type are evaluated.
+        let static_ty = self.normalize_erasing_regions(
+            ty::ParamEnv::empty(),
+            self.type_of(def_id),
+        );
+
+        if self.is_mutable_static(def_id) {
+            self.mk_mut_ptr(static_ty)
+        } else if self.is_foreign_item(def_id) {
+            self.mk_imm_ptr(static_ty)
+        } else {
+            self.mk_imm_ref(self.lifetimes.re_erased, static_ty)
+        }
+    }
+
     /// Expands the given impl trait type, stopping if the type is recursive.
     pub fn try_expand_impl_trait_type(
         self,
diff --git a/src/librustc_codegen_llvm/back/lto.rs b/src/librustc_codegen_llvm/back/lto.rs
index b3be3d09f17..d0b065ccc84 100644
--- a/src/librustc_codegen_llvm/back/lto.rs
+++ b/src/librustc_codegen_llvm/back/lto.rs
@@ -541,7 +541,7 @@ pub(crate) fn run_pass_manager(cgcx: &CodegenContext<LlvmCodegenBackend>,
     debug!("running the pass manager");
     unsafe {
         let pm = llvm::LLVMCreatePassManager();
-        llvm::LLVMRustAddAnalysisPasses(module.module_llvm.tm, pm, module.module_llvm.llmod());
+        llvm::LLVMAddAnalysisPasses(module.module_llvm.tm, pm);
 
         if config.verify_llvm_ir {
             let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr().cast());
diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs
index 6cc7b0b4b1e..07ac76cec99 100644
--- a/src/librustc_codegen_llvm/back/write.rs
+++ b/src/librustc_codegen_llvm/back/write.rs
@@ -365,27 +365,13 @@ pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
 
             add_sanitizer_passes(config, &mut extra_passes);
 
-            for pass_name in &cgcx.plugin_passes {
-                if let Some(pass) = find_pass(pass_name) {
-                    extra_passes.push(pass);
-                } else {
-                    diag_handler.err(&format!("a plugin asked for LLVM pass \
-                                               `{}` but LLVM does not \
-                                               recognize it", pass_name));
-                }
-
-                if pass_name == "name-anon-globals" {
-                    have_name_anon_globals_pass = true;
-                }
-            }
-
             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
             // we'll get errors in LLVM.
             let using_thin_buffers = config.bitcode_needed();
             if !config.no_prepopulate_passes {
-                llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
-                llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
+                llvm::LLVMAddAnalysisPasses(tm, fpm);
+                llvm::LLVMAddAnalysisPasses(tm, mpm);
                 let opt_level = to_llvm_opt_settings(opt_level).0;
                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
                     (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
@@ -509,7 +495,7 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
         {
             let cpm = llvm::LLVMCreatePassManager();
-            llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
+            llvm::LLVMAddAnalysisPasses(tm, cpm);
             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
             f(cpm)
         }
diff --git a/src/librustc_codegen_llvm/lib.rs b/src/librustc_codegen_llvm/lib.rs
index e7562c399b2..acc221f0657 100644
--- a/src/librustc_codegen_llvm/lib.rs
+++ b/src/librustc_codegen_llvm/lib.rs
@@ -30,6 +30,7 @@ extern crate libc;
 #[macro_use] extern crate rustc;
 extern crate rustc_target;
 #[macro_use] extern crate rustc_data_structures;
+extern crate rustc_feature;
 extern crate rustc_index;
 extern crate rustc_incremental;
 extern crate rustc_codegen_utils;
diff --git a/src/librustc_codegen_llvm/llvm/ffi.rs b/src/librustc_codegen_llvm/llvm/ffi.rs
index 241ca695e5f..a49e863fa21 100644
--- a/src/librustc_codegen_llvm/llvm/ffi.rs
+++ b/src/librustc_codegen_llvm/llvm/ffi.rs
@@ -1341,6 +1341,8 @@ extern "C" {
 
     pub fn LLVMInitializePasses();
 
+    pub fn LLVMAddAnalysisPasses(T: &'a TargetMachine, PM: &PassManager<'a>);
+
     pub fn LLVMPassManagerBuilderCreate() -> &'static mut PassManagerBuilder;
     pub fn LLVMPassManagerBuilderDispose(PMB: &'static mut PassManagerBuilder);
     pub fn LLVMPassManagerBuilderSetSizeLevel(PMB: &PassManagerBuilder, Value: Bool);
@@ -1703,7 +1705,6 @@ extern "C" {
                                        EmitStackSizeSection: bool)
                                        -> Option<&'static mut TargetMachine>;
     pub fn LLVMRustDisposeTargetMachine(T: &'static mut TargetMachine);
-    pub fn LLVMRustAddAnalysisPasses(T: &'a TargetMachine, PM: &PassManager<'a>, M: &'a Module);
     pub fn LLVMRustAddBuilderLibraryInfo(PMB: &'a PassManagerBuilder,
                                          M: &'a Module,
                                          DisableSimplifyLibCalls: bool);
diff --git a/src/librustc_codegen_llvm/llvm_util.rs b/src/librustc_codegen_llvm/llvm_util.rs
index 290ca409261..72612c4704e 100644
--- a/src/librustc_codegen_llvm/llvm_util.rs
+++ b/src/librustc_codegen_llvm/llvm_util.rs
@@ -6,7 +6,7 @@ use rustc::session::config::PrintRequest;
 use rustc_target::spec::{MergeFunctions, PanicStrategy};
 use libc::c_int;
 use std::ffi::CString;
-use syntax::feature_gate::UnstableFeatures;
+use rustc_feature::UnstableFeatures;
 use syntax::symbol::sym;
 
 use std::str;
@@ -108,6 +108,8 @@ const ARM_WHITELIST: &[(&str, Option<Symbol>)] = &[
     ("rclass", Some(sym::arm_target_feature)),
     ("dsp", Some(sym::arm_target_feature)),
     ("neon", Some(sym::arm_target_feature)),
+    ("crc", Some(sym::arm_target_feature)),
+    ("crypto", Some(sym::arm_target_feature)),
     ("v5te", Some(sym::arm_target_feature)),
     ("v6", Some(sym::arm_target_feature)),
     ("v6k", Some(sym::arm_target_feature)),
diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs
index 9d3e57449f8..863b41ec15e 100644
--- a/src/librustc_codegen_ssa/back/write.rs
+++ b/src/librustc_codegen_ssa/back/write.rs
@@ -231,8 +231,6 @@ pub struct CodegenContext<B: WriteBackendMethods> {
     pub total_cgus: usize,
     // Handler to use for diagnostics produced during codegen.
     pub diag_emitter: SharedEmitter,
-    // LLVM passes added by plugins.
-    pub plugin_passes: Vec<String>,
     // LLVM optimizations for which we want to print remarks.
     pub remark: Passes,
     // Worker thread number
@@ -1028,7 +1026,6 @@ fn start_executing_work<B: ExtraBackendMethods>(
         time_passes: sess.time_extended(),
         prof: sess.prof.clone(),
         exported_symbols,
-        plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
         remark: sess.opts.cg.remark.clone(),
         worker: 0,
         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
diff --git a/src/librustc_codegen_ssa/mir/block.rs b/src/librustc_codegen_ssa/mir/block.rs
index 14be0e80fb4..d76392f7570 100644
--- a/src/librustc_codegen_ssa/mir/block.rs
+++ b/src/librustc_codegen_ssa/mir/block.rs
@@ -528,18 +528,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
             _ => FnAbi::new(&bx, sig, &extra_args)
         };
 
-        // This should never be reachable at runtime:
-        // We should only emit a call to this intrinsic in #[cfg(miri)] mode,
-        // which means that we will never actually use the generate object files
-        // (we will just be interpreting the MIR)
-        //
-        // Note that we still need to be able to codegen *something* for this intrisnic:
-        // Miri currently uses Xargo to build a special libstd. As a side effect,
-        // we generate normal object files for libstd - while these are never used,
-        // we still need to be able to build them.
+        // For normal codegen, this Miri-specific intrinsic is just a NOP.
         if intrinsic == Some("miri_start_panic") {
-            bx.abort();
-            bx.unreachable();
+            let target = destination.as_ref().unwrap().1;
+            helper.maybe_sideeffect(self.mir, &mut bx, &[target]);
+            helper.funclet_br(self, &mut bx, target);
             return;
         }
 
diff --git a/src/librustc_driver/Cargo.toml b/src/librustc_driver/Cargo.toml
index 2b7e4d35248..d1cb4cbeb9b 100644
--- a/src/librustc_driver/Cargo.toml
+++ b/src/librustc_driver/Cargo.toml
@@ -19,6 +19,7 @@ rustc_target = { path = "../librustc_target" }
 rustc_lint = { path = "../librustc_lint" }
 rustc_data_structures = { path = "../librustc_data_structures" }
 errors = { path = "../librustc_errors", package = "rustc_errors" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_metadata = { path = "../librustc_metadata" }
 rustc_mir = { path = "../librustc_mir" }
 rustc_parse = { path = "../librustc_parse" }
diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs
index 13829b842fd..93f4e73ccc3 100644
--- a/src/librustc_driver/lib.rs
+++ b/src/librustc_driver/lib.rs
@@ -41,10 +41,10 @@ use rustc::util::common::{set_time_depth, time, print_time_passes_entry, ErrorRe
 use rustc_metadata::locator;
 use rustc_codegen_utils::codegen_backend::CodegenBackend;
 use errors::{PResult, registry::Registry};
-use rustc_interface::interface;
+use rustc_interface::{interface, Queries};
 use rustc_interface::util::get_codegen_sysroot;
 use rustc_data_structures::sync::SeqCst;
-
+use rustc_feature::{find_gated_cfg, UnstableFeatures};
 use rustc_serialize::json::ToJson;
 
 use std::borrow::Cow;
@@ -61,10 +61,9 @@ use std::str;
 use std::time::Instant;
 
 use syntax::ast;
-use syntax::source_map::FileLoader;
-use syntax::feature_gate::{GatedCfg, UnstableFeatures};
-use syntax::symbol::sym;
-use syntax_pos::{DUMMY_SP, FileName};
+use syntax_pos::source_map::FileLoader;
+use syntax_pos::symbol::sym;
+use syntax_pos::FileName;
 
 pub mod pretty;
 mod args;
@@ -99,17 +98,29 @@ pub trait Callbacks {
     fn config(&mut self, _config: &mut interface::Config) {}
     /// Called after parsing. Return value instructs the compiler whether to
     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
-    fn after_parsing(&mut self, _compiler: &interface::Compiler) -> Compilation {
+    fn after_parsing<'tcx>(
+        &mut self,
+        _compiler: &interface::Compiler,
+        _queries: &'tcx Queries<'tcx>,
+    ) -> Compilation {
         Compilation::Continue
     }
     /// Called after expansion. Return value instructs the compiler whether to
     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
-    fn after_expansion(&mut self, _compiler: &interface::Compiler) -> Compilation {
+    fn after_expansion<'tcx>(
+        &mut self,
+        _compiler: &interface::Compiler,
+        _queries: &'tcx Queries<'tcx>,
+    ) -> Compilation {
         Compilation::Continue
     }
     /// Called after analysis. Return value instructs the compiler whether to
     /// continue the compilation afterwards (defaults to `Compilation::Continue`)
-    fn after_analysis(&mut self, _compiler: &interface::Compiler) -> Compilation {
+    fn after_analysis<'tcx>(
+        &mut self,
+        _compiler: &interface::Compiler,
+        _queries: &'tcx Queries<'tcx>,
+    ) -> Compilation {
         Compilation::Continue
     }
 }
@@ -283,120 +294,127 @@ pub fn run_compiler(
             return sess.compile_status();
         }
 
-        compiler.parse()?;
-
-        if let Some(ppm) = &sess.opts.pretty {
-            if ppm.needs_ast_map() {
-                compiler.global_ctxt()?.peek_mut().enter(|tcx| {
-                    let expanded_crate = compiler.expansion()?.take().0;
-                    pretty::print_after_hir_lowering(
-                        tcx,
-                        compiler.input(),
-                        &expanded_crate,
+        let linker = compiler.enter(|queries| {
+            let early_exit = || sess.compile_status().map(|_| None);
+            queries.parse()?;
+
+            if let Some(ppm) = &sess.opts.pretty {
+                if ppm.needs_ast_map() {
+                    queries.global_ctxt()?.peek_mut().enter(|tcx| {
+                        let expanded_crate = queries.expansion()?.take().0;
+                        pretty::print_after_hir_lowering(
+                            tcx,
+                            compiler.input(),
+                            &expanded_crate,
+                            *ppm,
+                            compiler.output_file().as_ref().map(|p| &**p),
+                        );
+                        Ok(())
+                    })?;
+                } else {
+                    let krate = queries.parse()?.take();
+                    pretty::print_after_parsing(
+                        sess,
+                        &compiler.input(),
+                        &krate,
                         *ppm,
                         compiler.output_file().as_ref().map(|p| &**p),
                     );
-                    Ok(())
-                })?;
-            } else {
-                let krate = compiler.parse()?.take();
-                pretty::print_after_parsing(
-                    sess,
-                    &compiler.input(),
-                    &krate,
-                    *ppm,
-                    compiler.output_file().as_ref().map(|p| &**p),
-                );
+                }
+                return early_exit();
             }
-            return sess.compile_status();
-        }
 
-        if callbacks.after_parsing(compiler) == Compilation::Stop {
-            return sess.compile_status();
-        }
+            if callbacks.after_parsing(compiler, queries) == Compilation::Stop {
+                return early_exit();
+            }
 
-        if sess.opts.debugging_opts.parse_only ||
-           sess.opts.debugging_opts.show_span.is_some() ||
-           sess.opts.debugging_opts.ast_json_noexpand {
-            return sess.compile_status();
-        }
+            if sess.opts.debugging_opts.parse_only ||
+               sess.opts.debugging_opts.show_span.is_some() ||
+               sess.opts.debugging_opts.ast_json_noexpand {
+               return early_exit();
+            }
 
-        {
-            let (_, lint_store) = &*compiler.register_plugins()?.peek();
+            {
+                let (_, lint_store) = &*queries.register_plugins()?.peek();
 
-            // Lint plugins are registered; now we can process command line flags.
-            if sess.opts.describe_lints {
-                describe_lints(&sess, &lint_store, true);
-                return sess.compile_status();
+                // Lint plugins are registered; now we can process command line flags.
+                if sess.opts.describe_lints {
+                    describe_lints(&sess, &lint_store, true);
+                    return early_exit();
+                }
             }
-        }
 
-        compiler.expansion()?;
-        if callbacks.after_expansion(compiler) == Compilation::Stop {
-            return sess.compile_status();
-        }
+            queries.expansion()?;
+            if callbacks.after_expansion(compiler, queries) == Compilation::Stop {
+                return early_exit();
+            }
 
-        compiler.prepare_outputs()?;
+            queries.prepare_outputs()?;
 
-        if sess.opts.output_types.contains_key(&OutputType::DepInfo)
-            && sess.opts.output_types.len() == 1
-        {
-            return sess.compile_status();
-        }
+            if sess.opts.output_types.contains_key(&OutputType::DepInfo)
+                && sess.opts.output_types.len() == 1
+            {
+                return early_exit();
+            }
 
-        compiler.global_ctxt()?;
+            queries.global_ctxt()?;
 
-        if sess.opts.debugging_opts.no_analysis ||
-           sess.opts.debugging_opts.ast_json {
-            return sess.compile_status();
-        }
+            if sess.opts.debugging_opts.no_analysis ||
+               sess.opts.debugging_opts.ast_json {
+                   return early_exit();
+            }
 
-        if sess.opts.debugging_opts.save_analysis {
-            let expanded_crate = &compiler.expansion()?.peek().0;
-            let crate_name = compiler.crate_name()?.peek().clone();
-            compiler.global_ctxt()?.peek_mut().enter(|tcx| {
-                let result = tcx.analysis(LOCAL_CRATE);
-
-                time(sess, "save analysis", || {
-                    save::process_crate(
-                        tcx,
-                        &expanded_crate,
-                        &crate_name,
-                        &compiler.input(),
-                        None,
-                        DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name)
-                    )
-                });
-
-                result
-                // AST will be dropped *after* the `after_analysis` callback
-                // (needed by the RLS)
-            })?;
-        } else {
-            // Drop AST after creating GlobalCtxt to free memory
-            mem::drop(compiler.expansion()?.take());
-        }
+            if sess.opts.debugging_opts.save_analysis {
+                let expanded_crate = &queries.expansion()?.peek().0;
+                let crate_name = queries.crate_name()?.peek().clone();
+                queries.global_ctxt()?.peek_mut().enter(|tcx| {
+                    let result = tcx.analysis(LOCAL_CRATE);
+
+                    time(sess, "save analysis", || {
+                        save::process_crate(
+                            tcx,
+                            &expanded_crate,
+                            &crate_name,
+                            &compiler.input(),
+                            None,
+                            DumpHandler::new(
+                                compiler.output_dir().as_ref().map(|p| &**p), &crate_name
+                            )
+                        )
+                    });
+
+                    result
+                    // AST will be dropped *after* the `after_analysis` callback
+                    // (needed by the RLS)
+                })?;
+            } else {
+                // Drop AST after creating GlobalCtxt to free memory
+                mem::drop(queries.expansion()?.take());
+            }
 
-        compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
+            queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?;
 
-        if callbacks.after_analysis(compiler) == Compilation::Stop {
-            return sess.compile_status();
-        }
+            if callbacks.after_analysis(compiler, queries) == Compilation::Stop {
+                return early_exit();
+            }
 
-        if sess.opts.debugging_opts.save_analysis {
-            mem::drop(compiler.expansion()?.take());
-        }
+            if sess.opts.debugging_opts.save_analysis {
+                mem::drop(queries.expansion()?.take());
+            }
 
-        compiler.ongoing_codegen()?;
+            queries.ongoing_codegen()?;
 
-        // Drop GlobalCtxt after starting codegen to free memory
-        mem::drop(compiler.global_ctxt()?.take());
+            if sess.opts.debugging_opts.print_type_sizes {
+                sess.code_stats.print_type_sizes();
+            }
 
-        if sess.opts.debugging_opts.print_type_sizes {
-            sess.code_stats.print_type_sizes();
-        }
+            let linker = queries.linker()?;
+            Ok(Some(linker))
+        })?;
 
-        compiler.link()?;
+        if let Some(linker) = linker {
+            linker.link()?
+        }
 
         if sess.opts.debugging_opts.perf_stats {
             sess.print_perf_stats();
@@ -677,12 +695,6 @@ impl RustcDefaultCalls {
                         .is_nightly_build();
 
                     let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
-                        let gated_cfg = GatedCfg::gate(&ast::MetaItem {
-                            path: ast::Path::from_ident(ast::Ident::with_dummy_span(name)),
-                            kind: ast::MetaItemKind::Word,
-                            span: DUMMY_SP,
-                        });
-
                         // Note that crt-static is a specially recognized cfg
                         // directive that's printed out here as part of
                         // rust-lang/rust#37406, but in general the
@@ -693,10 +705,11 @@ impl RustcDefaultCalls {
                         // through to build scripts.
                         let value = value.as_ref().map(|s| s.as_str());
                         let value = value.as_ref().map(|s| s.as_ref());
-                        if name != sym::target_feature || value != Some("crt-static") {
-                            if !allow_unstable_cfg && gated_cfg.is_some() {
-                                return None
-                            }
+                        if (name != sym::target_feature || value != Some("crt-static"))
+                            && !allow_unstable_cfg
+                            && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
+                        {
+                            return None;
                         }
 
                         if let Some(value) = value {
diff --git a/src/librustc_error_codes/error_codes.rs b/src/librustc_error_codes/error_codes.rs
index 709ccce517a..7f111b42403 100644
--- a/src/librustc_error_codes/error_codes.rs
+++ b/src/librustc_error_codes/error_codes.rs
@@ -107,6 +107,7 @@ E0199: include_str!("./error_codes/E0199.md"),
 E0200: include_str!("./error_codes/E0200.md"),
 E0201: include_str!("./error_codes/E0201.md"),
 E0202: include_str!("./error_codes/E0202.md"),
+E0203: include_str!("./error_codes/E0203.md"),
 E0204: include_str!("./error_codes/E0204.md"),
 E0205: include_str!("./error_codes/E0205.md"),
 E0206: include_str!("./error_codes/E0206.md"),
@@ -446,8 +447,6 @@ E0745: include_str!("./error_codes/E0745.md"),
 //  E0190, // deprecated: can only cast a &-pointer to an &-object
 //  E0194, // merged into E0403
 //  E0196, // cannot determine a type for this closure
-    E0203, // type parameter has more than one relaxed default bound,
-           // and only one is supported
     E0208,
 //  E0209, // builtin traits can only be implemented on structs or enums
     E0212, // cannot extract an associated type from a higher-ranked trait bound
diff --git a/src/librustc_error_codes/error_codes/E0080.md b/src/librustc_error_codes/error_codes/E0080.md
index 262bf00d385..273238a943b 100644
--- a/src/librustc_error_codes/error_codes/E0080.md
+++ b/src/librustc_error_codes/error_codes/E0080.md
@@ -1,14 +1,18 @@
-This error indicates that the compiler was unable to sensibly evaluate a
-constant expression that had to be evaluated. Attempting to divide by 0
-or causing integer overflow are two ways to induce this error. For example:
+A constant value failed to get evaluated.
+
+Erroneous code example:
 
 ```compile_fail,E0080
 enum Enum {
     X = (1 << 500),
-    Y = (1 / 0)
+    Y = (1 / 0),
 }
 ```
 
+This error indicates that the compiler was unable to sensibly evaluate a
+constant expression that had to be evaluated. Attempting to divide by 0
+or causing an integer overflow are two ways to induce this error.
+
 Ensure that the expressions given can be evaluated as the desired integer type.
 See the FFI section of the Reference for more information about using a custom
 integer type:
diff --git a/src/librustc_error_codes/error_codes/E0081.md b/src/librustc_error_codes/error_codes/E0081.md
index ec88ca9765e..fd5eca68e21 100644
--- a/src/librustc_error_codes/error_codes/E0081.md
+++ b/src/librustc_error_codes/error_codes/E0081.md
@@ -1,21 +1,23 @@
-Enum discriminants are used to differentiate enum variants stored in memory.
-This error indicates that the same value was used for two or more variants,
-making them impossible to tell apart.
+A discrimant value is present more than once.
+
+Erroneous code example:
 
 ```compile_fail,E0081
-// Bad.
 enum Enum {
     P = 3,
-    X = 3,
+    X = 3, // error!
     Y = 5,
 }
 ```
 
+Enum discriminants are used to differentiate enum variants stored in memory.
+This error indicates that the same value was used for two or more variants,
+making it impossible to distinguish them.
+
 ```
-// Good.
 enum Enum {
     P,
-    X = 3,
+    X = 3, // ok!
     Y = 5,
 }
 ```
@@ -27,7 +29,7 @@ variants.
 ```compile_fail,E0081
 enum Bad {
     X,
-    Y = 0
+    Y = 0, // error!
 }
 ```
 
diff --git a/src/librustc_error_codes/error_codes/E0091.md b/src/librustc_error_codes/error_codes/E0091.md
index 2a092402429..03cb3280371 100644
--- a/src/librustc_error_codes/error_codes/E0091.md
+++ b/src/librustc_error_codes/error_codes/E0091.md
@@ -1,5 +1,6 @@
-You gave an unnecessary type or const parameter in a type alias. Erroneous
-code example:
+An unnecessary type or const parameter was given in a type alias.
+
+Erroneous code example:
 
 ```compile_fail,E0091
 type Foo<T> = u32; // error: type parameter `T` is unused
diff --git a/src/librustc_error_codes/error_codes/E0203.md b/src/librustc_error_codes/error_codes/E0203.md
new file mode 100644
index 00000000000..1edb519275f
--- /dev/null
+++ b/src/librustc_error_codes/error_codes/E0203.md
@@ -0,0 +1,18 @@
+Having multiple relaxed default bounds is unsupported.
+
+Erroneous code example:
+
+```compile_fail,E0203
+struct Bad<T: ?Sized + ?Send>{
+    inner: T
+}
+```
+
+Here the type `T` cannot have a relaxed bound for multiple default traits
+(`Sized` and `Send`). This can be fixed by only using one relaxed bound.
+
+```
+struct Good<T: ?Sized>{
+    inner: T
+}
+```
diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs
index ea779982ba9..45191375748 100644
--- a/src/librustc_errors/emitter.rs
+++ b/src/librustc_errors/emitter.rs
@@ -835,7 +835,7 @@ impl EmitterWriter {
             return vec![];
         }
 
-        // Write the colunmn separator.
+        // Write the column separator.
         //
         // After this we will have:
         //
@@ -906,7 +906,7 @@ impl EmitterWriter {
         //   |  __________
         //   | |    |
         //   | |
-        // 3 |
+        // 3 | |
         // 4 | | }
         //   | |_
         for &(pos, annotation) in &annotations_position {
@@ -920,7 +920,7 @@ impl EmitterWriter {
             if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
                 for p in line_offset + 1..=line_offset + pos {
                     buffer.putc(p,
-                                code_offset + annotation.start_col - margin.computed_left,
+                                (code_offset + annotation.start_col).saturating_sub(left),
                                 '|',
                                 style);
                 }
diff --git a/src/librustc_feature/Cargo.toml b/src/librustc_feature/Cargo.toml
new file mode 100644
index 00000000000..40ce922947b
--- /dev/null
+++ b/src/librustc_feature/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+authors = ["The Rust Project Developers"]
+name = "rustc_feature"
+version = "0.0.0"
+edition = "2018"
+
+[lib]
+name = "rustc_feature"
+path = "lib.rs"
+doctest = false
+
+[dependencies]
+rustc_data_structures = { path = "../librustc_data_structures" }
+lazy_static = "1.0.0"
+syntax_pos = { path = "../libsyntax_pos" }
diff --git a/src/libsyntax/feature_gate/accepted.rs b/src/librustc_feature/accepted.rs
index dab83f48a03..fec5a7f1a45 100644
--- a/src/libsyntax/feature_gate/accepted.rs
+++ b/src/librustc_feature/accepted.rs
@@ -1,7 +1,7 @@
 //! List of the accepted feature gates.
 
-use crate::symbol::sym;
 use super::{State, Feature};
+use syntax_pos::symbol::sym;
 
 macro_rules! declare_features {
     ($(
diff --git a/src/libsyntax/feature_gate/active.rs b/src/librustc_feature/active.rs
index b04b30aa6bc..16d8ada9f24 100644
--- a/src/libsyntax/feature_gate/active.rs
+++ b/src/librustc_feature/active.rs
@@ -2,10 +2,9 @@
 
 use super::{State, Feature};
 
-use crate::edition::Edition;
-use crate::symbol::{Symbol, sym};
-
+use syntax_pos::edition::Edition;
 use syntax_pos::Span;
+use syntax_pos::symbol::{Symbol, sym};
 
 macro_rules! set {
     ($field: ident) => {{
@@ -37,7 +36,7 @@ macro_rules! declare_features {
             ),+];
 
         /// A set of features to be used by later passes.
-        #[derive(Clone)]
+        #[derive(Clone, Default)]
         pub struct Features {
             /// `#![feature]` attrs for language features, for error reporting.
             pub declared_lang_features: Vec<(Symbol, Span, Option<Symbol>)>,
@@ -50,17 +49,7 @@ macro_rules! declare_features {
         }
 
         impl Features {
-            pub fn new() -> Features {
-                Features {
-                    declared_lang_features: Vec::new(),
-                    declared_lib_features: Vec::new(),
-                    $($feature: false),+
-                }
-            }
-
-            pub fn walk_feature_fields<F>(&self, mut f: F)
-                where F: FnMut(&str, bool)
-            {
+            pub fn walk_feature_fields(&self, mut f: impl FnMut(&str, bool)) {
                 $(f(stringify!($feature), self.$feature);)+
             }
         }
@@ -535,6 +524,9 @@ declare_features! (
     /// Allows the use of `if` and `match` in constants.
     (active, const_if_match, "1.41.0", Some(49146), None),
 
+    /// Allows the use of `#[cfg(sanitize = "option")]`; set when -Zsanitizer is used.
+    (active, cfg_sanitize, "1.41.0", Some(39699), None),
+
     // -------------------------------------------------------------------------
     // feature-group-end: actual feature gates
     // -------------------------------------------------------------------------
diff --git a/src/libsyntax/feature_gate/builtin_attrs.rs b/src/librustc_feature/builtin_attrs.rs
index a9f41633f30..4fa0198d871 100644
--- a/src/libsyntax/feature_gate/builtin_attrs.rs
+++ b/src/librustc_feature/builtin_attrs.rs
@@ -3,17 +3,10 @@
 use AttributeType::*;
 use AttributeGate::*;
 
-use super::check::{emit_feature_err, GateIssue};
-use super::check::{Stability, EXPLAIN_ALLOW_INTERNAL_UNSAFE, EXPLAIN_ALLOW_INTERNAL_UNSTABLE};
-use super::active::Features;
+use crate::{Features, Stability};
 
-use crate::ast;
-use crate::attr::AttributeTemplate;
-use crate::sess::ParseSess;
-use crate::symbol::{Symbol, sym};
-
-use syntax_pos::Span;
 use rustc_data_structures::fx::FxHashMap;
+use syntax_pos::symbol::{Symbol, sym};
 use lazy_static::lazy_static;
 
 type GateFn = fn(&Features) -> bool;
@@ -24,39 +17,20 @@ macro_rules! cfg_fn {
     }
 }
 
+pub type GatedCfg = (Symbol, Symbol, GateFn);
+
 /// `cfg(...)`'s that are feature gated.
-const GATED_CFGS: &[(Symbol, Symbol, GateFn)] = &[
+const GATED_CFGS: &[GatedCfg] = &[
     // (name in cfg, feature, function to check if the feature is enabled)
     (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)),
     (sym::target_has_atomic, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
     (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
+    (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
 ];
 
-#[derive(Debug)]
-pub struct GatedCfg {
-    span: Span,
-    index: usize,
-}
-
-impl GatedCfg {
-    pub fn gate(cfg: &ast::MetaItem) -> Option<GatedCfg> {
-        GATED_CFGS.iter()
-                  .position(|info| cfg.check_name(info.0))
-                  .map(|idx| {
-                      GatedCfg {
-                          span: cfg.span,
-                          index: idx
-                      }
-                  })
-    }
-
-    pub fn check_and_emit(&self, sess: &ParseSess, features: &Features) {
-        let (cfg, feature, has_feature) = GATED_CFGS[self.index];
-        if !has_feature(features) && !self.span.allows_unstable(feature) {
-            let explain = format!("`cfg({})` is experimental and subject to change", cfg);
-            emit_feature_err(sess, feature, self.span, GateIssue::Language, &explain);
-        }
-    }
+/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
+pub fn find_gated_cfg(pred: impl Fn(Symbol) -> bool) -> Option<&'static GatedCfg> {
+    GATED_CFGS.iter().find(|(cfg_sym, ..)| pred(*cfg_sym))
 }
 
 // If you change this, please modify `src/doc/unstable-book` as well. You must
@@ -108,6 +82,21 @@ impl AttributeGate {
     }
 }
 
+/// A template that the attribute input must match.
+/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
+#[derive(Clone, Copy)]
+pub struct AttributeTemplate {
+    pub word: bool,
+    pub list: Option<&'static str>,
+    pub name_value_str: Option<&'static str>,
+}
+
+impl AttributeTemplate {
+    pub fn only_word() -> Self {
+        Self { word: true, list: None, name_value_str: None }
+    }
+}
+
 /// A convenience macro for constructing attribute templates.
 /// E.g., `template!(Word, List: "description")` means that the attribute
 /// supports forms `#[attr]` and `#[attr(description)]`.
@@ -295,7 +284,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
         )
     ),
     (
-        sym::plugin, CrateLevel, template!(List: "name|name(args)"),
+        sym::plugin, CrateLevel, template!(List: "name"),
         Gated(
             Stability::Deprecated(
                 "https://github.com/rust-lang/rust/pull/64675",
@@ -361,9 +350,12 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
     ),
     gated!(
         allow_internal_unstable, Normal, template!(Word, List: "feat1, feat2, ..."),
-        EXPLAIN_ALLOW_INTERNAL_UNSTABLE,
+        "allow_internal_unstable side-steps feature gating and stability checks",
+    ),
+    gated!(
+        allow_internal_unsafe, Normal, template!(Word),
+        "allow_internal_unsafe side-steps the unsafe_code lint",
     ),
-    gated!(allow_internal_unsafe, Normal, template!(Word), EXPLAIN_ALLOW_INTERNAL_UNSAFE),
 
     // ==========================================================================
     // Internal attributes: Type system related:
@@ -587,14 +579,10 @@ pub fn deprecated_attributes() -> Vec<&'static BuiltinAttribute> {
     BUILTIN_ATTRIBUTES.iter().filter(|(.., gate)| gate.is_deprecated()).collect()
 }
 
-pub fn is_builtin_attr_name(name: ast::Name) -> bool {
+pub fn is_builtin_attr_name(name: Symbol) -> bool {
     BUILTIN_ATTRIBUTE_MAP.get(&name).is_some()
 }
 
-pub fn is_builtin_attr(attr: &ast::Attribute) -> bool {
-    attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)).is_some()
-}
-
 lazy_static! {
     pub static ref BUILTIN_ATTRIBUTE_MAP: FxHashMap<Symbol, &'static BuiltinAttribute> = {
         let mut map = FxHashMap::default();
diff --git a/src/librustc_feature/lib.rs b/src/librustc_feature/lib.rs
new file mode 100644
index 00000000000..c38bb3740af
--- /dev/null
+++ b/src/librustc_feature/lib.rs
@@ -0,0 +1,137 @@
+//! # Feature gates
+//!
+//! This crate declares the set of past and present unstable features in the compiler.
+//! Feature gate checking itself is done in `libsyntax/feature_gate/check.rs` at the moment.
+//!
+//! Features are enabled in programs via the crate-level attributes of
+//! `#![feature(...)]` with a comma-separated list of features.
+//!
+//! For the purpose of future feature-tracking, once a feature gate is added,
+//! even if it is stabilized or removed, *do not remove it*. Instead, move the
+//! symbol to the `accepted` or `removed` modules respectively.
+
+mod accepted;
+mod removed;
+mod active;
+mod builtin_attrs;
+
+use std::fmt;
+use std::num::NonZeroU32;
+use syntax_pos::{Span, edition::Edition, symbol::Symbol};
+
+#[derive(Clone, Copy)]
+pub enum State {
+    Accepted,
+    Active { set: fn(&mut Features, Span) },
+    Removed { reason: Option<&'static str> },
+    Stabilized { reason: Option<&'static str> },
+}
+
+impl fmt::Debug for State {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            State::Accepted { .. } => write!(f, "accepted"),
+            State::Active { .. } => write!(f, "active"),
+            State::Removed { .. } => write!(f, "removed"),
+            State::Stabilized { .. } => write!(f, "stabilized"),
+        }
+    }
+}
+
+#[derive(Debug, Clone)]
+pub struct Feature {
+    pub state: State,
+    pub name: Symbol,
+    pub since: &'static str,
+    issue: Option<u32>,  // FIXME: once #58732 is done make this an Option<NonZeroU32>
+    pub edition: Option<Edition>,
+    description: &'static str,
+}
+
+impl Feature {
+    fn issue(&self) -> Option<NonZeroU32> {
+        self.issue.and_then(|i| NonZeroU32::new(i))
+    }
+}
+
+#[derive(Copy, Clone, Debug)]
+pub enum Stability {
+    Unstable,
+    // First argument is tracking issue link; second argument is an optional
+    // help message, which defaults to "remove this attribute".
+    Deprecated(&'static str, Option<&'static str>),
+}
+
+#[derive(Clone, Copy, Hash)]
+pub enum UnstableFeatures {
+    /// Hard errors for unstable features are active, as on beta/stable channels.
+    Disallow,
+    /// Allow features to be activated, as on nightly.
+    Allow,
+    /// Errors are bypassed for bootstrapping. This is required any time
+    /// during the build that feature-related lints are set to warn or above
+    /// because the build turns on warnings-as-errors and uses lots of unstable
+    /// features. As a result, this is always required for building Rust itself.
+    Cheat
+}
+
+impl UnstableFeatures {
+    pub fn from_environment() -> UnstableFeatures {
+        // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
+        let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
+        // `true` if we should enable unstable features for bootstrapping.
+        let bootstrap = std::env::var("RUSTC_BOOTSTRAP").is_ok();
+        match (disable_unstable_features, bootstrap) {
+            (_, true) => UnstableFeatures::Cheat,
+            (true, _) => UnstableFeatures::Disallow,
+            (false, _) => UnstableFeatures::Allow
+        }
+    }
+
+    pub fn is_nightly_build(&self) -> bool {
+        match *self {
+            UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
+            UnstableFeatures::Disallow => false,
+        }
+    }
+}
+
+fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
+    if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
+        // FIXME (#28244): enforce that active features have issue numbers
+        // assert!(info.issue().is_some())
+        info.issue()
+    } else {
+        // search in Accepted, Removed, or Stable Removed features
+        let found = ACCEPTED_FEATURES
+            .iter()
+            .chain(REMOVED_FEATURES)
+            .chain(STABLE_REMOVED_FEATURES)
+            .find(|t| t.name == feature);
+        match found {
+            Some(found) => found.issue(),
+            None => panic!("feature `{}` is not declared anywhere", feature),
+        }
+    }
+}
+
+pub enum GateIssue {
+    Language,
+    Library(Option<NonZeroU32>)
+}
+
+pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> {
+    match issue {
+        GateIssue::Language => find_lang_feature_issue(feature),
+        GateIssue::Library(lib) => lib,
+    }
+}
+
+pub use accepted::ACCEPTED_FEATURES;
+pub use active::{ACTIVE_FEATURES, Features, INCOMPLETE_FEATURES};
+pub use removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
+pub use builtin_attrs::{
+    AttributeGate, AttributeTemplate, AttributeType, find_gated_cfg, GatedCfg,
+    BuiltinAttribute, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP,
+    deprecated_attributes, is_builtin_attr_name,
+};
diff --git a/src/libsyntax/feature_gate/removed.rs b/src/librustc_feature/removed.rs
index f0aa74c65df..340bd32fb8a 100644
--- a/src/libsyntax/feature_gate/removed.rs
+++ b/src/librustc_feature/removed.rs
@@ -1,7 +1,7 @@
 //! List of the removed feature gates.
 
-use crate::symbol::sym;
 use super::{State, Feature};
+use syntax_pos::symbol::sym;
 
 macro_rules! declare_features {
     ($(
diff --git a/src/librustc_interface/interface.rs b/src/librustc_interface/interface.rs
index 70ed4aad7b4..beb2465bd4a 100644
--- a/src/librustc_interface/interface.rs
+++ b/src/librustc_interface/interface.rs
@@ -1,4 +1,3 @@
-use crate::queries::Queries;
 use crate::util;
 pub use crate::passes::BoxedResolver;
 
@@ -36,7 +35,6 @@ pub struct Compiler {
     pub(crate) input_path: Option<PathBuf>,
     pub(crate) output_dir: Option<PathBuf>,
     pub(crate) output_file: Option<PathBuf>,
-    pub(crate) queries: Queries,
     pub(crate) crate_name: Option<String>,
     pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut lint::LintStore) + Send + Sync>>,
     pub(crate) override_queries:
@@ -169,7 +167,6 @@ pub fn run_compiler_in_existing_thread_pool<R>(
         input_path: config.input_path,
         output_dir: config.output_dir,
         output_file: config.output_file,
-        queries: Default::default(),
         crate_name: config.crate_name,
         register_lints: config.register_lints,
         override_queries: config.override_queries,
diff --git a/src/librustc_interface/lib.rs b/src/librustc_interface/lib.rs
index 53baf6556fb..76af4342f5c 100644
--- a/src/librustc_interface/lib.rs
+++ b/src/librustc_interface/lib.rs
@@ -18,6 +18,7 @@ pub mod util;
 mod proc_macro_decls;
 
 pub use interface::{run_compiler, Config};
+pub use queries::Queries;
 
 #[cfg(test)]
 mod tests;
diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs
index a745d63426b..f985a5b3755 100644
--- a/src/librustc_interface/passes.rs
+++ b/src/librustc_interface/passes.rs
@@ -3,6 +3,7 @@ use crate::util;
 use crate::proc_macro_decls;
 
 use log::{info, warn, log_enabled};
+use rustc::arena::Arena;
 use rustc::dep_graph::DepGraph;
 use rustc::hir;
 use rustc::hir::lowering::lower_crate;
@@ -22,15 +23,13 @@ use rustc_codegen_ssa::back::link::emit_metadata;
 use rustc_codegen_utils::codegen_backend::CodegenBackend;
 use rustc_codegen_utils::link::filename_for_metadata;
 use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel};
-use rustc_data_structures::sync::{Lrc, ParallelIterator, par_iter};
+use rustc_data_structures::sync::{Lrc, Once, ParallelIterator, par_iter, WorkerLocal};
 use rustc_errors::PResult;
 use rustc_incremental;
-use rustc_metadata::cstore;
 use rustc_mir as mir;
 use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
 use rustc_passes::{self, ast_validation, hir_stats, layout_test};
 use rustc_plugin_impl as plugin;
-use rustc_plugin_impl::registry::Registry;
 use rustc_privacy;
 use rustc_resolve::{Resolver, ResolverArenas};
 use rustc_traits;
@@ -106,8 +105,7 @@ declare_box_region_type!(
     (&mut Resolver<'_>) -> (Result<ast::Crate>, ResolverOutputs)
 );
 
-/// Runs the "early phases" of the compiler: initial `cfg` processing,
-/// loading compiler plugins (including those from `addl_plugins`),
+/// Runs the "early phases" of the compiler: initial `cfg` processing, loading compiler plugins,
 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
 /// harness if one is to be provided, injection of a dependency on the
 /// standard library and prelude, and name resolution.
@@ -209,33 +207,22 @@ pub fn register_plugins<'a>(
         middle::recursion_limit::update_limits(sess, &krate);
     });
 
-    let registrars = time(sess, "plugin loading", || {
-        plugin::load::load_plugins(
-            sess,
-            metadata_loader,
-            &krate,
-            Some(sess.opts.debugging_opts.extra_plugins.clone()),
-        )
-    });
-
     let mut lint_store = rustc_lint::new_lint_store(
         sess.opts.debugging_opts.no_interleave_lints,
         sess.unstable_options(),
     );
+    register_lints(&sess, &mut lint_store);
 
-    (register_lints)(&sess, &mut lint_store);
-
-    let mut registry = Registry::new(sess, &mut lint_store, krate.span);
-
+    let registrars = time(sess, "plugin loading", || {
+        plugin::load::load_plugins(sess, metadata_loader, &krate)
+    });
     time(sess, "plugin registration", || {
+        let mut registry = plugin::Registry { lint_store: &mut lint_store };
         for registrar in registrars {
-            registry.args_hidden = Some(registrar.args);
-            (registrar.fun)(&mut registry);
+            registrar(&mut registry);
         }
     });
 
-    *sess.plugin_llvm_passes.borrow_mut() = registry.llvm_passes;
-
     Ok((krate, Lrc::new(lint_store)))
 }
 
@@ -728,7 +715,7 @@ pub fn default_provide(providers: &mut ty::query::Providers<'_>) {
     rustc_passes::provide(providers);
     rustc_traits::provide(providers);
     middle::region::provide(providers);
-    cstore::provide(providers);
+    rustc_metadata::provide(providers);
     lint::provide(providers);
     rustc_lint::provide(providers);
     rustc_codegen_utils::provide(providers);
@@ -736,97 +723,81 @@ pub fn default_provide(providers: &mut ty::query::Providers<'_>) {
 }
 
 pub fn default_provide_extern(providers: &mut ty::query::Providers<'_>) {
-    cstore::provide_extern(providers);
+    rustc_metadata::provide_extern(providers);
     rustc_codegen_ssa::provide_extern(providers);
 }
 
-declare_box_region_type!(
-    pub BoxedGlobalCtxt,
-    for('tcx),
-    (&'tcx GlobalCtxt<'tcx>) -> ((), ())
-);
+pub struct QueryContext<'tcx>(&'tcx GlobalCtxt<'tcx>);
 
-impl BoxedGlobalCtxt {
+impl<'tcx> QueryContext<'tcx> {
     pub fn enter<F, R>(&mut self, f: F) -> R
     where
-        F: for<'tcx> FnOnce(TyCtxt<'tcx>) -> R,
+        F: FnOnce(TyCtxt<'tcx>) -> R,
     {
-        self.access(|gcx| ty::tls::enter_global(gcx, |tcx| f(tcx)))
+        ty::tls::enter_global(self.0, |tcx| f(tcx))
+    }
+
+    pub fn print_stats(&self) {
+        self.0.queries.print_stats()
     }
 }
 
-pub fn create_global_ctxt(
-    compiler: &Compiler,
+pub fn create_global_ctxt<'tcx>(
+    compiler: &'tcx Compiler,
     lint_store: Lrc<lint::LintStore>,
-    mut hir_forest: hir::map::Forest,
+    hir_forest: &'tcx hir::map::Forest,
     mut resolver_outputs: ResolverOutputs,
     outputs: OutputFilenames,
     crate_name: &str,
-) -> BoxedGlobalCtxt {
-    let sess = compiler.session().clone();
-    let codegen_backend = compiler.codegen_backend().clone();
-    let crate_name = crate_name.to_string();
+    global_ctxt: &'tcx Once<GlobalCtxt<'tcx>>,
+    all_arenas: &'tcx AllArenas,
+    arena: &'tcx WorkerLocal<Arena<'tcx>>,
+) -> QueryContext<'tcx> {
+    let sess = &compiler.session();
     let defs = mem::take(&mut resolver_outputs.definitions);
-    let override_queries = compiler.override_queries;
-
-    let ((), result) = BoxedGlobalCtxt::new(static move || {
-        let sess = &*sess;
 
-        let global_ctxt: Option<GlobalCtxt<'_>>;
-        let arenas = AllArenas::new();
-
-        // Construct the HIR map.
-        let hir_map = time(sess, "indexing HIR", || {
-            hir::map::map_crate(sess, &*resolver_outputs.cstore, &mut hir_forest, &defs)
-        });
-
-        let query_result_on_disk_cache = time(sess, "load query result cache", || {
-            rustc_incremental::load_query_result_cache(sess)
-        });
-
-        let mut local_providers = ty::query::Providers::default();
-        default_provide(&mut local_providers);
-        codegen_backend.provide(&mut local_providers);
-
-        let mut extern_providers = local_providers;
-        default_provide_extern(&mut extern_providers);
-        codegen_backend.provide_extern(&mut extern_providers);
+    // Construct the HIR map.
+    let hir_map = time(sess, "indexing HIR", || {
+        hir::map::map_crate(sess, &*resolver_outputs.cstore, &hir_forest, defs)
+    });
 
-        if let Some(callback) = override_queries {
-            callback(sess, &mut local_providers, &mut extern_providers);
-        }
+    let query_result_on_disk_cache = time(sess, "load query result cache", || {
+        rustc_incremental::load_query_result_cache(sess)
+    });
 
-        let gcx = TyCtxt::create_global_ctxt(
-            sess,
-            lint_store,
-            local_providers,
-            extern_providers,
-            &arenas,
-            resolver_outputs,
-            hir_map,
-            query_result_on_disk_cache,
-            &crate_name,
-            &outputs
-        );
+    let codegen_backend = compiler.codegen_backend();
+    let mut local_providers = ty::query::Providers::default();
+    default_provide(&mut local_providers);
+    codegen_backend.provide(&mut local_providers);
 
-        global_ctxt = Some(gcx);
-        let gcx = global_ctxt.as_ref().unwrap();
+    let mut extern_providers = local_providers;
+    default_provide_extern(&mut extern_providers);
+    codegen_backend.provide_extern(&mut extern_providers);
 
-        ty::tls::enter_global(gcx, |tcx| {
-            // Do some initialization of the DepGraph that can only be done with the
-            // tcx available.
-            time(tcx.sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
-        });
+    if let Some(callback) = compiler.override_queries {
+        callback(sess, &mut local_providers, &mut extern_providers);
+    }
 
-        yield BoxedGlobalCtxt::initial_yield(());
-        box_region_allow_access!(for('tcx), (&'tcx GlobalCtxt<'tcx>), (gcx));
+    let gcx = global_ctxt.init_locking(|| TyCtxt::create_global_ctxt(
+        sess,
+        lint_store,
+        local_providers,
+        extern_providers,
+        &all_arenas,
+        arena,
+        resolver_outputs,
+        hir_map,
+        query_result_on_disk_cache,
+        &crate_name,
+        &outputs
+    ));
 
-        if sess.opts.debugging_opts.query_stats {
-            gcx.queries.print_stats();
-        }
+    // Do some initialization of the DepGraph that can only be done with the tcx available.
+    ty::tls::enter_global(&gcx, |tcx| {
+        time(tcx.sess, "dep graph tcx init", || rustc_incremental::dep_graph_tcx_init(tcx));
     });
 
-    result
+    QueryContext(gcx)
 }
 
 /// Runs the resolution, type-checking, region checking and other
diff --git a/src/librustc_interface/queries.rs b/src/librustc_interface/queries.rs
index 9094f36d44e..6103d42c5db 100644
--- a/src/librustc_interface/queries.rs
+++ b/src/librustc_interface/queries.rs
@@ -1,17 +1,19 @@
 use crate::interface::{Compiler, Result};
-use crate::passes::{self, BoxedResolver, BoxedGlobalCtxt};
+use crate::passes::{self, BoxedResolver, QueryContext};
 
 use rustc_incremental::DepGraphFuture;
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{Lrc, Once, WorkerLocal};
+use rustc_codegen_utils::codegen_backend::CodegenBackend;
 use rustc::session::config::{OutputFilenames, OutputType};
 use rustc::util::common::{time, ErrorReported};
+use rustc::arena::Arena;
 use rustc::hir;
 use rustc::lint;
 use rustc::session::Session;
 use rustc::lint::LintStore;
 use rustc::hir::def_id::LOCAL_CRATE;
 use rustc::ty::steal::Steal;
-use rustc::ty::ResolverOutputs;
+use rustc::ty::{AllArenas, ResolverOutputs, GlobalCtxt};
 use rustc::dep_graph::DepGraph;
 use std::cell::{Ref, RefMut, RefCell};
 use std::rc::Rc;
@@ -44,13 +46,6 @@ impl<T> Query<T> {
             .unwrap()
     }
 
-    /// Returns a stolen query result. Panics if there's already a result.
-    pub fn give(&self, value: T) {
-        let mut result = self.result.borrow_mut();
-        assert!(result.is_none(), "a result already exists");
-        *result = Some(Ok(value));
-    }
-
     /// Borrows the query result using the RefCell. Panics if the result is stolen.
     pub fn peek(&self) -> Ref<'_, T> {
         Ref::map(self.result.borrow(), |r| {
@@ -74,24 +69,54 @@ impl<T> Default for Query<T> {
     }
 }
 
-#[derive(Default)]
-pub(crate) struct Queries {
+pub struct Queries<'tcx> {
+    compiler: &'tcx Compiler,
+    gcx: Once<GlobalCtxt<'tcx>>,
+
+    all_arenas: AllArenas,
+    arena: WorkerLocal<Arena<'tcx>>,
+
     dep_graph_future: Query<Option<DepGraphFuture>>,
     parse: Query<ast::Crate>,
     crate_name: Query<String>,
     register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
     expansion: Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>,
     dep_graph: Query<DepGraph>,
-    lower_to_hir: Query<(Steal<hir::map::Forest>, Steal<ResolverOutputs>)>,
+    lower_to_hir: Query<(&'tcx hir::map::Forest, Steal<ResolverOutputs>)>,
     prepare_outputs: Query<OutputFilenames>,
-    global_ctxt: Query<BoxedGlobalCtxt>,
+    global_ctxt: Query<QueryContext<'tcx>>,
     ongoing_codegen: Query<Box<dyn Any>>,
-    link: Query<()>,
 }
 
-impl Compiler {
+impl<'tcx> Queries<'tcx> {
+    pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
+        Queries {
+            compiler,
+            gcx: Once::new(),
+            all_arenas: AllArenas::new(),
+            arena: WorkerLocal::new(|_| Arena::default()),
+            dep_graph_future: Default::default(),
+            parse: Default::default(),
+            crate_name: Default::default(),
+            register_plugins: Default::default(),
+            expansion: Default::default(),
+            dep_graph: Default::default(),
+            lower_to_hir: Default::default(),
+            prepare_outputs: Default::default(),
+            global_ctxt: Default::default(),
+            ongoing_codegen: Default::default(),
+        }
+    }
+
+    fn session(&self) -> &Lrc<Session> {
+        &self.compiler.sess
+    }
+    fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
+        &self.compiler.codegen_backend()
+    }
+
     pub fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
-        self.queries.dep_graph_future.compute(|| {
+        self.dep_graph_future.compute(|| {
             Ok(if self.session().opts.build_dep_graph() {
                 Some(rustc_incremental::load_dep_graph(self.session()))
             } else {
@@ -101,8 +126,8 @@ impl Compiler {
     }
 
     pub fn parse(&self) -> Result<&Query<ast::Crate>> {
-        self.queries.parse.compute(|| {
-            passes::parse(self.session(), &self.input).map_err(
+        self.parse.compute(|| {
+            passes::parse(self.session(), &self.compiler.input).map_err(
                 |mut parse_error| {
                     parse_error.emit();
                     ErrorReported
@@ -112,7 +137,7 @@ impl Compiler {
     }
 
     pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
-        self.queries.register_plugins.compute(|| {
+        self.register_plugins.compute(|| {
             let crate_name = self.crate_name()?.peek().clone();
             let krate = self.parse()?.take();
 
@@ -120,7 +145,7 @@ impl Compiler {
             let result = passes::register_plugins(
                 self.session(),
                 &*self.codegen_backend().metadata_loader(),
-                self.register_lints
+                self.compiler.register_lints
                     .as_ref()
                     .map(|p| &**p)
                     .unwrap_or_else(|| empty),
@@ -140,8 +165,8 @@ impl Compiler {
     }
 
     pub fn crate_name(&self) -> Result<&Query<String>> {
-        self.queries.crate_name.compute(|| {
-            Ok(match self.crate_name {
+        self.crate_name.compute(|| {
+            Ok(match self.compiler.crate_name {
                 Some(ref crate_name) => crate_name.clone(),
                 None => {
                     let parse_result = self.parse()?;
@@ -149,7 +174,7 @@ impl Compiler {
                     rustc_codegen_utils::link::find_crate_name(
                         Some(self.session()),
                         &krate.attrs,
-                        &self.input
+                        &self.compiler.input
                     )
                 }
             })
@@ -159,11 +184,11 @@ impl Compiler {
     pub fn expansion(
         &self
     ) -> Result<&Query<(ast::Crate, Steal<Rc<RefCell<BoxedResolver>>>, Lrc<LintStore>)>> {
-        self.queries.expansion.compute(|| {
+        self.expansion.compute(|| {
             let crate_name = self.crate_name()?.peek().clone();
             let (krate, lint_store) = self.register_plugins()?.take();
             passes::configure_and_expand(
-                self.sess.clone(),
+                self.session().clone(),
                 lint_store.clone(),
                 self.codegen_backend().metadata_loader(),
                 krate,
@@ -175,7 +200,7 @@ impl Compiler {
     }
 
     pub fn dep_graph(&self) -> Result<&Query<DepGraph>> {
-        self.queries.dep_graph.compute(|| {
+        self.dep_graph.compute(|| {
             Ok(match self.dep_graph_future()?.take() {
                 None => DepGraph::new_disabled(),
                 Some(future) => {
@@ -192,15 +217,15 @@ impl Compiler {
     }
 
     pub fn lower_to_hir(
-        &self,
-    ) -> Result<&Query<(Steal<hir::map::Forest>, Steal<ResolverOutputs>)>> {
-        self.queries.lower_to_hir.compute(|| {
+        &'tcx self,
+    ) -> Result<&Query<(&'tcx hir::map::Forest, Steal<ResolverOutputs>)>> {
+        self.lower_to_hir.compute(|| {
             let expansion_result = self.expansion()?;
             let peeked = expansion_result.peek();
             let krate = &peeked.0;
             let resolver = peeked.1.steal();
             let lint_store = &peeked.2;
-            let hir = Steal::new(resolver.borrow_mut().access(|resolver| {
+            let hir = resolver.borrow_mut().access(|resolver| {
                 passes::lower_to_hir(
                     self.session(),
                     lint_store,
@@ -208,41 +233,47 @@ impl Compiler {
                     &*self.dep_graph()?.peek(),
                     &krate
                 )
-            })?);
+            })?;
+            let hir = self.arena.alloc(hir);
             Ok((hir, Steal::new(BoxedResolver::to_resolver_outputs(resolver))))
         })
     }
 
     pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
-        self.queries.prepare_outputs.compute(|| {
+        self.prepare_outputs.compute(|| {
             let expansion_result = self.expansion()?;
             let (krate, boxed_resolver, _) = &*expansion_result.peek();
             let crate_name = self.crate_name()?;
             let crate_name = crate_name.peek();
-            passes::prepare_outputs(self.session(), self, &krate, &boxed_resolver, &crate_name)
+            passes::prepare_outputs(
+                self.session(), self.compiler, &krate, &boxed_resolver, &crate_name
+            )
         })
     }
 
-    pub fn global_ctxt(&self) -> Result<&Query<BoxedGlobalCtxt>> {
-        self.queries.global_ctxt.compute(|| {
+    pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
+        self.global_ctxt.compute(|| {
             let crate_name = self.crate_name()?.peek().clone();
             let outputs = self.prepare_outputs()?.peek().clone();
             let lint_store = self.expansion()?.peek().2.clone();
-            let hir = self.lower_to_hir()?;
-            let hir = hir.peek();
-            let (hir_forest, resolver_outputs) = &*hir;
+            let hir = self.lower_to_hir()?.peek();
+            let (ref hir_forest, ref resolver_outputs) = &*hir;
             Ok(passes::create_global_ctxt(
-                self,
+                self.compiler,
                 lint_store,
-                hir_forest.steal(),
+                hir_forest,
                 resolver_outputs.steal(),
                 outputs,
-                &crate_name))
+                &crate_name,
+                &self.gcx,
+                &self.all_arenas,
+                &self.arena,
+            ))
         })
     }
 
-    pub fn ongoing_codegen(&self) -> Result<&Query<Box<dyn Any>>> {
-        self.queries.ongoing_codegen.compute(|| {
+    pub fn ongoing_codegen(&'tcx self) -> Result<&Query<Box<dyn Any>>> {
+        self.ongoing_codegen.compute(|| {
             let outputs = self.prepare_outputs()?;
             self.global_ctxt()?.peek_mut().enter(|tcx| {
                 tcx.analysis(LOCAL_CRATE).ok();
@@ -259,22 +290,58 @@ impl Compiler {
         })
     }
 
-    pub fn link(&self) -> Result<&Query<()>> {
-        self.queries.link.compute(|| {
-            let sess = self.session();
-
-            let ongoing_codegen = self.ongoing_codegen()?.take();
+    pub fn linker(&'tcx self) -> Result<Linker> {
+        let dep_graph = self.dep_graph()?;
+        let prepare_outputs = self.prepare_outputs()?;
+        let ongoing_codegen = self.ongoing_codegen()?;
 
-            self.codegen_backend().join_codegen_and_link(
-                ongoing_codegen,
-                sess,
-                &*self.dep_graph()?.peek(),
-                &*self.prepare_outputs()?.peek(),
-            ).map_err(|_| ErrorReported)?;
+        let sess = self.session().clone();
+        let codegen_backend = self.codegen_backend().clone();
 
-            Ok(())
+        Ok(Linker {
+            sess,
+            dep_graph: dep_graph.peek().clone(),
+            prepare_outputs: prepare_outputs.take(),
+            ongoing_codegen: ongoing_codegen.take(),
+            codegen_backend,
         })
     }
+}
+
+pub struct Linker {
+    sess: Lrc<Session>,
+    dep_graph: DepGraph,
+    prepare_outputs: OutputFilenames,
+    ongoing_codegen: Box<dyn Any>,
+    codegen_backend: Lrc<Box<dyn CodegenBackend>>,
+}
+
+impl Linker {
+    pub fn link(self) -> Result<()> {
+        self.codegen_backend.join_codegen_and_link(
+            self.ongoing_codegen,
+            &self.sess,
+            &self.dep_graph,
+            &self.prepare_outputs,
+        ).map_err(|_| ErrorReported)
+    }
+}
+
+impl Compiler {
+    pub fn enter<F, T>(&self, f: F) -> T
+        where F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T
+    {
+        let queries = Queries::new(&self);
+        let ret = f(&queries);
+
+        if self.session().opts.debugging_opts.query_stats {
+            if let Ok(gcx) = queries.global_ctxt() {
+                gcx.peek().print_stats();
+            }
+        }
+
+        ret
+    }
 
     // This method is different to all the other methods in `Compiler` because
     // it lacks a `Queries` entry. It's also not currently used. It does serve
@@ -282,24 +349,30 @@ impl Compiler {
     // between some passes. And see `rustc_driver::run_compiler` for a more
     // complex example.
     pub fn compile(&self) -> Result<()> {
-        self.prepare_outputs()?;
+        let linker = self.enter(|queries| {
+            queries.prepare_outputs()?;
 
-        if self.session().opts.output_types.contains_key(&OutputType::DepInfo)
-            && self.session().opts.output_types.len() == 1
-        {
-            return Ok(())
-        }
+            if self.session().opts.output_types.contains_key(&OutputType::DepInfo)
+                && self.session().opts.output_types.len() == 1
+            {
+                return Ok(None)
+            }
+
+            queries.global_ctxt()?;
 
-        self.global_ctxt()?;
+            // Drop AST after creating GlobalCtxt to free memory.
+            mem::drop(queries.expansion()?.take());
 
-        // Drop AST after creating GlobalCtxt to free memory.
-        mem::drop(self.expansion()?.take());
+            queries.ongoing_codegen()?;
 
-        self.ongoing_codegen()?;
+            let linker = queries.linker()?;
+            Ok(Some(linker))
+        })?;
 
-        // Drop GlobalCtxt after starting codegen to free memory.
-        mem::drop(self.global_ctxt()?.take());
+        if let Some(linker) = linker {
+            linker.link()?
+        }
 
-        self.link().map(|_| ())
+        Ok(())
     }
 }
diff --git a/src/librustc_interface/tests.rs b/src/librustc_interface/tests.rs
index d39a5d3a073..4c630b56cb4 100644
--- a/src/librustc_interface/tests.rs
+++ b/src/librustc_interface/tests.rs
@@ -651,10 +651,6 @@ fn test_debugging_options_tracking_hash() {
     assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
 
     opts = reference.clone();
-    opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
-    assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
-
-    opts = reference.clone();
     opts.debugging_opts.force_overflow_checks = Some(true);
     assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
 
diff --git a/src/librustc_lint/Cargo.toml b/src/librustc_lint/Cargo.toml
index d26d8791f66..ed38243581b 100644
--- a/src/librustc_lint/Cargo.toml
+++ b/src/librustc_lint/Cargo.toml
@@ -15,5 +15,6 @@ rustc_target = { path = "../librustc_target" }
 syntax = { path = "../libsyntax" }
 syntax_pos = { path = "../libsyntax_pos" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_index = { path = "../librustc_index" }
 rustc_error_codes = { path = "../librustc_error_codes" }
diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs
index 38624034022..b08a095beac 100644
--- a/src/librustc_lint/builtin.rs
+++ b/src/librustc_lint/builtin.rs
@@ -24,7 +24,7 @@
 use std::fmt::Write;
 
 use rustc::hir::def::{Res, DefKind};
-use rustc::hir::def_id::{DefId, LOCAL_CRATE};
+use rustc::hir::def_id::DefId;
 use rustc::ty::{self, Ty, TyCtxt, layout::VariantIdx};
 use rustc::{lint, util};
 use rustc::lint::FutureIncompatibleInfo;
@@ -34,15 +34,15 @@ use lint::{LateContext, LintContext, LintArray};
 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
 
 use rustc::util::nodemap::FxHashSet;
+use rustc_feature::{AttributeGate, AttributeTemplate, AttributeType, deprecated_attributes};
+use rustc_feature::Stability;
 
 use syntax::tokenstream::{TokenTree, TokenStream};
 use syntax::ast::{self, Expr};
 use syntax::ptr::P;
-use syntax::attr::{self, HasAttrs, AttributeTemplate};
+use syntax::attr::{self, HasAttrs};
 use syntax::source_map::Spanned;
 use syntax::edition::Edition;
-use syntax::feature_gate::{self, AttributeGate, AttributeType};
-use syntax::feature_gate::{Stability, deprecated_attributes};
 use syntax_pos::{BytePos, Span};
 use syntax::symbol::{Symbol, kw, sym};
 use syntax::errors::{Applicability, DiagnosticBuilder};
@@ -801,45 +801,6 @@ impl EarlyLintPass for UnusedDocComment {
 }
 
 declare_lint! {
-    PLUGIN_AS_LIBRARY,
-    Warn,
-    "compiler plugin used as ordinary library in non-plugin crate"
-}
-
-declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]);
-
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
-    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
-        if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
-            // We're compiling a plugin; it's fine to link other plugins.
-            return;
-        }
-
-        match it.kind {
-            hir::ItemKind::ExternCrate(..) => (),
-            _ => return,
-        };
-
-        let def_id = cx.tcx.hir().local_def_id(it.hir_id);
-        let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
-            Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
-            None => {
-                // Probably means we aren't linking the crate for some reason.
-                //
-                // Not sure if / when this could happen.
-                return;
-            }
-        };
-
-        if prfn.is_some() {
-            cx.span_lint(PLUGIN_AS_LIBRARY,
-                         it.span,
-                         "compiler plugin used as an ordinary library");
-        }
-    }
-}
-
-declare_lint! {
     NO_MANGLE_CONST_ITEMS,
     Deny,
     "const items will not have their symbols exported"
@@ -1268,7 +1229,6 @@ declare_lint_pass!(
         MISSING_DEBUG_IMPLEMENTATIONS,
         ANONYMOUS_PARAMETERS,
         UNUSED_DOC_COMMENTS,
-        PLUGIN_AS_LIBRARY,
         NO_MANGLE_CONST_ITEMS,
         NO_MANGLE_GENERIC_ITEMS,
         MUTABLE_TRANSMUTES,
@@ -1850,7 +1810,7 @@ impl EarlyLintPass for IncompleteFeatures {
         features.declared_lang_features
             .iter().map(|(name, span, _)| (name, span))
             .chain(features.declared_lib_features.iter().map(|(name, span)| (name, span)))
-            .filter(|(name, _)| feature_gate::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
+            .filter(|(name, _)| rustc_feature::INCOMPLETE_FEATURES.iter().any(|f| name == &f))
             .for_each(|(name, &span)| {
                 cx.struct_span_lint(
                     INCOMPLETE_FEATURES,
diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs
index 7e8dc1d1679..ab4063c421c 100644
--- a/src/librustc_lint/lib.rs
+++ b/src/librustc_lint/lib.rs
@@ -157,8 +157,6 @@ macro_rules! late_lint_mod_passes {
             // Depends on types used in type definitions
             MissingCopyImplementations: MissingCopyImplementations,
 
-            PluginAsLibrary: PluginAsLibrary,
-
             // Depends on referenced function signatures in expressions
             MutableTransmutes: MutableTransmutes,
 
@@ -350,6 +348,7 @@ fn register_builtins(store: &mut lint::LintStore, no_interleave_lints: bool) {
         "converted into hard error, see https://github.com/rust-lang/rust/issues/35896");
     store.register_removed("nested_impl_trait",
         "converted into hard error, see https://github.com/rust-lang/rust/issues/59014");
+    store.register_removed("plugin_as_library", "plugins have been deprecated and retired");
 }
 
 fn register_internals(store: &mut lint::LintStore) {
diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs
index 9f293bdaa10..f7de7ec7e18 100644
--- a/src/librustc_lint/unused.rs
+++ b/src/librustc_lint/unused.rs
@@ -1,3 +1,4 @@
+use rustc::hir;
 use rustc::hir::def::{Res, DefKind};
 use rustc::hir::def_id::DefId;
 use rustc::lint;
@@ -7,19 +8,17 @@ use rustc::ty::adjustment;
 use rustc_data_structures::fx::FxHashMap;
 use lint::{LateContext, EarlyContext, LintContext, LintArray};
 use lint::{LintPass, EarlyLintPass, LateLintPass};
+use rustc_feature::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
 
 use syntax::ast;
 use syntax::attr;
 use syntax::errors::{Applicability, pluralize};
-use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
 use syntax::print::pprust;
 use syntax::symbol::{kw, sym};
 use syntax::symbol::Symbol;
 use syntax::util::parser;
 use syntax_pos::{Span, BytePos};
 
-use rustc::hir;
-
 use log::debug;
 
 declare_lint! {
diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs
index 7b54b98cbc1..dbf2dcf1c0a 100644
--- a/src/librustc_metadata/creader.rs
+++ b/src/librustc_metadata/creader.rs
@@ -1,38 +1,47 @@
 //! Validates all used crates and extern libraries and loads their metadata
 
-use crate::cstore::CStore;
 use crate::locator::{CrateLocator, CratePaths};
 use crate::rmeta::{CrateMetadata, CrateNumMap, CrateRoot, CrateDep, MetadataBlob};
 
 use rustc::hir::def_id::CrateNum;
 use rustc_data_structures::svh::Svh;
+use rustc_data_structures::sync::Lrc;
+use rustc_index::vec::IndexVec;
 use rustc::middle::cstore::DepKind;
 use rustc::session::{Session, CrateDisambiguator};
 use rustc::session::config::{Sanitizer, self};
 use rustc_target::spec::{PanicStrategy, TargetTriple};
 use rustc::session::search_paths::PathKind;
 use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
-use rustc::util::nodemap::FxHashSet;
 use rustc::hir::map::Definitions;
 use rustc::hir::def_id::LOCAL_CRATE;
+use rustc::ty::TyCtxt;
 
 use std::path::Path;
 use std::{cmp, fs};
 
 use syntax::ast;
 use syntax::attr;
+use syntax::edition::Edition;
 use syntax::expand::allocator::{global_allocator_spans, AllocatorKind};
 use syntax::symbol::{Symbol, sym};
 use syntax::span_fatal;
+use syntax_expand::base::SyntaxExtension;
 use syntax_pos::{Span, DUMMY_SP};
 use log::{debug, info, log_enabled};
 use proc_macro::bridge::client::ProcMacro;
 
 use rustc_error_codes::*;
 
-crate struct Library {
-    pub source: CrateSource,
-    pub metadata: MetadataBlob,
+#[derive(Clone)]
+pub struct CStore {
+    metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
+    injected_panic_runtime: Option<CrateNum>,
+    /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
+    /// If the above is true, then this field denotes the kind of the found allocator.
+    allocator_kind: Option<AllocatorKind>,
+    /// This crate has a `#[global_allocator]` item.
+    has_global_allocator: bool,
 }
 
 pub struct CrateLoader<'a> {
@@ -44,18 +53,14 @@ pub struct CrateLoader<'a> {
     cstore: CStore,
 }
 
-fn dump_crates(cstore: &CStore) {
-    info!("resolved crates:");
-    cstore.iter_crate_data(|cnum, data| {
-        info!("  name: {}", data.root.name);
-        info!("  cnum: {}", cnum);
-        info!("  hash: {}", data.root.hash);
-        info!("  reqd: {:?}", *data.dep_kind.lock());
-        let CrateSource { dylib, rlib, rmeta } = data.source.clone();
-        dylib.map(|dl| info!("  dylib: {}", dl.0.display()));
-        rlib.map(|rl|  info!("   rlib: {}", rl.0.display()));
-        rmeta.map(|rl| info!("   rmeta: {}", rl.0.display()));
-    });
+pub enum LoadedMacro {
+    MacroDef(ast::Item, Edition),
+    ProcMacro(SyntaxExtension),
+}
+
+crate struct Library {
+    pub source: CrateSource,
+    pub metadata: MetadataBlob,
 }
 
 enum LoadResult {
@@ -75,6 +80,90 @@ impl<'a> LoadError<'a> {
     }
 }
 
+fn dump_crates(cstore: &CStore) {
+    info!("resolved crates:");
+    cstore.iter_crate_data(|cnum, data| {
+        info!("  name: {}", data.name());
+        info!("  cnum: {}", cnum);
+        info!("  hash: {}", data.hash());
+        info!("  reqd: {:?}", data.dep_kind());
+        let CrateSource { dylib, rlib, rmeta } = data.source();
+        dylib.as_ref().map(|dl| info!("  dylib: {}", dl.0.display()));
+        rlib.as_ref().map(|rl|  info!("   rlib: {}", rl.0.display()));
+        rmeta.as_ref().map(|rl| info!("   rmeta: {}", rl.0.display()));
+    });
+}
+
+impl CStore {
+    crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
+        tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
+    }
+
+    fn alloc_new_crate_num(&mut self) -> CrateNum {
+        self.metas.push(None);
+        CrateNum::new(self.metas.len() - 1)
+    }
+
+    crate fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
+        self.metas[cnum].as_ref()
+            .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
+    }
+
+    fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
+        assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
+        self.metas[cnum] = Some(Lrc::new(data));
+    }
+
+    crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
+        for (cnum, data) in self.metas.iter_enumerated() {
+            if let Some(data) = data {
+                f(cnum, data);
+            }
+        }
+    }
+
+    fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
+        if !deps.contains(&cnum) {
+            let data = self.get_crate_data(cnum);
+            for &dep in data.dependencies().iter() {
+                if dep != cnum {
+                    self.push_dependencies_in_postorder(deps, dep);
+                }
+            }
+
+            deps.push(cnum);
+        }
+    }
+
+    crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
+        let mut deps = Vec::new();
+        if cnum == LOCAL_CRATE {
+            self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
+        } else {
+            self.push_dependencies_in_postorder(&mut deps, cnum);
+        }
+        deps
+    }
+
+    fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
+        let mut deps = self.crate_dependencies_in_postorder(cnum);
+        deps.reverse();
+        deps
+    }
+
+    crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
+        self.injected_panic_runtime
+    }
+
+    crate fn allocator_kind(&self) -> Option<AllocatorKind> {
+        self.allocator_kind
+    }
+
+    crate fn has_global_allocator(&self) -> bool {
+        self.has_global_allocator
+    }
+}
+
 impl<'a> CrateLoader<'a> {
     pub fn new(
         sess: &'a Session,
@@ -85,7 +174,16 @@ impl<'a> CrateLoader<'a> {
             sess,
             metadata_loader,
             local_crate_name: Symbol::intern(local_crate_name),
-            cstore: Default::default(),
+            cstore: CStore {
+                // We add an empty entry for LOCAL_CRATE (which maps to zero) in
+                // order to make array indices in `metas` match with the
+                // corresponding `CrateNum`. This first entry will always remain
+                // `None`.
+                metas: IndexVec::from_elem_n(None, 1),
+                injected_panic_runtime: None,
+                allocator_kind: None,
+                has_global_allocator: false,
+            }
         }
     }
 
@@ -97,14 +195,13 @@ impl<'a> CrateLoader<'a> {
         self.cstore
     }
 
-    fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
-                      -> Option<CrateNum> {
+    fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
         let mut ret = None;
         self.cstore.iter_crate_data(|cnum, data| {
-            if data.root.name != name { return }
+            if data.name() != name { return }
 
             match hash {
-                Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
+                Some(hash) if hash == data.hash() => { ret = Some(cnum); return }
                 Some(..) => return,
                 None => {}
             }
@@ -118,7 +215,7 @@ impl<'a> CrateLoader<'a> {
             // We're also sure to compare *paths*, not actual byte slices. The
             // `source` stores paths which are normalized which may be different
             // from the strings on the command line.
-            let source = &self.cstore.get_crate_data(cnum).source;
+            let source = self.cstore.get_crate_data(cnum).source();
             if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
                 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
                 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
@@ -152,26 +249,26 @@ impl<'a> CrateLoader<'a> {
                                   span: Span,
                                   root: &CrateRoot<'_>) {
         // Check for (potential) conflicts with the local crate
-        if self.local_crate_name == root.name &&
-           self.sess.local_crate_disambiguator() == root.disambiguator {
+        if self.local_crate_name == root.name() &&
+           self.sess.local_crate_disambiguator() == root.disambiguator() {
             span_fatal!(self.sess, span, E0519,
                         "the current crate is indistinguishable from one of its \
                          dependencies: it has the same crate-name `{}` and was \
                          compiled with the same `-C metadata` arguments. This \
                          will result in symbol conflicts between the two.",
-                        root.name)
+                        root.name())
         }
 
         // Check for conflicts with any crate loaded so far
         self.cstore.iter_crate_data(|_, other| {
-            if other.root.name == root.name && // same crate-name
-               other.root.disambiguator == root.disambiguator &&  // same crate-disambiguator
-               other.root.hash != root.hash { // but different SVH
+            if other.name() == root.name() && // same crate-name
+               other.disambiguator() == root.disambiguator() &&  // same crate-disambiguator
+               other.hash() != root.hash() { // but different SVH
                 span_fatal!(self.sess, span, E0523,
                         "found two different crates with name `{}` that are \
                          not distinguished by differing `-C metadata`. This \
                          will result in symbol conflicts between the two.",
-                        root.name)
+                        root.name())
             }
         });
     }
@@ -189,14 +286,14 @@ impl<'a> CrateLoader<'a> {
 
         let Library { source, metadata } = lib;
         let crate_root = metadata.get_root();
-        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash);
+        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
         self.verify_no_symbol_conflicts(span, &crate_root);
 
         let private_dep = self.sess.opts.externs.get(&name.as_str())
             .map(|e| e.is_private_dep)
             .unwrap_or(false);
 
-        info!("register crate `{}` (private_dep = {})", crate_root.name, private_dep);
+        info!("register crate `{}` (private_dep = {})", crate_root.name(), private_dep);
 
         // Claim this crate number and cache it
         let cnum = self.cstore.alloc_new_crate_num();
@@ -207,7 +304,7 @@ impl<'a> CrateLoader<'a> {
         let root = if let Some(root) = root {
             root
         } else {
-            crate_paths = CratePaths::new(crate_root.name, source.clone());
+            crate_paths = CratePaths::new(crate_root.name(), source.clone());
             &crate_paths
         };
 
@@ -221,7 +318,7 @@ impl<'a> CrateLoader<'a> {
                 None => (&source, &crate_root),
             };
             let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
-            Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator, span))
+            Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator(), span))
         } else {
             None
         };
@@ -316,10 +413,10 @@ impl<'a> CrateLoader<'a> {
         let (root, hash, host_hash, extra_filename, path_kind) = match dep {
             Some((root, dep)) => (
                 Some(root),
-                Some(&dep.hash),
-                dep.host_hash.as_ref(),
+                Some(dep.hash),
+                dep.host_hash,
                 Some(&dep.extra_filename[..]),
-                PathKind::Dependency
+                PathKind::Dependency,
             ),
             None => (None, None, None, None, PathKind::Crate),
         };
@@ -350,12 +447,10 @@ impl<'a> CrateLoader<'a> {
         match result {
             (LoadResult::Previous(cnum), None) => {
                 let data = self.cstore.get_crate_data(cnum);
-                if data.root.is_proc_macro_crate() {
+                if data.is_proc_macro_crate() {
                     dep_kind = DepKind::UnexportedMacrosOnly;
                 }
-                data.dep_kind.with_lock(|data_dep_kind| {
-                    *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
-                });
+                data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
                 Ok(cnum)
             }
             (LoadResult::Loaded(library), host_library) => {
@@ -380,7 +475,7 @@ impl<'a> CrateLoader<'a> {
         if locator.triple == self.sess.opts.target_triple {
             let mut result = LoadResult::Loaded(library);
             self.cstore.iter_crate_data(|cnum, data| {
-                if data.root.name == root.name && root.hash == data.root.hash {
+                if data.name() == root.name() && root.hash() == data.hash() {
                     assert!(locator.hash.is_none());
                     info!("load success, going to previous cnum: {}", cnum);
                     result = LoadResult::Previous(cnum);
@@ -392,44 +487,14 @@ impl<'a> CrateLoader<'a> {
         }
     }
 
-    fn update_extern_crate(&self,
-                           cnum: CrateNum,
-                           mut extern_crate: ExternCrate,
-                           visited: &mut FxHashSet<(CrateNum, bool)>)
-    {
-        if !visited.insert((cnum, extern_crate.is_direct())) { return }
-
+    fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
         let cmeta = self.cstore.get_crate_data(cnum);
-        let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
-
-        // Prefer:
-        // - something over nothing (tuple.0);
-        // - direct extern crate to indirect (tuple.1);
-        // - shorter paths to longer (tuple.2).
-        let new_rank = (
-            true,
-            extern_crate.is_direct(),
-            cmp::Reverse(extern_crate.path_len),
-        );
-        let old_rank = match *old_extern_crate {
-            None => (false, false, cmp::Reverse(usize::max_value())),
-            Some(ref c) => (
-                true,
-                c.is_direct(),
-                cmp::Reverse(c.path_len),
-            ),
-        };
-        if old_rank >= new_rank {
-            return; // no change needed
-        }
-
-        *old_extern_crate = Some(extern_crate);
-        drop(old_extern_crate);
-
-        // Propagate the extern crate info to dependencies.
-        extern_crate.dependency_of = cnum;
-        for &dep_cnum in cmeta.dependencies.borrow().iter() {
-            self.update_extern_crate(dep_cnum, extern_crate, visited);
+        if cmeta.update_extern_crate(extern_crate) {
+            // Propagate the extern crate info to dependencies if it was updated.
+            let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
+            for &dep_cnum in cmeta.dependencies().iter() {
+                self.update_extern_crate(dep_cnum, extern_crate);
+            }
         }
     }
 
@@ -503,7 +568,6 @@ impl<'a> CrateLoader<'a> {
         });
         if !any_non_rlib {
             info!("panic runtime injection skipped, only generating rlib");
-            self.cstore.injected_panic_runtime = None;
             return
         }
 
@@ -520,14 +584,13 @@ impl<'a> CrateLoader<'a> {
                                                           sym::needs_panic_runtime);
 
         self.cstore.iter_crate_data(|cnum, data| {
-            needs_panic_runtime = needs_panic_runtime ||
-                                  data.root.needs_panic_runtime;
-            if data.root.panic_runtime {
+            needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
+            if data.is_panic_runtime() {
                 // Inject a dependency from all #![needs_panic_runtime] to this
                 // #![panic_runtime] crate.
                 self.inject_dependency_if(cnum, "a panic runtime",
-                                          &|data| data.root.needs_panic_runtime);
-                runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
+                                          &|data| data.needs_panic_runtime());
+                runtime_found = runtime_found || data.dep_kind() == DepKind::Explicit;
             }
         });
 
@@ -535,7 +598,6 @@ impl<'a> CrateLoader<'a> {
         // we just don't need one at all, then we're done here and there's
         // nothing else to do.
         if !needs_panic_runtime || runtime_found {
-            self.cstore.injected_panic_runtime = None;
             return
         }
 
@@ -562,11 +624,11 @@ impl<'a> CrateLoader<'a> {
 
         // Sanity check the loaded crate to ensure it is indeed a panic runtime
         // and the panic strategy is indeed what we thought it was.
-        if !data.root.panic_runtime {
+        if !data.is_panic_runtime() {
             self.sess.err(&format!("the crate `{}` is not a panic runtime",
                                    name));
         }
-        if data.root.panic_strategy != desired_strategy {
+        if data.panic_strategy() != desired_strategy {
             self.sess.err(&format!("the crate `{}` does not have the panic \
                                     strategy `{}`",
                                    name, desired_strategy.desc()));
@@ -574,7 +636,7 @@ impl<'a> CrateLoader<'a> {
 
         self.cstore.injected_panic_runtime = Some(cnum);
         self.inject_dependency_if(cnum, "a panic runtime",
-                                  &|data| data.root.needs_panic_runtime);
+                                  &|data| data.needs_panic_runtime());
     }
 
     fn inject_sanitizer_runtime(&mut self) {
@@ -648,7 +710,7 @@ impl<'a> CrateLoader<'a> {
 
             let mut uses_std = false;
             self.cstore.iter_crate_data(|_, data| {
-                if data.root.name == sym::std {
+                if data.name() == sym::std {
                     uses_std = true;
                 }
             });
@@ -666,7 +728,7 @@ impl<'a> CrateLoader<'a> {
                 let data = self.cstore.get_crate_data(cnum);
 
                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
-                if !data.root.sanitizer_runtime {
+                if !data.is_sanitizer_runtime() {
                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
                                            name));
                 }
@@ -687,7 +749,7 @@ impl<'a> CrateLoader<'a> {
             let data = self.cstore.get_crate_data(cnum);
 
             // Sanity check the loaded crate to ensure it is indeed a profiler runtime
-            if !data.root.profiler_runtime {
+            if !data.is_profiler_runtime() {
                 self.sess.err(&format!("the crate `profiler_builtins` is not \
                                         a profiler runtime"));
             }
@@ -695,7 +757,7 @@ impl<'a> CrateLoader<'a> {
     }
 
     fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
-        let has_global_allocator = match &*global_allocator_spans(krate) {
+        self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
             [span1, span2, ..] => {
                 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
                     .span_label(*span2, "cannot define a new global allocator")
@@ -705,7 +767,6 @@ impl<'a> CrateLoader<'a> {
             }
             spans => !spans.is_empty()
         };
-        self.sess.has_global_allocator.set(has_global_allocator);
 
         // Check to see if we actually need an allocator. This desire comes
         // about through the `#![needs_allocator]` attribute and is typically
@@ -713,10 +774,9 @@ impl<'a> CrateLoader<'a> {
         let mut needs_allocator = attr::contains_name(&krate.attrs,
                                                       sym::needs_allocator);
         self.cstore.iter_crate_data(|_, data| {
-            needs_allocator = needs_allocator || data.root.needs_allocator;
+            needs_allocator = needs_allocator || data.needs_allocator();
         });
         if !needs_allocator {
-            self.cstore.allocator_kind = None;
             return
         }
 
@@ -732,7 +792,6 @@ impl<'a> CrateLoader<'a> {
                 }
             });
         if all_rlib {
-            self.cstore.allocator_kind = None;
             return
         }
 
@@ -743,29 +802,24 @@ impl<'a> CrateLoader<'a> {
         // First up we check for global allocators. Look at the crate graph here
         // and see what's a global allocator, including if we ourselves are a
         // global allocator.
-        let mut global_allocator = if has_global_allocator {
-            Some(None)
+        let mut global_allocator = if self.cstore.has_global_allocator {
+            Some(Symbol::intern("this crate"))
         } else {
             None
         };
         self.cstore.iter_crate_data(|_, data| {
-            if !data.root.has_global_allocator {
+            if !data.has_global_allocator() {
                 return
             }
             match global_allocator {
-                Some(Some(other_crate)) => {
+                Some(other_crate) => {
                     self.sess.err(&format!("the `#[global_allocator]` in {} \
-                                            conflicts with this global \
+                                            conflicts with global \
                                             allocator in: {}",
                                            other_crate,
-                                           data.root.name));
+                                           data.name()));
                 }
-                Some(None) => {
-                    self.sess.err(&format!("the `#[global_allocator]` in this \
-                                            crate conflicts with global \
-                                            allocator in: {}", data.root.name));
-                }
-                None => global_allocator = Some(Some(data.root.name)),
+                None => global_allocator = Some(data.name()),
             }
         });
         if global_allocator.is_some() {
@@ -779,7 +833,7 @@ impl<'a> CrateLoader<'a> {
         // attribute.
         let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
         self.cstore.iter_crate_data(|_, data| {
-            if data.root.has_default_lib_allocator {
+            if data.has_default_lib_allocator() {
                 has_default = true;
             }
         });
@@ -790,7 +844,7 @@ impl<'a> CrateLoader<'a> {
                            add `#[global_allocator]` to a static item \
                            that implements the GlobalAlloc trait.");
         }
-        self.cstore.allocator_kind = Some(AllocatorKind::DefaultLib);
+        self.cstore.allocator_kind = Some(AllocatorKind::Default);
     }
 
     fn inject_dependency_if(&self,
@@ -807,15 +861,15 @@ impl<'a> CrateLoader<'a> {
         // Before we inject any dependencies, make sure we don't inject a
         // circular dependency by validating that this crate doesn't
         // transitively depend on any crates satisfying `needs_dep`.
-        for dep in self.cstore.crate_dependencies_in_rpo(krate) {
+        for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
             let data = self.cstore.get_crate_data(dep);
             if needs_dep(&data) {
                 self.sess.err(&format!("the crate `{}` cannot depend \
                                         on a crate that needs {}, but \
                                         it depends on `{}`",
-                                       self.cstore.get_crate_data(krate).root.name,
+                                       self.cstore.get_crate_data(krate).name(),
                                        what,
-                                       data.root.name));
+                                       data.name()));
             }
         }
 
@@ -829,7 +883,7 @@ impl<'a> CrateLoader<'a> {
             }
 
             info!("injecting a dep from {} to {}", cnum, krate);
-            data.dependencies.borrow_mut().push(krate);
+            data.add_dependency(krate);
         });
     }
 
@@ -879,7 +933,6 @@ impl<'a> CrateLoader<'a> {
                         path_len,
                         dependency_of: LOCAL_CRATE,
                     },
-                    &mut FxHashSet::default(),
                 );
                 cnum
             }
@@ -899,27 +952,12 @@ impl<'a> CrateLoader<'a> {
                 path_len: usize::max_value(),
                 dependency_of: LOCAL_CRATE,
             },
-            &mut FxHashSet::default(),
         );
 
         cnum
     }
 
     pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
-        let cnum = self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()?;
-
-        self.update_extern_crate(
-            cnum,
-            ExternCrate {
-                src: ExternCrateSource::Path,
-                span,
-                // to have the least priority in `update_extern_crate`
-                path_len: usize::max_value(),
-                dependency_of: LOCAL_CRATE,
-            },
-            &mut FxHashSet::default(),
-        );
-
-        Some(cnum)
+        self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()
     }
 }
diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs
deleted file mode 100644
index 48cf0b982f2..00000000000
--- a/src/librustc_metadata/cstore.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-// The crate store - a central repo for information collected about external
-// crates and libraries
-
-use crate::rmeta::CrateMetadata;
-
-use rustc_data_structures::sync::Lrc;
-use rustc_index::vec::IndexVec;
-use rustc::hir::def_id::CrateNum;
-use syntax::ast;
-use syntax::edition::Edition;
-use syntax::expand::allocator::AllocatorKind;
-use syntax_expand::base::SyntaxExtension;
-
-pub use crate::rmeta::{provide, provide_extern};
-
-#[derive(Clone)]
-pub struct CStore {
-    metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
-    crate injected_panic_runtime: Option<CrateNum>,
-    crate allocator_kind: Option<AllocatorKind>,
-}
-
-pub enum LoadedMacro {
-    MacroDef(ast::Item, Edition),
-    ProcMacro(SyntaxExtension),
-}
-
-impl Default for CStore {
-    fn default() -> Self {
-        CStore {
-            // We add an empty entry for LOCAL_CRATE (which maps to zero) in
-            // order to make array indices in `metas` match with the
-            // corresponding `CrateNum`. This first entry will always remain
-            // `None`.
-            metas: IndexVec::from_elem_n(None, 1),
-            injected_panic_runtime: None,
-            allocator_kind: None,
-        }
-    }
-}
-
-impl CStore {
-    crate fn alloc_new_crate_num(&mut self) -> CrateNum {
-        self.metas.push(None);
-        CrateNum::new(self.metas.len() - 1)
-    }
-
-    crate fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
-        self.metas[cnum].as_ref()
-            .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
-    }
-
-    crate fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
-        assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
-        self.metas[cnum] = Some(Lrc::new(data));
-    }
-
-    crate fn iter_crate_data<I>(&self, mut i: I)
-        where I: FnMut(CrateNum, &CrateMetadata)
-    {
-        for (k, v) in self.metas.iter_enumerated() {
-            if let &Some(ref v) = v {
-                i(k, v);
-            }
-        }
-    }
-
-    crate fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum> {
-        let mut ordering = Vec::new();
-        self.push_dependencies_in_postorder(&mut ordering, krate);
-        ordering.reverse();
-        ordering
-    }
-
-    crate fn push_dependencies_in_postorder(&self, ordering: &mut Vec<CrateNum>, krate: CrateNum) {
-        if ordering.contains(&krate) {
-            return;
-        }
-
-        let data = self.get_crate_data(krate);
-        for &dep in data.dependencies.borrow().iter() {
-            if dep != krate {
-                self.push_dependencies_in_postorder(ordering, dep);
-            }
-        }
-
-        ordering.push(krate);
-    }
-
-    crate fn do_postorder_cnums_untracked(&self) -> Vec<CrateNum> {
-        let mut ordering = Vec::new();
-        for (num, v) in self.metas.iter_enumerated() {
-            if let &Some(_) = v {
-                self.push_dependencies_in_postorder(&mut ordering, num);
-            }
-        }
-        return ordering
-    }
-}
diff --git a/src/librustc_metadata/dependency_format.rs b/src/librustc_metadata/dependency_format.rs
index dbf7fede146..d6d722c47b3 100644
--- a/src/librustc_metadata/dependency_format.rs
+++ b/src/librustc_metadata/dependency_format.rs
@@ -51,6 +51,8 @@
 //! Additionally, the algorithm is geared towards finding *any* solution rather
 //! than finding a number of solutions (there are normally quite a few).
 
+use crate::creader::CStore;
+
 use rustc::hir::def_id::CrateNum;
 use rustc::middle::cstore::LinkagePreference::{self, RequireStatic, RequireDynamic};
 use rustc::middle::cstore::{self, DepKind};
@@ -184,7 +186,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList {
     //
     // Things like allocators and panic runtimes may not have been activated
     // quite yet, so do so here.
-    activate_injected_dep(tcx.injected_panic_runtime(), &mut ret,
+    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret,
                           &|cnum| tcx.is_panic_runtime(cnum));
 
     // When dylib B links to dylib A, then when using B we must also link to A.
@@ -263,7 +265,7 @@ fn attempt_static(tcx: TyCtxt<'_>) -> Option<DependencyList> {
     // Our allocator/panic runtime may not have been linked above if it wasn't
     // explicitly linked, which is the case for any injected dependency. Handle
     // that here and activate them.
-    activate_injected_dep(tcx.injected_panic_runtime(), &mut ret,
+    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret,
                           &|cnum| tcx.is_panic_runtime(cnum));
 
     Some(ret)
diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs
index 35ac7686647..8c0b7345e1e 100644
--- a/src/librustc_metadata/lib.rs
+++ b/src/librustc_metadata/lib.rs
@@ -24,6 +24,8 @@ extern crate rustc;
 #[macro_use]
 extern crate rustc_data_structures;
 
+pub use rmeta::{provide, provide_extern};
+
 mod dependency_format;
 mod foreign_modules;
 mod link_args;
@@ -31,7 +33,6 @@ mod native_libs;
 mod rmeta;
 
 pub mod creader;
-pub mod cstore;
 pub mod dynamic_lib;
 pub mod locator;
 
diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs
index 64230fd9e60..c6fb80eca05 100644
--- a/src/librustc_metadata/locator.rs
+++ b/src/librustc_metadata/locator.rs
@@ -262,8 +262,8 @@ crate struct CrateLocator<'a> {
     // Immutable per-search configuration.
     crate_name: Symbol,
     exact_paths: Vec<PathBuf>,
-    pub hash: Option<&'a Svh>,
-    pub host_hash: Option<&'a Svh>,
+    pub hash: Option<Svh>,
+    pub host_hash: Option<Svh>,
     extra_filename: Option<&'a str>,
     pub target: &'a Target,
     pub triple: TargetTriple,
@@ -313,8 +313,8 @@ impl<'a> CrateLocator<'a> {
         sess: &'a Session,
         metadata_loader: &'a dyn MetadataLoader,
         crate_name: Symbol,
-        hash: Option<&'a Svh>,
-        host_hash: Option<&'a Svh>,
+        hash: Option<Svh>,
+        host_hash: Option<Svh>,
         extra_filename: Option<&'a str>,
         is_host: bool,
         path_kind: PathKind,
@@ -597,7 +597,7 @@ impl<'a> CrateLocator<'a> {
                                                "multiple matching crates for `{}`",
                                                self.crate_name);
                 let candidates = libraries.iter().filter_map(|(_, lib)| {
-                    let crate_name = &lib.metadata.get_root().name.as_str();
+                    let crate_name = &lib.metadata.get_root().name().as_str();
                     match &(&lib.source.dylib, &lib.source.rlib) {
                         &(&Some((ref pd, _)), &Some((ref pr, _))) => {
                             Some(format!("\ncrate `{}`: {}\n{:>padding$}",
@@ -774,35 +774,36 @@ impl<'a> CrateLocator<'a> {
         }
 
         if self.exact_paths.is_empty() {
-            if self.crate_name != root.name {
+            if self.crate_name != root.name() {
                 info!("Rejecting via crate name");
                 return None;
             }
         }
 
-        if root.triple != self.triple {
+        if root.triple() != &self.triple {
             info!("Rejecting via crate triple: expected {} got {}",
                   self.triple,
-                  root.triple);
+                  root.triple());
             self.rejected_via_triple.push(CrateMismatch {
                 path: libpath.to_path_buf(),
-                got: root.triple.to_string(),
+                got: root.triple().to_string(),
             });
             return None;
         }
 
-        if let Some(myhash) = self.hash {
-            if *myhash != root.hash {
-                info!("Rejecting via hash: expected {} got {}", *myhash, root.hash);
+        let hash = root.hash();
+        if let Some(expected_hash) = self.hash {
+            if hash != expected_hash {
+                info!("Rejecting via hash: expected {} got {}", expected_hash, hash);
                 self.rejected_via_hash.push(CrateMismatch {
                     path: libpath.to_path_buf(),
-                    got: myhash.to_string(),
+                    got: hash.to_string(),
                 });
                 return None;
             }
         }
 
-        Some(root.hash)
+        Some(hash)
     }
 
 
@@ -1021,7 +1022,7 @@ pub fn find_plugin_registrar(
 
     match library.source.dylib {
         Some(dylib) => {
-            Some((dylib.0, library.metadata.get_root().disambiguator))
+            Some((dylib.0, library.metadata.get_root().disambiguator()))
         }
         None => {
             span_err!(sess, span, E0457,
diff --git a/src/librustc_metadata/native_libs.rs b/src/librustc_metadata/native_libs.rs
index e577b238c86..425e5d1d821 100644
--- a/src/librustc_metadata/native_libs.rs
+++ b/src/librustc_metadata/native_libs.rs
@@ -7,7 +7,7 @@ use rustc::util::nodemap::FxHashSet;
 use rustc_target::spec::abi::Abi;
 use syntax::attr;
 use syntax::source_map::Span;
-use syntax::feature_gate::{self, GateIssue};
+use syntax::feature_gate::feature_err;
 use syntax::symbol::{kw, sym, Symbol};
 use syntax::{span_err, struct_span_err};
 
@@ -158,27 +158,29 @@ impl Collector<'tcx> {
             }
         }
         if lib.cfg.is_some() && !self.tcx.features().link_cfg {
-            feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
-                                           sym::link_cfg,
-                                           span.unwrap(),
-                                           GateIssue::Language,
-                                           "is unstable");
+            feature_err(&self.tcx.sess.parse_sess, sym::link_cfg, span.unwrap(), "is unstable")
+                .emit();
         }
         if lib.kind == cstore::NativeStaticNobundle &&
-           !self.tcx.features().static_nobundle {
-            feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
-                                           sym::static_nobundle,
-                                           span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
-                                           GateIssue::Language,
-                                           "kind=\"static-nobundle\" is unstable");
+           !self.tcx.features().static_nobundle
+        {
+            feature_err(
+                &self.tcx.sess.parse_sess,
+                sym::static_nobundle,
+                span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
+                "kind=\"static-nobundle\" is unstable"
+            )
+            .emit();
         }
         if lib.kind == cstore::NativeRawDylib &&
            !self.tcx.features().raw_dylib {
-            feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
-                                           sym::raw_dylib,
-                                           span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
-                                           GateIssue::Language,
-                                           "kind=\"raw-dylib\" is unstable");
+            feature_err(
+                &self.tcx.sess.parse_sess,
+                sym::raw_dylib,
+                span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
+                "kind=\"raw-dylib\" is unstable"
+            )
+            .emit();
         }
         self.libs.push(lib);
     }
diff --git a/src/librustc_metadata/rmeta/decoder.rs b/src/librustc_metadata/rmeta/decoder.rs
index e6ccbf5c38b..820783bab6d 100644
--- a/src/librustc_metadata/rmeta/decoder.rs
+++ b/src/librustc_metadata/rmeta/decoder.rs
@@ -4,7 +4,7 @@ use crate::rmeta::*;
 use crate::rmeta::table::{FixedSizeEncoding, Table};
 
 use rustc_index::vec::{Idx, IndexVec};
-use rustc_data_structures::sync::{Lrc, Lock, Once, AtomicCell};
+use rustc_data_structures::sync::{Lrc, Lock, LockGuard, Once, AtomicCell};
 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
 use rustc::hir::map::definitions::DefPathTable;
 use rustc::hir;
@@ -66,7 +66,7 @@ crate struct CrateMetadata {
     /// lifetime is only used behind `Lazy`, and therefore acts like an
     /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
     /// is being used to decode those values.
-    crate root: CrateRoot<'static>,
+    root: CrateRoot<'static>,
     /// For each definition in this crate, we encode a key. When the
     /// crate is loaded, we read all the keys and put them in this
     /// hashmap, which gives the reverse mapping. This allows us to
@@ -97,11 +97,11 @@ crate struct CrateMetadata {
     /// IDs as they are seen from the current compilation session.
     cnum_map: CrateNumMap,
     /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
-    crate dependencies: Lock<Vec<CrateNum>>,
+    dependencies: Lock<Vec<CrateNum>>,
     /// How to link (or not link) this crate to the currently compiled crate.
-    crate dep_kind: Lock<DepKind>,
+    dep_kind: Lock<DepKind>,
     /// Filesystem location of this crate.
-    crate source: CrateSource,
+    source: CrateSource,
     /// Whether or not this crate should be consider a private dependency
     /// for purposes of the 'exported_private_dependencies' lint
     private_dep: bool,
@@ -112,7 +112,7 @@ crate struct CrateMetadata {
 
     /// Information about the `extern crate` item or path that caused this crate to be loaded.
     /// If this is `None`, then the crate was injected (e.g., by the allocator).
-    crate extern_crate: Lock<Option<ExternCrate>>,
+    extern_crate: Lock<Option<ExternCrate>>,
 }
 
 /// Holds information about a syntax_pos::SourceFile imported from another crate.
@@ -558,6 +558,22 @@ impl CrateRoot<'_> {
         self.proc_macro_data.is_some()
     }
 
+    crate fn name(&self) -> Symbol {
+        self.name
+    }
+
+    crate fn disambiguator(&self) -> CrateDisambiguator {
+        self.disambiguator
+    }
+
+    crate fn hash(&self) -> Svh {
+        self.hash
+    }
+
+    crate fn triple(&self) -> &TargetTriple {
+        &self.triple
+    }
+
     crate fn decode_crate_deps(
         &self,
         metadata: &'a MetadataBlob,
@@ -1517,6 +1533,83 @@ impl<'a, 'tcx> CrateMetadata {
 
         dep_node_index
     }
+
+    crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
+        self.dependencies.borrow()
+    }
+
+    crate fn add_dependency(&self, cnum: CrateNum) {
+        self.dependencies.borrow_mut().push(cnum);
+    }
+
+    crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
+        let mut extern_crate = self.extern_crate.borrow_mut();
+        let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
+        if update {
+            *extern_crate = Some(new_extern_crate);
+        }
+        update
+    }
+
+    crate fn source(&self) -> &CrateSource {
+        &self.source
+    }
+
+    crate fn dep_kind(&self) -> DepKind {
+        *self.dep_kind.lock()
+    }
+
+    crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
+        self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
+    }
+
+    crate fn panic_strategy(&self) -> PanicStrategy {
+        self.root.panic_strategy
+    }
+
+    crate fn needs_panic_runtime(&self) -> bool {
+        self.root.needs_panic_runtime
+    }
+
+    crate fn is_panic_runtime(&self) -> bool {
+        self.root.panic_runtime
+    }
+
+    crate fn is_sanitizer_runtime(&self) -> bool {
+        self.root.sanitizer_runtime
+    }
+
+    crate fn is_profiler_runtime(&self) -> bool {
+        self.root.profiler_runtime
+    }
+
+    crate fn needs_allocator(&self) -> bool {
+        self.root.needs_allocator
+    }
+
+    crate fn has_global_allocator(&self) -> bool {
+        self.root.has_global_allocator
+    }
+
+    crate fn has_default_lib_allocator(&self) -> bool {
+        self.root.has_default_lib_allocator
+    }
+
+    crate fn is_proc_macro_crate(&self) -> bool {
+        self.root.is_proc_macro_crate()
+    }
+
+    crate fn name(&self) -> Symbol {
+        self.root.name
+    }
+
+    crate fn disambiguator(&self) -> CrateDisambiguator {
+        self.root.disambiguator
+    }
+
+    crate fn hash(&self) -> Svh {
+        self.root.hash
+    }
 }
 
 // Cannot be implemented on 'ProcMacro', as libproc_macro
diff --git a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs
index abb0ceb4ff4..8214153f153 100644
--- a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs
+++ b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs
@@ -1,4 +1,4 @@
-use crate::cstore::{self, LoadedMacro};
+use crate::creader::{CStore, LoadedMacro};
 use crate::link_args;
 use crate::native_libs;
 use crate::foreign_modules;
@@ -51,9 +51,7 @@ macro_rules! provide {
                 let ($def_id, $other) = def_id_arg.into_args();
                 assert!(!$def_id.is_local());
 
-                let $cdata = $tcx.crate_data_as_any($def_id.krate);
-                let $cdata = $cdata.downcast_ref::<rmeta::CrateMetadata>()
-                    .expect("CrateStore created data is not a CrateMetadata");
+                let $cdata = CStore::from_tcx($tcx).get_crate_data($def_id.krate);
 
                 if $tcx.dep_graph.is_fully_enabled() {
                     let crate_dep_node_index = $cdata.get_crate_dep_node_index($tcx);
@@ -192,6 +190,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
     }
     crate_disambiguator => { cdata.root.disambiguator }
     crate_hash => { cdata.root.hash }
+    crate_host_hash => { cdata.host_hash }
     original_crate_name => { cdata.root.name }
 
     extra_filename => { cdata.root.extra_filename.clone() }
@@ -377,12 +376,20 @@ pub fn provide(providers: &mut Providers<'_>) {
             assert_eq!(cnum, LOCAL_CRATE);
             Lrc::new(crate::dependency_format::calculate(tcx))
         },
+        has_global_allocator: |tcx, cnum| {
+            assert_eq!(cnum, LOCAL_CRATE);
+            CStore::from_tcx(tcx).has_global_allocator()
+        },
+        postorder_cnums: |tcx, cnum| {
+            assert_eq!(cnum, LOCAL_CRATE);
+            tcx.arena.alloc_slice(&CStore::from_tcx(tcx).crate_dependencies_in_postorder(cnum))
+        },
 
         ..*providers
     };
 }
 
-impl cstore::CStore {
+impl CStore {
     pub fn export_macros_untracked(&self, cnum: CrateNum) {
         let data = self.get_crate_data(cnum);
         let mut dep_kind = data.dep_kind.lock();
@@ -458,9 +465,9 @@ impl cstore::CStore {
     }
 }
 
-impl CrateStore for cstore::CStore {
-    fn crate_data_as_any(&self, cnum: CrateNum) -> &dyn Any {
-        self.get_crate_data(cnum)
+impl CrateStore for CStore {
+    fn as_any(&self) -> &dyn Any {
+        self
     }
 
     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
@@ -486,10 +493,6 @@ impl CrateStore for cstore::CStore {
         self.get_crate_data(cnum).root.hash
     }
 
-    fn crate_host_hash_untracked(&self, cnum: CrateNum) -> Option<Svh> {
-        self.get_crate_data(cnum).host_hash
-    }
-
     /// Returns the `DefKey` for a given `DefId`. This indicates the
     /// parent `DefId` as well as some idea of what kind of data the
     /// `DefId` refers to.
@@ -516,10 +519,6 @@ impl CrateStore for cstore::CStore {
         result
     }
 
-    fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
-        self.do_postorder_cnums_untracked()
-    }
-
     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata {
         encoder::encode_metadata(tcx)
     }
@@ -529,11 +528,7 @@ impl CrateStore for cstore::CStore {
         rmeta::METADATA_HEADER
     }
 
-    fn injected_panic_runtime(&self) -> Option<CrateNum> {
-        self.injected_panic_runtime
-    }
-
     fn allocator_kind(&self) -> Option<AllocatorKind> {
-        self.allocator_kind
+        self.allocator_kind()
     }
 }
diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs
index 8074bde6123..3a318ddc1e1 100644
--- a/src/librustc_metadata/rmeta/encoder.rs
+++ b/src/librustc_metadata/rmeta/encoder.rs
@@ -496,7 +496,6 @@ impl<'tcx> EncodeContext<'tcx> {
 
         let attrs = tcx.hir().krate_attrs();
         let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
-        let has_global_allocator = *tcx.sess.has_global_allocator.get();
 
         let root = self.lazy(CrateRoot {
             name: tcx.crate_name(LOCAL_CRATE),
@@ -506,7 +505,7 @@ impl<'tcx> EncodeContext<'tcx> {
             disambiguator: tcx.sess.local_crate_disambiguator(),
             panic_strategy: tcx.sess.panic_strategy(),
             edition: tcx.sess.edition(),
-            has_global_allocator: has_global_allocator,
+            has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
             has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
             has_default_lib_allocator: has_default_lib_allocator,
             plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
diff --git a/src/librustc_metadata/rmeta/mod.rs b/src/librustc_metadata/rmeta/mod.rs
index 1bca2836a3a..4ea562fced3 100644
--- a/src/librustc_metadata/rmeta/mod.rs
+++ b/src/librustc_metadata/rmeta/mod.rs
@@ -173,16 +173,16 @@ macro_rules! Lazy {
 
 #[derive(RustcEncodable, RustcDecodable)]
 crate struct CrateRoot<'tcx> {
-    pub name: Symbol,
-    pub triple: TargetTriple,
+    name: Symbol,
+    triple: TargetTriple,
     extra_filename: String,
-    pub hash: Svh,
-    pub disambiguator: CrateDisambiguator,
-    pub panic_strategy: PanicStrategy,
+    hash: Svh,
+    disambiguator: CrateDisambiguator,
+    panic_strategy: PanicStrategy,
     edition: Edition,
-    pub has_global_allocator: bool,
+    has_global_allocator: bool,
     has_panic_handler: bool,
-    pub has_default_lib_allocator: bool,
+    has_default_lib_allocator: bool,
     plugin_registrar_fn: Option<DefIndex>,
     proc_macro_decls_static: Option<DefIndex>,
     proc_macro_stability: Option<attr::Stability>,
@@ -207,12 +207,12 @@ crate struct CrateRoot<'tcx> {
     proc_macro_data: Option<Lazy<[DefIndex]>>,
 
     compiler_builtins: bool,
-    pub needs_allocator: bool,
-    pub needs_panic_runtime: bool,
+    needs_allocator: bool,
+    needs_panic_runtime: bool,
     no_builtins: bool,
-    pub panic_runtime: bool,
-    pub profiler_runtime: bool,
-    pub sanitizer_runtime: bool,
+    panic_runtime: bool,
+    profiler_runtime: bool,
+    sanitizer_runtime: bool,
     symbol_mangling_version: SymbolManglingVersion,
 }
 
diff --git a/src/librustc_mir/borrow_check/conflict_errors.rs b/src/librustc_mir/borrow_check/conflict_errors.rs
index 8508bf62d8f..48f8ad9bbd8 100644
--- a/src/librustc_mir/borrow_check/conflict_errors.rs
+++ b/src/librustc_mir/borrow_check/conflict_errors.rs
@@ -7,6 +7,7 @@ use rustc::mir::{
     PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
 };
 use rustc::ty::{self, Ty};
+use rustc::traits::error_reporting::suggest_constraining_type_param;
 use rustc_data_structures::fx::FxHashSet;
 use rustc_index::vec::Idx;
 use rustc_errors::{Applicability, DiagnosticBuilder};
@@ -231,13 +232,16 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
                 if let ty::Param(param_ty) = ty.kind {
                     let tcx = self.infcx.tcx;
                     let generics = tcx.generics_of(self.mir_def_id);
-                    let def_id = generics.type_param(&param_ty, tcx).def_id;
-                    if let Some(sp) = tcx.hir().span_if_local(def_id) {
-                        err.span_label(
-                            sp,
-                            "consider adding a `Copy` constraint to this type argument",
-                        );
-                    }
+                    let param = generics.type_param(&param_ty, tcx);
+                    let generics = tcx.hir().get_generics(self.mir_def_id).unwrap();
+                    suggest_constraining_type_param(
+                        generics,
+                        &mut err,
+                        &param.name.as_str(),
+                        "Copy",
+                        tcx.sess.source_map(),
+                        span,
+                    );
                 }
                 let span = if let Some(local) = place.as_local() {
                     let decl = &self.body.local_decls[local];
diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs
index 649aeac12de..3a783f674e9 100644
--- a/src/librustc_mir/borrow_check/mod.rs
+++ b/src/librustc_mir/borrow_check/mod.rs
@@ -300,11 +300,10 @@ fn do_mir_borrowck<'a, 'tcx>(
         let mut initial_diag =
             mbcx.report_conflicting_borrow(location, (&place, span), bk, &borrow);
 
-        let lint_root = if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
-            let scope = mbcx.body.source_info(location).scope;
-            vsi[scope].lint_root
-        } else {
-            id
+        let scope = mbcx.body.source_info(location).scope;
+        let lint_root = match &mbcx.body.source_scopes[scope].local_data {
+            ClearCrossCrate::Set(data) => data.lint_root,
+            _ => id,
         };
 
         // Span and message don't matter; we overwrite them below anyway
@@ -338,38 +337,40 @@ fn do_mir_borrowck<'a, 'tcx>(
     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
     let used_mut = mbcx.used_mut;
     for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) {
-        if let ClearCrossCrate::Set(ref vsi) = mbcx.body.source_scope_local_data {
-            let local_decl = &mbcx.body.local_decls[local];
-
-            // Skip over locals that begin with an underscore or have no name
-            match mbcx.local_names[local] {
-                Some(name) => if name.as_str().starts_with("_") {
-                    continue;
-                },
-                None => continue,
-            }
+        let local_decl = &mbcx.body.local_decls[local];
+        let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data {
+            ClearCrossCrate::Set(data) => data.lint_root,
+            _ => continue,
+        };
 
-            let span = local_decl.source_info.span;
-            if span.desugaring_kind().is_some() {
-                // If the `mut` arises as part of a desugaring, we should ignore it.
+        // Skip over locals that begin with an underscore or have no name
+        match mbcx.local_names[local] {
+            Some(name) => if name.as_str().starts_with("_") {
                 continue;
-            }
+            },
+            None => continue,
+        }
 
-            let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
-            tcx.struct_span_lint_hir(
-                UNUSED_MUT,
-                vsi[local_decl.source_info.scope].lint_root,
-                span,
-                "variable does not need to be mutable",
-            )
-            .span_suggestion_short(
-                mut_span,
-                "remove this `mut`",
-                String::new(),
-                Applicability::MachineApplicable,
-            )
-            .emit();
+        let span = local_decl.source_info.span;
+        if span.desugaring_kind().is_some() {
+            // If the `mut` arises as part of a desugaring, we should ignore it.
+            continue;
         }
+
+        let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
+        tcx.struct_span_lint_hir(
+            UNUSED_MUT,
+            lint_root,
+            span,
+            "variable does not need to be mutable",
+        )
+        .span_suggestion_short(
+            mut_span,
+            "remove this `mut`",
+            String::new(),
+            Applicability::MachineApplicable,
+        )
+        .emit();
     }
 
     // Buffer any move errors that we collected and de-duplicated.
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs
index c0cf4eb5285..938059c2a92 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/outlives_suggestion.rs
@@ -78,17 +78,7 @@ impl OutlivesSuggestionBuilder<'a> {
         match name.source {
             RegionNameSource::NamedEarlyBoundRegion(..)
             | RegionNameSource::NamedFreeRegion(..)
-            | RegionNameSource::Static => {
-                // FIXME: This is a bit hacky. We should ideally have a semantic way for checking
-                // if the name is `'_`...
-                if name.name().with(|name| name != "'_") {
-                    debug!("Region {:?} is suggestable", name);
-                    true
-                } else {
-                    debug!("Region {:?} is NOT suggestable", name);
-                    false
-                }
-            }
+            | RegionNameSource::Static => true,
 
             // Don't give suggestions for upvars, closure return types, or other unnamable
             // regions.
@@ -98,7 +88,8 @@ impl OutlivesSuggestionBuilder<'a> {
             | RegionNameSource::MatchedAdtAndSegment(..)
             | RegionNameSource::AnonRegionFromUpvar(..)
             | RegionNameSource::AnonRegionFromOutput(..)
-            | RegionNameSource::AnonRegionFromYieldTy(..) => {
+            | RegionNameSource::AnonRegionFromYieldTy(..)
+            | RegionNameSource::AnonRegionFromAsyncFn(..) => {
                 debug!("Region {:?} is NOT suggestable", name);
                 false
             }
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
index e59928987a0..0f5d1c5edc4 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
@@ -13,13 +13,13 @@ use rustc::hir::def_id::DefId;
 use rustc::infer::InferCtxt;
 use rustc::mir::{Local, Body};
 use rustc::ty::subst::{SubstsRef, GenericArgKind};
-use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt};
+use rustc::ty::{self, RegionVid, Ty, TyCtxt};
 use rustc::ty::print::RegionHighlightMode;
 use rustc_index::vec::IndexVec;
 use rustc_errors::DiagnosticBuilder;
 use syntax::symbol::kw;
 use rustc_data_structures::fx::FxHashMap;
-use syntax_pos::{Span, symbol::Symbol};
+use syntax_pos::{Span, symbol::Symbol, DUMMY_SP};
 
 /// A name for a particular region used in emitting diagnostics. This name could be a generated
 /// name like `'1`, a name used by the user like `'a`, or a name like `'static`.
@@ -55,7 +55,10 @@ crate enum RegionNameSource {
     AnonRegionFromUpvar(Span, String),
     /// The region corresponding to the return type of a closure.
     AnonRegionFromOutput(Span, String, String),
+    /// The region from a type yielded by a generator.
     AnonRegionFromYieldTy(Span, String),
+    /// An anonymous region from an async fn.
+    AnonRegionFromAsyncFn(Span),
 }
 
 /// Records region names that have been assigned before so that we can use the same ones in later
@@ -113,14 +116,11 @@ impl RegionName {
             RegionNameSource::MatchedAdtAndSegment(..) |
             RegionNameSource::AnonRegionFromUpvar(..) |
             RegionNameSource::AnonRegionFromOutput(..) |
-            RegionNameSource::AnonRegionFromYieldTy(..) => false,
+            RegionNameSource::AnonRegionFromYieldTy(..) |
+            RegionNameSource::AnonRegionFromAsyncFn(..) => false,
         }
     }
 
-    crate fn name(&self) -> Symbol {
-        self.name
-    }
-
     crate fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) {
         match &self.source {
             RegionNameSource::NamedFreeRegion(span)
@@ -137,7 +137,8 @@ impl RegionName {
             RegionNameSource::CannotMatchHirTy(span, type_name) => {
                 diag.span_label(*span, format!("has type `{}`", type_name));
             }
-            RegionNameSource::MatchedHirTy(span) => {
+            RegionNameSource::MatchedHirTy(span) |
+            RegionNameSource::AnonRegionFromAsyncFn(span) => {
                 diag.span_label(
                     *span,
                     format!("let's call the lifetime of this reference `{}`", self),
@@ -270,7 +271,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
         match error_region {
             ty::ReEarlyBound(ebr) => {
                 if ebr.has_name() {
-                    let span = self.get_named_span(tcx, error_region, ebr.name);
+                    let span = tcx.hir().span_if_local(ebr.def_id).unwrap_or(DUMMY_SP);
                     Some(RegionName {
                         name: ebr.name,
                         source: RegionNameSource::NamedEarlyBoundRegion(span),
@@ -286,12 +287,30 @@ impl<'tcx> RegionInferenceContext<'tcx> {
             }),
 
             ty::ReFree(free_region) => match free_region.bound_region {
-                ty::BoundRegion::BrNamed(_, name) => {
-                    let span = self.get_named_span(tcx, error_region, name);
-                    Some(RegionName {
-                        name,
-                        source: RegionNameSource::NamedFreeRegion(span),
-                    })
+                ty::BoundRegion::BrNamed(region_def_id, name) => {
+                    // Get the span to point to, even if we don't use the name.
+                    let span = tcx.hir().span_if_local(region_def_id).unwrap_or(DUMMY_SP);
+                    debug!("bound region named: {:?}, is_named: {:?}",
+                        name, free_region.bound_region.is_named());
+
+                    if free_region.bound_region.is_named() {
+                        // A named region that is actually named.
+                        Some(RegionName {
+                            name,
+                            source: RegionNameSource::NamedFreeRegion(span),
+                        })
+                    } else {
+                        // If we spuriously thought that the region is named, we should let the
+                        // system generate a true name for error messages. Currently this can
+                        // happen if we have an elided name in an async fn for example: the
+                        // compiler will generate a region named `'_`, but reporting such a name is
+                        // not actually useful, so we synthesize a name for it instead.
+                        let name = renctx.synthesize_region_name();
+                        Some(RegionName {
+                            name,
+                            source: RegionNameSource::AnonRegionFromAsyncFn(span),
+                        })
+                    }
                 }
 
                 ty::BoundRegion::BrEnv => {
@@ -350,40 +369,6 @@ impl<'tcx> RegionInferenceContext<'tcx> {
         }
     }
 
-    /// Gets a span of a named region to provide context for error messages that
-    /// mention that span, for example:
-    ///
-    /// ```
-    ///  |
-    ///  | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
-    ///  |                --  -- lifetime `'b` defined here
-    ///  |                |
-    ///  |                lifetime `'a` defined here
-    ///  |
-    ///  |     with_signature(cell, t, |cell, t| require(cell, t));
-    ///  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
-    ///  |                                                         outlive `'a`
-    /// ```
-    fn get_named_span(
-        &self,
-        tcx: TyCtxt<'tcx>,
-        error_region: &RegionKind,
-        name: Symbol,
-    ) -> Span {
-        let scope = error_region.free_region_binding_scope(tcx);
-        let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
-
-        let span = tcx.sess.source_map().def_span(tcx.hir().span(node));
-        if let Some(param) = tcx.hir()
-            .get_generics(scope)
-            .and_then(|generics| generics.get_named(name))
-        {
-            param.span
-        } else {
-            span
-        }
-    }
-
     /// Finds an argument that contains `fr` and label it with a fully
     /// elaborated type, returning something like `'1`. Result looks
     /// like:
diff --git a/src/librustc_mir/build/matches/test.rs b/src/librustc_mir/build/matches/test.rs
index 07c5d640a32..c893d6f4856 100644
--- a/src/librustc_mir/build/matches/test.rs
+++ b/src/librustc_mir/build/matches/test.rs
@@ -84,10 +84,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
                 }
             }
 
+            PatKind::Or { .. } => {
+                self.hir.tcx().sess.span_fatal(
+                    match_pair.pattern.span,
+                    "or-patterns are not fully implemented yet"
+                )
+            }
+
             PatKind::AscribeUserType { .. } |
             PatKind::Array { .. } |
             PatKind::Wild |
-            PatKind::Or { .. } |
             PatKind::Binding { .. } |
             PatKind::Leaf { .. } |
             PatKind::Deref { .. } => {
diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs
index 180f2cc089f..eb9b401f272 100644
--- a/src/librustc_mir/build/mod.rs
+++ b/src/librustc_mir/build/mod.rs
@@ -5,7 +5,7 @@ use crate::hair::{LintLevel, BindingMode, PatKind};
 use crate::transform::MirSource;
 use crate::util as mir_util;
 use rustc::hir;
-use rustc::hir::Node;
+use rustc::hir::{Node, GeneratorKind};
 use rustc::hir::def_id::DefId;
 use rustc::middle::lang_items;
 use rustc::middle::region;
@@ -279,7 +279,7 @@ struct Builder<'a, 'tcx> {
 
     fn_span: Span,
     arg_count: usize,
-    is_generator: bool,
+    generator_kind: Option<GeneratorKind>,
 
     /// The current set of scopes, updated as we traverse;
     /// see the `scope` module for more details.
@@ -309,7 +309,6 @@ struct Builder<'a, 'tcx> {
     /// The vector of all scopes that we have created thus far;
     /// we track this for debuginfo later.
     source_scopes: IndexVec<SourceScope, SourceScopeData>,
-    source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
     source_scope: SourceScope,
 
     /// The guard-context: each time we build the guard expression for
@@ -570,7 +569,7 @@ where
         safety,
         return_ty,
         return_ty_span,
-        body.generator_kind.is_some());
+        body.generator_kind);
 
     let call_site_scope = region::Scope {
         id: body.value.hir_id.local_id,
@@ -647,7 +646,7 @@ fn construct_const<'a, 'tcx>(
         Safety::Safe,
         const_ty,
         const_ty_span,
-        false,
+        None,
     );
 
     let mut block = START_BLOCK;
@@ -678,7 +677,7 @@ fn construct_error<'a, 'tcx>(
     let owner_id = hir.tcx().hir().body_owner(body_id);
     let span = hir.tcx().hir().span(owner_id);
     let ty = hir.tcx().types.err;
-    let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, false);
+    let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, None);
     let source_info = builder.source_info(span);
     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
     builder.finish()
@@ -691,7 +690,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
            safety: Safety,
            return_ty: Ty<'tcx>,
            return_span: Span,
-           is_generator: bool)
+           generator_kind: Option<GeneratorKind>)
            -> Builder<'a, 'tcx> {
         let lint_level = LintLevel::Explicit(hir.root_lint_level);
         let mut builder = Builder {
@@ -699,12 +698,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
             cfg: CFG { basic_blocks: IndexVec::new() },
             fn_span: span,
             arg_count,
-            is_generator,
+            generator_kind,
             scopes: Default::default(),
             block_context: BlockContext::new(),
             source_scopes: IndexVec::new(),
             source_scope: OUTERMOST_SOURCE_SCOPE,
-            source_scope_local_data: IndexVec::new(),
             guard_context: vec![],
             push_unsafe_count: 0,
             unpushed_unsafe: safety,
@@ -741,13 +739,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
         Body::new(
             self.cfg.basic_blocks,
             self.source_scopes,
-            ClearCrossCrate::Set(self.source_scope_local_data),
             self.local_decls,
             self.canonical_user_type_annotations,
             self.arg_count,
             self.var_debug_info,
             self.fn_span,
             self.hir.control_flow_destroyed(),
+            self.generator_kind
         )
     }
 
@@ -941,7 +939,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
             self.hir.root_lint_level
         );
         let parent_root = tcx.maybe_lint_level_root_bounded(
-            self.source_scope_local_data[original_source_scope].lint_root,
+            self.source_scopes[original_source_scope]
+                .local_data
+                .as_ref()
+                .assert_crate_local()
+                .lint_root,
             self.hir.root_lint_level,
         );
         if current_root != parent_root {
diff --git a/src/librustc_mir/build/scope.rs b/src/librustc_mir/build/scope.rs
index 1b3d8641f20..00a30af806a 100644
--- a/src/librustc_mir/build/scope.rs
+++ b/src/librustc_mir/build/scope.rs
@@ -91,6 +91,7 @@ use syntax_pos::{DUMMY_SP, Span};
 use rustc_data_structures::fx::FxHashMap;
 use std::collections::hash_map::Entry;
 use std::mem;
+use rustc::hir::GeneratorKind;
 
 #[derive(Debug)]
 struct Scope {
@@ -219,7 +220,12 @@ impl Scope {
     /// `storage_only` controls whether to invalidate only drop paths that run `StorageDead`.
     /// `this_scope_only` controls whether to invalidate only drop paths that refer to the current
     /// top-of-scope (as opposed to dependent scopes).
-    fn invalidate_cache(&mut self, storage_only: bool, is_generator: bool, this_scope_only: bool) {
+    fn invalidate_cache(
+        &mut self,
+        storage_only: bool,
+        generator_kind: Option<GeneratorKind>,
+        this_scope_only: bool
+    ) {
         // FIXME: maybe do shared caching of `cached_exits` etc. to handle functions
         // with lots of `try!`?
 
@@ -229,7 +235,7 @@ impl Scope {
         // the current generator drop and unwind refer to top-of-scope
         self.cached_generator_drop = None;
 
-        let ignore_unwinds = storage_only && !is_generator;
+        let ignore_unwinds = storage_only && generator_kind.is_none();
         if !ignore_unwinds {
             self.cached_unwind.invalidate();
         }
@@ -430,7 +436,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
             // We estimate the true lint roots here to avoid creating a lot of source scopes.
 
             let parent_root = tcx.maybe_lint_level_root_bounded(
-                self.source_scope_local_data[source_scope].lint_root,
+                self.source_scopes[source_scope]
+                    .local_data
+                    .as_ref()
+                    .assert_crate_local()
+                    .lint_root,
                 self.hir.root_lint_level,
             );
             let current_root = tcx.maybe_lint_level_root_bounded(
@@ -481,7 +491,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
 
         unpack!(block = build_scope_drops(
             &mut self.cfg,
-            self.is_generator,
+            self.generator_kind,
             &scope,
             block,
             unwind_to,
@@ -574,7 +584,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
 
             unpack!(block = build_scope_drops(
                 &mut self.cfg,
-                self.is_generator,
+                self.generator_kind,
                 scope,
                 block,
                 unwind_to,
@@ -625,7 +635,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
 
             unpack!(block = build_scope_drops(
                 &mut self.cfg,
-                self.is_generator,
+                self.generator_kind,
                 scope,
                 block,
                 unwind_to,
@@ -648,23 +658,22 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
         let parent = self.source_scope;
         debug!("new_source_scope({:?}, {:?}, {:?}) - parent({:?})={:?}",
                span, lint_level, safety,
-               parent, self.source_scope_local_data.get(parent));
-        let scope = self.source_scopes.push(SourceScopeData {
-            span,
-            parent_scope: Some(parent),
-        });
+               parent, self.source_scopes.get(parent));
         let scope_local_data = SourceScopeLocalData {
             lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
                 lint_root
             } else {
-                self.source_scope_local_data[parent].lint_root
+                self.source_scopes[parent].local_data.as_ref().assert_crate_local().lint_root
             },
             safety: safety.unwrap_or_else(|| {
-                self.source_scope_local_data[parent].safety
+                self.source_scopes[parent].local_data.as_ref().assert_crate_local().safety
             })
         };
-        self.source_scope_local_data.push(scope_local_data);
-        scope
+        self.source_scopes.push(SourceScopeData {
+            span,
+            parent_scope: Some(parent),
+            local_data: ClearCrossCrate::Set(scope_local_data),
+        })
     }
 
     /// Given a span and the current source scope, make a SourceInfo.
@@ -809,7 +818,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
             // invalidating caches of each scope visited. This way bare minimum of the
             // caches gets invalidated. i.e., if a new drop is added into the middle scope, the
             // cache of outer scope stays intact.
-            scope.invalidate_cache(!needs_drop, self.is_generator, this_scope);
+            scope.invalidate_cache(!needs_drop, self.generator_kind, this_scope);
             if this_scope {
                 let region_scope_span = region_scope.span(self.hir.tcx(),
                                                           &self.hir.region_scope_tree);
@@ -958,7 +967,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
                         }
                     }
 
-                    top_scope.invalidate_cache(true, self.is_generator, true);
+                    top_scope.invalidate_cache(true, self.generator_kind, true);
                 } else {
                     bug!("Expected as_local_operand to produce a temporary");
                 }
@@ -1016,7 +1025,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
 
         for scope in self.scopes.top_scopes(first_uncached) {
             target = build_diverge_scope(&mut self.cfg, scope.region_scope_span,
-                                         scope, target, generator_drop, self.is_generator);
+                                         scope, target, generator_drop, self.generator_kind);
         }
 
         target
@@ -1079,14 +1088,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
         assert_eq!(top_scope.region_scope, region_scope);
 
         top_scope.drops.clear();
-        top_scope.invalidate_cache(false, self.is_generator, true);
+        top_scope.invalidate_cache(false, self.generator_kind, true);
     }
 }
 
 /// Builds drops for pop_scope and exit_scope.
 fn build_scope_drops<'tcx>(
     cfg: &mut CFG<'tcx>,
-    is_generator: bool,
+    generator_kind: Option<GeneratorKind>,
     scope: &Scope,
     mut block: BasicBlock,
     last_unwind_to: BasicBlock,
@@ -1130,7 +1139,7 @@ fn build_scope_drops<'tcx>(
                     continue;
                 }
 
-                let unwind_to = get_unwind_to(scope, is_generator, drop_idx, generator_drop)
+                let unwind_to = get_unwind_to(scope, generator_kind, drop_idx, generator_drop)
                     .unwrap_or(last_unwind_to);
 
                 let next = cfg.start_new_block();
@@ -1156,19 +1165,19 @@ fn build_scope_drops<'tcx>(
 
 fn get_unwind_to(
     scope: &Scope,
-    is_generator: bool,
+    generator_kind: Option<GeneratorKind>,
     unwind_from: usize,
     generator_drop: bool,
 ) -> Option<BasicBlock> {
     for drop_idx in (0..unwind_from).rev() {
         let drop_data = &scope.drops[drop_idx];
-        match (is_generator, &drop_data.kind) {
-            (true, DropKind::Storage) => {
+        match (generator_kind, &drop_data.kind) {
+            (Some(_), DropKind::Storage) => {
                 return Some(drop_data.cached_block.get(generator_drop).unwrap_or_else(|| {
                     span_bug!(drop_data.span, "cached block not present for {:?}", drop_data)
                 }));
             }
-            (false, DropKind::Value) => {
+            (None, DropKind::Value) => {
                 return Some(drop_data.cached_block.get(generator_drop).unwrap_or_else(|| {
                     span_bug!(drop_data.span, "cached block not present for {:?}", drop_data)
                 }));
@@ -1184,7 +1193,7 @@ fn build_diverge_scope<'tcx>(cfg: &mut CFG<'tcx>,
                              scope: &mut Scope,
                              mut target: BasicBlock,
                              generator_drop: bool,
-                             is_generator: bool)
+                             generator_kind: Option<GeneratorKind>)
                              -> BasicBlock
 {
     // Build up the drops in **reverse** order. The end result will
@@ -1224,7 +1233,7 @@ fn build_diverge_scope<'tcx>(cfg: &mut CFG<'tcx>,
         // match the behavior of clang, but on inspection eddyb says
         // this is not what clang does.
         match drop_data.kind {
-            DropKind::Storage if is_generator => {
+            DropKind::Storage if generator_kind.is_some() => {
                 storage_deads.push(Statement {
                     source_info: source_info(drop_data.span),
                     kind: StatementKind::StorageDead(drop_data.local)
diff --git a/src/librustc_mir/const_eval.rs b/src/librustc_mir/const_eval.rs
index eb9d04f7d8e..0967b257885 100644
--- a/src/librustc_mir/const_eval.rs
+++ b/src/librustc_mir/const_eval.rs
@@ -146,7 +146,16 @@ fn eval_body_using_ecx<'mir, 'tcx>(
     let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
-    assert!(body.arg_count == 0);
+
+    // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
+    // make sense if the body is expecting nontrivial arguments.
+    // (The alternative would be to use `eval_fn_call` with an args slice.)
+    for arg in body.args_iter() {
+        let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
+        let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
+        assert!(layout.is_zst())
+    };
+
     ecx.push_stack_frame(
         cid.instance,
         body.span,
diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs
index afc4e461c0d..8c852854be1 100644
--- a/src/librustc_mir/hair/cx/expr.rs
+++ b/src/librustc_mir/hair/cx/expr.rs
@@ -933,14 +933,7 @@ fn convert_path_expr<'a, 'tcx>(
         // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is
         // a constant reference (or constant raw pointer for `static mut`) in MIR
         Res::Def(DefKind::Static, id) => {
-            let ty = cx.tcx.type_of(id);
-            let ty = if cx.tcx.is_mutable_static(id) {
-                cx.tcx.mk_mut_ptr(ty)
-            } else if cx.tcx.is_foreign_item(id) {
-                cx.tcx.mk_imm_ptr(ty)
-            } else {
-                cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_static, ty)
-            };
+            let ty = cx.tcx.static_ptr_ty(id);
             let ptr = cx.tcx.alloc_map.lock().create_static_alloc(id);
             let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
             ExprKind::Deref { arg: Expr {
diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs
index 5e7a7f01e7a..f2c5bf1bf6d 100644
--- a/src/librustc_mir/hair/pattern/_match.rs
+++ b/src/librustc_mir/hair/pattern/_match.rs
@@ -347,6 +347,7 @@ impl PatternFolder<'tcx> for LiteralExpander<'tcx> {
             ) => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty),
 
             (_, &PatKind::Binding { subpattern: Some(ref s), .. }) => s.fold_with(self),
+            (_, &PatKind::AscribeUserType { subpattern: ref s, .. }) => s.fold_with(self),
             _ => pat.super_fold_with(self),
         }
     }
@@ -399,6 +400,25 @@ impl<'p, 'tcx> PatStack<'p, 'tcx> {
         self.0.iter().map(|p| *p)
     }
 
+    // If the first pattern is an or-pattern, expand this pattern. Otherwise, return `None`.
+    fn expand_or_pat(&self) -> Option<Vec<Self>> {
+        if self.is_empty() {
+            None
+        } else if let PatKind::Or { pats } = &*self.head().kind {
+            Some(
+                pats.iter()
+                    .map(|pat| {
+                        let mut new_patstack = PatStack::from_pattern(pat);
+                        new_patstack.0.extend_from_slice(&self.0[1..]);
+                        new_patstack
+                    })
+                    .collect(),
+            )
+        } else {
+            None
+        }
+    }
+
     /// This computes `D(self)`. See top of the file for explanations.
     fn specialize_wildcard(&self) -> Option<Self> {
         if self.head().is_wildcard() { Some(self.to_tail()) } else { None }
@@ -446,8 +466,13 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
         Matrix(vec![])
     }
 
+    /// Pushes a new row to the matrix. If the row starts with an or-pattern, this expands it.
     pub fn push(&mut self, row: PatStack<'p, 'tcx>) {
-        self.0.push(row)
+        if let Some(rows) = row.expand_or_pat() {
+            self.0.extend(rows);
+        } else {
+            self.0.push(row);
+        }
     }
 
     /// Iterate over the first component of each row
@@ -471,12 +496,10 @@ impl<'p, 'tcx> Matrix<'p, 'tcx> {
         'a: 'q,
         'p: 'q,
     {
-        Matrix(
-            self.0
-                .iter()
-                .filter_map(|r| r.specialize_constructor(cx, constructor, ctor_wild_subpatterns))
-                .collect(),
-        )
+        self.0
+            .iter()
+            .filter_map(|r| r.specialize_constructor(cx, constructor, ctor_wild_subpatterns))
+            .collect()
     }
 }
 
@@ -528,7 +551,12 @@ impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
     where
         T: IntoIterator<Item = PatStack<'p, 'tcx>>,
     {
-        Matrix(iter.into_iter().collect())
+        let mut matrix = Matrix::empty();
+        for x in iter {
+            // Using `push` ensures we correctly expand or-patterns.
+            matrix.push(x);
+        }
+        matrix
     }
 }
 
@@ -747,7 +775,7 @@ impl<'tcx> Constructor<'tcx> {
                     .iter()
                     .filter_map(|c: &Constructor<'_>| match c {
                         Slice(slice) => Some(*slice),
-                        // FIXME(#65413): We ignore `ConstantValue`s here.
+                        // FIXME(oli-obk): implement `deref` for `ConstValue`
                         ConstantValue(..) => None,
                         _ => bug!("bad slice pattern constructor {:?}", c),
                     })
@@ -1601,6 +1629,15 @@ pub fn is_useful<'p, 'a, 'tcx>(
 
     assert!(rows.iter().all(|r| r.len() == v.len()));
 
+    // If the first pattern is an or-pattern, expand it.
+    if let Some(vs) = v.expand_or_pat() {
+        return vs
+            .into_iter()
+            .map(|v| is_useful(cx, matrix, &v, witness_preference, hir_id))
+            .find(|result| result.is_useful())
+            .unwrap_or(NotUseful);
+    }
+
     let (ty, span) = matrix
         .heads()
         .map(|r| (r.ty, r.span))
@@ -1759,9 +1796,7 @@ fn pat_constructor<'tcx>(
     pat: &Pat<'tcx>,
 ) -> Option<Constructor<'tcx>> {
     match *pat.kind {
-        PatKind::AscribeUserType { ref subpattern, .. } => {
-            pat_constructor(tcx, param_env, subpattern)
-        }
+        PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
         PatKind::Binding { .. } | PatKind::Wild => None,
         PatKind::Leaf { .. } | PatKind::Deref { .. } => Some(Single),
         PatKind::Variant { adt_def, variant_index, .. } => {
@@ -1771,7 +1806,19 @@ fn pat_constructor<'tcx>(
             if let Some(int_range) = IntRange::from_const(tcx, param_env, value, pat.span) {
                 Some(IntRange(int_range))
             } else {
-                Some(ConstantValue(value))
+                match (value.val, &value.ty.kind) {
+                    (_, ty::Array(_, n)) => {
+                        let len = n.eval_usize(tcx, param_env);
+                        Some(Slice(Slice { array_len: Some(len), kind: FixedLen(len) }))
+                    }
+                    (ty::ConstKind::Value(ConstValue::Slice { start, end, .. }), ty::Slice(_)) => {
+                        let len = (end - start) as u64;
+                        Some(Slice(Slice { array_len: None, kind: FixedLen(len) }))
+                    }
+                    // FIXME(oli-obk): implement `deref` for `ConstValue`
+                    // (ty::ConstKind::Value(ConstValue::ByRef { .. }), ty::Slice(_)) => { ... }
+                    _ => Some(ConstantValue(value)),
+                }
             }
         }
         PatKind::Range(PatRange { lo, hi, end }) => {
@@ -1802,9 +1849,7 @@ fn pat_constructor<'tcx>(
                 if slice.is_some() { VarLen(prefix, suffix) } else { FixedLen(prefix + suffix) };
             Some(Slice(Slice { array_len, kind }))
         }
-        PatKind::Or { .. } => {
-            bug!("support for or-patterns has not been fully implemented yet.");
-        }
+        PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
     }
 }
 
@@ -2085,32 +2130,19 @@ fn split_grouped_constructors<'p, 'tcx>(
                 let mut max_suffix_len = self_suffix;
                 let mut max_fixed_len = 0;
 
-                for row in matrix.heads() {
-                    match *row.kind {
-                        PatKind::Constant { value } => {
-                            // extract the length of an array/slice from a constant
-                            match (value.val, &value.ty.kind) {
-                                (_, ty::Array(_, n)) => {
-                                    max_fixed_len =
-                                        cmp::max(max_fixed_len, n.eval_usize(tcx, param_env))
-                                }
-                                (
-                                    ty::ConstKind::Value(ConstValue::Slice { start, end, .. }),
-                                    ty::Slice(_),
-                                ) => max_fixed_len = cmp::max(max_fixed_len, (end - start) as u64),
-                                _ => {}
+                let head_ctors =
+                    matrix.heads().filter_map(|pat| pat_constructor(tcx, param_env, pat));
+                for ctor in head_ctors {
+                    match ctor {
+                        Slice(slice) => match slice.pattern_kind() {
+                            FixedLen(len) => {
+                                max_fixed_len = cmp::max(max_fixed_len, len);
                             }
-                        }
-                        PatKind::Slice { ref prefix, slice: None, ref suffix }
-                        | PatKind::Array { ref prefix, slice: None, ref suffix } => {
-                            let fixed_len = prefix.len() as u64 + suffix.len() as u64;
-                            max_fixed_len = cmp::max(max_fixed_len, fixed_len);
-                        }
-                        PatKind::Slice { ref prefix, slice: Some(_), ref suffix }
-                        | PatKind::Array { ref prefix, slice: Some(_), ref suffix } => {
-                            max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
-                            max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
-                        }
+                            VarLen(prefix, suffix) => {
+                                max_prefix_len = cmp::max(max_prefix_len, prefix);
+                                max_suffix_len = cmp::max(max_suffix_len, suffix);
+                            }
+                        },
                         _ => {}
                     }
                 }
@@ -2250,21 +2282,17 @@ fn patterns_for_variant<'p, 'a: 'p, 'tcx>(
 /// fields filled with wild patterns.
 fn specialize_one_pattern<'p, 'a: 'p, 'q: 'p, 'tcx>(
     cx: &mut MatchCheckCtxt<'a, 'tcx>,
-    mut pat: &'q Pat<'tcx>,
+    pat: &'q Pat<'tcx>,
     constructor: &Constructor<'tcx>,
     ctor_wild_subpatterns: &[&'p Pat<'tcx>],
 ) -> Option<PatStack<'p, 'tcx>> {
-    while let PatKind::AscribeUserType { ref subpattern, .. } = *pat.kind {
-        pat = subpattern;
-    }
-
     if let NonExhaustive = constructor {
         // Only a wildcard pattern can match the special extra constructor
         return if pat.is_wildcard() { Some(PatStack::default()) } else { None };
     }
 
     let result = match *pat.kind {
-        PatKind::AscribeUserType { .. } => bug!(), // Handled above
+        PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
 
         PatKind::Binding { .. } | PatKind::Wild => {
             Some(PatStack::from_slice(ctor_wild_subpatterns))
@@ -2410,9 +2438,7 @@ fn specialize_one_pattern<'p, 'a: 'p, 'q: 'p, 'tcx>(
             _ => span_bug!(pat.span, "unexpected ctor {:?} for slice pat", constructor),
         },
 
-        PatKind::Or { .. } => {
-            bug!("support for or-patterns has not been fully implemented yet.");
-        }
+        PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
     };
     debug!("specialize({:#?}, {:#?}) = {:#?}", pat, ctor_wild_subpatterns, result);
 
diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs
index 626e81fa911..6c16c4f2219 100644
--- a/src/librustc_mir/interpret/eval_context.rs
+++ b/src/librustc_mir/interpret/eval_context.rs
@@ -548,7 +548,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
 
         info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
 
-        if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit {
+        if self.stack.len() > *self.tcx.sess.recursion_limit.get() {
             throw_exhaust!(StackFrameLimitReached)
         } else {
             Ok(())
@@ -849,8 +849,8 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
                 } else {
                     block.terminator().source_info
                 };
-                match body.source_scope_local_data {
-                    mir::ClearCrossCrate::Set(ref ivs) => Some(ivs[source_info.scope].lint_root),
+                match &body.source_scopes[source_info.scope].local_data {
+                    mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
                     mir::ClearCrossCrate::Clear => None,
                 }
             });
diff --git a/src/librustc_mir/interpret/intern.rs b/src/librustc_mir/interpret/intern.rs
index 630f3f60344..f9cb40ffe94 100644
--- a/src/librustc_mir/interpret/intern.rs
+++ b/src/librustc_mir/interpret/intern.rs
@@ -100,7 +100,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>>(
     // This match is just a canary for future changes to `MemoryKind`, which most likely need
     // changes in this function.
     match kind {
-        MemoryKind::Stack | MemoryKind::Vtable => {},
+        MemoryKind::Stack | MemoryKind::Vtable | MemoryKind::CallerLocation => {},
     }
     // Set allocation mutability as appropriate. This is used by LLVM to put things into
     // read-only memory, and also by Miri when evluating other constants/statics that
diff --git a/src/librustc_mir/interpret/intrinsics/caller_location.rs b/src/librustc_mir/interpret/intrinsics/caller_location.rs
index 88bfcd63129..9e07a3f1072 100644
--- a/src/librustc_mir/interpret/intrinsics/caller_location.rs
+++ b/src/librustc_mir/interpret/intrinsics/caller_location.rs
@@ -28,7 +28,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
         let file = Scalar::Ptr(self.tag_static_base_pointer(file_ptr));
         let file_len = Scalar::from_uint(filename.as_str().len() as u128, ptr_size);
 
-        let location = self.allocate(loc_layout, MemoryKind::Stack);
+        let location = self.allocate(loc_layout, MemoryKind::CallerLocation);
 
         let file_out = self.mplace_field(location, 0)?;
         let file_ptr_out = self.force_ptr(self.mplace_field(file_out, 0)?.ptr)?;
diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs
index eccdc5b0326..a8011f7abb1 100644
--- a/src/librustc_mir/interpret/memory.rs
+++ b/src/librustc_mir/interpret/memory.rs
@@ -24,11 +24,13 @@ use super::{
 
 #[derive(Debug, PartialEq, Copy, Clone)]
 pub enum MemoryKind<T> {
-    /// Error if deallocated except during a stack pop
+    /// Stack memory. Error if deallocated except during a stack pop.
     Stack,
-    /// Error if ever deallocated
+    /// Memory backing vtables. Error if ever deallocated.
     Vtable,
-    /// Additional memory kinds a machine wishes to distinguish from the builtin ones
+    /// Memory allocated by `caller_location` intrinsic. Error if ever deallocated.
+    CallerLocation,
+    /// Additional memory kinds a machine wishes to distinguish from the builtin ones.
     Machine(T),
 }
 
@@ -38,6 +40,7 @@ impl<T: MayLeak> MayLeak for MemoryKind<T> {
         match self {
             MemoryKind::Stack => false,
             MemoryKind::Vtable => true,
+            MemoryKind::CallerLocation => true,
             MemoryKind::Machine(k) => k.may_leak()
         }
     }
@@ -719,6 +722,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
                     let extra = match kind {
                         MemoryKind::Stack => " (stack)".to_owned(),
                         MemoryKind::Vtable => " (vtable)".to_owned(),
+                        MemoryKind::CallerLocation => " (caller_location)".to_owned(),
                         MemoryKind::Machine(m) => format!(" ({:?})", m),
                     };
                     self.dump_alloc_helper(
diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs
index 5b263f76801..70d9836b6ff 100644
--- a/src/librustc_mir/interpret/place.rs
+++ b/src/librustc_mir/interpret/place.rs
@@ -651,20 +651,28 @@ where
         use rustc::mir::PlaceBase;
 
         let mut place_ty = match &place.base {
-            PlaceBase::Local(mir::RETURN_PLACE) => match self.frame().return_place {
-                Some(return_place) => {
-                    // We use our layout to verify our assumption; caller will validate
-                    // their layout on return.
-                    PlaceTy {
-                        place: *return_place,
-                        layout: self.layout_of(
-                            self.subst_from_frame_and_normalize_erasing_regions(
-                                self.frame().body.return_ty()
-                            )
-                        )?,
-                    }
+            PlaceBase::Local(mir::RETURN_PLACE) => {
+                // `return_place` has the *caller* layout, but we want to use our
+                // `layout to verify our assumption. The caller will validate
+                // their layout on return.
+                PlaceTy {
+                    place: match self.frame().return_place {
+                        Some(p) => *p,
+                        // Even if we don't have a return place, we sometimes need to
+                        // create this place, but any attempt to read from / write to it
+                        // (even a ZST read/write) needs to error, so let us make this
+                        // a NULL place.
+                        //
+                        // FIXME: Ideally we'd make sure that the place projections also
+                        // bail out.
+                        None => Place::null(&*self),
+                    },
+                    layout: self.layout_of(
+                        self.subst_from_frame_and_normalize_erasing_regions(
+                            self.frame().body.return_ty()
+                        )
+                    )?,
                 }
-                None => throw_unsup!(InvalidNullPointerUsage),
             },
             PlaceBase::Local(local) => PlaceTy {
                 // This works even for dead/uninitialized locals; we check further when writing
@@ -791,8 +799,8 @@ where
         // to handle padding properly, which is only correct if we never look at this data with the
         // wrong type.
 
-        let ptr = match self.check_mplace_access(dest, None)
-            .expect("places should be checked on creation")
+        // Invalid places are a thing: the return place of a diverging function
+        let ptr = match self.check_mplace_access(dest, None)?
         {
             Some(ptr) => ptr,
             None => return Ok(()), // zero-sized access
diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs
index daa0a5e1bc4..50cd3188510 100644
--- a/src/librustc_mir/interpret/terminator.rs
+++ b/src/librustc_mir/interpret/terminator.rs
@@ -7,7 +7,7 @@ use syntax::source_map::Span;
 use rustc_target::spec::abi::Abi;
 
 use super::{
-    InterpResult, PointerArithmetic,
+    GlobalId, InterpResult, PointerArithmetic,
     InterpCx, Machine, OpTy, ImmTy, PlaceTy, MPlaceTy, StackPopCleanup, FnVal,
 };
 
@@ -142,8 +142,10 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
                         OverflowNeg => err_panic!(OverflowNeg),
                         DivisionByZero => err_panic!(DivisionByZero),
                         RemainderByZero => err_panic!(RemainderByZero),
-                        GeneratorResumedAfterReturn => err_panic!(GeneratorResumedAfterReturn),
-                        GeneratorResumedAfterPanic => err_panic!(GeneratorResumedAfterPanic),
+                        ResumedAfterReturn(generator_kind)
+                            => err_panic!(ResumedAfterReturn(*generator_kind)),
+                        ResumedAfterPanic(generator_kind)
+                            => err_panic!(ResumedAfterPanic(*generator_kind)),
                         Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
                     }
                     .into());
@@ -284,6 +286,18 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
             ty::InstanceDef::DropGlue(..) |
             ty::InstanceDef::CloneShim(..) |
             ty::InstanceDef::Item(_) => {
+                // If this function is a `const fn` then as an optimization we can query this
+                // evaluation immediately.
+                //
+                // For the moment we only do this for functions which take no arguments
+                // (or all arguments are ZSTs) so that we don't memoize too much.
+                if self.tcx.is_const_fn_raw(instance.def.def_id()) &&
+                   args.iter().all(|a| a.layout.is_zst())
+                {
+                    let gid = GlobalId { instance, promoted: None };
+                    return self.eval_const_fn_call(gid, ret);
+                }
+
                 // We need MIR for this fn
                 let body = match M::find_fn(self, instance, args, ret, unwind)? {
                     Some(body) => body,
@@ -449,6 +463,25 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
         }
     }
 
+    /// Evaluate a const function where all arguments (if any) are zero-sized types.
+    /// The evaluation is memoized thanks to the query system.
+    fn eval_const_fn_call(
+        &mut self,
+        gid: GlobalId<'tcx>,
+        ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>,
+    ) -> InterpResult<'tcx> {
+        trace!("eval_const_fn_call: {:?}", gid);
+
+        let place = self.const_eval_raw(gid)?;
+        let dest = ret.ok_or_else(|| err_ub!(Unreachable))?.0;
+
+        self.copy_op(place.into(), dest)?;
+
+        self.return_to_block(ret.map(|r| r.1))?;
+        self.dump_place(*dest);
+        return Ok(())
+    }
+
     fn drop_in_place(
         &mut self,
         place: PlaceTy<'tcx, M::PointerTag>,
diff --git a/src/librustc_mir/lib.rs b/src/librustc_mir/lib.rs
index cca76700ed1..f4fb9a5e4f2 100644
--- a/src/librustc_mir/lib.rs
+++ b/src/librustc_mir/lib.rs
@@ -29,6 +29,7 @@ Rust MIR: a lowered representation of Rust. Also: an experiment!
 #![feature(stmt_expr_attributes)]
 #![feature(bool_to_option)]
 #![feature(trait_alias)]
+#![feature(matches_macro)]
 
 #![recursion_limit="256"]
 
diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs
index b5cb6a92816..708686fdcf9 100644
--- a/src/librustc_mir/shim.rs
+++ b/src/librustc_mir/shim.rs
@@ -196,19 +196,11 @@ fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>)
     block(&mut blocks, TerminatorKind::Goto { target: return_block });
     block(&mut blocks, TerminatorKind::Return);
 
-    let mut body = Body::new(
+    let mut body = new_body(
         blocks,
-        IndexVec::from_elem_n(
-            SourceScopeData { span: span, parent_scope: None }, 1
-        ),
-        ClearCrossCrate::Clear,
         local_decls_for_sig(&sig, span),
-        IndexVec::new(),
         sig.inputs().len(),
-        vec![],
-        span,
-        vec![],
-    );
+        span);
 
     if let Some(..) = ty {
         // The first argument (index 0), but add 1 for the return value.
@@ -247,6 +239,28 @@ fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>)
     body
 }
 
+fn new_body<'tcx>(
+    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
+    local_decls: IndexVec<Local, LocalDecl<'tcx>>,
+    arg_count: usize,
+    span: Span,
+) -> Body<'tcx> {
+    Body::new(
+        basic_blocks,
+        IndexVec::from_elem_n(
+            SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
+            1,
+        ),
+        local_decls,
+        IndexVec::new(),
+        arg_count,
+        vec![],
+        span,
+        vec![],
+        None,
+    )
+}
+
 pub struct DropShimElaborator<'a, 'tcx> {
     pub body: &'a Body<'tcx>,
     pub patch: MirPatch<'tcx>,
@@ -362,18 +376,11 @@ impl CloneShimBuilder<'tcx> {
     }
 
     fn into_mir(self) -> Body<'tcx> {
-        Body::new(
+        new_body(
             self.blocks,
-            IndexVec::from_elem_n(
-                SourceScopeData { span: self.span, parent_scope: None }, 1
-            ),
-            ClearCrossCrate::Clear,
             self.local_decls,
-            IndexVec::new(),
             self.sig.inputs().len(),
-            vec![],
             self.span,
-            vec![],
         )
     }
 
@@ -822,19 +829,13 @@ fn build_call_shim<'tcx>(
         block(&mut blocks, vec![], TerminatorKind::Resume, true);
     }
 
-    let mut body = Body::new(
+    let mut body = new_body(
         blocks,
-        IndexVec::from_elem_n(
-            SourceScopeData { span: span, parent_scope: None }, 1
-        ),
-        ClearCrossCrate::Clear,
         local_decls,
-        IndexVec::new(),
         sig.inputs().len(),
-        vec![],
         span,
-        vec![],
     );
+
     if let Abi::RustCall = sig.abi {
         body.spread_arg = Some(Local::new(sig.inputs().len()));
     }
@@ -908,18 +909,11 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &Body<'_> {
         is_cleanup: false
     };
 
-    let body = Body::new(
+    let body = new_body(
         IndexVec::from_elem_n(start_block, 1),
-        IndexVec::from_elem_n(
-            SourceScopeData { span: span, parent_scope: None }, 1
-        ),
-        ClearCrossCrate::Clear,
         local_decls,
-        IndexVec::new(),
         sig.inputs().len(),
-        vec![],
         span,
-        vec![],
     );
 
     crate::util::dump_mir(
diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs
index acad56be604..a4f12a4e54f 100644
--- a/src/librustc_mir/transform/check_consts/ops.rs
+++ b/src/librustc_mir/transform/check_consts/ops.rs
@@ -4,7 +4,7 @@ use rustc::hir::def_id::DefId;
 use rustc::mir::BorrowKind;
 use rustc::session::config::nightly_options;
 use rustc::ty::TyCtxt;
-use syntax::feature_gate::{emit_feature_err, GateIssue};
+use syntax::feature_gate::feature_err;
 use syntax::symbol::sym;
 use syntax_pos::{Span, Symbol};
 
@@ -222,13 +222,13 @@ impl NonConstOp for Panic {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
+        feature_err(
             &item.tcx.sess.parse_sess,
             sym::const_panic,
             span,
-            GateIssue::Language,
             &format!("panicking in {}s is unstable", item.const_kind()),
-        );
+        )
+        .emit();
     }
 }
 
@@ -240,13 +240,13 @@ impl NonConstOp for RawPtrComparison {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
+        feature_err(
             &item.tcx.sess.parse_sess,
             sym::const_compare_raw_pointers,
             span,
-            GateIssue::Language,
             &format!("comparing raw pointers inside {}", item.const_kind()),
-        );
+        )
+        .emit();
     }
 }
 
@@ -258,14 +258,14 @@ impl NonConstOp for RawPtrDeref {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
-            &item.tcx.sess.parse_sess, sym::const_raw_ptr_deref,
-            span, GateIssue::Language,
+        feature_err(
+            &item.tcx.sess.parse_sess, sym::const_raw_ptr_deref, span,
             &format!(
                 "dereferencing raw pointers in {}s is unstable",
                 item.const_kind(),
             ),
-        );
+        )
+        .emit();
     }
 }
 
@@ -277,14 +277,14 @@ impl NonConstOp for RawPtrToIntCast {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
-            &item.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast,
-            span, GateIssue::Language,
+        feature_err(
+            &item.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast, span,
             &format!(
                 "casting pointers to integers in {}s is unstable",
                 item.const_kind(),
             ),
-        );
+        )
+        .emit();
     }
 }
 
@@ -334,11 +334,11 @@ impl NonConstOp for Transmute {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
-            &item.tcx.sess.parse_sess, sym::const_transmute,
-            span, GateIssue::Language,
-            &format!("The use of std::mem::transmute() \
-            is gated in {}s", item.const_kind()));
+        feature_err(
+            &item.tcx.sess.parse_sess, sym::const_transmute, span,
+            &format!("The use of std::mem::transmute() is gated in {}s", item.const_kind())
+        )
+        .emit();
     }
 }
 
@@ -355,10 +355,10 @@ impl NonConstOp for UnionAccess {
     }
 
     fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
-        emit_feature_err(
-            &item.tcx.sess.parse_sess, sym::const_fn_union,
-            span, GateIssue::Language,
+        feature_err(
+            &item.tcx.sess.parse_sess, sym::const_fn_union, span,
             "unions in const fn are unstable",
-        );
+        )
+        .emit();
     }
 }
diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs
index 9ed1ca740b8..2d5a0a2afcd 100644
--- a/src/librustc_mir/transform/check_consts/qualifs.rs
+++ b/src/librustc_mir/transform/check_consts/qualifs.rs
@@ -5,7 +5,7 @@ use rustc::ty::{self, Ty};
 use rustc::hir::def_id::DefId;
 use syntax_pos::DUMMY_SP;
 
-use super::{ConstKind, Item as ConstCx};
+use super::Item as ConstCx;
 
 pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs {
     ConstQualifs {
@@ -33,9 +33,10 @@ pub trait Qualif {
     /// of the type.
     fn in_any_value_of_ty(_cx: &ConstCx<'_, 'tcx>, _ty: Ty<'tcx>) -> bool;
 
-    fn in_static(_cx: &ConstCx<'_, 'tcx>, _def_id: DefId) -> bool {
-        // FIXME(eddyb) should we do anything here for value properties?
-        false
+    fn in_static(cx: &ConstCx<'_, 'tcx>, def_id: DefId) -> bool {
+        // `mir_const_qualif` does return the qualifs in the final value of a `static`, so we could
+        // use value-based qualification here, but we shouldn't do this without a good reason.
+        Self::in_any_value_of_ty(cx, cx.tcx.type_of(def_id))
     }
 
     fn in_projection_structurally(
@@ -217,34 +218,6 @@ impl Qualif for HasMutInterior {
         rvalue: &Rvalue<'tcx>,
     ) -> bool {
         match *rvalue {
-            // Returning `true` for `Rvalue::Ref` indicates the borrow isn't
-            // allowed in constants (and the `Checker` will error), and/or it
-            // won't be promoted, due to `&mut ...` or interior mutability.
-            Rvalue::Ref(_, kind, ref place) => {
-                let ty = place.ty(cx.body, cx.tcx).ty;
-
-                if let BorrowKind::Mut { .. } = kind {
-                    // In theory, any zero-sized value could be borrowed
-                    // mutably without consequences.
-                    match ty.kind {
-                        // Inside a `static mut`, &mut [...] is also allowed.
-                        | ty::Array(..)
-                        | ty::Slice(_)
-                        if cx.const_kind == Some(ConstKind::StaticMut)
-                        => {},
-
-                        // FIXME(eddyb): We only return false for `&mut []` outside a const
-                        // context which seems unnecessary given that this is merely a ZST.
-                        | ty::Array(_, len)
-                        if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
-                            && cx.const_kind == None
-                        => {},
-
-                        _ => return true,
-                    }
-                }
-            }
-
             Rvalue::Aggregate(ref kind, _) => {
                 if let AggregateKind::Adt(def, ..) = **kind {
                     if Some(def.did) == cx.tcx.lang_items().unsafe_cell_type() {
diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs
index bee37f69a5e..783c64ece73 100644
--- a/src/librustc_mir/transform/check_consts/validation.rs
+++ b/src/librustc_mir/transform/check_consts/validation.rs
@@ -23,13 +23,6 @@ use super::qualifs::{self, HasMutInterior, NeedsDrop};
 use super::resolver::FlowSensitiveAnalysis;
 use super::{ConstKind, Item, Qualif, is_lang_panic_fn};
 
-#[derive(Copy, Clone, Debug, PartialEq, Eq)]
-pub enum CheckOpResult {
-    Forbidden,
-    Unleashed,
-    Allowed,
-}
-
 pub type IndirectlyMutableResults<'mir, 'tcx> =
     old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
 
@@ -149,17 +142,6 @@ pub struct Validator<'a, 'mir, 'tcx> {
 
     /// The span of the current statement.
     span: Span,
-
-    /// True if the local was assigned the result of an illegal borrow (`ops::MutBorrow`).
-    ///
-    /// This is used to hide errors from {re,}borrowing the newly-assigned local, instead pointing
-    /// the user to the place where the illegal borrow occurred. This set is only populated once an
-    /// error has been emitted, so it will never cause an erroneous `mir::Body` to pass validation.
-    ///
-    /// FIXME(ecstaticmorse): assert at the end of checking that if `tcx.has_errors() == false`,
-    /// this set is empty. Note that if we start removing locals from
-    /// `derived_from_illegal_borrow`, just checking at the end won't be enough.
-    derived_from_illegal_borrow: BitSet<Local>,
 }
 
 impl Deref for Validator<'_, 'mir, 'tcx> {
@@ -213,7 +195,6 @@ impl Validator<'a, 'mir, 'tcx> {
             span: item.body.span,
             item,
             qualifs,
-            derived_from_illegal_borrow: BitSet::new_empty(item.body.local_decls.len()),
         }
     }
 
@@ -258,15 +239,15 @@ impl Validator<'a, 'mir, 'tcx> {
     }
 
     /// Emits an error at the given `span` if an expression cannot be evaluated in the current
-    /// context. Returns `Forbidden` if an error was emitted.
-    pub fn check_op_spanned<O>(&mut self, op: O, span: Span) -> CheckOpResult
+    /// context.
+    pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
     where
         O: NonConstOp
     {
         trace!("check_op: op={:?}", op);
 
         if op.is_allowed_in_item(self) {
-            return CheckOpResult::Allowed;
+            return;
         }
 
         // If an operation is supported in miri (and is not already controlled by a feature gate) it
@@ -276,20 +257,19 @@ impl Validator<'a, 'mir, 'tcx> {
 
         if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
             self.tcx.sess.span_warn(span, "skipping const checks");
-            return CheckOpResult::Unleashed;
+            return;
         }
 
         op.emit_error(self, span);
-        CheckOpResult::Forbidden
     }
 
     /// Emits an error if an expression cannot be evaluated in the current context.
-    pub fn check_op(&mut self, op: impl NonConstOp) -> CheckOpResult {
+    pub fn check_op(&mut self, op: impl NonConstOp) {
         let span = self.span;
         self.check_op_spanned(op, span)
     }
 
-    fn check_static(&mut self, def_id: DefId, span: Span) -> CheckOpResult {
+    fn check_static(&mut self, def_id: DefId, span: Span) {
         let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
         if is_thread_local {
             self.check_op_spanned(ops::ThreadLocalAccess, span)
@@ -322,20 +302,9 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
         trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
 
-        // Check nested operands and places.
+        // Special-case reborrows to be more like a copy of a reference.
         if let Rvalue::Ref(_, kind, ref place) = *rvalue {
-            // Special-case reborrows to be more like a copy of a reference.
-            let mut reborrow_place = None;
-            if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
-                if elem == ProjectionElem::Deref {
-                    let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
-                    if let ty::Ref(..) = base_ty.kind {
-                        reborrow_place = Some(proj_base);
-                    }
-                }
-            }
-
-            if let Some(proj) = reborrow_place {
+            if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
                 let ctx = match kind {
                     BorrowKind::Shared => PlaceContext::NonMutatingUse(
                         NonMutatingUseContext::SharedBorrow,
@@ -351,14 +320,13 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
                     ),
                 };
                 self.visit_place_base(&place.base, ctx, location);
-                self.visit_projection(&place.base, proj, ctx, location);
-            } else {
-                self.super_rvalue(rvalue, location);
+                self.visit_projection(&place.base, reborrowed_proj, ctx, location);
+                return;
             }
-        } else {
-            self.super_rvalue(rvalue, location);
         }
 
+        self.super_rvalue(rvalue, location);
+
         match *rvalue {
             Rvalue::Use(_) |
             Rvalue::Repeat(..) |
@@ -369,9 +337,58 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
             Rvalue::Cast(CastKind::Pointer(_), ..) |
             Rvalue::Discriminant(..) |
             Rvalue::Len(_) |
-            Rvalue::Ref(..) |
             Rvalue::Aggregate(..) => {}
 
+            | Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
+            | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place)
+            => {
+                let ty = place.ty(self.body, self.tcx).ty;
+                let is_allowed = match ty.kind {
+                    // Inside a `static mut`, `&mut [...]` is allowed.
+                    ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut
+                        => true,
+
+                    // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
+                    // that this is merely a ZST and it is already eligible for promotion.
+                    // This may require an RFC?
+                    /*
+                    ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
+                        => true,
+                    */
+
+                    _ => false,
+                };
+
+                if !is_allowed {
+                    self.check_op(ops::MutBorrow(kind));
+                }
+            }
+
+            // At the moment, `PlaceBase::Static` is only used for promoted MIR.
+            | Rvalue::Ref(_, BorrowKind::Shared, ref place)
+            | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
+            if matches!(place.base, PlaceBase::Static(_))
+            => bug!("Saw a promoted during const-checking, which must run before promotion"),
+
+            | Rvalue::Ref(_, kind @ BorrowKind::Shared, ref place)
+            | Rvalue::Ref(_, kind @ BorrowKind::Shallow, ref place)
+            => {
+                // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
+                // seek the cursors beforehand.
+                self.qualifs.has_mut_interior.cursor.seek_before(location);
+                self.qualifs.indirectly_mutable.seek(location);
+
+                let borrowed_place_has_mut_interior = HasMutInterior::in_place(
+                    &self.item,
+                    &|local| self.qualifs.has_mut_interior_eager_seek(local),
+                    place.as_ref(),
+                );
+
+                if borrowed_place_has_mut_interior {
+                    self.check_op(ops::MutBorrow(kind));
+                }
+            }
+
             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
                 let operand_ty = operand.ty(self.body, self.tcx);
                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
@@ -436,58 +453,6 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
         }
     }
 
-    fn visit_assign(&mut self, dest: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
-        trace!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
-
-        // Error on mutable borrows or shared borrows of values with interior mutability.
-        //
-        // This replicates the logic at the start of `assign` in the old const checker.  Note that
-        // it depends on `HasMutInterior` being set for mutable borrows as well as values with
-        // interior mutability.
-        if let Rvalue::Ref(_, kind, ref borrowed_place) = *rvalue {
-            // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually seek
-            // the cursors beforehand.
-            self.qualifs.has_mut_interior.cursor.seek_before(location);
-            self.qualifs.indirectly_mutable.seek(location);
-
-            let rvalue_has_mut_interior = HasMutInterior::in_rvalue(
-                &self.item,
-                &|local| self.qualifs.has_mut_interior_eager_seek(local),
-                rvalue,
-            );
-
-            if rvalue_has_mut_interior {
-                let is_derived_from_illegal_borrow = match borrowed_place.as_local() {
-                    // If an unprojected local was borrowed and its value was the result of an
-                    // illegal borrow, suppress this error and mark the result of this borrow as
-                    // illegal as well.
-                    Some(borrowed_local)
-                        if self.derived_from_illegal_borrow.contains(borrowed_local) =>
-                    {
-                        true
-                    }
-
-                    // Otherwise proceed normally: check the legality of a mutable borrow in this
-                    // context.
-                    _ => self.check_op(ops::MutBorrow(kind)) == CheckOpResult::Forbidden,
-                };
-
-                // When the target of the assignment is a local with no projections, mark it as
-                // derived from an illegal borrow if necessary.
-                //
-                // FIXME: should we also clear `derived_from_illegal_borrow` when a local is
-                // assigned a new value?
-                if is_derived_from_illegal_borrow {
-                    if let Some(dest) = dest.as_local() {
-                        self.derived_from_illegal_borrow.insert(dest);
-                    }
-                }
-            }
-        }
-
-        self.super_assign(dest, rvalue, location);
-    }
-
     fn visit_projection_elem(
         &mut self,
         place_base: &PlaceBase<'tcx>,
@@ -560,7 +525,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
         trace!("visit_statement: statement={:?} location={:?}", statement, location);
 
         match statement.kind {
-            StatementKind::Assign(..) => {
+            StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
                 self.super_statement(statement, location);
             }
             StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
@@ -568,7 +533,6 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
             }
             // FIXME(eddyb) should these really do nothing?
             StatementKind::FakeRead(..) |
-            StatementKind::SetDiscriminant { .. } |
             StatementKind::StorageLive(_) |
             StatementKind::StorageDead(_) |
             StatementKind::InlineAsm {..} |
@@ -725,3 +689,36 @@ fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId)
         }
     });
 }
+
+fn place_as_reborrow(
+    tcx: TyCtxt<'tcx>,
+    body: &Body<'tcx>,
+    place: &'a Place<'tcx>,
+) -> Option<&'a [PlaceElem<'tcx>]> {
+    place
+        .projection
+        .split_last()
+        .and_then(|(outermost, inner)| {
+            if outermost != &ProjectionElem::Deref {
+                return None;
+            }
+
+            // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
+            // that points to the allocation for the static. Don't treat these as reborrows.
+            if let PlaceBase::Local(local) = place.base {
+                if body.local_decls[local].is_ref_to_static() {
+                    return None;
+                }
+            }
+
+            // Ensure the type being derefed is a reference and not a raw pointer.
+            //
+            // This is sufficient to prevent an access to a `static mut` from being marked as a
+            // reborrow, even if the check above were to disappear.
+            let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
+            match inner_ty.kind {
+                ty::Ref(..) => Some(inner),
+                _ => None,
+            }
+        })
+}
diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs
index b7cc4e9fcf6..d12d21aee6a 100644
--- a/src/librustc_mir/transform/check_unsafety.rs
+++ b/src/librustc_mir/transform/check_unsafety.rs
@@ -1,6 +1,4 @@
 use rustc_data_structures::fx::FxHashSet;
-use rustc_index::vec::IndexVec;
-use rustc_data_structures::sync::Lrc;
 
 use rustc::ty::query::Providers;
 use rustc::ty::{self, TyCtxt};
@@ -24,7 +22,6 @@ pub struct UnsafetyChecker<'a, 'tcx> {
     body: &'a Body<'tcx>,
     const_context: bool,
     min_const_fn: bool,
-    source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
     violations: Vec<UnsafetyViolation>,
     source_info: SourceInfo,
     tcx: TyCtxt<'tcx>,
@@ -39,7 +36,6 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
         const_context: bool,
         min_const_fn: bool,
         body: &'a Body<'tcx>,
-        source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
         tcx: TyCtxt<'tcx>,
         param_env: ty::ParamEnv<'tcx>,
     ) -> Self {
@@ -51,7 +47,6 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
             body,
             const_context,
             min_const_fn,
-            source_scope_local_data,
             violations: vec![],
             source_info: SourceInfo {
                 span: body.span,
@@ -219,8 +214,11 @@ impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
             if context.is_borrow() {
                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
                     let source_info = self.source_info;
-                    let lint_root =
-                        self.source_scope_local_data[source_info.scope].lint_root;
+                    let lint_root = self.body.source_scopes[source_info.scope]
+                        .local_data
+                        .as_ref()
+                        .assert_crate_local()
+                        .lint_root;
                     self.register_violations(&[UnsafetyViolation {
                         source_info,
                         description: Symbol::intern("borrow of packed field"),
@@ -346,7 +344,11 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
     fn register_violations(&mut self,
                            violations: &[UnsafetyViolation],
                            unsafe_blocks: &[(hir::HirId, bool)]) {
-        let safety = self.source_scope_local_data[self.source_info.scope].safety;
+        let safety = self.body.source_scopes[self.source_info.scope]
+            .local_data
+            .as_ref()
+            .assert_crate_local()
+            .safety;
         let within_unsafe = match safety {
             // `unsafe` blocks are required in safe code
             Safety::Safe => {
@@ -516,17 +518,6 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult
     // `mir_built` force this.
     let body = &tcx.mir_built(def_id).borrow();
 
-    let source_scope_local_data = match body.source_scope_local_data {
-        ClearCrossCrate::Set(ref data) => data,
-        ClearCrossCrate::Clear => {
-            debug!("unsafety_violations: {:?} - remote, skipping", def_id);
-            return UnsafetyCheckResult {
-                violations: Lrc::new([]),
-                unsafe_blocks: Lrc::new([])
-            }
-        }
-    };
-
     let param_env = tcx.param_env(def_id);
 
     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
@@ -536,9 +527,7 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult
         hir::BodyOwnerKind::Const |
         hir::BodyOwnerKind::Static(_) => (true, false),
     };
-    let mut checker = UnsafetyChecker::new(
-        const_context, min_const_fn,
-        body, source_scope_local_data, tcx, param_env);
+    let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
     checker.visit_body(body);
 
     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs
index 8de16308e83..67958af3460 100644
--- a/src/librustc_mir/transform/const_prop.rs
+++ b/src/librustc_mir/transform/const_prop.rs
@@ -9,7 +9,7 @@ use rustc::hir::def_id::DefId;
 use rustc::mir::{
     AggregateKind, Constant, Location, Place, PlaceBase, Body, Operand, Rvalue, Local, UnOp,
     StatementKind, Statement, LocalKind, TerminatorKind, Terminator,  ClearCrossCrate, SourceInfo,
-    BinOp, SourceScope, SourceScopeLocalData, LocalDecl, BasicBlock, RETURN_PLACE,
+    BinOp, SourceScope, SourceScopeData, LocalDecl, BasicBlock, RETURN_PLACE,
 };
 use rustc::mir::visit::{
     Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
@@ -74,23 +74,17 @@ impl<'tcx> MirPass<'tcx> for ConstProp {
 
         trace!("ConstProp starting for {:?}", source.def_id());
 
-        // Steal some data we need from `body`.
-        let source_scope_local_data = std::mem::replace(
-            &mut body.source_scope_local_data,
-            ClearCrossCrate::Clear
-        );
-
         let dummy_body =
             &Body::new(
                 body.basic_blocks().clone(),
-                Default::default(),
-                ClearCrossCrate::Clear,
+                body.source_scopes.clone(),
                 body.local_decls.clone(),
                 Default::default(),
                 body.arg_count,
                 Default::default(),
                 tcx.def_span(source.def_id()),
                 Default::default(),
+                body.generator_kind,
             );
 
         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
@@ -100,19 +94,11 @@ impl<'tcx> MirPass<'tcx> for ConstProp {
         let mut optimization_finder = ConstPropagator::new(
             body,
             dummy_body,
-            source_scope_local_data,
             tcx,
             source
         );
         optimization_finder.visit_body(body);
 
-        // put back the data we stole from `mir`
-        let source_scope_local_data = optimization_finder.release_stolen_data();
-        std::mem::replace(
-            &mut body.source_scope_local_data,
-            source_scope_local_data
-        );
-
         trace!("ConstProp done for {:?}", source.def_id());
     }
 }
@@ -167,14 +153,14 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
         _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
         _unwind: Option<BasicBlock>
     ) -> InterpResult<'tcx> {
-        throw_unsup_format!("calling intrinsics isn't supported in ConstProp");
+        throw_unsup!(ConstPropUnsupported("calling intrinsics isn't supported in ConstProp"));
     }
 
     fn ptr_to_int(
         _mem: &Memory<'mir, 'tcx, Self>,
         _ptr: Pointer,
     ) -> InterpResult<'tcx, u64> {
-        throw_unsup_format!("ptr-to-int casts aren't supported in ConstProp");
+        throw_unsup!(ConstPropUnsupported("ptr-to-int casts aren't supported in ConstProp"));
     }
 
     fn binary_ptr_op(
@@ -184,7 +170,8 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
         _right: ImmTy<'tcx>,
     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
         // We can't do this because aliasing of memory can differ between const eval and llvm
-        throw_unsup_format!("pointer arithmetic or comparisons aren't supported in ConstProp");
+        throw_unsup!(ConstPropUnsupported("pointer arithmetic or comparisons aren't supported \
+            in ConstProp"));
     }
 
     fn find_foreign_static(
@@ -217,7 +204,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
         _dest: PlaceTy<'tcx>,
     ) -> InterpResult<'tcx> {
-        throw_unsup_format!("can't const prop `box` keyword");
+        throw_unsup!(ConstPropUnsupported("can't const prop `box` keyword"));
     }
 
     fn access_local(
@@ -228,7 +215,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
         let l = &frame.locals[local];
 
         if l.value == LocalValue::Uninitialized {
-            throw_unsup_format!("tried to access an uninitialized local");
+            throw_unsup!(ConstPropUnsupported("tried to access an uninitialized local"));
         }
 
         l.access()
@@ -240,7 +227,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
         // if the static allocation is mutable or if it has relocations (it may be legal to mutate
         // the memory behind that in the future), then we can't const prop it
         if allocation.mutability == Mutability::Mutable || allocation.relocations().len() > 0 {
-            throw_unsup_format!("can't eval mutable statics in ConstProp");
+            throw_unsup!(ConstPropUnsupported("can't eval mutable statics in ConstProp"));
         }
 
         Ok(())
@@ -265,7 +252,9 @@ struct ConstPropagator<'mir, 'tcx> {
     source: MirSource<'tcx>,
     can_const_prop: IndexVec<Local, bool>,
     param_env: ParamEnv<'tcx>,
-    source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
+    // FIXME(eddyb) avoid cloning these two fields more than once,
+    // by accessing them through `ecx` instead.
+    source_scopes: IndexVec<SourceScope, SourceScopeData>,
     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
     ret: Option<OpTy<'tcx, ()>>,
 }
@@ -297,7 +286,6 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
     fn new(
         body: &Body<'tcx>,
         dummy_body: &'mir Body<'tcx>,
-        source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
         tcx: TyCtxt<'tcx>,
         source: MirSource<'tcx>,
     ) -> ConstPropagator<'mir, 'tcx> {
@@ -335,17 +323,15 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
             source,
             param_env,
             can_const_prop,
-            source_scope_local_data,
+            // FIXME(eddyb) avoid cloning these two fields more than once,
+            // by accessing them through `ecx` instead.
+            source_scopes: body.source_scopes.clone(),
             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
             local_decls: body.local_decls.clone(),
             ret: ret.map(Into::into),
         }
     }
 
-    fn release_stolen_data(self) -> ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>> {
-        self.source_scope_local_data
-    }
-
     fn get_const(&self, local: Local) -> Option<Const<'tcx>> {
         if local == RETURN_PLACE {
             // Try to read the return place as an immediate so that if it is representable as a
@@ -375,22 +361,36 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
     {
         self.ecx.tcx.span = source_info.span;
-        let lint_root = match self.source_scope_local_data {
-            ClearCrossCrate::Set(ref ivs) => {
-                //FIXME(#51314): remove this check
-                if source_info.scope.index() >= ivs.len() {
-                    return None;
-                }
-                ivs[source_info.scope].lint_root
-            },
+        // FIXME(eddyb) move this to the `Panic(_)` error case, so that
+        // `f(self)` is always called, and that the only difference when the
+        // scope's `local_data` is missing, is that the lint isn't emitted.
+        let lint_root = match &self.source_scopes[source_info.scope].local_data {
+            ClearCrossCrate::Set(data) => data.lint_root,
             ClearCrossCrate::Clear => return None,
         };
         let r = match f(self) {
             Ok(val) => Some(val),
             Err(error) => {
-                use rustc::mir::interpret::InterpError::*;
+                use rustc::mir::interpret::{
+                    UnsupportedOpInfo,
+                    UndefinedBehaviorInfo,
+                    InterpError::*
+                };
                 match error.kind {
-                    Exit(_) => bug!("the CTFE program cannot exit"),
+                    MachineStop(_) => bug!("ConstProp does not stop"),
+
+                    // Some error shouldn't come up because creating them causes
+                    // an allocation, which we should avoid. When that happens,
+                    // dedicated error variants should be introduced instead.
+                    // Only test this in debug builds though to avoid disruptions.
+                    Unsupported(UnsupportedOpInfo::Unsupported(_))
+                    | Unsupported(UnsupportedOpInfo::ValidationFailure(_))
+                    | UndefinedBehavior(UndefinedBehaviorInfo::Ub(_))
+                    | UndefinedBehavior(UndefinedBehaviorInfo::UbExperimental(_))
+                      if cfg!(debug_assertions) => {
+                        bug!("const-prop encountered allocating error: {:?}", error.kind);
+                    }
+
                     Unsupported(_)
                     | UndefinedBehavior(_)
                     | InvalidProgram(_)
@@ -506,8 +506,8 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
                     let right_size = r.layout.size;
                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
-                        let source_scope_local_data = match self.source_scope_local_data {
-                            ClearCrossCrate::Set(ref data) => data,
+                        let lint_root = match &self.source_scopes[source_info.scope].local_data {
+                            ClearCrossCrate::Set(data) => data.lint_root,
                             ClearCrossCrate::Clear => return None,
                         };
                         let dir = if *op == BinOp::Shr {
@@ -515,10 +515,9 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
                         } else {
                             "left"
                         };
-                        let hir_id = source_scope_local_data[source_info.scope].lint_root;
                         self.tcx.lint_hir(
                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
-                            hir_id,
+                            lint_root,
                             span,
                             &format!("attempt to shift {} with overflow", dir));
                         return None;
diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs
index a904c6a3ada..5d88629435b 100644
--- a/src/librustc_mir/transform/generator.rs
+++ b/src/librustc_mir/transform/generator.rs
@@ -1056,16 +1056,23 @@ fn create_generator_resume_function<'tcx>(
     let mut cases = create_cases(body, &transform, |point| Some(point.resume));
 
     use rustc::mir::interpret::PanicInfo::{
-        GeneratorResumedAfterPanic,
-        GeneratorResumedAfterReturn,
+        ResumedAfterPanic,
+        ResumedAfterReturn,
     };
 
     // Jump to the entry point on the unresumed
     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
-    // Panic when resumed on the returned state
-    cases.insert(1, (RETURNED, insert_panic_block(tcx, body, GeneratorResumedAfterReturn)));
-    // Panic when resumed on the poisoned state
-    cases.insert(2, (POISONED, insert_panic_block(tcx, body, GeneratorResumedAfterPanic)));
+
+    // Panic when resumed on the returned or poisoned state
+    let generator_kind = body.generator_kind.unwrap();
+    cases.insert(1, (RETURNED, insert_panic_block(
+        tcx,
+        body,
+        ResumedAfterReturn(generator_kind))));
+    cases.insert(2, (POISONED, insert_panic_block(
+        tcx,
+        body,
+        ResumedAfterPanic(generator_kind))));
 
     insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
 
diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs
index 867673beb35..ebfadd0cfd3 100644
--- a/src/librustc_mir/transform/inline.rs
+++ b/src/librustc_mir/transform/inline.rs
@@ -391,9 +391,14 @@ impl Inliner<'tcx> {
                 for mut scope in callee_body.source_scopes.iter().cloned() {
                     if scope.parent_scope.is_none() {
                         scope.parent_scope = Some(callsite.location.scope);
+                        // FIXME(eddyb) is this really needed?
+                        // (also note that it's always overwritten below)
                         scope.span = callee_body.span;
                     }
 
+                    // FIXME(eddyb) this doesn't seem right at all.
+                    // The inlined source scopes should probably be annotated as
+                    // such, but also contain all of the original information.
                     scope.span = callsite.location.span;
 
                     let idx = caller_body.source_scopes.push(scope);
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 2c3aec103a5..591f3ca4400 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -24,7 +24,6 @@ use syntax::symbol::sym;
 use syntax_pos::{Span, DUMMY_SP};
 
 use rustc_index::vec::{IndexVec, Idx};
-use rustc_index::bit_set::HybridBitSet;
 use rustc_target::spec::abi::Abi;
 
 use std::cell::Cell;
@@ -35,10 +34,8 @@ use crate::transform::check_consts::{qualifs, Item, ConstKind, is_lang_panic_fn}
 
 /// A `MirPass` for promotion.
 ///
-/// In this case, "promotion" entails the following:
-/// - Extract promotable temps in `fn` and `const fn` into their own MIR bodies.
-/// - Extend lifetimes in `const` and `static` by removing `Drop` and `StorageDead`.
-/// - Emit errors if the requirements of `#[rustc_args_required_const]` are not met.
+/// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
+/// errors when promotion of `#[rustc_args_required_const]` arguments fails.
 ///
 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
 /// newly created `StaticKind::Promoted`.
@@ -63,26 +60,13 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
 
         let def_id = src.def_id();
 
-        let item = Item::new(tcx, def_id, body);
         let mut rpo = traversal::reverse_postorder(body);
         let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
 
         let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates);
 
-        // For now, lifetime extension is done in `const` and `static`s without creating promoted
-        // MIR fragments by removing `Drop` and `StorageDead` for each referent. However, this will
-        // not work inside loops when they are allowed in `const`s.
-        //
-        // FIXME: use promoted MIR fragments everywhere?
-        let promoted_fragments = if should_create_promoted_mir_fragments(item.const_kind) {
-            promote_candidates(def_id, body, tcx, temps, promotable_candidates)
-        } else {
-            // FIXME: promote const array initializers in consts.
-            remove_drop_and_storage_dead_on_promoted_locals(tcx, body, &promotable_candidates);
-            IndexVec::new()
-        };
-
-        self.promoted_fragments.set(promoted_fragments);
+        let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
+        self.promoted_fragments.set(promoted);
     }
 }
 
@@ -1097,13 +1081,13 @@ pub fn promote_candidates<'tcx>(
                 // FIXME: maybe try to filter this to avoid blowing up
                 // memory usage?
                 body.source_scopes.clone(),
-                body.source_scope_local_data.clone(),
                 initial_locals,
                 IndexVec::new(),
                 0,
                 vec![],
                 body.span,
                 vec![],
+                body.generator_kind,
             ),
             tcx,
             source: body,
@@ -1178,83 +1162,3 @@ crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
             should_promote={:?} feature_flag={:?}", mir_def_id, should_promote, feature_flag);
     should_promote && !feature_flag
 }
-
-fn should_create_promoted_mir_fragments(const_kind: Option<ConstKind>) -> bool {
-    match const_kind {
-        Some(ConstKind::ConstFn) | None => true,
-        Some(ConstKind::Const) | Some(ConstKind::Static) | Some(ConstKind::StaticMut) => false,
-    }
-}
-
-/// In `const` and `static` everything without `StorageDead`
-/// is `'static`, we don't have to create promoted MIR fragments,
-/// just remove `Drop` and `StorageDead` on "promoted" locals.
-fn remove_drop_and_storage_dead_on_promoted_locals(
-    tcx: TyCtxt<'tcx>,
-    body: &mut Body<'tcx>,
-    promotable_candidates: &[Candidate],
-) {
-    debug!("run_pass: promotable_candidates={:?}", promotable_candidates);
-
-    // Removing `StorageDead` will cause errors for temps declared inside a loop body. For now we
-    // simply skip promotion if a loop exists, since loops are not yet allowed in a `const`.
-    //
-    // FIXME: Just create MIR fragments for `const`s instead of using this hackish approach?
-    if body.is_cfg_cyclic() {
-        tcx.sess.delay_span_bug(body.span, "Control-flow cycle detected in `const`");
-        return;
-    }
-
-    // The underlying local for promotion contexts like `&temp` and `&(temp.proj)`.
-    let mut requires_lifetime_extension = HybridBitSet::new_empty(body.local_decls.len());
-
-    promotable_candidates
-        .iter()
-        .filter_map(|c| {
-            match c {
-                Candidate::Ref(loc) => Some(loc),
-                Candidate::Repeat(_) | Candidate::Argument { .. } => None,
-            }
-        })
-        .map(|&Location { block, statement_index }| {
-            // FIXME: store the `Local` for each `Candidate` when it is created.
-            let place = match &body[block].statements[statement_index].kind {
-                StatementKind::Assign(box ( _, Rvalue::Ref(_, _, place))) => place,
-                _ => bug!("`Candidate::Ref` without corresponding assignment"),
-            };
-
-            match place.base {
-                PlaceBase::Local(local) => local,
-                PlaceBase::Static(_) => bug!("`Candidate::Ref` for a non-local"),
-            }
-        })
-        .for_each(|local| {
-            requires_lifetime_extension.insert(local);
-        });
-
-    // Remove `Drop` terminators and `StorageDead` statements for all promotable temps that require
-    // lifetime extension.
-    for block in body.basic_blocks_mut() {
-        block.statements.retain(|statement| {
-            match statement.kind {
-                StatementKind::StorageDead(index) => !requires_lifetime_extension.contains(index),
-                _ => true
-            }
-        });
-        let terminator = block.terminator_mut();
-        match &terminator.kind {
-            TerminatorKind::Drop {
-                location,
-                target,
-                ..
-            } => {
-                if let Some(index) = location.as_local() {
-                    if requires_lifetime_extension.contains(index) {
-                        terminator.kind = TerminatorKind::Goto { target: *target };
-                    }
-                }
-            }
-            _ => {}
-        }
-    }
-}
diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs
index 81f4c277f4d..e40d6a5952e 100644
--- a/src/librustc_mir/transform/qualify_min_const_fn.rs
+++ b/src/librustc_mir/transform/qualify_min_const_fn.rs
@@ -225,7 +225,7 @@ fn check_statement(
         StatementKind::FakeRead(_, place) => check_place(tcx, place, span, def_id, body),
 
         // just an assignment
-        StatementKind::SetDiscriminant { .. } => Ok(()),
+        StatementKind::SetDiscriminant { place, .. } => check_place(tcx, place, span, def_id, body),
 
         | StatementKind::InlineAsm { .. } => {
             Err((span, "cannot use inline assembly in const fn".into()))
diff --git a/src/librustc_mir/transform/simplify_try.rs b/src/librustc_mir/transform/simplify_try.rs
index de5c2ebb571..9dc5daa9b07 100644
--- a/src/librustc_mir/transform/simplify_try.rs
+++ b/src/librustc_mir/transform/simplify_try.rs
@@ -34,7 +34,8 @@ pub struct SimplifyArmIdentity;
 
 impl<'tcx> MirPass<'tcx> for SimplifyArmIdentity {
     fn run_pass(&self, _: TyCtxt<'tcx>, _: MirSource<'tcx>, body: &mut Body<'tcx>) {
-        for bb in body.basic_blocks_mut() {
+        let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
+        for bb in basic_blocks {
             // Need 3 statements:
             let (s0, s1, s2) = match &mut *bb.statements {
                 [s0, s1, s2] => (s0, s1, s2),
@@ -51,7 +52,12 @@ impl<'tcx> MirPass<'tcx> for SimplifyArmIdentity {
                 Some(x) => x,
             };
             if local_tmp_s0 != local_tmp_s1
+                // The field-and-variant information match up.
                 || vf_s0 != vf_s1
+                // Source and target locals have the same type.
+                // FIXME(Centril | oli-obk): possibly relax to same layout?
+                || local_decls[local_0].ty != local_decls[local_1].ty
+                // We're setting the discriminant of `local_0` to this variant.
                 || Some((local_0, vf_s0.var_idx)) != match_set_discr(s2)
             {
                 continue;
diff --git a/src/librustc_parse/Cargo.toml b/src/librustc_parse/Cargo.toml
index a9175487a75..95b3256f53a 100644
--- a/src/librustc_parse/Cargo.toml
+++ b/src/librustc_parse/Cargo.toml
@@ -16,6 +16,7 @@ syntax_pos = { path = "../libsyntax_pos" }
 syntax = { path = "../libsyntax" }
 errors = { path = "../librustc_errors", package = "rustc_errors" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_lexer = { path = "../librustc_lexer" }
 rustc_target = { path = "../librustc_target" }
 smallvec = { version = "1.0", features = ["union", "may_dangle"] }
diff --git a/src/librustc_parse/config.rs b/src/librustc_parse/config.rs
index 7ce555ed57a..26e51e83d62 100644
--- a/src/librustc_parse/config.rs
+++ b/src/librustc_parse/config.rs
@@ -9,14 +9,9 @@
 //! [#64197]: https://github.com/rust-lang/rust/issues/64197
 
 use crate::validate_attr;
+use rustc_feature::Features;
 use syntax::attr::HasAttrs;
-use syntax::feature_gate::{
-    feature_err,
-    EXPLAIN_STMT_ATTR_SYNTAX,
-    Features,
-    get_features,
-    GateIssue,
-};
+use syntax::feature_gate::{feature_err, get_features};
 use syntax::attr;
 use syntax::ast;
 use syntax::edition::Edition;
@@ -52,7 +47,7 @@ pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition,
         } else { // the entire crate is unconfigured
             krate.attrs = Vec::new();
             krate.module.items = Vec::new();
-            return (krate, Features::new());
+            return (krate, Features::default());
         }
 
         features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
@@ -217,8 +212,7 @@ impl<'a> StripUnconfigured<'a> {
             let mut err = feature_err(self.sess,
                                       sym::stmt_expr_attributes,
                                       attr.span,
-                                      GateIssue::Language,
-                                      EXPLAIN_STMT_ATTR_SYNTAX);
+                                      "attributes on expressions are experimental");
 
             if attr.is_doc_comment() {
                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
diff --git a/src/librustc_parse/validate_attr.rs b/src/librustc_parse/validate_attr.rs
index bbe0dc1c35f..a3c9e266593 100644
--- a/src/librustc_parse/validate_attr.rs
+++ b/src/librustc_parse/validate_attr.rs
@@ -1,10 +1,10 @@
 //! Meta-syntax validation logic of attributes for post-expansion.
 
 use errors::{PResult, Applicability};
-use syntax::ast::{self, Attribute, AttrKind, Ident, MetaItem};
-use syntax::attr::{AttributeTemplate, mk_name_value_item_str};
+use rustc_feature::{AttributeTemplate, BUILTIN_ATTRIBUTE_MAP};
+use syntax::ast::{self, Attribute, AttrKind, Ident, MetaItem, MetaItemKind};
+use syntax::attr::mk_name_value_item_str;
 use syntax::early_buffered_lints::BufferedEarlyLintId;
-use syntax::feature_gate::BUILTIN_ATTRIBUTE_MAP;
 use syntax::token;
 use syntax::tokenstream::TokenTree;
 use syntax::sess::ParseSess;
@@ -41,6 +41,16 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta
     })
 }
 
+/// Checks that the given meta-item is compatible with this `AttributeTemplate`.
+fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool {
+    match meta {
+        MetaItemKind::Word => template.word,
+        MetaItemKind::List(..) => template.list.is_some(),
+        MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(),
+        MetaItemKind::NameValue(..) => false,
+    }
+}
+
 pub fn check_builtin_attribute(
     sess: &ParseSess,
     attr: &Attribute,
@@ -57,7 +67,7 @@ pub fn check_builtin_attribute(
                              name == sym::test || name == sym::bench;
 
     match parse_meta(sess, attr) {
-        Ok(meta) => if !should_skip(name) && !template.compatible(&meta.kind) {
+        Ok(meta) => if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) {
             let error_msg = format!("malformed `{}` attribute input", name);
             let mut msg = "attribute must be of the form ".to_owned();
             let mut suggestions = vec![];
diff --git a/src/librustc_passes/Cargo.toml b/src/librustc_passes/Cargo.toml
index 7a98734bdbe..bb2f7c67418 100644
--- a/src/librustc_passes/Cargo.toml
+++ b/src/librustc_passes/Cargo.toml
@@ -12,6 +12,7 @@ path = "lib.rs"
 log = "0.4"
 rustc = { path = "../librustc" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_index = { path = "../librustc_index" }
 rustc_parse = { path = "../librustc_parse" }
 rustc_target = { path = "../librustc_target" }
diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs
index e189b7175f9..5a29a56ad54 100644
--- a/src/librustc_passes/ast_validation.rs
+++ b/src/librustc_passes/ast_validation.rs
@@ -14,7 +14,6 @@ use rustc_parse::validate_attr;
 use syntax::ast::*;
 use syntax::attr;
 use syntax::expand::is_proc_macro_attr;
-use syntax::feature_gate::is_builtin_attr;
 use syntax::print::pprust;
 use syntax::source_map::Spanned;
 use syntax::symbol::{kw, sym};
@@ -257,7 +256,7 @@ impl<'a> AstValidator<'a> {
             .flat_map(|i| i.attrs.as_ref())
             .filter(|attr| {
                 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
-                !arr.contains(&attr.name_or_empty()) && is_builtin_attr(attr)
+                !arr.contains(&attr.name_or_empty()) && attr::is_builtin_attr(attr)
             })
             .for_each(|attr| if attr.is_doc_comment() {
                 let mut err = self.err_handler().struct_span_err(
diff --git a/src/librustc_passes/check_const.rs b/src/librustc_passes/check_const.rs
index 24bc088e24a..63c6e60de79 100644
--- a/src/librustc_passes/check_const.rs
+++ b/src/librustc_passes/check_const.rs
@@ -13,8 +13,9 @@ use rustc::hir::map::Map;
 use rustc::hir;
 use rustc::ty::TyCtxt;
 use rustc::ty::query::Providers;
+use rustc_feature::Features;
 use syntax::ast::Mutability;
-use syntax::feature_gate::{emit_feature_err, Features, GateIssue};
+use syntax::feature_gate::feature_err;
 use syntax::span_err;
 use syntax_pos::{sym, Span};
 use rustc_error_codes::*;
@@ -140,13 +141,7 @@ impl<'tcx> CheckConstVisitor<'tcx> {
             | NonConstExpr::Match(hir::MatchSource::Normal)
             | NonConstExpr::Match(hir::MatchSource::IfDesugar { .. })
             | NonConstExpr::Match(hir::MatchSource::IfLetDesugar { .. })
-            => emit_feature_err(
-                &self.tcx.sess.parse_sess,
-                sym::const_if_match,
-                span,
-                GateIssue::Language,
-                &msg
-            ),
+            => feature_err(&self.tcx.sess.parse_sess, sym::const_if_match, span, &msg).emit(),
 
             _ => span_err!(self.tcx.sess, span, E0744, "{}", msg),
         }
diff --git a/src/librustc_plugin_impl/lib.rs b/src/librustc_plugin_impl/lib.rs
index f4e90b7b7da..5c4ea39aecc 100644
--- a/src/librustc_plugin_impl/lib.rs
+++ b/src/librustc_plugin_impl/lib.rs
@@ -10,10 +10,16 @@
 
 #![feature(nll)]
 
-#![recursion_limit="256"]
+use rustc::lint::LintStore;
 
-pub use registry::Registry;
-
-pub mod registry;
-pub mod load;
 pub mod build;
+pub mod load;
+
+/// Structure used to register plugins.
+///
+/// A plugin registrar function takes an `&mut Registry` and should call
+/// methods to register its plugins.
+pub struct Registry<'a> {
+    /// The `LintStore` allows plugins to register new lints.
+    pub lint_store: &'a mut LintStore,
+}
diff --git a/src/librustc_plugin_impl/load.rs b/src/librustc_plugin_impl/load.rs
index 31b3b07c3e1..0bd91076592 100644
--- a/src/librustc_plugin_impl/load.rs
+++ b/src/librustc_plugin_impl/load.rs
@@ -3,33 +3,21 @@
 use rustc::middle::cstore::MetadataLoader;
 use rustc::session::Session;
 use rustc_metadata::locator;
-use crate::registry::Registry;
+use crate::Registry;
 
 use std::borrow::ToOwned;
 use std::env;
 use std::mem;
 use std::path::PathBuf;
-use syntax::ast;
+use syntax::ast::{Crate, Ident};
 use syntax::struct_span_err;
-use syntax::symbol::{Symbol, kw, sym};
-use syntax_pos::{Span, DUMMY_SP};
+use syntax::symbol::sym;
+use syntax_pos::Span;
 
 use rustc_error_codes::*;
 
 /// Pointer to a registrar function.
-pub type PluginRegistrarFun =
-    fn(&mut Registry<'_>);
-
-pub struct PluginRegistrar {
-    pub fun: PluginRegistrarFun,
-    pub args: Vec<ast::NestedMetaItem>,
-}
-
-struct PluginLoader<'a> {
-    sess: &'a Session,
-    metadata_loader: &'a dyn MetadataLoader,
-    plugins: Vec<PluginRegistrar>,
-}
+type PluginRegistrarFn = fn(&mut Registry<'_>);
 
 fn call_malformed_plugin_attribute(sess: &Session, span: Span) {
     struct_span_err!(sess, span, E0498, "malformed `plugin` attribute")
@@ -40,98 +28,76 @@ fn call_malformed_plugin_attribute(sess: &Session, span: Span) {
 /// Read plugin metadata and dynamically load registrar functions.
 pub fn load_plugins(sess: &Session,
                     metadata_loader: &dyn MetadataLoader,
-                    krate: &ast::Crate,
-                    addl_plugins: Option<Vec<String>>) -> Vec<PluginRegistrar> {
-    let mut loader = PluginLoader { sess, metadata_loader, plugins: Vec::new() };
-
-    // do not report any error now. since crate attributes are
-    // not touched by expansion, every use of plugin without
-    // the feature enabled will result in an error later...
-    if sess.features_untracked().plugin {
-        for attr in &krate.attrs {
-            if !attr.check_name(sym::plugin) {
-                continue;
-            }
+                    krate: &Crate) -> Vec<PluginRegistrarFn> {
+    let mut plugins = Vec::new();
 
-            let plugins = match attr.meta_item_list() {
-                Some(xs) => xs,
-                None => continue,
-            };
-
-            for plugin in plugins {
-                // plugins must have a name and can't be key = value
-                let name = plugin.name_or_empty();
-                if name != kw::Invalid && !plugin.is_value_str() {
-                    let args = plugin.meta_item_list().map(ToOwned::to_owned);
-                    loader.load_plugin(plugin.span(), name, args.unwrap_or_default());
-                } else {
-                    call_malformed_plugin_attribute(sess, attr.span);
-                }
-            }
+    for attr in &krate.attrs {
+        if !attr.check_name(sym::plugin) {
+            continue;
         }
-    }
 
-    if let Some(plugins) = addl_plugins {
-        for plugin in plugins {
-            loader.load_plugin(DUMMY_SP, Symbol::intern(&plugin), vec![]);
+        for plugin in attr.meta_item_list().unwrap_or_default() {
+            match plugin.ident() {
+                Some(ident) if plugin.is_word() =>
+                    load_plugin(&mut plugins, sess, metadata_loader, ident),
+                _ => call_malformed_plugin_attribute(sess, plugin.span()),
+            }
         }
     }
 
-    loader.plugins
+    plugins
 }
 
-impl<'a> PluginLoader<'a> {
-    fn load_plugin(&mut self, span: Span, name: Symbol, args: Vec<ast::NestedMetaItem>) {
-        let registrar = locator::find_plugin_registrar(self.sess, self.metadata_loader, span, name);
-
-        if let Some((lib, disambiguator)) = registrar {
-            let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator);
-            let fun = self.dylink_registrar(span, lib, symbol);
-            self.plugins.push(PluginRegistrar {
-                fun,
-                args,
-            });
-        }
+fn load_plugin(plugins: &mut Vec<PluginRegistrarFn>,
+               sess: &Session,
+               metadata_loader: &dyn MetadataLoader,
+               ident: Ident) {
+    let registrar = locator::find_plugin_registrar(sess, metadata_loader, ident.span, ident.name);
+
+    if let Some((lib, disambiguator)) = registrar {
+        let symbol = sess.generate_plugin_registrar_symbol(disambiguator);
+        let fun = dylink_registrar(sess, ident.span, lib, symbol);
+        plugins.push(fun);
     }
+}
 
-    // Dynamically link a registrar function into the compiler process.
-    fn dylink_registrar(&mut self,
-                        span: Span,
-                        path: PathBuf,
-                        symbol: String) -> PluginRegistrarFun {
-        use rustc_metadata::dynamic_lib::DynamicLibrary;
-
-        // Make sure the path contains a / or the linker will search for it.
-        let path = env::current_dir().unwrap().join(&path);
-
-        let lib = match DynamicLibrary::open(Some(&path)) {
-            Ok(lib) => lib,
-            // this is fatal: there are almost certainly macros we need
-            // inside this crate, so continue would spew "macro undefined"
-            // errors
-            Err(err) => {
-                self.sess.span_fatal(span, &err)
-            }
-        };
-
-        unsafe {
-            let registrar =
-                match lib.symbol(&symbol) {
-                    Ok(registrar) => {
-                        mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
-                    }
-                    // again fatal if we can't register macros
-                    Err(err) => {
-                        self.sess.span_fatal(span, &err)
-                    }
-                };
-
-            // Intentionally leak the dynamic library. We can't ever unload it
-            // since the library can make things that will live arbitrarily long
-            // (e.g., an @-box cycle or a thread).
-            mem::forget(lib);
-
-            registrar
+// Dynamically link a registrar function into the compiler process.
+fn dylink_registrar(sess: &Session,
+                    span: Span,
+                    path: PathBuf,
+                    symbol: String) -> PluginRegistrarFn {
+    use rustc_metadata::dynamic_lib::DynamicLibrary;
+
+    // Make sure the path contains a / or the linker will search for it.
+    let path = env::current_dir().unwrap().join(&path);
+
+    let lib = match DynamicLibrary::open(Some(&path)) {
+        Ok(lib) => lib,
+        // this is fatal: there are almost certainly macros we need
+        // inside this crate, so continue would spew "macro undefined"
+        // errors
+        Err(err) => {
+            sess.span_fatal(span, &err)
         }
+    };
+
+    unsafe {
+        let registrar =
+            match lib.symbol(&symbol) {
+                Ok(registrar) => {
+                    mem::transmute::<*mut u8, PluginRegistrarFn>(registrar)
+                }
+                // again fatal if we can't register macros
+                Err(err) => {
+                    sess.span_fatal(span, &err)
+                }
+            };
+
+        // Intentionally leak the dynamic library. We can't ever unload it
+        // since the library can make things that will live arbitrarily long
+        // (e.g., an @-box cycle or a thread).
+        mem::forget(lib);
+
+        registrar
     }
 }
diff --git a/src/librustc_plugin_impl/registry.rs b/src/librustc_plugin_impl/registry.rs
deleted file mode 100644
index bc684d59e5a..00000000000
--- a/src/librustc_plugin_impl/registry.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-//! Used by plugin crates to tell `rustc` about the plugins they provide.
-
-use rustc::lint::LintStore;
-use rustc::session::Session;
-use syntax::ast;
-use syntax_pos::Span;
-
-use std::borrow::ToOwned;
-
-/// Structure used to register plugins.
-///
-/// A plugin registrar function takes an `&mut Registry` and should call
-/// methods to register its plugins.
-///
-/// This struct has public fields and other methods for use by `rustc`
-/// itself. They are not documented here, and plugin authors should
-/// not use them.
-pub struct Registry<'a> {
-    /// Compiler session. Useful if you want to emit diagnostic messages
-    /// from the plugin registrar.
-    pub sess: &'a Session,
-
-    /// The `LintStore` allows plugins to register new lints.
-    pub lint_store: &'a mut LintStore,
-
-    #[doc(hidden)]
-    pub args_hidden: Option<Vec<ast::NestedMetaItem>>,
-
-    #[doc(hidden)]
-    pub krate_span: Span,
-
-    #[doc(hidden)]
-    pub llvm_passes: Vec<String>,
-}
-
-impl<'a> Registry<'a> {
-    #[doc(hidden)]
-    pub fn new(sess: &'a Session, lint_store: &'a mut LintStore, krate_span: Span) -> Registry<'a> {
-        Registry {
-            sess,
-            lint_store,
-            args_hidden: None,
-            krate_span,
-            llvm_passes: vec![],
-        }
-    }
-
-    /// Gets the plugin's arguments, if any.
-    ///
-    /// These are specified inside the `plugin` crate attribute as
-    ///
-    /// ```no_run
-    /// #![plugin(my_plugin_name(... args ...))]
-    /// ```
-    ///
-    /// Returns empty slice in case the plugin was loaded
-    /// with `--extra-plugins`
-    pub fn args(&self) -> &[ast::NestedMetaItem] {
-        self.args_hidden.as_ref().map(|v| &v[..]).unwrap_or(&[])
-    }
-
-    /// Register an LLVM pass.
-    ///
-    /// Registration with LLVM itself is handled through static C++ objects with
-    /// constructors. This method simply adds a name to the list of passes to
-    /// execute.
-    pub fn register_llvm_pass(&mut self, name: &str) {
-        self.llvm_passes.push(name.to_owned());
-    }
-}
diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs
index 8c4b4c16510..fcbc2a3301a 100644
--- a/src/librustc_privacy/lib.rs
+++ b/src/librustc_privacy/lib.rs
@@ -84,7 +84,7 @@ where
 {
     fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
         let TraitRef { def_id, substs } = trait_ref;
-        self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref) ||
+        self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path()) ||
         (!self.def_id_visitor.shallow() && substs.visit_with(self))
     }
 
diff --git a/src/librustc_resolve/Cargo.toml b/src/librustc_resolve/Cargo.toml
index 6cce893f8ec..caca20e4221 100644
--- a/src/librustc_resolve/Cargo.toml
+++ b/src/librustc_resolve/Cargo.toml
@@ -20,6 +20,7 @@ arena = { path = "../libarena" }
 errors = { path = "../librustc_errors", package = "rustc_errors" }
 syntax_pos = { path = "../libsyntax_pos" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_metadata = { path = "../librustc_metadata" }
 rustc_error_codes = { path = "../librustc_error_codes" }
 smallvec = { version = "1.0", features = ["union", "may_dangle"] }
diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs
index 6694ddc53d4..04e233c5973 100644
--- a/src/librustc_resolve/build_reduced_graph.rs
+++ b/src/librustc_resolve/build_reduced_graph.rs
@@ -19,7 +19,7 @@ use rustc::hir::def::{self, *};
 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
 use rustc::ty;
 use rustc::middle::cstore::CrateStore;
-use rustc_metadata::cstore::LoadedMacro;
+use rustc_metadata::creader::LoadedMacro;
 
 use std::cell::Cell;
 use std::ptr;
@@ -29,10 +29,8 @@ use errors::Applicability;
 
 use syntax::ast::{Name, Ident};
 use syntax::attr;
-
 use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
 use syntax::ast::{MetaItemKind, StmtKind, TraitItem, TraitItemKind};
-use syntax::feature_gate::is_builtin_attr;
 use syntax::token::{self, Token};
 use syntax::print::pprust;
 use syntax::{span_err, struct_span_err};
@@ -1231,7 +1229,7 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {
     }
 
     fn visit_attribute(&mut self, attr: &'b ast::Attribute) {
-        if !attr.is_doc_comment() && is_builtin_attr(attr) {
+        if !attr.is_doc_comment() && attr::is_builtin_attr(attr) {
             self.r.builtin_attrs.push(
                 (attr.get_normal_item().path.segments[0].ident, self.parent_scope)
             );
diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs
index e134b8b92ac..4dcafb6d279 100644
--- a/src/librustc_resolve/diagnostics.rs
+++ b/src/librustc_resolve/diagnostics.rs
@@ -9,8 +9,8 @@ use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
 use rustc::session::Session;
 use rustc::ty::{self, DefIdTree};
 use rustc::util::nodemap::FxHashSet;
+use rustc_feature::BUILTIN_ATTRIBUTES;
 use syntax::ast::{self, Ident, Path};
-use syntax::feature_gate::BUILTIN_ATTRIBUTES;
 use syntax::source_map::SourceMap;
 use syntax::struct_span_err;
 use syntax::symbol::{Symbol, kw};
diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs
index ab2aeb2fa82..be36e02f5b5 100644
--- a/src/librustc_resolve/lib.rs
+++ b/src/librustc_resolve/lib.rs
@@ -32,8 +32,7 @@ use rustc::ty::{self, DefIdTree, ResolverOutputs};
 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
 use rustc::span_bug;
 
-use rustc_metadata::creader::CrateLoader;
-use rustc_metadata::cstore::CStore;
+use rustc_metadata::creader::{CrateLoader, CStore};
 
 use syntax::{struct_span_err, unwrap_or};
 use syntax::ast::{self, Name, NodeId, Ident, FloatTy, IntTy, UintTy};
diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs
index 21c24f9da1c..9e7098da49f 100644
--- a/src/librustc_resolve/macros.rs
+++ b/src/librustc_resolve/macros.rs
@@ -12,18 +12,18 @@ use rustc::middle::stability;
 use rustc::session::Session;
 use rustc::util::nodemap::FxHashSet;
 use rustc::{ty, lint, span_bug};
+use rustc_feature::is_builtin_attr_name;
 use syntax::ast::{self, NodeId, Ident};
 use syntax::attr::{self, StabilityLevel};
 use syntax::edition::Edition;
-use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
-use syntax::feature_gate::GateIssue;
+use syntax::feature_gate::feature_err;
 use syntax::print::pprust;
-use syntax::symbol::{Symbol, kw, sym};
 use syntax_expand::base::{self, InvocationRes, Indeterminate};
 use syntax_expand::base::SyntaxExtension;
 use syntax_expand::expand::{AstFragment, AstFragmentKind, Invocation, InvocationKind};
 use syntax_expand::compile_declarative_macro;
 use syntax_pos::hygiene::{self, ExpnId, ExpnData, ExpnKind};
+use syntax_pos::symbol::{Symbol, kw, sym};
 use syntax_pos::{Span, DUMMY_SP};
 
 use std::{mem, ptr};
@@ -346,13 +346,8 @@ impl<'a> Resolver<'a> {
                segment.ident.as_str().starts_with("rustc") {
                 let msg =
                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler";
-                emit_feature_err(
-                    &self.session.parse_sess,
-                    sym::rustc_attrs,
-                    segment.ident.span,
-                    GateIssue::Language,
-                    msg,
-                );
+                feature_err(&self.session.parse_sess, sym::rustc_attrs, segment.ident.span, msg)
+                    .emit();
             }
         }
 
diff --git a/src/librustc_target/abi/call/mod.rs b/src/librustc_target/abi/call/mod.rs
index aced12aa32a..3a3ad763790 100644
--- a/src/librustc_target/abi/call/mod.rs
+++ b/src/librustc_target/abi/call/mod.rs
@@ -69,6 +69,8 @@ mod attr_impl {
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct ArgAttributes {
     pub regular: ArgAttribute,
+    /// The minimum size of the pointee, guaranteed to be valid for the duration of the whole call
+    /// (corresponding to LLVM's dereferenceable and dereferenceable_or_null attributes).
     pub pointee_size: Size,
     pub pointee_align: Option<Align>
 }
diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs
index a33b2e32c86..af978d5095e 100644
--- a/src/librustc_typeck/astconv.rs
+++ b/src/librustc_typeck/astconv.rs
@@ -23,7 +23,7 @@ use crate::require_c_abi_if_c_variadic;
 use smallvec::SmallVec;
 use syntax::ast;
 use syntax::errors::pluralize;
-use syntax::feature_gate::{GateIssue, emit_feature_err};
+use syntax::feature_gate::feature_err;
 use syntax::util::lev_distance::find_best_match_for_name;
 use syntax::symbol::sym;
 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
@@ -914,8 +914,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             } else {
                 "parenthetical notation is only stable when used with `Fn`-family traits"
             };
-            emit_feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures,
-                             span, GateIssue::Language, msg);
+            feature_err(&self.tcx().sess.parse_sess, sym::unboxed_closures, span, msg).emit();
         }
 
         self.create_substs_for_ast_path(span,
@@ -1149,8 +1148,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
             });
-            self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
-                                          binding.item_name, binding.span)
+            self.one_bound_for_assoc_type(
+                candidates,
+                &trait_ref.print_only_trait_path().to_string(),
+                binding.item_name,
+                binding.span
+            )
         }?;
 
         let (assoc_ident, def_scope) =
@@ -1589,12 +1592,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
                 if let Some(span) = bound_span {
                     err.span_label(span, format!("ambiguous `{}` from `{}`",
                                                  assoc_name,
-                                                 bound));
+                                                 bound.print_only_trait_path()));
                 } else {
                     span_note!(&mut err, span,
                                "associated type `{}` could derive from `{}`",
                                ty_param_name,
-                               bound);
+                               bound.print_only_trait_path());
                 }
             }
             err.emit();
diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs
index 871acb2726a..901a2192e20 100644
--- a/src/librustc_typeck/check/coercion.rs
+++ b/src/librustc_typeck/check/coercion.rs
@@ -644,11 +644,13 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
         }
 
         if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
-            feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
-                                           sym::unsized_tuple_coercion,
-                                           self.cause.span,
-                                           feature_gate::GateIssue::Language,
-                                           feature_gate::EXPLAIN_UNSIZED_TUPLE_COERCION);
+            feature_gate::feature_err(
+                &self.tcx.sess.parse_sess,
+                sym::unsized_tuple_coercion,
+                self.cause.span,
+                "unsized tuple coercion is not stable enough for use and is subject to change",
+            )
+            .emit();
         }
 
         Ok(coercion)
diff --git a/src/librustc_typeck/check/generator_interior.rs b/src/librustc_typeck/check/generator_interior.rs
index 6e37c0dbbdf..fcf6b22f74f 100644
--- a/src/librustc_typeck/check/generator_interior.rs
+++ b/src/librustc_typeck/check/generator_interior.rs
@@ -185,6 +185,8 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
     }
 
     fn visit_expr(&mut self, expr: &'tcx Expr) {
+        let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
+
         match &expr.kind {
             ExprKind::Call(callee, args) => match &callee.kind {
                 ExprKind::Path(qpath) => {
@@ -210,13 +212,20 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> {
                 }
                 _ => intravisit::walk_expr(self, expr),
             }
+            ExprKind::Path(qpath) => {
+                let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id);
+                if let Res::Def(DefKind::Static, def_id) = res {
+                    // Statics are lowered to temporary references or
+                    // pointers in MIR, so record that type.
+                    let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id);
+                    self.record(ptr_ty, scope, Some(expr), expr.span);
+                }
+            }
             _ => intravisit::walk_expr(self, expr),
         }
 
         self.expr_count += 1;
 
-        let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
-
         // If there are adjustments, then record the final type --
         // this is the actual value that is being produced.
         if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {
diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs
index 6e37a1a47f0..f4b53b4d106 100644
--- a/src/librustc_typeck/check/method/suggest.rs
+++ b/src/librustc_typeck/check/method/suggest.rs
@@ -502,7 +502,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
 
                 if !unsatisfied_predicates.is_empty() {
                     let mut bound_list = unsatisfied_predicates.iter()
-                        .map(|p| format!("`{} : {}`", p.self_ty(), p))
+                        .map(|p| format!("`{} : {}`", p.self_ty(), p.print_only_trait_path()))
                         .collect::<Vec<_>>();
                     bound_list.sort();
                     bound_list.dedup();  // #35677
diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs
index 930241262b0..c7a0190a1d1 100644
--- a/src/librustc_typeck/check/mod.rs
+++ b/src/librustc_typeck/check/mod.rs
@@ -125,7 +125,7 @@ use syntax_pos::{self, BytePos, Span, MultiSpan};
 use syntax_pos::hygiene::DesugaringKind;
 use syntax::ast;
 use syntax::attr;
-use syntax::feature_gate::{GateIssue, emit_feature_err};
+use syntax::feature_gate::feature_err;
 use syntax::source_map::{DUMMY_SP, original_sp};
 use syntax::symbol::{kw, sym, Ident};
 use syntax::util::parser::ExprPrecedence;
@@ -2002,7 +2002,7 @@ fn check_impl_items_against_trait<'tcx>(
                              "item `{}` is an associated const, \
                               which doesn't match its trait `{}`",
                              ty_impl_item.ident,
-                             impl_trait_ref);
+                             impl_trait_ref.print_only_trait_path());
                          err.span_label(impl_item.span, "does not match trait");
                          // We can only get the spans from local trait definition
                          // Same for E0324 and E0325
@@ -2026,7 +2026,7 @@ fn check_impl_items_against_trait<'tcx>(
                             "item `{}` is an associated method, \
                              which doesn't match its trait `{}`",
                             ty_impl_item.ident,
-                            impl_trait_ref);
+                            impl_trait_ref.print_only_trait_path());
                          err.span_label(impl_item.span, "does not match trait");
                          if let Some(trait_span) = tcx.hir().span_if_local(ty_trait_item.def_id) {
                             err.span_label(trait_span, "item in trait");
@@ -2045,7 +2045,7 @@ fn check_impl_items_against_trait<'tcx>(
                             "item `{}` is an associated type, \
                              which doesn't match its trait `{}`",
                             ty_impl_item.ident,
-                            impl_trait_ref);
+                            impl_trait_ref.print_only_trait_path());
                          err.span_label(impl_item.span, "does not match trait");
                          if let Some(trait_span) = tcx.hir().span_if_local(ty_trait_item.def_id) {
                             err.span_label(trait_span, "item in trait");
@@ -2373,13 +2373,13 @@ fn check_transparent(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) {
 
     if adt.is_enum() {
         if !tcx.features().transparent_enums {
-            emit_feature_err(
+            feature_err(
                 &tcx.sess.parse_sess,
                 sym::transparent_enums,
                 sp,
-                GateIssue::Language,
                 "transparent enums are unstable",
-            );
+            )
+            .emit();
         }
         if adt.variants.len() != 1 {
             bad_variant_count(tcx, adt, sp, def_id);
@@ -2391,11 +2391,13 @@ fn check_transparent(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) {
     }
 
     if adt.is_union() && !tcx.features().transparent_unions {
-        emit_feature_err(&tcx.sess.parse_sess,
-                         sym::transparent_unions,
-                         sp,
-                         GateIssue::Language,
-                         "transparent unions are unstable");
+        feature_err(
+            &tcx.sess.parse_sess,
+            sym::transparent_unions,
+            sp,
+            "transparent unions are unstable",
+        )
+        .emit();
     }
 
     // For each field, figure out if it's known to be a ZST and align(1)
@@ -2452,11 +2454,13 @@ pub fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant], i
     let repr_type_ty = def.repr.discr_type().to_ty(tcx);
     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
         if !tcx.features().repr128 {
-            emit_feature_err(&tcx.sess.parse_sess,
-                             sym::repr128,
-                             sp,
-                             GateIssue::Language,
-                             "repr with 128-bit type is unstable");
+            feature_err(
+                &tcx.sess.parse_sess,
+                sym::repr128,
+                sp,
+                "repr with 128-bit type is unstable",
+            )
+            .emit();
         }
     }
 
diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs
index f4fdc2882e7..8ceb2174852 100644
--- a/src/librustc_typeck/check/regionck.rs
+++ b/src/librustc_typeck/check/regionck.rs
@@ -74,8 +74,7 @@
 
 use crate::check::dropck;
 use crate::check::FnCtxt;
-use crate::middle::mem_categorization as mc;
-use crate::middle::mem_categorization::Categorization;
+use crate::mem_categorization as mc;
 use crate::middle::region;
 use rustc::hir::def_id::DefId;
 use rustc::infer::outlives::env::OutlivesEnvironment;
@@ -88,7 +87,6 @@ use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
 use rustc::hir::{self, PatKind};
 use std::mem;
 use std::ops::Deref;
-use std::rc::Rc;
 use syntax_pos::Span;
 
 // a variation on try that just returns unit
@@ -814,18 +812,17 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
     where
         F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
     {
-        f(mc::MemCategorizationContext::with_infer(
+        f(mc::MemCategorizationContext::new(
             &self.infcx,
             self.outlives_environment.param_env,
             self.body_owner,
-            &self.region_scope_tree,
             &self.tables.borrow(),
         ))
     }
 
     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
     /// dereferenced, the lifetime of the pointer includes the deref expr.
-    fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt_<'tcx>> {
+    fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::Place<'tcx>> {
         debug!("constrain_adjustments(expr={:?})", expr);
 
         let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
@@ -899,10 +896,6 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
             }
 
             cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
-
-            if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
-                self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
-            }
         }
 
         Ok(cmt)
@@ -921,16 +914,22 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
         )
     }
 
-    fn check_safety_of_rvalue_destructor_if_necessary(&mut self, cmt: &mc::cmt_<'tcx>, span: Span) {
-        if let Categorization::Rvalue = cmt.cat {
-            let typ = self.resolve_type(cmt.ty);
-            let body_id = self.body_id;
-            let _ = dropck::check_drop_obligations(
-                self,
-                typ,
-                span,
-                body_id,
-            );
+    fn check_safety_of_rvalue_destructor_if_necessary(
+        &mut self,
+        place: &mc::Place<'tcx>,
+        span: Span,
+    ) {
+        if let mc::PlaceBase::Rvalue = place.base {
+            if place.projections.is_empty() {
+                let typ = self.resolve_type(place.ty);
+                let body_id = self.body_id;
+                let _ = dropck::check_drop_obligations(
+                    self,
+                    typ,
+                    span,
+                    body_id,
+                );
+            }
         }
     }
 
@@ -1035,7 +1034,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
             }
             Some(ref expr) => &**expr,
         };
-        let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr))));
+        let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
         self.link_pattern(discr_cmt, &local.pat);
     }
 
@@ -1044,7 +1043,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
     /// linked to the lifetime of its guarantor (if any).
     fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
         debug!("regionck::for_match()");
-        let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(discr))));
+        let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
         debug!("discr_cmt={:?}", discr_cmt);
         for arm in arms {
             self.link_pattern(discr_cmt.clone(), &arm.pat);
@@ -1058,7 +1057,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
         for param in params {
             let param_ty = self.node_ty(param.hir_id);
             let param_cmt = self.with_mc(|mc| {
-                Rc::new(mc.cat_rvalue(param.hir_id, param.pat.span, param_ty))
+                mc.cat_rvalue(param.hir_id, param.pat.span, param_ty)
             });
             debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
             self.link_pattern(param_cmt, &param.pat);
@@ -1067,7 +1066,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
 
     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
     /// in the discriminant, if needed.
-    fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
+    fn link_pattern(&self, discr_cmt: mc::Place<'tcx>, root_pat: &hir::Pat) {
         debug!(
             "link_pattern(discr_cmt={:?}, root_pat={:?})",
             discr_cmt, root_pat
@@ -1100,7 +1099,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
     fn link_autoref(
         &self,
         expr: &hir::Expr,
-        expr_cmt: &mc::cmt_<'tcx>,
+        expr_cmt: &mc::Place<'tcx>,
         autoref: &adjustment::AutoBorrow<'tcx>,
     ) {
         debug!(
@@ -1130,7 +1129,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
         span: Span,
         id: hir::HirId,
         mutbl: hir::Mutability,
-        cmt_borrowed: &mc::cmt_<'tcx>,
+        cmt_borrowed: &mc::Place<'tcx>,
     ) {
         debug!(
             "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
@@ -1153,61 +1152,35 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
         span: Span,
         borrow_region: ty::Region<'tcx>,
         borrow_kind: ty::BorrowKind,
-        borrow_cmt: &mc::cmt_<'tcx>,
+        borrow_place: &mc::Place<'tcx>,
     ) {
-        let origin = infer::DataBorrowed(borrow_cmt.ty, span);
-        self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
+        let origin = infer::DataBorrowed(borrow_place.ty, span);
+        self.type_must_outlive(origin, borrow_place.ty, borrow_region);
 
-        let mut borrow_kind = borrow_kind;
-        let mut borrow_cmt_cat = borrow_cmt.cat.clone();
-
-        loop {
+        for pointer_ty in borrow_place.deref_tys() {
             debug!(
-                "link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
-                borrow_region, borrow_kind, borrow_cmt
+                "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
+                borrow_region, borrow_kind, borrow_place
             );
-            match borrow_cmt_cat {
-                Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
-                    match self.link_reborrowed_region(
+            match pointer_ty.kind {
+                ty::RawPtr(_) => return,
+                ty::Ref(ref_region, _, ref_mutability) => {
+                    if self.link_reborrowed_region(
                         span,
                         borrow_region,
-                        borrow_kind,
-                        ref_cmt,
                         ref_region,
-                        ref_kind,
-                        borrow_cmt.note,
+                        ref_mutability,
                     ) {
-                        Some((c, k)) => {
-                            borrow_cmt_cat = c.cat.clone();
-                            borrow_kind = k;
-                        }
-                        None => {
-                            return;
-                        }
+                        return;
                     }
-                }
-
-                Categorization::Downcast(cmt_base, _)
-                | Categorization::Deref(cmt_base, mc::Unique)
-                | Categorization::Interior(cmt_base, _) => {
-                    // Borrowing interior or owned data requires the base
-                    // to be valid and borrowable in the same fashion.
-                    borrow_cmt_cat = cmt_base.cat.clone();
-                    borrow_kind = borrow_kind;
-                }
 
-                Categorization::Deref(_, mc::UnsafePtr(..))
-                | Categorization::StaticItem
-                | Categorization::Upvar(..)
-                | Categorization::Local(..)
-                | Categorization::ThreadLocal
-                | Categorization::Rvalue => {
-                    // These are all "base cases" with independent lifetimes
-                    // that are not subject to inference
-                    return;
                 }
+                _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty)
             }
         }
+        if let mc::PlaceBase::Upvar(upvar_id) = borrow_place.base {
+            self.link_upvar_region(span, borrow_region, upvar_id);
+        }
     }
 
     /// This is the most complicated case: the path being borrowed is
@@ -1231,83 +1204,28 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
     ///
     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
     ///
-    /// Unfortunately, there are some complications beyond the simple
-    /// scenario I just painted:
-    ///
-    /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
-    ///    case, we have two jobs. First, we are inferring whether this reference
-    ///    should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
-    ///    adjust that based on this borrow (e.g., if this is an `&mut` borrow,
-    ///    then `r` must be an `&mut` reference). Second, whenever we link
-    ///    two regions (here, `'z <= 'a`), we supply a *cause*, and in this
-    ///    case we adjust the cause to indicate that the reference being
-    ///    "reborrowed" is itself an upvar. This provides a nicer error message
-    ///    should something go wrong.
+    /// There is a complication beyond the simple scenario I just painted: there
+    /// may in fact be more levels of reborrowing. In the example, I said the
+    /// borrow was like `&'z *r`, but it might in fact be a borrow like
+    /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
+    /// ensure that `'z <= 'a` and `'z <= 'b`.
     ///
-    /// 2. There may in fact be more levels of reborrowing. In the
-    ///    example, I said the borrow was like `&'z *r`, but it might
-    ///    in fact be a borrow like `&'z **q` where `q` has type `&'a
-    ///    &'b mut T`. In that case, we want to ensure that `'z <= 'a`
-    ///    and `'z <= 'b`. This is explained more below.
+    /// The return value of this function indicates whether we *don't* need to
+    /// the recurse to the next reference up.
     ///
-    /// The return value of this function indicates whether we need to
-    /// recurse and process `ref_cmt` (see case 2 above).
+    /// This is explained more below.
     fn link_reborrowed_region(
         &self,
         span: Span,
         borrow_region: ty::Region<'tcx>,
-        borrow_kind: ty::BorrowKind,
-        ref_cmt: mc::cmt<'tcx>,
         ref_region: ty::Region<'tcx>,
-        mut ref_kind: ty::BorrowKind,
-        note: mc::Note,
-    ) -> Option<(mc::cmt<'tcx>, ty::BorrowKind)> {
-        // Possible upvar ID we may need later to create an entry in the
-        // maybe link map.
-
-        // Detect by-ref upvar `x`:
-        let cause = match note {
-            mc::NoteUpvarRef(ref upvar_id) => {
-                match self.tables.borrow().upvar_capture_map.get(upvar_id) {
-                    Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
-                        // The mutability of the upvar may have been modified
-                        // by the above adjustment, so update our local variable.
-                        ref_kind = upvar_borrow.kind;
-
-                        infer::ReborrowUpvar(span, *upvar_id)
-                    }
-                    _ => {
-                        span_bug!(span, "Illegal upvar id: {:?}", upvar_id);
-                    }
-                }
-            }
-            mc::NoteClosureEnv(ref upvar_id) => {
-                // We don't have any mutability changes to propagate, but
-                // we do want to note that an upvar reborrow caused this
-                // link
-                infer::ReborrowUpvar(span, *upvar_id)
-            }
-            _ => infer::Reborrow(span),
-        };
-
+        ref_mutability: hir::Mutability,
+    ) -> bool {
         debug!(
             "link_reborrowed_region: {:?} <= {:?}",
             borrow_region, ref_region
         );
-        self.sub_regions(cause, borrow_region, ref_region);
-
-        // If we end up needing to recurse and establish a region link
-        // with `ref_cmt`, calculate what borrow kind we will end up
-        // needing. This will be used below.
-        //
-        // One interesting twist is that we can weaken the borrow kind
-        // when we recurse: to reborrow an `&mut` referent as mutable,
-        // borrowck requires a unique path to the `&mut` reference but not
-        // necessarily a *mutable* path.
-        let new_borrow_kind = match borrow_kind {
-            ty::ImmBorrow => ty::ImmBorrow,
-            ty::MutBorrow | ty::UniqueImmBorrow => ty::UniqueImmBorrow,
-        };
+        self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
 
         // Decide whether we need to recurse and link any regions within
         // the `ref_cmt`. This is concerned for the case where the value
@@ -1336,24 +1254,83 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
         // (Note that since we have not examined `ref_cmt.cat`, we don't
         // know whether this scenario has occurred; but I wanted to show
         // how all the types get adjusted.)
-        match ref_kind {
-            ty::ImmBorrow => {
+        match ref_mutability {
+            hir::Mutability::Immutable => {
                 // The reference being reborrowed is a shareable ref of
                 // type `&'a T`. In this case, it doesn't matter where we
                 // *found* the `&T` pointer, the memory it references will
                 // be valid and immutable for `'a`. So we can stop here.
-                //
-                // (Note that the `borrow_kind` must also be ImmBorrow or
-                // else the user is borrowed imm memory as mut memory,
-                // which means they'll get an error downstream in borrowck
-                // anyhow.)
-                return None;
+                true
+            }
+
+            hir::Mutability::Mutable => {
+                // The reference being reborrowed is either an `&mut T`. This is
+                // the case where recursion is needed.
+                false
             }
+        }
+    }
 
-            ty::MutBorrow | ty::UniqueImmBorrow => {
-                // The reference being reborrowed is either an `&mut T` or
-                // `&uniq T`. This is the case where recursion is needed.
-                return Some((ref_cmt, new_borrow_kind));
+    /// An upvar may be behind up to 2 references:
+    ///
+    /// * One can come from the reference to a "by-reference" upvar.
+    /// * Another one can come from the reference to the closure itself if it's
+    ///   a `FnMut` or `Fn` closure.
+    ///
+    /// This function links the lifetimes of those references to the lifetime
+    /// of the borrow that's provided. See [link_reborrowed_region] for some
+    /// more explanation of this in the general case.
+    ///
+    /// We also supply a *cause*, and in this case we set the cause to
+    /// indicate that the reference being "reborrowed" is itself an upvar. This
+    /// provides a nicer error message should something go wrong.
+    fn link_upvar_region(
+        &self,
+        span: Span,
+        borrow_region: ty::Region<'tcx>,
+        upvar_id: ty::UpvarId,
+    ) {
+        debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
+        // A by-reference upvar can't be borrowed for longer than the
+        // upvar is borrowed from the environment.
+        match self.tables.borrow().upvar_capture(upvar_id) {
+            ty::UpvarCapture::ByRef(upvar_borrow) => {
+                self.sub_regions(
+                    infer::ReborrowUpvar(span, upvar_id),
+                    borrow_region,
+                    upvar_borrow.region,
+                );
+                if let ty::ImmBorrow = upvar_borrow.kind {
+                    debug!("link_upvar_region: capture by shared ref");
+                    return;
+                }
+            }
+            ty::UpvarCapture::ByValue => {}
+        }
+        let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id);
+        let ty = self.resolve_node_type(fn_hir_id);
+        debug!("link_upvar_region: ty={:?}", ty);
+
+        // A closure capture can't be borrowed for longer than the
+        // reference to the closure.
+        if let ty::Closure(closure_def_id, substs) = ty.kind {
+            match self.infcx.closure_kind(closure_def_id, substs) {
+                Some(ty::ClosureKind::Fn) | Some(ty::ClosureKind::FnMut) => {
+                    // Region of environment pointer
+                    let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
+                        scope: upvar_id.closure_expr_id.to_def_id(),
+                        bound_region: ty::BrEnv
+                    }));
+                    self.sub_regions(
+                        infer::ReborrowUpvar(span, upvar_id),
+                        borrow_region,
+                        env_region,
+                    );
+                }
+                Some(ty::ClosureKind::FnOnce) => {}
+                None => {
+                    span_bug!(span, "Have not inferred closure kind before regionck");
+                }
             }
         }
     }
diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs
index 390ee0d0f83..3002459d56f 100644
--- a/src/librustc_typeck/check/upvar.rs
+++ b/src/librustc_typeck/check/upvar.rs
@@ -32,9 +32,9 @@
 
 use super::FnCtxt;
 
-use crate::middle::expr_use_visitor as euv;
-use crate::middle::mem_categorization as mc;
-use crate::middle::mem_categorization::Categorization;
+use crate::expr_use_visitor as euv;
+use crate::mem_categorization as mc;
+use crate::mem_categorization::PlaceBase;
 use rustc::hir;
 use rustc::hir::def_id::DefId;
 use rustc::hir::def_id::LocalDefId;
@@ -76,6 +76,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
 }
 
 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
+    /// Analysis starting point.
     fn analyze_closure(
         &self,
         closure_hir_id: hir::HirId,
@@ -83,9 +84,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
         body: &hir::Body,
         capture_clause: hir::CaptureBy,
     ) {
-        /*!
-         * Analysis starting point.
-         */
 
         debug!(
             "analyze_closure(id={:?}, body.id={:?})",
@@ -171,20 +169,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
 
         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body.id());
         assert_eq!(body_owner_def_id, closure_def_id);
-        let region_scope_tree = &self.tcx.region_scope_tree(body_owner_def_id);
         let mut delegate = InferBorrowKind {
             fcx: self,
-            closure_def_id: closure_def_id,
+            closure_def_id,
             current_closure_kind: ty::ClosureKind::LATTICE_BOTTOM,
             current_origin: None,
             adjust_upvar_captures: ty::UpvarCaptureMap::default(),
         };
-        euv::ExprUseVisitor::with_infer(
+        euv::ExprUseVisitor::new(
             &mut delegate,
             &self.infcx,
             body_owner_def_id,
             self.param_env,
-            region_scope_tree,
             &self.tables.borrow(),
         )
         .consume_body(body);
@@ -312,13 +308,10 @@ struct InferBorrowKind<'a, 'tcx> {
 impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
     fn adjust_upvar_borrow_kind_for_consume(
         &mut self,
-        cmt: &mc::cmt_<'tcx>,
+        place: &mc::Place<'tcx>,
         mode: euv::ConsumeMode,
     ) {
-        debug!(
-            "adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
-            cmt, mode
-        );
+        debug!("adjust_upvar_borrow_kind_for_consume(place={:?}, mode={:?})", place, mode);
 
         // we only care about moves
         match mode {
@@ -329,132 +322,68 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
         }
 
         let tcx = self.fcx.tcx;
+        let upvar_id = if let PlaceBase::Upvar(upvar_id) = place.base {
+            upvar_id
+        } else {
+            return;
+        };
 
-        // watch out for a move of the deref of a borrowed pointer;
-        // for that to be legal, the upvar would have to be borrowed
-        // by value instead
-        let guarantor = cmt.guarantor();
-        debug!(
-            "adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
-            guarantor
-        );
-        debug!(
-            "adjust_upvar_borrow_kind_for_consume: guarantor.cat={:?}",
-            guarantor.cat
-        );
-        if let Categorization::Deref(_, mc::BorrowedPtr(..)) = guarantor.cat {
-            debug!(
-                "adjust_upvar_borrow_kind_for_consume: found deref with note {:?}",
-                cmt.note
-            );
-            match guarantor.note {
-                mc::NoteUpvarRef(upvar_id) => {
-                    debug!(
-                        "adjust_upvar_borrow_kind_for_consume: \
-                         setting upvar_id={:?} to by value",
-                        upvar_id
-                    );
+        debug!("adjust_upvar_borrow_kind_for_consume: upvar={:?}", upvar_id);
 
-                    // to move out of an upvar, this must be a FnOnce closure
-                    self.adjust_closure_kind(
-                        upvar_id.closure_expr_id,
-                        ty::ClosureKind::FnOnce,
-                        guarantor.span,
-                        var_name(tcx, upvar_id.var_path.hir_id),
-                    );
+        // To move out of an upvar, this must be a FnOnce closure
+        self.adjust_closure_kind(
+            upvar_id.closure_expr_id,
+            ty::ClosureKind::FnOnce,
+            place.span,
+            var_name(tcx, upvar_id.var_path.hir_id),
+        );
 
-                    self.adjust_upvar_captures
-                        .insert(upvar_id, ty::UpvarCapture::ByValue);
-                }
-                mc::NoteClosureEnv(upvar_id) => {
-                    // we get just a closureenv ref if this is a
-                    // `move` closure, or if the upvar has already
-                    // been inferred to by-value. In any case, we
-                    // must still adjust the kind of the closure
-                    // to be a FnOnce closure to permit moves out
-                    // of the environment.
-                    self.adjust_closure_kind(
-                        upvar_id.closure_expr_id,
-                        ty::ClosureKind::FnOnce,
-                        guarantor.span,
-                        var_name(tcx, upvar_id.var_path.hir_id),
-                    );
-                }
-                mc::NoteIndex | mc::NoteNone => {}
-            }
-        }
+        self.adjust_upvar_captures.insert(upvar_id, ty::UpvarCapture::ByValue);
     }
 
-    /// Indicates that `cmt` is being directly mutated (e.g., assigned
-    /// to). If cmt contains any by-ref upvars, this implies that
-    /// those upvars must be borrowed using an `&mut` borrow.
-    fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: &mc::cmt_<'tcx>) {
-        debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})", cmt);
-
-        match cmt.cat.clone() {
-            Categorization::Deref(base, mc::Unique)
-            | Categorization::Interior(base, _)
-            | Categorization::Downcast(base, _) => {
-                // Interior or owned data is mutable if base is
-                // mutable, so iterate to the base.
-                self.adjust_upvar_borrow_kind_for_mut(&base);
-            }
-
-            Categorization::Deref(base, mc::BorrowedPtr(..)) => {
-                if !self.try_adjust_upvar_deref(cmt, ty::MutBorrow) {
+    /// Indicates that `place` is being directly mutated (e.g., assigned
+    /// to). If the place is based on a by-ref upvar, this implies that
+    /// the upvar must be borrowed using an `&mut` borrow.
+    fn adjust_upvar_borrow_kind_for_mut(&mut self, place: &mc::Place<'tcx>) {
+        debug!("adjust_upvar_borrow_kind_for_mut(place={:?})", place);
+
+        if let PlaceBase::Upvar(upvar_id) = place.base {
+            let mut borrow_kind = ty::MutBorrow;
+            for pointer_ty in place.deref_tys() {
+                match pointer_ty.kind {
+                    // Raw pointers don't inherit mutability.
+                    ty::RawPtr(_) => return,
                     // assignment to deref of an `&mut`
                     // borrowed pointer implies that the
                     // pointer itself must be unique, but not
                     // necessarily *mutable*
-                    self.adjust_upvar_borrow_kind_for_unique(&base);
+                    ty::Ref(.., hir::Mutability::Mutable) => borrow_kind = ty::UniqueImmBorrow,
+                    _ => (),
                 }
             }
-
-            Categorization::Deref(_, mc::UnsafePtr(..))
-            | Categorization::StaticItem
-            | Categorization::ThreadLocal
-            | Categorization::Rvalue
-            | Categorization::Local(_)
-            | Categorization::Upvar(..) => {
-                return;
-            }
+            self.adjust_upvar_deref(upvar_id, place.span, borrow_kind);
         }
     }
 
-    fn adjust_upvar_borrow_kind_for_unique(&mut self, cmt: &mc::cmt_<'tcx>) {
-        debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})", cmt);
+    fn adjust_upvar_borrow_kind_for_unique(&mut self, place: &mc::Place<'tcx>) {
+        debug!("adjust_upvar_borrow_kind_for_unique(place={:?})", place);
 
-        match cmt.cat.clone() {
-            Categorization::Deref(base, mc::Unique)
-            | Categorization::Interior(base, _)
-            | Categorization::Downcast(base, _) => {
-                // Interior or owned data is unique if base is
-                // unique.
-                self.adjust_upvar_borrow_kind_for_unique(&base);
-            }
-
-            Categorization::Deref(base, mc::BorrowedPtr(..)) => {
-                if !self.try_adjust_upvar_deref(cmt, ty::UniqueImmBorrow) {
-                    // for a borrowed pointer to be unique, its
-                    // base must be unique
-                    self.adjust_upvar_borrow_kind_for_unique(&base);
-                }
+        if let PlaceBase::Upvar(upvar_id) = place.base {
+            if place.deref_tys().any(ty::TyS::is_unsafe_ptr) {
+                // Raw pointers don't inherit mutability.
+                return;
             }
-
-            Categorization::Deref(_, mc::UnsafePtr(..))
-            | Categorization::StaticItem
-            | Categorization::ThreadLocal
-            | Categorization::Rvalue
-            | Categorization::Local(_)
-            | Categorization::Upvar(..) => {}
+            // for a borrowed pointer to be unique, its base must be unique
+            self.adjust_upvar_deref(upvar_id, place.span, ty::UniqueImmBorrow);
         }
     }
 
-    fn try_adjust_upvar_deref(
+    fn adjust_upvar_deref(
         &mut self,
-        cmt: &mc::cmt_<'tcx>,
+        upvar_id: ty::UpvarId,
+        place_span: Span,
         borrow_kind: ty::BorrowKind,
-    ) -> bool {
+    ) {
         assert!(match borrow_kind {
             ty::MutBorrow => true,
             ty::UniqueImmBorrow => true,
@@ -465,39 +394,19 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
 
         let tcx = self.fcx.tcx;
 
-        match cmt.note {
-            mc::NoteUpvarRef(upvar_id) => {
-                // if this is an implicit deref of an
-                // upvar, then we need to modify the
-                // borrow_kind of the upvar to make sure it
-                // is inferred to mutable if necessary
-                self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
-
-                // also need to be in an FnMut closure since this is not an ImmBorrow
-                self.adjust_closure_kind(
-                    upvar_id.closure_expr_id,
-                    ty::ClosureKind::FnMut,
-                    cmt.span,
-                    var_name(tcx, upvar_id.var_path.hir_id),
-                );
-
-                true
-            }
-            mc::NoteClosureEnv(upvar_id) => {
-                // this kind of deref occurs in a `move` closure, or
-                // for a by-value upvar; in either case, to mutate an
-                // upvar, we need to be an FnMut closure
-                self.adjust_closure_kind(
-                    upvar_id.closure_expr_id,
-                    ty::ClosureKind::FnMut,
-                    cmt.span,
-                    var_name(tcx, upvar_id.var_path.hir_id),
-                );
-
-                true
-            }
-            mc::NoteIndex | mc::NoteNone => false,
-        }
+        // if this is an implicit deref of an
+        // upvar, then we need to modify the
+        // borrow_kind of the upvar to make sure it
+        // is inferred to mutable if necessary
+        self.adjust_upvar_borrow_kind(upvar_id, borrow_kind);
+
+        // also need to be in an FnMut closure since this is not an ImmBorrow
+        self.adjust_closure_kind(
+            upvar_id.closure_expr_id,
+            ty::ClosureKind::FnMut,
+            place_span,
+            var_name(tcx, upvar_id.var_path.hir_id),
+        );
     }
 
     /// We infer the borrow_kind with which to borrow upvars in a stack closure.
@@ -509,7 +418,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
         let upvar_capture = self
             .adjust_upvar_captures
             .get(&upvar_id)
-            .cloned()
+            .copied()
             .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id));
         debug!(
             "adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
@@ -586,29 +495,29 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> {
 }
 
 impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
-    fn consume(&mut self, cmt: &mc::cmt_<'tcx>,mode: euv::ConsumeMode) {
-        debug!("consume(cmt={:?},mode={:?})", cmt, mode);
-        self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
+    fn consume(&mut self, place: &mc::Place<'tcx>,mode: euv::ConsumeMode) {
+        debug!("consume(place={:?},mode={:?})", place, mode);
+        self.adjust_upvar_borrow_kind_for_consume(place, mode);
     }
 
-    fn borrow(&mut self, cmt: &mc::cmt_<'tcx>, bk: ty::BorrowKind) {
-        debug!("borrow(cmt={:?}, bk={:?})", cmt, bk);
+    fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind) {
+        debug!("borrow(place={:?}, bk={:?})", place, bk);
 
         match bk {
             ty::ImmBorrow => {}
             ty::UniqueImmBorrow => {
-                self.adjust_upvar_borrow_kind_for_unique(cmt);
+                self.adjust_upvar_borrow_kind_for_unique(place);
             }
             ty::MutBorrow => {
-                self.adjust_upvar_borrow_kind_for_mut(cmt);
+                self.adjust_upvar_borrow_kind_for_mut(place);
             }
         }
     }
 
-    fn mutate(&mut self, assignee_cmt: &mc::cmt_<'tcx>) {
-        debug!("mutate(assignee_cmt={:?})", assignee_cmt);
+    fn mutate(&mut self, assignee_place: &mc::Place<'tcx>) {
+        debug!("mutate(assignee_place={:?})", assignee_place);
 
-        self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);
+        self.adjust_upvar_borrow_kind_for_mut(assignee_place);
     }
 }
 
diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs
index b491b103313..20b6b01de57 100644
--- a/src/librustc_typeck/check/wfcheck.rs
+++ b/src/librustc_typeck/check/wfcheck.rs
@@ -10,7 +10,7 @@ use rustc::middle::lang_items;
 use rustc::infer::opaque_types::may_define_opaque_type;
 
 use syntax::ast;
-use syntax::feature_gate::{self, GateIssue};
+use syntax::feature_gate;
 use syntax_pos::Span;
 use syntax::symbol::sym;
 use errors::DiagnosticBuilder;
@@ -830,13 +830,13 @@ fn check_method_receiver<'fcx, 'tcx>(
                     &fcx.tcx.sess.parse_sess,
                     sym::arbitrary_self_types,
                     span,
-                    GateIssue::Language,
                     &format!(
                         "`{}` cannot be used as the type of `self` without \
                             the `arbitrary_self_types` feature",
                         receiver_ty,
                     ),
-                ).help(HELP_FOR_SELF_TYPE)
+                )
+                .help(HELP_FOR_SELF_TYPE)
                 .emit();
             } else {
                 // Report error; would not have worked with `arbitrary_self_types`.
diff --git a/src/librustc_typeck/coherence/unsafety.rs b/src/librustc_typeck/coherence/unsafety.rs
index 5bb44499968..650e15ea8a7 100644
--- a/src/librustc_typeck/coherence/unsafety.rs
+++ b/src/librustc_typeck/coherence/unsafety.rs
@@ -35,7 +35,7 @@ impl UnsafetyChecker<'tcx> {
                               item.span,
                               E0199,
                               "implementing the trait `{}` is not unsafe",
-                              trait_ref);
+                              trait_ref.print_only_trait_path());
                 }
 
                 (Unsafety::Unsafe, _, Unsafety::Normal, hir::ImplPolarity::Positive) => {
@@ -43,7 +43,7 @@ impl UnsafetyChecker<'tcx> {
                               item.span,
                               E0200,
                               "the trait `{}` requires an `unsafe impl` declaration",
-                              trait_ref);
+                              trait_ref.print_only_trait_path());
                 }
 
                 (Unsafety::Normal, Some(attr_name), Unsafety::Normal,
diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs
index 652f081e176..6d6e7685fa0 100644
--- a/src/librustc_typeck/collect.rs
+++ b/src/librustc_typeck/collect.rs
@@ -909,14 +909,12 @@ fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
             let parent_id = tcx.hir().get_parent_item(hir_id);
             Some(tcx.hir().local_def_id(parent_id))
         }
-        // FIXME(#43408) enable this in all cases when we get lazy normalization.
-        Node::AnonConst(&anon_const) => {
-            // HACK(eddyb) this provides the correct generics when the workaround
-            // for a const parameter `AnonConst` is being used elsewhere, as then
-            // there won't be the kind of cyclic dependency blocking #43408.
-            let expr = &tcx.hir().body(anon_const.body).value;
-            let icx = ItemCtxt::new(tcx, def_id);
-            if AstConv::const_param_def_id(&icx, expr).is_some() {
+        // FIXME(#43408) enable this always when we get lazy normalization.
+        Node::AnonConst(_) => {
+            // HACK(eddyb) this provides the correct generics when
+            // `feature(const_generics)` is enabled, so that const expressions
+            // used with const generics, e.g. `Foo<{N+1}>`, can work at all.
+            if tcx.features().const_generics {
                 let parent_id = tcx.hir().get_parent_item(hir_id);
                 Some(tcx.hir().local_def_id(parent_id))
             } else {
@@ -1494,16 +1492,16 @@ fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
                         _ => None,
                     };
                     if let Some(unsupported_type) = err {
-                        feature_gate::emit_feature_err(
+                        feature_gate::feature_err(
                             &tcx.sess.parse_sess,
                             sym::const_compare_raw_pointers,
                             hir_ty.span,
-                            feature_gate::GateIssue::Language,
                             &format!(
                                 "using {} as const generic parameters is unstable",
                                 unsupported_type
                             ),
-                        );
+                        )
+                        .emit();
                     };
                 }
                 if ty::search_for_structural_match_violation(
@@ -2522,13 +2520,13 @@ fn from_target_feature(
                 None => true,
             };
             if !allowed && id.is_local() {
-                feature_gate::emit_feature_err(
+                feature_gate::feature_err(
                     &tcx.sess.parse_sess,
                     feature_gate.unwrap(),
                     item.span(),
-                    feature_gate::GateIssue::Language,
                     &format!("the target feature `{}` is currently unstable", feature),
-                );
+                )
+                .emit();
             }
             Some(Symbol::intern(feature))
         }));
diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc_typeck/expr_use_visitor.rs
index 00bddf50c29..03d7ab2d633 100644
--- a/src/librustc/middle/expr_use_visitor.rs
+++ b/src/librustc_typeck/expr_use_visitor.rs
@@ -5,16 +5,17 @@
 pub use self::ConsumeMode::*;
 use self::OverloadedCallType::*;
 
-use crate::hir::def::Res;
-use crate::hir::def_id::DefId;
-use crate::hir::ptr::P;
-use crate::infer::InferCtxt;
-use crate::middle::mem_categorization as mc;
-use crate::middle::region;
-use crate::ty::{self, TyCtxt, adjustment};
-
-use crate::hir::{self, PatKind};
-use std::rc::Rc;
+// Export these here so that Clippy can use them.
+pub use mc::{PlaceBase, Place, Projection};
+
+use rustc::hir::{self, PatKind};
+use rustc::hir::def::Res;
+use rustc::hir::def_id::DefId;
+use rustc::hir::ptr::P;
+use rustc::infer::InferCtxt;
+use rustc::ty::{self, TyCtxt, adjustment};
+
+use crate::mem_categorization as mc;
 use syntax_pos::Span;
 
 ///////////////////////////////////////////////////////////////////////////
@@ -23,15 +24,15 @@ use syntax_pos::Span;
 /// This trait defines the callbacks you can expect to receive when
 /// employing the ExprUseVisitor.
 pub trait Delegate<'tcx> {
-    // The value found at `cmt` is either copied or moved, depending
+    // The value found at `place` is either copied or moved, depending
     // on mode.
-    fn consume(&mut self, cmt: &mc::cmt_<'tcx>, mode: ConsumeMode);
+    fn consume(&mut self, place: &mc::Place<'tcx>, mode: ConsumeMode);
 
-    // The value found at `cmt` is being borrowed with kind `bk`.
-    fn borrow(&mut self, cmt: &mc::cmt_<'tcx>, bk: ty::BorrowKind);
+    // The value found at `place` is being borrowed with kind `bk`.
+    fn borrow(&mut self, place: &mc::Place<'tcx>, bk: ty::BorrowKind);
 
-    // The path at `cmt` is being assigned to.
-    fn mutate(&mut self, assignee_cmt: &mc::cmt_<'tcx>);
+    // The path at `place` is being assigned to.
+    fn mutate(&mut self, assignee_place: &mc::Place<'tcx>);
 }
 
 #[derive(Copy, Clone, PartialEq, Debug)]
@@ -85,7 +86,6 @@ impl OverloadedCallType {
 pub struct ExprUseVisitor<'a, 'tcx> {
     mc: mc::MemCategorizationContext<'a, 'tcx>,
     delegate: &'a mut dyn Delegate<'tcx>,
-    param_env: ty::ParamEnv<'tcx>,
 }
 
 // If the MC results in an error, it's because the type check
@@ -112,49 +112,22 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
     ///
     /// - `delegate` -- who receives the callbacks
     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
-    /// - `region_scope_tree` --- region scope tree for the code being analyzed
     /// - `tables` --- typeck results for the code being analyzed
-    ///
-    /// See also `with_infer`, which is used *during* typeck.
     pub fn new(
         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
-        tcx: TyCtxt<'tcx>,
-        body_owner: DefId,
-        param_env: ty::ParamEnv<'tcx>,
-        region_scope_tree: &'a region::ScopeTree,
-        tables: &'a ty::TypeckTables<'tcx>,
-    ) -> Self {
-        ExprUseVisitor {
-            mc: mc::MemCategorizationContext::new(tcx,
-                                                  param_env,
-                                                  body_owner,
-                                                  region_scope_tree,
-                                                  tables),
-            delegate,
-            param_env,
-        }
-    }
-}
-
-impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
-    pub fn with_infer(
-        delegate: &'a mut (dyn Delegate<'tcx> + 'a),
         infcx: &'a InferCtxt<'a, 'tcx>,
         body_owner: DefId,
         param_env: ty::ParamEnv<'tcx>,
-        region_scope_tree: &'a region::ScopeTree,
         tables: &'a ty::TypeckTables<'tcx>,
     ) -> Self {
         ExprUseVisitor {
-            mc: mc::MemCategorizationContext::with_infer(
+            mc: mc::MemCategorizationContext::new(
                 infcx,
                 param_env,
                 body_owner,
-                region_scope_tree,
                 tables,
             ),
             delegate,
-            param_env,
         }
     }
 
@@ -165,26 +138,23 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
             debug!("consume_body: param_ty = {:?}", param_ty);
 
-            let param_cmt = Rc::new(self.mc.cat_rvalue(
-                param.hir_id,
-                param.pat.span,
-                param_ty));
+            let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
 
-            self.walk_irrefutable_pat(param_cmt, &param.pat);
+            self.walk_irrefutable_pat(&param_place, &param.pat);
         }
 
         self.consume_expr(&body.value);
     }
 
     fn tcx(&self) -> TyCtxt<'tcx> {
-        self.mc.tcx
+        self.mc.tcx()
     }
 
-    fn delegate_consume(&mut self, cmt: &mc::cmt_<'tcx>) {
-        debug!("delegate_consume(cmt={:?})", cmt);
+    fn delegate_consume(&mut self, place: &Place<'tcx>) {
+        debug!("delegate_consume(place={:?})", place);
 
-        let mode = copy_or_move(&self.mc, self.param_env, cmt);
-        self.delegate.consume(cmt, mode);
+        let mode = copy_or_move(&self.mc, place);
+        self.delegate.consume(place, mode);
     }
 
     fn consume_exprs(&mut self, exprs: &[hir::Expr]) {
@@ -196,22 +166,22 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
     pub fn consume_expr(&mut self, expr: &hir::Expr) {
         debug!("consume_expr(expr={:?})", expr);
 
-        let cmt = return_if_err!(self.mc.cat_expr(expr));
-        self.delegate_consume(&cmt);
+        let place = return_if_err!(self.mc.cat_expr(expr));
+        self.delegate_consume(&place);
         self.walk_expr(expr);
     }
 
     fn mutate_expr(&mut self, expr: &hir::Expr) {
-        let cmt = return_if_err!(self.mc.cat_expr(expr));
-        self.delegate.mutate(&cmt);
+        let place = return_if_err!(self.mc.cat_expr(expr));
+        self.delegate.mutate(&place);
         self.walk_expr(expr);
     }
 
     fn borrow_expr(&mut self, expr: &hir::Expr, bk: ty::BorrowKind) {
         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
 
-        let cmt = return_if_err!(self.mc.cat_expr(expr));
-        self.delegate.borrow(&cmt, bk);
+        let place = return_if_err!(self.mc.cat_expr(expr));
+        self.delegate.borrow(&place, bk);
 
         self.walk_expr(expr)
     }
@@ -263,12 +233,12 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
             }
 
             hir::ExprKind::Match(ref discr, ref arms, _) => {
-                let discr_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&discr)));
+                let discr_place = return_if_err!(self.mc.cat_expr(&discr));
                 self.borrow_expr(&discr, ty::ImmBorrow);
 
                 // treatment of the discriminant is handled while walking the arms.
                 for arm in arms {
-                    self.walk_arm(discr_cmt.clone(), arm);
+                    self.walk_arm(&discr_place, arm);
                 }
             }
 
@@ -414,8 +384,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
             // "assigns", which is handled by
             // `walk_pat`:
             self.walk_expr(&expr);
-            let init_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&expr)));
-            self.walk_irrefutable_pat(init_cmt, &local.pat);
+            let init_place = return_if_err!(self.mc.cat_expr(&expr));
+            self.walk_irrefutable_pat(&init_place, &local.pat);
         }
     }
 
@@ -446,11 +416,11 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
             None => { return; }
         };
 
-        let with_cmt = Rc::new(return_if_err!(self.mc.cat_expr(&with_expr)));
+        let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
 
         // Select just those fields of the `with`
         // expression that will actually be used
-        match with_cmt.ty.kind {
+        match with_place.ty.kind {
             ty::Adt(adt, substs) if adt.is_struct() => {
                 // Consume those fields of the with expression that are needed.
                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
@@ -458,14 +428,12 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                         self.tcx().field_index(f.hir_id, self.mc.tables) == f_index
                     });
                     if !is_mentioned {
-                        let cmt_field = self.mc.cat_field(
+                        let field_place = self.mc.cat_projection(
                             &*with_expr,
-                            with_cmt.clone(),
-                            f_index,
-                            with_field.ident,
-                            with_field.ty(self.tcx(), substs)
+                            with_place.clone(),
+                            with_field.ty(self.tcx(), substs),
                         );
-                        self.delegate_consume(&cmt_field);
+                        self.delegate_consume(&field_place);
                     }
                 }
             }
@@ -492,7 +460,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
     // process.
     fn walk_adjustment(&mut self, expr: &hir::Expr) {
         let adjustments = self.mc.tables.expr_adjustments(expr);
-        let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr));
+        let mut place = return_if_err!(self.mc.cat_expr_unadjusted(expr));
         for adjustment in adjustments {
             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
             match adjustment.kind {
@@ -500,7 +468,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                 adjustment::Adjust::Pointer(_)  => {
                     // Creating a closure/fn-pointer or unsizing consumes
                     // the input and stores it into the resulting rvalue.
-                    self.delegate_consume(&cmt);
+                    self.delegate_consume(&place);
                 }
 
                 adjustment::Adjust::Deref(None) => {}
@@ -512,47 +480,47 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                 // this is an autoref of `x`.
                 adjustment::Adjust::Deref(Some(ref deref)) => {
                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
-                    self.delegate.borrow(&cmt, bk);
+                    self.delegate.borrow(&place, bk);
                 }
 
                 adjustment::Adjust::Borrow(ref autoref) => {
-                    self.walk_autoref(expr, &cmt, autoref);
+                    self.walk_autoref(expr, &place, autoref);
                 }
             }
-            cmt = return_if_err!(self.mc.cat_expr_adjusted(expr, cmt, &adjustment));
+            place = return_if_err!(self.mc.cat_expr_adjusted(expr, place, &adjustment));
         }
     }
 
     /// Walks the autoref `autoref` applied to the autoderef'd
-    /// `expr`. `cmt_base` is the mem-categorized form of `expr`
+    /// `expr`. `base_place` is the mem-categorized form of `expr`
     /// after all relevant autoderefs have occurred.
     fn walk_autoref(&mut self,
                     expr: &hir::Expr,
-                    cmt_base: &mc::cmt_<'tcx>,
+                    base_place: &mc::Place<'tcx>,
                     autoref: &adjustment::AutoBorrow<'tcx>) {
-        debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})",
+        debug!("walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
                expr.hir_id,
-               cmt_base,
+               base_place,
                autoref);
 
         match *autoref {
             adjustment::AutoBorrow::Ref(_, m) => {
-                self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m.into()));
+                self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
             }
 
             adjustment::AutoBorrow::RawPtr(m) => {
-                debug!("walk_autoref: expr.hir_id={} cmt_base={:?}",
+                debug!("walk_autoref: expr.hir_id={} base_place={:?}",
                        expr.hir_id,
-                       cmt_base);
+                       base_place);
 
 
-                self.delegate.borrow(cmt_base, ty::BorrowKind::from_mutbl(m));
+                self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
             }
         }
     }
 
-    fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) {
-        self.walk_pat(discr_cmt.clone(), &arm.pat);
+    fn walk_arm(&mut self, discr_place: &Place<'tcx>, arm: &hir::Arm) {
+        self.walk_pat(discr_place, &arm.pat);
 
         if let Some(hir::Guard::If(ref e)) = arm.guard {
             self.consume_expr(e)
@@ -563,22 +531,22 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
 
     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
     /// let binding, and *not* a match arm or nested pat.)
-    fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
-        self.walk_pat(cmt_discr, pat);
+    fn walk_irrefutable_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat) {
+        self.walk_pat(discr_place, pat);
     }
 
 
     /// The core driver for walking a pattern
-    fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) {
-        debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat);
+    fn walk_pat(&mut self, discr_place: &Place<'tcx>, pat: &hir::Pat) {
+        debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
 
         let tcx = self.tcx();
-        let ExprUseVisitor { ref mc, ref mut delegate, param_env } = *self;
-        return_if_err!(mc.cat_pattern(cmt_discr.clone(), pat, |cmt_pat, pat| {
+        let ExprUseVisitor { ref mc, ref mut delegate } = *self;
+        return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
                 debug!(
-                    "walk_pat: binding cmt_pat={:?} pat={:?}",
-                    cmt_pat,
+                    "walk_pat: binding place={:?} pat={:?}",
+                    place,
                     pat,
                 );
                 if let Some(&bm) = mc.tables.pat_binding_modes().get(pat.hir_id) {
@@ -591,20 +559,20 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                     // Each match binding is effectively an assignment to the
                     // binding being produced.
                     let def = Res::Local(canonical_id);
-                    if let Ok(ref binding_cmt) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
-                        delegate.mutate(binding_cmt);
+                    if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
+                        delegate.mutate(binding_place);
                     }
 
                     // It is also a borrow or copy/move of the value being matched.
                     match bm {
                         ty::BindByReference(m) => {
                             let bk = ty::BorrowKind::from_mutbl(m);
-                            delegate.borrow(&cmt_pat, bk);
+                            delegate.borrow(place, bk);
                         }
                         ty::BindByValue(..) => {
-                            let mode = copy_or_move(mc, param_env, &cmt_pat);
+                            let mode = copy_or_move(mc, place);
                             debug!("walk_pat binding consuming pat");
-                            delegate.consume(&cmt_pat, mode);
+                            delegate.consume(place, mode);
                         }
                     }
                 } else {
@@ -625,16 +593,18 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                     closure_expr_id: closure_def_id.to_local(),
                 };
                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
-                let cmt_var = return_if_err!(self.cat_captured_var(closure_expr.hir_id,
-                                                                   fn_decl_span,
-                                                                   var_id));
+                let captured_place = return_if_err!(self.cat_captured_var(
+                    closure_expr.hir_id,
+                    fn_decl_span,
+                    var_id,
+                ));
                 match upvar_capture {
                     ty::UpvarCapture::ByValue => {
-                        let mode = copy_or_move(&self.mc, self.param_env, &cmt_var);
-                        self.delegate.consume(&cmt_var, mode);
+                        let mode = copy_or_move(&self.mc, &captured_place);
+                        self.delegate.consume(&captured_place, mode);
                     }
                     ty::UpvarCapture::ByRef(upvar_borrow) => {
-                        self.delegate.borrow(&cmt_var, upvar_borrow.kind);
+                        self.delegate.borrow(&captured_place, upvar_borrow.kind);
                     }
                 }
             }
@@ -645,8 +615,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
                         closure_hir_id: hir::HirId,
                         closure_span: Span,
                         var_id: hir::HirId)
-                        -> mc::McResult<mc::cmt_<'tcx>> {
-        // Create the cmt for the variable being borrowed, from the
+                        -> mc::McResult<mc::Place<'tcx>> {
+        // Create the place for the variable being borrowed, from the
         // perspective of the creator (parent) of the closure.
         let var_ty = self.mc.node_ty(var_id)?;
         self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
@@ -655,10 +625,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
 
 fn copy_or_move<'a, 'tcx>(
     mc: &mc::MemCategorizationContext<'a, 'tcx>,
-    param_env: ty::ParamEnv<'tcx>,
-    cmt: &mc::cmt_<'tcx>,
+    place: &Place<'tcx>,
 ) -> ConsumeMode {
-    if !mc.type_is_copy_modulo_regions(param_env, cmt.ty, cmt.span) {
+    if !mc.type_is_copy_modulo_regions(place.ty, place.span) {
         Move
     } else {
         Copy
diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs
index 0f147f92b5f..c606feab087 100644
--- a/src/librustc_typeck/lib.rs
+++ b/src/librustc_typeck/lib.rs
@@ -75,6 +75,9 @@ This API is completely unstable and subject to change.
 
 #[macro_use] extern crate rustc;
 
+// This is used by Clippy.
+pub mod expr_use_visitor;
+
 mod astconv;
 mod check;
 mod check_unused;
@@ -83,6 +86,7 @@ mod collect;
 mod constrained_generic_params;
 mod structured_errors;
 mod impl_wf_check;
+mod mem_categorization;
 mod namespace;
 mod outlives;
 mod variance;
diff --git a/src/librustc_typeck/mem_categorization.rs b/src/librustc_typeck/mem_categorization.rs
new file mode 100644
index 00000000000..84e5d234da9
--- /dev/null
+++ b/src/librustc_typeck/mem_categorization.rs
@@ -0,0 +1,707 @@
+//! # Categorization
+//!
+//! The job of the categorization module is to analyze an expression to
+//! determine what kind of memory is used in evaluating it (for example,
+//! where dereferences occur and what kind of pointer is dereferenced;
+//! whether the memory is mutable, etc.).
+//!
+//! Categorization effectively transforms all of our expressions into
+//! expressions of the following forms (the actual enum has many more
+//! possibilities, naturally, but they are all variants of these base
+//! forms):
+//!
+//!     E = rvalue    // some computed rvalue
+//!       | x         // address of a local variable or argument
+//!       | *E        // deref of a ptr
+//!       | E.comp    // access to an interior component
+//!
+//! Imagine a routine ToAddr(Expr) that evaluates an expression and returns an
+//! address where the result is to be found. If Expr is a place, then this
+//! is the address of the place. If `Expr` is an rvalue, this is the address of
+//! some temporary spot in memory where the result is stored.
+//!
+//! Now, `cat_expr()` classifies the expression `Expr` and the address `A = ToAddr(Expr)`
+//! as follows:
+//!
+//! - `cat`: what kind of expression was this? This is a subset of the
+//!   full expression forms which only includes those that we care about
+//!   for the purpose of the analysis.
+//! - `mutbl`: mutability of the address `A`.
+//! - `ty`: the type of data found at the address `A`.
+//!
+//! The resulting categorization tree differs somewhat from the expressions
+//! themselves. For example, auto-derefs are explicit. Also, an index a[b] is
+//! decomposed into two operations: a dereference to reach the array data and
+//! then an index to jump forward to the relevant item.
+//!
+//! ## By-reference upvars
+//!
+//! One part of the codegen which may be non-obvious is that we translate
+//! closure upvars into the dereference of a borrowed pointer; this more closely
+//! resembles the runtime codegen. So, for example, if we had:
+//!
+//!     let mut x = 3;
+//!     let y = 5;
+//!     let inc = || x += y;
+//!
+//! Then when we categorize `x` (*within* the closure) we would yield a
+//! result of `*x'`, effectively, where `x'` is a `Categorization::Upvar` reference
+//! tied to `x`. The type of `x'` will be a borrowed pointer.
+
+use rustc::hir;
+use rustc::hir::PatKind;
+use rustc::hir::def_id::DefId;
+use rustc::hir::def::{Res, DefKind};
+use rustc::infer::InferCtxt;
+use rustc::ty::adjustment;
+use rustc::ty::{self, Ty, TyCtxt};
+use rustc::ty::fold::TypeFoldable;
+
+use syntax_pos::Span;
+
+use rustc_data_structures::fx::FxIndexMap;
+
+#[derive(Clone, Debug)]
+pub enum PlaceBase {
+    /// A temporary variable
+    Rvalue,
+    /// A named `static` item
+    StaticItem,
+    /// A named local variable
+    Local(hir::HirId),
+    /// An upvar referenced by closure env
+    Upvar(ty::UpvarId),
+}
+
+#[derive(Clone, Debug)]
+pub enum Projection<'tcx> {
+    /// A dereference of a pointer, reference or `Box<T>` of the given type
+    Deref(Ty<'tcx>),
+    /// An index or a field
+    Other,
+}
+
+/// A `Place` represents how a value is located in memory.
+///
+/// This is an HIR version of `mir::Place`
+#[derive(Clone, Debug)]
+pub struct Place<'tcx> {
+    /// `HirId` of the expression or pattern producing this value.
+    pub hir_id: hir::HirId,
+    /// The `Span` of the expression or pattern producing this value.
+    pub span: Span,
+    /// The type of the `Place`
+    pub ty: Ty<'tcx>,
+    /// The "outermost" place that holds this value.
+    pub base: PlaceBase,
+    /// How this place is derived from the base place.
+    pub projections: Vec<Projection<'tcx>>,
+}
+
+impl<'tcx> Place<'tcx> {
+    /// Returns an iterator of the types that have to be dereferenced to access
+    /// the `Place`.
+    ///
+    /// The types are in the reverse order that they are applied. So if
+    /// `x: &*const u32` and the `Place` is `**x`, then the types returned are
+    ///`*const u32` then `&*const u32`.
+    crate fn deref_tys(&self) -> impl Iterator<Item=Ty<'tcx>> + '_ {
+        self.projections.iter().rev().filter_map(|proj| if let Projection::Deref(deref_ty) = *proj {
+            Some(deref_ty)
+        } else {
+            None
+        })
+    }
+}
+
+crate trait HirNode {
+    fn hir_id(&self) -> hir::HirId;
+    fn span(&self) -> Span;
+}
+
+impl HirNode for hir::Expr {
+    fn hir_id(&self) -> hir::HirId { self.hir_id }
+    fn span(&self) -> Span { self.span }
+}
+
+impl HirNode for hir::Pat {
+    fn hir_id(&self) -> hir::HirId { self.hir_id }
+    fn span(&self) -> Span { self.span }
+}
+
+#[derive(Clone)]
+crate struct MemCategorizationContext<'a, 'tcx> {
+    crate tables: &'a ty::TypeckTables<'tcx>,
+    infcx: &'a InferCtxt<'a, 'tcx>,
+    param_env: ty::ParamEnv<'tcx>,
+    body_owner: DefId,
+    upvars: Option<&'tcx FxIndexMap<hir::HirId, hir::Upvar>>,
+}
+
+crate type McResult<T> = Result<T, ()>;
+
+impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
+    /// Creates a `MemCategorizationContext`.
+    crate fn new(
+        infcx: &'a InferCtxt<'a, 'tcx>,
+        param_env: ty::ParamEnv<'tcx>,
+        body_owner: DefId,
+        tables: &'a ty::TypeckTables<'tcx>,
+    ) -> MemCategorizationContext<'a, 'tcx> {
+        MemCategorizationContext {
+            tables,
+            infcx,
+            param_env,
+            body_owner,
+            upvars: infcx.tcx.upvars(body_owner),
+        }
+    }
+
+    crate fn tcx(&self) -> TyCtxt<'tcx> {
+        self.infcx.tcx
+    }
+
+    crate fn type_is_copy_modulo_regions(
+        &self,
+        ty: Ty<'tcx>,
+        span: Span,
+    ) -> bool {
+        self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span)
+    }
+
+    fn resolve_vars_if_possible<T>(&self, value: &T) -> T
+        where T: TypeFoldable<'tcx>
+    {
+        self.infcx.resolve_vars_if_possible(value)
+    }
+
+    fn is_tainted_by_errors(&self) -> bool {
+        self.infcx.is_tainted_by_errors()
+    }
+
+    fn resolve_type_vars_or_error(&self,
+                                  id: hir::HirId,
+                                  ty: Option<Ty<'tcx>>)
+                                  -> McResult<Ty<'tcx>> {
+        match ty {
+            Some(ty) => {
+                let ty = self.resolve_vars_if_possible(&ty);
+                if ty.references_error() || ty.is_ty_var() {
+                    debug!("resolve_type_vars_or_error: error from {:?}", ty);
+                    Err(())
+                } else {
+                    Ok(ty)
+                }
+            }
+            // FIXME
+            None if self.is_tainted_by_errors() => Err(()),
+            None => {
+                bug!("no type for node {}: {} in mem_categorization",
+                     id, self.tcx().hir().node_to_string(id));
+            }
+        }
+    }
+
+    crate fn node_ty(&self, hir_id: hir::HirId) -> McResult<Ty<'tcx>> {
+        self.resolve_type_vars_or_error(hir_id, self.tables.node_type_opt(hir_id))
+    }
+
+    fn expr_ty(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
+        self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr))
+    }
+
+    crate fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
+        self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr))
+    }
+
+    /// Returns the type of value that this pattern matches against.
+    /// Some non-obvious cases:
+    ///
+    /// - a `ref x` binding matches against a value of type `T` and gives
+    ///   `x` the type `&T`; we return `T`.
+    /// - a pattern with implicit derefs (thanks to default binding
+    ///   modes #42640) may look like `Some(x)` but in fact have
+    ///   implicit deref patterns attached (e.g., it is really
+    ///   `&Some(x)`). In that case, we return the "outermost" type
+    ///   (e.g., `&Option<T>).
+    crate fn pat_ty_adjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
+        // Check for implicit `&` types wrapping the pattern; note
+        // that these are never attached to binding patterns, so
+        // actually this is somewhat "disjoint" from the code below
+        // that aims to account for `ref x`.
+        if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) {
+            if let Some(first_ty) = vec.first() {
+                debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty);
+                return Ok(first_ty);
+            }
+        }
+
+        self.pat_ty_unadjusted(pat)
+    }
+
+
+    /// Like `pat_ty`, but ignores implicit `&` patterns.
+    fn pat_ty_unadjusted(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
+        let base_ty = self.node_ty(pat.hir_id)?;
+        debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty);
+
+        // This code detects whether we are looking at a `ref x`,
+        // and if so, figures out what the type *being borrowed* is.
+        let ret_ty = match pat.kind {
+            PatKind::Binding(..) => {
+                let bm = *self.tables
+                              .pat_binding_modes()
+                              .get(pat.hir_id)
+                              .expect("missing binding mode");
+
+                if let ty::BindByReference(_) = bm {
+                    // a bind-by-ref means that the base_ty will be the type of the ident itself,
+                    // but what we want here is the type of the underlying value being borrowed.
+                    // So peel off one-level, turning the &T into T.
+                    match base_ty.builtin_deref(false) {
+                        Some(t) => t.ty,
+                        None => {
+                            debug!("By-ref binding of non-derefable type {:?}", base_ty);
+                            return Err(());
+                        }
+                    }
+                } else {
+                    base_ty
+                }
+            }
+            _ => base_ty,
+        };
+        debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty);
+
+        Ok(ret_ty)
+    }
+
+    crate fn cat_expr(&self, expr: &hir::Expr) -> McResult<Place<'tcx>> {
+        // This recursion helper avoids going through *too many*
+        // adjustments, since *only* non-overloaded deref recurses.
+        fn helper<'a, 'tcx>(
+            mc: &MemCategorizationContext<'a, 'tcx>,
+            expr: &hir::Expr,
+            adjustments: &[adjustment::Adjustment<'tcx>],
+        ) -> McResult<Place<'tcx>> {
+            match adjustments.split_last() {
+                None => mc.cat_expr_unadjusted(expr),
+                Some((adjustment, previous)) => {
+                    mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment)
+                }
+            }
+        }
+
+        helper(self, expr, self.tables.expr_adjustments(expr))
+    }
+
+    crate fn cat_expr_adjusted(&self, expr: &hir::Expr,
+                             previous: Place<'tcx>,
+                             adjustment: &adjustment::Adjustment<'tcx>)
+                             -> McResult<Place<'tcx>> {
+        self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment)
+    }
+
+    fn cat_expr_adjusted_with<F>(&self, expr: &hir::Expr,
+                                 previous: F,
+                                 adjustment: &adjustment::Adjustment<'tcx>)
+                                 -> McResult<Place<'tcx>>
+        where F: FnOnce() -> McResult<Place<'tcx>>
+    {
+        debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr);
+        let target = self.resolve_vars_if_possible(&adjustment.target);
+        match adjustment.kind {
+            adjustment::Adjust::Deref(overloaded) => {
+                // Equivalent to *expr or something similar.
+                let base = if let Some(deref) = overloaded {
+                    let ref_ty = self.tcx().mk_ref(deref.region, ty::TypeAndMut {
+                        ty: target,
+                        mutbl: deref.mutbl,
+                    });
+                    self.cat_rvalue(expr.hir_id, expr.span, ref_ty)
+                } else {
+                    previous()?
+                };
+                self.cat_deref(expr, base)
+            }
+
+            adjustment::Adjust::NeverToAny |
+            adjustment::Adjust::Pointer(_) |
+            adjustment::Adjust::Borrow(_) => {
+                // Result is an rvalue.
+                Ok(self.cat_rvalue(expr.hir_id, expr.span, target))
+            }
+        }
+    }
+
+    crate fn cat_expr_unadjusted(&self, expr: &hir::Expr) -> McResult<Place<'tcx>> {
+        debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr);
+
+        let expr_ty = self.expr_ty(expr)?;
+        match expr.kind {
+            hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
+                if self.tables.is_method_call(expr) {
+                    self.cat_overloaded_place(expr, e_base)
+                } else {
+                    let base = self.cat_expr(&e_base)?;
+                    self.cat_deref(expr, base)
+                }
+            }
+
+            hir::ExprKind::Field(ref base, _) => {
+                let base = self.cat_expr(&base)?;
+                debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
+                       expr.hir_id,
+                       expr,
+                       base);
+                Ok(self.cat_projection(expr, base, expr_ty))
+            }
+
+            hir::ExprKind::Index(ref base, _) => {
+                if self.tables.is_method_call(expr) {
+                    // If this is an index implemented by a method call, then it
+                    // will include an implicit deref of the result.
+                    // The call to index() returns a `&T` value, which
+                    // is an rvalue. That is what we will be
+                    // dereferencing.
+                    self.cat_overloaded_place(expr, base)
+                } else {
+                    let base = self.cat_expr(&base)?;
+                    Ok(self.cat_projection(expr, base, expr_ty))
+                }
+            }
+
+            hir::ExprKind::Path(ref qpath) => {
+                let res = self.tables.qpath_res(qpath, expr.hir_id);
+                self.cat_res(expr.hir_id, expr.span, expr_ty, res)
+            }
+
+            hir::ExprKind::Type(ref e, _) => {
+                self.cat_expr(&e)
+            }
+
+            hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
+            hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
+            hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
+            hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
+            hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) | hir::ExprKind::DropTemps(..) |
+            hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) |
+            hir::ExprKind::Binary(..) |
+            hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
+            hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
+            hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
+            hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) | hir::ExprKind::Err => {
+                Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty))
+            }
+        }
+    }
+
+    crate fn cat_res(&self,
+                   hir_id: hir::HirId,
+                   span: Span,
+                   expr_ty: Ty<'tcx>,
+                   res: Res)
+                   -> McResult<Place<'tcx>> {
+        debug!("cat_res: id={:?} expr={:?} def={:?}",
+               hir_id, expr_ty, res);
+
+        match res {
+            Res::Def(DefKind::Ctor(..), _)
+            | Res::Def(DefKind::Const, _)
+            | Res::Def(DefKind::ConstParam, _)
+            | Res::Def(DefKind::AssocConst, _)
+            | Res::Def(DefKind::Fn, _)
+            | Res::Def(DefKind::Method, _)
+            | Res::SelfCtor(..) => {
+                Ok(self.cat_rvalue(hir_id, span, expr_ty))
+            }
+
+            Res::Def(DefKind::Static, _) => {
+                Ok(Place {
+                    hir_id,
+                    span,
+                    ty: expr_ty,
+                    base: PlaceBase::StaticItem,
+                    projections: Vec::new(),
+                })
+            }
+
+            Res::Local(var_id) => {
+                if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) {
+                    self.cat_upvar(hir_id, span, var_id)
+                } else {
+                    Ok(Place {
+                        hir_id,
+                        span,
+                        ty: expr_ty,
+                        base: PlaceBase::Local(var_id),
+                        projections: Vec::new(),
+                    })
+                }
+            }
+
+            def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
+        }
+    }
+
+    /// Categorize an upvar.
+    ///
+    /// Note: the actual upvar access contains invisible derefs of closure
+    /// environment and upvar reference as appropriate. Only regionck cares
+    /// about these dereferences, so we let it compute them as needed.
+    fn cat_upvar(
+        &self,
+        hir_id: hir::HirId,
+        span: Span,
+        var_id: hir::HirId,
+    ) -> McResult<Place<'tcx>> {
+        let closure_expr_def_id = self.body_owner;
+
+        let upvar_id = ty::UpvarId {
+            var_path: ty::UpvarPath { hir_id: var_id },
+            closure_expr_id: closure_expr_def_id.to_local(),
+        };
+        let var_ty = self.node_ty(var_id)?;
+
+        let ret = Place {
+            hir_id,
+            span,
+            ty: var_ty,
+            base: PlaceBase::Upvar(upvar_id),
+            projections: Vec::new(),
+        };
+
+        debug!("cat_upvar ret={:?}", ret);
+        Ok(ret)
+    }
+
+    crate fn cat_rvalue(&self, hir_id: hir::HirId, span: Span, expr_ty: Ty<'tcx>) -> Place<'tcx> {
+        debug!("cat_rvalue hir_id={:?}, expr_ty={:?}, span={:?}", hir_id, expr_ty, span);
+        let ret = Place {
+            hir_id,
+            span,
+            base: PlaceBase::Rvalue,
+            projections: Vec::new(),
+            ty: expr_ty,
+        };
+        debug!("cat_rvalue ret={:?}", ret);
+        ret
+    }
+
+    crate fn cat_projection<N: HirNode>(
+        &self,
+        node: &N,
+        base_place: Place<'tcx>,
+        ty: Ty<'tcx>,
+    ) -> Place<'tcx> {
+        let mut projections = base_place.projections;
+        projections.push(Projection::Other);
+        let ret = Place {
+            hir_id: node.hir_id(),
+            span: node.span(),
+            ty,
+            base: base_place.base,
+            projections,
+        };
+        debug!("cat_field ret {:?}", ret);
+        ret
+    }
+
+    fn cat_overloaded_place(
+        &self,
+        expr: &hir::Expr,
+        base: &hir::Expr,
+    ) -> McResult<Place<'tcx>> {
+        debug!("cat_overloaded_place(expr={:?}, base={:?})", expr, base);
+
+        // Reconstruct the output assuming it's a reference with the
+        // same region and mutability as the receiver. This holds for
+        // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
+        let place_ty = self.expr_ty(expr)?;
+        let base_ty = self.expr_ty_adjusted(base)?;
+
+        let (region, mutbl) = match base_ty.kind {
+            ty::Ref(region, _, mutbl) => (region, mutbl),
+            _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
+        };
+        let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut {
+            ty: place_ty,
+            mutbl,
+        });
+
+        let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty);
+        self.cat_deref(expr, base)
+    }
+
+    fn cat_deref(
+        &self,
+        node: &impl HirNode,
+        base_place: Place<'tcx>,
+    ) -> McResult<Place<'tcx>> {
+        debug!("cat_deref: base_place={:?}", base_place);
+
+        let base_ty = base_place.ty;
+        let deref_ty = match base_ty.builtin_deref(true) {
+            Some(mt) => mt.ty,
+            None => {
+                debug!("explicit deref of non-derefable type: {:?}", base_ty);
+                return Err(());
+            }
+        };
+        let mut projections = base_place.projections;
+        projections.push(Projection::Deref(base_ty));
+
+        let ret = Place {
+            hir_id: node.hir_id(),
+            span: node.span(),
+            ty: deref_ty,
+            base: base_place.base,
+            projections,
+        };
+        debug!("cat_deref ret {:?}", ret);
+        Ok(ret)
+    }
+
+    crate fn cat_pattern<F>(&self, place: Place<'tcx>, pat: &hir::Pat, mut op: F) -> McResult<()>
+        where F: FnMut(&Place<'tcx>, &hir::Pat),
+    {
+        self.cat_pattern_(place, pat, &mut op)
+    }
+
+    // FIXME(#19596) This is a workaround, but there should be a better way to do this
+    fn cat_pattern_<F>(&self, mut place: Place<'tcx>, pat: &hir::Pat, op: &mut F) -> McResult<()>
+        where F: FnMut(&Place<'tcx>, &hir::Pat)
+    {
+        // Here, `place` is the `Place` being matched and pat is the pattern it
+        // is being matched against.
+        //
+        // In general, the way that this works is that we walk down the pattern,
+        // constructing a `Place` that represents the path that will be taken
+        // to reach the value being matched.
+
+        debug!("cat_pattern(pat={:?}, place={:?})", pat, place);
+
+        // If (pattern) adjustments are active for this pattern, adjust the `Place` correspondingly.
+        // `Place`s are constructed differently from patterns. For example, in
+        //
+        // ```
+        // match foo {
+        //     &&Some(x, ) => { ... },
+        //     _ => { ... },
+        // }
+        // ```
+        //
+        // the pattern `&&Some(x,)` is represented as `Ref { Ref { TupleStruct }}`. To build the
+        // corresponding `Place` we start with the `Place` for `foo`, and then, by traversing the
+        // pattern, try to answer the question: given the address of `foo`, how is `x` reached?
+        //
+        // `&&Some(x,)` `place_foo`
+        //  `&Some(x,)` `deref { place_foo}`
+        //   `Some(x,)` `deref { deref { place_foo }}`
+        //        (x,)` `field0 { deref { deref { place_foo }}}` <- resulting place
+        //
+        // The above example has no adjustments. If the code were instead the (after adjustments,
+        // equivalent) version
+        //
+        // ```
+        // match foo {
+        //     Some(x, ) => { ... },
+        //     _ => { ... },
+        // }
+        // ```
+        //
+        // Then we see that to get the same result, we must start with
+        // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)`
+        // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`.
+        for _ in 0..self.tables
+                        .pat_adjustments()
+                        .get(pat.hir_id)
+                        .map(|v| v.len())
+                        .unwrap_or(0)
+        {
+            debug!("cat_pattern: applying adjustment to place={:?}", place);
+            place = self.cat_deref(pat, place)?;
+        }
+        let place = place; // lose mutability
+        debug!("cat_pattern: applied adjustment derefs to get place={:?}", place);
+
+        // Invoke the callback, but only now, after the `place` has adjusted.
+        //
+        // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that
+        // case, the initial `place` will be that for `&Some(3)` and the pattern is `Some(x)`. We
+        // don't want to call `op` with these incompatible values. As written, what happens instead
+        // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern
+        // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)`
+        // result in the place `Downcast<Some>(*&Some(3)).0` associated to `x` and invoke `op` with
+        // that (where the `ref` on `x` is implied).
+        op(&place, pat);
+
+        match pat.kind {
+            PatKind::TupleStruct(_, ref subpats, _)
+            | PatKind::Tuple(ref subpats, _) => {
+                // S(p1, ..., pN) or (p1, ..., pN)
+                for subpat in subpats.iter() {
+                    let subpat_ty = self.pat_ty_adjusted(&subpat)?;
+                    let sub_place = self.cat_projection(pat, place.clone(), subpat_ty);
+                    self.cat_pattern_(sub_place, &subpat, op)?;
+                }
+            }
+
+            PatKind::Struct(_, ref field_pats, _) => {
+                // S { f1: p1, ..., fN: pN }
+                for fp in field_pats {
+                    let field_ty = self.pat_ty_adjusted(&fp.pat)?;
+                    let field_place = self.cat_projection(pat, place.clone(), field_ty);
+                    self.cat_pattern_(field_place, &fp.pat, op)?;
+                }
+            }
+
+            PatKind::Or(ref pats) => {
+                for pat in pats {
+                    self.cat_pattern_(place.clone(), &pat, op)?;
+                }
+            }
+
+            PatKind::Binding(.., Some(ref subpat)) => {
+                self.cat_pattern_(place, &subpat, op)?;
+            }
+
+            PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
+                // box p1, &p1, &mut p1.  we can ignore the mutability of
+                // PatKind::Ref since that information is already contained
+                // in the type.
+                let subplace = self.cat_deref(pat, place)?;
+                self.cat_pattern_(subplace, &subpat, op)?;
+            }
+
+            PatKind::Slice(ref before, ref slice, ref after) => {
+                let element_ty = match place.ty.builtin_index() {
+                    Some(ty) => ty,
+                    None => {
+                        debug!("explicit index of non-indexable type {:?}", place);
+                        return Err(());
+                    }
+                };
+                let elt_place = self.cat_projection(pat, place.clone(), element_ty);
+                for before_pat in before {
+                    self.cat_pattern_(elt_place.clone(), &before_pat, op)?;
+                }
+                if let Some(ref slice_pat) = *slice {
+                    let slice_pat_ty = self.pat_ty_adjusted(&slice_pat)?;
+                    let slice_place = self.cat_projection(pat, place, slice_pat_ty);
+                    self.cat_pattern_(slice_place, &slice_pat, op)?;
+                }
+                for after_pat in after {
+                    self.cat_pattern_(elt_place.clone(), &after_pat, op)?;
+                }
+            }
+
+            PatKind::Path(_) | PatKind::Binding(.., None) |
+            PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
+                // always ok
+            }
+        }
+
+        Ok(())
+    }
+}
diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs
index 09f4873967e..078948cc63b 100644
--- a/src/librustdoc/clean/cfg.rs
+++ b/src/librustdoc/clean/cfg.rs
@@ -7,10 +7,10 @@ use std::mem;
 use std::fmt::{self, Write};
 use std::ops;
 
+use rustc_feature::Features;
 use syntax::symbol::{Symbol, sym};
 use syntax::ast::{MetaItem, MetaItemKind, NestedMetaItem, LitKind};
 use syntax::sess::ParseSess;
-use syntax::feature_gate::Features;
 
 use syntax_pos::Span;
 
diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs
index b3b3750320a..4b5fc7c2a1e 100644
--- a/src/librustdoc/clean/inline.rs
+++ b/src/librustdoc/clean/inline.rs
@@ -10,7 +10,7 @@ use syntax_pos::Span;
 use rustc::hir;
 use rustc::hir::def::{Res, DefKind, CtorKind};
 use rustc::hir::def_id::DefId;
-use rustc_metadata::cstore::LoadedMacro;
+use rustc_metadata::creader::LoadedMacro;
 use rustc::ty;
 use rustc::util::nodemap::FxHashSet;
 
diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
index 612f3c69871..b77b1c720cf 100644
--- a/src/librustdoc/core.rs
+++ b/src/librustdoc/core.rs
@@ -12,12 +12,12 @@ use rustc::session::DiagnosticOutput;
 use rustc::util::nodemap::{FxHashMap, FxHashSet};
 use rustc_interface::interface;
 use rustc_driver::abort_on_err;
+use rustc_feature::UnstableFeatures;
 use rustc_resolve as resolve;
 
 use syntax::ast::CRATE_NODE_ID;
 use syntax::source_map;
 use syntax::attr;
-use syntax::feature_gate::UnstableFeatures;
 use errors::json::JsonEmitter;
 use syntax::symbol::sym;
 use syntax_pos::DUMMY_SP;
@@ -343,14 +343,14 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
         registry: rustc_driver::diagnostics_registry(),
     };
 
-    interface::run_compiler_in_existing_thread_pool(config, |compiler| {
+    interface::run_compiler_in_existing_thread_pool(config, |compiler| compiler.enter(|queries| {
         let sess = compiler.session();
 
         // We need to hold on to the complete resolver, so we cause everything to be
         // cloned for the analysis passes to use. Suboptimal, but necessary in the
         // current architecture.
         let resolver = {
-            let parts = abort_on_err(compiler.expansion(), sess).peek();
+            let parts = abort_on_err(queries.expansion(), sess).peek();
             let resolver = parts.1.borrow();
 
             // Before we actually clone it, let's force all the extern'd crates to
@@ -358,10 +358,11 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
             // intra-doc-links
             resolver.borrow_mut().access(|resolver| {
                 for extern_name in &extern_names {
-                    resolver.resolve_str_path_error(DUMMY_SP, extern_name, TypeNS, CRATE_NODE_ID)
-                        .unwrap_or_else(
-                            |()| panic!("Unable to resolve external crate {}", extern_name)
-                        );
+                    resolver.resolve_str_path_error(
+                        DUMMY_SP, extern_name, TypeNS, CRATE_NODE_ID
+                    ).unwrap_or_else(
+                        |()| panic!("Unable to resolve external crate {}", extern_name)
+                    );
                 }
             });
 
@@ -373,7 +374,7 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
             sess.fatal("Compilation failed, aborting rustdoc");
         }
 
-        let mut global_ctxt = abort_on_err(compiler.global_ctxt(), sess).take();
+        let mut global_ctxt = abort_on_err(queries.global_ctxt(), sess).take();
 
         global_ctxt.enter(|tcx| {
             tcx.analysis(LOCAL_CRATE).ok();
@@ -447,8 +448,8 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
                         },
                         sym::plugins => {
                             report_deprecated_attr("plugins = \"...\"", diag);
-                            eprintln!("WARNING: `#![doc(plugins = \"...\")]` no longer functions; \
-                                      see CVE-2018-1000622");
+                            eprintln!("WARNING: `#![doc(plugins = \"...\")]` \
+                                      no longer functions; see CVE-2018-1000622");
                             continue
                         },
                         _ => continue,
@@ -486,7 +487,7 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt
 
             (krate, ctxt.renderinfo.into_inner(), render_options)
         })
-    })
+    }))
 }
 
 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs
index 56f1191feed..7945850ef08 100644
--- a/src/librustdoc/externalfiles.rs
+++ b/src/librustdoc/externalfiles.rs
@@ -2,7 +2,7 @@ use std::fs;
 use std::path::Path;
 use std::str;
 use errors;
-use crate::syntax::feature_gate::UnstableFeatures;
+use rustc_feature::UnstableFeatures;
 use crate::syntax::edition::Edition;
 use crate::html::markdown::{IdMap, ErrorCodes, Markdown, Playground};
 
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index ba94cb82c00..b5c1a77a387 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -45,7 +45,6 @@ use errors;
 use serialize::json::{ToJson, Json, as_json};
 use syntax::ast;
 use syntax::edition::Edition;
-use syntax::feature_gate::UnstableFeatures;
 use syntax::print::pprust;
 use syntax::source_map::FileName;
 use syntax::symbol::{Symbol, sym};
@@ -56,6 +55,7 @@ use rustc::middle::stability;
 use rustc::hir;
 use rustc::util::nodemap::{FxHashMap, FxHashSet};
 use rustc_data_structures::flock;
+use rustc_feature::UnstableFeatures;
 
 use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
 use crate::config::RenderOptions;
diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs
index 69d9748bb88..be3644ecf96 100644
--- a/src/librustdoc/lib.rs
+++ b/src/librustdoc/lib.rs
@@ -24,6 +24,7 @@ extern crate env_logger;
 extern crate rustc;
 extern crate rustc_data_structures;
 extern crate rustc_driver;
+extern crate rustc_feature;
 extern crate rustc_error_codes;
 extern crate rustc_index;
 extern crate rustc_resolve;
diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs
index 8431271e62d..7dc3df23a6d 100644
--- a/src/librustdoc/markdown.rs
+++ b/src/librustdoc/markdown.rs
@@ -6,7 +6,7 @@ use errors;
 use testing;
 use syntax::edition::Edition;
 use syntax::source_map::DUMMY_SP;
-use syntax::feature_gate::UnstableFeatures;
+use rustc_feature::UnstableFeatures;
 
 use crate::externalfiles::{LoadStringError, load_string};
 use crate::config::{Options, RenderOptions};
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index d8f2dbca835..3c021ae7465 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -5,10 +5,10 @@ use rustc::hir;
 use rustc::lint as lint;
 use rustc::ty;
 use rustc_resolve::ParentScope;
+use rustc_feature::UnstableFeatures;
 use syntax;
 use syntax::ast::{self, Ident};
 use syntax_expand::base::SyntaxExtensionKind;
-use syntax::feature_gate::UnstableFeatures;
 use syntax::symbol::Symbol;
 use syntax_pos::DUMMY_SP;
 
diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs
index 22f209b8bad..5fd7ab03224 100644
--- a/src/librustdoc/test.rs
+++ b/src/librustdoc/test.rs
@@ -1,4 +1,5 @@
 use rustc_data_structures::sync::Lrc;
+use rustc_feature::UnstableFeatures;
 use rustc_interface::interface;
 use rustc_target::spec::TargetTriple;
 use rustc::hir;
@@ -9,7 +10,6 @@ use syntax::ast;
 use syntax::with_globals;
 use syntax::source_map::SourceMap;
 use syntax::edition::Edition;
-use syntax::feature_gate::UnstableFeatures;
 use std::env;
 use std::io::{self, Write};
 use std::panic;
@@ -85,14 +85,14 @@ pub fn run(options: Options) -> i32 {
     let mut test_args = options.test_args.clone();
     let display_warnings = options.display_warnings;
 
-    let tests = interface::run_compiler(config, |compiler| -> Result<_, ErrorReported> {
-        let lower_to_hir = compiler.lower_to_hir()?;
+    let tests = interface::run_compiler(config, |compiler| compiler.enter(|queries| {
+        let lower_to_hir = queries.lower_to_hir()?;
 
-        let mut opts = scrape_test_config(lower_to_hir.peek().0.borrow().krate());
+        let mut opts = scrape_test_config(lower_to_hir.peek().0.krate());
         opts.display_warnings |= options.display_warnings;
         let enable_per_target_ignores = options.enable_per_target_ignores;
         let mut collector = Collector::new(
-            compiler.crate_name()?.peek().to_string(),
+            queries.crate_name()?.peek().to_string(),
             options,
             false,
             opts,
@@ -101,7 +101,8 @@ pub fn run(options: Options) -> i32 {
             enable_per_target_ignores,
         );
 
-        let mut global_ctxt = compiler.global_ctxt()?.take();
+        let mut global_ctxt = queries.global_ctxt()?.take();
+
         global_ctxt.enter(|tcx| {
             let krate = tcx.hir().krate();
             let mut hir_collector = HirCollector {
@@ -116,8 +117,9 @@ pub fn run(options: Options) -> i32 {
             });
         });
 
-        Ok(collector.tests)
-    }).expect("compiler aborted in rustdoc!");
+        let ret : Result<_, ErrorReported> = Ok(collector.tests);
+        ret
+    })).expect("compiler aborted in rustdoc!");
 
     test_args.insert(0, "rustdoctest".to_string());
 
diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs
index 7db0aad3909..41bdfea53e5 100644
--- a/src/libstd/ascii.rs
+++ b/src/libstd/ascii.rs
@@ -17,7 +17,7 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::ascii::{EscapeDefault, escape_default};
+pub use core::ascii::{escape_default, EscapeDefault};
 
 /// Extension methods for ASCII-subset only operations.
 ///
diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs
index 9f400713a86..5ba1c940251 100644
--- a/src/libstd/backtrace.rs
+++ b/src/libstd/backtrace.rs
@@ -95,10 +95,10 @@ use crate::env;
 use crate::fmt;
 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
 use crate::sync::Mutex;
-use crate::sys_common::backtrace::{output_filename, lock};
+use crate::sys_common::backtrace::{lock, output_filename};
 use crate::vec::Vec;
-use backtrace_rs as backtrace;
 use backtrace::BytesOrWideString;
+use backtrace_rs as backtrace;
 
 /// A captured OS thread stack backtrace.
 ///
diff --git a/src/libstd/benches/hash/map.rs b/src/libstd/benches/hash/map.rs
index 25425c5968e..bf646cbae47 100644
--- a/src/libstd/benches/hash/map.rs
+++ b/src/libstd/benches/hash/map.rs
@@ -1,7 +1,7 @@
 #![cfg(test)]
 
-use test::Bencher;
 use std::collections::HashMap;
+use test::Bencher;
 
 #[bench]
 fn new_drop(b: &mut Bencher) {
diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs
index f5957466be8..522b8b25144 100644
--- a/src/libstd/collections/mod.rs
+++ b/src/libstd/collections/mod.rs
@@ -413,20 +413,20 @@
 #[doc(hidden)]
 pub use crate::ops::Bound;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use alloc_crate::collections::{BinaryHeap, BTreeMap, BTreeSet};
-#[stable(feature = "rust1", since = "1.0.0")]
-pub use alloc_crate::collections::{LinkedList, VecDeque};
-#[stable(feature = "rust1", since = "1.0.0")]
 pub use alloc_crate::collections::{binary_heap, btree_map, btree_set};
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use alloc_crate::collections::{linked_list, vec_deque};
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use alloc_crate::collections::{BTreeMap, BTreeSet, BinaryHeap};
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use alloc_crate::collections::{LinkedList, VecDeque};
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use self::hash_map::HashMap;
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use self::hash_set::HashSet;
 
-#[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
+#[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
 pub use alloc_crate::collections::TryReserveError;
 
 mod hash;
diff --git a/src/libstd/env.rs b/src/libstd/env.rs
index b8989369269..cf71b61b917 100644
--- a/src/libstd/env.rs
+++ b/src/libstd/env.rs
@@ -78,7 +78,9 @@ pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
 ///
 /// [`std::env::vars`]: fn.vars.html
 #[stable(feature = "env", since = "1.0.0")]
-pub struct Vars { inner: VarsOs }
+pub struct Vars {
+    inner: VarsOs,
+}
 
 /// An iterator over a snapshot of the environment variables of this process.
 ///
@@ -87,7 +89,9 @@ pub struct Vars { inner: VarsOs }
 ///
 /// [`std::env::vars_os`]: fn.vars_os.html
 #[stable(feature = "env", since = "1.0.0")]
-pub struct VarsOs { inner: os_imp::Env }
+pub struct VarsOs {
+    inner: os_imp::Env,
+}
 
 /// Returns an iterator of (variable, value) pairs of strings, for all the
 /// environment variables of the current process.
@@ -147,11 +151,11 @@ pub fn vars_os() -> VarsOs {
 impl Iterator for Vars {
     type Item = (String, String);
     fn next(&mut self) -> Option<(String, String)> {
-        self.inner.next().map(|(a, b)| {
-            (a.into_string().unwrap(), b.into_string().unwrap())
-        })
+        self.inner.next().map(|(a, b)| (a.into_string().unwrap(), b.into_string().unwrap()))
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.inner.size_hint()
     }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
@@ -164,8 +168,12 @@ impl fmt::Debug for Vars {
 #[stable(feature = "env", since = "1.0.0")]
 impl Iterator for VarsOs {
     type Item = (OsString, OsString);
-    fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
+    fn next(&mut self) -> Option<(OsString, OsString)> {
+        self.inner.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.inner.size_hint()
+    }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
@@ -239,9 +247,8 @@ pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
 }
 
 fn _var_os(key: &OsStr) -> Option<OsString> {
-    os_imp::getenv(key).unwrap_or_else(|e| {
-        panic!("failed to get environment variable `{:?}`: {}", key, e)
-    })
+    os_imp::getenv(key)
+        .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
 }
 
 /// The error type for operations interacting with environment variables.
@@ -321,8 +328,7 @@ pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
 
 fn _set_var(k: &OsStr, v: &OsStr) {
     os_imp::setenv(k, v).unwrap_or_else(|e| {
-        panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
-               k, v, e)
+        panic!("failed to set environment variable `{:?}` to `{:?}`: {}", k, v, e)
     })
 }
 
@@ -363,9 +369,8 @@ pub fn remove_var<K: AsRef<OsStr>>(k: K) {
 }
 
 fn _remove_var(k: &OsStr) {
-    os_imp::unsetenv(k).unwrap_or_else(|e| {
-        panic!("failed to remove environment variable `{:?}`: {}", k, e)
-    })
+    os_imp::unsetenv(k)
+        .unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", k, e))
 }
 
 /// An iterator that splits an environment variable into paths according to
@@ -379,7 +384,9 @@ fn _remove_var(k: &OsStr) {
 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
 /// [`std::env::split_paths`]: fn.split_paths.html
 #[stable(feature = "env", since = "1.0.0")]
-pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
+pub struct SplitPaths<'a> {
+    inner: os_imp::SplitPaths<'a>,
+}
 
 /// Parses input according to platform conventions for the `PATH`
 /// environment variable.
@@ -412,8 +419,12 @@ pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
 #[stable(feature = "env", since = "1.0.0")]
 impl<'a> Iterator for SplitPaths<'a> {
     type Item = PathBuf;
-    fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
+    fn next(&mut self) -> Option<PathBuf> {
+        self.inner.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.inner.size_hint()
+    }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
@@ -430,7 +441,7 @@ impl fmt::Debug for SplitPaths<'_> {
 #[derive(Debug)]
 #[stable(feature = "env", since = "1.0.0")]
 pub struct JoinPathsError {
-    inner: os_imp::JoinPathsError
+    inner: os_imp::JoinPathsError,
 }
 
 /// Joins a collection of [`Path`]s appropriately for the `PATH`
@@ -499,11 +510,11 @@ pub struct JoinPathsError {
 /// [`env::split_paths`]: fn.split_paths.html
 #[stable(feature = "env", since = "1.0.0")]
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
-    where I: IntoIterator<Item=T>, T: AsRef<OsStr>
+where
+    I: IntoIterator<Item = T>,
+    T: AsRef<OsStr>,
 {
-    os_imp::join_paths(paths.into_iter()).map_err(|e| {
-        JoinPathsError { inner: e }
-    })
+    os_imp::join_paths(paths.into_iter()).map_err(|e| JoinPathsError { inner: e })
 }
 
 #[stable(feature = "env", since = "1.0.0")]
@@ -515,7 +526,9 @@ impl fmt::Display for JoinPathsError {
 
 #[stable(feature = "env", since = "1.0.0")]
 impl Error for JoinPathsError {
-    fn description(&self) -> &str { self.inner.description() }
+    fn description(&self) -> &str {
+        self.inner.description()
+    }
 }
 
 /// Returns the path of the current user's home directory if known.
@@ -549,9 +562,11 @@ impl Error for JoinPathsError {
 ///     None => println!("Impossible to get your home dir!"),
 /// }
 /// ```
-#[rustc_deprecated(since = "1.29.0",
+#[rustc_deprecated(
+    since = "1.29.0",
     reason = "This function's behavior is unexpected and probably not what you want. \
-              Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
+              Consider using the home_dir function from https://crates.io/crates/dirs instead."
+)]
 #[stable(feature = "env", since = "1.0.0")]
 pub fn home_dir() -> Option<PathBuf> {
     os_imp::home_dir()
@@ -674,7 +689,9 @@ pub fn current_exe() -> io::Result<PathBuf> {
 /// [`String`]: ../string/struct.String.html
 /// [`std::env::args`]: ./fn.args.html
 #[stable(feature = "env", since = "1.0.0")]
-pub struct Args { inner: ArgsOs }
+pub struct Args {
+    inner: ArgsOs,
+}
 
 /// An iterator over the arguments of a process, yielding an [`OsString`] value
 /// for each argument.
@@ -689,7 +706,9 @@ pub struct Args { inner: ArgsOs }
 /// [`OsString`]: ../ffi/struct.OsString.html
 /// [`std::env::args_os`]: ./fn.args_os.html
 #[stable(feature = "env", since = "1.0.0")]
-pub struct ArgsOs { inner: sys::args::Args }
+pub struct ArgsOs {
+    inner: sys::args::Args,
+}
 
 /// Returns the arguments which this program was started with (normally passed
 /// via the command line).
@@ -702,6 +721,11 @@ pub struct ArgsOs { inner: sys::args::Args }
 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
 /// passed as-is.
 ///
+/// On glibc Linux, arguments are retrieved by placing a function in .init_array.
+/// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
+/// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
+/// and Windows.
+///
 /// # Panics
 ///
 /// The returned iterator will panic during iteration if any argument to the
@@ -732,6 +756,11 @@ pub fn args() -> Args {
 /// set to arbitrary text, and it may not even exist, so this property should
 /// not be relied upon for security purposes.
 ///
+/// On glibc Linux, arguments are retrieved by placing a function in .init_array.
+/// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
+/// This allows `std::env::args` to work even in a `cdylib` or `staticlib`, as it does on macOS
+/// and Windows.
+///
 /// # Examples
 ///
 /// ```
@@ -759,13 +788,19 @@ impl Iterator for Args {
     fn next(&mut self) -> Option<String> {
         self.inner.next().map(|s| s.into_string().unwrap())
     }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.inner.size_hint()
+    }
 }
 
 #[stable(feature = "env", since = "1.0.0")]
 impl ExactSizeIterator for Args {
-    fn len(&self) -> usize { self.inner.len() }
-    fn is_empty(&self) -> bool { self.inner.is_empty() }
+    fn len(&self) -> usize {
+        self.inner.len()
+    }
+    fn is_empty(&self) -> bool {
+        self.inner.is_empty()
+    }
 }
 
 #[stable(feature = "env_iterators", since = "1.12.0")]
@@ -778,9 +813,7 @@ impl DoubleEndedIterator for Args {
 #[stable(feature = "std_debug", since = "1.16.0")]
 impl fmt::Debug for Args {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("Args")
-            .field("inner", &self.inner.inner.inner_debug())
-            .finish()
+        f.debug_struct("Args").field("inner", &self.inner.inner.inner_debug()).finish()
     }
 }
 
@@ -793,27 +826,35 @@ impl !Sync for ArgsOs {}
 #[stable(feature = "env", since = "1.0.0")]
 impl Iterator for ArgsOs {
     type Item = OsString;
-    fn next(&mut self) -> Option<OsString> { self.inner.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
+    fn next(&mut self) -> Option<OsString> {
+        self.inner.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.inner.size_hint()
+    }
 }
 
 #[stable(feature = "env", since = "1.0.0")]
 impl ExactSizeIterator for ArgsOs {
-    fn len(&self) -> usize { self.inner.len() }
-    fn is_empty(&self) -> bool { self.inner.is_empty() }
+    fn len(&self) -> usize {
+        self.inner.len()
+    }
+    fn is_empty(&self) -> bool {
+        self.inner.is_empty()
+    }
 }
 
 #[stable(feature = "env_iterators", since = "1.12.0")]
 impl DoubleEndedIterator for ArgsOs {
-    fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
+    fn next_back(&mut self) -> Option<OsString> {
+        self.inner.next_back()
+    }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
 impl fmt::Debug for ArgsOs {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("ArgsOs")
-            .field("inner", &self.inner.inner_debug())
-            .finish()
+        f.debug_struct("ArgsOs").field("inner", &self.inner.inner_debug()).finish()
     }
 }
 
@@ -1023,8 +1064,8 @@ mod tests {
         use crate::path::PathBuf;
 
         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
-            split_paths(unparsed).collect::<Vec<_>>() ==
-                parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
+            split_paths(unparsed).collect::<Vec<_>>()
+                == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
         }
 
         assert!(check_parse("", &mut [""]));
@@ -1032,11 +1073,12 @@ mod tests {
         assert!(check_parse(";;", &mut ["", "", ""]));
         assert!(check_parse(r"c:\", &mut [r"c:\"]));
         assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
-        assert!(check_parse(r"c:\;c:\Program Files\",
-                            &mut [r"c:\", r"c:\Program Files\"]));
+        assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"]));
         assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
-        assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
-                            &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
+        assert!(check_parse(
+            r#"c:\;c:\"foo;bar"\;c:\baz"#,
+            &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]
+        ));
     }
 
     #[test]
@@ -1045,8 +1087,8 @@ mod tests {
         use crate::path::PathBuf;
 
         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
-            split_paths(unparsed).collect::<Vec<_>>() ==
-                parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
+            split_paths(unparsed).collect::<Vec<_>>()
+                == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
         }
 
         assert!(check_parse("", &mut [""]));
@@ -1062,15 +1104,12 @@ mod tests {
         use crate::ffi::OsStr;
 
         fn test_eq(input: &[&str], output: &str) -> bool {
-            &*join_paths(input.iter().cloned()).unwrap() ==
-                OsStr::new(output)
+            &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
         }
 
         assert!(test_eq(&[], ""));
-        assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
-                         "/bin:/usr/bin:/usr/local/bin"));
-        assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
-                         ":/bin:::/usr/bin:"));
+        assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin"));
+        assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:"));
         assert!(join_paths(["/te:st"].iter().cloned()).is_err());
     }
 
@@ -1080,17 +1119,13 @@ mod tests {
         use crate::ffi::OsStr;
 
         fn test_eq(input: &[&str], output: &str) -> bool {
-            &*join_paths(input.iter().cloned()).unwrap() ==
-                OsStr::new(output)
+            &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output)
         }
 
         assert!(test_eq(&[], ""));
-        assert!(test_eq(&[r"c:\windows", r"c:\"],
-                        r"c:\windows;c:\"));
-        assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
-                        r";c:\windows;;;c:\;"));
-        assert!(test_eq(&[r"c:\te;st", r"c:\"],
-                        r#""c:\te;st";c:\"#));
+        assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\"));
+        assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;"));
+        assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#));
         assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
     }
 
@@ -1098,9 +1133,11 @@ mod tests {
     fn args_debug() {
         assert_eq!(
             format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
-            format!("{:?}", args()));
+            format!("{:?}", args())
+        );
         assert_eq!(
             format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
-            format!("{:?}", args_os()));
+            format!("{:?}", args_os())
+        );
     }
 }
diff --git a/src/libstd/f32.rs b/src/libstd/f32.rs
index 4b672a4c788..54e0caeddaa 100644
--- a/src/libstd/f32.rs
+++ b/src/libstd/f32.rs
@@ -14,15 +14,15 @@ use crate::intrinsics;
 use crate::sys::cmath;
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f32::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON};
+pub use core::f32::consts;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f32::{MIN_EXP, MAX_EXP, MIN_10_EXP};
+pub use core::f32::{DIGITS, EPSILON, MANTISSA_DIGITS, RADIX};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f32::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY};
+pub use core::f32::{INFINITY, MAX_10_EXP, NAN, NEG_INFINITY};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f32::{MIN, MIN_POSITIVE, MAX};
+pub use core::f32::{MAX, MIN, MIN_POSITIVE};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f32::consts;
+pub use core::f32::{MAX_EXP, MIN_10_EXP, MIN_EXP};
 
 #[cfg(not(test))]
 #[lang = "f32_runtime"]
@@ -142,7 +142,9 @@ impl f32 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    pub fn fract(self) -> f32 { self - self.trunc() }
+    pub fn fract(self) -> f32 {
+        self - self.trunc()
+    }
 
     /// Computes the absolute value of `self`. Returns `NAN` if the
     /// number is `NAN`.
@@ -192,11 +194,7 @@ impl f32 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn signum(self) -> f32 {
-        if self.is_nan() {
-            NAN
-        } else {
-            1.0_f32.copysign(self)
-        }
+        if self.is_nan() { NAN } else { 1.0_f32.copysign(self) }
     }
 
     /// Returns a number composed of the magnitude of `self` and the sign of
@@ -277,7 +275,7 @@ impl f32 {
     pub fn div_euclid(self, rhs: f32) -> f32 {
         let q = (self / rhs).trunc();
         if self % rhs < 0.0 {
-            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 }
+            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
         }
         q
     }
@@ -310,14 +308,9 @@ impl f32 {
     #[stable(feature = "euclidean_division", since = "1.38.0")]
     pub fn rem_euclid(self, rhs: f32) -> f32 {
         let r = self % rhs;
-        if r < 0.0 {
-            r + rhs.abs()
-        } else {
-            r
-        }
+        if r < 0.0 { r + rhs.abs() } else { r }
     }
 
-
     /// Raises a number to an integer power.
     ///
     /// Using this function is generally faster than using `powf`
@@ -383,11 +376,7 @@ impl f32 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn sqrt(self) -> f32 {
-        if self < 0.0 {
-            NAN
-        } else {
-            unsafe { intrinsics::sqrtf32(self) }
-        }
+        if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf32(self) } }
     }
 
     /// Returns `e^(self)`, (the exponential function).
@@ -486,7 +475,9 @@ impl f32 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    pub fn log(self, base: f32) -> f32 { self.ln() / base.ln() }
+    pub fn log(self, base: f32) -> f32 {
+        self.ln() / base.ln()
+    }
 
     /// Returns the base 2 logarithm of the number.
     ///
@@ -559,14 +550,16 @@ impl f32 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    #[rustc_deprecated(since = "1.10.0",
-                       reason = "you probably meant `(self - other).abs()`: \
-                                 this operation is `(self - other).max(0.0)` \
-                                 except that `abs_sub` also propagates NaNs (also \
-                                 known as `fdimf` in C). If you truly need the positive \
-                                 difference, consider using that expression or the C function \
-                                 `fdimf`, depending on how you wish to handle NaN (please consider \
-                                 filing an issue describing your use-case too).")]
+    #[rustc_deprecated(
+        since = "1.10.0",
+        reason = "you probably meant `(self - other).abs()`: \
+                  this operation is `(self - other).max(0.0)` \
+                  except that `abs_sub` also propagates NaNs (also \
+                  known as `fdimf` in C). If you truly need the positive \
+                  difference, consider using that expression or the C function \
+                  `fdimf`, depending on how you wish to handle NaN (please consider \
+                  filing an issue describing your use-case too)."
+    )]
     pub fn abs_sub(self, other: f32) -> f32 {
         unsafe { cmath::fdimf(self, other) }
     }
@@ -967,11 +960,7 @@ impl f32 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn acosh(self) -> f32 {
-        if self < 1.0 {
-            crate::f32::NAN
-        } else {
-            (self + ((self * self) - 1.0).sqrt()).ln()
-        }
+        if self < 1.0 { crate::f32::NAN } else { (self + ((self * self) - 1.0).sqrt()).ln() }
     }
 
     /// Inverse hyperbolic tangent function.
@@ -1022,19 +1011,22 @@ impl f32 {
     pub fn clamp(self, min: f32, max: f32) -> f32 {
         assert!(min <= max);
         let mut x = self;
-        if x < min { x = min; }
-        if x > max { x = max; }
+        if x < min {
+            x = min;
+        }
+        if x > max {
+            x = max;
+        }
         x
     }
-
 }
 
 #[cfg(test)]
 mod tests {
     use crate::f32;
     use crate::f32::*;
-    use crate::num::*;
     use crate::num::FpCategory as Fp;
+    use crate::num::*;
 
     #[test]
     fn test_num_f32() {
@@ -1279,7 +1271,7 @@ mod tests {
         assert_eq!((-0f32).abs(), 0f32);
         assert_eq!((-1f32).abs(), 1f32);
         assert_eq!(NEG_INFINITY.abs(), INFINITY);
-        assert_eq!((1f32/NEG_INFINITY).abs(), 0f32);
+        assert_eq!((1f32 / NEG_INFINITY).abs(), 0f32);
         assert!(NAN.abs().is_nan());
     }
 
@@ -1291,7 +1283,7 @@ mod tests {
         assert_eq!((-0f32).signum(), -1f32);
         assert_eq!((-1f32).signum(), -1f32);
         assert_eq!(NEG_INFINITY.signum(), -1f32);
-        assert_eq!((1f32/NEG_INFINITY).signum(), -1f32);
+        assert_eq!((1f32 / NEG_INFINITY).signum(), -1f32);
         assert!(NAN.signum().is_nan());
     }
 
@@ -1303,7 +1295,7 @@ mod tests {
         assert!(!(-0f32).is_sign_positive());
         assert!(!(-1f32).is_sign_positive());
         assert!(!NEG_INFINITY.is_sign_positive());
-        assert!(!(1f32/NEG_INFINITY).is_sign_positive());
+        assert!(!(1f32 / NEG_INFINITY).is_sign_positive());
         assert!(NAN.is_sign_positive());
         assert!(!(-NAN).is_sign_positive());
     }
@@ -1316,7 +1308,7 @@ mod tests {
         assert!((-0f32).is_sign_negative());
         assert!((-1f32).is_sign_negative());
         assert!(NEG_INFINITY.is_sign_negative());
-        assert!((1f32/NEG_INFINITY).is_sign_negative());
+        assert!((1f32 / NEG_INFINITY).is_sign_negative());
         assert!(!NAN.is_sign_negative());
         assert!((-NAN).is_sign_negative());
     }
diff --git a/src/libstd/f64.rs b/src/libstd/f64.rs
index b16038ee1f8..aa32e5fb998 100644
--- a/src/libstd/f64.rs
+++ b/src/libstd/f64.rs
@@ -14,15 +14,15 @@ use crate::intrinsics;
 use crate::sys::cmath;
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f64::{RADIX, MANTISSA_DIGITS, DIGITS, EPSILON};
+pub use core::f64::consts;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f64::{MIN_EXP, MAX_EXP, MIN_10_EXP};
+pub use core::f64::{DIGITS, EPSILON, MANTISSA_DIGITS, RADIX};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f64::{MAX_10_EXP, NAN, INFINITY, NEG_INFINITY};
+pub use core::f64::{INFINITY, MAX_10_EXP, NAN, NEG_INFINITY};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f64::{MIN, MIN_POSITIVE, MAX};
+pub use core::f64::{MAX, MIN, MIN_POSITIVE};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::f64::consts;
+pub use core::f64::{MAX_EXP, MIN_10_EXP, MIN_EXP};
 
 #[cfg(not(test))]
 #[lang = "f64_runtime"]
@@ -120,7 +120,9 @@ impl f64 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    pub fn fract(self) -> f64 { self - self.trunc() }
+    pub fn fract(self) -> f64 {
+        self - self.trunc()
+    }
 
     /// Computes the absolute value of `self`. Returns `NAN` if the
     /// number is `NAN`.
@@ -170,11 +172,7 @@ impl f64 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn signum(self) -> f64 {
-        if self.is_nan() {
-            NAN
-        } else {
-            1.0_f64.copysign(self)
-        }
+        if self.is_nan() { NAN } else { 1.0_f64.copysign(self) }
     }
 
     /// Returns a number composed of the magnitude of `self` and the sign of
@@ -286,11 +284,7 @@ impl f64 {
     #[stable(feature = "euclidean_division", since = "1.38.0")]
     pub fn rem_euclid(self, rhs: f64) -> f64 {
         let r = self % rhs;
-        if r < 0.0 {
-            r + rhs.abs()
-        } else {
-            r
-        }
+        if r < 0.0 { r + rhs.abs() } else { r }
     }
 
     /// Raises a number to an integer power.
@@ -348,11 +342,7 @@ impl f64 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn sqrt(self) -> f64 {
-        if self < 0.0 {
-            NAN
-        } else {
-            unsafe { intrinsics::sqrtf64(self) }
-        }
+        if self < 0.0 { NAN } else { unsafe { intrinsics::sqrtf64(self) } }
     }
 
     /// Returns `e^(self)`, (the exponential function).
@@ -413,7 +403,7 @@ impl f64 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn ln(self) -> f64 {
-        self.log_wrapper(|n| { unsafe { intrinsics::logf64(n) } })
+        self.log_wrapper(|n| unsafe { intrinsics::logf64(n) })
     }
 
     /// Returns the logarithm of the number with respect to an arbitrary base.
@@ -435,7 +425,9 @@ impl f64 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    pub fn log(self, base: f64) -> f64 { self.ln() / base.ln() }
+    pub fn log(self, base: f64) -> f64 {
+        self.ln() / base.ln()
+    }
 
     /// Returns the base 2 logarithm of the number.
     ///
@@ -455,9 +447,9 @@ impl f64 {
     pub fn log2(self) -> f64 {
         self.log_wrapper(|n| {
             #[cfg(target_os = "android")]
-                return crate::sys::android::log2f64(n);
+            return crate::sys::android::log2f64(n);
             #[cfg(not(target_os = "android"))]
-                return unsafe { intrinsics::log2f64(n) };
+            return unsafe { intrinsics::log2f64(n) };
         })
     }
 
@@ -477,7 +469,7 @@ impl f64 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn log10(self) -> f64 {
-        self.log_wrapper(|n| { unsafe { intrinsics::log10f64(n) } })
+        self.log_wrapper(|n| unsafe { intrinsics::log10f64(n) })
     }
 
     /// The positive difference of two numbers.
@@ -500,14 +492,16 @@ impl f64 {
     #[must_use = "method returns a new number and does not mutate the original value"]
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
-    #[rustc_deprecated(since = "1.10.0",
-    reason = "you probably meant `(self - other).abs()`: \
-                                 this operation is `(self - other).max(0.0)` \
-                                 except that `abs_sub` also propagates NaNs (also \
-                                 known as `fdim` in C). If you truly need the positive \
-                                 difference, consider using that expression or the C function \
-                                 `fdim`, depending on how you wish to handle NaN (please consider \
-                                 filing an issue describing your use-case too).")]
+    #[rustc_deprecated(
+        since = "1.10.0",
+        reason = "you probably meant `(self - other).abs()`: \
+                  this operation is `(self - other).max(0.0)` \
+                  except that `abs_sub` also propagates NaNs (also \
+                  known as `fdim` in C). If you truly need the positive \
+                  difference, consider using that expression or the C function \
+                  `fdim`, depending on how you wish to handle NaN (please consider \
+                  filing an issue describing your use-case too)."
+    )]
     pub fn abs_sub(self, other: f64) -> f64 {
         unsafe { cmath::fdim(self, other) }
     }
@@ -888,11 +882,7 @@ impl f64 {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn acosh(self) -> f64 {
-        if self < 1.0 {
-            NAN
-        } else {
-            (self + ((self * self) - 1.0).sqrt()).ln()
-        }
+        if self < 1.0 { NAN } else { (self + ((self * self) - 1.0).sqrt()).ln() }
     }
 
     /// Inverse hyperbolic tangent function.
@@ -943,8 +933,12 @@ impl f64 {
     pub fn clamp(self, min: f64, max: f64) -> f64 {
         assert!(min <= max);
         let mut x = self;
-        if x < min { x = min; }
-        if x > max { x = max; }
+        if x < min {
+            x = min;
+        }
+        if x > max {
+            x = max;
+        }
         x
     }
 
@@ -978,8 +972,8 @@ impl f64 {
 mod tests {
     use crate::f64;
     use crate::f64::*;
-    use crate::num::*;
     use crate::num::FpCategory as Fp;
+    use crate::num::*;
 
     #[test]
     fn test_num_f64() {
diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs
index 28d9906eb93..72f7367c9dc 100644
--- a/src/libstd/ffi/mod.rs
+++ b/src/libstd/ffi/mod.rs
@@ -155,21 +155,23 @@
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-#[stable(feature = "rust1", since = "1.0.0")]
-pub use self::c_str::{CString, CStr, NulError, IntoStringError};
 #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
-pub use self::c_str::{FromBytesWithNulError};
+pub use self::c_str::FromBytesWithNulError;
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::c_str::{CStr, CString, IntoStringError, NulError};
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::os_str::{OsString, OsStr};
+pub use self::os_str::{OsStr, OsString};
 
 #[stable(feature = "core_c_void", since = "1.30.0")]
 pub use core::ffi::c_void;
 
-#[unstable(feature = "c_variadic",
-           reason = "the `c_variadic` feature has not been properly tested on \
-                     all supported platforms",
-           issue = "44930")]
+#[unstable(
+    feature = "c_variadic",
+    reason = "the `c_variadic` feature has not been properly tested on \
+              all supported platforms",
+    issue = "44930"
+)]
 pub use core::ffi::{VaList, VaListImpl};
 
 mod c_str;
diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
index 30db6a58d40..e5cf022f044 100644
--- a/src/libstd/fs.rs
+++ b/src/libstd/fs.rs
@@ -9,12 +9,12 @@
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-use crate::fmt;
 use crate::ffi::OsString;
-use crate::io::{self, SeekFrom, Seek, Read, Initializer, Write, IoSlice, IoSliceMut};
+use crate::fmt;
+use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
 use crate::path::{Path, PathBuf};
 use crate::sys::fs as fs_imp;
-use crate::sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
+use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
 use crate::time::SystemTime;
 
 /// A reference to an open file on the filesystem.
@@ -585,9 +585,7 @@ impl File {
     /// ```
     #[stable(feature = "file_try_clone", since = "1.9.0")]
     pub fn try_clone(&self) -> io::Result<File> {
-        Ok(File {
-            inner: self.inner.duplicate()?
-        })
+        Ok(File { inner: self.inner.duplicate()? })
     }
 
     /// Changes the permissions on the underlying file.
@@ -629,7 +627,9 @@ impl File {
 }
 
 impl AsInner<fs_imp::File> for File {
-    fn as_inner(&self) -> &fs_imp::File { &self.inner }
+    fn as_inner(&self) -> &fs_imp::File {
+        &self.inner
+    }
 }
 impl FromInner<fs_imp::File> for File {
     fn from_inner(f: fs_imp::File) -> File {
@@ -674,7 +674,9 @@ impl Write for File {
         self.inner.write_vectored(bufs)
     }
 
-    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+    fn flush(&mut self) -> io::Result<()> {
+        self.inner.flush()
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Seek for File {
@@ -707,7 +709,9 @@ impl Write for &File {
         self.inner.write_vectored(bufs)
     }
 
-    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+    fn flush(&mut self) -> io::Result<()> {
+        self.inner.flush()
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Seek for &File {
@@ -748,7 +752,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn read(&mut self, read: bool) -> &mut OpenOptions {
-        self.0.read(read); self
+        self.0.read(read);
+        self
     }
 
     /// Sets the option for write access.
@@ -768,7 +773,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn write(&mut self, write: bool) -> &mut OpenOptions {
-        self.0.write(write); self
+        self.0.write(write);
+        self
     }
 
     /// Sets the option for the append mode.
@@ -814,7 +820,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn append(&mut self, append: bool) -> &mut OpenOptions {
-        self.0.append(append); self
+        self.0.append(append);
+        self
     }
 
     /// Sets the option for truncating a previous file.
@@ -833,7 +840,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
-        self.0.truncate(truncate); self
+        self.0.truncate(truncate);
+        self
     }
 
     /// Sets the option for creating a new file.
@@ -856,7 +864,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn create(&mut self, create: bool) -> &mut OpenOptions {
-        self.0.create(create); self
+        self.0.create(create);
+        self
     }
 
     /// Sets the option to always create a new file.
@@ -889,7 +898,8 @@ impl OpenOptions {
     /// ```
     #[stable(feature = "expand_open_options2", since = "1.9.0")]
     pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
-        self.0.create_new(create_new); self
+        self.0.create_new(create_new);
+        self
     }
 
     /// Opens a file at `path` with the options specified by `self`.
@@ -946,11 +956,15 @@ impl OpenOptions {
 }
 
 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
-    fn as_inner(&self) -> &fs_imp::OpenOptions { &self.0 }
+    fn as_inner(&self) -> &fs_imp::OpenOptions {
+        &self.0
+    }
 }
 
 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
-    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
+    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
+        &mut self.0
+    }
 }
 
 impl Metadata {
@@ -994,7 +1008,9 @@ impl Metadata {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
+    pub fn is_dir(&self) -> bool {
+        self.file_type().is_dir()
+    }
 
     /// Returns `true` if this metadata is for a regular file. The
     /// result is mutually exclusive to the result of
@@ -1017,7 +1033,9 @@ impl Metadata {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn is_file(&self) -> bool { self.file_type().is_file() }
+    pub fn is_file(&self) -> bool {
+        self.file_type().is_file()
+    }
 
     /// Returns the size of the file, in bytes, this metadata is for.
     ///
@@ -1034,7 +1052,9 @@ impl Metadata {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn len(&self) -> u64 { self.0.size() }
+    pub fn len(&self) -> u64 {
+        self.0.size()
+    }
 
     /// Returns the permissions of the file this metadata is for.
     ///
@@ -1170,11 +1190,15 @@ impl fmt::Debug for Metadata {
 }
 
 impl AsInner<fs_imp::FileAttr> for Metadata {
-    fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
+    fn as_inner(&self) -> &fs_imp::FileAttr {
+        &self.0
+    }
 }
 
 impl FromInner<fs_imp::FileAttr> for Metadata {
-    fn from_inner(attr: fs_imp::FileAttr) -> Metadata { Metadata(attr) }
+    fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
+        Metadata(attr)
+    }
 }
 
 impl Permissions {
@@ -1194,7 +1218,9 @@ impl Permissions {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn readonly(&self) -> bool { self.0.readonly() }
+    pub fn readonly(&self) -> bool {
+        self.0.readonly()
+    }
 
     /// Modifies the readonly flag for this set of permissions. If the
     /// `readonly` argument is `true`, using the resulting `Permission` will
@@ -1256,7 +1282,9 @@ impl FileType {
     /// }
     /// ```
     #[stable(feature = "file_type", since = "1.1.0")]
-    pub fn is_dir(&self) -> bool { self.0.is_dir() }
+    pub fn is_dir(&self) -> bool {
+        self.0.is_dir()
+    }
 
     /// Tests whether this file type represents a regular file.
     /// The result is  mutually exclusive to the results of
@@ -1280,7 +1308,9 @@ impl FileType {
     /// }
     /// ```
     #[stable(feature = "file_type", since = "1.1.0")]
-    pub fn is_file(&self) -> bool { self.0.is_file() }
+    pub fn is_file(&self) -> bool {
+        self.0.is_file()
+    }
 
     /// Tests whether this file type represents a symbolic link.
     /// The result is mutually exclusive to the results of
@@ -1314,11 +1344,15 @@ impl FileType {
     /// }
     /// ```
     #[stable(feature = "file_type", since = "1.1.0")]
-    pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
+    pub fn is_symlink(&self) -> bool {
+        self.0.is_symlink()
+    }
 }
 
 impl AsInner<fs_imp::FileType> for FileType {
-    fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
+    fn as_inner(&self) -> &fs_imp::FileType {
+        &self.0
+    }
 }
 
 impl FromInner<fs_imp::FilePermissions> for Permissions {
@@ -1328,7 +1362,9 @@ impl FromInner<fs_imp::FilePermissions> for Permissions {
 }
 
 impl AsInner<fs_imp::FilePermissions> for Permissions {
-    fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
+    fn as_inner(&self) -> &fs_imp::FilePermissions {
+        &self.0
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -1370,7 +1406,9 @@ impl DirEntry {
     ///
     /// The exact text, of course, depends on what files you have in `.`.
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn path(&self) -> PathBuf { self.0.path() }
+    pub fn path(&self) -> PathBuf {
+        self.0.path()
+    }
 
     /// Returns the metadata for the file that this entry points at.
     ///
@@ -1468,14 +1506,14 @@ impl DirEntry {
 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
 impl fmt::Debug for DirEntry {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_tuple("DirEntry")
-            .field(&self.path())
-            .finish()
+        f.debug_tuple("DirEntry").field(&self.path()).finish()
     }
 }
 
 impl AsInner<fs_imp::DirEntry> for DirEntry {
-    fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
+    fn as_inner(&self) -> &fs_imp::DirEntry {
+        &self.0
+    }
 }
 
 /// Removes a file from the filesystem.
@@ -1744,9 +1782,11 @@ pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<(
 /// }
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_deprecated(since = "1.1.0",
-             reason = "replaced with std::os::unix::fs::symlink and \
-                       std::os::windows::fs::{symlink_file, symlink_dir}")]
+#[rustc_deprecated(
+    since = "1.1.0",
+    reason = "replaced with std::os::unix::fs::symlink and \
+              std::os::windows::fs::{symlink_file, symlink_dir}"
+)]
 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
     fs_imp::symlink(src.as_ref(), dst.as_ref())
 }
@@ -2089,8 +2129,7 @@ pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
 /// }
 /// ```
 #[stable(feature = "set_permissions", since = "1.1.0")]
-pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
-                                       -> io::Result<()> {
+pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
     fs_imp::set_perm(path.as_ref(), perm.0)
 }
 
@@ -2107,10 +2146,7 @@ impl DirBuilder {
     /// ```
     #[stable(feature = "dir_builder", since = "1.6.0")]
     pub fn new() -> DirBuilder {
-        DirBuilder {
-            inner: fs_imp::DirBuilder::new(),
-            recursive: false,
-        }
+        DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
     }
 
     /// Indicates that directories should be created recursively, creating all
@@ -2157,16 +2193,12 @@ impl DirBuilder {
     }
 
     fn _create(&self, path: &Path) -> io::Result<()> {
-        if self.recursive {
-            self.create_dir_all(path)
-        } else {
-            self.inner.mkdir(path)
-        }
+        if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
     }
 
     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
         if path == Path::new("") {
-            return Ok(())
+            return Ok(());
         }
 
         match self.inner.mkdir(path) {
@@ -2177,7 +2209,9 @@ impl DirBuilder {
         }
         match path.parent() {
             Some(p) => self.create_dir_all(p)?,
-            None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
+            None => {
+                return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
+            }
         }
         match self.inner.mkdir(path) {
             Ok(()) => Ok(()),
@@ -2201,48 +2235,62 @@ mod tests {
     use crate::io::{ErrorKind, SeekFrom};
     use crate::path::Path;
     use crate::str;
-    use crate::sys_common::io::test::{TempDir, tmpdir};
+    use crate::sys_common::io::test::{tmpdir, TempDir};
     use crate::thread;
 
     use rand::{rngs::StdRng, RngCore, SeedableRng};
 
-    #[cfg(windows)]
-    use crate::os::windows::fs::{symlink_dir, symlink_file};
-    #[cfg(windows)]
-    use crate::sys::fs::symlink_junction;
     #[cfg(unix)]
     use crate::os::unix::fs::symlink as symlink_dir;
     #[cfg(unix)]
     use crate::os::unix::fs::symlink as symlink_file;
     #[cfg(unix)]
     use crate::os::unix::fs::symlink as symlink_junction;
+    #[cfg(windows)]
+    use crate::os::windows::fs::{symlink_dir, symlink_file};
+    #[cfg(windows)]
+    use crate::sys::fs::symlink_junction;
 
-    macro_rules! check { ($e:expr) => (
-        match $e {
-            Ok(t) => t,
-            Err(e) => panic!("{} failed with: {}", stringify!($e), e),
-        }
-    ) }
+    macro_rules! check {
+        ($e:expr) => {
+            match $e {
+                Ok(t) => t,
+                Err(e) => panic!("{} failed with: {}", stringify!($e), e),
+            }
+        };
+    }
 
     #[cfg(windows)]
-    macro_rules! error { ($e:expr, $s:expr) => (
-        match $e {
-            Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
-            Err(ref err) => assert!(err.raw_os_error() == Some($s),
-                                    format!("`{}` did not have a code of `{}`", err, $s))
-        }
-    ) }
+    macro_rules! error {
+        ($e:expr, $s:expr) => {
+            match $e {
+                Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
+                Err(ref err) => assert!(
+                    err.raw_os_error() == Some($s),
+                    format!("`{}` did not have a code of `{}`", err, $s)
+                ),
+            }
+        };
+    }
 
     #[cfg(unix)]
-    macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
-
-    macro_rules! error_contains { ($e:expr, $s:expr) => (
-        match $e {
-            Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
-            Err(ref err) => assert!(err.to_string().contains($s),
-                                    format!("`{}` did not contain `{}`", err, $s))
-        }
-    ) }
+    macro_rules! error {
+        ($e:expr, $s:expr) => {
+            error_contains!($e, $s)
+        };
+    }
+
+    macro_rules! error_contains {
+        ($e:expr, $s:expr) => {
+            match $e {
+                Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
+                Err(ref err) => assert!(
+                    err.to_string().contains($s),
+                    format!("`{}` did not contain `{}`", err, $s)
+                ),
+            }
+        };
+    }
 
     // Several test fail on windows if the user does not have permission to
     // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
@@ -2251,7 +2299,9 @@ mod tests {
     // tests most of the time, but at least we do if the user has the right
     // permissions.
     pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
-        if cfg!(unix) { return true }
+        if cfg!(unix) {
+            return true;
+        }
         let link = tmpdir.join("some_hopefully_unique_link_name");
 
         match symlink_file(r"nonexisting_target", link) {
@@ -2276,7 +2326,7 @@ mod tests {
             let mut read_buf = [0; 1028];
             let read_str = match check!(read_stream.read(&mut read_buf)) {
                 0 => panic!("shouldn't happen"),
-                n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
+                n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
             };
             assert_eq!(read_str, message);
         }
@@ -2363,9 +2413,9 @@ mod tests {
 
     #[test]
     fn file_test_io_seek_and_write() {
-        let initial_msg =   "food-is-yummy";
-        let overwrite_msg =    "-the-bar!!";
-        let final_msg =     "foo-the-bar!!";
+        let initial_msg = "food-is-yummy";
+        let overwrite_msg = "-the-bar!!";
+        let final_msg = "foo-the-bar!!";
         let seek_idx = 3;
         let mut read_mem = [0; 13];
         let tmpdir = tmpdir();
@@ -2388,7 +2438,7 @@ mod tests {
     #[test]
     fn file_test_io_seek_shakedown() {
         //                   01234567890123
-        let initial_msg =   "qwer-asdf-zxcv";
+        let initial_msg = "qwer-asdf-zxcv";
         let chunk_one: &str = "qwer";
         let chunk_two: &str = "asdf";
         let chunk_three: &str = "zxcv";
@@ -2497,13 +2547,11 @@ mod tests {
         check!(fs::create_dir(filename));
         let mask = 0o7777;
 
-        check!(fs::set_permissions(filename,
-                                   fs::Permissions::from_mode(0)));
+        check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
         let metadata0 = check!(fs::metadata(filename));
         assert_eq!(mask & metadata0.permissions().mode(), 0);
 
-        check!(fs::set_permissions(filename,
-                                   fs::Permissions::from_mode(0o1777)));
+        check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
         let metadata1 = check!(fs::metadata(filename));
         assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
     }
@@ -2568,8 +2616,7 @@ mod tests {
         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
         {
             let mut opts = OpenOptions::new();
-            let mut fs = check!(opts.read(true).write(true)
-                                    .create(true).open(filename));
+            let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
             let msg = "hw";
             fs.write(msg.as_bytes()).unwrap();
 
@@ -2703,7 +2750,7 @@ mod tests {
             for _ in 0..40 {
                 dir = dir.join("a");
             }
-            let mut join = vec!();
+            let mut join = vec![];
             for _ in 0..8 {
                 let dir = dir.clone();
                 join.push(thread::spawn(move || {
@@ -2771,7 +2818,9 @@ mod tests {
     #[cfg(windows)]
     fn recursive_rmdir_of_file_symlink() {
         let tmpdir = tmpdir();
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
 
         let f1 = tmpdir.join("f1");
         let f2 = tmpdir.join("f2");
@@ -2854,8 +2903,7 @@ mod tests {
         check!(check!(File::open(&out)).read_to_end(&mut v));
         assert_eq!(v, b"hello");
 
-        assert_eq!(check!(input.metadata()).permissions(),
-                   check!(out.metadata()).permissions());
+        assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
     }
 
     #[test]
@@ -2865,7 +2913,8 @@ mod tests {
 
         check!(File::create(&out));
         match fs::copy(&*out, tmpdir.path()) {
-            Ok(..) => panic!(), Err(..) => {}
+            Ok(..) => panic!(),
+            Err(..) => {}
         }
     }
 
@@ -2890,7 +2939,8 @@ mod tests {
         let out = tmpdir.join("out");
 
         match fs::copy(tmpdir.path(), &out) {
-            Ok(..) => panic!(), Err(..) => {}
+            Ok(..) => panic!(),
+            Err(..) => {}
         }
         assert!(!out.exists());
     }
@@ -2938,7 +2988,9 @@ mod tests {
     #[test]
     fn copy_file_follows_dst_symlink() {
         let tmp = tmpdir();
-        if !got_symlink_permission(&tmp) { return };
+        if !got_symlink_permission(&tmp) {
+            return;
+        };
 
         let in_path = tmp.join("in.txt");
         let out_path = tmp.join("out.txt");
@@ -2958,7 +3010,9 @@ mod tests {
     #[test]
     fn symlinks_work() {
         let tmpdir = tmpdir();
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
 
         let input = tmpdir.join("in.txt");
         let out = tmpdir.join("out.txt");
@@ -2966,8 +3020,7 @@ mod tests {
         check!(check!(File::create(&input)).write("foobar".as_bytes()));
         check!(symlink_file(&input, &out));
         assert!(check!(out.symlink_metadata()).file_type().is_symlink());
-        assert_eq!(check!(fs::metadata(&out)).len(),
-                   check!(fs::metadata(&input)).len());
+        assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
         let mut v = Vec::new();
         check!(check!(File::open(&out)).read_to_end(&mut v));
         assert_eq!(v, b"foobar".to_vec());
@@ -2977,31 +3030,40 @@ mod tests {
     fn symlink_noexist() {
         // Symlinks can point to things that don't exist
         let tmpdir = tmpdir();
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
 
         // Use a relative path for testing. Symlinks get normalized by Windows,
         // so we may not get the same path back for absolute paths
         check!(symlink_file(&"foo", &tmpdir.join("bar")));
-        assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
-                   "foo");
+        assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
     }
 
     #[test]
     fn read_link() {
         if cfg!(windows) {
             // directory symlink
-            assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
-                       r"C:\ProgramData");
+            assert_eq!(
+                check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
+                r"C:\ProgramData"
+            );
             // junction
-            assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
-                       r"C:\Users\Default");
+            assert_eq!(
+                check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
+                r"C:\Users\Default"
+            );
             // junction with special permissions
-            assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
-                       r"C:\Users");
+            assert_eq!(
+                check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
+                r"C:\Users"
+            );
         }
         let tmpdir = tmpdir();
         let link = tmpdir.join("link");
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
         check!(symlink_file(&"foo", &link));
         assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
     }
@@ -3023,10 +3085,8 @@ mod tests {
 
         check!(check!(File::create(&input)).write("foobar".as_bytes()));
         check!(fs::hard_link(&input, &out));
-        assert_eq!(check!(fs::metadata(&out)).len(),
-                   check!(fs::metadata(&input)).len());
-        assert_eq!(check!(fs::metadata(&out)).len(),
-                   check!(input.metadata()).len());
+        assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
+        assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
         let mut v = Vec::new();
         check!(check!(File::open(&out)).read_to_end(&mut v));
         assert_eq!(v, b"foobar".to_vec());
@@ -3134,15 +3194,22 @@ mod tests {
     #[test]
     fn open_flavors() {
         use crate::fs::OpenOptions as OO;
-        fn c<T: Clone>(t: &T) -> T { t.clone() }
+        fn c<T: Clone>(t: &T) -> T {
+            t.clone()
+        }
 
         let tmpdir = tmpdir();
 
-        let mut r = OO::new(); r.read(true);
-        let mut w = OO::new(); w.write(true);
-        let mut rw = OO::new(); rw.read(true).write(true);
-        let mut a = OO::new(); a.append(true);
-        let mut ra = OO::new(); ra.read(true).append(true);
+        let mut r = OO::new();
+        r.read(true);
+        let mut w = OO::new();
+        w.write(true);
+        let mut rw = OO::new();
+        rw.read(true).write(true);
+        let mut a = OO::new();
+        a.append(true);
+        let mut ra = OO::new();
+        ra.read(true).append(true);
 
         #[cfg(windows)]
         let invalid_options = 87; // ERROR_INVALID_PARAMETER
@@ -3201,7 +3268,7 @@ mod tests {
 
         // Test opening a file without setting an access mode
         let mut blank = OO::new();
-         error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
+        error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
 
         // Test write works
         check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
@@ -3279,8 +3346,10 @@ mod tests {
         assert!(v == &bytes[..]);
 
         check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
-        error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
-                        "stream did not contain valid UTF-8");
+        error_contains!(
+            fs::read_to_string(&tmpdir.join("not-utf8")),
+            "stream did not contain valid UTF-8"
+        );
 
         let s = "𐁁𐀓𐀠𐀴𐀍";
         check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
@@ -3292,11 +3361,9 @@ mod tests {
     fn file_try_clone() {
         let tmpdir = tmpdir();
 
-        let mut f1 = check!(OpenOptions::new()
-                                       .read(true)
-                                       .write(true)
-                                       .create(true)
-                                       .open(&tmpdir.join("test")));
+        let mut f1 = check!(
+            OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
+        );
         let mut f2 = check!(f1.try_clone());
 
         check!(f1.write_all(b"hello world"));
@@ -3341,7 +3408,9 @@ mod tests {
     #[test]
     fn realpath_works() {
         let tmpdir = tmpdir();
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
 
         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
         let file = tmpdir.join("test");
@@ -3366,7 +3435,9 @@ mod tests {
     #[test]
     fn realpath_works_tricky() {
         let tmpdir = tmpdir();
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
 
         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
         let a = tmpdir.join("a");
@@ -3452,7 +3523,9 @@ mod tests {
         assert!(junction.is_dir());
         assert!(b.exists());
 
-        if !got_symlink_permission(&tmpdir) { return };
+        if !got_symlink_permission(&tmpdir) {
+            return;
+        };
         check!(symlink_dir(&target, &link));
         check!(fs::create_dir_all(&d));
         assert!(link.is_dir());
@@ -3482,8 +3555,8 @@ mod tests {
             // Not always available
             match (a.created(), b.created()) {
                 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
-                (Err(e1), Err(e2)) if e1.kind() == ErrorKind::Other &&
-                                      e2.kind() == ErrorKind::Other => {}
+                (Err(e1), Err(e2))
+                    if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
                 (a, b) => panic!(
                     "creation time must be always supported or not supported: {:?} {:?}",
                     a, b,
diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs
index 557da174d89..8e81b292f6f 100644
--- a/src/libstd/io/buffered.rs
+++ b/src/libstd/io/buffered.rs
@@ -5,8 +5,9 @@ use crate::io::prelude::*;
 use crate::cmp;
 use crate::error;
 use crate::fmt;
-use crate::io::{self, Initializer, DEFAULT_BUF_SIZE, Error, ErrorKind, SeekFrom, IoSlice,
-        IoSliceMut};
+use crate::io::{
+    self, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, SeekFrom, DEFAULT_BUF_SIZE,
+};
 use crate::memchr;
 
 /// The `BufReader<R>` struct adds buffering to any reader.
@@ -100,12 +101,7 @@ impl<R: Read> BufReader<R> {
             let mut buffer = Vec::with_capacity(capacity);
             buffer.set_len(capacity);
             inner.initializer().initialize(&mut buffer);
-            BufReader {
-                inner,
-                buf: buffer.into_boxed_slice(),
-                pos: 0,
-                cap: 0,
-            }
+            BufReader { inner, buf: buffer.into_boxed_slice(), pos: 0, cap: 0 }
         }
     }
 }
@@ -130,7 +126,9 @@ impl<R> BufReader<R> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_ref(&self) -> &R { &self.inner }
+    pub fn get_ref(&self) -> &R {
+        &self.inner
+    }
 
     /// Gets a mutable reference to the underlying reader.
     ///
@@ -151,7 +149,9 @@ impl<R> BufReader<R> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
+    pub fn get_mut(&mut self) -> &mut R {
+        &mut self.inner
+    }
 
     /// Returns a reference to the internally buffered data.
     ///
@@ -199,7 +199,9 @@ impl<R> BufReader<R> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn into_inner(self) -> R { self.inner }
+    pub fn into_inner(self) -> R {
+        self.inner
+    }
 
     /// Invalidates all data in the internal buffer.
     #[inline]
@@ -220,17 +222,17 @@ impl<R: Seek> BufReader<R> {
         if offset < 0 {
             if let Some(new_pos) = pos.checked_sub((-offset) as u64) {
                 self.pos = new_pos as usize;
-                return Ok(())
+                return Ok(());
             }
         } else {
             if let Some(new_pos) = pos.checked_add(offset as u64) {
                 if new_pos <= self.cap as u64 {
                     self.pos = new_pos as usize;
-                    return Ok(())
+                    return Ok(());
                 }
             }
         }
-        self.seek(SeekFrom::Current(offset)).map(|_|())
+        self.seek(SeekFrom::Current(offset)).map(|_| ())
     }
 }
 
@@ -293,7 +295,10 @@ impl<R: Read> BufRead for BufReader<R> {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<R> fmt::Debug for BufReader<R> where R: fmt::Debug {
+impl<R> fmt::Debug for BufReader<R>
+where
+    R: fmt::Debug,
+{
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt.debug_struct("BufReader")
             .field("reader", &self.inner)
@@ -483,11 +488,7 @@ impl<W: Write> BufWriter<W> {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
-        BufWriter {
-            inner: Some(inner),
-            buf: Vec::with_capacity(capacity),
-            panicked: false,
-        }
+        BufWriter { inner: Some(inner), buf: Vec::with_capacity(capacity), panicked: false }
     }
 
     fn flush_buf(&mut self) -> io::Result<()> {
@@ -501,14 +502,16 @@ impl<W: Write> BufWriter<W> {
 
             match r {
                 Ok(0) => {
-                    ret = Err(Error::new(ErrorKind::WriteZero,
-                                         "failed to write the buffered data"));
+                    ret =
+                        Err(Error::new(ErrorKind::WriteZero, "failed to write the buffered data"));
                     break;
                 }
                 Ok(n) => written += n,
                 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
-                Err(e) => { ret = Err(e); break }
-
+                Err(e) => {
+                    ret = Err(e);
+                    break;
+                }
             }
         }
         if written > 0 {
@@ -531,7 +534,9 @@ impl<W: Write> BufWriter<W> {
     /// let reference = buffer.get_ref();
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_ref(&self) -> &W { self.inner.as_ref().unwrap() }
+    pub fn get_ref(&self) -> &W {
+        self.inner.as_ref().unwrap()
+    }
 
     /// Gets a mutable reference to the underlying writer.
     ///
@@ -549,7 +554,9 @@ impl<W: Write> BufWriter<W> {
     /// let reference = buffer.get_mut();
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_mut(&mut self) -> &mut W { self.inner.as_mut().unwrap() }
+    pub fn get_mut(&mut self) -> &mut W {
+        self.inner.as_mut().unwrap()
+    }
 
     /// Returns a reference to the internally buffered data.
     ///
@@ -592,7 +599,7 @@ impl<W: Write> BufWriter<W> {
     pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
         match self.flush_buf() {
             Err(e) => Err(IntoInnerError(self, e)),
-            Ok(()) => Ok(self.inner.take().unwrap())
+            Ok(()) => Ok(self.inner.take().unwrap()),
         }
     }
 }
@@ -634,7 +641,10 @@ impl<W: Write> Write for BufWriter<W> {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<W: Write> fmt::Debug for BufWriter<W> where W: fmt::Debug {
+impl<W: Write> fmt::Debug for BufWriter<W>
+where
+    W: fmt::Debug,
+{
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt.debug_struct("BufWriter")
             .field("writer", &self.inner.as_ref().unwrap())
@@ -693,7 +703,9 @@ impl<W> IntoInnerError<W> {
     /// };
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn error(&self) -> &Error { &self.1 }
+    pub fn error(&self) -> &Error {
+        &self.1
+    }
 
     /// Returns the buffered writer instance which generated the error.
     ///
@@ -726,12 +738,16 @@ impl<W> IntoInnerError<W> {
     /// };
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn into_inner(self) -> W { self.0 }
+    pub fn into_inner(self) -> W {
+        self.0
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<W> From<IntoInnerError<W>> for Error {
-    fn from(iie: IntoInnerError<W>) -> Error { iie.1 }
+    fn from(iie: IntoInnerError<W>) -> Error {
+        iie.1
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -856,10 +872,7 @@ impl<W: Write> LineWriter<W> {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> {
-        LineWriter {
-            inner: BufWriter::with_capacity(capacity, inner),
-            need_flush: false,
-        }
+        LineWriter { inner: BufWriter::with_capacity(capacity, inner), need_flush: false }
     }
 
     /// Gets a reference to the underlying writer.
@@ -879,7 +892,9 @@ impl<W: Write> LineWriter<W> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_ref(&self) -> &W { self.inner.get_ref() }
+    pub fn get_ref(&self) -> &W {
+        self.inner.get_ref()
+    }
 
     /// Gets a mutable reference to the underlying writer.
     ///
@@ -902,7 +917,9 @@ impl<W: Write> LineWriter<W> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn get_mut(&mut self) -> &mut W { self.inner.get_mut() }
+    pub fn get_mut(&mut self) -> &mut W {
+        self.inner.get_mut()
+    }
 
     /// Unwraps this `LineWriter`, returning the underlying writer.
     ///
@@ -930,10 +947,7 @@ impl<W: Write> LineWriter<W> {
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
         self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
-            IntoInnerError(LineWriter {
-                inner: buf,
-                need_flush: false,
-            }, e)
+            IntoInnerError(LineWriter { inner: buf, need_flush: false }, e)
         })
     }
 }
@@ -953,7 +967,6 @@ impl<W: Write> Write for LineWriter<W> {
             None => return self.inner.write(buf),
         };
 
-
         // Ok, we're going to write a partial amount of the data given first
         // followed by flushing the newline. After we've successfully written
         // some data then we *must* report that we wrote that data, so future
@@ -962,7 +975,7 @@ impl<W: Write> Write for LineWriter<W> {
         let n = self.inner.write(&buf[..=i])?;
         self.need_flush = true;
         if self.flush().is_err() || n != i + 1 {
-            return Ok(n)
+            return Ok(n);
         }
 
         // At this point we successfully wrote `i + 1` bytes and flushed it out,
@@ -984,12 +997,17 @@ impl<W: Write> Write for LineWriter<W> {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<W: Write> fmt::Debug for LineWriter<W> where W: fmt::Debug {
+impl<W: Write> fmt::Debug for LineWriter<W>
+where
+    W: fmt::Debug,
+{
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt.debug_struct("LineWriter")
             .field("writer", &self.inner.inner)
-            .field("buffer",
-                   &format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()))
+            .field(
+                "buffer",
+                &format_args!("{}/{}", self.inner.buf.len(), self.inner.buf.capacity()),
+            )
             .finish()
     }
 }
@@ -1008,11 +1026,7 @@ mod tests {
 
     impl Read for ShortReader {
         fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
-            if self.lengths.is_empty() {
-                Ok(0)
-            } else {
-                Ok(self.lengths.remove(0))
-            }
+            if self.lengths.is_empty() { Ok(0) } else { Ok(self.lengths.remove(0)) }
         }
     }
 
@@ -1123,7 +1137,7 @@ mod tests {
     fn test_buffered_reader_seek_underflow() {
         // gimmick reader that yields its position modulo 256 for each byte
         struct PositionReader {
-            pos: u64
+            pos: u64,
         }
         impl Read for PositionReader {
             fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
@@ -1154,7 +1168,7 @@ mod tests {
 
         let mut reader = BufReader::with_capacity(5, PositionReader { pos: 0 });
         assert_eq!(reader.fill_buf().ok(), Some(&[0, 1, 2, 3, 4][..]));
-        assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value()-5));
+        assert_eq!(reader.seek(SeekFrom::End(-5)).ok(), Some(u64::max_value() - 5));
         assert_eq!(reader.fill_buf().ok().map(|s| s.len()), Some(5));
         // the following seek will require two underlying seeks
         let expected = 9223372036854775802;
@@ -1361,7 +1375,7 @@ mod tests {
 
     #[test]
     fn test_short_reads() {
-        let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]};
+        let inner = ShortReader { lengths: vec![0, 1, 2, 0, 1, 0] };
         let mut reader = BufReader::new(inner);
         let mut buf = [0, 0];
         assert_eq!(reader.read(&mut buf).unwrap(), 0);
@@ -1379,7 +1393,9 @@ mod tests {
         struct FailFlushWriter;
 
         impl Write for FailFlushWriter {
-            fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
+            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+                Ok(buf.len())
+            }
             fn flush(&mut self) -> io::Result<()> {
                 Err(io::Error::last_os_error())
             }
@@ -1405,30 +1421,30 @@ mod tests {
                 WRITES.fetch_add(1, Ordering::SeqCst);
                 panic!();
             }
-            fn flush(&mut self) -> io::Result<()> { Ok(()) }
+            fn flush(&mut self) -> io::Result<()> {
+                Ok(())
+            }
         }
 
         thread::spawn(|| {
             let mut writer = BufWriter::new(PanicWriter);
             let _ = writer.write(b"hello world");
             let _ = writer.flush();
-        }).join().unwrap_err();
+        })
+        .join()
+        .unwrap_err();
 
         assert_eq!(WRITES.load(Ordering::SeqCst), 1);
     }
 
     #[bench]
     fn bench_buffered_reader(b: &mut test::Bencher) {
-        b.iter(|| {
-            BufReader::new(io::empty())
-        });
+        b.iter(|| BufReader::new(io::empty()));
     }
 
     #[bench]
     fn bench_buffered_writer(b: &mut test::Bencher) {
-        b.iter(|| {
-            BufWriter::new(io::sink())
-        });
+        b.iter(|| BufWriter::new(io::sink()));
     }
 
     struct AcceptOneThenFail {
@@ -1457,10 +1473,7 @@ mod tests {
 
     #[test]
     fn erroneous_flush_retried() {
-        let a = AcceptOneThenFail {
-            written: false,
-            flushed: false,
-        };
+        let a = AcceptOneThenFail { written: false, flushed: false };
 
         let mut l = LineWriter::new(a);
         assert_eq!(l.write(b"a\nb\na").unwrap(), 4);
diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs
index c29a68e6f02..c20bd3097b2 100644
--- a/src/libstd/io/error.rs
+++ b/src/libstd/io/error.rs
@@ -1,8 +1,8 @@
+use crate::convert::From;
 use crate::error;
 use crate::fmt;
 use crate::result;
 use crate::sys;
-use crate::convert::From;
 
 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
 /// operations.
@@ -73,7 +73,7 @@ enum Repr {
 #[derive(Debug)]
 struct Custom {
     kind: ErrorKind,
-    error: Box<dyn error::Error+Send+Sync>,
+    error: Box<dyn error::Error + Send + Sync>,
 }
 
 /// A list specifying general categories of I/O error.
@@ -220,9 +220,7 @@ impl From<ErrorKind> for Error {
     /// [`Error`]: ../../std/io/struct.Error.html
     #[inline]
     fn from(kind: ErrorKind) -> Error {
-        Error {
-            repr: Repr::Simple(kind)
-        }
+        Error { repr: Repr::Simple(kind) }
     }
 }
 
@@ -247,18 +245,14 @@ impl Error {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new<E>(kind: ErrorKind, error: E) -> Error
-        where E: Into<Box<dyn error::Error+Send+Sync>>
+    where
+        E: Into<Box<dyn error::Error + Send + Sync>>,
     {
         Self::_new(kind, error.into())
     }
 
-    fn _new(kind: ErrorKind, error: Box<dyn error::Error+Send+Sync>) -> Error {
-        Error {
-            repr: Repr::Custom(Box::new(Custom {
-                kind,
-                error,
-            }))
-        }
+    fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
+        Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
     }
 
     /// Returns an error representing the last OS error which occurred.
@@ -370,7 +364,7 @@ impl Error {
     /// }
     /// ```
     #[stable(feature = "io_error_inner", since = "1.3.0")]
-    pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> {
+    pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
         match self.repr {
             Repr::Os(..) => None,
             Repr::Simple(..) => None,
@@ -441,7 +435,7 @@ impl Error {
     /// }
     /// ```
     #[stable(feature = "io_error_inner", since = "1.3.0")]
-    pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> {
+    pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
         match self.repr {
             Repr::Os(..) => None,
             Repr::Simple(..) => None,
@@ -475,11 +469,11 @@ impl Error {
     /// }
     /// ```
     #[stable(feature = "io_error_inner", since = "1.3.0")]
-    pub fn into_inner(self) -> Option<Box<dyn error::Error+Send+Sync>> {
+    pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
         match self.repr {
             Repr::Os(..) => None,
             Repr::Simple(..) => None,
-            Repr::Custom(c) => Some(c.error)
+            Repr::Custom(c) => Some(c.error),
         }
     }
 
@@ -514,11 +508,12 @@ impl Error {
 impl fmt::Debug for Repr {
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
-            Repr::Os(code) =>
-                fmt.debug_struct("Os")
-                    .field("code", &code)
-                    .field("kind", &sys::decode_error_kind(code))
-                    .field("message", &sys::os::error_string(code)).finish(),
+            Repr::Os(code) => fmt
+                .debug_struct("Os")
+                .field("code", &code)
+                .field("kind", &sys::decode_error_kind(code))
+                .field("message", &sys::os::error_string(code))
+                .finish(),
             Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
             Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
         }
@@ -567,17 +562,17 @@ impl error::Error for Error {
 }
 
 fn _assert_error_is_sync_send() {
-    fn _is_sync_send<T: Sync+Send>() {}
+    fn _is_sync_send<T: Sync + Send>() {}
     _is_sync_send::<Error>();
 }
 
 #[cfg(test)]
 mod test {
-    use super::{Error, ErrorKind, Repr, Custom};
+    use super::{Custom, Error, ErrorKind, Repr};
     use crate::error;
     use crate::fmt;
-    use crate::sys::os::error_string;
     use crate::sys::decode_error_kind;
+    use crate::sys::os::error_string;
 
     #[test]
     fn test_debug_error() {
@@ -587,20 +582,18 @@ mod test {
         let err = Error {
             repr: Repr::Custom(box Custom {
                 kind: ErrorKind::InvalidInput,
-                error: box Error {
-                    repr: super::Repr::Os(code)
-                },
-            })
+                error: box Error { repr: super::Repr::Os(code) },
+            }),
         };
         let expected = format!(
             "Custom {{ \
-                kind: InvalidInput, \
-                error: Os {{ \
-                    code: {:?}, \
-                    kind: {:?}, \
-                    message: {:?} \
-                }} \
-            }}",
+             kind: InvalidInput, \
+             error: Os {{ \
+             code: {:?}, \
+             kind: {:?}, \
+             message: {:?} \
+             }} \
+             }}",
             code, kind, msg
         );
         assert_eq!(format!("{:?}", err), expected);
diff --git a/src/libstd/io/impls.rs b/src/libstd/io/impls.rs
index c959f2d389b..b7f82e65299 100644
--- a/src/libstd/io/impls.rs
+++ b/src/libstd/io/impls.rs
@@ -1,7 +1,8 @@
 use crate::cmp;
-use crate::io::{self, SeekFrom, Read, Initializer, Write, Seek, BufRead, Error, ErrorKind,
-        IoSliceMut, IoSlice};
 use crate::fmt;
+use crate::io::{
+    self, BufRead, Error, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write,
+};
 use crate::mem;
 
 // =============================================================================
@@ -42,7 +43,9 @@ impl<R: Read + ?Sized> Read for &mut R {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<W: Write + ?Sized> Write for &mut W {
     #[inline]
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        (**self).write(buf)
+    }
 
     #[inline]
     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
@@ -50,7 +53,9 @@ impl<W: Write + ?Sized> Write for &mut W {
     }
 
     #[inline]
-    fn flush(&mut self) -> io::Result<()> { (**self).flush() }
+    fn flush(&mut self) -> io::Result<()> {
+        (**self).flush()
+    }
 
     #[inline]
     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
@@ -65,15 +70,21 @@ impl<W: Write + ?Sized> Write for &mut W {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<S: Seek + ?Sized> Seek for &mut S {
     #[inline]
-    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        (**self).seek(pos)
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<B: BufRead + ?Sized> BufRead for &mut B {
     #[inline]
-    fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
+    fn fill_buf(&mut self) -> io::Result<&[u8]> {
+        (**self).fill_buf()
+    }
 
     #[inline]
-    fn consume(&mut self, amt: usize) { (**self).consume(amt) }
+    fn consume(&mut self, amt: usize) {
+        (**self).consume(amt)
+    }
 
     #[inline]
     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
@@ -121,7 +132,9 @@ impl<R: Read + ?Sized> Read for Box<R> {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<W: Write + ?Sized> Write for Box<W> {
     #[inline]
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) }
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        (**self).write(buf)
+    }
 
     #[inline]
     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
@@ -129,7 +142,9 @@ impl<W: Write + ?Sized> Write for Box<W> {
     }
 
     #[inline]
-    fn flush(&mut self) -> io::Result<()> { (**self).flush() }
+    fn flush(&mut self) -> io::Result<()> {
+        (**self).flush()
+    }
 
     #[inline]
     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
@@ -144,15 +159,21 @@ impl<W: Write + ?Sized> Write for Box<W> {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<S: Seek + ?Sized> Seek for Box<S> {
     #[inline]
-    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { (**self).seek(pos) }
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        (**self).seek(pos)
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<B: BufRead + ?Sized> BufRead for Box<B> {
     #[inline]
-    fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() }
+    fn fill_buf(&mut self) -> io::Result<&[u8]> {
+        (**self).fill_buf()
+    }
 
     #[inline]
-    fn consume(&mut self, amt: usize) { (**self).consume(amt) }
+    fn consume(&mut self, amt: usize) {
+        (**self).consume(amt)
+    }
 
     #[inline]
     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
@@ -227,8 +248,7 @@ impl Read for &[u8] {
     #[inline]
     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
         if buf.len() > self.len() {
-            return Err(Error::new(ErrorKind::UnexpectedEof,
-                                  "failed to fill whole buffer"));
+            return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"));
         }
         let (a, b) = self.split_at(buf.len());
 
@@ -257,10 +277,14 @@ impl Read for &[u8] {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl BufRead for &[u8] {
     #[inline]
-    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) }
+    fn fill_buf(&mut self) -> io::Result<&[u8]> {
+        Ok(*self)
+    }
 
     #[inline]
-    fn consume(&mut self, amt: usize) { *self = &self[amt..]; }
+    fn consume(&mut self, amt: usize) {
+        *self = &self[amt..];
+    }
 }
 
 /// Write is implemented for `&mut [u8]` by copying into the slice, overwriting
@@ -302,7 +326,9 @@ impl Write for &mut [u8] {
     }
 
     #[inline]
-    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+    fn flush(&mut self) -> io::Result<()> {
+        Ok(())
+    }
 }
 
 /// Write is implemented for `Vec<u8>` by appending to the vector.
@@ -332,7 +358,9 @@ impl Write for Vec<u8> {
     }
 
     #[inline]
-    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+    fn flush(&mut self) -> io::Result<()> {
+        Ok(())
+    }
 }
 
 #[cfg(test)]
diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs
index be364a10593..20c1c5cd1b8 100644
--- a/src/libstd/io/mod.rs
+++ b/src/libstd/io/mod.rs
@@ -261,49 +261,54 @@
 
 use crate::cmp;
 use crate::fmt;
-use crate::slice;
-use crate::str;
 use crate::memchr;
 use crate::ops::{Deref, DerefMut};
 use crate::ptr;
+use crate::slice;
+use crate::str;
 use crate::sys;
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::buffered::{BufReader, BufWriter, LineWriter};
-#[stable(feature = "rust1", since = "1.0.0")]
 pub use self::buffered::IntoInnerError;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::cursor::Cursor;
+pub use self::buffered::{BufReader, BufWriter, LineWriter};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::error::{Result, Error, ErrorKind};
+pub use self::cursor::Cursor;
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
+pub use self::error::{Error, ErrorKind, Result};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
+pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
+pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
 #[unstable(feature = "print_internals", issue = "0")]
-pub use self::stdio::{_print, _eprint};
+pub use self::stdio::{_eprint, _print};
 #[unstable(feature = "libstd_io_internals", issue = "42788")]
 #[doc(no_inline, hidden)]
 pub use self::stdio::{set_panic, set_print};
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
 
-pub mod prelude;
 mod buffered;
 mod cursor;
 mod error;
 mod impls;
 mod lazy;
-mod util;
+pub mod prelude;
 mod stdio;
+mod util;
 
 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
 
-struct Guard<'a> { buf: &'a mut Vec<u8>, len: usize }
+struct Guard<'a> {
+    buf: &'a mut Vec<u8>,
+    len: usize,
+}
 
 impl Drop for Guard<'_> {
     fn drop(&mut self) {
-        unsafe { self.buf.set_len(self.len); }
+        unsafe {
+            self.buf.set_len(self.len);
+        }
     }
 }
 
@@ -326,15 +331,15 @@ impl Drop for Guard<'_> {
 //    the function only *appends* bytes to the buffer. We'll get undefined
 //    behavior if existing bytes are overwritten to have non-UTF-8 data.
 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
-    where F: FnOnce(&mut Vec<u8>) -> Result<usize>
+where
+    F: FnOnce(&mut Vec<u8>) -> Result<usize>,
 {
     unsafe {
         let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
         let ret = f(g.buf);
         if str::from_utf8(&g.buf[g.len..]).is_err() {
             ret.and_then(|_| {
-                Err(Error::new(ErrorKind::InvalidData,
-                               "stream did not contain valid UTF-8"))
+                Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
             })
         } else {
             g.len = g.buf.len();
@@ -405,23 +410,17 @@ where
 
 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
 where
-    F: FnOnce(&mut [u8]) -> Result<usize>
+    F: FnOnce(&mut [u8]) -> Result<usize>,
 {
-    let buf = bufs
-        .iter_mut()
-        .find(|b| !b.is_empty())
-        .map_or(&mut [][..], |b| &mut **b);
+    let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
     read(buf)
 }
 
 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
 where
-    F: FnOnce(&[u8]) -> Result<usize>
+    F: FnOnce(&[u8]) -> Result<usize>,
 {
-    let buf = bufs
-        .iter()
-        .find(|b| !b.is_empty())
-        .map_or(&[][..], |b| &**b);
+    let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
     write(buf)
 }
 
@@ -767,14 +766,16 @@ pub trait Read {
         while !buf.is_empty() {
             match self.read(buf) {
                 Ok(0) => break,
-                Ok(n) => { let tmp = buf; buf = &mut tmp[n..]; }
+                Ok(n) => {
+                    let tmp = buf;
+                    buf = &mut tmp[n..];
+                }
                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                 Err(e) => return Err(e),
             }
         }
         if !buf.is_empty() {
-            Err(Error::new(ErrorKind::UnexpectedEof,
-                           "failed to fill whole buffer"))
+            Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
         } else {
             Ok(())
         }
@@ -815,7 +816,12 @@ pub trait Read {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
+    fn by_ref(&mut self) -> &mut Self
+    where
+        Self: Sized,
+    {
+        self
+    }
 
     /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
     ///
@@ -852,7 +858,10 @@ pub trait Read {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn bytes(self) -> Bytes<Self> where Self: Sized {
+    fn bytes(self) -> Bytes<Self>
+    where
+        Self: Sized,
+    {
         Bytes { inner: self }
     }
 
@@ -887,7 +896,10 @@ pub trait Read {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
+    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
+    where
+        Self: Sized,
+    {
         Chain { first: self, second: next, done_first: false }
     }
 
@@ -923,7 +935,10 @@ pub trait Read {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn take(self, limit: u64) -> Take<Self> where Self: Sized {
+    fn take(self, limit: u64) -> Take<Self>
+    where
+        Self: Sized,
+    {
         Take { inner: self, limit: limit }
     }
 }
@@ -1339,8 +1354,9 @@ pub trait Write {
     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
         while !buf.is_empty() {
             match self.write(buf) {
-                Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
-                                               "failed to write whole buffer")),
+                Ok(0) => {
+                    return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
+                }
                 Ok(n) => buf = &buf[n..],
                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                 Err(e) => return Err(e),
@@ -1444,7 +1460,12 @@ pub trait Write {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
+    fn by_ref(&mut self) -> &mut Self
+    where
+        Self: Sized,
+    {
+        self
+    }
 }
 
 /// The `Seek` trait provides a cursor which can be moved within a stream of
@@ -1601,15 +1622,14 @@ pub enum SeekFrom {
     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
 }
 
-fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>)
-                                   -> Result<usize> {
+fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
     let mut read = 0;
     loop {
         let (done, used) = {
             let available = match r.fill_buf() {
                 Ok(n) => n,
                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
-                Err(e) => return Err(e)
+                Err(e) => return Err(e),
             };
             match memchr::memchr(delim, available) {
                 Some(i) => {
@@ -1900,7 +1920,10 @@ pub trait BufRead: Read {
     /// assert_eq!(split_iter.next(), None);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn split(self, byte: u8) -> Split<Self> where Self: Sized {
+    fn split(self, byte: u8) -> Split<Self>
+    where
+        Self: Sized,
+    {
         Split { buf: self, delim: byte }
     }
 
@@ -1939,7 +1962,10 @@ pub trait BufRead: Read {
     ///
     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
     #[stable(feature = "rust1", since = "1.0.0")]
-    fn lines(self) -> Lines<Self> where Self: Sized {
+    fn lines(self) -> Lines<Self>
+    where
+        Self: Sized,
+    {
         Lines { buf: self }
     }
 }
@@ -2035,10 +2061,7 @@ impl<T, U> Chain<T, U> {
 #[stable(feature = "std_debug", since = "1.16.0")]
 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("Chain")
-            .field("t", &self.first)
-            .field("u", &self.second)
-            .finish()
+        f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
     }
 }
 
@@ -2066,11 +2089,7 @@ impl<T: Read, U: Read> Read for Chain<T, U> {
 
     unsafe fn initializer(&self) -> Initializer {
         let initializer = self.first.initializer();
-        if initializer.should_initialize() {
-            initializer
-        } else {
-            self.second.initializer()
-        }
+        if initializer.should_initialize() { initializer } else { self.second.initializer() }
     }
 }
 
@@ -2079,7 +2098,9 @@ impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
     fn fill_buf(&mut self) -> Result<&[u8]> {
         if !self.done_first {
             match self.first.fill_buf()? {
-                buf if buf.is_empty() => { self.done_first = true; }
+                buf if buf.is_empty() => {
+                    self.done_first = true;
+                }
                 buf => return Ok(buf),
             }
         }
@@ -2087,11 +2108,7 @@ impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
     }
 
     fn consume(&mut self, amt: usize) {
-        if !self.done_first {
-            self.first.consume(amt)
-        } else {
-            self.second.consume(amt)
-        }
+        if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
     }
 }
 
@@ -2137,7 +2154,9 @@ impl<T> Take<T> {
     /// }
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn limit(&self) -> u64 { self.limit }
+    pub fn limit(&self) -> u64 {
+        self.limit
+    }
 
     /// Sets the number of bytes that can be read before this instance will
     /// return EOF. This is the same as constructing a new `Take` instance, so
@@ -2351,7 +2370,7 @@ impl<B: BufRead> Iterator for Split<B> {
                 }
                 Some(Ok(buf))
             }
-            Err(e) => Some(Err(e))
+            Err(e) => Some(Err(e)),
         }
     }
 }
@@ -2385,16 +2404,16 @@ impl<B: BufRead> Iterator for Lines<B> {
                 }
                 Some(Ok(buf))
             }
-            Err(e) => Some(Err(e))
+            Err(e) => Some(Err(e)),
         }
     }
 }
 
 #[cfg(test)]
 mod tests {
+    use super::{repeat, Cursor, SeekFrom};
     use crate::cmp;
     use crate::io::prelude::*;
-    use super::{Cursor, SeekFrom, repeat};
     use crate::io::{self, IoSlice, IoSliceMut};
     use crate::mem;
     use crate::ops::Deref;
@@ -2509,16 +2528,14 @@ mod tests {
         let mut buf = [0; 4];
 
         let mut c = Cursor::new(&b""[..]);
-        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
-                   io::ErrorKind::UnexpectedEof);
+        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
 
         let mut c = Cursor::new(&b"123"[..]).chain(Cursor::new(&b"456789"[..]));
         c.read_exact(&mut buf).unwrap();
         assert_eq!(&buf, b"1234");
         c.read_exact(&mut buf).unwrap();
         assert_eq!(&buf, b"5678");
-        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
-                   io::ErrorKind::UnexpectedEof);
+        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
     }
 
     #[test]
@@ -2526,12 +2543,10 @@ mod tests {
         let mut buf = [0; 4];
 
         let mut c = &b""[..];
-        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
-                   io::ErrorKind::UnexpectedEof);
+        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
 
         let mut c = &b"123"[..];
-        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(),
-                   io::ErrorKind::UnexpectedEof);
+        assert_eq!(c.read_exact(&mut buf).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
         // make sure the optimized (early returning) method is being used
         assert_eq!(&buf, &[0; 4]);
 
@@ -2558,7 +2573,7 @@ mod tests {
             fn fill_buf(&mut self) -> io::Result<&[u8]> {
                 Err(io::Error::new(io::ErrorKind::Other, ""))
             }
-            fn consume(&mut self, _amt: usize) { }
+            fn consume(&mut self, _amt: usize) {}
         }
 
         let mut buf = [0; 1];
@@ -2591,11 +2606,9 @@ mod tests {
     #[test]
     fn chain_bufread() {
         let testdata = b"ABCDEFGHIJKL";
-        let chain1 = (&testdata[..3]).chain(&testdata[3..6])
-                                     .chain(&testdata[6..9])
-                                     .chain(&testdata[9..]);
-        let chain2 = (&testdata[..4]).chain(&testdata[4..8])
-                                     .chain(&testdata[8..]);
+        let chain1 =
+            (&testdata[..3]).chain(&testdata[3..6]).chain(&testdata[6..9]).chain(&testdata[9..]);
+        let chain2 = (&testdata[..4]).chain(&testdata[4..8]).chain(&testdata[8..]);
         cmp_bufread(chain1, chain2, &testdata[..]);
     }
 
@@ -2651,7 +2664,6 @@ mod tests {
         assert_eq!(c.stream_position()?, 15);
         assert_eq!(c.stream_position()?, 15);
 
-
         c.seek(SeekFrom::Start(7))?;
         c.seek(SeekFrom::Current(2))?;
         assert_eq!(c.stream_position()?, 9);
@@ -2700,9 +2712,7 @@ mod tests {
         // that will not allocate when the limit has already been reached. In
         // this case, vec2 never grows.
         let mut vec2 = Vec::with_capacity(input.len());
-        ExampleSliceReader { slice: input }
-            .take(input.len() as u64)
-            .read_to_end(&mut vec2)?;
+        ExampleSliceReader { slice: input }.take(input.len() as u64).read_to_end(&mut vec2)?;
         assert_eq!(vec2.len(), input.len());
         assert_eq!(vec2.capacity(), input.len(), "did not allocate more");
 
diff --git a/src/libstd/io/prelude.rs b/src/libstd/io/prelude.rs
index 2e19edf2621..3baab2be377 100644
--- a/src/libstd/io/prelude.rs
+++ b/src/libstd/io/prelude.rs
@@ -11,4 +11,4 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use super::{Read, Write, BufRead, Seek};
+pub use super::{BufRead, Read, Seek, Write};
diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs
index 33cc87eb795..b09161b97aa 100644
--- a/src/libstd/io/util.rs
+++ b/src/libstd/io/util.rs
@@ -1,7 +1,7 @@
 #![allow(missing_copy_implementations)]
 
 use crate::fmt;
-use crate::io::{self, Read, Initializer, Write, ErrorKind, BufRead, IoSlice, IoSliceMut};
+use crate::io::{self, BufRead, ErrorKind, Initializer, IoSlice, IoSliceMut, Read, Write};
 use crate::mem::MaybeUninit;
 
 /// Copies the entire contents of a reader into a writer.
@@ -41,7 +41,9 @@ use crate::mem::MaybeUninit;
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
-    where R: Read, W: Write
+where
+    R: Read,
+    W: Write,
 {
     let mut buf = MaybeUninit::<[u8; super::DEFAULT_BUF_SIZE]>::uninit();
     // FIXME(#53491): This is calling `get_mut` and `get_ref` on an uninitialized
@@ -49,7 +51,9 @@ pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<
     // This is still technically undefined behavior due to creating a reference
     // to uninitialized data, but within libstd we can rely on more guarantees
     // than if this code were in an external lib.
-    unsafe { reader.initializer().initialize(buf.get_mut()); }
+    unsafe {
+        reader.initializer().initialize(buf.get_mut());
+    }
 
     let mut written = 0;
     loop {
@@ -71,7 +75,9 @@ pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<
 ///
 /// [`empty`]: fn.empty.html
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct Empty { _priv: () }
+pub struct Empty {
+    _priv: (),
+}
 
 /// Constructs a new handle to an empty reader.
 ///
@@ -91,12 +97,16 @@ pub struct Empty { _priv: () }
 /// assert!(buffer.is_empty());
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
-pub fn empty() -> Empty { Empty { _priv: () } }
+pub fn empty() -> Empty {
+    Empty { _priv: () }
+}
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Read for Empty {
     #[inline]
-    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> { Ok(0) }
+    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
+        Ok(0)
+    }
 
     #[inline]
     unsafe fn initializer(&self) -> Initializer {
@@ -106,7 +116,9 @@ impl Read for Empty {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl BufRead for Empty {
     #[inline]
-    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) }
+    fn fill_buf(&mut self) -> io::Result<&[u8]> {
+        Ok(&[])
+    }
     #[inline]
     fn consume(&mut self, _n: usize) {}
 }
@@ -125,7 +137,9 @@ impl fmt::Debug for Empty {
 ///
 /// [repeat]: fn.repeat.html
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct Repeat { byte: u8 }
+pub struct Repeat {
+    byte: u8,
+}
 
 /// Creates an instance of a reader that infinitely repeats one byte.
 ///
@@ -142,7 +156,9 @@ pub struct Repeat { byte: u8 }
 /// assert_eq!(buffer, [0b101, 0b101, 0b101]);
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
-pub fn repeat(byte: u8) -> Repeat { Repeat { byte } }
+pub fn repeat(byte: u8) -> Repeat {
+    Repeat { byte }
+}
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Read for Repeat {
@@ -183,7 +199,9 @@ impl fmt::Debug for Repeat {
 ///
 /// [sink]: fn.sink.html
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct Sink { _priv: () }
+pub struct Sink {
+    _priv: (),
+}
 
 /// Creates an instance of a writer which will successfully consume all data.
 ///
@@ -200,12 +218,16 @@ pub struct Sink { _priv: () }
 /// assert_eq!(num_bytes, 5);
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
-pub fn sink() -> Sink { Sink { _priv: () } }
+pub fn sink() -> Sink {
+    Sink { _priv: () }
+}
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Write for Sink {
     #[inline]
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        Ok(buf.len())
+    }
 
     #[inline]
     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
@@ -214,7 +236,9 @@ impl Write for Sink {
     }
 
     #[inline]
-    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+    fn flush(&mut self) -> io::Result<()> {
+        Ok(())
+    }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
@@ -227,7 +251,7 @@ impl fmt::Debug for Sink {
 #[cfg(test)]
 mod tests {
     use crate::io::prelude::*;
-    use crate::io::{copy, sink, empty, repeat};
+    use crate::io::{copy, empty, repeat, sink};
 
     #[test]
     fn copy_copies() {
diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs
index acf53f7f003..1dbb0c6ec83 100644
--- a/src/libstd/lib.rs
+++ b/src/libstd/lib.rs
@@ -234,6 +234,7 @@
 #![feature(allocator_internals)]
 #![feature(allow_internal_unsafe)]
 #![feature(allow_internal_unstable)]
+#![feature(atomic_mut_ptr)]
 #![feature(arbitrary_self_types)]
 #![feature(array_error_internals)]
 #![feature(asm)]
diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs
index 2df79ee97fb..11850a1b5fc 100644
--- a/src/libstd/macros.rs
+++ b/src/libstd/macros.rs
@@ -313,9 +313,8 @@ macro_rules! dbg {
 
 #[cfg(test)]
 macro_rules! assert_approx_eq {
-    ($a:expr, $b:expr) => ({
+    ($a:expr, $b:expr) => {{
         let (a, b) = (&$a, &$b);
-        assert!((*a - *b).abs() < 1.0e-6,
-                "{} is not approximately equal to {}", *a, *b);
-    })
+        assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);
+    }};
 }
diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs
index f9255b82fc8..d5f4ece726b 100644
--- a/src/libstd/net/addr.rs
+++ b/src/libstd/net/addr.rs
@@ -1,16 +1,16 @@
+use crate::convert::TryInto;
 use crate::fmt;
 use crate::hash;
 use crate::io;
+use crate::iter;
 use crate::mem;
-use crate::net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
+use crate::net::{hton, ntoh, IpAddr, Ipv4Addr, Ipv6Addr};
 use crate::option;
+use crate::slice;
 use crate::sys::net::netc as c;
-use crate::sys_common::{FromInner, AsInner, IntoInner};
 use crate::sys_common::net::LookupHost;
+use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::vec;
-use crate::iter;
-use crate::slice;
-use crate::convert::TryInto;
 
 /// An internet socket address, either IPv4 or IPv6.
 ///
@@ -74,7 +74,9 @@ pub enum SocketAddr {
 /// ```
 #[derive(Copy)]
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct SocketAddrV4 { inner: c::sockaddr_in }
+pub struct SocketAddrV4 {
+    inner: c::sockaddr_in,
+}
 
 /// An IPv6 socket address.
 ///
@@ -104,7 +106,9 @@ pub struct SocketAddrV4 { inner: c::sockaddr_in }
 /// ```
 #[derive(Copy)]
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
+pub struct SocketAddrV6 {
+    inner: c::sockaddr_in6,
+}
 
 impl SocketAddr {
     /// Creates a new socket address from an [IP address] and a port number.
@@ -274,7 +278,7 @@ impl SocketAddrV4 {
                 sin_family: c::AF_INET as c::sa_family_t,
                 sin_port: hton(port),
                 sin_addr: *ip.as_inner(),
-                .. unsafe { mem::zeroed() }
+                ..unsafe { mem::zeroed() }
             },
         }
     }
@@ -291,9 +295,7 @@ impl SocketAddrV4 {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn ip(&self) -> &Ipv4Addr {
-        unsafe {
-            &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
-        }
+        unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
     }
 
     /// Changes the IP address associated with this socket address.
@@ -362,8 +364,7 @@ impl SocketAddrV6 {
     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
-               -> SocketAddrV6 {
+    pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
         SocketAddrV6 {
             inner: c::sockaddr_in6 {
                 sin6_family: c::AF_INET6 as c::sa_family_t,
@@ -371,7 +372,7 @@ impl SocketAddrV6 {
                 sin6_addr: *ip.as_inner(),
                 sin6_flowinfo: flowinfo,
                 sin6_scope_id: scope_id,
-                .. unsafe { mem::zeroed() }
+                ..unsafe { mem::zeroed() }
             },
         }
     }
@@ -388,9 +389,7 @@ impl SocketAddrV6 {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn ip(&self) -> &Ipv6Addr {
-        unsafe {
-            &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
-        }
+        unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
     }
 
     /// Changes the IP address associated with this socket address.
@@ -633,27 +632,31 @@ impl fmt::Debug for SocketAddrV6 {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Clone for SocketAddrV4 {
-    fn clone(&self) -> SocketAddrV4 { *self }
+    fn clone(&self) -> SocketAddrV4 {
+        *self
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Clone for SocketAddrV6 {
-    fn clone(&self) -> SocketAddrV6 { *self }
+    fn clone(&self) -> SocketAddrV6 {
+        *self
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl PartialEq for SocketAddrV4 {
     fn eq(&self, other: &SocketAddrV4) -> bool {
-        self.inner.sin_port == other.inner.sin_port &&
-            self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
+        self.inner.sin_port == other.inner.sin_port
+            && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl PartialEq for SocketAddrV6 {
     fn eq(&self, other: &SocketAddrV6) -> bool {
-        self.inner.sin6_port == other.inner.sin6_port &&
-            self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
-            self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
-            self.inner.sin6_scope_id == other.inner.sin6_scope_id
+        self.inner.sin6_port == other.inner.sin6_port
+            && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
+            && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
+            && self.inner.sin6_scope_id == other.inner.sin6_scope_id
     }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -670,8 +673,13 @@ impl hash::Hash for SocketAddrV4 {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl hash::Hash for SocketAddrV6 {
     fn hash<H: hash::Hasher>(&self, s: &mut H) {
-        (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
-         self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
+        (
+            self.inner.sin6_port,
+            &self.inner.sin6_addr.s6_addr,
+            self.inner.sin6_flowinfo,
+            self.inner.sin6_scope_id,
+        )
+            .hash(s)
     }
 }
 
@@ -795,7 +803,7 @@ pub trait ToSocketAddrs {
     /// Returned iterator over socket addresses which this type may correspond
     /// to.
     #[stable(feature = "rust1", since = "1.0.0")]
-    type Iter: Iterator<Item=SocketAddr>;
+    type Iter: Iterator<Item = SocketAddr>;
 
     /// Converts this object to an iterator of resolved `SocketAddr`s.
     ///
@@ -864,7 +872,12 @@ impl ToSocketAddrs for (Ipv6Addr, u16) {
 
 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
     let p = lh.port();
-    let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect();
+    let v: Vec<_> = lh
+        .map(|mut a| {
+            a.set_port(p);
+            a
+        })
+        .collect();
     Ok(v.into_iter())
 }
 
@@ -877,11 +890,11 @@ impl ToSocketAddrs for (&str, u16) {
         // try to parse the host as a regular IP address first
         if let Ok(addr) = host.parse::<Ipv4Addr>() {
             let addr = SocketAddrV4::new(addr, port);
-            return Ok(vec![SocketAddr::V4(addr)].into_iter())
+            return Ok(vec![SocketAddr::V4(addr)].into_iter());
         }
         if let Ok(addr) = host.parse::<Ipv6Addr>() {
             let addr = SocketAddrV6::new(addr, port, 0, 0);
-            return Ok(vec![SocketAddr::V6(addr)].into_iter())
+            return Ok(vec![SocketAddr::V6(addr)].into_iter());
         }
 
         resolve_socket_addr((host, port).try_into()?)
@@ -929,8 +942,8 @@ impl ToSocketAddrs for String {
 
 #[cfg(all(test, not(target_os = "emscripten")))]
 mod tests {
+    use crate::net::test::{sa4, sa6, tsa};
     use crate::net::*;
-    use crate::net::test::{tsa, sa6, sa4};
 
     #[test]
     fn to_socket_addr_ipaddr_u16() {
@@ -991,8 +1004,12 @@ mod tests {
 
     #[test]
     fn set_ip() {
-        fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
-        fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
+        fn ip4(low: u8) -> Ipv4Addr {
+            Ipv4Addr::new(77, 88, 21, low)
+        }
+        fn ip6(low: u16) -> Ipv6Addr {
+            Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
+        }
 
         let mut v4 = SocketAddrV4::new(ip4(11), 80);
         assert_eq!(v4.ip(), &ip4(11));
@@ -1068,7 +1085,11 @@ mod tests {
     #[test]
     fn is_v6() {
         let v6 = SocketAddr::V6(SocketAddrV6::new(
-                Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
+            Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
+            80,
+            10,
+            0,
+        ));
         assert!(!v6.is_ipv4());
         assert!(v6.is_ipv6());
     }
diff --git a/src/libstd/net/parser.rs b/src/libstd/net/parser.rs
index 5a76139530a..8106d1c3315 100644
--- a/src/libstd/net/parser.rs
+++ b/src/libstd/net/parser.rs
@@ -16,10 +16,7 @@ struct Parser<'a> {
 
 impl<'a> Parser<'a> {
     fn new(s: &'a str) -> Parser<'a> {
-        Parser {
-            s: s.as_bytes(),
-            pos: 0,
-        }
+        Parser { s: s.as_bytes(), pos: 0 }
     }
 
     fn is_eof(&self) -> bool {
@@ -27,7 +24,8 @@ impl<'a> Parser<'a> {
     }
 
     // Commit only if parser returns Some
-    fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
+    fn read_atomically<T, F>(&mut self, cb: F) -> Option<T>
+    where
         F: FnOnce(&mut Parser<'_>) -> Option<T>,
     {
         let pos = self.pos;
@@ -39,17 +37,18 @@ impl<'a> Parser<'a> {
     }
 
     // Commit only if parser read till EOF
-    fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
+    fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T>
+    where
         F: FnOnce(&mut Parser<'_>) -> Option<T>,
     {
-        self.read_atomically(move |p| {
-            cb(p).filter(|_| p.is_eof())
-        })
+        self.read_atomically(move |p| cb(p).filter(|_| p.is_eof()))
     }
 
     // Return result of first successful parser
-    fn read_or<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser<'_>) -> Option<T> + 'static>])
-               -> Option<T> {
+    fn read_or<T>(
+        &mut self,
+        parsers: &mut [Box<dyn FnMut(&mut Parser<'_>) -> Option<T> + 'static>],
+    ) -> Option<T> {
         for pf in parsers {
             if let Some(r) = self.read_atomically(|p: &mut Parser<'_>| pf(p)) {
                 return Some(r);
@@ -59,11 +58,8 @@ impl<'a> Parser<'a> {
     }
 
     // Apply 3 parsers sequentially
-    fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
-                                       pa: PA,
-                                       pb: PB,
-                                       pc: PC)
-                                       -> Option<(A, B, C)> where
+    fn read_seq_3<A, B, C, PA, PB, PC>(&mut self, pa: PA, pb: PB, pc: PC) -> Option<(A, B, C)>
+    where
         PA: FnOnce(&mut Parser<'_>) -> Option<A>,
         PB: FnOnce(&mut Parser<'_>) -> Option<B>,
         PC: FnOnce(&mut Parser<'_>) -> Option<C>,
@@ -74,7 +70,7 @@ impl<'a> Parser<'a> {
             let c = if b.is_some() { pc(p) } else { None };
             match (a, b, c) {
                 (Some(a), Some(b), Some(c)) => Some((a, b, c)),
-                _ => None
+                _ => None,
             }
         })
     }
@@ -92,11 +88,9 @@ impl<'a> Parser<'a> {
 
     // Return char and advance iff next char is equal to requested
     fn read_given_char(&mut self, c: char) -> Option<char> {
-        self.read_atomically(|p| {
-            match p.read_char() {
-                Some(next) if next == c => Some(next),
-                _ => None,
-            }
+        self.read_atomically(|p| match p.read_char() {
+            Some(next) if next == c => Some(next),
+            _ => None,
         })
     }
 
@@ -116,9 +110,7 @@ impl<'a> Parser<'a> {
             }
         }
 
-        self.read_atomically(|p| {
-            p.read_char().and_then(|c| parse_digit(c, radix))
-        })
+        self.read_atomically(|p| p.read_char().and_then(|c| parse_digit(c, radix)))
     }
 
     fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
@@ -130,14 +122,14 @@ impl<'a> Parser<'a> {
                     r = r * (radix as u32) + (d as u32);
                     digit_count += 1;
                     if digit_count > max_digits || r >= upto {
-                        return None
+                        return None;
                     }
                 }
                 None => {
                     if digit_count == 0 {
-                        return None
+                        return None;
                     } else {
-                        return Some(r)
+                        return Some(r);
                     }
                 }
             };
@@ -173,12 +165,11 @@ impl<'a> Parser<'a> {
             assert!(head.len() + tail.len() <= 8);
             let mut gs = [0; 8];
             gs[..head.len()].copy_from_slice(head);
-            gs[(8 - tail.len()) .. 8].copy_from_slice(tail);
+            gs[(8 - tail.len())..8].copy_from_slice(tail);
             Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
         }
 
-        fn read_groups(p: &mut Parser<'_>, groups: &mut [u16; 8], limit: usize)
-                       -> (usize, bool) {
+        fn read_groups(p: &mut Parser<'_>, groups: &mut [u16; 8], limit: usize) -> (usize, bool) {
             let mut i = 0;
             while i < limit {
                 if i < limit - 1 {
@@ -206,7 +197,7 @@ impl<'a> Parser<'a> {
                 });
                 match group {
                     Some(g) => groups[i] = g,
-                    None => return (i, false)
+                    None => return (i, false),
                 }
                 i += 1;
             }
@@ -218,13 +209,13 @@ impl<'a> Parser<'a> {
 
         if head_size == 8 {
             return Some(Ipv6Addr::new(
-                head[0], head[1], head[2], head[3],
-                head[4], head[5], head[6], head[7]))
+                head[0], head[1], head[2], head[3], head[4], head[5], head[6], head[7],
+            ));
         }
 
         // IPv4 part is not allowed before `::`
         if head_ipv4 {
-            return None
+            return None;
         }
 
         // read `::` if previous code parsed less than 8 groups
@@ -252,9 +243,7 @@ impl<'a> Parser<'a> {
     fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
         let ip_addr = |p: &mut Parser<'_>| p.read_ipv4_addr();
         let colon = |p: &mut Parser<'_>| p.read_given_char(':');
-        let port = |p: &mut Parser<'_>| {
-            p.read_number(10, 5, 0x10000).map(|n| n as u16)
-        };
+        let port = |p: &mut Parser<'_>| p.read_number(10, 5, 0x10000).map(|n| n as u16);
 
         self.read_seq_3(ip_addr, colon, port).map(|t| {
             let (ip, _, port): (Ipv4Addr, char, u16) = t;
@@ -270,9 +259,7 @@ impl<'a> Parser<'a> {
             p.read_seq_3(open_br, ip_addr, clos_br).map(|t| t.1)
         };
         let colon = |p: &mut Parser<'_>| p.read_given_char(':');
-        let port = |p: &mut Parser<'_>| {
-            p.read_number(10, 5, 0x10000).map(|n| n as u16)
-        };
+        let port = |p: &mut Parser<'_>| p.read_number(10, 5, 0x10000).map(|n| n as u16);
 
         self.read_seq_3(ip_addr, colon, port).map(|t| {
             let (ip, _, port): (Ipv6Addr, char, u16) = t;
@@ -293,7 +280,7 @@ impl FromStr for IpAddr {
     fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
         match Parser::new(s).read_till_eof(|p| p.read_ip_addr()) {
             Some(s) => Ok(s),
-            None => Err(AddrParseError(()))
+            None => Err(AddrParseError(())),
         }
     }
 }
@@ -304,7 +291,7 @@ impl FromStr for Ipv4Addr {
     fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
         match Parser::new(s).read_till_eof(|p| p.read_ipv4_addr()) {
             Some(s) => Ok(s),
-            None => Err(AddrParseError(()))
+            None => Err(AddrParseError(())),
         }
     }
 }
@@ -315,7 +302,7 @@ impl FromStr for Ipv6Addr {
     fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
         match Parser::new(s).read_till_eof(|p| p.read_ipv6_addr()) {
             Some(s) => Ok(s),
-            None => Err(AddrParseError(()))
+            None => Err(AddrParseError(())),
         }
     }
 }
diff --git a/src/libstd/net/tcp.rs b/src/libstd/net/tcp.rs
index d8b6fb6da93..5c022159970 100644
--- a/src/libstd/net/tcp.rs
+++ b/src/libstd/net/tcp.rs
@@ -2,7 +2,7 @@ use crate::io::prelude::*;
 
 use crate::fmt;
 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
-use crate::net::{ToSocketAddrs, SocketAddr, Shutdown};
+use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
 use crate::sys_common::net as net_imp;
 use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::Duration;
@@ -93,7 +93,9 @@ pub struct TcpListener(net_imp::TcpListener);
 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
 #[stable(feature = "rust1", since = "1.0.0")]
 #[derive(Debug)]
-pub struct Incoming<'a> { listener: &'a TcpListener }
+pub struct Incoming<'a> {
+    listener: &'a TcpListener,
+}
 
 impl TcpStream {
     /// Opens a TCP connection to a remote host.
@@ -567,7 +569,9 @@ impl TcpStream {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Read for TcpStream {
-    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.0.read(buf)
+    }
 
     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
         self.0.read_vectored(bufs)
@@ -580,17 +584,23 @@ impl Read for TcpStream {
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Write for TcpStream {
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.0.write(buf)
+    }
 
     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
         self.0.write_vectored(bufs)
     }
 
-    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+    fn flush(&mut self) -> io::Result<()> {
+        Ok(())
+    }
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Read for &TcpStream {
-    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.0.read(buf)
+    }
 
     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
         self.0.read_vectored(bufs)
@@ -603,25 +613,35 @@ impl Read for &TcpStream {
 }
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Write for &TcpStream {
-    fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.0.write(buf)
+    }
 
     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
         self.0.write_vectored(bufs)
     }
 
-    fn flush(&mut self) -> io::Result<()> { Ok(()) }
+    fn flush(&mut self) -> io::Result<()> {
+        Ok(())
+    }
 }
 
 impl AsInner<net_imp::TcpStream> for TcpStream {
-    fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
+    fn as_inner(&self) -> &net_imp::TcpStream {
+        &self.0
+    }
 }
 
 impl FromInner<net_imp::TcpStream> for TcpStream {
-    fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
+    fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
+        TcpStream(inner)
+    }
 }
 
 impl IntoInner<net_imp::TcpStream> for TcpStream {
-    fn into_inner(self) -> net_imp::TcpStream { self.0 }
+    fn into_inner(self) -> net_imp::TcpStream {
+        self.0
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -814,16 +834,20 @@ impl TcpListener {
     }
 
     #[stable(feature = "net2_mutators", since = "1.9.0")]
-    #[rustc_deprecated(since = "1.16.0",
-                       reason = "this option can only be set before the socket is bound")]
+    #[rustc_deprecated(
+        since = "1.16.0",
+        reason = "this option can only be set before the socket is bound"
+    )]
     #[allow(missing_docs)]
     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
         self.0.set_only_v6(only_v6)
     }
 
     #[stable(feature = "net2_mutators", since = "1.9.0")]
-    #[rustc_deprecated(since = "1.16.0",
-                       reason = "this option can only be set before the socket is bound")]
+    #[rustc_deprecated(
+        since = "1.16.0",
+        reason = "this option can only be set before the socket is bound"
+    )]
     #[allow(missing_docs)]
     pub fn only_v6(&self) -> io::Result<bool> {
         self.0.only_v6()
@@ -907,7 +931,9 @@ impl<'a> Iterator for Incoming<'a> {
 }
 
 impl AsInner<net_imp::TcpListener> for TcpListener {
-    fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
+    fn as_inner(&self) -> &net_imp::TcpListener {
+        &self.0
+    }
 }
 
 impl FromInner<net_imp::TcpListener> for TcpListener {
@@ -917,7 +943,9 @@ impl FromInner<net_imp::TcpListener> for TcpListener {
 }
 
 impl IntoInner<net_imp::TcpListener> for TcpListener {
-    fn into_inner(self) -> net_imp::TcpListener { self.0 }
+    fn into_inner(self) -> net_imp::TcpListener {
+        self.0
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -930,13 +958,13 @@ impl fmt::Debug for TcpListener {
 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
 mod tests {
     use crate::fmt;
-    use crate::io::{ErrorKind, IoSlice, IoSliceMut};
     use crate::io::prelude::*;
-    use crate::net::*;
+    use crate::io::{ErrorKind, IoSlice, IoSliceMut};
     use crate::net::test::{next_test_ip4, next_test_ip6};
+    use crate::net::*;
     use crate::sync::mpsc::channel;
-    use crate::time::{Instant, Duration};
     use crate::thread;
+    use crate::time::{Duration, Instant};
 
     fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
         f(next_test_ip4());
@@ -949,15 +977,14 @@ mod tests {
                 Ok(t) => t,
                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
             }
-        }
+        };
     }
 
     #[test]
     fn bind_error() {
         match TcpListener::bind("1.1.1.1:9999") {
             Ok(..) => panic!(),
-            Err(e) =>
-                assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
+            Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
         }
     }
 
@@ -965,11 +992,15 @@ mod tests {
     fn connect_error() {
         match TcpStream::connect("0.0.0.0:1") {
             Ok(..) => panic!(),
-            Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
-                              e.kind() == ErrorKind::InvalidInput ||
-                              e.kind() == ErrorKind::AddrInUse ||
-                              e.kind() == ErrorKind::AddrNotAvailable,
-                              "bad error: {} {:?}", e, e.kind()),
+            Err(e) => assert!(
+                e.kind() == ErrorKind::ConnectionRefused
+                    || e.kind() == ErrorKind::InvalidInput
+                    || e.kind() == ErrorKind::AddrInUse
+                    || e.kind() == ErrorKind::AddrNotAvailable,
+                "bad error: {} {:?}",
+                e,
+                e.kind()
+            ),
         }
     }
 
@@ -979,8 +1010,7 @@ mod tests {
         let listener = t!(TcpListener::bind(&socket_addr));
 
         let _t = thread::spawn(move || {
-            let mut stream = t!(TcpStream::connect(&("localhost",
-                                                     socket_addr.port())));
+            let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
             t!(stream.write(&[144]));
         });
 
@@ -995,7 +1025,7 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let host = match addr {
                     SocketAddr::V4(..) => "127.0.0.1",
                     SocketAddr::V6(..) => "::1",
@@ -1017,7 +1047,7 @@ mod tests {
             let acceptor = t!(TcpListener::bind(&addr));
 
             let (tx, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut stream = t!(TcpStream::connect(&addr));
                 t!(stream.write(&[99]));
                 tx.send(t!(stream.local_addr())).unwrap();
@@ -1036,7 +1066,7 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _stream = t!(TcpStream::connect(&addr));
                 // Close
             });
@@ -1056,7 +1086,7 @@ mod tests {
             let acceptor = t!(TcpListener::bind(&addr));
 
             let (tx, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 drop(t!(TcpStream::connect(&addr)));
                 tx.send(()).unwrap();
             });
@@ -1067,10 +1097,13 @@ mod tests {
             match stream.write(&buf) {
                 Ok(..) => {}
                 Err(e) => {
-                    assert!(e.kind() == ErrorKind::ConnectionReset ||
-                            e.kind() == ErrorKind::BrokenPipe ||
-                            e.kind() == ErrorKind::ConnectionAborted,
-                            "unknown error: {}", e);
+                    assert!(
+                        e.kind() == ErrorKind::ConnectionReset
+                            || e.kind() == ErrorKind::BrokenPipe
+                            || e.kind() == ErrorKind::ConnectionAborted,
+                        "unknown error: {}",
+                        e
+                    );
                 }
             }
         })
@@ -1082,7 +1115,7 @@ mod tests {
             let max = 10;
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 for _ in 0..max {
                     let mut stream = t!(TcpStream::connect(&addr));
                     t!(stream.write(&[99]));
@@ -1104,11 +1137,11 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let acceptor = acceptor;
                 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
                     // Start another thread to handle the connection
-                    let _t = thread::spawn(move|| {
+                    let _t = thread::spawn(move || {
                         let mut stream = t!(stream);
                         let mut buf = [0];
                         t!(stream.read(&mut buf));
@@ -1121,9 +1154,11 @@ mod tests {
         });
 
         fn connect(i: usize, addr: SocketAddr) {
-            if i == MAX { return }
+            if i == MAX {
+                return;
+            }
 
-            let t = thread::spawn(move|| {
+            let t = thread::spawn(move || {
                 let mut stream = t!(TcpStream::connect(&addr));
                 // Connect again before writing
                 connect(i + 1, addr);
@@ -1139,10 +1174,10 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 for stream in acceptor.incoming().take(MAX) {
                     // Start another thread to handle the connection
-                    let _t = thread::spawn(move|| {
+                    let _t = thread::spawn(move || {
                         let mut stream = t!(stream);
                         let mut buf = [0];
                         t!(stream.read(&mut buf));
@@ -1155,9 +1190,11 @@ mod tests {
         });
 
         fn connect(i: usize, addr: SocketAddr) {
-            if i == MAX { return }
+            if i == MAX {
+                return;
+            }
 
-            let t = thread::spawn(move|| {
+            let t = thread::spawn(move || {
                 let mut stream = t!(TcpStream::connect(&addr));
                 connect(i + 1, addr);
                 t!(stream.write(&[99]));
@@ -1172,7 +1209,7 @@ mod tests {
             let listener = t!(TcpListener::bind(&addr));
             let so_name = t!(listener.local_addr());
             assert_eq!(addr, so_name);
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 t!(listener.accept());
             });
 
@@ -1186,7 +1223,7 @@ mod tests {
         each_ip(&mut |addr| {
             let (tx, rx) = channel();
             let srv = t!(TcpListener::bind(&addr));
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut cl = t!(srv.accept()).0;
                 cl.write(&[10]).unwrap();
                 let mut b = [0];
@@ -1215,9 +1252,11 @@ mod tests {
             let mut a = [];
             let mut b = [0];
             let mut c = [0; 3];
-            let len = t!(s2.read_vectored(
-                &mut [IoSliceMut::new(&mut a), IoSliceMut::new(&mut b), IoSliceMut::new(&mut c)],
-            ));
+            let len = t!(s2.read_vectored(&mut [
+                IoSliceMut::new(&mut a),
+                IoSliceMut::new(&mut b),
+                IoSliceMut::new(&mut c)
+            ],));
             assert!(len > 0);
             assert_eq!(b, [10]);
             // some implementations don't support readv, so we may only fill the first buffer
@@ -1260,10 +1299,14 @@ mod tests {
                     listener1, listener2
                 ),
                 Err(e) => {
-                    assert!(e.kind() == ErrorKind::ConnectionRefused ||
-                            e.kind() == ErrorKind::Other ||
-                            e.kind() == ErrorKind::AddrInUse,
-                            "unknown error: {} {:?}", e, e.kind());
+                    assert!(
+                        e.kind() == ErrorKind::ConnectionRefused
+                            || e.kind() == ErrorKind::Other
+                            || e.kind() == ErrorKind::AddrInUse,
+                        "unknown error: {} {:?}",
+                        e,
+                        e.kind()
+                    );
                 }
             }
         })
@@ -1274,7 +1317,7 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 t!(TcpStream::connect(&addr));
             });
 
@@ -1289,7 +1332,7 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s = t!(TcpStream::connect(&addr));
                 let mut buf = [0, 0];
                 assert_eq!(s.read(&mut buf).unwrap(), 1);
@@ -1302,7 +1345,7 @@ mod tests {
 
             let (tx1, rx1) = channel();
             let (tx2, rx2) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s2 = s2;
                 rx1.recv().unwrap();
                 t!(s2.write(&[1]));
@@ -1322,7 +1365,7 @@ mod tests {
             let (tx1, rx) = channel();
             let tx2 = tx1.clone();
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s = t!(TcpStream::connect(&addr));
                 t!(s.write(&[1]));
                 rx.recv().unwrap();
@@ -1334,7 +1377,7 @@ mod tests {
             let s2 = t!(s1.try_clone());
 
             let (done, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s2 = s2;
                 let mut buf = [0, 0];
                 t!(s2.read(&mut buf));
@@ -1354,7 +1397,7 @@ mod tests {
         each_ip(&mut |addr| {
             let acceptor = t!(TcpListener::bind(&addr));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s = t!(TcpStream::connect(&addr));
                 let mut buf = [0, 1];
                 t!(s.read(&mut buf));
@@ -1365,7 +1408,7 @@ mod tests {
             let s2 = t!(s1.try_clone());
 
             let (done, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s2 = s2;
                 t!(s2.write(&[1]));
                 done.send(()).unwrap();
@@ -1382,7 +1425,7 @@ mod tests {
     fn shutdown_smoke() {
         each_ip(&mut |addr| {
             let a = t!(TcpListener::bind(&addr));
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut c = t!(a.accept()).0;
                 let mut b = [0];
                 assert_eq!(c.read(&mut b).unwrap(), 0);
@@ -1405,7 +1448,7 @@ mod tests {
         each_ip(&mut |addr| {
             let a = t!(TcpListener::bind(&addr));
             let (tx, rx) = channel::<()>();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _s = t!(a.accept());
                 let _ = rx.recv();
             });
@@ -1444,7 +1487,7 @@ mod tests {
         each_ip(&mut |addr| {
             let a = t!(TcpListener::bind(&addr));
             let (tx1, rx) = channel::<()>();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _s = t!(a.accept());
                 let _ = rx.recv();
             });
@@ -1452,7 +1495,7 @@ mod tests {
             let s = t!(TcpStream::connect(&addr));
             let s2 = t!(s.try_clone());
             let (tx, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut s2 = s2;
                 assert_eq!(t!(s2.read(&mut [0])), 0);
                 tx.send(()).unwrap();
@@ -1475,7 +1518,7 @@ mod tests {
             let (tx, rx) = channel();
             let (txdone, rxdone) = channel();
             let txdone2 = txdone.clone();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut tcp = t!(TcpStream::connect(&addr));
                 rx.recv().unwrap();
                 t!(tcp.write(&[0]));
@@ -1486,7 +1529,7 @@ mod tests {
             let tcp = t!(accept.accept()).0;
             let tcp2 = t!(tcp.try_clone());
             let txdone3 = txdone.clone();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut tcp2 = tcp2;
                 t!(tcp2.read(&mut [0]));
                 txdone3.send(()).unwrap();
@@ -1512,10 +1555,10 @@ mod tests {
             let a = t!(TcpListener::bind(&addr));
             let a2 = t!(a.try_clone());
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _ = TcpStream::connect(&addr);
             });
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _ = TcpStream::connect(&addr);
             });
 
@@ -1533,17 +1576,17 @@ mod tests {
             let (tx, rx) = channel();
             let tx2 = tx.clone();
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 tx.send(t!(a.accept())).unwrap();
             });
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 tx2.send(t!(a2.accept())).unwrap();
             });
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _ = TcpStream::connect(&addr);
             });
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let _ = TcpStream::connect(&addr);
             });
 
@@ -1563,10 +1606,10 @@ mod tests {
             addr.to_string()
         }
 
-        #[cfg(unix)]
-        use crate::os::unix::io::AsRawFd;
         #[cfg(target_env = "sgx")]
         use crate::os::fortanix_sgx::io::AsRawFd;
+        #[cfg(unix)]
+        use crate::os::unix::io::AsRawFd;
         #[cfg(not(windows))]
         fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
             addr.as_raw_fd()
@@ -1576,22 +1619,26 @@ mod tests {
             addr.as_raw_socket()
         }
 
-        let inner_name = if cfg!(windows) {"socket"} else {"fd"};
+        let inner_name = if cfg!(windows) { "socket" } else { "fd" };
         let socket_addr = next_test_ip4();
 
         let listener = t!(TcpListener::bind(&socket_addr));
-        let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
-                              render_socket_addr(&socket_addr),
-                              inner_name,
-                              render_inner(&listener));
+        let compare = format!(
+            "TcpListener {{ addr: {:?}, {}: {:?} }}",
+            render_socket_addr(&socket_addr),
+            inner_name,
+            render_inner(&listener)
+        );
         assert_eq!(format!("{:?}", listener), compare);
 
         let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
-        let compare = format!("TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
-                              render_socket_addr(&stream.local_addr().unwrap()),
-                              render_socket_addr(&stream.peer_addr().unwrap()),
-                              inner_name,
-                              render_inner(&stream));
+        let compare = format!(
+            "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
+            render_socket_addr(&stream.local_addr().unwrap()),
+            render_socket_addr(&stream.peer_addr().unwrap()),
+            inner_name,
+            render_inner(&stream)
+        );
         assert_eq!(format!("{:?}", stream), compare);
     }
 
@@ -1638,8 +1685,11 @@ mod tests {
         let mut buf = [0; 10];
         let start = Instant::now();
         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
-        assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
-                "unexpected_error: {:?}", kind);
+        assert!(
+            kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
+            "unexpected_error: {:?}",
+            kind
+        );
         assert!(start.elapsed() > Duration::from_millis(400));
         drop(listener);
     }
@@ -1662,8 +1712,11 @@ mod tests {
 
         let start = Instant::now();
         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
-        assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
-                "unexpected_error: {:?}", kind);
+        assert!(
+            kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
+            "unexpected_error: {:?}",
+            kind
+        );
         assert!(start.elapsed() > Duration::from_millis(400));
         drop(listener);
     }
@@ -1749,9 +1802,9 @@ mod tests {
             let (txdone, rxdone) = channel();
 
             let srv = t!(TcpListener::bind(&addr));
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut cl = t!(srv.accept()).0;
-                cl.write(&[1,3,3,7]).unwrap();
+                cl.write(&[1, 3, 3, 7]).unwrap();
                 t!(rxdone.recv());
             });
 
diff --git a/src/libstd/net/test.rs b/src/libstd/net/test.rs
index e2991cbdd88..37937b5ea95 100644
--- a/src/libstd/net/test.rs
+++ b/src/libstd/net/test.rs
@@ -1,7 +1,7 @@
 #![allow(warnings)] // not used on emscripten
 
 use crate::env;
-use crate::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
+use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
 use crate::sync::atomic::{AtomicUsize, Ordering};
 
 static PORT: AtomicUsize = AtomicUsize::new(0);
@@ -13,8 +13,7 @@ pub fn next_test_ip4() -> SocketAddr {
 
 pub fn next_test_ip6() -> SocketAddr {
     let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
-    SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
-                                     port, 0, 0))
+    SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), port, 0, 0))
 }
 
 pub fn sa4(a: Ipv4Addr, p: u16) -> SocketAddr {
@@ -41,11 +40,21 @@ fn base_port() -> u16 {
     } else {
         env::current_dir().unwrap().into_os_string().into_string().unwrap()
     };
-    let dirs = ["32-opt", "32-nopt",
-                "musl-64-opt", "cross-opt",
-                "64-opt", "64-nopt", "64-opt-vg", "64-debug-opt",
-                "all-opt", "snap3", "dist", "sgx"];
-    dirs.iter().enumerate().find(|&(_, dir)| {
-        cwd.contains(dir)
-    }).map(|p| p.0).unwrap_or(0) as u16 * 1000 + 19600
+    let dirs = [
+        "32-opt",
+        "32-nopt",
+        "musl-64-opt",
+        "cross-opt",
+        "64-opt",
+        "64-nopt",
+        "64-opt-vg",
+        "64-debug-opt",
+        "all-opt",
+        "snap3",
+        "dist",
+        "sgx",
+    ];
+    dirs.iter().enumerate().find(|&(_, dir)| cwd.contains(dir)).map(|p| p.0).unwrap_or(0) as u16
+        * 1000
+        + 19600
 }
diff --git a/src/libstd/net/udp.rs b/src/libstd/net/udp.rs
index a9e4457f423..0096b827ca4 100644
--- a/src/libstd/net/udp.rs
+++ b/src/libstd/net/udp.rs
@@ -1,6 +1,6 @@
 use crate::fmt;
 use crate::io::{self, Error, ErrorKind};
-use crate::net::{ToSocketAddrs, SocketAddr, Ipv4Addr, Ipv6Addr};
+use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
 use crate::sys_common::net as net_imp;
 use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::Duration;
@@ -171,12 +171,10 @@ impl UdpSocket {
     /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
-                                     -> io::Result<usize> {
+    pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
         match addr.to_socket_addrs()?.next() {
             Some(addr) => self.0.send_to(buf, &addr),
-            None => Err(Error::new(ErrorKind::InvalidInput,
-                                   "no addresses to send data to")),
+            None => Err(Error::new(ErrorKind::InvalidInput, "no addresses to send data to")),
         }
     }
 
@@ -817,15 +815,21 @@ impl UdpSocket {
 }
 
 impl AsInner<net_imp::UdpSocket> for UdpSocket {
-    fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
+    fn as_inner(&self) -> &net_imp::UdpSocket {
+        &self.0
+    }
 }
 
 impl FromInner<net_imp::UdpSocket> for UdpSocket {
-    fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
+    fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
+        UdpSocket(inner)
+    }
 }
 
 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
-    fn into_inner(self) -> net_imp::UdpSocket { self.0 }
+    fn into_inner(self) -> net_imp::UdpSocket {
+        self.0
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -838,12 +842,12 @@ impl fmt::Debug for UdpSocket {
 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
 mod tests {
     use crate::io::ErrorKind;
-    use crate::net::*;
     use crate::net::test::{next_test_ip4, next_test_ip6};
+    use crate::net::*;
     use crate::sync::mpsc::channel;
     use crate::sys_common::AsInner;
-    use crate::time::{Instant, Duration};
     use crate::thread;
+    use crate::time::{Duration, Instant};
 
     fn each_ip(f: &mut dyn FnMut(SocketAddr, SocketAddr)) {
         f(next_test_ip4(), next_test_ip4());
@@ -856,16 +860,14 @@ mod tests {
                 Ok(t) => t,
                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
             }
-        }
+        };
     }
 
     #[test]
     fn bind_error() {
         match UdpSocket::bind("1.1.1.1:9999") {
             Ok(..) => panic!(),
-            Err(e) => {
-                assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
-            }
+            Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
         }
     }
 
@@ -875,7 +877,7 @@ mod tests {
             let (tx1, rx1) = channel();
             let (tx2, rx2) = channel();
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let client = t!(UdpSocket::bind(&client_ip));
                 rx1.recv().unwrap();
                 t!(client.send_to(&[99], &server_ip));
@@ -917,7 +919,7 @@ mod tests {
             let sock1 = t!(UdpSocket::bind(&addr1));
             let sock2 = t!(UdpSocket::bind(&addr2));
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut buf = [0, 0];
                 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
                 assert_eq!(buf[0], 1);
@@ -928,7 +930,7 @@ mod tests {
 
             let (tx1, rx1) = channel();
             let (tx2, rx2) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 rx1.recv().unwrap();
                 t!(sock3.send_to(&[1], &addr2));
                 tx2.send(()).unwrap();
@@ -948,7 +950,7 @@ mod tests {
             let (tx1, rx) = channel();
             let tx2 = tx1.clone();
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 t!(sock2.send_to(&[1], &addr1));
                 rx.recv().unwrap();
                 t!(sock2.send_to(&[2], &addr1));
@@ -958,7 +960,7 @@ mod tests {
             let sock3 = t!(sock1.try_clone());
 
             let (done, rx) = channel();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut buf = [0, 0];
                 t!(sock3.recv_from(&mut buf));
                 tx2.send(()).unwrap();
@@ -981,7 +983,7 @@ mod tests {
             let (tx, rx) = channel();
             let (serv_tx, serv_rx) = channel();
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 let mut buf = [0, 1];
                 rx.recv().unwrap();
                 t!(sock2.recv_from(&mut buf));
@@ -992,15 +994,19 @@ mod tests {
 
             let (done, rx) = channel();
             let tx2 = tx.clone();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 match sock3.send_to(&[1], &addr2) {
-                    Ok(..) => { let _ = tx2.send(()); }
+                    Ok(..) => {
+                        let _ = tx2.send(());
+                    }
                     Err(..) => {}
                 }
                 done.send(()).unwrap();
             });
             match sock1.send_to(&[2], &addr2) {
-                Ok(..) => { let _ = tx.send(()); }
+                Ok(..) => {
+                    let _ = tx.send(());
+                }
                 Err(..) => {}
             }
             drop(tx);
@@ -1012,13 +1018,13 @@ mod tests {
 
     #[test]
     fn debug() {
-        let name = if cfg!(windows) {"socket"} else {"fd"};
+        let name = if cfg!(windows) { "socket" } else { "fd" };
         let socket_addr = next_test_ip4();
 
         let udpsock = t!(UdpSocket::bind(&socket_addr));
         let udpsock_inner = udpsock.0.socket().as_inner();
-        let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
-                              socket_addr, name, udpsock_inner);
+        let compare =
+            format!("UdpSocket {{ addr: {:?}, {}: {:?} }}", socket_addr, name, udpsock_inner);
         assert_eq!(format!("{:?}", udpsock), compare);
     }
 
@@ -1063,8 +1069,11 @@ mod tests {
         loop {
             let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
             if kind != ErrorKind::Interrupted {
-                assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
-                        "unexpected_error: {:?}", kind);
+                assert!(
+                    kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
+                    "unexpected_error: {:?}",
+                    kind
+                );
                 break;
             }
         }
@@ -1088,8 +1097,11 @@ mod tests {
         loop {
             let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
             if kind != ErrorKind::Interrupted {
-                assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
-                        "unexpected_error: {:?}", kind);
+                assert!(
+                    kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
+                    "unexpected_error: {:?}",
+                    kind
+                );
                 break;
             }
         }
diff --git a/src/libstd/num.rs b/src/libstd/num.rs
index 2a2ca0b5237..de8acf8d9d4 100644
--- a/src/libstd/num.rs
+++ b/src/libstd/num.rs
@@ -7,56 +7,64 @@
 #![allow(missing_docs)]
 
 #[stable(feature = "rust1", since = "1.0.0")]
-pub use core::num::{FpCategory, ParseIntError, ParseFloatError, TryFromIntError};
-#[stable(feature = "rust1", since = "1.0.0")]
 pub use core::num::Wrapping;
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError};
 
-#[stable(feature = "nonzero", since = "1.28.0")]
-pub use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
 #[stable(feature = "signed_nonzero", since = "1.34.0")]
-pub use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
-
-#[unstable(feature = "int_error_matching",
-           reason = "it can be useful to match errors when making error messages \
-                     for integer parsing",
-           issue = "22639")]
+pub use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
+#[stable(feature = "nonzero", since = "1.28.0")]
+pub use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
+
+#[unstable(
+    feature = "int_error_matching",
+    reason = "it can be useful to match errors when making error messages \
+              for integer parsing",
+    issue = "22639"
+)]
 pub use core::num::IntErrorKind;
 
-#[cfg(test)] use crate::fmt;
-#[cfg(test)] use crate::ops::{Add, Sub, Mul, Div, Rem};
+#[cfg(test)]
+use crate::fmt;
+#[cfg(test)]
+use crate::ops::{Add, Div, Mul, Rem, Sub};
 
 /// Helper function for testing numeric operations
 #[cfg(test)]
-pub fn test_num<T>(ten: T, two: T) where
+pub fn test_num<T>(ten: T, two: T)
+where
     T: PartialEq
-     + Add<Output=T> + Sub<Output=T>
-     + Mul<Output=T> + Div<Output=T>
-     + Rem<Output=T> + fmt::Debug
-     + Copy
+        + Add<Output = T>
+        + Sub<Output = T>
+        + Mul<Output = T>
+        + Div<Output = T>
+        + Rem<Output = T>
+        + fmt::Debug
+        + Copy,
 {
-    assert_eq!(ten.add(two),  ten + two);
-    assert_eq!(ten.sub(two),  ten - two);
-    assert_eq!(ten.mul(two),  ten * two);
-    assert_eq!(ten.div(two),  ten / two);
-    assert_eq!(ten.rem(two),  ten % two);
+    assert_eq!(ten.add(two), ten + two);
+    assert_eq!(ten.sub(two), ten - two);
+    assert_eq!(ten.mul(two), ten * two);
+    assert_eq!(ten.div(two), ten / two);
+    assert_eq!(ten.rem(two), ten % two);
 }
 
 #[cfg(test)]
 mod tests {
-    use crate::u8;
+    use crate::ops::Mul;
     use crate::u16;
     use crate::u32;
     use crate::u64;
+    use crate::u8;
     use crate::usize;
-    use crate::ops::Mul;
 
     #[test]
     fn test_saturating_add_uint() {
         use crate::usize::MAX;
         assert_eq!(3_usize.saturating_add(5_usize), 8_usize);
-        assert_eq!(3_usize.saturating_add(MAX-1), MAX);
+        assert_eq!(3_usize.saturating_add(MAX - 1), MAX);
         assert_eq!(MAX.saturating_add(MAX), MAX);
-        assert_eq!((MAX-2).saturating_add(1), MAX-1);
+        assert_eq!((MAX - 2).saturating_add(1), MAX - 1);
     }
 
     #[test]
@@ -65,16 +73,16 @@ mod tests {
         assert_eq!(5_usize.saturating_sub(3_usize), 2_usize);
         assert_eq!(3_usize.saturating_sub(5_usize), 0_usize);
         assert_eq!(0_usize.saturating_sub(1_usize), 0_usize);
-        assert_eq!((MAX-1).saturating_sub(MAX), 0);
+        assert_eq!((MAX - 1).saturating_sub(MAX), 0);
     }
 
     #[test]
     fn test_saturating_add_int() {
-        use crate::isize::{MIN,MAX};
+        use crate::isize::{MAX, MIN};
         assert_eq!(3i32.saturating_add(5), 8);
-        assert_eq!(3isize.saturating_add(MAX-1), MAX);
+        assert_eq!(3isize.saturating_add(MAX - 1), MAX);
         assert_eq!(MAX.saturating_add(MAX), MAX);
-        assert_eq!((MAX-2).saturating_add(1), MAX-1);
+        assert_eq!((MAX - 2).saturating_add(1), MAX - 1);
         assert_eq!(3i32.saturating_add(-5), -2);
         assert_eq!(MIN.saturating_add(-1), MIN);
         assert_eq!((-2isize).saturating_add(-MAX), MIN);
@@ -82,14 +90,14 @@ mod tests {
 
     #[test]
     fn test_saturating_sub_int() {
-        use crate::isize::{MIN,MAX};
+        use crate::isize::{MAX, MIN};
         assert_eq!(3i32.saturating_sub(5), -2);
         assert_eq!(MIN.saturating_sub(1), MIN);
         assert_eq!((-2isize).saturating_sub(MAX), MIN);
         assert_eq!(3i32.saturating_sub(-5), 8);
-        assert_eq!(3isize.saturating_sub(-(MAX-1)), MAX);
+        assert_eq!(3isize.saturating_sub(-(MAX - 1)), MAX);
         assert_eq!(MAX.saturating_sub(-MAX), MAX);
-        assert_eq!((MAX-2).saturating_sub(-1), MAX-1);
+        assert_eq!((MAX - 2).saturating_sub(-1), MAX - 1);
     }
 
     #[test]
@@ -128,7 +136,7 @@ mod tests {
     }
 
     macro_rules! test_is_power_of_two {
-        ($test_name:ident, $T:ident) => (
+        ($test_name:ident, $T:ident) => {
             fn $test_name() {
                 #![test]
                 assert_eq!((0 as $T).is_power_of_two(), false);
@@ -139,27 +147,29 @@ mod tests {
                 assert_eq!((5 as $T).is_power_of_two(), false);
                 assert_eq!(($T::MAX / 2 + 1).is_power_of_two(), true);
             }
-        )
+        };
     }
 
-    test_is_power_of_two!{ test_is_power_of_two_u8, u8 }
-    test_is_power_of_two!{ test_is_power_of_two_u16, u16 }
-    test_is_power_of_two!{ test_is_power_of_two_u32, u32 }
-    test_is_power_of_two!{ test_is_power_of_two_u64, u64 }
-    test_is_power_of_two!{ test_is_power_of_two_uint, usize }
+    test_is_power_of_two! { test_is_power_of_two_u8, u8 }
+    test_is_power_of_two! { test_is_power_of_two_u16, u16 }
+    test_is_power_of_two! { test_is_power_of_two_u32, u32 }
+    test_is_power_of_two! { test_is_power_of_two_u64, u64 }
+    test_is_power_of_two! { test_is_power_of_two_uint, usize }
 
     macro_rules! test_next_power_of_two {
-        ($test_name:ident, $T:ident) => (
+        ($test_name:ident, $T:ident) => {
             fn $test_name() {
                 #![test]
                 assert_eq!((0 as $T).next_power_of_two(), 1);
                 let mut next_power = 1;
                 for i in 1 as $T..40 {
-                     assert_eq!(i.next_power_of_two(), next_power);
-                     if i == next_power { next_power *= 2 }
+                    assert_eq!(i.next_power_of_two(), next_power);
+                    if i == next_power {
+                        next_power *= 2
+                    }
                 }
             }
-        )
+        };
     }
 
     test_next_power_of_two! { test_next_power_of_two_u8, u8 }
@@ -169,23 +179,25 @@ mod tests {
     test_next_power_of_two! { test_next_power_of_two_uint, usize }
 
     macro_rules! test_checked_next_power_of_two {
-        ($test_name:ident, $T:ident) => (
+        ($test_name:ident, $T:ident) => {
             fn $test_name() {
                 #![test]
                 assert_eq!((0 as $T).checked_next_power_of_two(), Some(1));
                 let smax = $T::MAX >> 1;
-                assert_eq!(smax.checked_next_power_of_two(), Some(smax+1));
+                assert_eq!(smax.checked_next_power_of_two(), Some(smax + 1));
                 assert_eq!((smax + 1).checked_next_power_of_two(), Some(smax + 1));
                 assert_eq!((smax + 2).checked_next_power_of_two(), None);
                 assert_eq!(($T::MAX - 1).checked_next_power_of_two(), None);
                 assert_eq!($T::MAX.checked_next_power_of_two(), None);
                 let mut next_power = 1;
                 for i in 1 as $T..40 {
-                     assert_eq!(i.checked_next_power_of_two(), Some(next_power));
-                     if i == next_power { next_power *= 2 }
+                    assert_eq!(i.checked_next_power_of_two(), Some(next_power));
+                    if i == next_power {
+                        next_power *= 2
+                    }
                 }
             }
-        )
+        };
     }
 
     test_checked_next_power_of_two! { test_checked_next_power_of_two_u8, u8 }
@@ -196,7 +208,7 @@ mod tests {
 
     #[test]
     fn test_pow() {
-        fn naive_pow<T: Mul<Output=T> + Copy>(one: T, base: T, exp: usize) -> T {
+        fn naive_pow<T: Mul<Output = T> + Copy>(one: T, base: T, exp: usize) -> T {
             (0..exp).fold(one, |acc, _| acc * base)
         }
         macro_rules! assert_pow {
@@ -204,7 +216,7 @@ mod tests {
                 let result = $num.pow($exp);
                 assert_eq!(result, $expected);
                 assert_eq!(result, naive_pow(1, $num, $exp));
-            }}
+            }};
         }
         assert_pow!((3u32,     0 ) => 1);
         assert_pow!((5u32,     1 ) => 5);
@@ -280,7 +292,6 @@ mod tests {
     }
 }
 
-
 #[cfg(test)]
 mod bench {
     use test::Bencher;
@@ -288,6 +299,8 @@ mod bench {
     #[bench]
     fn bench_pow_function(b: &mut Bencher) {
         let v = (0..1024).collect::<Vec<u32>>();
-        b.iter(|| {v.iter().fold(0u32, |old, new| old.pow(*new as u32));});
+        b.iter(|| {
+            v.iter().fold(0u32, |old, new| old.pow(*new as u32));
+        });
     }
 }
diff --git a/src/libstd/os/android/fs.rs b/src/libstd/os/android/fs.rs
index 90fdee567ae..9356e607c90 100644
--- a/src/libstd/os/android/fs.rs
+++ b/src/libstd/os/android/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -62,10 +64,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/android/mod.rs b/src/libstd/os/android/mod.rs
index ad1cd85095d..dbb0127f369 100644
--- a/src/libstd/os/android/mod.rs
+++ b/src/libstd/os/android/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/android/raw.rs b/src/libstd/os/android/raw.rs
index 946a77cbfd3..2b8ade8a82e 100644
--- a/src/libstd/os/android/raw.rs
+++ b/src/libstd/os/android/raw.rs
@@ -1,11 +1,13 @@
 //! Android-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
@@ -15,12 +17,12 @@ pub type pthread_t = c_long;
 
 #[doc(inline)]
 #[stable(feature = "raw_ext", since = "1.1.0")]
-pub use self::arch::{dev_t, mode_t, blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
+pub use self::arch::{blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t, stat, time_t};
 
 #[cfg(any(target_arch = "arm", target_arch = "x86"))]
 mod arch {
-    use crate::os::raw::{c_uint, c_uchar, c_ulonglong, c_longlong, c_ulong};
-    use crate::os::unix::raw::{uid_t, gid_t};
+    use crate::os::raw::{c_longlong, c_uchar, c_uint, c_ulong, c_ulonglong};
+    use crate::os::unix::raw::{gid_t, uid_t};
 
     #[stable(feature = "raw_ext", since = "1.1.0")]
     pub type dev_t = u64;
@@ -83,14 +85,12 @@ mod arch {
         #[stable(feature = "raw_ext", since = "1.1.0")]
         pub st_ino: c_ulonglong,
     }
-
 }
 
-
 #[cfg(target_arch = "aarch64")]
 mod arch {
     use crate::os::raw::{c_uchar, c_ulong};
-    use crate::os::unix::raw::{uid_t, gid_t};
+    use crate::os::unix::raw::{gid_t, uid_t};
 
     #[stable(feature = "raw_ext", since = "1.1.0")]
     pub type dev_t = u64;
@@ -157,8 +157,8 @@ mod arch {
 
 #[cfg(target_arch = "x86_64")]
 mod arch {
-    use crate::os::raw::{c_uint, c_long, c_ulong};
-    use crate::os::unix::raw::{uid_t, gid_t};
+    use crate::os::raw::{c_long, c_uint, c_ulong};
+    use crate::os::unix::raw::{gid_t, uid_t};
 
     #[stable(feature = "raw_ext", since = "1.1.0")]
     pub type dev_t = u64;
diff --git a/src/libstd/os/dragonfly/fs.rs b/src/libstd/os/dragonfly/fs.rs
index ba3d8d7867d..8552abb1cb9 100644
--- a/src/libstd/os/dragonfly/fs.rs
+++ b/src/libstd/os/dragonfly/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -68,10 +70,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/dragonfly/mod.rs b/src/libstd/os/dragonfly/mod.rs
index c8df03e742f..350b5fca7ea 100644
--- a/src/libstd/os/dragonfly/mod.rs
+++ b/src/libstd/os/dragonfly/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/dragonfly/raw.rs b/src/libstd/os/dragonfly/raw.rs
index 46ef5a1e7cf..2a2d2904372 100644
--- a/src/libstd/os/dragonfly/raw.rs
+++ b/src/libstd/os/dragonfly/raw.rs
@@ -1,24 +1,35 @@
 //! Dragonfly-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type fflags_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/emscripten/fs.rs b/src/libstd/os/emscripten/fs.rs
index aa6aa38283d..f5e30dc8eef 100644
--- a/src/libstd/os/emscripten/fs.rs
+++ b/src/libstd/os/emscripten/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -62,10 +64,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat64
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat64 as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/emscripten/mod.rs b/src/libstd/os/emscripten/mod.rs
index 3111325021a..d35307162cc 100644
--- a/src/libstd/os/emscripten/mod.rs
+++ b/src/libstd/os/emscripten/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/emscripten/raw.rs b/src/libstd/os/emscripten/raw.rs
index e5513487979..dda7c82525d 100644
--- a/src/libstd/os/emscripten/raw.rs
+++ b/src/libstd/os/emscripten/raw.rs
@@ -3,28 +3,38 @@
 //! except using the musl-specific stat64 structure in liblibc.
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::{c_long, c_short, c_uint, c_ulong};
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = c_ulong;
 
 #[doc(inline)]
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = c_long;
 
 #[repr(C)]
 #[derive(Clone)]
diff --git a/src/libstd/os/fortanix_sgx/mod.rs b/src/libstd/os/fortanix_sgx/mod.rs
index 4e30b1edd15..69923268e57 100644
--- a/src/libstd/os/fortanix_sgx/mod.rs
+++ b/src/libstd/os/fortanix_sgx/mod.rs
@@ -21,19 +21,20 @@ pub mod usercalls {
 
     /// Lowest-level interfaces to usercalls and usercall ABI type definitions.
     pub mod raw {
+        pub use crate::sys::abi::usercalls::raw::{
+            accept_stream, alloc, async_queues, bind_stream, close, connect_stream, exit, flush,
+            free, insecure_time, launch_thread, read, read_alloc, send, wait, write,
+        };
         pub use crate::sys::abi::usercalls::raw::{do_usercall, Usercalls as UsercallNrs};
-        pub use crate::sys::abi::usercalls::raw::{accept_stream, alloc, async_queues, bind_stream,
-                                           close, connect_stream, exit, flush, free, insecure_time,
-                                           launch_thread, read, read_alloc, send, wait, write};
 
         // fortanix-sgx-abi re-exports
-        pub use crate::sys::abi::usercalls::raw::{ByteBuffer, FifoDescriptor, Return, Usercall};
         pub use crate::sys::abi::usercalls::raw::Error;
-        pub use crate::sys::abi::usercalls::raw::{EV_RETURNQ_NOT_EMPTY, EV_UNPARK,
-                                           EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT,
-                                           RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE,
-                                           WAIT_NO};
+        pub use crate::sys::abi::usercalls::raw::{ByteBuffer, FifoDescriptor, Return, Usercall};
         pub use crate::sys::abi::usercalls::raw::{Fd, Result, Tcs};
+        pub use crate::sys::abi::usercalls::raw::{
+            EV_RETURNQ_NOT_EMPTY, EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT,
+            RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO,
+        };
     }
 }
 
@@ -42,7 +43,7 @@ pub mod mem {
     pub use crate::sys::abi::mem::*;
 }
 
-pub use crate::sys::ext::{io, arch, ffi};
+pub use crate::sys::ext::{arch, ffi, io};
 
 /// Functions for querying thread-related information.
 pub mod thread {
diff --git a/src/libstd/os/freebsd/fs.rs b/src/libstd/os/freebsd/fs.rs
index cfe8d575c67..6798e0d8f44 100644
--- a/src/libstd/os/freebsd/fs.rs
+++ b/src/libstd/os/freebsd/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -72,10 +74,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/freebsd/mod.rs b/src/libstd/os/freebsd/mod.rs
index 1d9ee5468fe..c072fae557f 100644
--- a/src/libstd/os/freebsd/mod.rs
+++ b/src/libstd/os/freebsd/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/freebsd/raw.rs b/src/libstd/os/freebsd/raw.rs
index 0c58154ae60..aeae08fc6aa 100644
--- a/src/libstd/os/freebsd/raw.rs
+++ b/src/libstd/os/freebsd/raw.rs
@@ -1,24 +1,35 @@
 //! FreeBSD-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type fflags_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/fuchsia/mod.rs b/src/libstd/os/fuchsia/mod.rs
index 740eb011fb1..cd1b8233eb3 100644
--- a/src/libstd/os/fuchsia/mod.rs
+++ b/src/libstd/os/fuchsia/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/fuchsia/raw.rs b/src/libstd/os/fuchsia/raw.rs
index 7e44a79b371..f94659cd5ba 100644
--- a/src/libstd/os/fuchsia/raw.rs
+++ b/src/libstd/os/fuchsia/raw.rs
@@ -1,38 +1,50 @@
 //! Fuchsia-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_ulong;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = c_ulong;
 
 #[doc(inline)]
 #[stable(feature = "raw_ext", since = "1.1.0")]
-pub use self::arch::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t};
+pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
 
-#[cfg(any(target_arch = "x86",
-          target_arch = "le32",
-          target_arch = "powerpc",
-          target_arch = "arm"))]
+#[cfg(any(
+    target_arch = "x86",
+    target_arch = "le32",
+    target_arch = "powerpc",
+    target_arch = "arm"
+))]
 mod arch {
     use crate::os::raw::{c_long, c_short, c_uint};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -84,20 +96,29 @@ mod arch {
     use crate::os::raw::{c_long, c_ulong};
 
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = i64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -146,19 +167,25 @@ mod arch {
 
 #[cfg(target_arch = "mips64")]
 mod arch {
-    pub use libc::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t};
+    pub use libc::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
 }
 
 #[cfg(target_arch = "aarch64")]
 mod arch {
-    use crate::os::raw::{c_long, c_int};
+    use crate::os::raw::{c_int, c_long};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -207,14 +234,20 @@ mod arch {
 
 #[cfg(target_arch = "x86_64")]
 mod arch {
-    use crate::os::raw::{c_long, c_int};
+    use crate::os::raw::{c_int, c_long};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
diff --git a/src/libstd/os/haiku/fs.rs b/src/libstd/os/haiku/fs.rs
index 4097f8c26a6..13a4a92ae90 100644
--- a/src/libstd/os/haiku/fs.rs
+++ b/src/libstd/os/haiku/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -66,10 +68,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/haiku/mod.rs b/src/libstd/os/haiku/mod.rs
index c6a43d9342d..73f500cadaa 100644
--- a/src/libstd/os/haiku/mod.rs
+++ b/src/libstd/os/haiku/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/haiku/raw.rs b/src/libstd/os/haiku/raw.rs
index d86f4f3ba57..0d7e70b6b35 100644
--- a/src/libstd/os/haiku/raw.rs
+++ b/src/libstd/os/haiku/raw.rs
@@ -1,23 +1,31 @@
 //! Haiku-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-
 #![allow(deprecated)]
 
-use crate::os::raw::{c_long};
-use crate::os::unix::raw::{uid_t, gid_t};
+use crate::os::raw::c_long;
+use crate::os::unix::raw::{gid_t, uid_t};
 
 // Use the direct definition of usize, instead of uintptr_t like in libc
-#[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = usize;
+#[stable(feature = "pthread_t", since = "1.8.0")]
+pub type pthread_t = usize;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = i32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = i32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = i64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = i32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = i64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = i32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = i32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = i32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i32;
 
 #[repr(C)]
 #[derive(Clone)]
diff --git a/src/libstd/os/ios/fs.rs b/src/libstd/os/ios/fs.rs
index 9bdfa8e690b..08d3e4bcedf 100644
--- a/src/libstd/os/ios/fs.rs
+++ b/src/libstd/os/ios/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -72,10 +74,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/ios/mod.rs b/src/libstd/os/ios/mod.rs
index 098473c0dc9..fdefa1f6b21 100644
--- a/src/libstd/os/ios/mod.rs
+++ b/src/libstd/os/ios/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/ios/raw.rs b/src/libstd/os/ios/raw.rs
index fa38bca09e2..97b0a96b0f1 100644
--- a/src/libstd/os/ios/raw.rs
+++ b/src/libstd/os/ios/raw.rs
@@ -1,23 +1,33 @@
 //! iOS-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/linux/fs.rs b/src/libstd/os/linux/fs.rs
index 78321ac3185..dd71201b50b 100644
--- a/src/libstd/os/linux/fs.rs
+++ b/src/libstd/os/linux/fs.rs
@@ -34,10 +34,7 @@ pub trait MetadataExt {
     /// }
     /// ```
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(
-        since = "1.8.0",
-        reason = "other methods of this trait are now prefered"
-    )]
+    #[rustc_deprecated(since = "1.8.0", reason = "other methods of this trait are now prefered")]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -328,10 +325,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat64
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat64 as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/linux/mod.rs b/src/libstd/os/linux/mod.rs
index 3111325021a..d35307162cc 100644
--- a/src/libstd/os/linux/mod.rs
+++ b/src/libstd/os/linux/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/linux/raw.rs b/src/libstd/os/linux/raw.rs
index 21e1cf8a22b..d9b2236047b 100644
--- a/src/libstd/os/linux/raw.rs
+++ b/src/libstd/os/linux/raw.rs
@@ -1,41 +1,53 @@
 //! Linux-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 #![allow(missing_debug_implementations)]
 
 use crate::os::raw::c_ulong;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = c_ulong;
 
 #[doc(inline)]
 #[stable(feature = "raw_ext", since = "1.1.0")]
-pub use self::arch::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t};
+pub use self::arch::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
 
-#[cfg(any(target_arch = "x86",
-          target_arch = "le32",
-          target_arch = "powerpc",
-          target_arch = "arm",
-          target_arch = "asmjs",
-          target_arch = "wasm32"))]
+#[cfg(any(
+    target_arch = "x86",
+    target_arch = "le32",
+    target_arch = "powerpc",
+    target_arch = "arm",
+    target_arch = "asmjs",
+    target_arch = "wasm32"
+))]
 mod arch {
     use crate::os::raw::{c_long, c_short, c_uint};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -87,20 +99,29 @@ mod arch {
     use crate::os::raw::{c_long, c_ulong};
 
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = i64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
     #[cfg(target_env = "musl")]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
     #[cfg(not(target_env = "musl"))]
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -149,14 +170,20 @@ mod arch {
 
 #[cfg(target_arch = "hexagon")]
 mod arch {
-    use crate::os::raw::{c_long, c_int, c_longlong, culonglong};
+    use crate::os::raw::{c_int, c_long, c_longlong, culonglong};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = c_longlong;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = c_long;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = c_ulonglong;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = c_uint;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = c_longlong;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = c_longlong;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = c_long;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = c_ulonglong;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = c_uint;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = c_longlong;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = c_long;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -199,27 +226,31 @@ mod arch {
         #[stable(feature = "raw_ext", since = "1.1.0")]
         pub st_ctime_nsec: ::c_long,
         #[stable(feature = "raw_ext", since = "1.1.0")]
-        pub __pad3: [::c_int;2],
+        pub __pad3: [::c_int; 2],
     }
 }
 
-#[cfg(any(target_arch = "mips64",
-          target_arch = "s390x",
-          target_arch = "sparc64"))]
+#[cfg(any(target_arch = "mips64", target_arch = "s390x", target_arch = "sparc64"))]
 mod arch {
-    pub use libc::{off_t, ino_t, nlink_t, blksize_t, blkcnt_t, stat, time_t};
+    pub use libc::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
 }
 
 #[cfg(target_arch = "aarch64")]
 mod arch {
-    use crate::os::raw::{c_long, c_int};
+    use crate::os::raw::{c_int, c_long};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
@@ -268,14 +299,20 @@ mod arch {
 
 #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64"))]
 mod arch {
-    use crate::os::raw::{c_long, c_int};
+    use crate::os::raw::{c_int, c_long};
 
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-    #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blkcnt_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type blksize_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type ino_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type nlink_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type off_t = u64;
+    #[stable(feature = "raw_ext", since = "1.1.0")]
+    pub type time_t = i64;
 
     #[repr(C)]
     #[derive(Clone)]
diff --git a/src/libstd/os/macos/fs.rs b/src/libstd/os/macos/fs.rs
index bf951ee18c9..ad313a1240d 100644
--- a/src/libstd/os/macos/fs.rs
+++ b/src/libstd/os/macos/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -74,10 +76,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/macos/mod.rs b/src/libstd/os/macos/mod.rs
index ce48d6e1cc2..791d703b142 100644
--- a/src/libstd/os/macos/mod.rs
+++ b/src/libstd/os/macos/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/macos/raw.rs b/src/libstd/os/macos/raw.rs
index 5685642c07f..708261d86bd 100644
--- a/src/libstd/os/macos/raw.rs
+++ b/src/libstd/os/macos/raw.rs
@@ -1,23 +1,33 @@
 //! macOS-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/mod.rs b/src/libstd/os/mod.rs
index a8d2b0cb397..91e37ed833a 100644
--- a/src/libstd/os/mod.rs
+++ b/src/libstd/os/mod.rs
@@ -38,20 +38,35 @@ cfg_if::cfg_if! {
     }
 }
 
-#[cfg(target_os = "android")]    pub mod android;
-#[cfg(target_os = "dragonfly")]  pub mod dragonfly;
-#[cfg(target_os = "freebsd")]    pub mod freebsd;
-#[cfg(target_os = "haiku")]      pub mod haiku;
-#[cfg(target_os = "ios")]        pub mod ios;
-#[cfg(target_os = "macos")]      pub mod macos;
-#[cfg(target_os = "netbsd")]     pub mod netbsd;
-#[cfg(target_os = "openbsd")]    pub mod openbsd;
-#[cfg(target_os = "solaris")]    pub mod solaris;
-#[cfg(target_os = "emscripten")] pub mod emscripten;
-#[cfg(target_os = "fuchsia")]    pub mod fuchsia;
-#[cfg(target_os = "redox")]      pub mod redox;
-#[cfg(target_os = "wasi")]       pub mod wasi;
-#[cfg(target_os = "vxworks")]    pub mod vxworks;
-#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] pub mod fortanix_sgx;
+#[cfg(target_os = "android")]
+pub mod android;
+#[cfg(target_os = "dragonfly")]
+pub mod dragonfly;
+#[cfg(target_os = "emscripten")]
+pub mod emscripten;
+#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
+pub mod fortanix_sgx;
+#[cfg(target_os = "freebsd")]
+pub mod freebsd;
+#[cfg(target_os = "fuchsia")]
+pub mod fuchsia;
+#[cfg(target_os = "haiku")]
+pub mod haiku;
+#[cfg(target_os = "ios")]
+pub mod ios;
+#[cfg(target_os = "macos")]
+pub mod macos;
+#[cfg(target_os = "netbsd")]
+pub mod netbsd;
+#[cfg(target_os = "openbsd")]
+pub mod openbsd;
+#[cfg(target_os = "redox")]
+pub mod redox;
+#[cfg(target_os = "solaris")]
+pub mod solaris;
+#[cfg(target_os = "vxworks")]
+pub mod vxworks;
+#[cfg(target_os = "wasi")]
+pub mod wasi;
 
 pub mod raw;
diff --git a/src/libstd/os/netbsd/fs.rs b/src/libstd/os/netbsd/fs.rs
index dedfc6390ce..90980fdce80 100644
--- a/src/libstd/os/netbsd/fs.rs
+++ b/src/libstd/os/netbsd/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -70,10 +72,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/netbsd/mod.rs b/src/libstd/os/netbsd/mod.rs
index 37463639799..497a51a1df6 100644
--- a/src/libstd/os/netbsd/mod.rs
+++ b/src/libstd/os/netbsd/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/netbsd/raw.rs b/src/libstd/os/netbsd/raw.rs
index 1d5d5c6891e..475fcdcc4aa 100644
--- a/src/libstd/os/netbsd/raw.rs
+++ b/src/libstd/os/netbsd/raw.rs
@@ -1,25 +1,36 @@
 //! NetBSD-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
-use crate::os::unix::raw::{uid_t, gid_t};
+use crate::os::unix::raw::{gid_t, uid_t};
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type fflags_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/openbsd/fs.rs b/src/libstd/os/openbsd/fs.rs
index 1c019159be0..47da00ae26e 100644
--- a/src/libstd/os/openbsd/fs.rs
+++ b/src/libstd/os/openbsd/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -70,10 +72,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/openbsd/mod.rs b/src/libstd/os/openbsd/mod.rs
index 37463639799..497a51a1df6 100644
--- a/src/libstd/os/openbsd/mod.rs
+++ b/src/libstd/os/openbsd/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/openbsd/raw.rs b/src/libstd/os/openbsd/raw.rs
index 094168453d7..8e34e5483b7 100644
--- a/src/libstd/os/openbsd/raw.rs
+++ b/src/libstd/os/openbsd/raw.rs
@@ -1,24 +1,35 @@
 //! OpenBSD-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type fflags_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = usize;
diff --git a/src/libstd/os/raw/mod.rs b/src/libstd/os/raw/mod.rs
index 611a1709c8d..e09012007f2 100644
--- a/src/libstd/os/raw/mod.rs
+++ b/src/libstd/os/raw/mod.rs
@@ -9,85 +9,135 @@
 #![stable(feature = "raw_os", since = "1.1.0")]
 
 #[doc(include = "char.md")]
-#[cfg(any(all(target_os = "linux", any(target_arch = "aarch64",
-                                       target_arch = "arm",
-                                       target_arch = "hexagon",
-                                       target_arch = "powerpc",
-                                       target_arch = "powerpc64",
-                                       target_arch = "s390x")),
-          all(target_os = "android", any(target_arch = "aarch64",
-                                         target_arch = "arm")),
-          all(target_os = "l4re", target_arch = "x86_64"),
-          all(target_os = "freebsd", any(target_arch = "aarch64",
-                                         target_arch = "arm",
-                                         target_arch = "powerpc",
-                                         target_arch = "powerpc64")),
-          all(target_os = "netbsd", any(target_arch = "aarch64",
-                                        target_arch = "arm",
-                                        target_arch = "powerpc")),
-          all(target_os = "openbsd", target_arch = "aarch64"),
-          all(target_os = "vxworks", any(target_arch = "aarch64",
-                                         target_arch = "arm",
-                                         target_arch = "powerpc64",
-                                         target_arch = "powerpc")),
-          all(target_os = "fuchsia", target_arch = "aarch64")))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_char = u8;
+#[cfg(any(
+    all(
+        target_os = "linux",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "hexagon",
+            target_arch = "powerpc",
+            target_arch = "powerpc64",
+            target_arch = "s390x"
+        )
+    ),
+    all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")),
+    all(target_os = "l4re", target_arch = "x86_64"),
+    all(
+        target_os = "freebsd",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "powerpc",
+            target_arch = "powerpc64"
+        )
+    ),
+    all(
+        target_os = "netbsd",
+        any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc")
+    ),
+    all(target_os = "openbsd", target_arch = "aarch64"),
+    all(
+        target_os = "vxworks",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "powerpc64",
+            target_arch = "powerpc"
+        )
+    ),
+    all(target_os = "fuchsia", target_arch = "aarch64")
+))]
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_char = u8;
 #[doc(include = "char.md")]
-#[cfg(not(any(all(target_os = "linux", any(target_arch = "aarch64",
-                                           target_arch = "arm",
-                                           target_arch = "hexagon",
-                                           target_arch = "powerpc",
-                                           target_arch = "powerpc64",
-                                           target_arch = "s390x")),
-              all(target_os = "android", any(target_arch = "aarch64",
-                                             target_arch = "arm")),
-              all(target_os = "l4re", target_arch = "x86_64"),
-              all(target_os = "freebsd", any(target_arch = "aarch64",
-                                             target_arch = "arm",
-                                             target_arch = "powerpc",
-                                             target_arch = "powerpc64")),
-              all(target_os = "netbsd", any(target_arch = "aarch64",
-                                            target_arch = "arm",
-                                            target_arch = "powerpc")),
-              all(target_os = "openbsd", target_arch = "aarch64"),
-              all(target_os = "vxworks", any(target_arch = "aarch64",
-                                             target_arch = "arm",
-                                             target_arch = "powerpc64",
-                                             target_arch = "powerpc")),
-              all(target_os = "fuchsia", target_arch = "aarch64"))))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_char = i8;
+#[cfg(not(any(
+    all(
+        target_os = "linux",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "hexagon",
+            target_arch = "powerpc",
+            target_arch = "powerpc64",
+            target_arch = "s390x"
+        )
+    ),
+    all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")),
+    all(target_os = "l4re", target_arch = "x86_64"),
+    all(
+        target_os = "freebsd",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "powerpc",
+            target_arch = "powerpc64"
+        )
+    ),
+    all(
+        target_os = "netbsd",
+        any(target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc")
+    ),
+    all(target_os = "openbsd", target_arch = "aarch64"),
+    all(
+        target_os = "vxworks",
+        any(
+            target_arch = "aarch64",
+            target_arch = "arm",
+            target_arch = "powerpc64",
+            target_arch = "powerpc"
+        )
+    ),
+    all(target_os = "fuchsia", target_arch = "aarch64")
+)))]
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_char = i8;
 #[doc(include = "schar.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_schar = i8;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_schar = i8;
 #[doc(include = "uchar.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_uchar = u8;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_uchar = u8;
 #[doc(include = "short.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_short = i16;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_short = i16;
 #[doc(include = "ushort.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ushort = u16;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_ushort = u16;
 #[doc(include = "int.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_int = i32;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_int = i32;
 #[doc(include = "uint.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_uint = u32;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_uint = u32;
 #[doc(include = "long.md")]
 #[cfg(any(target_pointer_width = "32", windows))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_long = i32;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_long = i32;
 #[doc(include = "ulong.md")]
 #[cfg(any(target_pointer_width = "32", windows))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulong = u32;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_ulong = u32;
 #[doc(include = "long.md")]
 #[cfg(all(target_pointer_width = "64", not(windows)))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_long = i64;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_long = i64;
 #[doc(include = "ulong.md")]
 #[cfg(all(target_pointer_width = "64", not(windows)))]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulong = u64;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_ulong = u64;
 #[doc(include = "longlong.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_longlong = i64;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_longlong = i64;
 #[doc(include = "ulonglong.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_ulonglong = u64;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_ulonglong = u64;
 #[doc(include = "float.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_float = f32;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_float = f32;
 #[doc(include = "double.md")]
-#[stable(feature = "raw_os", since = "1.1.0")] pub type c_double = f64;
+#[stable(feature = "raw_os", since = "1.1.0")]
+pub type c_double = f64;
 
 #[stable(feature = "raw_os", since = "1.1.0")]
 #[doc(no_inline)]
diff --git a/src/libstd/os/redox/fs.rs b/src/libstd/os/redox/fs.rs
index 80a12907619..6c87df534bd 100644
--- a/src/libstd/os/redox/fs.rs
+++ b/src/libstd/os/redox/fs.rs
@@ -34,9 +34,11 @@ pub trait MetadataExt {
     /// }
     /// ```
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -327,10 +329,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/redox/mod.rs b/src/libstd/os/redox/mod.rs
index c60da5926da..d786759c611 100644
--- a/src/libstd/os/redox/mod.rs
+++ b/src/libstd/os/redox/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/redox/raw.rs b/src/libstd/os/redox/raw.rs
index 23d8ff7694b..abe6dfc6b0c 100644
--- a/src/libstd/os/redox/raw.rs
+++ b/src/libstd/os/redox/raw.rs
@@ -1,30 +1,42 @@
 //! Redox-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 #![allow(missing_debug_implementations)]
 
 use crate::os::raw::{c_char, c_int, c_long, c_ulong, c_void};
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = c_long;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type gid_t = c_int;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = c_int;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type uid_t = c_int;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = c_long;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type gid_t = c_int;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = c_int;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type uid_t = c_int;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = *mut c_void;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = c_ulong;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = c_ulong;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = c_ulong;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = c_ulong;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = c_long;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = c_long;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = c_ulong;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = c_ulong;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = c_ulong;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = c_ulong;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = c_long;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = c_long;
 
 #[repr(C)]
 #[derive(Clone)]
diff --git a/src/libstd/os/solaris/fs.rs b/src/libstd/os/solaris/fs.rs
index 55a8d5d1ef0..549d3d75636 100644
--- a/src/libstd/os/solaris/fs.rs
+++ b/src/libstd/os/solaris/fs.rs
@@ -18,9 +18,11 @@ pub trait MetadataExt {
     /// Unix platforms. The `os::unix::fs::MetadataExt` trait contains the
     /// cross-Unix abstractions contained within the raw stat.
     #[stable(feature = "metadata_ext", since = "1.1.0")]
-    #[rustc_deprecated(since = "1.8.0",
-                       reason = "deprecated in favor of the accessor \
-                                 methods of this trait")]
+    #[rustc_deprecated(
+        since = "1.8.0",
+        reason = "deprecated in favor of the accessor \
+                  methods of this trait"
+    )]
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat;
 
@@ -62,10 +64,7 @@ pub trait MetadataExt {
 impl MetadataExt for Metadata {
     #[allow(deprecated)]
     fn as_raw_stat(&self) -> &raw::stat {
-        unsafe {
-            &*(self.as_inner().as_inner() as *const libc::stat
-                                          as *const raw::stat)
-        }
+        unsafe { &*(self.as_inner().as_inner() as *const libc::stat as *const raw::stat) }
     }
     fn st_dev(&self) -> u64 {
         self.as_inner().as_inner().st_dev as u64
diff --git a/src/libstd/os/solaris/mod.rs b/src/libstd/os/solaris/mod.rs
index 7f560c9b093..e4cfd53291a 100644
--- a/src/libstd/os/solaris/mod.rs
+++ b/src/libstd/os/solaris/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/solaris/raw.rs b/src/libstd/os/solaris/raw.rs
index 93270efea2b..e78f9992bb3 100644
--- a/src/libstd/os/solaris/raw.rs
+++ b/src/libstd/os/solaris/raw.rs
@@ -1,25 +1,36 @@
 //! Solaris-specific raw type definitions
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
 use crate::os::raw::c_long;
-use crate::os::unix::raw::{uid_t, gid_t};
+use crate::os::unix::raw::{gid_t, uid_t};
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blkcnt_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type blksize_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type dev_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type fflags_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type ino_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type mode_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type nlink_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type off_t = u64;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blkcnt_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type blksize_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type dev_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type fflags_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type ino_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type mode_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type nlink_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type off_t = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = u32;
@@ -61,5 +72,5 @@ pub struct stat {
     #[stable(feature = "raw_ext", since = "1.1.0")]
     pub st_blocks: blkcnt_t,
     #[stable(feature = "raw_ext", since = "1.1.0")]
-    pub __unused: [u8; 16]
+    pub __unused: [u8; 16],
 }
diff --git a/src/libstd/os/vxworks/mod.rs b/src/libstd/os/vxworks/mod.rs
index 2255a103d35..0a7ac641dd3 100644
--- a/src/libstd/os/vxworks/mod.rs
+++ b/src/libstd/os/vxworks/mod.rs
@@ -2,5 +2,5 @@
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
 
-pub mod raw;
 pub mod fs;
+pub mod raw;
diff --git a/src/libstd/os/vxworks/raw.rs b/src/libstd/os/vxworks/raw.rs
index ae0560a5a92..29a0af5645e 100644
--- a/src/libstd/os/vxworks/raw.rs
+++ b/src/libstd/os/vxworks/raw.rs
@@ -1,7 +1,7 @@
 //! VxWorks-specific raw type definitions
 #![stable(feature = "metadata_ext", since = "1.1.0")]
 
-use crate::os::raw::{c_ulong};
+use crate::os::raw::c_ulong;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub type pthread_t = c_ulong;
diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs
index e36496d4c1c..ac8e0daf766 100644
--- a/src/libstd/panic.rs
+++ b/src/libstd/panic.rs
@@ -7,21 +7,21 @@ use crate::cell::UnsafeCell;
 use crate::collections;
 use crate::fmt;
 use crate::future::Future;
-use crate::pin::Pin;
 use crate::ops::{Deref, DerefMut};
 use crate::panicking;
-use crate::ptr::{Unique, NonNull};
+use crate::pin::Pin;
+use crate::ptr::{NonNull, Unique};
 use crate::rc::Rc;
-use crate::sync::{Arc, Mutex, RwLock};
 use crate::sync::atomic;
+use crate::sync::{Arc, Mutex, RwLock};
 use crate::task::{Context, Poll};
 use crate::thread::Result;
 
 #[stable(feature = "panic_hooks", since = "1.10.0")]
-pub use crate::panicking::{take_hook, set_hook};
+pub use crate::panicking::{set_hook, take_hook};
 
 #[stable(feature = "panic_hooks", since = "1.10.0")]
-pub use core::panic::{PanicInfo, Location};
+pub use core::panic::{Location, PanicInfo};
 
 /// A marker trait which represents "panic safe" types in Rust.
 ///
@@ -103,8 +103,8 @@ pub use core::panic::{PanicInfo, Location};
 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
 #[stable(feature = "catch_unwind", since = "1.9.0")]
 #[rustc_on_unimplemented(
-    message="the type `{Self}` may not be safely transferred across an unwind boundary",
-    label="`{Self}` may not be safely transferred across an unwind boundary",
+    message = "the type `{Self}` may not be safely transferred across an unwind boundary",
+    label = "`{Self}` may not be safely transferred across an unwind boundary"
 )]
 pub auto trait UnwindSafe {}
 
@@ -121,10 +121,10 @@ pub auto trait UnwindSafe {}
 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
 #[stable(feature = "catch_unwind", since = "1.9.0")]
 #[rustc_on_unimplemented(
-    message="the type `{Self}` may contain interior mutability and a reference may not be safely \
-             transferrable across a catch_unwind boundary",
-    label="`{Self}` may contain interior mutability and a reference may not be safely \
-           transferrable across a catch_unwind boundary",
+    message = "the type `{Self}` may contain interior mutability and a reference may not be safely \
+               transferrable across a catch_unwind boundary",
+    label = "`{Self}` may contain interior mutability and a reference may not be safely \
+             transferrable across a catch_unwind boundary"
 )]
 pub auto trait RefUnwindSafe {}
 
@@ -187,10 +187,7 @@ pub auto trait RefUnwindSafe {}
 /// // ...
 /// ```
 #[stable(feature = "catch_unwind", since = "1.9.0")]
-pub struct AssertUnwindSafe<T>(
-    #[stable(feature = "catch_unwind", since = "1.9.0")]
-    pub T
-);
+pub struct AssertUnwindSafe<T>(#[stable(feature = "catch_unwind", since = "1.9.0")] pub T);
 
 // Implementations of the `UnwindSafe` trait:
 //
@@ -290,7 +287,12 @@ impl<T> RefUnwindSafe for atomic::AtomicPtr<T> {}
 // https://github.com/rust-lang/rust/issues/62301
 #[stable(feature = "hashbrown", since = "1.36.0")]
 impl<K, V, S> UnwindSafe for collections::HashMap<K, V, S>
-    where K: UnwindSafe, V: UnwindSafe, S: UnwindSafe {}
+where
+    K: UnwindSafe,
+    V: UnwindSafe,
+    S: UnwindSafe,
+{
+}
 
 #[stable(feature = "catch_unwind", since = "1.9.0")]
 impl<T> Deref for AssertUnwindSafe<T> {
@@ -320,9 +322,7 @@ impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> {
 #[stable(feature = "std_debug", since = "1.16.0")]
 impl<T: fmt::Debug> fmt::Debug for AssertUnwindSafe<T> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_tuple("AssertUnwindSafe")
-            .field(&self.0)
-            .finish()
+        f.debug_tuple("AssertUnwindSafe").field(&self.0).finish()
     }
 }
 
@@ -391,9 +391,7 @@ impl<F: Future> Future for AssertUnwindSafe<F> {
 /// ```
 #[stable(feature = "catch_unwind", since = "1.9.0")]
 pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
-    unsafe {
-        panicking::r#try(f)
-    }
+    unsafe { panicking::r#try(f) }
 }
 
 /// Triggers a panic without invoking the panic hook.
@@ -425,5 +423,5 @@ pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R> {
 /// ```
 #[stable(feature = "resume_unwind", since = "1.9.0")]
 pub fn resume_unwind(payload: Box<dyn Any + Send>) -> ! {
-    panicking::update_count_then_panic(payload)
+    panicking::rust_panic_without_hook(payload)
 }
diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs
index 6819a4a04d7..c028ddcd676 100644
--- a/src/libstd/panicking.rs
+++ b/src/libstd/panicking.rs
@@ -20,6 +20,7 @@ use crate::sys_common::rwlock::RWLock;
 use crate::sys_common::{thread_info, util};
 use crate::sys_common::backtrace::{self, RustBacktrace};
 use crate::thread;
+use crate::process;
 
 #[cfg(not(test))]
 use crate::io::set_panic;
@@ -46,6 +47,8 @@ extern {
                                 vtable_ptr: *mut usize) -> u32;
 
     /// `payload` is actually a `*mut &mut dyn BoxMeUp` but that would cause FFI warnings.
+    /// It cannot be `Box<dyn BoxMeUp>` because the other end of this call does not depend
+    /// on liballoc, and thus cannot use `Box`.
     #[unwind(allowed)]
     fn __rust_start_panic(payload: usize) -> u32;
 }
@@ -296,14 +299,6 @@ pub fn panicking() -> bool {
     update_panic_count(0) != 0
 }
 
-/// Entry point of panic from the libcore crate (`panic_impl` lang item).
-#[cfg(not(test))]
-#[panic_handler]
-#[unwind(allowed)]
-pub fn rust_begin_panic(info: &PanicInfo<'_>) -> ! {
-    continue_panic_fmt(&info)
-}
-
 /// The entry point for panicking with a formatted message.
 ///
 /// This is designed to reduce the amount of code required at the call
@@ -324,13 +319,17 @@ pub fn begin_panic_fmt(msg: &fmt::Arguments<'_>,
         unsafe { intrinsics::abort() }
     }
 
+    // Just package everything into a `PanicInfo` and continue like libcore panics.
     let (file, line, col) = *file_line_col;
     let location = Location::internal_constructor(file, line, col);
     let info = PanicInfo::internal_constructor(Some(msg), &location);
-    continue_panic_fmt(&info)
+    begin_panic_handler(&info)
 }
 
-fn continue_panic_fmt(info: &PanicInfo<'_>) -> ! {
+/// Entry point of panics from the libcore crate (`panic_impl` lang item).
+#[cfg_attr(not(test), panic_handler)]
+#[unwind(allowed)]
+pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
     struct PanicPayload<'a> {
         inner: &'a fmt::Arguments<'a>,
         string: Option<String>,
@@ -345,6 +344,7 @@ fn continue_panic_fmt(info: &PanicInfo<'_>) -> ! {
             use crate::fmt::Write;
 
             let inner = self.inner;
+            // Lazily, the first time this gets called, run the actual string formatting.
             self.string.get_or_insert_with(|| {
                 let mut s = String::new();
                 drop(s.write_fmt(*inner));
@@ -354,7 +354,7 @@ fn continue_panic_fmt(info: &PanicInfo<'_>) -> ! {
     }
 
     unsafe impl<'a> BoxMeUp for PanicPayload<'a> {
-        fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
+        fn take_box(&mut self) -> *mut (dyn Any + Send) {
             let contents = mem::take(self.fill());
             Box::into_raw(Box::new(contents))
         }
@@ -378,7 +378,9 @@ fn continue_panic_fmt(info: &PanicInfo<'_>) -> ! {
         &file_line_col);
 }
 
-/// This is the entry point of panicking for panic!() and assert!().
+/// This is the entry point of panicking for the non-format-string variants of
+/// panic!() and assert!(). In particular, this is the only entry point that supports
+/// arbitrary payloads, not just format strings.
 #[unstable(feature = "libstd_sys_internals",
            reason = "used by the panic! macro",
            issue = "0")]
@@ -412,10 +414,10 @@ pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u3
     }
 
     unsafe impl<A: Send + 'static> BoxMeUp for PanicPayload<A> {
-        fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
+        fn take_box(&mut self) -> *mut (dyn Any + Send) {
             let data = match self.inner.take() {
                 Some(a) => Box::new(a) as Box<dyn Any + Send>,
-                None => Box::new(()),
+                None => process::abort(),
             };
             Box::into_raw(data)
         }
@@ -423,7 +425,7 @@ pub fn begin_panic<M: Any + Send>(msg: M, file_line_col: &(&'static str, u32, u3
         fn get(&mut self) -> &(dyn Any + Send) {
             match self.inner {
                 Some(ref a) => a,
-                None => &(),
+                None => process::abort(),
             }
         }
     }
@@ -457,9 +459,12 @@ fn rust_panic_with_hook(payload: &mut dyn BoxMeUp,
         let mut info = PanicInfo::internal_constructor(message, &location);
         HOOK_LOCK.read();
         match HOOK {
-            // Some platforms know that printing to stderr won't ever actually
+            // Some platforms (like wasm) know that printing to stderr won't ever actually
             // print anything, and if that's the case we can skip the default
-            // hook.
+            // hook. Since string formatting happens lazily when calling `payload`
+            // methods, this means we avoid formatting the string at all!
+            // (The panic runtime might still call `payload.take_box()` though and trigger
+            // formatting.)
             Hook::Default if panic_output().is_none() => {}
             Hook::Default => {
                 info.set_payload(payload.get());
@@ -486,14 +491,15 @@ fn rust_panic_with_hook(payload: &mut dyn BoxMeUp,
     rust_panic(payload)
 }
 
-/// Shim around rust_panic. Called by resume_unwind.
-pub fn update_count_then_panic(msg: Box<dyn Any + Send>) -> ! {
+/// This is the entry point for `resume_unwind`.
+/// It just forwards the payload to the panic runtime.
+pub fn rust_panic_without_hook(payload: Box<dyn Any + Send>) -> ! {
     update_panic_count(1);
 
     struct RewrapBox(Box<dyn Any + Send>);
 
     unsafe impl BoxMeUp for RewrapBox {
-        fn box_me_up(&mut self) -> *mut (dyn Any + Send) {
+        fn take_box(&mut self) -> *mut (dyn Any + Send) {
             Box::into_raw(mem::replace(&mut self.0, Box::new(())))
         }
 
@@ -502,7 +508,7 @@ pub fn update_count_then_panic(msg: Box<dyn Any + Send>) -> ! {
         }
     }
 
-    rust_panic(&mut RewrapBox(msg))
+    rust_panic(&mut RewrapBox(payload))
 }
 
 /// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
diff --git a/src/libstd/path.rs b/src/libstd/path.rs
index 6d6bc760649..42bca0a9575 100644
--- a/src/libstd/path.rs
+++ b/src/libstd/path.rs
@@ -84,7 +84,7 @@ use crate::sync::Arc;
 
 use crate::ffi::{OsStr, OsString};
 
-use crate::sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix};
+use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR};
 
 ////////////////////////////////////////////////////////////////////////////////
 // GENERAL NOTES
@@ -196,26 +196,13 @@ impl<'a> Prefix<'a> {
         match *self {
             Verbatim(x) => 4 + os_str_len(x),
             VerbatimUNC(x, y) => {
-                8 + os_str_len(x) +
-                if os_str_len(y) > 0 {
-                    1 + os_str_len(y)
-                } else {
-                    0
-                }
-            },
+                8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
+            }
             VerbatimDisk(_) => 6,
-            UNC(x, y) => {
-                2 + os_str_len(x) +
-                if os_str_len(y) > 0 {
-                    1 + os_str_len(y)
-                } else {
-                    0
-                }
-            },
+            UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
             DeviceNS(x) => 4 + os_str_len(x),
             Disk(_) => 2,
         }
-
     }
 
     /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
@@ -291,8 +278,9 @@ pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
 // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
 // `iter` after having exhausted `prefix`.
 fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
-    where I: Iterator<Item = Component<'a>> + Clone,
-          J: Iterator<Item = Component<'b>>,
+where
+    I: Iterator<Item = Component<'a>> + Clone,
+    J: Iterator<Item = Component<'b>>,
 {
     loop {
         let mut iter_next = iter.clone();
@@ -326,11 +314,7 @@ fn has_redox_scheme(s: &[u8]) -> bool {
 
 /// Says whether the first byte after the prefix is a separator.
 fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
-    let path = if let Some(p) = prefix {
-        &s[p.len()..]
-    } else {
-        s
-    };
+    let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
     !path.is_empty() && is_sep_byte(path[0])
 }
 
@@ -352,8 +336,7 @@ fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
         if before == Some(b"") {
             (Some(file), None)
         } else {
-            (before.map(|s| u8_slice_as_os_str(s)),
-             after.map(|s| u8_slice_as_os_str(s)))
+            (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
         }
     }
 }
@@ -370,9 +353,9 @@ fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
 /// directory component, and a body (of normal components)
 #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
 enum State {
-    Prefix = 0,         // c:
-    StartDir = 1,       // / or . or nothing
-    Body = 2,           // foo/bar/baz
+    Prefix = 0,   // c:
+    StartDir = 1, // / or . or nothing
+    Body = 2,     // foo/bar/baz
     Done = 3,
 }
 
@@ -509,9 +492,7 @@ pub enum Component<'a> {
     ///
     /// [`Prefix`]: enum.Prefix.html
     #[stable(feature = "rust1", since = "1.0.0")]
-    Prefix(
-        #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>
-    ),
+    Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
 
     /// The root directory component, appears after any prefix and before anything else.
     ///
@@ -637,15 +618,11 @@ impl fmt::Debug for Components<'_> {
 
         impl fmt::Debug for DebugHelper<'_> {
             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                f.debug_list()
-                    .entries(self.0.components())
-                    .finish()
+                f.debug_list().entries(self.0.components()).finish()
             }
         }
 
-        f.debug_tuple("Components")
-            .field(&DebugHelper(self.as_path()))
-            .finish()
+        f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
     }
 }
 
@@ -664,26 +641,14 @@ impl<'a> Components<'a> {
     /// how much of the prefix is left from the point of view of iteration?
     #[inline]
     fn prefix_remaining(&self) -> usize {
-        if self.front == State::Prefix {
-            self.prefix_len()
-        } else {
-            0
-        }
+        if self.front == State::Prefix { self.prefix_len() } else { 0 }
     }
 
     // Given the iteration so far, how much of the pre-State::Body path is left?
     #[inline]
     fn len_before_body(&self) -> usize {
-        let root = if self.front <= State::StartDir && self.has_physical_root {
-            1
-        } else {
-            0
-        };
-        let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
-            1
-        } else {
-            0
-        };
+        let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
+        let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
         self.prefix_remaining() + root + cur_dir
     }
 
@@ -695,11 +660,7 @@ impl<'a> Components<'a> {
 
     #[inline]
     fn is_sep_byte(&self, b: u8) -> bool {
-        if self.prefix_verbatim() {
-            is_verbatim_sep(b)
-        } else {
-            is_sep_byte(b)
-        }
+        if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
     }
 
     /// Extracts a slice corresponding to the portion of the path remaining for iteration.
@@ -758,8 +719,8 @@ impl<'a> Components<'a> {
         match comp {
             b"." if self.prefix_verbatim() => Some(Component::CurDir),
             b"." => None, // . components are normalized away, except at
-                          // the beginning of a path, which is treated
-                          // separately via `include_cur_dir`
+            // the beginning of a path, which is treated
+            // separately via `include_cur_dir`
             b".." => Some(Component::ParentDir),
             b"" => None,
             _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })),
@@ -835,15 +796,11 @@ impl fmt::Debug for Iter<'_> {
 
         impl fmt::Debug for DebugHelper<'_> {
             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                f.debug_list()
-                    .entries(self.0.iter())
-                    .finish()
+                f.debug_list().entries(self.0.iter()).finish()
             }
         }
 
-        f.debug_tuple("Iter")
-            .field(&DebugHelper(self.as_path()))
-            .finish()
+        f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
     }
 }
 
@@ -1174,9 +1131,7 @@ impl PathBuf {
     /// [`OsString`]: ../ffi/struct.OsString.html
     #[unstable(feature = "path_buf_capacity", issue = "58234")]
     pub fn with_capacity(capacity: usize) -> PathBuf {
-        PathBuf {
-            inner: OsString::with_capacity(capacity)
-        }
+        PathBuf { inner: OsString::with_capacity(capacity) }
     }
 
     /// Coerces to a [`Path`] slice.
@@ -1239,8 +1194,10 @@ impl PathBuf {
         // in the special case of `C:` on Windows, do *not* add a separator
         {
             let comps = self.components();
-            if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() &&
-               comps.prefix.unwrap().is_drive() {
+            if comps.prefix_len() > 0
+                && comps.prefix_len() == comps.path.len()
+                && comps.prefix.unwrap().is_drive()
+            {
                 need_sep = false
             }
         }
@@ -1527,7 +1484,7 @@ impl From<PathBuf> for OsString {
     /// Converts a `PathBuf` into a `OsString`
     ///
     /// This conversion does not allocate or copy memory.
-    fn from(path_buf : PathBuf) -> OsString {
+    fn from(path_buf: PathBuf) -> OsString {
         path_buf.inner
     }
 }
@@ -1992,13 +1949,11 @@ impl Path {
     pub fn parent(&self) -> Option<&Path> {
         let mut comps = self.components();
         let comp = comps.next_back();
-        comp.and_then(|p| {
-            match p {
-                Component::Normal(_) |
-                Component::CurDir |
-                Component::ParentDir => Some(comps.as_path()),
-                _ => None,
+        comp.and_then(|p| match p {
+            Component::Normal(_) | Component::CurDir | Component::ParentDir => {
+                Some(comps.as_path())
             }
+            _ => None,
         })
     }
 
@@ -2026,9 +1981,7 @@ impl Path {
     /// [`parent`]: struct.Path.html#method.parent
     #[stable(feature = "path_ancestors", since = "1.28.0")]
     pub fn ancestors(&self) -> Ancestors<'_> {
-        Ancestors {
-            next: Some(&self),
-        }
+        Ancestors { next: Some(&self) }
     }
 
     /// Returns the final component of the `Path`, if there is one.
@@ -2055,11 +2008,9 @@ impl Path {
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn file_name(&self) -> Option<&OsStr> {
-        self.components().next_back().and_then(|p| {
-            match p {
-                Component::Normal(p) => Some(p.as_ref()),
-                _ => None,
-            }
+        self.components().next_back().and_then(|p| match p {
+            Component::Normal(p) => Some(p.as_ref()),
+            _ => None,
         })
     }
 
@@ -2092,15 +2043,14 @@ impl Path {
     /// assert_eq!(path.strip_prefix(prefix), Ok(Path::new("haha/foo.txt")));
     /// ```
     #[stable(since = "1.7.0", feature = "path_strip_prefix")]
-    pub fn strip_prefix<P>(&self, base: P)
-                           -> Result<&Path, StripPrefixError>
-        where P: AsRef<Path>
+    pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
+    where
+        P: AsRef<Path>,
     {
         self._strip_prefix(base.as_ref())
     }
 
-    fn _strip_prefix(&self, base: &Path)
-                     -> Result<&Path, StripPrefixError> {
+    fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
         iter_after(self.components(), base.components())
             .map(|c| c.as_path())
             .ok_or(StripPrefixError(()))
@@ -2329,8 +2279,8 @@ impl Path {
         Components {
             path: self.as_u8_slice(),
             prefix,
-            has_physical_root: has_physical_root(self.as_u8_slice(), prefix) ||
-                               has_redox_scheme(self.as_u8_slice()),
+            has_physical_root: has_physical_root(self.as_u8_slice(), prefix)
+                || has_redox_scheme(self.as_u8_slice()),
             front: State::Prefix,
             back: State::Body,
         }
@@ -2727,14 +2677,18 @@ impl AsRef<Path> for PathBuf {
 impl<'a> IntoIterator for &'a PathBuf {
     type Item = &'a OsStr;
     type IntoIter = Iter<'a>;
-    fn into_iter(self) -> Iter<'a> { self.iter() }
+    fn into_iter(self) -> Iter<'a> {
+        self.iter()
+    }
 }
 
 #[stable(feature = "path_into_iter", since = "1.6.0")]
 impl<'a> IntoIterator for &'a Path {
     type Item = &'a OsStr;
     type IntoIter = Iter<'a>;
-    fn into_iter(self) -> Iter<'a> { self.iter() }
+    fn into_iter(self) -> Iter<'a> {
+        self.iter()
+    }
 }
 
 macro_rules! impl_cmp {
@@ -2742,13 +2696,17 @@ macro_rules! impl_cmp {
         #[stable(feature = "partialeq_path", since = "1.6.0")]
         impl<'a, 'b> PartialEq<$rhs> for $lhs {
             #[inline]
-            fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) }
+            fn eq(&self, other: &$rhs) -> bool {
+                <Path as PartialEq>::eq(self, other)
+            }
         }
 
         #[stable(feature = "partialeq_path", since = "1.6.0")]
         impl<'a, 'b> PartialEq<$lhs> for $rhs {
             #[inline]
-            fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) }
+            fn eq(&self, other: &$lhs) -> bool {
+                <Path as PartialEq>::eq(self, other)
+            }
         }
 
         #[stable(feature = "cmp_path", since = "1.8.0")]
@@ -2766,7 +2724,7 @@ macro_rules! impl_cmp {
                 <Path as PartialOrd>::partial_cmp(self, other)
             }
         }
-    }
+    };
 }
 
 impl_cmp!(PathBuf, Path);
@@ -2780,13 +2738,17 @@ macro_rules! impl_cmp_os_str {
         #[stable(feature = "cmp_path", since = "1.8.0")]
         impl<'a, 'b> PartialEq<$rhs> for $lhs {
             #[inline]
-            fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) }
+            fn eq(&self, other: &$rhs) -> bool {
+                <Path as PartialEq>::eq(self, other.as_ref())
+            }
         }
 
         #[stable(feature = "cmp_path", since = "1.8.0")]
         impl<'a, 'b> PartialEq<$lhs> for $rhs {
             #[inline]
-            fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) }
+            fn eq(&self, other: &$lhs) -> bool {
+                <Path as PartialEq>::eq(self.as_ref(), other)
+            }
         }
 
         #[stable(feature = "cmp_path", since = "1.8.0")]
@@ -2804,7 +2766,7 @@ macro_rules! impl_cmp_os_str {
                 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
             }
         }
-    }
+    };
 }
 
 impl_cmp_os_str!(PathBuf, OsStr);
@@ -2831,7 +2793,9 @@ impl fmt::Display for StripPrefixError {
 
 #[stable(since = "1.7.0", feature = "strip_prefix")]
 impl Error for StripPrefixError {
-    fn description(&self) -> &str { "prefix not found" }
+    fn description(&self) -> &str {
+        "prefix not found"
+    }
 }
 
 #[cfg(test)]
@@ -2948,568 +2912,568 @@ mod tests {
     #[cfg(unix)]
     pub fn test_decompositions_unix() {
         t!("",
-           iter: [],
-           has_root: false,
-           is_absolute: false,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: [],
+        has_root: false,
+        is_absolute: false,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("/",
-           iter: ["/"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["/"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("/foo",
-           iter: ["/", "foo"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["/", "foo"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("/foo/",
-           iter: ["/", "foo"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["/", "foo"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/bar",
-           iter: ["foo", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("/foo/bar",
-           iter: ["/", "foo", "bar"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("/foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["/", "foo", "bar"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("/foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("///foo///",
-           iter: ["/", "foo"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["/", "foo"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("///foo///bar",
-           iter: ["/", "foo", "bar"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("///foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["/", "foo", "bar"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("///foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("./.",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("/..",
-           iter: ["/", ".."],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("/"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["/", ".."],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("/"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("../",
-           iter: [".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: [".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/.",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/..",
-           iter: ["foo", ".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["foo", ".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/./",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/./bar",
-           iter: ["foo", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("foo/../",
-           iter: ["foo", ".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["foo", ".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/../bar",
-           iter: ["foo", "..", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo/.."),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "..", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo/.."),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("./a",
-           iter: [".", "a"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("."),
-           file_name: Some("a"),
-           file_stem: Some("a"),
-           extension: None
-           );
+        iter: [".", "a"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("."),
+        file_name: Some("a"),
+        file_stem: Some("a"),
+        extension: None
+        );
 
         t!(".",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("./",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("a/b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a//b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a/./b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a/b/c",
-           iter: ["a", "b", "c"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a/b"),
-           file_name: Some("c"),
-           file_stem: Some("c"),
-           extension: None
-           );
+        iter: ["a", "b", "c"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a/b"),
+        file_name: Some("c"),
+        file_stem: Some("c"),
+        extension: None
+        );
 
         t!(".foo",
-           iter: [".foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some(".foo"),
-           file_stem: Some(".foo"),
-           extension: None
-           );
+        iter: [".foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some(".foo"),
+        file_stem: Some(".foo"),
+        extension: None
+        );
     }
 
     #[test]
     #[cfg(windows)]
     pub fn test_decompositions_windows() {
         t!("",
-           iter: [],
-           has_root: false,
-           is_absolute: false,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: [],
+        has_root: false,
+        is_absolute: false,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("/",
-           iter: ["\\"],
-           has_root: true,
-           is_absolute: false,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\"],
+        has_root: true,
+        is_absolute: false,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\",
-           iter: ["\\"],
-           has_root: true,
-           is_absolute: false,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\"],
+        has_root: true,
+        is_absolute: false,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("c:",
-           iter: ["c:"],
-           has_root: false,
-           is_absolute: false,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["c:"],
+        has_root: false,
+        is_absolute: false,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("c:\\",
-           iter: ["c:", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["c:", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("c:/",
-           iter: ["c:", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["c:", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("/foo",
-           iter: ["\\", "foo"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["\\", "foo"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("/foo/",
-           iter: ["\\", "foo"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["\\", "foo"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/bar",
-           iter: ["foo", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("/foo/bar",
-           iter: ["\\", "foo", "bar"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("/foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["\\", "foo", "bar"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("/foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("///foo///",
-           iter: ["\\", "foo"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("/"),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["\\", "foo"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("/"),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("///foo///bar",
-           iter: ["\\", "foo", "bar"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("///foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["\\", "foo", "bar"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("///foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("./.",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("/..",
-           iter: ["\\", ".."],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("/"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\", ".."],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("/"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("../",
-           iter: [".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: [".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/.",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/..",
-           iter: ["foo", ".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["foo", ".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/./",
-           iter: ["foo"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: Some("foo"),
-           file_stem: Some("foo"),
-           extension: None
-           );
+        iter: ["foo"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: Some("foo"),
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo/./bar",
-           iter: ["foo", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("foo/../",
-           iter: ["foo", ".."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo"),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["foo", ".."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo"),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("foo/../bar",
-           iter: ["foo", "..", "bar"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("foo/.."),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
+        iter: ["foo", "..", "bar"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("foo/.."),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("./a",
-           iter: [".", "a"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("."),
-           file_name: Some("a"),
-           file_stem: Some("a"),
-           extension: None
-           );
+        iter: [".", "a"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("."),
+        file_name: Some("a"),
+        file_stem: Some("a"),
+        extension: None
+        );
 
         t!(".",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("./",
-           iter: ["."],
-           has_root: false,
-           is_absolute: false,
-           parent: Some(""),
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["."],
+        has_root: false,
+        is_absolute: false,
+        parent: Some(""),
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("a/b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a//b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a/./b",
-           iter: ["a", "b"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["a", "b"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
 
         t!("a/b/c",
            iter: ["a", "b", "c"],
@@ -3521,291 +3485,273 @@ mod tests {
            extension: None);
 
         t!("a\\b\\c",
-           iter: ["a", "b", "c"],
-           has_root: false,
-           is_absolute: false,
-           parent: Some("a\\b"),
-           file_name: Some("c"),
-           file_stem: Some("c"),
-           extension: None
-           );
+        iter: ["a", "b", "c"],
+        has_root: false,
+        is_absolute: false,
+        parent: Some("a\\b"),
+        file_name: Some("c"),
+        file_stem: Some("c"),
+        extension: None
+        );
 
         t!("\\a",
-           iter: ["\\", "a"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("\\"),
-           file_name: Some("a"),
-           file_stem: Some("a"),
-           extension: None
-           );
+        iter: ["\\", "a"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("\\"),
+        file_name: Some("a"),
+        file_stem: Some("a"),
+        extension: None
+        );
 
         t!("c:\\foo.txt",
-           iter: ["c:", "\\", "foo.txt"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("c:\\"),
-           file_name: Some("foo.txt"),
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
+        iter: ["c:", "\\", "foo.txt"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("c:\\"),
+        file_name: Some("foo.txt"),
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("\\\\server\\share\\foo.txt",
-           iter: ["\\\\server\\share", "\\", "foo.txt"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\server\\share\\"),
-           file_name: Some("foo.txt"),
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
+        iter: ["\\\\server\\share", "\\", "foo.txt"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\server\\share\\"),
+        file_name: Some("foo.txt"),
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("\\\\server\\share",
-           iter: ["\\\\server\\share", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\server\\share", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\server",
-           iter: ["\\", "server"],
-           has_root: true,
-           is_absolute: false,
-           parent: Some("\\"),
-           file_name: Some("server"),
-           file_stem: Some("server"),
-           extension: None
-           );
+        iter: ["\\", "server"],
+        has_root: true,
+        is_absolute: false,
+        parent: Some("\\"),
+        file_name: Some("server"),
+        file_stem: Some("server"),
+        extension: None
+        );
 
         t!("\\\\?\\bar\\foo.txt",
-           iter: ["\\\\?\\bar", "\\", "foo.txt"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\?\\bar\\"),
-           file_name: Some("foo.txt"),
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
+        iter: ["\\\\?\\bar", "\\", "foo.txt"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\?\\bar\\"),
+        file_name: Some("foo.txt"),
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("\\\\?\\bar",
-           iter: ["\\\\?\\bar"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\?\\bar"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\",
-           iter: ["\\\\?\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\?\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\UNC\\server\\share\\foo.txt",
-           iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\?\\UNC\\server\\share\\"),
-           file_name: Some("foo.txt"),
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
+        iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\?\\UNC\\server\\share\\"),
+        file_name: Some("foo.txt"),
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("\\\\?\\UNC\\server",
-           iter: ["\\\\?\\UNC\\server"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\?\\UNC\\server"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\UNC\\",
-           iter: ["\\\\?\\UNC\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\?\\UNC\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\C:\\foo.txt",
-           iter: ["\\\\?\\C:", "\\", "foo.txt"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\?\\C:\\"),
-           file_name: Some("foo.txt"),
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
-
+        iter: ["\\\\?\\C:", "\\", "foo.txt"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\?\\C:\\"),
+        file_name: Some("foo.txt"),
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("\\\\?\\C:\\",
-           iter: ["\\\\?\\C:", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\?\\C:", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\C:",
-           iter: ["\\\\?\\C:"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\?\\C:"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\foo/bar",
-           iter: ["\\\\?\\foo/bar"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\?\\foo/bar"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\C:/foo",
-           iter: ["\\\\?\\C:/foo"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\?\\C:/foo"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\.\\foo\\bar",
-           iter: ["\\\\.\\foo", "\\", "bar"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\.\\foo\\"),
-           file_name: Some("bar"),
-           file_stem: Some("bar"),
-           extension: None
-           );
-
+        iter: ["\\\\.\\foo", "\\", "bar"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\.\\foo\\"),
+        file_name: Some("bar"),
+        file_stem: Some("bar"),
+        extension: None
+        );
 
         t!("\\\\.\\foo",
-           iter: ["\\\\.\\foo", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\.\\foo", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\.\\foo/bar",
-           iter: ["\\\\.\\foo/bar", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
-
+        iter: ["\\\\.\\foo/bar", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\.\\foo\\bar/baz",
-           iter: ["\\\\.\\foo", "\\", "bar", "baz"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\.\\foo\\bar"),
-           file_name: Some("baz"),
-           file_stem: Some("baz"),
-           extension: None
-           );
-
+        iter: ["\\\\.\\foo", "\\", "bar", "baz"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\.\\foo\\bar"),
+        file_name: Some("baz"),
+        file_stem: Some("baz"),
+        extension: None
+        );
 
         t!("\\\\.\\",
-           iter: ["\\\\.\\", "\\"],
-           has_root: true,
-           is_absolute: true,
-           parent: None,
-           file_name: None,
-           file_stem: None,
-           extension: None
-           );
+        iter: ["\\\\.\\", "\\"],
+        has_root: true,
+        is_absolute: true,
+        parent: None,
+        file_name: None,
+        file_stem: None,
+        extension: None
+        );
 
         t!("\\\\?\\a\\b\\",
-           iter: ["\\\\?\\a", "\\", "b"],
-           has_root: true,
-           is_absolute: true,
-           parent: Some("\\\\?\\a\\"),
-           file_name: Some("b"),
-           file_stem: Some("b"),
-           extension: None
-           );
+        iter: ["\\\\?\\a", "\\", "b"],
+        has_root: true,
+        is_absolute: true,
+        parent: Some("\\\\?\\a\\"),
+        file_name: Some("b"),
+        file_stem: Some("b"),
+        extension: None
+        );
     }
 
     #[test]
     pub fn test_stem_ext() {
         t!("foo",
-           file_stem: Some("foo"),
-           extension: None
-           );
+        file_stem: Some("foo"),
+        extension: None
+        );
 
         t!("foo.",
-           file_stem: Some("foo"),
-           extension: Some("")
-           );
+        file_stem: Some("foo"),
+        extension: Some("")
+        );
 
         t!(".foo",
-           file_stem: Some(".foo"),
-           extension: None
-           );
+        file_stem: Some(".foo"),
+        extension: None
+        );
 
         t!("foo.txt",
-           file_stem: Some("foo"),
-           extension: Some("txt")
-           );
+        file_stem: Some("foo"),
+        extension: Some("txt")
+        );
 
         t!("foo.bar.txt",
-           file_stem: Some("foo.bar"),
-           extension: Some("txt")
-           );
+        file_stem: Some("foo.bar"),
+        extension: Some("txt")
+        );
 
         t!("foo.bar.",
-           file_stem: Some("foo.bar"),
-           extension: Some("")
-           );
+        file_stem: Some("foo.bar"),
+        extension: Some("")
+        );
 
-        t!(".",
-           file_stem: None,
-           extension: None
-           );
+        t!(".", file_stem: None, extension: None);
 
-        t!("..",
-           file_stem: None,
-           extension: None
-           );
+        t!("..", file_stem: None, extension: None);
 
-        t!("",
-           file_stem: None,
-           extension: None
-           );
+        t!("", file_stem: None, extension: None);
     }
 
     #[test]
@@ -3873,26 +3819,20 @@ mod tests {
             tp!("C:a\\b\\c", "C:d", "C:d");
             tp!("C:", r"a\b\c", r"C:a\b\c");
             tp!("C:", r"..\a", r"C:..\a");
-            tp!("\\\\server\\share\\foo",
-                "bar",
-                "\\\\server\\share\\foo\\bar");
+            tp!("\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
             tp!("\\\\server\\share\\foo", "C:baz", "C:baz");
             tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d");
             tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
             tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
             tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
-            tp!("\\\\?\\UNC\\server\\share\\foo",
-                "bar",
-                "\\\\?\\UNC\\server\\share\\foo\\bar");
+            tp!("\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
             tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
             tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a");
 
             // Note: modified from old path API
             tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo");
 
-            tp!("C:\\a",
-                "\\\\?\\UNC\\server\\share",
-                "\\\\?\\UNC\\server\\share");
+            tp!("C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
             tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
             tp!("\\\\.\\foo\\bar", "C:a", "C:a");
             // again, not sure about the following, but I'm assuming \\.\ should be verbatim
@@ -3945,15 +3885,9 @@ mod tests {
             tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
             tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true);
             tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false);
-            tp!("\\\\?\\UNC\\server\\share\\a\\b",
-                "\\\\?\\UNC\\server\\share\\a",
-                true);
-            tp!("\\\\?\\UNC\\server\\share\\a",
-                "\\\\?\\UNC\\server\\share\\",
-                true);
-            tp!("\\\\?\\UNC\\server\\share",
-                "\\\\?\\UNC\\server\\share",
-                false);
+            tp!("\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
+            tp!("\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share\\", true);
+            tp!("\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
             tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
             tp!("\\\\.\\a\\b", "\\\\.\\a\\", true);
             tp!("\\\\.\\a", "\\\\.\\a", false);
@@ -4051,8 +3985,8 @@ mod tests {
 
     #[test]
     pub fn test_compare() {
-        use crate::hash::{Hash, Hasher};
         use crate::collections::hash_map::DefaultHasher;
+        use crate::hash::{Hash, Hasher};
 
         fn hash<T: Hash>(t: T) -> u64 {
             let mut s = DefaultHasher::new();
@@ -4095,83 +4029,83 @@ mod tests {
         );
 
         tc!("", "",
-            eq: true,
-            starts_with: true,
-            ends_with: true,
-            relative_from: Some("")
-            );
+        eq: true,
+        starts_with: true,
+        ends_with: true,
+        relative_from: Some("")
+        );
 
         tc!("foo", "",
-            eq: false,
-            starts_with: true,
-            ends_with: true,
-            relative_from: Some("foo")
-            );
+        eq: false,
+        starts_with: true,
+        ends_with: true,
+        relative_from: Some("foo")
+        );
 
         tc!("", "foo",
-            eq: false,
-            starts_with: false,
-            ends_with: false,
-            relative_from: None
-            );
+        eq: false,
+        starts_with: false,
+        ends_with: false,
+        relative_from: None
+        );
 
         tc!("foo", "foo",
-            eq: true,
-            starts_with: true,
-            ends_with: true,
-            relative_from: Some("")
-            );
+        eq: true,
+        starts_with: true,
+        ends_with: true,
+        relative_from: Some("")
+        );
 
         tc!("foo/", "foo",
-            eq: true,
-            starts_with: true,
-            ends_with: true,
-            relative_from: Some("")
-            );
+        eq: true,
+        starts_with: true,
+        ends_with: true,
+        relative_from: Some("")
+        );
 
         tc!("foo/bar", "foo",
-            eq: false,
-            starts_with: true,
-            ends_with: false,
-            relative_from: Some("bar")
-            );
+        eq: false,
+        starts_with: true,
+        ends_with: false,
+        relative_from: Some("bar")
+        );
 
         tc!("foo/bar/baz", "foo/bar",
-            eq: false,
-            starts_with: true,
-            ends_with: false,
-            relative_from: Some("baz")
-            );
+        eq: false,
+        starts_with: true,
+        ends_with: false,
+        relative_from: Some("baz")
+        );
 
         tc!("foo/bar", "foo/bar/baz",
-            eq: false,
-            starts_with: false,
-            ends_with: false,
-            relative_from: None
-            );
+        eq: false,
+        starts_with: false,
+        ends_with: false,
+        relative_from: None
+        );
 
         tc!("./foo/bar/", ".",
+        eq: false,
+        starts_with: true,
+        ends_with: false,
+        relative_from: Some("foo/bar")
+        );
+
+        if cfg!(windows) {
+            tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
+            r"c:\src\rust\cargo-test\test",
             eq: false,
             starts_with: true,
             ends_with: false,
-            relative_from: Some("foo/bar")
+            relative_from: Some("Cargo.toml")
             );
 
-        if cfg!(windows) {
-            tc!(r"C:\src\rust\cargo-test\test\Cargo.toml",
-                r"c:\src\rust\cargo-test\test",
-                eq: false,
-                starts_with: true,
-                ends_with: false,
-                relative_from: Some("Cargo.toml")
-                );
-
             tc!(r"c:\foo", r"C:\foo",
-                eq: true,
-                starts_with: true,
-                ends_with: true,
-                relative_from: Some("")
-                );
+            eq: true,
+            starts_with: true,
+            ends_with: true,
+            relative_from: Some("")
+            );
         }
     }
 
diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs
index 3e4cf91127f..7c0efe828c2 100644
--- a/src/libstd/prelude/v1.rs
+++ b/src/libstd/prelude/v1.rs
@@ -2,8 +2,6 @@
 //!
 //! See the [module-level documentation](../index.html) for more.
 
-
-
 #![stable(feature = "rust1", since = "1.0.0")]
 
 // Re-exported core operators
@@ -22,45 +20,27 @@ pub use crate::mem::drop;
 // Re-exported types and traits
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::convert::{AsRef, AsMut, Into, From};
+pub use crate::convert::{AsMut, AsRef, From, Into};
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::iter::{Iterator, Extend, IntoIterator};
+pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator};
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator};
+pub use crate::iter::{Extend, IntoIterator, Iterator};
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::option::Option::{self, Some, None};
+pub use crate::option::Option::{self, None, Some};
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::result::Result::{self, Ok, Err};
+pub use crate::result::Result::{self, Err, Ok};
 
 // Re-exported built-in macros
 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
 #[doc(no_inline)]
 pub use core::prelude::v1::{
-    asm,
-    assert,
-    cfg,
-    column,
-    compile_error,
-    concat,
-    concat_idents,
-    env,
-    file,
-    format_args,
-    format_args_nl,
-    global_asm,
-    include,
-    include_bytes,
-    include_str,
-    line,
-    log_syntax,
-    module_path,
-    option_env,
-    stringify,
-    trace_macros,
+    asm, assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args,
+    format_args_nl, global_asm, include, include_bytes, include_str, line, log_syntax, module_path,
+    option_env, stringify, trace_macros,
 };
 
 // FIXME: Attribute and derive macros are not documented because for them rustdoc generates
@@ -69,21 +49,8 @@ pub use core::prelude::v1::{
 #[allow(deprecated)]
 #[doc(hidden)]
 pub use core::prelude::v1::{
-    Clone,
-    Copy,
-    Debug,
-    Default,
-    Eq,
-    Hash,
-    Ord,
-    PartialEq,
-    PartialOrd,
-    RustcDecodable,
-    RustcEncodable,
-    bench,
-    global_allocator,
-    test,
-    test_case,
+    bench, global_allocator, test, test_case, Clone, Copy, Debug, Default, Eq, Hash, Ord,
+    PartialEq, PartialOrd, RustcDecodable, RustcEncodable,
 };
 
 // The file so far is equivalent to src/libcore/prelude/v1.rs,
@@ -91,13 +58,12 @@ pub use core::prelude::v1::{
 // Those files are duplicated rather than using glob imports
 // because we want docs to show these re-exports as pointing to within `std`.
 
-
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::boxed::Box;
+pub use crate::borrow::ToOwned;
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
-pub use crate::borrow::ToOwned;
+pub use crate::boxed::Box;
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(no_inline)]
 pub use crate::string::{String, ToString};
diff --git a/src/libstd/process.rs b/src/libstd/process.rs
index b1274a08cbe..3eee45d000c 100644
--- a/src/libstd/process.rs
+++ b/src/libstd/process.rs
@@ -186,7 +186,9 @@ pub struct Child {
 }
 
 impl AsInner<imp::Process> for Child {
-    fn as_inner(&self) -> &imp::Process { &self.handle }
+    fn as_inner(&self) -> &imp::Process {
+        &self.handle
+    }
 }
 
 impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
@@ -201,7 +203,9 @@ impl FromInner<(imp::Process, imp::StdioPipes)> for Child {
 }
 
 impl IntoInner<imp::Process> for Child {
-    fn into_inner(self) -> imp::Process { self.handle }
+    fn into_inner(self) -> imp::Process {
+        self.handle
+    }
 }
 
 #[stable(feature = "std_debug", since = "1.16.0")]
@@ -228,7 +232,7 @@ impl fmt::Debug for Child {
 /// [dropped]: ../ops/trait.Drop.html
 #[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStdin {
-    inner: AnonPipe
+    inner: AnonPipe,
 }
 
 #[stable(feature = "process", since = "1.0.0")]
@@ -247,11 +251,15 @@ impl Write for ChildStdin {
 }
 
 impl AsInner<AnonPipe> for ChildStdin {
-    fn as_inner(&self) -> &AnonPipe { &self.inner }
+    fn as_inner(&self) -> &AnonPipe {
+        &self.inner
+    }
 }
 
 impl IntoInner<AnonPipe> for ChildStdin {
-    fn into_inner(self) -> AnonPipe { self.inner }
+    fn into_inner(self) -> AnonPipe {
+        self.inner
+    }
 }
 
 impl FromInner<AnonPipe> for ChildStdin {
@@ -279,7 +287,7 @@ impl fmt::Debug for ChildStdin {
 /// [dropped]: ../ops/trait.Drop.html
 #[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStdout {
-    inner: AnonPipe
+    inner: AnonPipe,
 }
 
 #[stable(feature = "process", since = "1.0.0")]
@@ -299,11 +307,15 @@ impl Read for ChildStdout {
 }
 
 impl AsInner<AnonPipe> for ChildStdout {
-    fn as_inner(&self) -> &AnonPipe { &self.inner }
+    fn as_inner(&self) -> &AnonPipe {
+        &self.inner
+    }
 }
 
 impl IntoInner<AnonPipe> for ChildStdout {
-    fn into_inner(self) -> AnonPipe { self.inner }
+    fn into_inner(self) -> AnonPipe {
+        self.inner
+    }
 }
 
 impl FromInner<AnonPipe> for ChildStdout {
@@ -331,7 +343,7 @@ impl fmt::Debug for ChildStdout {
 /// [dropped]: ../ops/trait.Drop.html
 #[stable(feature = "process", since = "1.0.0")]
 pub struct ChildStderr {
-    inner: AnonPipe
+    inner: AnonPipe,
 }
 
 #[stable(feature = "process", since = "1.0.0")]
@@ -351,11 +363,15 @@ impl Read for ChildStderr {
 }
 
 impl AsInner<AnonPipe> for ChildStderr {
-    fn as_inner(&self) -> &AnonPipe { &self.inner }
+    fn as_inner(&self) -> &AnonPipe {
+        &self.inner
+    }
 }
 
 impl IntoInner<AnonPipe> for ChildStderr {
-    fn into_inner(self) -> AnonPipe { self.inner }
+    fn into_inner(self) -> AnonPipe {
+        self.inner
+    }
 }
 
 impl FromInner<AnonPipe> for ChildStderr {
@@ -533,7 +549,9 @@ impl Command {
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
     pub fn args<I, S>(&mut self, args: I) -> &mut Command
-        where I: IntoIterator<Item=S>, S: AsRef<OsStr>
+    where
+        I: IntoIterator<Item = S>,
+        S: AsRef<OsStr>,
     {
         for arg in args {
             self.arg(arg.as_ref());
@@ -560,7 +578,9 @@ impl Command {
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
     pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
-        where K: AsRef<OsStr>, V: AsRef<OsStr>
+    where
+        K: AsRef<OsStr>,
+        V: AsRef<OsStr>,
     {
         self.inner.env_mut().set(key.as_ref(), val.as_ref());
         self
@@ -592,7 +612,10 @@ impl Command {
     /// ```
     #[stable(feature = "command_envs", since = "1.19.0")]
     pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
-        where I: IntoIterator<Item=(K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>
+    where
+        I: IntoIterator<Item = (K, V)>,
+        K: AsRef<OsStr>,
+        V: AsRef<OsStr>,
     {
         for (ref key, ref val) in vars {
             self.inner.env_mut().set(key.as_ref(), val.as_ref());
@@ -794,7 +817,9 @@ impl Command {
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
     pub fn output(&mut self) -> io::Result<Output> {
-        self.inner.spawn(imp::Stdio::MakePipe, false).map(Child::from_inner)
+        self.inner
+            .spawn(imp::Stdio::MakePipe, false)
+            .map(Child::from_inner)
             .and_then(|p| p.wait_with_output())
     }
 
@@ -819,8 +844,10 @@ impl Command {
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
     pub fn status(&mut self) -> io::Result<ExitStatus> {
-        self.inner.spawn(imp::Stdio::Inherit, true).map(Child::from_inner)
-                  .and_then(|mut p| p.wait())
+        self.inner
+            .spawn(imp::Stdio::Inherit, true)
+            .map(Child::from_inner)
+            .and_then(|mut p| p.wait())
     }
 }
 
@@ -835,11 +862,15 @@ impl fmt::Debug for Command {
 }
 
 impl AsInner<imp::Command> for Command {
-    fn as_inner(&self) -> &imp::Command { &self.inner }
+    fn as_inner(&self) -> &imp::Command {
+        &self.inner
+    }
 }
 
 impl AsInnerMut<imp::Command> for Command {
-    fn as_inner_mut(&mut self) -> &mut imp::Command { &mut self.inner }
+    fn as_inner_mut(&mut self) -> &mut imp::Command {
+        &mut self.inner
+    }
 }
 
 /// The output of a finished process.
@@ -871,17 +902,16 @@ pub struct Output {
 #[stable(feature = "process_output_debug", since = "1.7.0")]
 impl fmt::Debug for Output {
     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
-
         let stdout_utf8 = str::from_utf8(&self.stdout);
         let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
             Ok(ref str) => str,
-            Err(_) => &self.stdout
+            Err(_) => &self.stdout,
         };
 
         let stderr_utf8 = str::from_utf8(&self.stderr);
         let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
             Ok(ref str) => str,
-            Err(_) => &self.stderr
+            Err(_) => &self.stderr,
         };
 
         fmt.debug_struct("Output")
@@ -943,7 +973,9 @@ impl Stdio {
     /// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
-    pub fn piped() -> Stdio { Stdio(imp::Stdio::MakePipe) }
+    pub fn piped() -> Stdio {
+        Stdio(imp::Stdio::MakePipe)
+    }
 
     /// The child inherits from the corresponding parent descriptor.
     ///
@@ -980,7 +1012,9 @@ impl Stdio {
     /// io::stdout().write_all(&output.stdout).unwrap();
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
-    pub fn inherit() -> Stdio { Stdio(imp::Stdio::Inherit) }
+    pub fn inherit() -> Stdio {
+        Stdio(imp::Stdio::Inherit)
+    }
 
     /// This stream will be ignored. This is the equivalent of attaching the
     /// stream to `/dev/null`
@@ -1017,7 +1051,9 @@ impl Stdio {
     /// // Ignores any piped-in input
     /// ```
     #[stable(feature = "process", since = "1.0.0")]
-    pub fn null() -> Stdio { Stdio(imp::Stdio::Null) }
+    pub fn null() -> Stdio {
+        Stdio(imp::Stdio::Null)
+    }
 }
 
 impl FromInner<imp::Stdio> for Stdio {
@@ -1217,7 +1253,9 @@ impl ExitStatus {
 }
 
 impl AsInner<imp::ExitStatus> for ExitStatus {
-    fn as_inner(&self) -> &imp::ExitStatus { &self.0 }
+    fn as_inner(&self) -> &imp::ExitStatus {
+        &self.0
+    }
 }
 
 impl FromInner<imp::ExitStatus> for ExitStatus {
@@ -1449,11 +1487,7 @@ impl Child {
         }
 
         let status = self.wait()?;
-        Ok(Output {
-            status,
-            stdout,
-            stderr,
-        })
+        Ok(Output { status, stdout, stderr })
     }
 }
 
@@ -1604,8 +1638,9 @@ pub fn id() -> u32 {
 #[cfg_attr(not(test), lang = "termination")]
 #[unstable(feature = "termination_trait_lib", issue = "43301")]
 #[rustc_on_unimplemented(
-  message="`main` has invalid return type `{Self}`",
-  label="`main` can only return types that implement `{Termination}`")]
+    message = "`main` has invalid return type `{Self}`",
+    label = "`main` can only return types that implement `{Termination}`"
+)]
 pub trait Termination {
     /// Is called to get the representation of the value as status code.
     /// This status code is returned to the operating system.
@@ -1615,7 +1650,9 @@ pub trait Termination {
 #[unstable(feature = "termination_trait_lib", issue = "43301")]
 impl Termination for () {
     #[inline]
-    fn report(self) -> i32 { ExitCode::SUCCESS.report() }
+    fn report(self) -> i32 {
+        ExitCode::SUCCESS.report()
+    }
 }
 
 #[unstable(feature = "termination_trait_lib", issue = "43301")]
@@ -1630,7 +1667,9 @@ impl<E: fmt::Debug> Termination for Result<(), E> {
 
 #[unstable(feature = "termination_trait_lib", issue = "43301")]
 impl Termination for ! {
-    fn report(self) -> i32 { self }
+    fn report(self) -> i32 {
+        self
+    }
 }
 
 #[unstable(feature = "termination_trait_lib", issue = "43301")]
@@ -1654,9 +1693,9 @@ impl Termination for ExitCode {
 mod tests {
     use crate::io::prelude::*;
 
+    use super::{Command, Output, Stdio};
     use crate::io::ErrorKind;
     use crate::str;
-    use super::{Command, Output, Stdio};
 
     // FIXME(#10380) these tests should not all be ignored on android.
 
@@ -1702,15 +1741,12 @@ mod tests {
     fn signal_reported_right() {
         use crate::os::unix::process::ExitStatusExt;
 
-        let mut p = Command::new("/bin/sh")
-                            .arg("-c").arg("read a")
-                            .stdin(Stdio::piped())
-                            .spawn().unwrap();
+        let mut p =
+            Command::new("/bin/sh").arg("-c").arg("read a").stdin(Stdio::piped()).spawn().unwrap();
         p.kill().unwrap();
         match p.wait().unwrap().signal() {
-            Some(9) => {},
-            result => panic!("not terminated by signal 9 (instead, {:?})",
-                             result),
+            Some(9) => {}
+            result => panic!("not terminated by signal 9 (instead, {:?})", result),
         }
     }
 
@@ -1743,9 +1779,7 @@ mod tests {
     #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
     fn set_current_dir_works() {
         let mut cmd = Command::new("/bin/sh");
-        cmd.arg("-c").arg("pwd")
-           .current_dir("/")
-           .stdout(Stdio::piped());
+        cmd.arg("-c").arg("pwd").current_dir("/").stdout(Stdio::piped());
         assert_eq!(run_output(cmd), "/\n");
     }
 
@@ -1753,10 +1787,12 @@ mod tests {
     #[cfg_attr(any(windows, target_os = "android", target_os = "vxworks"), ignore)]
     fn stdin_works() {
         let mut p = Command::new("/bin/sh")
-                            .arg("-c").arg("read line; echo $line")
-                            .stdin(Stdio::piped())
-                            .stdout(Stdio::piped())
-                            .spawn().unwrap();
+            .arg("-c")
+            .arg("read line; echo $line")
+            .stdin(Stdio::piped())
+            .stdout(Stdio::piped())
+            .spawn()
+            .unwrap();
         p.stdin.as_mut().unwrap().write("foobar".as_bytes()).unwrap();
         drop(p.stdin.take());
         let mut out = String::new();
@@ -1787,19 +1823,18 @@ mod tests {
     fn test_process_output_fail_to_start() {
         match Command::new("/no-binary-by-this-name-should-exist").output() {
             Err(e) => assert_eq!(e.kind(), ErrorKind::NotFound),
-            Ok(..) => panic!()
+            Ok(..) => panic!(),
         }
     }
 
     #[test]
     #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
     fn test_process_output_output() {
-        let Output {status, stdout, stderr}
-             = if cfg!(target_os = "windows") {
-                 Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
-             } else {
-                 Command::new("echo").arg("hello").output().unwrap()
-             };
+        let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
+            Command::new("cmd").args(&["/C", "echo hello"]).output().unwrap()
+        } else {
+            Command::new("echo").arg("hello").output().unwrap()
+        };
         let output_str = str::from_utf8(&stdout).unwrap();
 
         assert!(status.success());
@@ -1810,12 +1845,11 @@ mod tests {
     #[test]
     #[cfg_attr(any(target_os = "vxworks", target_os = "android"), ignore)]
     fn test_process_output_error() {
-        let Output {status, stdout, stderr}
-             = if cfg!(target_os = "windows") {
-                 Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
-             } else {
-                 Command::new("mkdir").arg("./").output().unwrap()
-             };
+        let Output { status, stdout, stderr } = if cfg!(target_os = "windows") {
+            Command::new("cmd").args(&["/C", "mkdir ."]).output().unwrap()
+        } else {
+            Command::new("mkdir").arg("./").output().unwrap()
+        };
 
         assert!(status.code() == Some(1));
         assert_eq!(stdout, Vec::new());
@@ -1854,7 +1888,7 @@ mod tests {
             Command::new("echo").arg("hello").stdout(Stdio::piped()).spawn().unwrap()
         };
 
-        let Output {status, stdout, stderr} = prog.wait_with_output().unwrap();
+        let Output { status, stdout, stderr } = prog.wait_with_output().unwrap();
         let output_str = str::from_utf8(&stdout).unwrap();
 
         assert!(status.success());
@@ -1862,11 +1896,11 @@ mod tests {
         assert_eq!(stderr, Vec::new());
     }
 
-    #[cfg(all(unix, not(target_os="android")))]
+    #[cfg(all(unix, not(target_os = "android")))]
     pub fn env_cmd() -> Command {
         Command::new("env")
     }
-    #[cfg(target_os="android")]
+    #[cfg(target_os = "android")]
     pub fn env_cmd() -> Command {
         let mut cmd = Command::new("/system/bin/sh");
         cmd.arg("-c").arg("set");
@@ -1897,8 +1931,11 @@ mod tests {
         let result = cmd.output().unwrap();
         let output = String::from_utf8_lossy(&result.stdout).to_string();
 
-        assert!(output.contains("RUN_TEST_NEW_ENV=123"),
-                "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
+        assert!(
+            output.contains("RUN_TEST_NEW_ENV=123"),
+            "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
+            output
+        );
     }
 
     #[test]
@@ -1907,8 +1944,11 @@ mod tests {
         let result = env_cmd().env("RUN_TEST_NEW_ENV", "123").output().unwrap();
         let output = String::from_utf8_lossy(&result.stdout).to_string();
 
-        assert!(output.contains("RUN_TEST_NEW_ENV=123"),
-                "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}", output);
+        assert!(
+            output.contains("RUN_TEST_NEW_ENV=123"),
+            "didn't find RUN_TEST_NEW_ENV inside of:\n\n{}",
+            output
+        );
     }
 
     #[test]
@@ -1927,10 +1967,16 @@ mod tests {
 
         let output = String::from_utf8_lossy(&result.stdout).to_string();
 
-        assert!(output.contains("RUN_TEST_NEW_ENV1=123"),
-                "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}", output);
-        assert!(output.contains("RUN_TEST_NEW_ENV2=456"),
-                "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}", output);
+        assert!(
+            output.contains("RUN_TEST_NEW_ENV1=123"),
+            "didn't find RUN_TEST_NEW_ENV1 inside of:\n\n{}",
+            output
+        );
+        assert!(
+            output.contains("RUN_TEST_NEW_ENV2=456"),
+            "didn't find RUN_TEST_NEW_ENV2 inside of:\n\n{}",
+            output
+        );
     }
 
     // Regression tests for #30858.
@@ -2005,8 +2051,11 @@ mod tests {
 
         extern "system" {
             fn WaitForDebugEvent(lpDebugEvent: *mut DEBUG_EVENT, dwMilliseconds: DWORD) -> BOOL;
-            fn ContinueDebugEvent(dwProcessId: DWORD, dwThreadId: DWORD,
-                                  dwContinueStatus: DWORD) -> BOOL;
+            fn ContinueDebugEvent(
+                dwProcessId: DWORD,
+                dwThreadId: DWORD,
+                dwContinueStatus: DWORD,
+            ) -> BOOL;
         }
 
         const DEBUG_PROCESS: DWORD = 1;
@@ -2015,15 +2064,12 @@ mod tests {
 
         let mut child = Command::new("cmd")
             .creation_flags(DEBUG_PROCESS)
-            .stdin(Stdio::piped()).spawn().unwrap();
+            .stdin(Stdio::piped())
+            .spawn()
+            .unwrap();
         child.stdin.take().unwrap().write_all(b"exit\r\n").unwrap();
         let mut events = 0;
-        let mut event = DEBUG_EVENT {
-            event_code: 0,
-            process_id: 0,
-            thread_id: 0,
-            _junk: [0; 164],
-        };
+        let mut event = DEBUG_EVENT { event_code: 0, process_id: 0, thread_id: 0, _junk: [0; 164] };
         loop {
             if unsafe { WaitForDebugEvent(&mut event as *mut DEBUG_EVENT, INFINITE) } == 0 {
                 panic!("WaitForDebugEvent failed!");
@@ -2034,9 +2080,10 @@ mod tests {
                 break;
             }
 
-            if unsafe { ContinueDebugEvent(event.process_id,
-                                           event.thread_id,
-                                           DBG_EXCEPTION_NOT_HANDLED) } == 0 {
+            if unsafe {
+                ContinueDebugEvent(event.process_id, event.thread_id, DBG_EXCEPTION_NOT_HANDLED)
+            } == 0
+            {
                 panic!("ContinueDebugEvent failed!");
             }
         }
diff --git a/src/libstd/rt.rs b/src/libstd/rt.rs
index 63e35d5ed91..1ed984509d2 100644
--- a/src/libstd/rt.rs
+++ b/src/libstd/rt.rs
@@ -6,21 +6,25 @@
 //! and should be considered as private implementation details for the
 //! time being.
 
-#![unstable(feature = "rt",
-            reason = "this public module should not exist and is highly likely \
-                      to disappear",
-            issue = "0")]
+#![unstable(
+    feature = "rt",
+    reason = "this public module should not exist and is highly likely \
+              to disappear",
+    issue = "0"
+)]
 #![doc(hidden)]
 
-
 // Re-export some of our utilities which are expected by other crates.
 pub use crate::panicking::{begin_panic, begin_panic_fmt, update_panic_count};
 
 // To reduce the generated code of the new `lang_start`, this function is doing
 // the real work.
 #[cfg(not(test))]
-fn lang_start_internal(main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe),
-                       argc: isize, argv: *const *const u8) -> isize {
+fn lang_start_internal(
+    main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindSafe),
+    argc: isize,
+    argv: *const *const u8,
+) -> isize {
     use crate::panic;
     use crate::sys;
     use crate::sys_common;
@@ -55,8 +59,10 @@ fn lang_start_internal(main: &(dyn Fn() -> i32 + Sync + crate::panic::RefUnwindS
 
 #[cfg(not(test))]
 #[lang = "start"]
-fn lang_start<T: crate::process::Termination + 'static>
-    (main: fn() -> T, argc: isize, argv: *const *const u8) -> isize
-{
+fn lang_start<T: crate::process::Termination + 'static>(
+    main: fn() -> T,
+    argc: isize,
+    argv: *const *const u8,
+) -> isize {
     lang_start_internal(&move || main().report(), argc, argv)
 }
diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs
index 23ba63a6109..eddbdff257a 100644
--- a/src/libstd/sync/barrier.rs
+++ b/src/libstd/sync/barrier.rs
@@ -1,5 +1,5 @@
 use crate::fmt;
-use crate::sync::{Mutex, Condvar};
+use crate::sync::{Condvar, Mutex};
 
 /// A barrier enables multiple threads to synchronize the beginning
 /// of some computation.
@@ -82,10 +82,7 @@ impl Barrier {
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new(n: usize) -> Barrier {
         Barrier {
-            lock: Mutex::new(BarrierState {
-                count: 0,
-                generation_id: 0,
-            }),
+            lock: Mutex::new(BarrierState { count: 0, generation_id: 0 }),
             cvar: Condvar::new(),
             num_threads: n,
         }
@@ -135,8 +132,7 @@ impl Barrier {
         if lock.count < self.num_threads {
             // We need a while loop to guard against spurious wakeups.
             // http://en.wikipedia.org/wiki/Spurious_wakeup
-            while local_gen == lock.generation_id &&
-                  lock.count < self.num_threads {
+            while local_gen == lock.generation_id && lock.count < self.num_threads {
                 lock = self.cvar.wait(lock).unwrap();
             }
             BarrierWaitResult(false)
@@ -152,9 +148,7 @@ impl Barrier {
 #[stable(feature = "std_debug", since = "1.16.0")]
 impl fmt::Debug for BarrierWaitResult {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("BarrierWaitResult")
-            .field("is_leader", &self.is_leader())
-            .finish()
+        f.debug_struct("BarrierWaitResult").field("is_leader", &self.is_leader()).finish()
     }
 }
 
@@ -176,13 +170,15 @@ impl BarrierWaitResult {
     /// println!("{:?}", barrier_wait_result.is_leader());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn is_leader(&self) -> bool { self.0 }
+    pub fn is_leader(&self) -> bool {
+        self.0
+    }
 }
 
 #[cfg(test)]
 mod tests {
-    use crate::sync::{Arc, Barrier};
     use crate::sync::mpsc::{channel, TryRecvError};
+    use crate::sync::{Arc, Barrier};
     use crate::thread;
 
     #[test]
@@ -196,7 +192,7 @@ mod tests {
         for _ in 0..N - 1 {
             let c = barrier.clone();
             let tx = tx.clone();
-            thread::spawn(move|| {
+            thread::spawn(move || {
                 tx.send(c.wait().is_leader()).unwrap();
             });
         }
diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs
index 6eacfaec253..d34de6a4fac 100644
--- a/src/libstd/sync/mpsc/blocking.rs
+++ b/src/libstd/sync/mpsc/blocking.rs
@@ -1,9 +1,9 @@
 //! Generic support for building blocking abstractions.
 
-use crate::thread::{self, Thread};
+use crate::mem;
 use crate::sync::atomic::{AtomicBool, Ordering};
 use crate::sync::Arc;
-use crate::mem;
+use crate::thread::{self, Thread};
 use crate::time::Instant;
 
 struct Inner {
@@ -28,16 +28,9 @@ impl !Send for WaitToken {}
 impl !Sync for WaitToken {}
 
 pub fn tokens() -> (WaitToken, SignalToken) {
-    let inner = Arc::new(Inner {
-        thread: thread::current(),
-        woken: AtomicBool::new(false),
-    });
-    let wait_token = WaitToken {
-        inner: inner.clone(),
-    };
-    let signal_token = SignalToken {
-        inner,
-    };
+    let inner = Arc::new(Inner { thread: thread::current(), woken: AtomicBool::new(false) });
+    let wait_token = WaitToken { inner: inner.clone() };
+    let signal_token = SignalToken { inner };
     (wait_token, signal_token)
 }
 
diff --git a/src/libstd/sync/mpsc/cache_aligned.rs b/src/libstd/sync/mpsc/cache_aligned.rs
index b14a9e5d61b..b0842144328 100644
--- a/src/libstd/sync/mpsc/cache_aligned.rs
+++ b/src/libstd/sync/mpsc/cache_aligned.rs
@@ -8,16 +8,16 @@ pub(super) struct Aligner;
 pub(super) struct CacheAligned<T>(pub T, pub Aligner);
 
 impl<T> Deref for CacheAligned<T> {
-     type Target = T;
-     fn deref(&self) -> &Self::Target {
-         &self.0
-     }
+    type Target = T;
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
 }
 
 impl<T> DerefMut for CacheAligned<T> {
-     fn deref_mut(&mut self) -> &mut Self::Target {
-         &mut self.0
-     }
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.0
+    }
 }
 
 impl<T> CacheAligned<T> {
diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs
index c2884a28f3c..2831bbcb88d 100644
--- a/src/libstd/sync/mpsc/mod.rs
+++ b/src/libstd/sync/mpsc/mod.rs
@@ -269,20 +269,20 @@
 // And now that you've seen all the races that I found and attempted to fix,
 // here's the code for you to find some more!
 
-use crate::sync::Arc;
+use crate::cell::UnsafeCell;
 use crate::error;
 use crate::fmt;
 use crate::mem;
-use crate::cell::UnsafeCell;
+use crate::sync::Arc;
 use crate::time::{Duration, Instant};
 
 mod blocking;
+mod mpsc_queue;
 mod oneshot;
 mod shared;
+mod spsc_queue;
 mod stream;
 mod sync;
-mod mpsc_queue;
-mod spsc_queue;
 
 mod cache_aligned;
 
@@ -322,10 +322,10 @@ pub struct Receiver<T> {
 // The receiver port can be sent from place to place, so long as it
 // is not used to receive non-sendable things.
 #[stable(feature = "rust1", since = "1.0.0")]
-unsafe impl<T: Send> Send for Receiver<T> { }
+unsafe impl<T: Send> Send for Receiver<T> {}
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> !Sync for Receiver<T> { }
+impl<T> !Sync for Receiver<T> {}
 
 /// An iterator over messages on a [`Receiver`], created by [`iter`].
 ///
@@ -359,7 +359,7 @@ impl<T> !Sync for Receiver<T> { }
 #[stable(feature = "rust1", since = "1.0.0")]
 #[derive(Debug)]
 pub struct Iter<'a, T: 'a> {
-    rx: &'a Receiver<T>
+    rx: &'a Receiver<T>,
 }
 
 /// An iterator that attempts to yield all pending values for a [`Receiver`],
@@ -404,7 +404,7 @@ pub struct Iter<'a, T: 'a> {
 #[stable(feature = "receiver_try_iter", since = "1.15.0")]
 #[derive(Debug)]
 pub struct TryIter<'a, T: 'a> {
-    rx: &'a Receiver<T>
+    rx: &'a Receiver<T>,
 }
 
 /// An owning iterator over messages on a [`Receiver`],
@@ -439,7 +439,7 @@ pub struct TryIter<'a, T: 'a> {
 #[stable(feature = "receiver_into_iter", since = "1.1.0")]
 #[derive(Debug)]
 pub struct IntoIter<T> {
-    rx: Receiver<T>
+    rx: Receiver<T>,
 }
 
 /// The sending-half of Rust's asynchronous [`channel`] type. This half can only be
@@ -482,10 +482,10 @@ pub struct Sender<T> {
 // The send port can be sent from place to place, so long as it
 // is not used to send non-sendable things.
 #[stable(feature = "rust1", since = "1.0.0")]
-unsafe impl<T: Send> Send for Sender<T> { }
+unsafe impl<T: Send> Send for Sender<T> {}
 
 #[stable(feature = "rust1", since = "1.0.0")]
-impl<T> !Sync for Sender<T> { }
+impl<T> !Sync for Sender<T> {}
 
 /// The sending-half of Rust's synchronous [`sync_channel`] type.
 ///
@@ -772,9 +772,7 @@ pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) {
 
 impl<T> Sender<T> {
     fn new(inner: Flavor<T>) -> Sender<T> {
-        Sender {
-            inner: UnsafeCell::new(inner),
-        }
+        Sender { inner: UnsafeCell::new(inner) }
     }
 
     /// Attempts to send a value on this channel, returning it back if it could
@@ -856,8 +854,7 @@ impl<T> Clone for Sender<T> {
                     let guard = a.postinit_lock();
                     let rx = Receiver::new(Flavor::Shared(a.clone()));
                     let sleeper = match p.upgrade(rx) {
-                        oneshot::UpSuccess |
-                        oneshot::UpDisconnected => None,
+                        oneshot::UpSuccess | oneshot::UpDisconnected => None,
                         oneshot::UpWoke(task) => Some(task),
                     };
                     a.inherit_blocker(sleeper, guard);
@@ -870,8 +867,7 @@ impl<T> Clone for Sender<T> {
                     let guard = a.postinit_lock();
                     let rx = Receiver::new(Flavor::Shared(a.clone()));
                     let sleeper = match p.upgrade(rx) {
-                        stream::UpSuccess |
-                        stream::UpDisconnected => None,
+                        stream::UpSuccess | stream::UpDisconnected => None,
                         stream::UpWoke(task) => Some(task),
                     };
                     a.inherit_blocker(sleeper, guard);
@@ -1078,48 +1074,31 @@ impl<T> Receiver<T> {
     pub fn try_recv(&self) -> Result<T, TryRecvError> {
         loop {
             let new_port = match *unsafe { self.inner() } {
-                Flavor::Oneshot(ref p) => {
-                    match p.try_recv() {
-                        Ok(t) => return Ok(t),
-                        Err(oneshot::Empty) => return Err(TryRecvError::Empty),
-                        Err(oneshot::Disconnected) => {
-                            return Err(TryRecvError::Disconnected)
-                        }
-                        Err(oneshot::Upgraded(rx)) => rx,
-                    }
-                }
-                Flavor::Stream(ref p) => {
-                    match p.try_recv() {
-                        Ok(t) => return Ok(t),
-                        Err(stream::Empty) => return Err(TryRecvError::Empty),
-                        Err(stream::Disconnected) => {
-                            return Err(TryRecvError::Disconnected)
-                        }
-                        Err(stream::Upgraded(rx)) => rx,
-                    }
-                }
-                Flavor::Shared(ref p) => {
-                    match p.try_recv() {
-                        Ok(t) => return Ok(t),
-                        Err(shared::Empty) => return Err(TryRecvError::Empty),
-                        Err(shared::Disconnected) => {
-                            return Err(TryRecvError::Disconnected)
-                        }
-                    }
-                }
-                Flavor::Sync(ref p) => {
-                    match p.try_recv() {
-                        Ok(t) => return Ok(t),
-                        Err(sync::Empty) => return Err(TryRecvError::Empty),
-                        Err(sync::Disconnected) => {
-                            return Err(TryRecvError::Disconnected)
-                        }
-                    }
-                }
+                Flavor::Oneshot(ref p) => match p.try_recv() {
+                    Ok(t) => return Ok(t),
+                    Err(oneshot::Empty) => return Err(TryRecvError::Empty),
+                    Err(oneshot::Disconnected) => return Err(TryRecvError::Disconnected),
+                    Err(oneshot::Upgraded(rx)) => rx,
+                },
+                Flavor::Stream(ref p) => match p.try_recv() {
+                    Ok(t) => return Ok(t),
+                    Err(stream::Empty) => return Err(TryRecvError::Empty),
+                    Err(stream::Disconnected) => return Err(TryRecvError::Disconnected),
+                    Err(stream::Upgraded(rx)) => rx,
+                },
+                Flavor::Shared(ref p) => match p.try_recv() {
+                    Ok(t) => return Ok(t),
+                    Err(shared::Empty) => return Err(TryRecvError::Empty),
+                    Err(shared::Disconnected) => return Err(TryRecvError::Disconnected),
+                },
+                Flavor::Sync(ref p) => match p.try_recv() {
+                    Ok(t) => return Ok(t),
+                    Err(sync::Empty) => return Err(TryRecvError::Empty),
+                    Err(sync::Disconnected) => return Err(TryRecvError::Disconnected),
+                },
             };
             unsafe {
-                mem::swap(self.inner_mut(),
-                          new_port.inner_mut());
+                mem::swap(self.inner_mut(), new_port.inner_mut());
             }
         }
     }
@@ -1185,29 +1164,23 @@ impl<T> Receiver<T> {
     pub fn recv(&self) -> Result<T, RecvError> {
         loop {
             let new_port = match *unsafe { self.inner() } {
-                Flavor::Oneshot(ref p) => {
-                    match p.recv(None) {
-                        Ok(t) => return Ok(t),
-                        Err(oneshot::Disconnected) => return Err(RecvError),
-                        Err(oneshot::Upgraded(rx)) => rx,
-                        Err(oneshot::Empty) => unreachable!(),
-                    }
-                }
-                Flavor::Stream(ref p) => {
-                    match p.recv(None) {
-                        Ok(t) => return Ok(t),
-                        Err(stream::Disconnected) => return Err(RecvError),
-                        Err(stream::Upgraded(rx)) => rx,
-                        Err(stream::Empty) => unreachable!(),
-                    }
-                }
-                Flavor::Shared(ref p) => {
-                    match p.recv(None) {
-                        Ok(t) => return Ok(t),
-                        Err(shared::Disconnected) => return Err(RecvError),
-                        Err(shared::Empty) => unreachable!(),
-                    }
-                }
+                Flavor::Oneshot(ref p) => match p.recv(None) {
+                    Ok(t) => return Ok(t),
+                    Err(oneshot::Disconnected) => return Err(RecvError),
+                    Err(oneshot::Upgraded(rx)) => rx,
+                    Err(oneshot::Empty) => unreachable!(),
+                },
+                Flavor::Stream(ref p) => match p.recv(None) {
+                    Ok(t) => return Ok(t),
+                    Err(stream::Disconnected) => return Err(RecvError),
+                    Err(stream::Upgraded(rx)) => rx,
+                    Err(stream::Empty) => unreachable!(),
+                },
+                Flavor::Shared(ref p) => match p.recv(None) {
+                    Ok(t) => return Ok(t),
+                    Err(shared::Disconnected) => return Err(RecvError),
+                    Err(shared::Empty) => unreachable!(),
+                },
                 Flavor::Sync(ref p) => return p.recv(None).map_err(|_| RecvError),
             };
             unsafe {
@@ -1383,36 +1356,28 @@ impl<T> Receiver<T> {
 
         loop {
             let port_or_empty = match *unsafe { self.inner() } {
-                Flavor::Oneshot(ref p) => {
-                    match p.recv(Some(deadline)) {
-                        Ok(t) => return Ok(t),
-                        Err(oneshot::Disconnected) => return Err(Disconnected),
-                        Err(oneshot::Upgraded(rx)) => Some(rx),
-                        Err(oneshot::Empty) => None,
-                    }
-                }
-                Flavor::Stream(ref p) => {
-                    match p.recv(Some(deadline)) {
-                        Ok(t) => return Ok(t),
-                        Err(stream::Disconnected) => return Err(Disconnected),
-                        Err(stream::Upgraded(rx)) => Some(rx),
-                        Err(stream::Empty) => None,
-                    }
-                }
-                Flavor::Shared(ref p) => {
-                    match p.recv(Some(deadline)) {
-                        Ok(t) => return Ok(t),
-                        Err(shared::Disconnected) => return Err(Disconnected),
-                        Err(shared::Empty) => None,
-                    }
-                }
-                Flavor::Sync(ref p) => {
-                    match p.recv(Some(deadline)) {
-                        Ok(t) => return Ok(t),
-                        Err(sync::Disconnected) => return Err(Disconnected),
-                        Err(sync::Empty) => None,
-                    }
-                }
+                Flavor::Oneshot(ref p) => match p.recv(Some(deadline)) {
+                    Ok(t) => return Ok(t),
+                    Err(oneshot::Disconnected) => return Err(Disconnected),
+                    Err(oneshot::Upgraded(rx)) => Some(rx),
+                    Err(oneshot::Empty) => None,
+                },
+                Flavor::Stream(ref p) => match p.recv(Some(deadline)) {
+                    Ok(t) => return Ok(t),
+                    Err(stream::Disconnected) => return Err(Disconnected),
+                    Err(stream::Upgraded(rx)) => Some(rx),
+                    Err(stream::Empty) => None,
+                },
+                Flavor::Shared(ref p) => match p.recv(Some(deadline)) {
+                    Ok(t) => return Ok(t),
+                    Err(shared::Disconnected) => return Err(Disconnected),
+                    Err(shared::Empty) => None,
+                },
+                Flavor::Sync(ref p) => match p.recv(Some(deadline)) {
+                    Ok(t) => return Ok(t),
+                    Err(sync::Disconnected) => return Err(Disconnected),
+                    Err(sync::Empty) => None,
+                },
             };
 
             if let Some(new_port) = port_or_empty {
@@ -1502,21 +1467,24 @@ impl<T> Receiver<T> {
     pub fn try_iter(&self) -> TryIter<'_, T> {
         TryIter { rx: self }
     }
-
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<'a, T> Iterator for Iter<'a, T> {
     type Item = T;
 
-    fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
+    fn next(&mut self) -> Option<T> {
+        self.rx.recv().ok()
+    }
 }
 
 #[stable(feature = "receiver_try_iter", since = "1.15.0")]
 impl<'a, T> Iterator for TryIter<'a, T> {
     type Item = T;
 
-    fn next(&mut self) -> Option<T> { self.rx.try_recv().ok() }
+    fn next(&mut self) -> Option<T> {
+        self.rx.try_recv().ok()
+    }
 }
 
 #[stable(feature = "receiver_into_iter", since = "1.1.0")]
@@ -1524,17 +1492,21 @@ impl<'a, T> IntoIterator for &'a Receiver<T> {
     type Item = T;
     type IntoIter = Iter<'a, T>;
 
-    fn into_iter(self) -> Iter<'a, T> { self.iter() }
+    fn into_iter(self) -> Iter<'a, T> {
+        self.iter()
+    }
 }
 
 #[stable(feature = "receiver_into_iter", since = "1.1.0")]
 impl<T> Iterator for IntoIter<T> {
     type Item = T;
-    fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
+    fn next(&mut self) -> Option<T> {
+        self.rx.recv().ok()
+    }
 }
 
 #[stable(feature = "receiver_into_iter", since = "1.1.0")]
-impl <T> IntoIterator for Receiver<T> {
+impl<T> IntoIterator for Receiver<T> {
     type Item = T;
     type IntoIter = IntoIter<T>;
 
@@ -1597,27 +1569,18 @@ impl<T> fmt::Debug for TrySendError<T> {
 impl<T> fmt::Display for TrySendError<T> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
-            TrySendError::Full(..) => {
-                "sending on a full channel".fmt(f)
-            }
-            TrySendError::Disconnected(..) => {
-                "sending on a closed channel".fmt(f)
-            }
+            TrySendError::Full(..) => "sending on a full channel".fmt(f),
+            TrySendError::Disconnected(..) => "sending on a closed channel".fmt(f),
         }
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl<T: Send> error::Error for TrySendError<T> {
-
     fn description(&self) -> &str {
         match *self {
-            TrySendError::Full(..) => {
-                "sending on a full channel"
-            }
-            TrySendError::Disconnected(..) => {
-                "sending on a closed channel"
-            }
+            TrySendError::Full(..) => "sending on a full channel",
+            TrySendError::Disconnected(..) => "sending on a closed channel",
         }
     }
 }
@@ -1640,7 +1603,6 @@ impl fmt::Display for RecvError {
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl error::Error for RecvError {
-
     fn description(&self) -> &str {
         "receiving on a closed channel"
     }
@@ -1650,27 +1612,18 @@ impl error::Error for RecvError {
 impl fmt::Display for TryRecvError {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
-            TryRecvError::Empty => {
-                "receiving on an empty channel".fmt(f)
-            }
-            TryRecvError::Disconnected => {
-                "receiving on a closed channel".fmt(f)
-            }
+            TryRecvError::Empty => "receiving on an empty channel".fmt(f),
+            TryRecvError::Disconnected => "receiving on a closed channel".fmt(f),
         }
     }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl error::Error for TryRecvError {
-
     fn description(&self) -> &str {
         match *self {
-            TryRecvError::Empty => {
-                "receiving on an empty channel"
-            }
-            TryRecvError::Disconnected => {
-                "receiving on a closed channel"
-            }
+            TryRecvError::Empty => "receiving on an empty channel",
+            TryRecvError::Disconnected => "receiving on a closed channel",
         }
     }
 }
@@ -1688,12 +1641,8 @@ impl From<RecvError> for TryRecvError {
 impl fmt::Display for RecvTimeoutError {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
-            RecvTimeoutError::Timeout => {
-                "timed out waiting on channel".fmt(f)
-            }
-            RecvTimeoutError::Disconnected => {
-                "channel is empty and sending half is closed".fmt(f)
-            }
+            RecvTimeoutError::Timeout => "timed out waiting on channel".fmt(f),
+            RecvTimeoutError::Disconnected => "channel is empty and sending half is closed".fmt(f),
         }
     }
 }
@@ -1702,12 +1651,8 @@ impl fmt::Display for RecvTimeoutError {
 impl error::Error for RecvTimeoutError {
     fn description(&self) -> &str {
         match *self {
-            RecvTimeoutError::Timeout => {
-                "timed out waiting on channel"
-            }
-            RecvTimeoutError::Disconnected => {
-                "channel is empty and sending half is closed"
-            }
+            RecvTimeoutError::Timeout => "timed out waiting on channel",
+            RecvTimeoutError::Disconnected => "channel is empty and sending half is closed",
         }
     }
 }
@@ -1769,7 +1714,7 @@ mod tests {
     #[test]
     fn smoke_threads() {
         let (tx, rx) = channel::<i32>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             tx.send(1).unwrap();
         });
         assert_eq!(rx.recv().unwrap(), 1);
@@ -1801,7 +1746,7 @@ mod tests {
     #[test]
     fn port_gone_concurrent() {
         let (tx, rx) = channel::<i32>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap();
         });
         while tx.send(1).is_ok() {}
@@ -1811,7 +1756,7 @@ mod tests {
     fn port_gone_concurrent_shared() {
         let (tx, rx) = channel::<i32>();
         let tx2 = tx.clone();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap();
         });
         while tx.send(1).is_ok() && tx2.send(1).is_ok() {}
@@ -1836,7 +1781,7 @@ mod tests {
     #[test]
     fn chan_gone_concurrent() {
         let (tx, rx) = channel::<i32>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             tx.send(1).unwrap();
             tx.send(1).unwrap();
         });
@@ -1846,8 +1791,10 @@ mod tests {
     #[test]
     fn stress() {
         let (tx, rx) = channel::<i32>();
-        let t = thread::spawn(move|| {
-            for _ in 0..10000 { tx.send(1).unwrap(); }
+        let t = thread::spawn(move || {
+            for _ in 0..10000 {
+                tx.send(1).unwrap();
+            }
         });
         for _ in 0..10000 {
             assert_eq!(rx.recv().unwrap(), 1);
@@ -1861,7 +1808,7 @@ mod tests {
         const NTHREADS: u32 = 8;
         let (tx, rx) = channel::<i32>();
 
-        let t = thread::spawn(move|| {
+        let t = thread::spawn(move || {
             for _ in 0..AMT * NTHREADS {
                 assert_eq!(rx.recv().unwrap(), 1);
             }
@@ -1873,8 +1820,10 @@ mod tests {
 
         for _ in 0..NTHREADS {
             let tx = tx.clone();
-            thread::spawn(move|| {
-                for _ in 0..AMT { tx.send(1).unwrap(); }
+            thread::spawn(move || {
+                for _ in 0..AMT {
+                    tx.send(1).unwrap();
+                }
             });
         }
         drop(tx);
@@ -1885,14 +1834,14 @@ mod tests {
     fn send_from_outside_runtime() {
         let (tx1, rx1) = channel::<()>();
         let (tx2, rx2) = channel::<i32>();
-        let t1 = thread::spawn(move|| {
+        let t1 = thread::spawn(move || {
             tx1.send(()).unwrap();
             for _ in 0..40 {
                 assert_eq!(rx2.recv().unwrap(), 1);
             }
         });
         rx1.recv().unwrap();
-        let t2 = thread::spawn(move|| {
+        let t2 = thread::spawn(move || {
             for _ in 0..40 {
                 tx2.send(1).unwrap();
             }
@@ -1904,7 +1853,7 @@ mod tests {
     #[test]
     fn recv_from_outside_runtime() {
         let (tx, rx) = channel::<i32>();
-        let t = thread::spawn(move|| {
+        let t = thread::spawn(move || {
             for _ in 0..40 {
                 assert_eq!(rx.recv().unwrap(), 1);
             }
@@ -1919,11 +1868,11 @@ mod tests {
     fn no_runtime() {
         let (tx1, rx1) = channel::<i32>();
         let (tx2, rx2) = channel::<i32>();
-        let t1 = thread::spawn(move|| {
+        let t1 = thread::spawn(move || {
             assert_eq!(rx1.recv().unwrap(), 1);
             tx2.send(2).unwrap();
         });
-        let t2 = thread::spawn(move|| {
+        let t2 = thread::spawn(move || {
             tx1.send(1).unwrap();
             assert_eq!(rx2.recv().unwrap(), 2);
         });
@@ -1956,11 +1905,12 @@ mod tests {
     #[test]
     fn oneshot_single_thread_recv_chan_close() {
         // Receiving on a closed chan will panic
-        let res = thread::spawn(move|| {
+        let res = thread::spawn(move || {
             let (tx, rx) = channel::<i32>();
             drop(tx);
             rx.recv().unwrap();
-        }).join();
+        })
+        .join();
         // What is our res?
         assert!(res.is_err());
     }
@@ -2025,7 +1975,7 @@ mod tests {
     #[test]
     fn oneshot_multi_task_recv_then_send() {
         let (tx, rx) = channel::<Box<i32>>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             assert!(*rx.recv().unwrap() == 10);
         });
 
@@ -2035,12 +1985,13 @@ mod tests {
     #[test]
     fn oneshot_multi_task_recv_then_close() {
         let (tx, rx) = channel::<Box<i32>>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             drop(tx);
         });
-        let res = thread::spawn(move|| {
+        let res = thread::spawn(move || {
             assert!(*rx.recv().unwrap() == 10);
-        }).join();
+        })
+        .join();
         assert!(res.is_err());
     }
 
@@ -2048,7 +1999,7 @@ mod tests {
     fn oneshot_multi_thread_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = channel::<i32>();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 drop(rx);
             });
             drop(tx);
@@ -2059,12 +2010,13 @@ mod tests {
     fn oneshot_multi_thread_send_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = channel::<i32>();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 drop(rx);
             });
-            let _ = thread::spawn(move|| {
+            let _ = thread::spawn(move || {
                 tx.send(1).unwrap();
-            }).join();
+            })
+            .join();
         }
     }
 
@@ -2072,14 +2024,15 @@ mod tests {
     fn oneshot_multi_thread_recv_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = channel::<i32>();
-            thread::spawn(move|| {
-                let res = thread::spawn(move|| {
+            thread::spawn(move || {
+                let res = thread::spawn(move || {
                     rx.recv().unwrap();
-                }).join();
+                })
+                .join();
                 assert!(res.is_err());
             });
-            let _t = thread::spawn(move|| {
-                thread::spawn(move|| {
+            let _t = thread::spawn(move || {
+                thread::spawn(move || {
                     drop(tx);
                 });
             });
@@ -2090,7 +2043,7 @@ mod tests {
     fn oneshot_multi_thread_send_recv_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = channel::<Box<isize>>();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 tx.send(box 10).unwrap();
             });
             assert!(*rx.recv().unwrap() == 10);
@@ -2106,18 +2059,22 @@ mod tests {
             recv(rx, 0);
 
             fn send(tx: Sender<Box<i32>>, i: i32) {
-                if i == 10 { return }
+                if i == 10 {
+                    return;
+                }
 
-                thread::spawn(move|| {
+                thread::spawn(move || {
                     tx.send(box i).unwrap();
                     send(tx, i + 1);
                 });
             }
 
             fn recv(rx: Receiver<Box<i32>>, i: i32) {
-                if i == 10 { return }
+                if i == 10 {
+                    return;
+                }
 
-                thread::spawn(move|| {
+                thread::spawn(move || {
                     assert!(*rx.recv().unwrap() == i);
                     recv(rx, i + 1);
                 });
@@ -2214,9 +2171,8 @@ mod tests {
     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
     fn very_long_recv_timeout_wont_panic() {
         let (tx, rx) = channel::<()>();
-        let join_handle = thread::spawn(move || {
-            rx.recv_timeout(Duration::from_secs(u64::max_value()))
-        });
+        let join_handle =
+            thread::spawn(move || rx.recv_timeout(Duration::from_secs(u64::max_value())));
         thread::sleep(Duration::from_secs(1));
         assert!(tx.send(()).is_ok());
         assert_eq!(join_handle.join().unwrap(), Ok(()));
@@ -2226,8 +2182,12 @@ mod tests {
     fn recv_a_lot() {
         // Regression test that we don't run out of stack in scheduler context
         let (tx, rx) = channel();
-        for _ in 0..10000 { tx.send(()).unwrap(); }
-        for _ in 0..10000 { rx.recv().unwrap(); }
+        for _ in 0..10000 {
+            tx.send(()).unwrap();
+        }
+        for _ in 0..10000 {
+            rx.recv().unwrap();
+        }
     }
 
     #[test]
@@ -2237,12 +2197,14 @@ mod tests {
         let total = 5;
         for _ in 0..total {
             let tx = tx.clone();
-            thread::spawn(move|| {
+            thread::spawn(move || {
                 tx.send(()).unwrap();
             });
         }
 
-        for _ in 0..total { rx.recv().unwrap(); }
+        for _ in 0..total {
+            rx.recv().unwrap();
+        }
 
         assert_eq!(rx.recv_timeout(Duration::from_millis(1)), Err(RecvTimeoutError::Timeout));
         tx.send(()).unwrap();
@@ -2255,7 +2217,7 @@ mod tests {
         let total = stress_factor() + 100;
         for _ in 0..total {
             let tx = tx.clone();
-            thread::spawn(move|| {
+            thread::spawn(move || {
                 tx.send(()).unwrap();
             });
         }
@@ -2270,7 +2232,7 @@ mod tests {
         let (tx, rx) = channel::<i32>();
         let (total_tx, total_rx) = channel::<i32>();
 
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             let mut acc = 0;
             for x in rx.iter() {
                 acc += x;
@@ -2290,7 +2252,7 @@ mod tests {
         let (tx, rx) = channel::<i32>();
         let (count_tx, count_rx) = channel();
 
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             let mut count = 0;
             for x in rx.iter() {
                 if count >= 3 {
@@ -2316,7 +2278,7 @@ mod tests {
         let (response_tx, response_rx) = channel();
 
         // Request `x`s until we have `6`.
-        let t = thread::spawn(move|| {
+        let t = thread::spawn(move || {
             let mut count = 0;
             loop {
                 for x in response_rx.try_iter() {
@@ -2341,11 +2303,11 @@ mod tests {
     #[test]
     fn test_recv_into_iter_owned() {
         let mut iter = {
-          let (tx, rx) = channel::<i32>();
-          tx.send(1).unwrap();
-          tx.send(2).unwrap();
+            let (tx, rx) = channel::<i32>();
+            tx.send(1).unwrap();
+            tx.send(2).unwrap();
 
-          rx.into_iter()
+            rx.into_iter()
         };
         assert_eq!(iter.next().unwrap(), 1);
         assert_eq!(iter.next().unwrap(), 2);
@@ -2369,7 +2331,7 @@ mod tests {
         let (tx1, rx1) = channel::<i32>();
         let (tx2, rx2) = channel::<()>();
         let (tx3, rx3) = channel::<()>();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx2.recv().unwrap();
             tx1.send(1).unwrap();
             tx3.send(()).unwrap();
@@ -2394,13 +2356,15 @@ mod tests {
     fn destroy_upgraded_shared_port_when_sender_still_active() {
         let (tx, rx) = channel();
         let (tx2, rx2) = channel();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap(); // wait on a oneshot
-            drop(rx);  // destroy a shared
+            drop(rx); // destroy a shared
             tx2.send(()).unwrap();
         });
         // make sure the other thread has gone to sleep
-        for _ in 0..5000 { thread::yield_now(); }
+        for _ in 0..5000 {
+            thread::yield_now();
+        }
 
         // upgrade to a shared chan and send a message
         let t = tx.clone();
@@ -2468,7 +2432,7 @@ mod sync_tests {
     #[test]
     fn smoke_threads() {
         let (tx, rx) = sync_channel::<i32>(0);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             tx.send(1).unwrap();
         });
         assert_eq!(rx.recv().unwrap(), 1);
@@ -2493,7 +2457,7 @@ mod sync_tests {
     #[test]
     fn port_gone_concurrent() {
         let (tx, rx) = sync_channel::<i32>(0);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap();
         });
         while tx.send(1).is_ok() {}
@@ -2503,7 +2467,7 @@ mod sync_tests {
     fn port_gone_concurrent_shared() {
         let (tx, rx) = sync_channel::<i32>(0);
         let tx2 = tx.clone();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap();
         });
         while tx.send(1).is_ok() && tx2.send(1).is_ok() {}
@@ -2528,7 +2492,7 @@ mod sync_tests {
     #[test]
     fn chan_gone_concurrent() {
         let (tx, rx) = sync_channel::<i32>(0);
-        thread::spawn(move|| {
+        thread::spawn(move || {
             tx.send(1).unwrap();
             tx.send(1).unwrap();
         });
@@ -2538,8 +2502,10 @@ mod sync_tests {
     #[test]
     fn stress() {
         let (tx, rx) = sync_channel::<i32>(0);
-        thread::spawn(move|| {
-            for _ in 0..10000 { tx.send(1).unwrap(); }
+        thread::spawn(move || {
+            for _ in 0..10000 {
+                tx.send(1).unwrap();
+            }
         });
         for _ in 0..10000 {
             assert_eq!(rx.recv().unwrap(), 1);
@@ -2551,8 +2517,10 @@ mod sync_tests {
     fn stress_recv_timeout_two_threads() {
         let (tx, rx) = sync_channel::<i32>(0);
 
-        thread::spawn(move|| {
-            for _ in 0..10000 { tx.send(1).unwrap(); }
+        thread::spawn(move || {
+            for _ in 0..10000 {
+                tx.send(1).unwrap();
+            }
         });
 
         let mut recv_count = 0;
@@ -2561,7 +2529,7 @@ mod sync_tests {
                 Ok(v) => {
                     assert_eq!(v, 1);
                     recv_count += 1;
-                },
+                }
                 Err(RecvTimeoutError::Timeout) => continue,
                 Err(RecvTimeoutError::Disconnected) => break,
             }
@@ -2578,14 +2546,14 @@ mod sync_tests {
         let (tx, rx) = sync_channel::<i32>(0);
         let (dtx, drx) = sync_channel::<()>(0);
 
-        thread::spawn(move|| {
+        thread::spawn(move || {
             let mut recv_count = 0;
             loop {
                 match rx.recv_timeout(Duration::from_millis(10)) {
                     Ok(v) => {
                         assert_eq!(v, 1);
                         recv_count += 1;
-                    },
+                    }
                     Err(RecvTimeoutError::Timeout) => continue,
                     Err(RecvTimeoutError::Disconnected) => break,
                 }
@@ -2599,8 +2567,10 @@ mod sync_tests {
 
         for _ in 0..NTHREADS {
             let tx = tx.clone();
-            thread::spawn(move|| {
-                for _ in 0..AMT { tx.send(1).unwrap(); }
+            thread::spawn(move || {
+                for _ in 0..AMT {
+                    tx.send(1).unwrap();
+                }
             });
         }
 
@@ -2616,7 +2586,7 @@ mod sync_tests {
         let (tx, rx) = sync_channel::<i32>(0);
         let (dtx, drx) = sync_channel::<()>(0);
 
-        thread::spawn(move|| {
+        thread::spawn(move || {
             for _ in 0..AMT * NTHREADS {
                 assert_eq!(rx.recv().unwrap(), 1);
             }
@@ -2629,8 +2599,10 @@ mod sync_tests {
 
         for _ in 0..NTHREADS {
             let tx = tx.clone();
-            thread::spawn(move|| {
-                for _ in 0..AMT { tx.send(1).unwrap(); }
+            thread::spawn(move || {
+                for _ in 0..AMT {
+                    tx.send(1).unwrap();
+                }
             });
         }
         drop(tx);
@@ -2662,11 +2634,12 @@ mod sync_tests {
     #[test]
     fn oneshot_single_thread_recv_chan_close() {
         // Receiving on a closed chan will panic
-        let res = thread::spawn(move|| {
+        let res = thread::spawn(move || {
             let (tx, rx) = sync_channel::<i32>(0);
             drop(tx);
             rx.recv().unwrap();
-        }).join();
+        })
+        .join();
         // What is our res?
         assert!(res.is_err());
     }
@@ -2746,7 +2719,7 @@ mod sync_tests {
     #[test]
     fn oneshot_multi_task_recv_then_send() {
         let (tx, rx) = sync_channel::<Box<i32>>(0);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             assert!(*rx.recv().unwrap() == 10);
         });
 
@@ -2756,12 +2729,13 @@ mod sync_tests {
     #[test]
     fn oneshot_multi_task_recv_then_close() {
         let (tx, rx) = sync_channel::<Box<i32>>(0);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             drop(tx);
         });
-        let res = thread::spawn(move|| {
+        let res = thread::spawn(move || {
             assert!(*rx.recv().unwrap() == 10);
-        }).join();
+        })
+        .join();
         assert!(res.is_err());
     }
 
@@ -2769,7 +2743,7 @@ mod sync_tests {
     fn oneshot_multi_thread_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = sync_channel::<i32>(0);
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 drop(rx);
             });
             drop(tx);
@@ -2780,12 +2754,13 @@ mod sync_tests {
     fn oneshot_multi_thread_send_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = sync_channel::<i32>(0);
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 drop(rx);
             });
             let _ = thread::spawn(move || {
                 tx.send(1).unwrap();
-            }).join();
+            })
+            .join();
         }
     }
 
@@ -2793,14 +2768,15 @@ mod sync_tests {
     fn oneshot_multi_thread_recv_close_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = sync_channel::<i32>(0);
-            let _t = thread::spawn(move|| {
-                let res = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
+                let res = thread::spawn(move || {
                     rx.recv().unwrap();
-                }).join();
+                })
+                .join();
                 assert!(res.is_err());
             });
-            let _t = thread::spawn(move|| {
-                thread::spawn(move|| {
+            let _t = thread::spawn(move || {
+                thread::spawn(move || {
                     drop(tx);
                 });
             });
@@ -2811,7 +2787,7 @@ mod sync_tests {
     fn oneshot_multi_thread_send_recv_stress() {
         for _ in 0..stress_factor() {
             let (tx, rx) = sync_channel::<Box<i32>>(0);
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 tx.send(box 10).unwrap();
             });
             assert!(*rx.recv().unwrap() == 10);
@@ -2827,18 +2803,22 @@ mod sync_tests {
             recv(rx, 0);
 
             fn send(tx: SyncSender<Box<i32>>, i: i32) {
-                if i == 10 { return }
+                if i == 10 {
+                    return;
+                }
 
-                thread::spawn(move|| {
+                thread::spawn(move || {
                     tx.send(box i).unwrap();
                     send(tx, i + 1);
                 });
             }
 
             fn recv(rx: Receiver<Box<i32>>, i: i32) {
-                if i == 10 { return }
+                if i == 10 {
+                    return;
+                }
 
-                thread::spawn(move|| {
+                thread::spawn(move || {
                     assert!(*rx.recv().unwrap() == i);
                     recv(rx, i + 1);
                 });
@@ -2850,8 +2830,12 @@ mod sync_tests {
     fn recv_a_lot() {
         // Regression test that we don't run out of stack in scheduler context
         let (tx, rx) = sync_channel(10000);
-        for _ in 0..10000 { tx.send(()).unwrap(); }
-        for _ in 0..10000 { rx.recv().unwrap(); }
+        for _ in 0..10000 {
+            tx.send(()).unwrap();
+        }
+        for _ in 0..10000 {
+            rx.recv().unwrap();
+        }
     }
 
     #[test]
@@ -2860,7 +2844,7 @@ mod sync_tests {
         let total = stress_factor() + 100;
         for _ in 0..total {
             let tx = tx.clone();
-            thread::spawn(move|| {
+            thread::spawn(move || {
                 tx.send(()).unwrap();
             });
         }
@@ -2875,7 +2859,7 @@ mod sync_tests {
         let (tx, rx) = sync_channel::<i32>(0);
         let (total_tx, total_rx) = sync_channel::<i32>(0);
 
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             let mut acc = 0;
             for x in rx.iter() {
                 acc += x;
@@ -2895,7 +2879,7 @@ mod sync_tests {
         let (tx, rx) = sync_channel::<i32>(0);
         let (count_tx, count_rx) = sync_channel(0);
 
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             let mut count = 0;
             for x in rx.iter() {
                 if count >= 3 {
@@ -2920,7 +2904,7 @@ mod sync_tests {
         let (tx1, rx1) = sync_channel::<i32>(1);
         let (tx2, rx2) = sync_channel::<()>(1);
         let (tx3, rx3) = sync_channel::<()>(1);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx2.recv().unwrap();
             tx1.send(1).unwrap();
             tx3.send(()).unwrap();
@@ -2945,13 +2929,15 @@ mod sync_tests {
     fn destroy_upgraded_shared_port_when_sender_still_active() {
         let (tx, rx) = sync_channel::<()>(0);
         let (tx2, rx2) = sync_channel::<()>(0);
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             rx.recv().unwrap(); // wait on a oneshot
-            drop(rx);  // destroy a shared
+            drop(rx); // destroy a shared
             tx2.send(()).unwrap();
         });
         // make sure the other thread has gone to sleep
-        for _ in 0..5000 { thread::yield_now(); }
+        for _ in 0..5000 {
+            thread::yield_now();
+        }
 
         // upgrade to a shared chan and send a message
         let t = tx.clone();
@@ -2965,14 +2951,18 @@ mod sync_tests {
     #[test]
     fn send1() {
         let (tx, rx) = sync_channel::<i32>(0);
-        let _t = thread::spawn(move|| { rx.recv().unwrap(); });
+        let _t = thread::spawn(move || {
+            rx.recv().unwrap();
+        });
         assert_eq!(tx.send(1), Ok(()));
     }
 
     #[test]
     fn send2() {
         let (tx, rx) = sync_channel::<i32>(0);
-        let _t = thread::spawn(move|| { drop(rx); });
+        let _t = thread::spawn(move || {
+            drop(rx);
+        });
         assert!(tx.send(1).is_err());
     }
 
@@ -2980,7 +2970,9 @@ mod sync_tests {
     fn send3() {
         let (tx, rx) = sync_channel::<i32>(1);
         assert_eq!(tx.send(1), Ok(()));
-        let _t =thread::spawn(move|| { drop(rx); });
+        let _t = thread::spawn(move || {
+            drop(rx);
+        });
         assert!(tx.send(1).is_err());
     }
 
@@ -2990,11 +2982,11 @@ mod sync_tests {
         let tx2 = tx.clone();
         let (done, donerx) = channel();
         let done2 = done.clone();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             assert!(tx.send(1).is_err());
             done.send(()).unwrap();
         });
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             assert!(tx2.send(2).is_err());
             done2.send(()).unwrap();
         });
@@ -3030,7 +3022,7 @@ mod sync_tests {
             let (tx1, rx1) = sync_channel::<()>(3);
             let (tx2, rx2) = sync_channel::<()>(3);
 
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 rx1.recv().unwrap();
                 tx2.try_send(()).unwrap();
             });
diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs
index 8f5681b97f4..6e7a7be4430 100644
--- a/src/libstd/sync/mpsc/mpsc_queue.rs
+++ b/src/libstd/sync/mpsc/mpsc_queue.rs
@@ -13,8 +13,8 @@
 
 pub use self::PopResult::*;
 
-use core::ptr;
 use core::cell::UnsafeCell;
+use core::ptr;
 
 use crate::boxed::Box;
 use crate::sync::atomic::{AtomicPtr, Ordering};
@@ -45,15 +45,12 @@ pub struct Queue<T> {
     tail: UnsafeCell<*mut Node<T>>,
 }
 
-unsafe impl<T: Send> Send for Queue<T> { }
-unsafe impl<T: Send> Sync for Queue<T> { }
+unsafe impl<T: Send> Send for Queue<T> {}
+unsafe impl<T: Send> Sync for Queue<T> {}
 
 impl<T> Node<T> {
     unsafe fn new(v: Option<T>) -> *mut Node<T> {
-        Box::into_raw(box Node {
-            next: AtomicPtr::new(ptr::null_mut()),
-            value: v,
-        })
+        Box::into_raw(box Node { next: AtomicPtr::new(ptr::null_mut()), value: v })
     }
 }
 
@@ -62,10 +59,7 @@ impl<T> Queue<T> {
     /// one consumer.
     pub fn new() -> Queue<T> {
         let stub = unsafe { Node::new(None) };
-        Queue {
-            head: AtomicPtr::new(stub),
-            tail: UnsafeCell::new(stub),
-        }
+        Queue { head: AtomicPtr::new(stub), tail: UnsafeCell::new(stub) }
     }
 
     /// Pushes a new value onto this queue.
@@ -101,7 +95,7 @@ impl<T> Queue<T> {
                 return Data(ret);
             }
 
-            if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
+            if self.head.load(Ordering::Acquire) == tail { Empty } else { Inconsistent }
         }
     }
 }
@@ -121,7 +115,7 @@ impl<T> Drop for Queue<T> {
 
 #[cfg(all(test, not(target_os = "emscripten")))]
 mod tests {
-    use super::{Queue, Data, Empty, Inconsistent};
+    use super::{Data, Empty, Inconsistent, Queue};
     use crate::sync::mpsc::channel;
     use crate::sync::Arc;
     use crate::thread;
@@ -140,7 +134,7 @@ mod tests {
         let q = Queue::new();
         match q.pop() {
             Empty => {}
-            Inconsistent | Data(..) => panic!()
+            Inconsistent | Data(..) => panic!(),
         }
         let (tx, rx) = channel();
         let q = Arc::new(q);
@@ -148,7 +142,7 @@ mod tests {
         for _ in 0..nthreads {
             let tx = tx.clone();
             let q = q.clone();
-            thread::spawn(move|| {
+            thread::spawn(move || {
                 for i in 0..nmsgs {
                     q.push(i);
                 }
@@ -159,8 +153,8 @@ mod tests {
         let mut i = 0;
         while i < nthreads * nmsgs {
             match q.pop() {
-                Empty | Inconsistent => {},
-                Data(_) => { i += 1 }
+                Empty | Inconsistent => {}
+                Data(_) => i += 1,
             }
         }
         drop(tx);
diff --git a/src/libstd/sync/mpsc/oneshot.rs b/src/libstd/sync/mpsc/oneshot.rs
index e7a5cc46b31..bbe77e7d0fb 100644
--- a/src/libstd/sync/mpsc/oneshot.rs
+++ b/src/libstd/sync/mpsc/oneshot.rs
@@ -21,22 +21,21 @@
 /// consuming the port). This upgrade is then also stored in the shared packet.
 /// The one caveat to consider is that when a port sees a disconnected channel
 /// it must check for data because there is no "data plus upgrade" state.
-
 pub use self::Failure::*;
-pub use self::UpgradeResult::*;
 use self::MyUpgrade::*;
+pub use self::UpgradeResult::*;
 
-use crate::sync::mpsc::Receiver;
-use crate::sync::mpsc::blocking::{self, SignalToken};
 use crate::cell::UnsafeCell;
 use crate::ptr;
 use crate::sync::atomic::{AtomicUsize, Ordering};
+use crate::sync::mpsc::blocking::{self, SignalToken};
+use crate::sync::mpsc::Receiver;
 use crate::time::Instant;
 
 // Various states you can find a port in.
-const EMPTY: usize = 0;          // initial state: no data, no blocked receiver
-const DATA: usize = 1;           // data ready for receiver to take
-const DISCONNECTED: usize = 2;   // channel is disconnected OR upgraded
+const EMPTY: usize = 0; // initial state: no data, no blocked receiver
+const DATA: usize = 1; // data ready for receiver to take
+const DISCONNECTED: usize = 2; // channel is disconnected OR upgraded
 // Any other value represents a pointer to a SignalToken value. The
 // protocol ensures that when the state moves *to* a pointer,
 // ownership of the token is given to the packet, and when the state
@@ -178,21 +177,17 @@ impl<T> Packet<T> {
                 // and an upgrade flags the channel as disconnected, so when we see
                 // this we first need to check if there's data available and *then*
                 // we go through and process the upgrade.
-                DISCONNECTED => {
-                    match (&mut *self.data.get()).take() {
-                        Some(data) => Ok(data),
-                        None => {
-                            match ptr::replace(self.upgrade.get(), SendUsed) {
-                                SendUsed | NothingSent => Err(Disconnected),
-                                GoUp(upgrade) => Err(Upgraded(upgrade))
-                            }
-                        }
-                    }
-                }
+                DISCONNECTED => match (&mut *self.data.get()).take() {
+                    Some(data) => Ok(data),
+                    None => match ptr::replace(self.upgrade.get(), SendUsed) {
+                        SendUsed | NothingSent => Err(Disconnected),
+                        GoUp(upgrade) => Err(Upgraded(upgrade)),
+                    },
+                },
 
                 // We are the sole receiver; there cannot be a blocking
                 // receiver already.
-                _ => unreachable!()
+                _ => unreachable!(),
             }
         }
     }
@@ -217,10 +212,13 @@ impl<T> Packet<T> {
 
                 // If the other end is already disconnected, then we failed the
                 // upgrade. Be sure to trash the port we were given.
-                DISCONNECTED => { ptr::replace(self.upgrade.get(), prev); UpDisconnected }
+                DISCONNECTED => {
+                    ptr::replace(self.upgrade.get(), prev);
+                    UpDisconnected
+                }
 
                 // If someone's waiting, we gotta wake them up
-                ptr => UpWoke(SignalToken::cast_from_usize(ptr))
+                ptr => UpWoke(SignalToken::cast_from_usize(ptr)),
             }
         }
     }
@@ -232,7 +230,7 @@ impl<T> Packet<T> {
             // If someone's waiting, we gotta wake them up
             ptr => unsafe {
                 SignalToken::cast_from_usize(ptr).signal();
-            }
+            },
         }
     }
 
@@ -246,10 +244,12 @@ impl<T> Packet<T> {
             // There's data on the channel, so make sure we destroy it promptly.
             // This is why not using an arc is a little difficult (need the box
             // to stay valid while we take the data).
-            DATA => unsafe { (&mut *self.data.get()).take().unwrap(); },
+            DATA => unsafe {
+                (&mut *self.data.get()).take().unwrap();
+            },
 
             // We're the only ones that can block on this port
-            _ => unreachable!()
+            _ => unreachable!(),
         }
     }
 
@@ -265,13 +265,11 @@ impl<T> Packet<T> {
         let state = match self.state.load(Ordering::SeqCst) {
             // Each of these states means that no further activity will happen
             // with regard to abortion selection
-            s @ EMPTY |
-            s @ DATA |
-            s @ DISCONNECTED => s,
+            s @ EMPTY | s @ DATA | s @ DISCONNECTED => s,
 
             // If we've got a blocked thread, then use an atomic to gain ownership
             // of it (may fail)
-            ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
+            ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst),
         };
 
         // Now that we've got ownership of our state, figure out what to do
@@ -302,7 +300,7 @@ impl<T> Packet<T> {
             ptr => unsafe {
                 drop(SignalToken::cast_from_usize(ptr));
                 Ok(false)
-            }
+            },
         }
     }
 }
diff --git a/src/libstd/sync/mpsc/shared.rs b/src/libstd/sync/mpsc/shared.rs
index dbcdcdac932..2b0393573fd 100644
--- a/src/libstd/sync/mpsc/shared.rs
+++ b/src/libstd/sync/mpsc/shared.rs
@@ -7,7 +7,6 @@
 /// High level implementation details can be found in the comment of the parent
 /// module. You'll also note that the implementation of the shared and stream
 /// channels are quite similar, and this is no coincidence!
-
 pub use self::Failure::*;
 use self::StartResult::*;
 
@@ -17,7 +16,7 @@ use core::isize;
 
 use crate::cell::UnsafeCell;
 use crate::ptr;
-use crate::sync::atomic::{AtomicUsize, AtomicIsize, AtomicBool, Ordering};
+use crate::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering};
 use crate::sync::mpsc::blocking::{self, SignalToken};
 use crate::sync::mpsc::mpsc_queue as mpsc;
 use crate::sync::{Mutex, MutexGuard};
@@ -34,9 +33,9 @@ const MAX_STEALS: isize = 1 << 20;
 
 pub struct Packet<T> {
     queue: mpsc::Queue<T>,
-    cnt: AtomicIsize, // How many items are on this channel
+    cnt: AtomicIsize,          // How many items are on this channel
     steals: UnsafeCell<isize>, // How many times has a port received without blocking?
-    to_wake: AtomicUsize, // SignalToken for wake up
+    to_wake: AtomicUsize,      // SignalToken for wake up
 
     // The number of channels which are currently using this packet.
     channels: AtomicUsize,
@@ -92,9 +91,7 @@ impl<T> Packet<T> {
     // threads in select().
     //
     // This can only be called at channel-creation time
-    pub fn inherit_blocker(&self,
-                           token: Option<SignalToken>,
-                           guard: MutexGuard<'_, ()>) {
+    pub fn inherit_blocker(&self, token: Option<SignalToken>, guard: MutexGuard<'_, ()>) {
         token.map(|token| {
             assert_eq!(self.cnt.load(Ordering::SeqCst), 0);
             assert_eq!(self.to_wake.load(Ordering::SeqCst), 0);
@@ -119,7 +116,9 @@ impl<T> Packet<T> {
             // To offset this bad increment, we initially set the steal count to
             // -1. You'll find some special code in abort_selection() as well to
             // ensure that this -1 steal count doesn't escape too far.
-            unsafe { *self.steals.get() = -1; }
+            unsafe {
+                *self.steals.get() = -1;
+            }
         });
 
         // When the shared packet is constructed, we grabbed this lock. The
@@ -132,7 +131,9 @@ impl<T> Packet<T> {
 
     pub fn send(&self, t: T) -> Result<(), T> {
         // See Port::drop for what's going on
-        if self.port_dropped.load(Ordering::SeqCst) { return Err(t) }
+        if self.port_dropped.load(Ordering::SeqCst) {
+            return Err(t);
+        }
 
         // Note that the multiple sender case is a little trickier
         // semantically than the single sender case. The logic for
@@ -160,7 +161,7 @@ impl<T> Packet<T> {
         // received". Once we get beyond this check, we have permanently
         // entered the realm of "this may be received"
         if self.cnt.load(Ordering::SeqCst) < DISCONNECTED + FUDGE {
-            return Err(t)
+            return Err(t);
         }
 
         self.queue.push(t);
@@ -197,7 +198,7 @@ impl<T> Packet<T> {
                         // maybe we're done, if we're not the last ones
                         // here, then we need to go try again.
                         if self.sender_drain.fetch_sub(1, Ordering::SeqCst) == 1 {
-                            break
+                            break;
                         }
                     }
 
@@ -236,7 +237,10 @@ impl<T> Packet<T> {
         }
 
         match self.try_recv() {
-            data @ Ok(..) => unsafe { *self.steals.get() -= 1; data },
+            data @ Ok(..) => unsafe {
+                *self.steals.get() -= 1;
+                data
+            },
             data => data,
         }
     }
@@ -252,12 +256,16 @@ impl<T> Packet<T> {
             let steals = ptr::replace(self.steals.get(), 0);
 
             match self.cnt.fetch_sub(1 + steals, Ordering::SeqCst) {
-                DISCONNECTED => { self.cnt.store(DISCONNECTED, Ordering::SeqCst); }
+                DISCONNECTED => {
+                    self.cnt.store(DISCONNECTED, Ordering::SeqCst);
+                }
                 // If we factor in our steals and notice that the channel has no
                 // data, we successfully sleep
                 n => {
                     assert!(n >= 0);
-                    if n - steals <= 0 { return Installed }
+                    if n - steals <= 0 {
+                        return Installed;
+                    }
                 }
             }
 
@@ -290,7 +298,10 @@ impl<T> Packet<T> {
                 loop {
                     thread::yield_now();
                     match self.queue.pop() {
-                        mpsc::Data(t) => { data = t; break }
+                        mpsc::Data(t) => {
+                            data = t;
+                            break;
+                        }
                         mpsc::Empty => panic!("inconsistent => empty"),
                         mpsc::Inconsistent => {}
                     }
@@ -361,9 +372,13 @@ impl<T> Packet<T> {
         }
 
         match self.cnt.swap(DISCONNECTED, Ordering::SeqCst) {
-            -1 => { self.take_to_wake().signal(); }
+            -1 => {
+                self.take_to_wake().signal();
+            }
             DISCONNECTED => {}
-            n => { assert!(n >= 0); }
+            n => {
+                assert!(n >= 0);
+            }
         }
     }
 
@@ -380,7 +395,9 @@ impl<T> Packet<T> {
             // control of this thread.
             loop {
                 match self.queue.pop() {
-                    mpsc::Data(..) => { steals += 1; }
+                    mpsc::Data(..) => {
+                        steals += 1;
+                    }
                     mpsc::Empty | mpsc::Inconsistent => break,
                 }
             }
@@ -406,7 +423,7 @@ impl<T> Packet<T> {
                 self.cnt.store(DISCONNECTED, Ordering::SeqCst);
                 DISCONNECTED
             }
-            n => n
+            n => n,
         }
     }
 
@@ -432,7 +449,7 @@ impl<T> Packet<T> {
         // positive.
         let steals = {
             let cnt = self.cnt.load(Ordering::SeqCst);
-            if cnt < 0 && cnt != DISCONNECTED {-cnt} else {0}
+            if cnt < 0 && cnt != DISCONNECTED { -cnt } else { 0 }
         };
         let prev = self.bump(steals + 1);
 
diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs
index 0edb1c24e80..c51aa7619db 100644
--- a/src/libstd/sync/mpsc/spsc_queue.rs
+++ b/src/libstd/sync/mpsc/spsc_queue.rs
@@ -6,8 +6,8 @@
 
 // http://www.1024cores.net/home/lock-free-algorithms/queues/unbounded-spsc-queue
 
-use core::ptr;
 use core::cell::UnsafeCell;
+use core::ptr;
 
 use crate::boxed::Box;
 use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
@@ -19,16 +19,16 @@ struct Node<T> {
     // FIXME: this could be an uninitialized T if we're careful enough, and
     //      that would reduce memory usage (and be a bit faster).
     //      is it worth it?
-    value: Option<T>,           // nullable for re-use of nodes
-    cached: bool,               // This node goes into the node cache
-    next: AtomicPtr<Node<T>>,   // next node in the queue
+    value: Option<T>,         // nullable for re-use of nodes
+    cached: bool,             // This node goes into the node cache
+    next: AtomicPtr<Node<T>>, // next node in the queue
 }
 
 /// The single-producer single-consumer queue. This structure is not cloneable,
 /// but it can be safely shared in an Arc if it is guaranteed that there
 /// is only one popper and one pusher touching the queue at any one point in
 /// time.
-pub struct Queue<T, ProducerAddition=(), ConsumerAddition=()> {
+pub struct Queue<T, ProducerAddition = (), ConsumerAddition = ()> {
     // consumer fields
     consumer: CacheAligned<Consumer<T, ConsumerAddition>>,
 
@@ -38,9 +38,9 @@ pub struct Queue<T, ProducerAddition=(), ConsumerAddition=()> {
 
 struct Consumer<T, Addition> {
     tail: UnsafeCell<*mut Node<T>>, // where to pop from
-    tail_prev: AtomicPtr<Node<T>>, // where to pop from
-    cache_bound: usize, // maximum cache size
-    cached_nodes: AtomicUsize, // number of nodes marked as cachable
+    tail_prev: AtomicPtr<Node<T>>,  // where to pop from
+    cache_bound: usize,             // maximum cache size
+    cached_nodes: AtomicUsize,      // number of nodes marked as cachable
     addition: Addition,
 }
 
@@ -51,9 +51,9 @@ struct Producer<T, Addition> {
     addition: Addition,
 }
 
-unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Send for Queue<T, P, C> { }
+unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Send for Queue<T, P, C> {}
 
-unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Sync for Queue<T, P, C> { }
+unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Sync for Queue<T, P, C> {}
 
 impl<T> Node<T> {
     fn new() -> *mut Node<T> {
@@ -66,7 +66,6 @@ impl<T> Node<T> {
 }
 
 impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerAddition> {
-
     /// Creates a new queue. With given additional elements in the producer and
     /// consumer portions of the queue.
     ///
@@ -107,13 +106,13 @@ impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerA
                 tail_prev: AtomicPtr::new(n1),
                 cache_bound: bound,
                 cached_nodes: AtomicUsize::new(0),
-                addition: consumer_addition
+                addition: consumer_addition,
             }),
             producer: CacheAligned::new(Producer {
                 head: UnsafeCell::new(n2),
                 first: UnsafeCell::new(n1),
                 tail_copy: UnsafeCell::new(n1),
-                addition: producer_addition
+                addition: producer_addition,
             }),
         }
     }
@@ -142,8 +141,7 @@ impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerA
         }
         // If the above fails, then update our copy of the tail and try
         // again.
-        *self.producer.0.tail_copy.get() =
-            self.consumer.tail_prev.load(Ordering::Acquire);
+        *self.producer.0.tail_copy.get() = self.consumer.tail_prev.load(Ordering::Acquire);
         if *self.producer.first.get() != *self.producer.tail_copy.get() {
             let ret = *self.producer.first.get();
             *self.producer.0.first.get() = (*ret).next.load(Ordering::Relaxed);
@@ -164,7 +162,9 @@ impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerA
             // the current tail node is a candidate for going into the cache.
             let tail = *self.consumer.tail.get();
             let next = (*tail).next.load(Ordering::Acquire);
-            if next.is_null() { return None }
+            if next.is_null() {
+                return None;
+            }
             assert!((*next).value.is_some());
             let ret = (*next).value.take();
 
@@ -182,7 +182,8 @@ impl<T, ProducerAddition, ConsumerAddition> Queue<T, ProducerAddition, ConsumerA
                     self.consumer.tail_prev.store(tail, Ordering::Release);
                 } else {
                     (*self.consumer.tail_prev.load(Ordering::Relaxed))
-                        .next.store(next, Ordering::Relaxed);
+                        .next
+                        .store(next, Ordering::Relaxed);
                     // We have successfully erased all references to 'tail', so
                     // now we can safely drop it.
                     let _: Box<Node<T>> = Box::from_raw(tail);
@@ -234,9 +235,9 @@ impl<T, ProducerAddition, ConsumerAddition> Drop for Queue<T, ProducerAddition,
 #[cfg(all(test, not(target_os = "emscripten")))]
 mod tests {
     use super::Queue;
+    use crate::sync::mpsc::channel;
     use crate::sync::Arc;
     use crate::thread;
-    use crate::sync::mpsc::channel;
 
     #[test]
     fn smoke() {
@@ -265,15 +266,15 @@ mod tests {
             match queue.peek() {
                 Some(vec) => {
                     assert_eq!(&*vec, &[1]);
-                },
-                None => unreachable!()
+                }
+                None => unreachable!(),
             }
 
             match queue.pop() {
                 Some(vec) => {
                     assert_eq!(&*vec, &[1]);
-                },
-                None => unreachable!()
+                }
+                None => unreachable!(),
             }
         }
     }
@@ -316,7 +317,7 @@ mod tests {
 
             let (tx, rx) = channel();
             let q2 = q.clone();
-            let _t = thread::spawn(move|| {
+            let _t = thread::spawn(move || {
                 for _ in 0..100000 {
                     loop {
                         match q2.pop() {
diff --git a/src/libstd/sync/mpsc/stream.rs b/src/libstd/sync/mpsc/stream.rs
index 40877282761..2e3270e81fc 100644
--- a/src/libstd/sync/mpsc/stream.rs
+++ b/src/libstd/sync/mpsc/stream.rs
@@ -6,10 +6,9 @@
 ///
 /// High level implementation details can be found in the comment of the parent
 /// module.
-
 pub use self::Failure::*;
-pub use self::UpgradeResult::*;
 use self::Message::*;
+pub use self::UpgradeResult::*;
 
 use core::cmp;
 use core::isize;
@@ -19,10 +18,10 @@ use crate::ptr;
 use crate::thread;
 use crate::time::Instant;
 
-use crate::sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool};
-use crate::sync::mpsc::Receiver;
+use crate::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering};
 use crate::sync::mpsc::blocking::{self, SignalToken};
 use crate::sync::mpsc::spsc_queue as spsc;
+use crate::sync::mpsc::Receiver;
 
 const DISCONNECTED: isize = isize::MIN;
 #[cfg(test)]
@@ -36,17 +35,16 @@ pub struct Packet<T> {
 }
 
 struct ProducerAddition {
-    cnt: AtomicIsize, // How many items are on this channel
+    cnt: AtomicIsize,     // How many items are on this channel
     to_wake: AtomicUsize, // SignalToken for the blocked thread to wake up
 
     port_dropped: AtomicBool, // flag if the channel has been destroyed.
 }
 
 struct ConsumerAddition {
-    steals: UnsafeCell<isize>,  // How many times has a port received without blocking?
+    steals: UnsafeCell<isize>, // How many times has a port received without blocking?
 }
 
-
 pub enum Failure<T> {
     Empty,
     Disconnected,
@@ -69,18 +67,18 @@ enum Message<T> {
 impl<T> Packet<T> {
     pub fn new() -> Packet<T> {
         Packet {
-            queue: unsafe { spsc::Queue::with_additions(
-                128,
-                ProducerAddition {
-                    cnt: AtomicIsize::new(0),
-                    to_wake: AtomicUsize::new(0),
-
-                    port_dropped: AtomicBool::new(false),
-                },
-                ConsumerAddition {
-                    steals: UnsafeCell::new(0),
-                }
-            )},
+            queue: unsafe {
+                spsc::Queue::with_additions(
+                    128,
+                    ProducerAddition {
+                        cnt: AtomicIsize::new(0),
+                        to_wake: AtomicUsize::new(0),
+
+                        port_dropped: AtomicBool::new(false),
+                    },
+                    ConsumerAddition { steals: UnsafeCell::new(0) },
+                )
+            },
         }
     }
 
@@ -88,11 +86,15 @@ impl<T> Packet<T> {
         // If the other port has deterministically gone away, then definitely
         // must return the data back up the stack. Otherwise, the data is
         // considered as being sent.
-        if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) { return Err(t) }
+        if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) {
+            return Err(t);
+        }
 
         match self.do_send(Data(t)) {
-            UpSuccess | UpDisconnected => {},
-            UpWoke(token) => { token.signal(); }
+            UpSuccess | UpDisconnected => {}
+            UpWoke(token) => {
+                token.signal();
+            }
         }
         Ok(())
     }
@@ -101,7 +103,7 @@ impl<T> Packet<T> {
         // If the port has gone away, then there's no need to proceed any
         // further.
         if self.queue.producer_addition().port_dropped.load(Ordering::SeqCst) {
-            return UpDisconnected
+            return UpDisconnected;
         }
 
         self.do_send(GoUp(up))
@@ -136,7 +138,10 @@ impl<T> Packet<T> {
 
             // Otherwise we just sent some data on a non-waiting queue, so just
             // make sure the world is sane and carry on!
-            n => { assert!(n >= 0); UpSuccess }
+            n => {
+                assert!(n >= 0);
+                UpSuccess
+            }
         }
     }
 
@@ -166,7 +171,9 @@ impl<T> Packet<T> {
             // data, we successfully sleep
             n => {
                 assert!(n >= 0);
-                if n - steals <= 0 { return Ok(()) }
+                if n - steals <= 0 {
+                    return Ok(());
+                }
             }
         }
 
@@ -199,8 +206,7 @@ impl<T> Packet<T> {
             // Messages which actually popped from the queue shouldn't count as
             // a steal, so offset the decrement here (we already have our
             // "steal" factored into the channel count above).
-            data @ Ok(..) |
-            data @ Err(Upgraded(..)) => unsafe {
+            data @ Ok(..) | data @ Err(Upgraded(..)) => unsafe {
                 *self.queue.consumer_addition().steals.get() -= 1;
                 data
             },
@@ -226,8 +232,10 @@ impl<T> Packet<T> {
                 if *self.queue.consumer_addition().steals.get() > MAX_STEALS {
                     match self.queue.producer_addition().cnt.swap(0, Ordering::SeqCst) {
                         DISCONNECTED => {
-                            self.queue.producer_addition().cnt.store(
-                                DISCONNECTED, Ordering::SeqCst);
+                            self.queue
+                                .producer_addition()
+                                .cnt
+                                .store(DISCONNECTED, Ordering::SeqCst);
                         }
                         n => {
                             let m = cmp::min(n, *self.queue.consumer_addition().steals.get());
@@ -259,13 +267,11 @@ impl<T> Packet<T> {
                     // We can ignore steals because the other end is
                     // disconnected and we'll never need to really factor in our
                     // steals again.
-                    _ => {
-                        match self.queue.pop() {
-                            Some(Data(t)) => Ok(t),
-                            Some(GoUp(up)) => Err(Upgraded(up)),
-                            None => Err(Disconnected),
-                        }
-                    }
+                    _ => match self.queue.pop() {
+                        Some(Data(t)) => Ok(t),
+                        Some(GoUp(up)) => Err(Upgraded(up)),
+                        None => Err(Disconnected),
+                    },
                 }
             }
         }
@@ -275,9 +281,13 @@ impl<T> Packet<T> {
         // Dropping a channel is pretty simple, we just flag it as disconnected
         // and then wakeup a blocker if there is one.
         match self.queue.producer_addition().cnt.swap(DISCONNECTED, Ordering::SeqCst) {
-            -1 => { self.take_to_wake().signal(); }
+            -1 => {
+                self.take_to_wake().signal();
+            }
             DISCONNECTED => {}
-            n => { assert!(n >= 0); }
+            n => {
+                assert!(n >= 0);
+            }
         }
     }
 
@@ -314,10 +324,15 @@ impl<T> Packet<T> {
         let mut steals = unsafe { *self.queue.consumer_addition().steals.get() };
         while {
             let cnt = self.queue.producer_addition().cnt.compare_and_swap(
-                            steals, DISCONNECTED, Ordering::SeqCst);
+                steals,
+                DISCONNECTED,
+                Ordering::SeqCst,
+            );
             cnt != DISCONNECTED && cnt != steals
         } {
-            while let Some(_) = self.queue.pop() { steals += 1; }
+            while let Some(_) = self.queue.pop() {
+                steals += 1;
+            }
         }
 
         // At this point in time, we have gated all future senders from sending,
@@ -338,13 +353,12 @@ impl<T> Packet<T> {
                 self.queue.producer_addition().cnt.store(DISCONNECTED, Ordering::SeqCst);
                 DISCONNECTED
             }
-            n => n
+            n => n,
         }
     }
 
     // Removes a previous thread from being blocked in this port
-    pub fn abort_selection(&self,
-                           was_upgrade: bool) -> Result<bool, Receiver<T>> {
+    pub fn abort_selection(&self, was_upgrade: bool) -> Result<bool, Receiver<T>> {
         // If we're aborting selection after upgrading from a oneshot, then
         // we're guarantee that no one is waiting. The only way that we could
         // have seen the upgrade is if data was actually sent on the channel
@@ -361,7 +375,7 @@ impl<T> Packet<T> {
         if was_upgrade {
             assert_eq!(unsafe { *self.queue.consumer_addition().steals.get() }, 0);
             assert_eq!(self.queue.producer_addition().to_wake.load(Ordering::SeqCst), 0);
-            return Ok(true)
+            return Ok(true);
         }
 
         // We want to make sure that the count on the channel goes non-negative,
@@ -416,12 +430,10 @@ impl<T> Packet<T> {
         // upgraded port.
         if has_data {
             match self.queue.peek() {
-                Some(&mut GoUp(..)) => {
-                    match self.queue.pop() {
-                        Some(GoUp(port)) => Err(port),
-                        _ => unreachable!(),
-                    }
-                }
+                Some(&mut GoUp(..)) => match self.queue.pop() {
+                    Some(GoUp(port)) => Err(port),
+                    _ => unreachable!(),
+                },
                 _ => Ok(true),
             }
         } else {
diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs
index 58a4b716afb..79e86817154 100644
--- a/src/libstd/sync/mpsc/sync.rs
+++ b/src/libstd/sync/mpsc/sync.rs
@@ -1,3 +1,4 @@
+use self::Blocker::*;
 /// Synchronous channels/ports
 ///
 /// This channel implementation differs significantly from the asynchronous
@@ -22,17 +23,15 @@
 /// implementation shares almost all code for the buffered and unbuffered cases
 /// of a synchronous channel. There are a few branches for the unbuffered case,
 /// but they're mostly just relevant to blocking senders.
-
 pub use self::Failure::*;
-use self::Blocker::*;
 
 use core::intrinsics::abort;
 use core::isize;
 use core::mem;
 use core::ptr;
 
-use crate::sync::atomic::{Ordering, AtomicUsize};
-use crate::sync::mpsc::blocking::{self, WaitToken, SignalToken};
+use crate::sync::atomic::{AtomicUsize, Ordering};
+use crate::sync::mpsc::blocking::{self, SignalToken, WaitToken};
 use crate::sync::{Mutex, MutexGuard};
 use crate::time::Instant;
 
@@ -46,9 +45,9 @@ pub struct Packet<T> {
     lock: Mutex<State<T>>,
 }
 
-unsafe impl<T: Send> Send for Packet<T> { }
+unsafe impl<T: Send> Send for Packet<T> {}
 
-unsafe impl<T: Send> Sync for Packet<T> { }
+unsafe impl<T: Send> Sync for Packet<T> {}
 
 struct State<T> {
     disconnected: bool, // Is the channel disconnected yet?
@@ -72,7 +71,7 @@ unsafe impl<T: Send> Send for State<T> {}
 enum Blocker {
     BlockedSender(SignalToken),
     BlockedReceiver(SignalToken),
-    NoneBlocked
+    NoneBlocked,
 }
 
 /// Simple queue for threading threads together. Nodes are stack-allocated, so
@@ -104,35 +103,35 @@ pub enum Failure {
 
 /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
 /// in the meantime. This re-locks the mutex upon returning.
-fn wait<'a, 'b, T>(lock: &'a Mutex<State<T>>,
-                   mut guard: MutexGuard<'b, State<T>>,
-                   f: fn(SignalToken) -> Blocker)
-                   -> MutexGuard<'a, State<T>>
-{
+fn wait<'a, 'b, T>(
+    lock: &'a Mutex<State<T>>,
+    mut guard: MutexGuard<'b, State<T>>,
+    f: fn(SignalToken) -> Blocker,
+) -> MutexGuard<'a, State<T>> {
     let (wait_token, signal_token) = blocking::tokens();
     match mem::replace(&mut guard.blocker, f(signal_token)) {
         NoneBlocked => {}
         _ => unreachable!(),
     }
-    drop(guard);         // unlock
-    wait_token.wait();   // block
+    drop(guard); // unlock
+    wait_token.wait(); // block
     lock.lock().unwrap() // relock
 }
 
 /// Same as wait, but waiting at most until `deadline`.
-fn wait_timeout_receiver<'a, 'b, T>(lock: &'a Mutex<State<T>>,
-                                    deadline: Instant,
-                                    mut guard: MutexGuard<'b, State<T>>,
-                                    success: &mut bool)
-                                    -> MutexGuard<'a, State<T>>
-{
+fn wait_timeout_receiver<'a, 'b, T>(
+    lock: &'a Mutex<State<T>>,
+    deadline: Instant,
+    mut guard: MutexGuard<'b, State<T>>,
+    success: &mut bool,
+) -> MutexGuard<'a, State<T>> {
     let (wait_token, signal_token) = blocking::tokens();
     match mem::replace(&mut guard.blocker, BlockedReceiver(signal_token)) {
         NoneBlocked => {}
         _ => unreachable!(),
     }
-    drop(guard);         // unlock
-    *success = wait_token.wait_max_until(deadline);   // block
+    drop(guard); // unlock
+    *success = wait_token.wait_max_until(deadline); // block
     let mut new_guard = lock.lock().unwrap(); // relock
     if !*success {
         abort_selection(&mut new_guard);
@@ -147,7 +146,10 @@ fn abort_selection<T>(guard: &mut MutexGuard<'_, State<T>>) -> bool {
             guard.blocker = BlockedSender(token);
             true
         }
-        BlockedReceiver(token) => { drop(token); false }
+        BlockedReceiver(token) => {
+            drop(token);
+            false
+        }
     }
 }
 
@@ -168,12 +170,9 @@ impl<T> Packet<T> {
                 blocker: NoneBlocked,
                 cap: capacity,
                 canceled: None,
-                queue: Queue {
-                    head: ptr::null_mut(),
-                    tail: ptr::null_mut(),
-                },
+                queue: Queue { head: ptr::null_mut(), tail: ptr::null_mut() },
                 buf: Buffer {
-                    buf: (0..capacity + if capacity == 0 {1} else {0}).map(|_| None).collect(),
+                    buf: (0..capacity + if capacity == 0 { 1 } else { 0 }).map(|_| None).collect(),
                     start: 0,
                     size: 0,
                 },
@@ -200,7 +199,9 @@ impl<T> Packet<T> {
 
     pub fn send(&self, t: T) -> Result<(), T> {
         let mut guard = self.acquire_send_slot();
-        if guard.disconnected { return Err(t) }
+        if guard.disconnected {
+            return Err(t);
+        }
         guard.buf.enqueue(t);
 
         match mem::replace(&mut guard.blocker, NoneBlocked) {
@@ -213,14 +214,17 @@ impl<T> Packet<T> {
                 assert!(guard.canceled.is_none());
                 guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
                 let mut guard = wait(&self.lock, guard, BlockedSender);
-                if canceled {Err(guard.buf.dequeue())} else {Ok(())}
+                if canceled { Err(guard.buf.dequeue()) } else { Ok(()) }
             }
 
             // success, we buffered some data
             NoneBlocked => Ok(()),
 
             // success, someone's about to receive our buffered data.
-            BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
+            BlockedReceiver(token) => {
+                wakeup(token, guard);
+                Ok(())
+            }
 
             BlockedSender(..) => panic!("lolwut"),
         }
@@ -271,10 +275,8 @@ impl<T> Packet<T> {
         // while loop because we're the only receiver.
         if !guard.disconnected && guard.buf.size() == 0 {
             if let Some(deadline) = deadline {
-                guard = wait_timeout_receiver(&self.lock,
-                                              deadline,
-                                              guard,
-                                              &mut woke_up_after_waiting);
+                guard =
+                    wait_timeout_receiver(&self.lock, deadline, guard, &mut woke_up_after_waiting);
             } else {
                 guard = wait(&self.lock, guard, BlockedReceiver);
                 woke_up_after_waiting = true;
@@ -290,7 +292,9 @@ impl<T> Packet<T> {
         // Pick up the data, wake up our neighbors, and carry on
         assert!(guard.buf.size() > 0 || (deadline.is_some() && !woke_up_after_waiting));
 
-        if guard.buf.size() == 0 { return Err(Empty); }
+        if guard.buf.size() == 0 {
+            return Err(Empty);
+        }
 
         let ret = guard.buf.dequeue();
         self.wakeup_senders(woke_up_after_waiting, guard);
@@ -301,8 +305,12 @@ impl<T> Packet<T> {
         let mut guard = self.lock.lock().unwrap();
 
         // Easy cases first
-        if guard.disconnected && guard.buf.size() == 0 { return Err(Disconnected) }
-        if guard.buf.size() == 0 { return Err(Empty) }
+        if guard.disconnected && guard.buf.size() == 0 {
+            return Err(Disconnected);
+        }
+        if guard.buf.size() == 0 {
+            return Err(Empty);
+        }
 
         // Be sure to wake up neighbors
         let ret = Ok(guard.buf.dequeue());
@@ -357,12 +365,14 @@ impl<T> Packet<T> {
         // Only flag the channel as disconnected if we're the last channel
         match self.channels.fetch_sub(1, Ordering::SeqCst) {
             1 => {}
-            _ => return
+            _ => return,
         }
 
         // Not much to do other than wake up a receiver if one's there
         let mut guard = self.lock.lock().unwrap();
-        if guard.disconnected { return }
+        if guard.disconnected {
+            return;
+        }
         guard.disconnected = true;
         match mem::replace(&mut guard.blocker, NoneBlocked) {
             NoneBlocked => {}
@@ -374,7 +384,9 @@ impl<T> Packet<T> {
     pub fn drop_port(&self) {
         let mut guard = self.lock.lock().unwrap();
 
-        if guard.disconnected { return }
+        if guard.disconnected {
+            return;
+        }
         guard.disconnected = true;
 
         // If the capacity is 0, then the sender may want its data back after
@@ -382,15 +394,9 @@ impl<T> Packet<T> {
         // the buffered data. As with many other portions of this code, this
         // needs to be careful to destroy the data *outside* of the lock to
         // prevent deadlock.
-        let _data = if guard.cap != 0 {
-            mem::take(&mut guard.buf.buf)
-        } else {
-            Vec::new()
-        };
-        let mut queue = mem::replace(&mut guard.queue, Queue {
-            head: ptr::null_mut(),
-            tail: ptr::null_mut(),
-        });
+        let _data = if guard.cap != 0 { mem::take(&mut guard.buf.buf) } else { Vec::new() };
+        let mut queue =
+            mem::replace(&mut guard.queue, Queue { head: ptr::null_mut(), tail: ptr::null_mut() });
 
         let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
             NoneBlocked => None,
@@ -402,7 +408,9 @@ impl<T> Packet<T> {
         };
         mem::drop(guard);
 
-        while let Some(token) = queue.dequeue() { token.signal(); }
+        while let Some(token) = queue.dequeue() {
+            token.signal();
+        }
         waiter.map(|t| t.signal());
     }
 }
@@ -416,7 +424,6 @@ impl<T> Drop for Packet<T> {
     }
 }
 
-
 ////////////////////////////////////////////////////////////////////////////////
 // Buffer, a simple ring buffer backed by Vec<T>
 ////////////////////////////////////////////////////////////////////////////////
@@ -437,8 +444,12 @@ impl<T> Buffer<T> {
         result.take().unwrap()
     }
 
-    fn size(&self) -> usize { self.size }
-    fn capacity(&self) -> usize { self.buf.len() }
+    fn size(&self) -> usize {
+        self.size
+    }
+    fn capacity(&self) -> usize {
+        self.buf.len()
+    }
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -466,7 +477,7 @@ impl Queue {
 
     fn dequeue(&mut self) -> Option<SignalToken> {
         if self.head.is_null() {
-            return None
+            return None;
         }
         let node = self.head;
         self.head = unsafe { (*node).next };
diff --git a/src/libstd/sys/cloudabi/os.rs b/src/libstd/sys/cloudabi/os.rs
index 7db7808a087..326faaa852a 100644
--- a/src/libstd/sys/cloudabi/os.rs
+++ b/src/libstd/sys/cloudabi/os.rs
@@ -18,9 +18,7 @@ pub fn errno() -> i32 {
 pub fn error_string(errno: i32) -> String {
     // cloudlibc's strerror() is guaranteed to be thread-safe. There is
     // thus no need to use strerror_r().
-    str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes())
-        .unwrap()
-        .to_owned()
+    str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes()).unwrap().to_owned()
 }
 
 pub fn exit(code: i32) -> ! {
diff --git a/src/libstd/sys/cloudabi/shims/fs.rs b/src/libstd/sys/cloudabi/shims/fs.rs
index 05f91541011..e6160d1457d 100644
--- a/src/libstd/sys/cloudabi/shims/fs.rs
+++ b/src/libstd/sys/cloudabi/shims/fs.rs
@@ -1,7 +1,7 @@
 use crate::ffi::OsString;
 use crate::fmt;
 use crate::hash::{Hash, Hasher};
-use crate::io::{self, SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
 use crate::path::{Path, PathBuf};
 use crate::sys::time::SystemTime;
 use crate::sys::{unsupported, Void};
diff --git a/src/libstd/sys/cloudabi/shims/mod.rs b/src/libstd/sys/cloudabi/shims/mod.rs
index fbb5ff55f22..b1b5f142f45 100644
--- a/src/libstd/sys/cloudabi/shims/mod.rs
+++ b/src/libstd/sys/cloudabi/shims/mod.rs
@@ -4,19 +4,16 @@ pub mod args;
 pub mod env;
 pub mod fs;
 pub mod net;
+pub mod os;
 #[path = "../../unix/path.rs"]
 pub mod path;
 pub mod pipe;
 pub mod process;
-pub mod os;
 
 // This enum is used as the storage for a bunch of types which can't actually exist.
 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
 pub enum Void {}
 
 pub fn unsupported<T>() -> io::Result<T> {
-    Err(io::Error::new(
-        io::ErrorKind::Other,
-        "This function is not available on CloudABI.",
-    ))
+    Err(io::Error::new(io::ErrorKind::Other, "This function is not available on CloudABI."))
 }
diff --git a/src/libstd/sys/cloudabi/shims/net.rs b/src/libstd/sys/cloudabi/shims/net.rs
index 8d609cdfad5..67c436fa795 100644
--- a/src/libstd/sys/cloudabi/shims/net.rs
+++ b/src/libstd/sys/cloudabi/shims/net.rs
@@ -1,9 +1,9 @@
+use crate::convert::TryFrom;
 use crate::fmt;
 use crate::io::{self, IoSlice, IoSliceMut};
 use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
-use crate::time::Duration;
 use crate::sys::{unsupported, Void};
-use crate::convert::TryFrom;
+use crate::time::Duration;
 
 #[allow(unused_extern_crates)]
 pub extern crate libc as netc;
diff --git a/src/libstd/sys/cloudabi/shims/process.rs b/src/libstd/sys/cloudabi/shims/process.rs
index 03a59d6d7c8..4702e5c5492 100644
--- a/src/libstd/sys/cloudabi/shims/process.rs
+++ b/src/libstd/sys/cloudabi/shims/process.rs
@@ -32,9 +32,7 @@ pub enum Stdio {
 
 impl Command {
     pub fn new(_program: &OsStr) -> Command {
-        Command {
-            env: Default::default(),
-        }
+        Command { env: Default::default() }
     }
 
     pub fn arg(&mut self, _arg: &OsStr) {}
diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs
index 240b6ea9e57..3afcae7ae75 100644
--- a/src/libstd/sys/cloudabi/thread.rs
+++ b/src/libstd/sys/cloudabi/thread.rs
@@ -58,8 +58,8 @@ impl Thread {
     }
 
     pub fn sleep(dur: Duration) {
-        let timeout = checked_dur2intervals(&dur)
-            .expect("overflow converting duration to nanoseconds");
+        let timeout =
+            checked_dur2intervals(&dur).expect("overflow converting duration to nanoseconds");
         unsafe {
             let subscription = abi::subscription {
                 type_: abi::eventtype::CLOCK,
@@ -85,11 +85,7 @@ impl Thread {
         unsafe {
             let ret = libc::pthread_join(self.id, ptr::null_mut());
             mem::forget(self);
-            assert!(
-                ret == 0,
-                "failed to join thread: {}",
-                io::Error::from_raw_os_error(ret)
-            );
+            assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
         }
     }
 }
diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs
index 5e502dcb2ba..c209231cf8c 100644
--- a/src/libstd/sys/cloudabi/time.rs
+++ b/src/libstd/sys/cloudabi/time.rs
@@ -10,9 +10,7 @@ pub struct Instant {
 }
 
 pub fn checked_dur2intervals(dur: &Duration) -> Option<abi::timestamp> {
-    dur.as_secs()
-        .checked_mul(NSEC_PER_SEC)?
-        .checked_add(dur.subsec_nanos() as abi::timestamp)
+    dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as abi::timestamp)
 }
 
 impl Instant {
@@ -39,15 +37,11 @@ impl Instant {
     }
 
     pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
-        Some(Instant {
-            t: self.t.checked_add(checked_dur2intervals(other)?)?,
-        })
+        Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
     }
 
     pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
-        Some(Instant {
-            t: self.t.checked_sub(checked_dur2intervals(other)?)?,
-        })
+        Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
     }
 }
 
@@ -69,29 +63,19 @@ impl SystemTime {
     pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
         if self.t >= other.t {
             let diff = self.t - other.t;
-            Ok(Duration::new(
-                diff / NSEC_PER_SEC,
-                (diff % NSEC_PER_SEC) as u32,
-            ))
+            Ok(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
         } else {
             let diff = other.t - self.t;
-            Err(Duration::new(
-                diff / NSEC_PER_SEC,
-                (diff % NSEC_PER_SEC) as u32,
-            ))
+            Err(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
         }
     }
 
     pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
-        Some(SystemTime {
-            t: self.t.checked_add(checked_dur2intervals(other)?)?,
-        })
+        Some(SystemTime { t: self.t.checked_add(checked_dur2intervals(other)?)? })
     }
 
     pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
-        Some(SystemTime {
-            t: self.t.checked_sub(checked_dur2intervals(other)?)?,
-        })
+        Some(SystemTime { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
     }
 }
 
diff --git a/src/libstd/sys/hermit/alloc.rs b/src/libstd/sys/hermit/alloc.rs
index 86cc4463632..d153914e77e 100644
--- a/src/libstd/sys/hermit/alloc.rs
+++ b/src/libstd/sys/hermit/alloc.rs
@@ -13,11 +13,7 @@ unsafe impl GlobalAlloc for System {
         let addr = abi::malloc(layout.size(), layout.align());
 
         if !addr.is_null() {
-            ptr::write_bytes(
-                addr,
-                0x00,
-                layout.size()
-            );
+            ptr::write_bytes(addr, 0x00, layout.size());
         }
 
         addr
diff --git a/src/libstd/sys/hermit/args.rs b/src/libstd/sys/hermit/args.rs
index 5b1f3add51f..72c1b8511ca 100644
--- a/src/libstd/sys/hermit/args.rs
+++ b/src/libstd/sys/hermit/args.rs
@@ -3,10 +3,14 @@ use crate::marker::PhantomData;
 use crate::vec;
 
 /// One-time global initialization.
-pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
+pub unsafe fn init(argc: isize, argv: *const *const u8) {
+    imp::init(argc, argv)
+}
 
 /// One-time global cleanup.
-pub unsafe fn cleanup() { imp::cleanup() }
+pub unsafe fn cleanup() {
+    imp::cleanup()
+}
 
 /// Returns the command line arguments
 pub fn args() -> Args {
@@ -26,24 +30,32 @@ impl Args {
 
 impl Iterator for Args {
     type Item = OsString;
-    fn next(&mut self) -> Option<OsString> { self.iter.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<OsString> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
 }
 
 impl ExactSizeIterator for Args {
-    fn len(&self) -> usize { self.iter.len() }
+    fn len(&self) -> usize {
+        self.iter.len()
+    }
 }
 
 impl DoubleEndedIterator for Args {
-    fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
+    fn next_back(&mut self) -> Option<OsString> {
+        self.iter.next_back()
+    }
 }
 
 mod imp {
-    use crate::sys_common::os_str_bytes::*;
-    use crate::ptr;
+    use super::Args;
     use crate::ffi::{CStr, OsString};
     use crate::marker::PhantomData;
-    use super::Args;
+    use crate::ptr;
+    use crate::sys_common::os_str_bytes::*;
 
     use crate::sys_common::mutex::Mutex;
 
@@ -64,19 +76,18 @@ mod imp {
     }
 
     pub fn args() -> Args {
-        Args {
-            iter: clone().into_iter(),
-            _dont_send_or_sync_me: PhantomData
-        }
+        Args { iter: clone().into_iter(), _dont_send_or_sync_me: PhantomData }
     }
 
     fn clone() -> Vec<OsString> {
         unsafe {
             let _guard = LOCK.lock();
-            (0..ARGC).map(|i| {
-                let cstr = CStr::from_ptr(*ARGV.offset(i) as *const i8);
-                OsStringExt::from_vec(cstr.to_bytes().to_vec())
-            }).collect()
+            (0..ARGC)
+                .map(|i| {
+                    let cstr = CStr::from_ptr(*ARGV.offset(i) as *const i8);
+                    OsStringExt::from_vec(cstr.to_bytes().to_vec())
+                })
+                .collect()
         }
     }
 }
diff --git a/src/libstd/sys/hermit/cmath.rs b/src/libstd/sys/hermit/cmath.rs
index fa7783122c2..304cf906b2a 100644
--- a/src/libstd/sys/hermit/cmath.rs
+++ b/src/libstd/sys/hermit/cmath.rs
@@ -1,5 +1,5 @@
 // These symbols are all defined in `compiler-builtins`
-extern {
+extern "C" {
     pub fn acos(n: f64) -> f64;
     pub fn acosf(n: f32) -> f32;
     pub fn asin(n: f64) -> f64;
diff --git a/src/libstd/sys/hermit/condvar.rs b/src/libstd/sys/hermit/condvar.rs
index 8e52b3da1b1..5b7f16ce562 100644
--- a/src/libstd/sys/hermit/condvar.rs
+++ b/src/libstd/sys/hermit/condvar.rs
@@ -18,12 +18,12 @@ impl Condvar {
     }
 
     pub unsafe fn notify_one(&self) {
-         let _ = abi::notify(self.id(), 1);
+        let _ = abi::notify(self.id(), 1);
     }
 
     #[inline]
     pub unsafe fn notify_all(&self) {
-         let _ = abi::notify(self.id(), -1 /* =all */);
+        let _ = abi::notify(self.id(), -1 /* =all */);
     }
 
     pub unsafe fn wait(&self, mutex: &Mutex) {
diff --git a/src/libstd/sys/hermit/fd.rs b/src/libstd/sys/hermit/fd.rs
index 84c54736647..f2f61fdfb8c 100644
--- a/src/libstd/sys/hermit/fd.rs
+++ b/src/libstd/sys/hermit/fd.rs
@@ -1,6 +1,6 @@
 #![unstable(reason = "not public", issue = "0", feature = "fd")]
 
-use crate::io::{self, Read, ErrorKind};
+use crate::io::{self, ErrorKind, Read};
 use crate::mem;
 use crate::sys::cvt;
 use crate::sys::hermit::abi;
@@ -16,7 +16,9 @@ impl FileDesc {
         FileDesc { fd }
     }
 
-    pub fn raw(&self) -> i32 { self.fd }
+    pub fn raw(&self) -> i32 {
+        self.fd
+    }
 
     /// Extracts the actual file descriptor without closing it.
     pub fn into_raw(self) -> i32 {
@@ -67,7 +69,9 @@ impl<'a> Read for &'a FileDesc {
 }
 
 impl AsInner<i32> for FileDesc {
-    fn as_inner(&self) -> &i32 { &self.fd }
+    fn as_inner(&self) -> &i32 {
+        &self.fd
+    }
 }
 
 impl Drop for FileDesc {
diff --git a/src/libstd/sys/hermit/fs.rs b/src/libstd/sys/hermit/fs.rs
index f8e5844a167..37ac5984eee 100644
--- a/src/libstd/sys/hermit/fs.rs
+++ b/src/libstd/sys/hermit/fs.rs
@@ -1,14 +1,14 @@
-use crate::ffi::{OsString, CString, CStr};
+use crate::ffi::{CStr, CString, OsString};
 use crate::fmt;
-use crate::io::{self, Error, ErrorKind};
 use crate::hash::{Hash, Hasher};
-use crate::io::{SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, Error, ErrorKind};
+use crate::io::{IoSlice, IoSliceMut, SeekFrom};
 use crate::path::{Path, PathBuf};
-use crate::sys::time::SystemTime;
-use crate::sys::{unsupported, Void};
+use crate::sys::cvt;
 use crate::sys::hermit::abi;
 use crate::sys::hermit::fd::FileDesc;
-use crate::sys::cvt;
+use crate::sys::time::SystemTime;
+use crate::sys::{unsupported, Void};
 use crate::sys_common::os_str_bytes::OsStrExt;
 
 pub use crate::sys_common::fs::copy;
@@ -45,7 +45,7 @@ pub struct OpenOptions {
     create: bool,
     create_new: bool,
     // system-specific
-    mode: i32
+    mode: i32,
 }
 
 pub struct FilePermissions(Void);
@@ -53,7 +53,7 @@ pub struct FilePermissions(Void);
 pub struct FileType(Void);
 
 #[derive(Debug)]
-pub struct DirBuilder { }
+pub struct DirBuilder {}
 
 impl FileAttr {
     pub fn size(&self) -> u64 {
@@ -109,8 +109,7 @@ impl PartialEq for FilePermissions {
     }
 }
 
-impl Eq for FilePermissions {
-}
+impl Eq for FilePermissions {}
 
 impl fmt::Debug for FilePermissions {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -146,8 +145,7 @@ impl PartialEq for FileType {
     }
 }
 
-impl Eq for FileType {
-}
+impl Eq for FileType {}
 
 impl Hash for FileType {
     fn hash<H: Hasher>(&self, _h: &mut H) {
@@ -204,50 +202,64 @@ impl OpenOptions {
             create: false,
             create_new: false,
             // system-specific
-            mode: 0x777
+            mode: 0x777,
         }
     }
 
-    pub fn read(&mut self, read: bool) { self.read = read; }
-    pub fn write(&mut self, write: bool) { self.write = write; }
-    pub fn append(&mut self, append: bool) { self.append = append; }
-    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
-    pub fn create(&mut self, create: bool) { self.create = create; }
-    pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+    pub fn append(&mut self, append: bool) {
+        self.append = append;
+    }
+    pub fn truncate(&mut self, truncate: bool) {
+        self.truncate = truncate;
+    }
+    pub fn create(&mut self, create: bool) {
+        self.create = create;
+    }
+    pub fn create_new(&mut self, create_new: bool) {
+        self.create_new = create_new;
+    }
 
     fn get_access_mode(&self) -> io::Result<i32> {
         match (self.read, self.write, self.append) {
-            (true,  false, false) => Ok(O_RDONLY),
-            (false, true,  false) => Ok(O_WRONLY),
-            (true,  true,  false) => Ok(O_RDWR),
-            (false, _,     true)  => Ok(O_WRONLY | O_APPEND),
-            (true,  _,     true)  => Ok(O_RDWR | O_APPEND),
+            (true, false, false) => Ok(O_RDONLY),
+            (false, true, false) => Ok(O_WRONLY),
+            (true, true, false) => Ok(O_RDWR),
+            (false, _, true) => Ok(O_WRONLY | O_APPEND),
+            (true, _, true) => Ok(O_RDWR | O_APPEND),
             (false, false, false) => {
                 Err(io::Error::new(ErrorKind::InvalidInput, "invalid access mode"))
-            },
+            }
         }
     }
 
     fn get_creation_mode(&self) -> io::Result<i32> {
         match (self.write, self.append) {
             (true, false) => {}
-            (false, false) =>
+            (false, false) => {
                 if self.truncate || self.create || self.create_new {
                     return Err(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode"));
-                },
-            (_, true) =>
+                }
+            }
+            (_, true) => {
                 if self.truncate && !self.create_new {
                     return Err(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode"));
-                },
+                }
+            }
         }
 
         Ok(match (self.create, self.truncate, self.create_new) {
-                (false, false, false) => 0,
-                (true,  false, false) => O_CREAT,
-                (false, true,  false) => O_TRUNC,
-                (true,  true,  false) => O_CREAT | O_TRUNC,
-                (_,      _,    true)  => O_CREAT | O_EXCL,
-           })
+            (false, false, false) => 0,
+            (true, false, false) => O_CREAT,
+            (false, true, false) => O_TRUNC,
+            (true, true, false) => O_CREAT | O_TRUNC,
+            (_, _, true) => O_CREAT | O_EXCL,
+        })
     }
 }
 
@@ -327,7 +339,7 @@ impl File {
 
 impl DirBuilder {
     pub fn new() -> DirBuilder {
-        DirBuilder { }
+        DirBuilder {}
     }
 
     pub fn mkdir(&self, _p: &Path) -> io::Result<()> {
diff --git a/src/libstd/sys/hermit/mod.rs b/src/libstd/sys/hermit/mod.rs
index d4359631769..1e4a53abdc7 100644
--- a/src/libstd/sys/hermit/mod.rs
+++ b/src/libstd/sys/hermit/mod.rs
@@ -13,34 +13,34 @@
 //! compiling for wasm. That way it's a compile time error for something that's
 //! guaranteed to be a runtime error!
 
-use crate::os::raw::c_char;
 use crate::intrinsics;
+use crate::os::raw::c_char;
 
 pub mod alloc;
 pub mod args;
-pub mod condvar;
-pub mod stdio;
-pub mod memchr;
-pub mod io;
-pub mod mutex;
-pub mod rwlock;
-pub mod os;
 pub mod cmath;
-pub mod thread;
+pub mod condvar;
 pub mod env;
-pub mod fs;
+pub mod fast_thread_local;
 pub mod fd;
+pub mod fs;
+pub mod io;
+pub mod memchr;
+pub mod mutex;
 pub mod net;
+pub mod os;
 pub mod path;
 pub mod pipe;
 pub mod process;
+pub mod rwlock;
 pub mod stack_overflow;
-pub mod time;
+pub mod stdio;
+pub mod thread;
 pub mod thread_local;
-pub mod fast_thread_local;
+pub mod time;
 
-pub use crate::sys_common::os_str_bytes as os_str;
 use crate::io::ErrorKind;
+pub use crate::sys_common::os_str_bytes as os_str;
 
 #[allow(unused_extern_crates)]
 pub extern crate hermit_abi as abi;
@@ -50,8 +50,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> {
 }
 
 pub fn unsupported_err() -> crate::io::Error {
-    crate::io::Error::new(crate::io::ErrorKind::Other,
-           "operation not supported on HermitCore yet")
+    crate::io::Error::new(crate::io::ErrorKind::Other, "operation not supported on HermitCore yet")
 }
 
 // This enum is used as the storage for a bunch of types which can't actually
@@ -71,9 +70,7 @@ pub unsafe fn strlen(start: *const c_char) -> usize {
 
 #[no_mangle]
 pub extern "C" fn floor(x: f64) -> f64 {
-    unsafe {
-        intrinsics::floorf64(x)
-    }
+    unsafe { intrinsics::floorf64(x) }
 }
 
 pub unsafe fn abort_internal() -> ! {
@@ -103,8 +100,11 @@ pub fn init() {
 
 #[cfg(not(test))]
 #[no_mangle]
-pub unsafe extern "C" fn runtime_entry(argc: i32, argv: *const *const c_char,
-                                       env: *const *const c_char) -> ! {
+pub unsafe extern "C" fn runtime_entry(
+    argc: i32,
+    argv: *const *const c_char,
+    env: *const *const c_char,
+) -> ! {
     extern "C" {
         fn main(argc: isize, argv: *const *const c_char) -> i32;
     }
@@ -139,9 +139,5 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind {
 }
 
 pub fn cvt(result: i32) -> crate::io::Result<usize> {
-    if result < 0 {
-        Err(crate::io::Error::from_raw_os_error(-result))
-    } else {
-        Ok(result as usize)
-    }
+    if result < 0 { Err(crate::io::Error::from_raw_os_error(-result)) } else { Ok(result as usize) }
 }
diff --git a/src/libstd/sys/hermit/mutex.rs b/src/libstd/sys/hermit/mutex.rs
index 9414bf8fbbb..b5c75f738d2 100644
--- a/src/libstd/sys/hermit/mutex.rs
+++ b/src/libstd/sys/hermit/mutex.rs
@@ -1,9 +1,9 @@
-use crate::ptr;
 use crate::ffi::c_void;
+use crate::ptr;
 use crate::sys::hermit::abi;
 
 pub struct Mutex {
-    inner: *const c_void
+    inner: *const c_void,
 }
 
 unsafe impl Send for Mutex {}
@@ -42,7 +42,7 @@ impl Mutex {
 }
 
 pub struct ReentrantMutex {
-    inner: *const c_void
+    inner: *const c_void,
 }
 
 impl ReentrantMutex {
diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs
index 5b7ff642271..82917e71be1 100644
--- a/src/libstd/sys/hermit/net.rs
+++ b/src/libstd/sys/hermit/net.rs
@@ -1,7 +1,7 @@
-use crate::fmt;
 use crate::convert::TryFrom;
+use crate::fmt;
 use crate::io::{self, IoSlice, IoSliceMut};
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
 use crate::str;
 use crate::sys::{unsupported, Void};
 use crate::time::Duration;
@@ -234,23 +234,19 @@ impl UdpSocket {
         match self.0 {}
     }
 
-    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
@@ -357,8 +353,7 @@ pub mod netc {
     }
 
     #[derive(Copy, Clone)]
-    pub struct sockaddr {
-    }
+    pub struct sockaddr {}
 
     pub type socklen_t = usize;
 }
diff --git a/src/libstd/sys/hermit/os.rs b/src/libstd/sys/hermit/os.rs
index 8a25cbcf07b..ad63b0e0c13 100644
--- a/src/libstd/sys/hermit/os.rs
+++ b/src/libstd/sys/hermit/os.rs
@@ -1,5 +1,6 @@
+use crate::collections::HashMap;
 use crate::error::Error as StdError;
-use crate::ffi::{CStr, OsString, OsStr};
+use crate::ffi::{CStr, OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::marker::PhantomData;
@@ -7,12 +8,11 @@ use crate::memchr;
 use crate::path::{self, PathBuf};
 use crate::ptr;
 use crate::str;
-use crate::sys::{unsupported, Void};
-use crate::collections::HashMap;
-use crate::vec;
 use crate::sync::Mutex;
-use crate::sys_common::os_str_bytes::*;
 use crate::sys::hermit::abi;
+use crate::sys::{unsupported, Void};
+use crate::sys_common::os_str_bytes::*;
+use crate::vec;
 
 pub fn errno() -> i32 {
     0
@@ -47,7 +47,9 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     Err(JoinPathsError)
 }
@@ -77,7 +79,7 @@ pub fn init_environment(env: *const *const i8) {
         let mut guard = ENV.as_ref().unwrap().lock().unwrap();
         let mut environ = env;
         while environ != ptr::null() && *environ != ptr::null() {
-            if let Some((key,value)) = parse(CStr::from_ptr(*environ).to_bytes()) {
+            if let Some((key, value)) = parse(CStr::from_ptr(*environ).to_bytes()) {
                 guard.insert(key, value);
             }
             environ = environ.offset(1);
@@ -93,10 +95,12 @@ pub fn init_environment(env: *const *const i8) {
             return None;
         }
         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
-        pos.map(|p| (
-            OsStringExt::from_vec(input[..p].to_vec()),
-            OsStringExt::from_vec(input[p+1..].to_vec()),
-        ))
+        pos.map(|p| {
+            (
+                OsStringExt::from_vec(input[..p].to_vec()),
+                OsStringExt::from_vec(input[p + 1..].to_vec()),
+            )
+        })
     }
 }
 
@@ -107,14 +111,18 @@ pub struct Env {
 
 impl Iterator for Env {
     type Item = (OsString, OsString);
-    fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<(OsString, OsString)> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
 }
 
 /// Returns a vector of (variable, value) byte-vector pairs for all the
 /// environment variables of the current process.
 pub fn env() -> Env {
-   unsafe {
+    unsafe {
         let guard = ENV.as_ref().unwrap().lock().unwrap();
         let mut result = Vec::new();
 
@@ -122,18 +130,15 @@ pub fn env() -> Env {
             result.push((key.clone(), value.clone()));
         }
 
-        return Env {
-            iter: result.into_iter(),
-            _dont_send_or_sync_me: PhantomData,
-        }
+        return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData };
     }
 }
 
 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
     unsafe {
         match ENV.as_ref().unwrap().lock().unwrap().get_mut(k) {
-            Some(value) => { Ok(Some(value.clone())) },
-            None => { Ok(None) },
+            Some(value) => Ok(Some(value.clone())),
+            None => Ok(None),
         }
     }
 }
@@ -168,7 +173,5 @@ pub fn exit(code: i32) -> ! {
 }
 
 pub fn getpid() -> u32 {
-    unsafe {
-        abi::getpid()
-    }
+    unsafe { abi::getpid() }
 }
diff --git a/src/libstd/sys/hermit/path.rs b/src/libstd/sys/hermit/path.rs
index 7a183956107..840a7ae0426 100644
--- a/src/libstd/sys/hermit/path.rs
+++ b/src/libstd/sys/hermit/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/hermit/pipe.rs b/src/libstd/sys/hermit/pipe.rs
index 9f07f054362..fb14dc59101 100644
--- a/src/libstd/sys/hermit/pipe.rs
+++ b/src/libstd/sys/hermit/pipe.rs
@@ -25,9 +25,6 @@ impl AnonPipe {
     }
 }
 
-pub fn read2(p1: AnonPipe,
-             _v1: &mut Vec<u8>,
-             _p2: AnonPipe,
-             _v2: &mut Vec<u8>) -> io::Result<()> {
+pub fn read2(p1: AnonPipe, _v1: &mut Vec<u8>, _p2: AnonPipe, _v2: &mut Vec<u8>) -> io::Result<()> {
     match p1.0 {}
 }
diff --git a/src/libstd/sys/hermit/process.rs b/src/libstd/sys/hermit/process.rs
index edf933d10e0..4702e5c5492 100644
--- a/src/libstd/sys/hermit/process.rs
+++ b/src/libstd/sys/hermit/process.rs
@@ -32,32 +32,28 @@ pub enum Stdio {
 
 impl Command {
     pub fn new(_program: &OsStr) -> Command {
-        Command {
-            env: Default::default()
-        }
+        Command { env: Default::default() }
     }
 
-    pub fn arg(&mut self, _arg: &OsStr) {
-    }
+    pub fn arg(&mut self, _arg: &OsStr) {}
 
     pub fn env_mut(&mut self) -> &mut CommandEnv {
         &mut self.env
     }
 
-    pub fn cwd(&mut self, _dir: &OsStr) {
-    }
+    pub fn cwd(&mut self, _dir: &OsStr) {}
 
-    pub fn stdin(&mut self, _stdin: Stdio) {
-    }
+    pub fn stdin(&mut self, _stdin: Stdio) {}
 
-    pub fn stdout(&mut self, _stdout: Stdio) {
-    }
+    pub fn stdout(&mut self, _stdout: Stdio) {}
 
-    pub fn stderr(&mut self, _stderr: Stdio) {
-    }
+    pub fn stderr(&mut self, _stderr: Stdio) {}
 
-    pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool)
-        -> io::Result<(Process, StdioPipes)> {
+    pub fn spawn(
+        &mut self,
+        _default: Stdio,
+        _needs_stdin: bool,
+    ) -> io::Result<(Process, StdioPipes)> {
         unsupported()
     }
 }
@@ -106,8 +102,7 @@ impl PartialEq for ExitStatus {
     }
 }
 
-impl Eq for ExitStatus {
-}
+impl Eq for ExitStatus {}
 
 impl fmt::Debug for ExitStatus {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/src/libstd/sys/hermit/rwlock.rs b/src/libstd/sys/hermit/rwlock.rs
index 990e7551114..c19799af3c7 100644
--- a/src/libstd/sys/hermit/rwlock.rs
+++ b/src/libstd/sys/hermit/rwlock.rs
@@ -1,7 +1,7 @@
 use super::mutex::Mutex;
 
 pub struct RWLock {
-    mutex: Mutex
+    mutex: Mutex,
 }
 
 unsafe impl Send for RWLock {}
@@ -9,9 +9,7 @@ unsafe impl Sync for RWLock {}
 
 impl RWLock {
     pub const fn new() -> RWLock {
-        RWLock {
-            mutex: Mutex::new()
-        }
+        RWLock { mutex: Mutex::new() }
     }
 
     #[inline]
diff --git a/src/libstd/sys/hermit/stack_overflow.rs b/src/libstd/sys/hermit/stack_overflow.rs
index b339e433e77..65a1b17acce 100644
--- a/src/libstd/sys/hermit/stack_overflow.rs
+++ b/src/libstd/sys/hermit/stack_overflow.rs
@@ -7,9 +7,7 @@ impl Handler {
 }
 
 #[inline]
-pub unsafe fn init() {
-}
+pub unsafe fn init() {}
 
 #[inline]
-pub unsafe fn cleanup() {
-}
+pub unsafe fn cleanup() {}
diff --git a/src/libstd/sys/hermit/stdio.rs b/src/libstd/sys/hermit/stdio.rs
index 9505f02fda8..2eb011ccb39 100644
--- a/src/libstd/sys/hermit/stdio.rs
+++ b/src/libstd/sys/hermit/stdio.rs
@@ -20,7 +20,6 @@ impl Stdin {
         //    .read(data)
         Ok(0)
     }
-
 }
 
 impl Stdout {
@@ -31,9 +30,7 @@ impl Stdout {
     pub fn write(&self, data: &[u8]) -> io::Result<usize> {
         let len;
 
-        unsafe {
-            len = abi::write(1, data.as_ptr() as *const u8, data.len())
-        }
+        unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) }
 
         if len < 0 {
             Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print"))
@@ -45,9 +42,7 @@ impl Stdout {
     pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result<usize> {
         let len;
 
-        unsafe {
-            len = abi::write(1, data.as_ptr() as *const u8, data.len())
-        }
+        unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) }
 
         if len < 0 {
             Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print"))
@@ -69,9 +64,7 @@ impl Stderr {
     pub fn write(&self, data: &[u8]) -> io::Result<usize> {
         let len;
 
-        unsafe {
-            len = abi::write(2, data.as_ptr() as *const u8, data.len())
-        }
+        unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) }
 
         if len < 0 {
             Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print"))
@@ -83,9 +76,7 @@ impl Stderr {
     pub fn write_vectored(&self, data: &[IoSlice<'_>]) -> io::Result<usize> {
         let len;
 
-        unsafe {
-            len = abi::write(2, data.as_ptr() as *const u8, data.len())
-        }
+        unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) }
 
         if len < 0 {
             Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print"))
diff --git a/src/libstd/sys/hermit/thread.rs b/src/libstd/sys/hermit/thread.rs
index 99a9c830c9e..c3c29c93826 100644
--- a/src/libstd/sys/hermit/thread.rs
+++ b/src/libstd/sys/hermit/thread.rs
@@ -1,11 +1,11 @@
 #![allow(dead_code)]
 
 use crate::ffi::CStr;
+use crate::fmt;
 use crate::io;
+use crate::mem;
 use crate::sys::hermit::abi;
 use crate::time::Duration;
-use crate::mem;
-use crate::fmt;
 use core::u32;
 
 use crate::sys_common::thread::*;
@@ -35,7 +35,7 @@ impl fmt::Display for Priority {
 pub const NORMAL_PRIO: Priority = Priority::from(2);
 
 pub struct Thread {
-    tid: Tid
+    tid: Tid,
 }
 
 unsafe impl Send for Thread {}
@@ -44,14 +44,20 @@ unsafe impl Sync for Thread {}
 pub const DEFAULT_MIN_STACK_SIZE: usize = 262144;
 
 impl Thread {
-    pub unsafe fn new_with_coreid(_stack: usize, p: Box<dyn FnOnce()>, core_id: isize)
-        -> io::Result<Thread>
-    {
+    pub unsafe fn new_with_coreid(
+        _stack: usize,
+        p: Box<dyn FnOnce()>,
+        core_id: isize,
+    ) -> io::Result<Thread> {
         let p = box p;
         let mut tid: Tid = u32::MAX;
-        let ret = abi::spawn(&mut tid as *mut Tid, thread_start,
-                            &*p as *const _ as *const u8 as usize,
-                            Priority::into(NORMAL_PRIO), core_id);
+        let ret = abi::spawn(
+            &mut tid as *mut Tid,
+            thread_start,
+            &*p as *const _ as *const u8 as usize,
+            Priority::into(NORMAL_PRIO),
+            core_id,
+        );
 
         return if ret == 0 {
             mem::forget(p); // ownership passed to pthread_create
@@ -60,16 +66,14 @@ impl Thread {
             Err(io::Error::new(io::ErrorKind::Other, "Unable to create thread!"))
         };
 
-        extern fn thread_start(main: usize) {
+        extern "C" fn thread_start(main: usize) {
             unsafe {
                 start_thread(main as *mut u8);
             }
         }
     }
 
-    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>)
-        -> io::Result<Thread>
-    {
+    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         Thread::new_with_coreid(stack, p, -1 /* = no specific core */)
     }
 
@@ -99,7 +103,9 @@ impl Thread {
     }
 
     #[inline]
-    pub fn id(&self) -> Tid { self.tid }
+    pub fn id(&self) -> Tid {
+        self.tid
+    }
 
     #[inline]
     pub fn into_id(self) -> Tid {
@@ -111,6 +117,10 @@ impl Thread {
 
 pub mod guard {
     pub type Guard = !;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
 }
diff --git a/src/libstd/sys/hermit/thread_local.rs b/src/libstd/sys/hermit/thread_local.rs
index 268fb770eae..ba967c7676c 100644
--- a/src/libstd/sys/hermit/thread_local.rs
+++ b/src/libstd/sys/hermit/thread_local.rs
@@ -7,7 +7,7 @@ use crate::sys_common::mutex::Mutex;
 
 pub type Key = usize;
 
-type Dtor = unsafe extern fn(*mut u8);
+type Dtor = unsafe extern "C" fn(*mut u8);
 
 static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
 
@@ -41,11 +41,7 @@ pub unsafe fn create(dtor: Option<Dtor>) -> Key {
 
 #[inline]
 pub unsafe fn get(key: Key) -> *mut u8 {
-    if let Some(&entry) = locals().get(&key) {
-        entry
-    } else {
-        ptr::null_mut()
-    }
+    if let Some(&entry) = locals().get(&key) { entry } else { ptr::null_mut() }
 }
 
 #[inline]
diff --git a/src/libstd/sys/hermit/time.rs b/src/libstd/sys/hermit/time.rs
index 8372189546d..c02de17c1fc 100644
--- a/src/libstd/sys/hermit/time.rs
+++ b/src/libstd/sys/hermit/time.rs
@@ -1,34 +1,35 @@
 #![allow(dead_code)]
 
-use crate::time::Duration;
 use crate::cmp::Ordering;
 use crate::convert::TryInto;
-use core::hash::{Hash, Hasher};
 use crate::sys::hermit::abi;
-use crate::sys::hermit::abi::{CLOCK_REALTIME, CLOCK_MONOTONIC, NSEC_PER_SEC};
 use crate::sys::hermit::abi::timespec;
+use crate::sys::hermit::abi::{CLOCK_MONOTONIC, CLOCK_REALTIME, NSEC_PER_SEC};
+use crate::time::Duration;
+use core::hash::{Hash, Hasher};
 
 #[derive(Copy, Clone, Debug)]
 struct Timespec {
-    t: timespec
+    t: timespec,
 }
 
 impl Timespec {
     const fn zero() -> Timespec {
-        Timespec {
-            t: timespec { tv_sec: 0, tv_nsec: 0 },
-        }
+        Timespec { t: timespec { tv_sec: 0, tv_nsec: 0 } }
     }
 
     fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
         if self >= other {
             Ok(if self.t.tv_nsec >= other.t.tv_nsec {
-                Duration::new((self.t.tv_sec - other.t.tv_sec) as u64,
-                              (self.t.tv_nsec - other.t.tv_nsec) as u32)
+                Duration::new(
+                    (self.t.tv_sec - other.t.tv_sec) as u64,
+                    (self.t.tv_nsec - other.t.tv_nsec) as u32,
+                )
             } else {
-                Duration::new((self.t.tv_sec - 1 - other.t.tv_sec) as u64,
-                              self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) -
-                              other.t.tv_nsec as u32)
+                Duration::new(
+                    (self.t.tv_sec - 1 - other.t.tv_sec) as u64,
+                    self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32,
+                )
             })
         } else {
             match other.sub_timespec(self) {
@@ -52,12 +53,7 @@ impl Timespec {
             nsec -= NSEC_PER_SEC as u32;
             secs = secs.checked_add(1)?;
         }
-        Some(Timespec {
-            t: timespec {
-                tv_sec: secs,
-                tv_nsec: nsec as _,
-            },
-        })
+        Some(Timespec { t: timespec { tv_sec: secs, tv_nsec: nsec as _ } })
     }
 
     fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
@@ -73,12 +69,7 @@ impl Timespec {
             nsec += NSEC_PER_SEC as i32;
             secs = secs.checked_sub(1)?;
         }
-        Some(Timespec {
-            t: timespec {
-                tv_sec: secs,
-                tv_nsec: nsec as _,
-            },
-        })
+        Some(Timespec { t: timespec { tv_sec: secs, tv_nsec: nsec as _ } })
     }
 }
 
@@ -105,7 +96,7 @@ impl Ord for Timespec {
 }
 
 impl Hash for Timespec {
-    fn hash<H : Hasher>(&self, state: &mut H) {
+    fn hash<H: Hasher>(&self, state: &mut H) {
         self.t.tv_sec.hash(state);
         self.t.tv_nsec.hash(state);
     }
@@ -150,9 +141,7 @@ pub struct SystemTime {
     t: Timespec,
 }
 
-pub const UNIX_EPOCH: SystemTime = SystemTime {
-    t: Timespec::zero(),
-};
+pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
 
 impl SystemTime {
     pub fn now() -> SystemTime {
diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs
index 0f107de83f0..87e7a5da2b7 100644
--- a/src/libstd/sys/sgx/abi/mod.rs
+++ b/src/libstd/sys/sgx/abi/mod.rs
@@ -1,11 +1,11 @@
 #![cfg_attr(test, allow(unused))] // RT initialization logic is not compiled for test
 
-use core::sync::atomic::{AtomicUsize, Ordering};
 use crate::io::Write;
+use core::sync::atomic::{AtomicUsize, Ordering};
 
 // runtime features
-mod reloc;
 pub(super) mod panic;
+mod reloc;
 
 // library features
 pub mod mem;
@@ -38,14 +38,16 @@ unsafe extern "C" fn tcs_init(secondary: bool) {
         UNINIT => {
             reloc::relocate_elf_rela();
             RELOC_STATE.store(DONE, Ordering::Release);
-        },
+        }
         // We need to wait until the initialization is done.
-        BUSY => while RELOC_STATE.load(Ordering::Acquire) == BUSY  {
-            core::arch::x86_64::_mm_pause()
-        },
+        BUSY => {
+            while RELOC_STATE.load(Ordering::Acquire) == BUSY {
+                core::arch::x86_64::_mm_pause()
+            }
+        }
         // Initialization is done.
-        DONE => {},
-        _ => unreachable!()
+        DONE => {}
+        _ => unreachable!(),
     }
 }
 
diff --git a/src/libstd/sys/sgx/abi/panic.rs b/src/libstd/sys/sgx/abi/panic.rs
index 2401476716f..229b3b3291f 100644
--- a/src/libstd/sys/sgx/abi/panic.rs
+++ b/src/libstd/sys/sgx/abi/panic.rs
@@ -16,21 +16,13 @@ fn empty_user_slice() -> &'static mut UserRef<[u8]> {
 
 impl SgxPanicOutput {
     pub(crate) fn new() -> Option<Self> {
-        if unsafe { DEBUG == 0 } {
-            None
-        } else {
-            Some(SgxPanicOutput(None))
-        }
+        if unsafe { DEBUG == 0 } { None } else { Some(SgxPanicOutput(None)) }
     }
 
     fn init(&mut self) -> &mut &'static mut UserRef<[u8]> {
         self.0.get_or_insert_with(|| unsafe {
             let ptr = take_debug_panic_buf_ptr();
-            if ptr.is_null() {
-                empty_user_slice()
-            } else {
-                UserRef::from_raw_parts_mut(ptr, 1024)
-            }
+            if ptr.is_null() { empty_user_slice() } else { UserRef::from_raw_parts_mut(ptr, 1024) }
         })
     }
 }
diff --git a/src/libstd/sys/sgx/abi/reloc.rs b/src/libstd/sys/sgx/abi/reloc.rs
index 6dd24c524fc..02dff0ad29f 100644
--- a/src/libstd/sys/sgx/abi/reloc.rs
+++ b/src/libstd/sys/sgx/abi/reloc.rs
@@ -1,5 +1,5 @@
-use crate::slice::from_raw_parts;
 use super::mem;
+use crate::slice::from_raw_parts;
 
 const R_X86_64_RELATIVE: u32 = 8;
 
@@ -11,18 +11,20 @@ struct Rela<T> {
 }
 
 pub fn relocate_elf_rela() {
-    extern {
+    extern "C" {
         static RELA: u64;
         static RELACOUNT: usize;
     }
 
-    if unsafe { RELACOUNT } == 0 { return }  // unsafe ok: link-time constant
+    if unsafe { RELACOUNT } == 0 {
+        return;
+    } // unsafe ok: link-time constant
 
     let relas = unsafe {
-        from_raw_parts::<Rela<u64>>(mem::rel_ptr(RELA), RELACOUNT)  // unsafe ok: link-time constant
+        from_raw_parts::<Rela<u64>>(mem::rel_ptr(RELA), RELACOUNT) // unsafe ok: link-time constant
     };
     for rela in relas {
-        if rela.info != (/*0 << 32 |*/ R_X86_64_RELATIVE as u64) {
+        if rela.info != (/*0 << 32 |*/R_X86_64_RELATIVE as u64) {
             rtabort!("Invalid relocation");
         }
         unsafe { *mem::rel_ptr_mut::<*const ()>(rela.offset) = mem::rel_ptr(rela.addend) };
diff --git a/src/libstd/sys/sgx/abi/thread.rs b/src/libstd/sys/sgx/abi/thread.rs
index c17fa2d0015..ef55b821a2b 100644
--- a/src/libstd/sys/sgx/abi/thread.rs
+++ b/src/libstd/sys/sgx/abi/thread.rs
@@ -6,6 +6,8 @@ use fortanix_sgx_abi::Tcs;
 /// is a one-to-one correspondence of the ID to the address of the TCS.
 #[unstable(feature = "sgx_platform", issue = "56975")]
 pub fn current() -> Tcs {
-    extern "C" { fn get_tcs_addr() -> Tcs; }
+    extern "C" {
+        fn get_tcs_addr() -> Tcs;
+    }
     unsafe { get_tcs_addr() }
 }
diff --git a/src/libstd/sys/sgx/abi/tls.rs b/src/libstd/sys/sgx/abi/tls.rs
index 03e08ad547d..81a766e367d 100644
--- a/src/libstd/sys/sgx/abi/tls.rs
+++ b/src/libstd/sys/sgx/abi/tls.rs
@@ -1,11 +1,11 @@
-use crate::sync::atomic::{AtomicUsize, Ordering};
-use crate::ptr;
-use crate::mem;
+use self::sync_bitset::*;
 use crate::cell::Cell;
+use crate::mem;
 use crate::num::NonZeroUsize;
-use self::sync_bitset::*;
+use crate::ptr;
+use crate::sync::atomic::{AtomicUsize, Ordering};
 
-#[cfg(target_pointer_width="64")]
+#[cfg(target_pointer_width = "64")]
 const USIZE_BITS: usize = 64;
 const TLS_KEYS: usize = 128; // Same as POSIX minimum
 const TLS_KEYS_BITSET_SIZE: usize = (TLS_KEYS + (USIZE_BITS - 1)) / USIZE_BITS;
@@ -50,18 +50,18 @@ impl Key {
 
 #[repr(C)]
 pub struct Tls {
-    data: [Cell<*mut u8>; TLS_KEYS]
+    data: [Cell<*mut u8>; TLS_KEYS],
 }
 
 pub struct ActiveTls<'a> {
-    tls: &'a Tls
+    tls: &'a Tls,
 }
 
 impl<'a> Drop for ActiveTls<'a> {
     fn drop(&mut self) {
         let value_with_destructor = |key: usize| {
             let ptr = TLS_DESTRUCTOR[key].load(Ordering::Relaxed);
-            unsafe { mem::transmute::<_,Option<unsafe extern fn(*mut u8)>>(ptr) }
+            unsafe { mem::transmute::<_, Option<unsafe extern "C" fn(*mut u8)>>(ptr) }
                 .map(|dtor| (&self.tls.data[key], dtor))
         };
 
@@ -99,7 +99,7 @@ impl Tls {
         &*(get_tls_ptr() as *const Tls)
     }
 
-    pub fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+    pub fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
         let index = if let Some(index) = TLS_KEY_IN_USE.set() {
             index
         } else {
@@ -127,10 +127,10 @@ impl Tls {
 }
 
 mod sync_bitset {
-    use crate::sync::atomic::{AtomicUsize, Ordering};
+    use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS};
     use crate::iter::{Enumerate, Peekable};
     use crate::slice::Iter;
-    use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS};
+    use crate::sync::atomic::{AtomicUsize, Ordering};
 
     /// A bitset that can be used synchronously.
     pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]);
@@ -146,10 +146,7 @@ mod sync_bitset {
 
         /// Not atomic.
         pub fn iter(&self) -> SyncBitsetIter<'_> {
-            SyncBitsetIter {
-                iter: self.0.iter().enumerate().peekable(),
-                elem_idx: 0,
-            }
+            SyncBitsetIter { iter: self.0.iter().enumerate().peekable(), elem_idx: 0 }
         }
 
         pub fn clear(&self, index: usize) {
@@ -171,7 +168,7 @@ mod sync_bitset {
                         current,
                         current | (1 << trailing_ones),
                         Ordering::AcqRel,
-                        Ordering::Relaxed
+                        Ordering::Relaxed,
                     ) {
                         Ok(_) => return Some(idx * USIZE_BITS + trailing_ones),
                         Err(previous) => current = previous,
diff --git a/src/libstd/sys/sgx/abi/usercalls/alloc.rs b/src/libstd/sys/sgx/abi/usercalls/alloc.rs
index 75dd0d429c2..b54c115a2b6 100644
--- a/src/libstd/sys/sgx/abi/usercalls/alloc.rs
+++ b/src/libstd/sys/sgx/abi/usercalls/alloc.rs
@@ -1,14 +1,14 @@
 #![allow(unused)]
 
-use crate::ptr::{self, NonNull};
-use crate::mem;
 use crate::cell::UnsafeCell;
+use crate::mem;
+use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut};
+use crate::ptr::{self, NonNull};
 use crate::slice;
-use crate::ops::{Deref, DerefMut, Index, IndexMut, CoerceUnsized};
 use crate::slice::SliceIndex;
 
-use fortanix_sgx_abi::*;
 use super::super::mem::is_user_range;
+use fortanix_sgx_abi::*;
 
 /// A type that can be safely read from or written to userspace.
 ///
@@ -109,9 +109,7 @@ pub unsafe trait UserSafe {
     /// * the pointer is null.
     /// * the pointed-to range is not in user memory.
     unsafe fn check_ptr(ptr: *const Self) {
-        let is_aligned = |p| -> bool {
-            0 == (p as usize) & (Self::align_of() - 1)
-        };
+        let is_aligned = |p| -> bool { 0 == (p as usize) & (Self::align_of() - 1) };
 
         assert!(is_aligned(ptr as *const u8));
         assert!(is_user_range(ptr as _, mem::size_of_val(&*ptr)));
@@ -183,7 +181,10 @@ impl<T: ?Sized> NewUserRef<NonNull<T>> for NonNull<UserRef<T>> {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T: ?Sized> User<T> where T: UserSafe {
+impl<T: ?Sized> User<T>
+where
+    T: UserSafe,
+{
     // This function returns memory that is practically uninitialized, but is
     // not considered "unspecified" or "undefined" for purposes of an
     // optimizing compiler. This is achieved by returning a pointer from
@@ -211,7 +212,7 @@ impl<T: ?Sized> User<T> where T: UserSafe {
             ptr::copy(
                 val as *const T as *const u8,
                 ret.0.as_ptr() as *mut u8,
-                mem::size_of_val(val)
+                mem::size_of_val(val),
             );
             ret
         }
@@ -244,7 +245,10 @@ impl<T: ?Sized> User<T> where T: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T> User<T> where T: UserSafe {
+impl<T> User<T>
+where
+    T: UserSafe,
+{
     /// Allocate space for `T` in user memory.
     pub fn uninitialized() -> Self {
         Self::new_uninit_bytes(mem::size_of::<T>())
@@ -252,7 +256,10 @@ impl<T> User<T> where T: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T> User<[T]> where [T]: UserSafe {
+impl<T> User<[T]>
+where
+    [T]: UserSafe,
+{
     /// Allocate space for a `[T]` of `n` elements in user memory.
     pub fn uninitialized(n: usize) -> Self {
         Self::new_uninit_bytes(n * mem::size_of::<T>())
@@ -278,7 +285,10 @@ impl<T> User<[T]> where [T]: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T: ?Sized> UserRef<T> where T: UserSafe {
+impl<T: ?Sized> UserRef<T>
+where
+    T: UserSafe,
+{
     /// Creates a `&UserRef<[T]>` from a raw pointer.
     ///
     /// # Safety
@@ -309,7 +319,7 @@ impl<T: ?Sized> UserRef<T> where T: UserSafe {
     /// * The pointed-to range is not in user memory
     pub unsafe fn from_mut_ptr<'a>(ptr: *mut T) -> &'a mut Self {
         T::check_ptr(ptr);
-        &mut*(ptr as *mut Self)
+        &mut *(ptr as *mut Self)
     }
 
     /// Copies `val` into user memory.
@@ -319,11 +329,11 @@ impl<T: ?Sized> UserRef<T> where T: UserSafe {
     /// the source. This can happen for dynamically-sized types such as slices.
     pub fn copy_from_enclave(&mut self, val: &T) {
         unsafe {
-            assert_eq!(mem::size_of_val(val), mem::size_of_val( &*self.0.get() ));
+            assert_eq!(mem::size_of_val(val), mem::size_of_val(&*self.0.get()));
             ptr::copy(
                 val as *const T as *const u8,
                 self.0.get() as *mut T as *mut u8,
-                mem::size_of_val(val)
+                mem::size_of_val(val),
             );
         }
     }
@@ -335,11 +345,11 @@ impl<T: ?Sized> UserRef<T> where T: UserSafe {
     /// the source. This can happen for dynamically-sized types such as slices.
     pub fn copy_to_enclave(&self, dest: &mut T) {
         unsafe {
-            assert_eq!(mem::size_of_val(dest), mem::size_of_val( &*self.0.get() ));
+            assert_eq!(mem::size_of_val(dest), mem::size_of_val(&*self.0.get()));
             ptr::copy(
                 self.0.get() as *const T as *const u8,
                 dest as *mut T as *mut u8,
-                mem::size_of_val(dest)
+                mem::size_of_val(dest),
             );
         }
     }
@@ -356,7 +366,10 @@ impl<T: ?Sized> UserRef<T> where T: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T> UserRef<T> where T: UserSafe {
+impl<T> UserRef<T>
+where
+    T: UserSafe,
+{
     /// Copies the value from user memory into enclave memory.
     pub fn to_enclave(&self) -> T {
         unsafe { ptr::read(self.0.get()) }
@@ -364,7 +377,10 @@ impl<T> UserRef<T> where T: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T> UserRef<[T]> where [T]: UserSafe {
+impl<T> UserRef<[T]>
+where
+    [T]: UserSafe,
+{
     /// Creates a `&UserRef<[T]>` from a raw thin pointer and a slice length.
     ///
     /// # Safety
@@ -396,7 +412,7 @@ impl<T> UserRef<[T]> where [T]: UserSafe {
     /// * The pointed-to range does not fit in the address space
     /// * The pointed-to range is not in user memory
     pub unsafe fn from_raw_parts_mut<'a>(ptr: *mut T, len: usize) -> &'a mut Self {
-        &mut*(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::<T>()).as_ptr() as *mut Self)
+        &mut *(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::<T>()).as_ptr() as *mut Self)
     }
 
     /// Obtain a raw pointer to the first element of this user slice.
@@ -439,20 +455,18 @@ impl<T> UserRef<[T]> where [T]: UserSafe {
 
     /// Returns an iterator over the slice.
     pub fn iter(&self) -> Iter<'_, T>
-        where T: UserSafe // FIXME: should be implied by [T]: UserSafe?
+    where
+        T: UserSafe, // FIXME: should be implied by [T]: UserSafe?
     {
-        unsafe {
-            Iter((&*self.as_raw_ptr()).iter())
-        }
+        unsafe { Iter((&*self.as_raw_ptr()).iter()) }
     }
 
     /// Returns an iterator that allows modifying each value.
     pub fn iter_mut(&mut self) -> IterMut<'_, T>
-        where T: UserSafe // FIXME: should be implied by [T]: UserSafe?
+    where
+        T: UserSafe, // FIXME: should be implied by [T]: UserSafe?
     {
-        unsafe {
-            IterMut((&mut*self.as_raw_mut_ptr()).iter_mut())
-        }
+        unsafe { IterMut((&mut *self.as_raw_mut_ptr()).iter_mut()) }
     }
 }
 
@@ -468,9 +482,7 @@ impl<'a, T: UserSafe> Iterator for Iter<'a, T> {
 
     #[inline]
     fn next(&mut self) -> Option<Self::Item> {
-        unsafe {
-            self.0.next().map(|e| UserRef::from_ptr(e))
-        }
+        unsafe { self.0.next().map(|e| UserRef::from_ptr(e)) }
     }
 }
 
@@ -486,14 +498,15 @@ impl<'a, T: UserSafe> Iterator for IterMut<'a, T> {
 
     #[inline]
     fn next(&mut self) -> Option<Self::Item> {
-        unsafe {
-            self.0.next().map(|e| UserRef::from_mut_ptr(e))
-        }
+        unsafe { self.0.next().map(|e| UserRef::from_mut_ptr(e)) }
     }
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T: ?Sized> Deref for User<T> where T: UserSafe {
+impl<T: ?Sized> Deref for User<T>
+where
+    T: UserSafe,
+{
     type Target = UserRef<T>;
 
     fn deref(&self) -> &Self::Target {
@@ -502,18 +515,24 @@ impl<T: ?Sized> Deref for User<T> where T: UserSafe {
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T: ?Sized> DerefMut for User<T> where T: UserSafe {
+impl<T: ?Sized> DerefMut for User<T>
+where
+    T: UserSafe,
+{
     fn deref_mut(&mut self) -> &mut Self::Target {
-        unsafe { &mut*self.0.as_ptr() }
+        unsafe { &mut *self.0.as_ptr() }
     }
 }
 
 #[unstable(feature = "sgx_platform", issue = "56975")]
-impl<T: ?Sized> Drop for User<T> where T: UserSafe {
+impl<T: ?Sized> Drop for User<T>
+where
+    T: UserSafe,
+{
     fn drop(&mut self) {
         unsafe {
             let ptr = (*self.0.as_ptr()).0.get();
-            super::free(ptr as _, mem::size_of_val(&mut*ptr), T::align_of());
+            super::free(ptr as _, mem::size_of_val(&mut *ptr), T::align_of());
         }
     }
 }
@@ -550,7 +569,7 @@ where
     #[inline]
     fn index_mut(&mut self, index: I) -> &mut UserRef<I::Output> {
         unsafe {
-            if let Some(slice) = index.get_mut(&mut*self.as_raw_mut_ptr()) {
+            if let Some(slice) = index.get_mut(&mut *self.as_raw_mut_ptr()) {
                 UserRef::from_mut_ptr(slice)
             } else {
                 rtabort!("index out of range for user slice");
diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs
index fca62e028de..ae803ee47a6 100644
--- a/src/libstd/sys/sgx/abi/usercalls/mod.rs
+++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs
@@ -1,5 +1,5 @@
 use crate::cmp;
-use crate::io::{Error as IoError, Result as IoResult, IoSlice, IoSliceMut};
+use crate::io::{Error as IoError, IoSlice, IoSliceMut, Result as IoResult};
 use crate::time::Duration;
 
 pub(crate) mod alloc;
@@ -26,7 +26,7 @@ pub fn read(fd: Fd, bufs: &mut [IoSliceMut<'_>]) -> IoResult<usize> {
                 userbuf[index..end].copy_to_enclave(&mut buf[..buflen]);
                 index += buf.len();
             } else {
-                break
+                break;
             }
         }
         Ok(userbuf.len())
@@ -60,7 +60,7 @@ pub fn write(fd: Fd, bufs: &[IoSlice<'_>]) -> IoResult<usize> {
                 userbuf[index..end].copy_from_enclave(&buf[..buflen]);
                 index += buf.len();
             } else {
-                break
+                break;
             }
         }
         raw::write(fd, userbuf.as_ptr(), userbuf.len()).from_sgx_result()
@@ -90,11 +90,8 @@ pub fn bind_stream(addr: &str) -> IoResult<(Fd, String)> {
     unsafe {
         let addr_user = alloc::User::new_from_enclave(addr.as_bytes());
         let mut local = alloc::User::<ByteBuffer>::uninitialized();
-        let fd = raw::bind_stream(
-            addr_user.as_ptr(),
-            addr_user.len(),
-            local.as_raw_mut_ptr()
-        ).from_sgx_result()?;
+        let fd = raw::bind_stream(addr_user.as_ptr(), addr_user.len(), local.as_raw_mut_ptr())
+            .from_sgx_result()?;
         let local = string_from_bytebuffer(&local, "bind_stream", "local_addr");
         Ok((fd, local))
     }
@@ -106,13 +103,10 @@ pub fn accept_stream(fd: Fd) -> IoResult<(Fd, String, String)> {
     unsafe {
         let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized();
         let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done
-                                                               // without forcing coercion?
+        // without forcing coercion?
         let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap());
-        let fd = raw::accept_stream(
-            fd,
-            local.as_raw_mut_ptr(),
-            peer.as_raw_mut_ptr()
-        ).from_sgx_result()?;
+        let fd = raw::accept_stream(fd, local.as_raw_mut_ptr(), peer.as_raw_mut_ptr())
+            .from_sgx_result()?;
         let local = string_from_bytebuffer(&local, "accept_stream", "local_addr");
         let peer = string_from_bytebuffer(&peer, "accept_stream", "peer_addr");
         Ok((fd, local, peer))
@@ -126,14 +120,15 @@ pub fn connect_stream(addr: &str) -> IoResult<(Fd, String, String)> {
         let addr_user = alloc::User::new_from_enclave(addr.as_bytes());
         let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized();
         let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done
-                                                               // without forcing coercion?
+        // without forcing coercion?
         let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap());
         let fd = raw::connect_stream(
             addr_user.as_ptr(),
             addr_user.len(),
             local.as_raw_mut_ptr(),
-            peer.as_raw_mut_ptr()
-        ).from_sgx_result()?;
+            peer.as_raw_mut_ptr(),
+        )
+        .from_sgx_result()?;
         let local = string_from_bytebuffer(&local, "connect_stream", "local_addr");
         let peer = string_from_bytebuffer(&peer, "connect_stream", "peer_addr");
         Ok((fd, local, peer))
@@ -183,25 +178,25 @@ pub use self::raw::free;
 
 fn check_os_error(err: Result) -> i32 {
     // FIXME: not sure how to make sure all variants of Error are covered
-    if err == Error::NotFound as _ ||
-       err == Error::PermissionDenied as _ ||
-       err == Error::ConnectionRefused as _ ||
-       err == Error::ConnectionReset as _ ||
-       err == Error::ConnectionAborted as _ ||
-       err == Error::NotConnected as _ ||
-       err == Error::AddrInUse as _ ||
-       err == Error::AddrNotAvailable as _ ||
-       err == Error::BrokenPipe as _ ||
-       err == Error::AlreadyExists as _ ||
-       err == Error::WouldBlock as _ ||
-       err == Error::InvalidInput as _ ||
-       err == Error::InvalidData as _ ||
-       err == Error::TimedOut as _ ||
-       err == Error::WriteZero as _ ||
-       err == Error::Interrupted as _ ||
-       err == Error::Other as _ ||
-       err == Error::UnexpectedEof as _ ||
-       ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err)
+    if err == Error::NotFound as _
+        || err == Error::PermissionDenied as _
+        || err == Error::ConnectionRefused as _
+        || err == Error::ConnectionReset as _
+        || err == Error::ConnectionAborted as _
+        || err == Error::NotConnected as _
+        || err == Error::AddrInUse as _
+        || err == Error::AddrNotAvailable as _
+        || err == Error::BrokenPipe as _
+        || err == Error::AlreadyExists as _
+        || err == Error::WouldBlock as _
+        || err == Error::InvalidInput as _
+        || err == Error::InvalidData as _
+        || err == Error::TimedOut as _
+        || err == Error::WriteZero as _
+        || err == Error::Interrupted as _
+        || err == Error::Other as _
+        || err == Error::UnexpectedEof as _
+        || ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err)
     {
         err
     } else {
diff --git a/src/libstd/sys/sgx/abi/usercalls/raw.rs b/src/libstd/sys/sgx/abi/usercalls/raw.rs
index e4694a8827a..e0ebf860618 100644
--- a/src/libstd/sys/sgx/abi/usercalls/raw.rs
+++ b/src/libstd/sys/sgx/abi/usercalls/raw.rs
@@ -3,8 +3,8 @@
 #[unstable(feature = "sgx_platform", issue = "56975")]
 pub use fortanix_sgx_abi::*;
 
-use crate::ptr::NonNull;
 use crate::num::NonZeroU64;
+use crate::ptr::NonNull;
 
 #[repr(C)]
 struct UsercallReturn(u64, u64);
@@ -25,9 +25,14 @@ extern "C" {
 /// Panics if `nr` is `0`.
 #[unstable(feature = "sgx_platform", issue = "56975")]
 #[inline]
-pub unsafe fn do_usercall(nr: NonZeroU64, p1: u64, p2: u64, p3: u64, p4: u64, abort: bool)
-    -> (u64, u64)
-{
+pub unsafe fn do_usercall(
+    nr: NonZeroU64,
+    p1: u64,
+    p2: u64,
+    p3: u64,
+    p4: u64,
+    abort: bool,
+) -> (u64, u64) {
     let UsercallReturn(a, b) = usercall(nr, p1, p2, abort as _, p3, p4);
     (a, b)
 }
@@ -109,11 +114,7 @@ define_ra!(<T> *mut T);
 
 impl RegisterArgument for bool {
     fn from_register(a: Register) -> bool {
-        if a != 0 {
-            true
-        } else {
-            false
-        }
+        if a != 0 { true } else { false }
     }
     fn into_register(self) -> Register {
         self as _
@@ -152,16 +153,17 @@ impl<T: RegisterArgument> ReturnValue for T {
 
 impl<T: RegisterArgument, U: RegisterArgument> ReturnValue for (T, U) {
     fn from_registers(_call: &'static str, regs: (Register, Register)) -> Self {
-        (
-            T::from_register(regs.0),
-            U::from_register(regs.1)
-        )
+        (T::from_register(regs.0), U::from_register(regs.1))
     }
 }
 
 macro_rules! return_type_is_abort {
-    (!) => { true };
-    ($r:ty) => { false };
+    (!) => {
+        true
+    };
+    ($r:ty) => {
+        false
+    };
 }
 
 // In this macro: using `$r:tt` because `$r:ty` doesn't match ! in `return_type_is_abort`
diff --git a/src/libstd/sys/sgx/args.rs b/src/libstd/sys/sgx/args.rs
index a84ab413876..b47a48e752c 100644
--- a/src/libstd/sys/sgx/args.rs
+++ b/src/libstd/sys/sgx/args.rs
@@ -1,9 +1,9 @@
 use super::abi::usercalls::{alloc, raw::ByteBuffer};
 use crate::ffi::OsString;
+use crate::slice;
 use crate::sync::atomic::{AtomicUsize, Ordering};
 use crate::sys::os_str::Buf;
 use crate::sys_common::FromInner;
-use crate::slice;
 
 #[cfg_attr(test, linkage = "available_externally")]
 #[export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE"]
@@ -14,8 +14,9 @@ type ArgsStore = Vec<OsString>;
 pub unsafe fn init(argc: isize, argv: *const *const u8) {
     if argc != 0 {
         let args = alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _);
-        let args = args.iter()
-            .map( |a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }) )
+        let args = args
+            .iter()
+            .map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
             .collect::<ArgsStore>();
         ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed);
     }
@@ -30,11 +31,7 @@ pub unsafe fn cleanup() {
 
 pub fn args() -> Args {
     let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
-    if let Some(args) = args {
-        Args(args.iter())
-    } else {
-        Args([].iter())
-    }
+    if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
 }
 
 pub struct Args(slice::Iter<'static, OsString>);
diff --git a/src/libstd/sys/sgx/cmath.rs b/src/libstd/sys/sgx/cmath.rs
index 5aabdc1c8d3..b89238f1da8 100644
--- a/src/libstd/sys/sgx/cmath.rs
+++ b/src/libstd/sys/sgx/cmath.rs
@@ -1,7 +1,7 @@
 #![cfg(not(test))]
 
 // These symbols are all defined in `compiler-builtins`
-extern {
+extern "C" {
     pub fn acos(n: f64) -> f64;
     pub fn acosf(n: f32) -> f32;
     pub fn asin(n: f64) -> f64;
diff --git a/src/libstd/sys/sgx/ext/io.rs b/src/libstd/sys/sgx/ext/io.rs
index fc88d10d3ed..8aa84a550d2 100644
--- a/src/libstd/sys/sgx/ext/io.rs
+++ b/src/libstd/sys/sgx/ext/io.rs
@@ -4,8 +4,8 @@
 //! description of [`TryIntoRawFd`](trait.TryIntoRawFd.html) for more details.
 #![unstable(feature = "sgx_platform", issue = "56975")]
 
-pub use crate::sys::abi::usercalls::raw::Fd as RawFd;
 use crate::net;
+pub use crate::sys::abi::usercalls::raw::Fd as RawFd;
 use crate::sys::{self, AsInner, FromInner, IntoInner, TryIntoInner};
 
 /// A trait to extract the raw SGX file descriptor from an underlying
@@ -60,11 +60,15 @@ pub trait TryIntoRawFd: Sized {
 }
 
 impl AsRawFd for net::TcpStream {
-    fn as_raw_fd(&self) -> RawFd { *self.as_inner().as_inner().as_inner().as_inner() }
+    fn as_raw_fd(&self) -> RawFd {
+        *self.as_inner().as_inner().as_inner().as_inner()
+    }
 }
 
 impl AsRawFd for net::TcpListener {
-    fn as_raw_fd(&self) -> RawFd { *self.as_inner().as_inner().as_inner().as_inner() }
+    fn as_raw_fd(&self) -> RawFd {
+        *self.as_inner().as_inner().as_inner().as_inner()
+    }
 }
 
 impl FromRawFd for net::TcpStream {
diff --git a/src/libstd/sys/sgx/ext/mod.rs b/src/libstd/sys/sgx/ext/mod.rs
index 51b2659da83..258ad3cd218 100644
--- a/src/libstd/sys/sgx/ext/mod.rs
+++ b/src/libstd/sys/sgx/ext/mod.rs
@@ -1,5 +1,5 @@
 #![unstable(feature = "sgx_platform", issue = "56975")]
 
 pub mod arch;
-pub mod io;
 pub mod ffi;
+pub mod io;
diff --git a/src/libstd/sys/sgx/fd.rs b/src/libstd/sys/sgx/fd.rs
index a1c4af81966..7da2424a642 100644
--- a/src/libstd/sys/sgx/fd.rs
+++ b/src/libstd/sys/sgx/fd.rs
@@ -1,9 +1,9 @@
 use fortanix_sgx_abi::Fd;
 
+use super::abi::usercalls;
 use crate::io::{self, IoSlice, IoSliceMut};
 use crate::mem;
 use crate::sys::{AsInner, FromInner, IntoInner};
-use super::abi::usercalls;
 
 #[derive(Debug)]
 pub struct FileDesc {
@@ -15,7 +15,9 @@ impl FileDesc {
         FileDesc { fd: fd }
     }
 
-    pub fn raw(&self) -> Fd { self.fd }
+    pub fn raw(&self) -> Fd {
+        self.fd
+    }
 
     /// Extracts the actual filedescriptor without closing it.
     pub fn into_raw(self) -> Fd {
@@ -46,7 +48,9 @@ impl FileDesc {
 }
 
 impl AsInner<Fd> for FileDesc {
-    fn as_inner(&self) -> &Fd { &self.fd }
+    fn as_inner(&self) -> &Fd {
+        &self.fd
+    }
 }
 
 impl IntoInner<Fd> for FileDesc {
diff --git a/src/libstd/sys/sgx/fs.rs b/src/libstd/sys/sgx/fs.rs
index e9095b375fe..e6160d1457d 100644
--- a/src/libstd/sys/sgx/fs.rs
+++ b/src/libstd/sys/sgx/fs.rs
@@ -1,7 +1,7 @@
 use crate::ffi::OsString;
 use crate::fmt;
 use crate::hash::{Hash, Hasher};
-use crate::io::{self, SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
 use crate::path::{Path, PathBuf};
 use crate::sys::time::SystemTime;
 use crate::sys::{unsupported, Void};
@@ -15,14 +15,14 @@ pub struct ReadDir(Void);
 pub struct DirEntry(Void);
 
 #[derive(Clone, Debug)]
-pub struct OpenOptions { }
+pub struct OpenOptions {}
 
 pub struct FilePermissions(Void);
 
 pub struct FileType(Void);
 
 #[derive(Debug)]
-pub struct DirBuilder { }
+pub struct DirBuilder {}
 
 impl FileAttr {
     pub fn size(&self) -> u64 {
@@ -78,8 +78,7 @@ impl PartialEq for FilePermissions {
     }
 }
 
-impl Eq for FilePermissions {
-}
+impl Eq for FilePermissions {}
 
 impl fmt::Debug for FilePermissions {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -115,8 +114,7 @@ impl PartialEq for FileType {
     }
 }
 
-impl Eq for FileType {
-}
+impl Eq for FileType {}
 
 impl Hash for FileType {
     fn hash<H: Hasher>(&self, _h: &mut H) {
@@ -164,15 +162,15 @@ impl DirEntry {
 
 impl OpenOptions {
     pub fn new() -> OpenOptions {
-        OpenOptions { }
+        OpenOptions {}
     }
 
-    pub fn read(&mut self, _read: bool) { }
-    pub fn write(&mut self, _write: bool) { }
-    pub fn append(&mut self, _append: bool) { }
-    pub fn truncate(&mut self, _truncate: bool) { }
-    pub fn create(&mut self, _create: bool) { }
-    pub fn create_new(&mut self, _create_new: bool) { }
+    pub fn read(&mut self, _read: bool) {}
+    pub fn write(&mut self, _write: bool) {}
+    pub fn append(&mut self, _append: bool) {}
+    pub fn truncate(&mut self, _truncate: bool) {}
+    pub fn create(&mut self, _create: bool) {}
+    pub fn create_new(&mut self, _create_new: bool) {}
 }
 
 impl File {
@@ -235,7 +233,7 @@ impl File {
 
 impl DirBuilder {
     pub fn new() -> DirBuilder {
-        DirBuilder { }
+        DirBuilder {}
     }
 
     pub fn mkdir(&self, _p: &Path) -> io::Result<()> {
diff --git a/src/libstd/sys/sgx/net.rs b/src/libstd/sys/sgx/net.rs
index f9eca9f4cb3..f36687b4d3d 100644
--- a/src/libstd/sys/sgx/net.rs
+++ b/src/libstd/sys/sgx/net.rs
@@ -1,12 +1,12 @@
-use crate::fmt;
-use crate::io::{self, IoSlice, IoSliceMut};
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
-use crate::time::Duration;
-use crate::sys::{unsupported, Void, sgx_ineffective, AsInner, FromInner, IntoInner, TryIntoInner};
-use crate::sys::fd::FileDesc;
 use crate::convert::TryFrom;
 use crate::error;
+use crate::fmt;
+use crate::io::{self, IoSlice, IoSliceMut};
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs};
 use crate::sync::Arc;
+use crate::sys::fd::FileDesc;
+use crate::sys::{sgx_ineffective, unsupported, AsInner, FromInner, IntoInner, TryIntoInner, Void};
+use crate::time::Duration;
 
 use super::abi::usercalls;
 
@@ -25,13 +25,15 @@ impl Socket {
 }
 
 impl AsInner<FileDesc> for Socket {
-    fn as_inner(&self) -> &FileDesc { &self.inner }
+    fn as_inner(&self) -> &FileDesc {
+        &self.inner
+    }
 }
 
 impl TryIntoInner<FileDesc> for Socket {
     fn try_into_inner(self) -> Result<FileDesc, Socket> {
         let Socket { inner, local_addr } = self;
-        Arc::try_unwrap(inner).map_err(|inner| Socket { inner, local_addr } )
+        Arc::try_unwrap(inner).map_err(|inner| Socket { inner, local_addr })
     }
 }
 
@@ -59,8 +61,7 @@ impl fmt::Debug for TcpStream {
             res.field("peer", peer);
         }
 
-        res.field("fd", &self.inner.inner.as_inner())
-            .finish()
+        res.field("fd", &self.inner.inner.as_inner()).finish()
     }
 }
 
@@ -69,10 +70,12 @@ fn io_err_to_addr(result: io::Result<&SocketAddr>) -> io::Result<String> {
         Ok(saddr) => Ok(saddr.to_string()),
         // need to downcast twice because io::Error::into_inner doesn't return the original
         // value if the conversion fails
-        Err(e) => if e.get_ref().and_then(|e| e.downcast_ref::<NonIpSockAddr>()).is_some() {
-            Ok(e.into_inner().unwrap().downcast::<NonIpSockAddr>().unwrap().host)
-        } else {
-            Err(e)
+        Err(e) => {
+            if e.get_ref().and_then(|e| e.downcast_ref::<NonIpSockAddr>()).is_some() {
+                Ok(e.into_inner().unwrap().downcast::<NonIpSockAddr>().unwrap().host)
+            } else {
+                Err(e)
+            }
         }
     }
 }
@@ -94,8 +97,10 @@ impl TcpStream {
 
     pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream> {
         if dur == Duration::default() {
-            return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                      "cannot set a 0 duration timeout"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "cannot set a 0 duration timeout",
+            ));
         }
         Self::connect(Ok(addr)) // FIXME: ignoring timeout
     }
@@ -103,20 +108,24 @@ impl TcpStream {
     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
         match dur {
             Some(dur) if dur == Duration::default() => {
-                return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                          "cannot set a 0 duration timeout"));
+                return Err(io::Error::new(
+                    io::ErrorKind::InvalidInput,
+                    "cannot set a 0 duration timeout",
+                ));
             }
-            _ => sgx_ineffective(())
+            _ => sgx_ineffective(()),
         }
     }
 
     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
         match dur {
             Some(dur) if dur == Duration::default() => {
-                return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                          "cannot set a 0 duration timeout"));
+                return Err(io::Error::new(
+                    io::ErrorKind::InvalidInput,
+                    "cannot set a 0 duration timeout",
+                ));
             }
-            _ => sgx_ineffective(())
+            _ => sgx_ineffective(()),
         }
     }
 
@@ -190,7 +199,9 @@ impl TcpStream {
 }
 
 impl AsInner<Socket> for TcpStream {
-    fn as_inner(&self) -> &Socket { &self.inner }
+    fn as_inner(&self) -> &Socket {
+        &self.inner
+    }
 }
 
 // `Inner` includes `peer_addr` so that a `TcpStream` maybe correctly
@@ -220,8 +231,7 @@ impl fmt::Debug for TcpListener {
             res.field("addr", addr);
         }
 
-        res.field("fd", &self.inner.inner.as_inner())
-            .finish()
+        res.field("fd", &self.inner.inner.as_inner()).finish()
     }
 }
 
@@ -273,7 +283,9 @@ impl TcpListener {
 }
 
 impl AsInner<Socket> for TcpListener {
-    fn as_inner(&self) -> &Socket { &self.inner }
+    fn as_inner(&self) -> &Socket {
+        &self.inner
+    }
 }
 
 impl IntoInner<Socket> for TcpListener {
@@ -367,23 +379,19 @@ impl UdpSocket {
         match self.0 {}
     }
 
-    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
@@ -428,7 +436,7 @@ impl fmt::Debug for UdpSocket {
 
 #[derive(Debug)]
 pub struct NonIpSockAddr {
-    host: String
+    host: String,
 }
 
 impl error::Error for NonIpSockAddr {
@@ -511,8 +519,7 @@ pub mod netc {
     }
 
     #[derive(Copy, Clone)]
-    pub struct sockaddr {
-    }
+    pub struct sockaddr {}
 
     pub type socklen_t = usize;
 }
diff --git a/src/libstd/sys/sgx/os.rs b/src/libstd/sys/sgx/os.rs
index 8b12c49edba..2c5b3134219 100644
--- a/src/libstd/sys/sgx/os.rs
+++ b/src/libstd/sys/sgx/os.rs
@@ -1,17 +1,17 @@
 use fortanix_sgx_abi::{Error, RESULT_SUCCESS};
 
+use crate::collections::HashMap;
 use crate::error::Error as StdError;
-use crate::ffi::{OsString, OsStr};
+use crate::ffi::{OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::path::{self, PathBuf};
 use crate::str;
-use crate::sys::{unsupported, Void, sgx_ineffective, decode_error_kind};
-use crate::collections::HashMap;
-use crate::vec;
-use crate::sync::Mutex;
 use crate::sync::atomic::{AtomicUsize, Ordering};
+use crate::sync::Mutex;
 use crate::sync::Once;
+use crate::sys::{decode_error_kind, sgx_ineffective, unsupported, Void};
+use crate::vec;
 
 pub fn errno() -> i32 {
     RESULT_SUCCESS
@@ -52,7 +52,9 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     Err(JoinPathsError)
 }
@@ -89,26 +91,21 @@ fn create_env_store() -> &'static EnvStore {
     ENV_INIT.call_once(|| {
         ENV.store(Box::into_raw(Box::new(EnvStore::default())) as _, Ordering::Relaxed)
     });
-    unsafe {
-        &*(ENV.load(Ordering::Relaxed) as *const EnvStore)
-    }
+    unsafe { &*(ENV.load(Ordering::Relaxed) as *const EnvStore) }
 }
 
 pub type Env = vec::IntoIter<(OsString, OsString)>;
 
 pub fn env() -> Env {
     let clone_to_vec = |map: &HashMap<OsString, OsString>| -> Vec<_> {
-        map.iter().map(|(k, v)| (k.clone(), v.clone()) ).collect()
+        map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
     };
 
-    get_env_store()
-        .map(|env| clone_to_vec(&env.lock().unwrap()) )
-        .unwrap_or_default()
-        .into_iter()
+    get_env_store().map(|env| clone_to_vec(&env.lock().unwrap())).unwrap_or_default().into_iter()
 }
 
 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
-    Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned() ))
+    Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned()))
 }
 
 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
diff --git a/src/libstd/sys/sgx/path.rs b/src/libstd/sys/sgx/path.rs
index b5fd7e3ae6d..06c9df3ff54 100644
--- a/src/libstd/sys/sgx/path.rs
+++ b/src/libstd/sys/sgx/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/sgx/process.rs b/src/libstd/sys/sgx/process.rs
index edf933d10e0..4702e5c5492 100644
--- a/src/libstd/sys/sgx/process.rs
+++ b/src/libstd/sys/sgx/process.rs
@@ -32,32 +32,28 @@ pub enum Stdio {
 
 impl Command {
     pub fn new(_program: &OsStr) -> Command {
-        Command {
-            env: Default::default()
-        }
+        Command { env: Default::default() }
     }
 
-    pub fn arg(&mut self, _arg: &OsStr) {
-    }
+    pub fn arg(&mut self, _arg: &OsStr) {}
 
     pub fn env_mut(&mut self) -> &mut CommandEnv {
         &mut self.env
     }
 
-    pub fn cwd(&mut self, _dir: &OsStr) {
-    }
+    pub fn cwd(&mut self, _dir: &OsStr) {}
 
-    pub fn stdin(&mut self, _stdin: Stdio) {
-    }
+    pub fn stdin(&mut self, _stdin: Stdio) {}
 
-    pub fn stdout(&mut self, _stdout: Stdio) {
-    }
+    pub fn stdout(&mut self, _stdout: Stdio) {}
 
-    pub fn stderr(&mut self, _stderr: Stdio) {
-    }
+    pub fn stderr(&mut self, _stderr: Stdio) {}
 
-    pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool)
-        -> io::Result<(Process, StdioPipes)> {
+    pub fn spawn(
+        &mut self,
+        _default: Stdio,
+        _needs_stdin: bool,
+    ) -> io::Result<(Process, StdioPipes)> {
         unsupported()
     }
 }
@@ -106,8 +102,7 @@ impl PartialEq for ExitStatus {
     }
 }
 
-impl Eq for ExitStatus {
-}
+impl Eq for ExitStatus {}
 
 impl fmt::Debug for ExitStatus {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/src/libstd/sys/sgx/stack_overflow.rs b/src/libstd/sys/sgx/stack_overflow.rs
index e63fa2bed65..a2d13d11849 100644
--- a/src/libstd/sys/sgx/stack_overflow.rs
+++ b/src/libstd/sys/sgx/stack_overflow.rs
@@ -7,8 +7,6 @@ impl Handler {
 }
 
 #[cfg_attr(test, allow(dead_code))]
-pub unsafe fn init() {
-}
+pub unsafe fn init() {}
 
-pub unsafe fn cleanup() {
-}
+pub unsafe fn cleanup() {}
diff --git a/src/libstd/sys/sgx/stdio.rs b/src/libstd/sys/sgx/stdio.rs
index a575401f5f6..716c174bd53 100644
--- a/src/libstd/sys/sgx/stdio.rs
+++ b/src/libstd/sys/sgx/stdio.rs
@@ -1,11 +1,11 @@
 use fortanix_sgx_abi as abi;
 
 use crate::io;
-use crate::sys::fd::FileDesc;
 #[cfg(not(test))]
 use crate::slice;
 #[cfg(not(test))]
 use crate::str;
+use crate::sys::fd::FileDesc;
 
 pub struct Stdin(());
 pub struct Stdout(());
@@ -19,7 +19,9 @@ fn with_std_fd<F: FnOnce(&FileDesc) -> R, R>(fd: abi::Fd, f: F) -> R {
 }
 
 impl Stdin {
-    pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
+    pub fn new() -> io::Result<Stdin> {
+        Ok(Stdin(()))
+    }
 }
 
 impl io::Read for Stdin {
@@ -29,7 +31,9 @@ impl io::Read for Stdin {
 }
 
 impl Stdout {
-    pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
+    pub fn new() -> io::Result<Stdout> {
+        Ok(Stdout(()))
+    }
 }
 
 impl io::Write for Stdout {
@@ -43,7 +47,9 @@ impl io::Write for Stdout {
 }
 
 impl Stderr {
-    pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
+    pub fn new() -> io::Result<Stderr> {
+        Ok(Stderr(()))
+    }
 }
 
 impl io::Write for Stderr {
diff --git a/src/libstd/sys/sgx/thread.rs b/src/libstd/sys/sgx/thread.rs
index b9f42d4ad1c..9b515eb82de 100644
--- a/src/libstd/sys/sgx/thread.rs
+++ b/src/libstd/sys/sgx/thread.rs
@@ -10,8 +10,8 @@ pub struct Thread(task_queue::JoinHandle);
 pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
 
 mod task_queue {
-    use crate::sync::{Mutex, MutexGuard, Once};
     use crate::sync::mpsc;
+    use crate::sync::{Mutex, MutexGuard, Once};
 
     pub type JoinHandle = mpsc::Receiver<()>;
 
@@ -41,7 +41,7 @@ mod task_queue {
 
     pub(super) fn lock() -> MutexGuard<'static, Vec<Task>> {
         unsafe {
-            TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default()) );
+            TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default()));
             TASK_QUEUE.as_ref().unwrap().lock().unwrap()
         }
     }
@@ -49,9 +49,7 @@ mod task_queue {
 
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
-    pub unsafe fn new(_stack: usize, p: Box<dyn FnOnce()>)
-        -> io::Result<Thread>
-    {
+    pub unsafe fn new(_stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         let mut queue_lock = task_queue::lock();
         usercalls::launch_thread()?;
         let (task, handle) = task_queue::Task::new(p);
@@ -86,6 +84,10 @@ impl Thread {
 
 pub mod guard {
     pub type Guard = !;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
 }
diff --git a/src/libstd/sys/sgx/thread_local.rs b/src/libstd/sys/sgx/thread_local.rs
index e0d0fe76957..b21784475f0 100644
--- a/src/libstd/sys/sgx/thread_local.rs
+++ b/src/libstd/sys/sgx/thread_local.rs
@@ -1,9 +1,9 @@
-use super::abi::tls::{Tls, Key as AbiKey};
+use super::abi::tls::{Key as AbiKey, Tls};
 
 pub type Key = usize;
 
 #[inline]
-pub unsafe fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+pub unsafe fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
     Tls::create(dtor).as_usize()
 }
 
diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs
index 4659f7ba71f..e2f6e6dba69 100644
--- a/src/libstd/sys/sgx/time.rs
+++ b/src/libstd/sys/sgx/time.rs
@@ -1,5 +1,5 @@
-use crate::time::Duration;
 use super::abi::usercalls;
+use crate::time::Duration;
 
 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
 pub struct Instant(Duration);
@@ -40,8 +40,7 @@ impl SystemTime {
         SystemTime(usercalls::insecure_time())
     }
 
-    pub fn sub_time(&self, other: &SystemTime)
-                    -> Result<Duration, Duration> {
+    pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
         self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
     }
 
diff --git a/src/libstd/sys/unix/alloc.rs b/src/libstd/sys/unix/alloc.rs
index cf4900b4894..77417e41331 100644
--- a/src/libstd/sys/unix/alloc.rs
+++ b/src/libstd/sys/unix/alloc.rs
@@ -1,6 +1,6 @@
-use crate::ptr;
-use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
 use crate::alloc::{GlobalAlloc, Layout, System};
+use crate::ptr;
+use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN};
 
 #[stable(feature = "alloc_system_type", since = "1.28.0")]
 unsafe impl GlobalAlloc for System {
@@ -16,7 +16,7 @@ unsafe impl GlobalAlloc for System {
             #[cfg(target_os = "macos")]
             {
                 if layout.align() > (1 << 31) {
-                    return ptr::null_mut()
+                    return ptr::null_mut();
                 }
             }
             aligned_malloc(&layout)
@@ -52,9 +52,7 @@ unsafe impl GlobalAlloc for System {
     }
 }
 
-#[cfg(any(target_os = "android",
-          target_os = "redox",
-          target_os = "solaris"))]
+#[cfg(any(target_os = "android", target_os = "redox", target_os = "solaris"))]
 #[inline]
 unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
     // On android we currently target API level 9 which unfortunately
@@ -77,9 +75,7 @@ unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
     libc::memalign(layout.align(), layout.size()) as *mut u8
 }
 
-#[cfg(not(any(target_os = "android",
-              target_os = "redox",
-              target_os = "solaris")))]
+#[cfg(not(any(target_os = "android", target_os = "redox", target_os = "solaris")))]
 #[inline]
 unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
     let mut out = ptr::null_mut();
@@ -87,9 +83,5 @@ unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
     // Since these are all powers of 2, we can just use max.
     let align = layout.align().max(crate::mem::size_of::<usize>());
     let ret = libc::posix_memalign(&mut out, align, layout.size());
-    if ret != 0 {
-        ptr::null_mut()
-    } else {
-        out as *mut u8
-    }
+    if ret != 0 { ptr::null_mut() } else { out as *mut u8 }
 }
diff --git a/src/libstd/sys/unix/android.rs b/src/libstd/sys/unix/android.rs
index 6774160bb25..c5e9d66e85e 100644
--- a/src/libstd/sys/unix/android.rs
+++ b/src/libstd/sys/unix/android.rs
@@ -21,8 +21,8 @@
 use libc::{c_int, c_void, sighandler_t, size_t, ssize_t};
 use libc::{ftruncate, pread, pwrite};
 
-use crate::io;
 use super::{cvt, cvt_r};
+use crate::io;
 
 // The `log2` and `log2f` functions apparently appeared in android-18, or at
 // least you can see they're not present in the android-17 header [1] and they
@@ -96,8 +96,7 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> {
             Some(f) => cvt_r(|| f(fd, size as i64)).map(|_| ()),
             None => {
                 if size > i32::max_value() as u64 {
-                    Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                       "cannot truncate >2GB"))
+                    Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot truncate >2GB"))
                 } else {
                     cvt_r(|| ftruncate(fd, size as i32)).map(|_| ())
                 }
@@ -108,53 +107,61 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> {
 
 #[cfg(target_pointer_width = "64")]
 pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> {
-    unsafe {
-        cvt_r(|| ftruncate(fd, size as i64)).map(|_| ())
-    }
+    unsafe { cvt_r(|| ftruncate(fd, size as i64)).map(|_| ()) }
 }
 
 #[cfg(target_pointer_width = "32")]
-pub unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: size_t, offset: i64)
-    -> io::Result<ssize_t>
-{
+pub unsafe fn cvt_pread64(
+    fd: c_int,
+    buf: *mut c_void,
+    count: size_t,
+    offset: i64,
+) -> io::Result<ssize_t> {
     use crate::convert::TryInto;
     weak!(fn pread64(c_int, *mut c_void, size_t, i64) -> ssize_t);
     pread64.get().map(|f| cvt(f(fd, buf, count, offset))).unwrap_or_else(|| {
         if let Ok(o) = offset.try_into() {
             cvt(pread(fd, buf, count, o))
         } else {
-            Err(io::Error::new(io::ErrorKind::InvalidInput,
-                               "cannot pread >2GB"))
+            Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pread >2GB"))
         }
     })
 }
 
 #[cfg(target_pointer_width = "32")]
-pub unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: i64)
-    -> io::Result<ssize_t>
-{
+pub unsafe fn cvt_pwrite64(
+    fd: c_int,
+    buf: *const c_void,
+    count: size_t,
+    offset: i64,
+) -> io::Result<ssize_t> {
     use crate::convert::TryInto;
     weak!(fn pwrite64(c_int, *const c_void, size_t, i64) -> ssize_t);
     pwrite64.get().map(|f| cvt(f(fd, buf, count, offset))).unwrap_or_else(|| {
         if let Ok(o) = offset.try_into() {
             cvt(pwrite(fd, buf, count, o))
         } else {
-            Err(io::Error::new(io::ErrorKind::InvalidInput,
-                               "cannot pwrite >2GB"))
+            Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pwrite >2GB"))
         }
     })
 }
 
 #[cfg(target_pointer_width = "64")]
-pub unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: size_t, offset: i64)
-    -> io::Result<ssize_t>
-{
+pub unsafe fn cvt_pread64(
+    fd: c_int,
+    buf: *mut c_void,
+    count: size_t,
+    offset: i64,
+) -> io::Result<ssize_t> {
     cvt(pread(fd, buf, count, offset))
 }
 
 #[cfg(target_pointer_width = "64")]
-pub unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: i64)
-    -> io::Result<ssize_t>
-{
+pub unsafe fn cvt_pwrite64(
+    fd: c_int,
+    buf: *const c_void,
+    count: size_t,
+    offset: i64,
+) -> io::Result<ssize_t> {
     cvt(pwrite(fd, buf, count, offset))
 }
diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs
index 82ef35ea7b5..2ed1585395e 100644
--- a/src/libstd/sys/unix/args.rs
+++ b/src/libstd/sys/unix/args.rs
@@ -72,12 +72,46 @@ mod imp {
     // acquire this mutex reentrantly!
     static LOCK: Mutex = Mutex::new();
 
-    pub unsafe fn init(argc: isize, argv: *const *const u8) {
+    unsafe fn really_init(argc: isize, argv: *const *const u8) {
         let _guard = LOCK.lock();
         ARGC = argc;
         ARGV = argv;
     }
 
+    #[inline(always)]
+    pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
+        // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize
+        // `ARGC` and `ARGV`. But in Miri that does not actually happen so we
+        // still initialize here.
+        #[cfg(any(
+            miri,
+            not(all(target_os = "linux", target_env = "gnu"))
+        ))]
+        really_init(_argc, _argv);
+    }
+
+    /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension.
+    /// This allows `std::env::args` to work even in a `cdylib`, as it does on macOS and Windows.
+    #[cfg(all(target_os = "linux", target_env = "gnu"))]
+    #[used]
+    #[link_section = ".init_array.00099"]
+    static ARGV_INIT_ARRAY: extern "C" fn(
+        crate::os::raw::c_int,
+        *const *const u8,
+        *const *const u8,
+    ) = {
+        extern "C" fn init_wrapper(
+            argc: crate::os::raw::c_int,
+            argv: *const *const u8,
+            _envp: *const *const u8,
+        ) {
+            unsafe {
+                really_init(argc as isize, argv);
+            }
+        }
+        init_wrapper
+    };
+
     pub unsafe fn cleanup() {
         let _guard = LOCK.lock();
         ARGC = 0;
diff --git a/src/libstd/sys/unix/cmath.rs b/src/libstd/sys/unix/cmath.rs
index f6bb58934fc..2916ebe4440 100644
--- a/src/libstd/sys/unix/cmath.rs
+++ b/src/libstd/sys/unix/cmath.rs
@@ -1,9 +1,9 @@
 #![cfg(not(test))]
 
-use libc::{c_float, c_double};
+use libc::{c_double, c_float};
 
 #[link_name = "m"]
-extern {
+extern "C" {
     pub fn acos(n: c_double) -> c_double;
     pub fn acosf(n: c_float) -> c_float;
     pub fn asin(n: c_double) -> c_double;
diff --git a/src/libstd/sys/unix/ext/fs.rs b/src/libstd/sys/unix/ext/fs.rs
index 0c52dc5b81b..732cd677a18 100644
--- a/src/libstd/sys/unix/ext/fs.rs
+++ b/src/libstd/sys/unix/ext/fs.rs
@@ -2,12 +2,12 @@
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-use crate::fs::{self, Permissions, OpenOptions};
+use crate::fs::{self, OpenOptions, Permissions};
 use crate::io;
 use crate::path::Path;
 use crate::sys;
-use crate::sys_common::{FromInner, AsInner, AsInnerMut};
 use crate::sys::platform::fs::MetadataExt as UnixMetadataExt;
+use crate::sys_common::{AsInner, AsInnerMut, FromInner};
 
 /// Unix-specific extensions to [`File`].
 ///
@@ -112,8 +112,7 @@ pub trait FileExt {
             }
         }
         if !buf.is_empty() {
-            Err(io::Error::new(io::ErrorKind::UnexpectedEof,
-                               "failed to fill whole buffer"))
+            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
         } else {
             Ok(())
         }
@@ -195,8 +194,12 @@ pub trait FileExt {
     fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
         while !buf.is_empty() {
             match self.write_at(buf, offset) {
-                Ok(0) => return Err(io::Error::new(io::ErrorKind::WriteZero,
-                                                   "failed to write whole buffer")),
+                Ok(0) => {
+                    return Err(io::Error::new(
+                        io::ErrorKind::WriteZero,
+                        "failed to write whole buffer",
+                    ));
+                }
                 Ok(n) => {
                     buf = &buf[n..];
                     offset += n as u64
@@ -356,11 +359,13 @@ pub trait OpenOptionsExt {
 #[stable(feature = "fs_ext", since = "1.1.0")]
 impl OpenOptionsExt for OpenOptions {
     fn mode(&mut self, mode: u32) -> &mut OpenOptions {
-        self.as_inner_mut().mode(mode); self
+        self.as_inner_mut().mode(mode);
+        self
     }
 
     fn custom_flags(&mut self, flags: i32) -> &mut OpenOptions {
-        self.as_inner_mut().custom_flags(flags); self
+        self.as_inner_mut().custom_flags(flags);
+        self
     }
 }
 
@@ -657,22 +662,54 @@ pub trait MetadataExt {
 
 #[stable(feature = "metadata_ext", since = "1.1.0")]
 impl MetadataExt for fs::Metadata {
-    fn dev(&self) -> u64 { self.st_dev() }
-    fn ino(&self) -> u64 { self.st_ino() }
-    fn mode(&self) -> u32 { self.st_mode() }
-    fn nlink(&self) -> u64 { self.st_nlink() }
-    fn uid(&self) -> u32 { self.st_uid() }
-    fn gid(&self) -> u32 { self.st_gid() }
-    fn rdev(&self) -> u64 { self.st_rdev() }
-    fn size(&self) -> u64 { self.st_size() }
-    fn atime(&self) -> i64 { self.st_atime() }
-    fn atime_nsec(&self) -> i64 { self.st_atime_nsec() }
-    fn mtime(&self) -> i64 { self.st_mtime() }
-    fn mtime_nsec(&self) -> i64 { self.st_mtime_nsec() }
-    fn ctime(&self) -> i64 { self.st_ctime() }
-    fn ctime_nsec(&self) -> i64 { self.st_ctime_nsec() }
-    fn blksize(&self) -> u64 { self.st_blksize() }
-    fn blocks(&self) -> u64 { self.st_blocks() }
+    fn dev(&self) -> u64 {
+        self.st_dev()
+    }
+    fn ino(&self) -> u64 {
+        self.st_ino()
+    }
+    fn mode(&self) -> u32 {
+        self.st_mode()
+    }
+    fn nlink(&self) -> u64 {
+        self.st_nlink()
+    }
+    fn uid(&self) -> u32 {
+        self.st_uid()
+    }
+    fn gid(&self) -> u32 {
+        self.st_gid()
+    }
+    fn rdev(&self) -> u64 {
+        self.st_rdev()
+    }
+    fn size(&self) -> u64 {
+        self.st_size()
+    }
+    fn atime(&self) -> i64 {
+        self.st_atime()
+    }
+    fn atime_nsec(&self) -> i64 {
+        self.st_atime_nsec()
+    }
+    fn mtime(&self) -> i64 {
+        self.st_mtime()
+    }
+    fn mtime_nsec(&self) -> i64 {
+        self.st_mtime_nsec()
+    }
+    fn ctime(&self) -> i64 {
+        self.st_ctime()
+    }
+    fn ctime_nsec(&self) -> i64 {
+        self.st_ctime_nsec()
+    }
+    fn blksize(&self) -> u64 {
+        self.st_blksize()
+    }
+    fn blocks(&self) -> u64 {
+        self.st_blocks()
+    }
 }
 
 /// Unix-specific extensions for [`FileType`].
@@ -759,10 +796,18 @@ pub trait FileTypeExt {
 
 #[stable(feature = "file_type_ext", since = "1.5.0")]
 impl FileTypeExt for fs::FileType {
-    fn is_block_device(&self) -> bool { self.as_inner().is(libc::S_IFBLK) }
-    fn is_char_device(&self) -> bool { self.as_inner().is(libc::S_IFCHR) }
-    fn is_fifo(&self) -> bool { self.as_inner().is(libc::S_IFIFO) }
-    fn is_socket(&self) -> bool { self.as_inner().is(libc::S_IFSOCK) }
+    fn is_block_device(&self) -> bool {
+        self.as_inner().is(libc::S_IFBLK)
+    }
+    fn is_char_device(&self) -> bool {
+        self.as_inner().is(libc::S_IFCHR)
+    }
+    fn is_fifo(&self) -> bool {
+        self.as_inner().is(libc::S_IFIFO)
+    }
+    fn is_socket(&self) -> bool {
+        self.as_inner().is(libc::S_IFSOCK)
+    }
 }
 
 /// Unix-specific extension methods for [`fs::DirEntry`].
@@ -794,7 +839,9 @@ pub trait DirEntryExt {
 
 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
 impl DirEntryExt for fs::DirEntry {
-    fn ino(&self) -> u64 { self.as_inner().ino() }
+    fn ino(&self) -> u64 {
+        self.as_inner().ino()
+    }
 }
 
 /// Creates a new symbolic link on the filesystem.
@@ -821,8 +868,7 @@ impl DirEntryExt for fs::DirEntry {
 /// }
 /// ```
 #[stable(feature = "symlink", since = "1.1.0")]
-pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
-{
+pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
     sys::fs::symlink(src.as_ref(), dst.as_ref())
 }
 
diff --git a/src/libstd/sys/unix/ext/io.rs b/src/libstd/sys/unix/ext/io.rs
index 6bcc59495e3..5077e2e28d1 100644
--- a/src/libstd/sys/unix/ext/io.rs
+++ b/src/libstd/sys/unix/ext/io.rs
@@ -3,9 +3,9 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use crate::fs;
+use crate::io;
 use crate::os::raw;
 use crate::sys;
-use crate::io;
 use crate::sys_common::{AsInner, FromInner, IntoInner};
 
 /// Raw file descriptors.
@@ -83,30 +83,42 @@ impl IntoRawFd for fs::File {
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stdin {
-    fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDIN_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stdout {
-    fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDOUT_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stderr {
-    fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDERR_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StdinLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDIN_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StdoutLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDOUT_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StderrLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDERR_FILENO
+    }
 }
diff --git a/src/libstd/sys/unix/ext/mod.rs b/src/libstd/sys/unix/ext/mod.rs
index ccbac1a3e4b..78a3fd05c73 100644
--- a/src/libstd/sys/unix/ext/mod.rs
+++ b/src/libstd/sys/unix/ext/mod.rs
@@ -15,11 +15,13 @@
 //! use std::fs::File;
 //! use std::os::unix::prelude::*;
 //!
-//! fn main() {
-//!     let f = File::create("foo.txt").unwrap();
+//! fn main() -> std::io::Result<()> {
+//!     let f = File::create("foo.txt")?;
 //!     let fd = f.as_raw_fd();
 //!
 //!     // use fd with native unix bindings
+//!
+//!     Ok(())
 //! }
 //! ```
 
diff --git a/src/libstd/sys/unix/ext/net.rs b/src/libstd/sys/unix/ext/net.rs
index 42edd5dbbea..5177cce628c 100644
--- a/src/libstd/sys/unix/ext/net.rs
+++ b/src/libstd/sys/unix/ext/net.rs
@@ -142,9 +142,12 @@ impl SocketAddr {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let socket = UnixListener::bind("/tmp/sock").unwrap();
-    /// let addr = socket.local_addr().expect("Couldn't get local address");
-    /// assert_eq!(addr.is_unnamed(), false);
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixListener::bind("/tmp/sock")?;
+    ///     let addr = socket.local_addr().expect("Couldn't get local address");
+    ///     assert_eq!(addr.is_unnamed(), false);
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// An unnamed address:
@@ -152,9 +155,12 @@ impl SocketAddr {
     /// ```
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let socket = UnixDatagram::unbound().unwrap();
-    /// let addr = socket.local_addr().expect("Couldn't get local address");
-    /// assert_eq!(addr.is_unnamed(), true);
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixDatagram::unbound()?;
+    ///     let addr = socket.local_addr().expect("Couldn't get local address");
+    ///     assert_eq!(addr.is_unnamed(), true);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn is_unnamed(&self) -> bool {
@@ -175,9 +181,12 @@ impl SocketAddr {
     /// use std::os::unix::net::UnixListener;
     /// use std::path::Path;
     ///
-    /// let socket = UnixListener::bind("/tmp/sock").unwrap();
-    /// let addr = socket.local_addr().expect("Couldn't get local address");
-    /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixListener::bind("/tmp/sock")?;
+    ///     let addr = socket.local_addr().expect("Couldn't get local address");
+    ///     assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// Without a pathname:
@@ -185,9 +194,12 @@ impl SocketAddr {
     /// ```
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let socket = UnixDatagram::unbound().unwrap();
-    /// let addr = socket.local_addr().expect("Couldn't get local address");
-    /// assert_eq!(addr.as_pathname(), None);
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixDatagram::unbound()?;
+    ///     let addr = socket.local_addr().expect("Couldn't get local address");
+    ///     assert_eq!(addr.as_pathname(), None);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn as_pathname(&self) -> Option<&Path> {
@@ -247,11 +259,14 @@ impl<'a> fmt::Display for AsciiEscaped<'a> {
 /// use std::os::unix::net::UnixStream;
 /// use std::io::prelude::*;
 ///
-/// let mut stream = UnixStream::connect("/path/to/my/socket").unwrap();
-/// stream.write_all(b"hello world").unwrap();
-/// let mut response = String::new();
-/// stream.read_to_string(&mut response).unwrap();
-/// println!("{}", response);
+/// fn main() -> std::io::Result<()> {
+///     let mut stream = UnixStream::connect("/path/to/my/socket")?;
+///     stream.write_all(b"hello world")?;
+///     let mut response = String::new();
+///     stream.read_to_string(&mut response)?;
+///     println!("{}", response);
+///     Ok(())
+/// }
 /// ```
 #[stable(feature = "unix_socket", since = "1.10.0")]
 pub struct UnixStream(Socket);
@@ -336,8 +351,11 @@ impl UnixStream {
     /// ```no_run
     /// use std::os::unix::net::UnixStream;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// let sock_copy = socket.try_clone().expect("Couldn't clone socket");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     let sock_copy = socket.try_clone().expect("Couldn't clone socket");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn try_clone(&self) -> io::Result<UnixStream> {
@@ -351,8 +369,11 @@ impl UnixStream {
     /// ```no_run
     /// use std::os::unix::net::UnixStream;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// let addr = socket.local_addr().expect("Couldn't get local address");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     let addr = socket.local_addr().expect("Couldn't get local address");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn local_addr(&self) -> io::Result<SocketAddr> {
@@ -366,8 +387,11 @@ impl UnixStream {
     /// ```no_run
     /// use std::os::unix::net::UnixStream;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// let addr = socket.peer_addr().expect("Couldn't get peer address");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     let addr = socket.peer_addr().expect("Couldn't get peer address");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
@@ -391,8 +415,11 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
@@ -403,10 +430,13 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
-    /// let err = result.unwrap_err();
-    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
+    ///     let err = result.unwrap_err();
+    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
@@ -430,8 +460,12 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.set_write_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("Couldn't set write timeout");
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
@@ -442,10 +476,13 @@ impl UnixStream {
     /// use std::net::UdpSocket;
     /// use std::time::Duration;
     ///
-    /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
-    /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
-    /// let err = result.unwrap_err();
-    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UdpSocket::bind("127.0.0.1:34254")?;
+    ///     let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
+    ///     let err = result.unwrap_err();
+    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
@@ -460,9 +497,12 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
-    /// assert_eq!(socket.read_timeout().unwrap(), Some(Duration::new(1, 0)));
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
+    ///     assert_eq!(socket.read_timeout()?, Some(Duration::new(1, 0)));
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
@@ -477,9 +517,13 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout");
-    /// assert_eq!(socket.write_timeout().unwrap(), Some(Duration::new(1, 0)));
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.set_write_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("Couldn't set write timeout");
+    ///     assert_eq!(socket.write_timeout()?, Some(Duration::new(1, 0)));
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
@@ -493,8 +537,11 @@ impl UnixStream {
     /// ```no_run
     /// use std::os::unix::net::UnixStream;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.set_nonblocking(true).expect("Couldn't set nonblocking");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
@@ -508,9 +555,12 @@ impl UnixStream {
     /// ```no_run
     /// use std::os::unix::net::UnixStream;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// if let Ok(Some(err)) = socket.take_error() {
-    ///     println!("Got error: {:?}", err);
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     if let Ok(Some(err)) = socket.take_error() {
+    ///         println!("Got error: {:?}", err);
+    ///     }
+    ///     Ok(())
     /// }
     /// ```
     ///
@@ -535,8 +585,11 @@ impl UnixStream {
     /// use std::os::unix::net::UnixStream;
     /// use std::net::Shutdown;
     ///
-    /// let socket = UnixStream::connect("/tmp/sock").unwrap();
-    /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixStream::connect("/tmp/sock")?;
+    ///     socket.shutdown(Shutdown::Both).expect("shutdown function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
@@ -697,20 +750,23 @@ impl IntoRawFd for net::UdpSocket {
 ///     // ...
 /// }
 ///
-/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
+/// fn main() -> std::io::Result<()> {
+///     let listener = UnixListener::bind("/path/to/the/socket")?;
 ///
-/// // accept connections and process them, spawning a new thread for each one
-/// for stream in listener.incoming() {
-///     match stream {
-///         Ok(stream) => {
-///             /* connection succeeded */
-///             thread::spawn(|| handle_client(stream));
-///         }
-///         Err(err) => {
-///             /* connection failed */
-///             break;
+///     // accept connections and process them, spawning a new thread for each one
+///     for stream in listener.incoming() {
+///         match stream {
+///             Ok(stream) => {
+///                 /* connection succeeded */
+///                 thread::spawn(|| handle_client(stream));
+///             }
+///             Err(err) => {
+///                 /* connection failed */
+///                 break;
+///             }
 ///         }
 ///     }
+///     Ok(())
 /// }
 /// ```
 #[stable(feature = "unix_socket", since = "1.10.0")]
@@ -773,11 +829,14 @@ impl UnixListener {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
     ///
-    /// match listener.accept() {
-    ///     Ok((socket, addr)) => println!("Got a client: {:?}", addr),
-    ///     Err(e) => println!("accept function failed: {:?}", e),
+    ///     match listener.accept() {
+    ///         Ok((socket, addr)) => println!("Got a client: {:?}", addr),
+    ///         Err(e) => println!("accept function failed: {:?}", e),
+    ///     }
+    ///     Ok(())
     /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
@@ -800,9 +859,11 @@ impl UnixListener {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
-    ///
-    /// let listener_copy = listener.try_clone().expect("try_clone failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
+    ///     let listener_copy = listener.try_clone().expect("try_clone failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn try_clone(&self) -> io::Result<UnixListener> {
@@ -816,9 +877,11 @@ impl UnixListener {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
-    ///
-    /// let addr = listener.local_addr().expect("Couldn't get local address");
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
+    ///     let addr = listener.local_addr().expect("Couldn't get local address");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn local_addr(&self) -> io::Result<SocketAddr> {
@@ -832,9 +895,11 @@ impl UnixListener {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
-    ///
-    /// listener.set_nonblocking(true).expect("Couldn't set non blocking");
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
+    ///     listener.set_nonblocking(true).expect("Couldn't set non blocking");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
@@ -848,10 +913,13 @@ impl UnixListener {
     /// ```no_run
     /// use std::os::unix::net::UnixListener;
     ///
-    /// let listener = UnixListener::bind("/tmp/sock").unwrap();
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/tmp/sock")?;
     ///
-    /// if let Ok(Some(err)) = listener.take_error() {
-    ///     println!("Got error: {:?}", err);
+    ///     if let Ok(Some(err)) = listener.take_error() {
+    ///         println!("Got error: {:?}", err);
+    ///     }
+    ///     Ok(())
     /// }
     /// ```
     ///
@@ -880,17 +948,20 @@ impl UnixListener {
     ///     // ...
     /// }
     ///
-    /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
-    ///
-    /// for stream in listener.incoming() {
-    ///     match stream {
-    ///         Ok(stream) => {
-    ///             thread::spawn(|| handle_client(stream));
-    ///         }
-    ///         Err(err) => {
-    ///             break;
+    /// fn main() -> std::io::Result<()> {
+    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
+    ///
+    ///     for stream in listener.incoming() {
+    ///         match stream {
+    ///             Ok(stream) => {
+    ///                 thread::spawn(|| handle_client(stream));
+    ///             }
+    ///             Err(err) => {
+    ///                 break;
+    ///             }
     ///         }
     ///     }
+    ///     Ok(())
     /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
@@ -947,17 +1018,20 @@ impl<'a> IntoIterator for &'a UnixListener {
 ///     // ...
 /// }
 ///
-/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
+/// fn main() -> std::io::Result<()> {
+///     let listener = UnixListener::bind("/path/to/the/socket")?;
 ///
-/// for stream in listener.incoming() {
-///     match stream {
-///         Ok(stream) => {
-///             thread::spawn(|| handle_client(stream));
-///         }
-///         Err(err) => {
-///             break;
+///     for stream in listener.incoming() {
+///         match stream {
+///             Ok(stream) => {
+///                 thread::spawn(|| handle_client(stream));
+///             }
+///             Err(err) => {
+///                 break;
+///             }
 ///         }
 ///     }
+///     Ok(())
 /// }
 /// ```
 #[derive(Debug)]
@@ -986,11 +1060,14 @@ impl<'a> Iterator for Incoming<'a> {
 /// ```no_run
 /// use std::os::unix::net::UnixDatagram;
 ///
-/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
-/// socket.send_to(b"hello world", "/path/to/other/socket").unwrap();
-/// let mut buf = [0; 100];
-/// let (count, address) = socket.recv_from(&mut buf).unwrap();
-/// println!("socket {:?} sent {:?}", address, &buf[..count]);
+/// fn main() -> std::io::Result<()> {
+///     let socket = UnixDatagram::bind("/path/to/my/socket")?;
+///     socket.send_to(b"hello world", "/path/to/other/socket")?;
+///     let mut buf = [0; 100];
+///     let (count, address) = socket.recv_from(&mut buf)?;
+///     println!("socket {:?} sent {:?}", address, &buf[..count]);
+///     Ok(())
+/// }
 /// ```
 #[stable(feature = "unix_socket", since = "1.10.0")]
 pub struct UnixDatagram(Socket);
@@ -1099,14 +1176,17 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// match sock.connect("/path/to/the/socket") {
-    ///     Ok(sock) => sock,
-    ///     Err(e) => {
-    ///         println!("Couldn't connect: {:?}", e);
-    ///         return
-    ///     }
-    /// };
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     match sock.connect("/path/to/the/socket") {
+    ///         Ok(sock) => sock,
+    ///         Err(e) => {
+    ///             println!("Couldn't connect: {:?}", e);
+    ///             return Err(e)
+    ///         }
+    ///     };
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
@@ -1133,9 +1213,11 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
-    ///
-    /// let sock_copy = sock.try_clone().expect("try_clone failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
+    ///     let sock_copy = sock.try_clone().expect("try_clone failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn try_clone(&self) -> io::Result<UnixDatagram> {
@@ -1149,9 +1231,11 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
-    ///
-    /// let addr = sock.local_addr().expect("Couldn't get local address");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
+    ///     let addr = sock.local_addr().expect("Couldn't get local address");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn local_addr(&self) -> io::Result<SocketAddr> {
@@ -1169,10 +1253,13 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.connect("/path/to/the/socket").unwrap();
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.connect("/path/to/the/socket")?;
     ///
-    /// let addr = sock.peer_addr().expect("Couldn't get peer address");
+    ///     let addr = sock.peer_addr().expect("Couldn't get peer address");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
@@ -1189,11 +1276,12 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// let mut buf = vec![0; 10];
-    /// match sock.recv_from(buf.as_mut_slice()) {
-    ///     Ok((size, sender)) => println!("received {} bytes from {:?}", size, sender),
-    ///     Err(e) => println!("recv_from function failed: {:?}", e),
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     let mut buf = vec![0; 10];
+    ///     let (size, sender) = sock.recv_from(buf.as_mut_slice())?;
+    ///     println!("received {} bytes from {:?}", size, sender);
+    ///     Ok(())
     /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
@@ -1229,9 +1317,12 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
-    /// let mut buf = vec![0; 10];
-    /// sock.recv(buf.as_mut_slice()).expect("recv function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::bind("/path/to/the/socket")?;
+    ///     let mut buf = vec![0; 10];
+    ///     sock.recv(buf.as_mut_slice()).expect("recv function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
@@ -1247,8 +1338,11 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
@@ -1280,9 +1374,12 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.connect("/some/sock").expect("Couldn't connect");
-    /// sock.send(b"omelette au fromage").expect("send_to function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.connect("/some/sock").expect("Couldn't connect");
+    ///     sock.send(b"omelette au fromage").expect("send_to function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
@@ -1307,8 +1404,12 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.set_read_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("set_read_timeout function failed");
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
@@ -1319,10 +1420,13 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixDatagram::unbound().unwrap();
-    /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
-    /// let err = result.unwrap_err();
-    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixDatagram::unbound()?;
+    ///     let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
+    ///     let err = result.unwrap_err();
+    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
@@ -1346,9 +1450,12 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.set_write_timeout(Some(Duration::new(1, 0)))
-    ///     .expect("set_write_timeout function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.set_write_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("set_write_timeout function failed");
+    ///     Ok(())
+    /// }
     /// ```
     ///
     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
@@ -1359,10 +1466,13 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let socket = UnixDatagram::unbound().unwrap();
-    /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
-    /// let err = result.unwrap_err();
-    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
+    /// fn main() -> std::io::Result<()> {
+    ///     let socket = UnixDatagram::unbound()?;
+    ///     let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
+    ///     let err = result.unwrap_err();
+    ///     assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
@@ -1377,9 +1487,13 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed");
-    /// assert_eq!(sock.read_timeout().unwrap(), Some(Duration::new(1, 0)));
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.set_read_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("set_read_timeout function failed");
+    ///     assert_eq!(sock.read_timeout()?, Some(Duration::new(1, 0)));
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
@@ -1394,10 +1508,13 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::time::Duration;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.set_write_timeout(Some(Duration::new(1, 0)))
-    ///     .expect("set_write_timeout function failed");
-    /// assert_eq!(sock.write_timeout().unwrap(), Some(Duration::new(1, 0)));
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.set_write_timeout(Some(Duration::new(1, 0)))
+    ///         .expect("set_write_timeout function failed");
+    ///     assert_eq!(sock.write_timeout()?, Some(Duration::new(1, 0)));
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
@@ -1411,8 +1528,11 @@ impl UnixDatagram {
     /// ```
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.set_nonblocking(true).expect("set_nonblocking function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.set_nonblocking(true).expect("set_nonblocking function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
@@ -1426,9 +1546,12 @@ impl UnixDatagram {
     /// ```no_run
     /// use std::os::unix::net::UnixDatagram;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// if let Ok(Some(err)) = sock.take_error() {
-    ///     println!("Got error: {:?}", err);
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     if let Ok(Some(err)) = sock.take_error() {
+    ///         println!("Got error: {:?}", err);
+    ///     }
+    ///     Ok(())
     /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
@@ -1448,8 +1571,11 @@ impl UnixDatagram {
     /// use std::os::unix::net::UnixDatagram;
     /// use std::net::Shutdown;
     ///
-    /// let sock = UnixDatagram::unbound().unwrap();
-    /// sock.shutdown(Shutdown::Both).expect("shutdown function failed");
+    /// fn main() -> std::io::Result<()> {
+    ///     let sock = UnixDatagram::unbound()?;
+    ///     sock.shutdown(Shutdown::Both).expect("shutdown function failed");
+    ///     Ok(())
+    /// }
     /// ```
     #[stable(feature = "unix_socket", since = "1.10.0")]
     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
diff --git a/src/libstd/sys/unix/ext/process.rs b/src/libstd/sys/unix/ext/process.rs
index 0e95f97486b..fa8670b4aec 100644
--- a/src/libstd/sys/unix/ext/process.rs
+++ b/src/libstd/sys/unix/ext/process.rs
@@ -4,10 +4,10 @@
 
 use crate::ffi::OsStr;
 use crate::io;
-use crate::os::unix::io::{FromRawFd, RawFd, AsRawFd, IntoRawFd};
+use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
 use crate::process;
 use crate::sys;
-use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner};
+use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
 
 /// Unix-specific extensions to the [`process::Command`] builder.
 ///
@@ -56,7 +56,8 @@ pub trait CommandExt {
     /// locations may not appear where intended.
     #[stable(feature = "process_pre_exec", since = "1.34.0")]
     unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static;
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static;
 
     /// Schedules a closure to be run just before the `exec` function is
     /// invoked.
@@ -68,7 +69,8 @@ pub trait CommandExt {
     #[stable(feature = "process_exec", since = "1.15.0")]
     #[rustc_deprecated(since = "1.37.0", reason = "should be unsafe, use `pre_exec` instead")]
     fn before_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static,
     {
         unsafe { self.pre_exec(f) }
     }
@@ -111,7 +113,8 @@ pub trait CommandExt {
     /// default executable path.
     #[unstable(feature = "process_set_argv0", issue = "66510")]
     fn arg0<S>(&mut self, arg: S) -> &mut process::Command
-        where S: AsRef<OsStr>;
+    where
+        S: AsRef<OsStr>;
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -127,7 +130,8 @@ impl CommandExt for process::Command {
     }
 
     unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static,
     {
         self.as_inner_mut().pre_exec(Box::new(f));
         self
@@ -138,7 +142,8 @@ impl CommandExt for process::Command {
     }
 
     fn arg0<S>(&mut self, arg: S) -> &mut process::Command
-        where S: AsRef<OsStr>
+    where
+        S: AsRef<OsStr>,
     {
         self.as_inner_mut().set_arg_0(arg.as_ref());
         self
diff --git a/src/libstd/sys/unix/ext/raw.rs b/src/libstd/sys/unix/ext/raw.rs
index 75ae54a919a..d81368a18b4 100644
--- a/src/libstd/sys/unix/ext/raw.rs
+++ b/src/libstd/sys/unix/ext/raw.rs
@@ -1,23 +1,28 @@
 //! Unix-specific primitives available on all unix platforms
 
 #![stable(feature = "raw_ext", since = "1.1.0")]
-#![rustc_deprecated(since = "1.8.0",
-                    reason = "these type aliases are no longer supported by \
-                              the standard library, the `libc` crate on \
-                              crates.io should be used instead for the correct \
-                              definitions")]
+#![rustc_deprecated(
+    since = "1.8.0",
+    reason = "these type aliases are no longer supported by \
+              the standard library, the `libc` crate on \
+              crates.io should be used instead for the correct \
+              definitions"
+)]
 #![allow(deprecated)]
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type uid_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type gid_t = u32;
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type pid_t = i32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type uid_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type gid_t = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type pid_t = i32;
 
 #[doc(inline)]
 #[stable(feature = "pthread_t", since = "1.8.0")]
 pub use crate::sys::platform::raw::pthread_t;
 #[doc(inline)]
 #[stable(feature = "raw_ext", since = "1.1.0")]
-pub use crate::sys::platform::raw::{dev_t, ino_t, mode_t, nlink_t, off_t, blksize_t};
+pub use crate::sys::platform::raw::{blkcnt_t, time_t};
 #[doc(inline)]
 #[stable(feature = "raw_ext", since = "1.1.0")]
-pub use crate::sys::platform::raw::{blkcnt_t, time_t};
+pub use crate::sys::platform::raw::{blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t};
diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs
index 7d718032ef6..dfb9307daea 100644
--- a/src/libstd/sys/unix/fast_thread_local.rs
+++ b/src/libstd/sys/unix/fast_thread_local.rs
@@ -10,25 +10,34 @@
 // fallback implementation to use as well.
 //
 // Due to rust-lang/rust#18804, make sure this is not generic!
-#[cfg(any(target_os = "linux", target_os = "fuchsia", target_os = "redox",
-          target_os = "emscripten"))]
-pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
+#[cfg(any(
+    target_os = "linux",
+    target_os = "fuchsia",
+    target_os = "redox",
+    target_os = "emscripten"
+))]
+pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
     use crate::mem;
     use crate::sys_common::thread_local::register_dtor_fallback;
 
-    extern {
+    extern "C" {
         #[linkage = "extern_weak"]
         static __dso_handle: *mut u8;
         #[linkage = "extern_weak"]
         static __cxa_thread_atexit_impl: *const libc::c_void;
     }
     if !__cxa_thread_atexit_impl.is_null() {
-        type F = unsafe extern fn(dtor: unsafe extern fn(*mut u8),
-                                  arg: *mut u8,
-                                  dso_handle: *mut u8) -> libc::c_int;
-        mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)
-            (dtor, t, &__dso_handle as *const _ as *mut _);
-        return
+        type F = unsafe extern "C" fn(
+            dtor: unsafe extern "C" fn(*mut u8),
+            arg: *mut u8,
+            dso_handle: *mut u8,
+        ) -> libc::c_int;
+        mem::transmute::<*const libc::c_void, F>(__cxa_thread_atexit_impl)(
+            dtor,
+            t,
+            &__dso_handle as *const _ as *mut _,
+        );
+        return;
     }
     register_dtor_fallback(t, dtor);
 }
@@ -44,7 +53,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
 // thread. thread_local dtors are pushed to the DTOR list without calling
 // _tlv_atexit.
 #[cfg(target_os = "macos")]
-pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
+pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
     use crate::cell::Cell;
     use crate::ptr;
 
@@ -55,7 +64,7 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
         REGISTERED.set(true);
     }
 
-    type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
+    type List = Vec<(*mut u8, unsafe extern "C" fn(*mut u8))>;
 
     #[thread_local]
     static DTORS: Cell<*mut List> = Cell::new(ptr::null_mut());
@@ -64,15 +73,14 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
         DTORS.set(Box::into_raw(v));
     }
 
-    extern {
-        fn _tlv_atexit(dtor: unsafe extern fn(*mut u8),
-                       arg: *mut u8);
+    extern "C" {
+        fn _tlv_atexit(dtor: unsafe extern "C" fn(*mut u8), arg: *mut u8);
     }
 
     let list: &mut List = &mut *DTORS.get();
     list.push((t, dtor));
 
-    unsafe extern fn run_dtors(_: *mut u8) {
+    unsafe extern "C" fn run_dtors(_: *mut u8) {
         let mut ptr = DTORS.replace(ptr::null_mut());
         while !ptr.is_null() {
             let list = Box::from_raw(ptr);
diff --git a/src/libstd/sys/unix/fd.rs b/src/libstd/sys/unix/fd.rs
index ba611a6b7e7..53b50763fbf 100644
--- a/src/libstd/sys/unix/fd.rs
+++ b/src/libstd/sys/unix/fd.rs
@@ -1,7 +1,7 @@
 #![unstable(reason = "not public", issue = "0", feature = "fd")]
 
 use crate::cmp;
-use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut};
+use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read};
 use crate::mem;
 use crate::sync::atomic::{AtomicBool, Ordering};
 use crate::sys::cvt;
@@ -35,7 +35,9 @@ impl FileDesc {
         FileDesc { fd }
     }
 
-    pub fn raw(&self) -> c_int { self.fd }
+    pub fn raw(&self) -> c_int {
+        self.fd
+    }
 
     /// Extracts the actual file descriptor without closing it.
     pub fn into_raw(self) -> c_int {
@@ -46,18 +48,18 @@ impl FileDesc {
 
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::read(self.fd,
-                       buf.as_mut_ptr() as *mut c_void,
-                       cmp::min(buf.len(), max_len()))
+            libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len()))
         })?;
         Ok(ret as usize)
     }
 
     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::readv(self.fd,
-                        bufs.as_ptr() as *const libc::iovec,
-                        cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
+            libc::readv(
+                self.fd,
+                bufs.as_ptr() as *const libc::iovec,
+                cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
+            )
         })?;
         Ok(ret as usize)
     }
@@ -72,39 +74,44 @@ impl FileDesc {
         use super::android::cvt_pread64;
 
         #[cfg(not(target_os = "android"))]
-        unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
-            -> io::Result<isize>
-        {
-            #[cfg(target_os = "linux")]
-            use libc::pread64;
+        unsafe fn cvt_pread64(
+            fd: c_int,
+            buf: *mut c_void,
+            count: usize,
+            offset: i64,
+        ) -> io::Result<isize> {
             #[cfg(not(target_os = "linux"))]
             use libc::pread as pread64;
+            #[cfg(target_os = "linux")]
+            use libc::pread64;
             cvt(pread64(fd, buf, count, offset))
         }
 
         unsafe {
-            cvt_pread64(self.fd,
-                        buf.as_mut_ptr() as *mut c_void,
-                        cmp::min(buf.len(), max_len()),
-                        offset as i64)
-                .map(|n| n as usize)
+            cvt_pread64(
+                self.fd,
+                buf.as_mut_ptr() as *mut c_void,
+                cmp::min(buf.len(), max_len()),
+                offset as i64,
+            )
+            .map(|n| n as usize)
         }
     }
 
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::write(self.fd,
-                        buf.as_ptr() as *const c_void,
-                        cmp::min(buf.len(), max_len()))
+            libc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len()))
         })?;
         Ok(ret as usize)
     }
 
     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::writev(self.fd,
-                         bufs.as_ptr() as *const libc::iovec,
-                         cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
+            libc::writev(
+                self.fd,
+                bufs.as_ptr() as *const libc::iovec,
+                cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
+            )
         })?;
         Ok(ret as usize)
     }
@@ -114,54 +121,61 @@ impl FileDesc {
         use super::android::cvt_pwrite64;
 
         #[cfg(not(target_os = "android"))]
-        unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
-            -> io::Result<isize>
-        {
-            #[cfg(target_os = "linux")]
-            use libc::pwrite64;
+        unsafe fn cvt_pwrite64(
+            fd: c_int,
+            buf: *const c_void,
+            count: usize,
+            offset: i64,
+        ) -> io::Result<isize> {
             #[cfg(not(target_os = "linux"))]
             use libc::pwrite as pwrite64;
+            #[cfg(target_os = "linux")]
+            use libc::pwrite64;
             cvt(pwrite64(fd, buf, count, offset))
         }
 
         unsafe {
-            cvt_pwrite64(self.fd,
-                         buf.as_ptr() as *const c_void,
-                         cmp::min(buf.len(), max_len()),
-                         offset as i64)
-                .map(|n| n as usize)
+            cvt_pwrite64(
+                self.fd,
+                buf.as_ptr() as *const c_void,
+                cmp::min(buf.len(), max_len()),
+                offset as i64,
+            )
+            .map(|n| n as usize)
         }
     }
 
     #[cfg(target_os = "linux")]
     pub fn get_cloexec(&self) -> io::Result<bool> {
-        unsafe {
-            Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0)
-        }
+        unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) }
     }
 
-    #[cfg(not(any(target_env = "newlib",
-                  target_os = "solaris",
-                  target_os = "emscripten",
-                  target_os = "fuchsia",
-                  target_os = "l4re",
-                  target_os = "linux",
-                  target_os = "haiku",
-                  target_os = "redox")))]
+    #[cfg(not(any(
+        target_env = "newlib",
+        target_os = "solaris",
+        target_os = "emscripten",
+        target_os = "fuchsia",
+        target_os = "l4re",
+        target_os = "linux",
+        target_os = "haiku",
+        target_os = "redox"
+    )))]
     pub fn set_cloexec(&self) -> io::Result<()> {
         unsafe {
             cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
             Ok(())
         }
     }
-    #[cfg(any(target_env = "newlib",
-              target_os = "solaris",
-              target_os = "emscripten",
-              target_os = "fuchsia",
-              target_os = "l4re",
-              target_os = "linux",
-              target_os = "haiku",
-              target_os = "redox"))]
+    #[cfg(any(
+        target_env = "newlib",
+        target_os = "solaris",
+        target_os = "emscripten",
+        target_os = "fuchsia",
+        target_os = "l4re",
+        target_os = "linux",
+        target_os = "haiku",
+        target_os = "redox"
+    ))]
     pub fn set_cloexec(&self) -> io::Result<()> {
         unsafe {
             let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
@@ -216,7 +230,7 @@ impl FileDesc {
         // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
         #[cfg(any(target_os = "android", target_os = "haiku"))]
         use libc::F_DUPFD as F_DUPFD_CLOEXEC;
-        #[cfg(not(any(target_os = "android", target_os="haiku")))]
+        #[cfg(not(any(target_os = "android", target_os = "haiku")))]
         use libc::F_DUPFD_CLOEXEC;
 
         let make_filedesc = |fd| {
@@ -224,8 +238,7 @@ impl FileDesc {
             fd.set_cloexec()?;
             Ok(fd)
         };
-        static TRY_CLOEXEC: AtomicBool =
-            AtomicBool::new(!cfg!(target_os = "android"));
+        static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = "android"));
         let fd = self.raw();
         if TRY_CLOEXEC.load(Ordering::Relaxed) {
             match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
@@ -237,7 +250,7 @@ impl FileDesc {
                         make_filedesc(fd)?
                     } else {
                         FileDesc::new(fd)
-                    })
+                    });
                 }
                 Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
                     TRY_CLOEXEC.store(false, Ordering::Relaxed);
@@ -261,7 +274,9 @@ impl<'a> Read for &'a FileDesc {
 }
 
 impl AsInner<c_int> for FileDesc {
-    fn as_inner(&self) -> &c_int { &self.fd }
+    fn as_inner(&self) -> &c_int {
+        &self.fd
+    }
 }
 
 impl Drop for FileDesc {
diff --git a/src/libstd/sys/unix/io.rs b/src/libstd/sys/unix/io.rs
index a3a72919176..b4a64e93c84 100644
--- a/src/libstd/sys/unix/io.rs
+++ b/src/libstd/sys/unix/io.rs
@@ -1,7 +1,7 @@
 use crate::marker::PhantomData;
 use crate::slice;
 
-use libc::{iovec, c_void};
+use libc::{c_void, iovec};
 
 #[repr(transparent)]
 pub struct IoSlice<'a> {
@@ -13,10 +13,7 @@ impl<'a> IoSlice<'a> {
     #[inline]
     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
         IoSlice {
-            vec: iovec {
-                iov_base: buf.as_ptr() as *mut u8 as *mut c_void,
-                iov_len: buf.len()
-            },
+            vec: iovec { iov_base: buf.as_ptr() as *mut u8 as *mut c_void, iov_len: buf.len() },
             _p: PhantomData,
         }
     }
@@ -35,9 +32,7 @@ impl<'a> IoSlice<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 }
 
@@ -51,10 +46,7 @@ impl<'a> IoSliceMut<'a> {
     #[inline]
     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
         IoSliceMut {
-            vec: iovec {
-                iov_base: buf.as_mut_ptr() as *mut c_void,
-                iov_len: buf.len()
-            },
+            vec: iovec { iov_base: buf.as_mut_ptr() as *mut c_void, iov_len: buf.len() },
             _p: PhantomData,
         }
     }
@@ -73,15 +65,11 @@ impl<'a> IoSliceMut<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 
     #[inline]
     pub fn as_mut_slice(&mut self) -> &mut [u8] {
-        unsafe {
-            slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 }
diff --git a/src/libstd/sys/unix/l4re.rs b/src/libstd/sys/unix/l4re.rs
index 2c6f21aa21a..c6e4f5693ed 100644
--- a/src/libstd/sys/unix/l4re.rs
+++ b/src/libstd/sys/unix/l4re.rs
@@ -1,16 +1,18 @@
 macro_rules! unimpl {
-    () => (return Err(io::Error::new(io::ErrorKind::Other, "No networking available on L4Re."));)
+    () => {
+        return Err(io::Error::new(io::ErrorKind::Other, "No networking available on L4Re."));
+    };
 }
 
 pub mod net {
     #![allow(warnings)]
+    use crate::convert::TryFrom;
     use crate::fmt;
     use crate::io::{self, IoSlice, IoSliceMut};
-    use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
-    use crate::sys_common::{AsInner, FromInner, IntoInner};
+    use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
     use crate::sys::fd::FileDesc;
+    use crate::sys_common::{AsInner, FromInner, IntoInner};
     use crate::time::Duration;
-    use crate::convert::TryFrom;
 
     #[allow(unused_extern_crates)]
     pub extern crate libc as netc;
@@ -33,8 +35,11 @@ pub mod net {
             unimpl!();
         }
 
-        pub fn accept(&self, _: *mut libc::sockaddr, _: *mut libc::socklen_t)
-                  -> io::Result<Socket> {
+        pub fn accept(
+            &self,
+            _: *mut libc::sockaddr,
+            _: *mut libc::socklen_t,
+        ) -> io::Result<Socket> {
             unimpl!();
         }
 
@@ -100,15 +105,21 @@ pub mod net {
     }
 
     impl AsInner<libc::c_int> for Socket {
-        fn as_inner(&self) -> &libc::c_int { self.0.as_inner() }
+        fn as_inner(&self) -> &libc::c_int {
+            self.0.as_inner()
+        }
     }
 
     impl FromInner<libc::c_int> for Socket {
-        fn from_inner(fd: libc::c_int) -> Socket { Socket(FileDesc::new(fd)) }
+        fn from_inner(fd: libc::c_int) -> Socket {
+            Socket(FileDesc::new(fd))
+        }
     }
 
     impl IntoInner<libc::c_int> for Socket {
-        fn into_inner(self) -> libc::c_int { self.0.into_raw() }
+        fn into_inner(self) -> libc::c_int {
+            self.0.into_raw()
+        }
     }
 
     pub struct TcpStream {
@@ -124,9 +135,13 @@ pub mod net {
             unimpl!();
         }
 
-        pub fn socket(&self) -> &Socket { &self.inner }
+        pub fn socket(&self) -> &Socket {
+            &self.inner
+        }
 
-        pub fn into_socket(self) -> Socket { self.inner }
+        pub fn into_socket(self) -> Socket {
+            self.inner
+        }
 
         pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
             unimpl!();
@@ -226,9 +241,13 @@ pub mod net {
             unimpl!();
         }
 
-        pub fn socket(&self) -> &Socket { &self.inner }
+        pub fn socket(&self) -> &Socket {
+            &self.inner
+        }
 
-        pub fn into_socket(self) -> Socket { self.inner }
+        pub fn into_socket(self) -> Socket {
+            self.inner
+        }
 
         pub fn socket_addr(&self) -> io::Result<SocketAddr> {
             unimpl!();
@@ -288,9 +307,13 @@ pub mod net {
             unimpl!();
         }
 
-        pub fn socket(&self) -> &Socket { &self.inner }
+        pub fn socket(&self) -> &Socket {
+            &self.inner
+        }
 
-        pub fn into_socket(self) -> Socket { self.inner }
+        pub fn into_socket(self) -> Socket {
+            self.inner
+        }
 
         pub fn peer_addr(&self) -> io::Result<SocketAddr> {
             unimpl!();
@@ -364,24 +387,20 @@ pub mod net {
             unimpl!();
         }
 
-        pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                             -> io::Result<()> {
-                                 unimpl!();
+        pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
+            unimpl!();
         }
 
-        pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                             -> io::Result<()> {
-                                 unimpl!();
+        pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
+            unimpl!();
         }
 
-        pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                              -> io::Result<()> {
-                                  unimpl!();
+        pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
+            unimpl!();
         }
 
-        pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                              -> io::Result<()> {
-                                  unimpl!();
+        pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
+            unimpl!();
         }
 
         pub fn set_ttl(&self, _: u32) -> io::Result<()> {
@@ -450,7 +469,6 @@ pub mod net {
     unsafe impl Sync for LookupHost {}
     unsafe impl Send for LookupHost {}
 
-
     impl TryFrom<&str> for LookupHost {
         type Error = io::Error;
 
diff --git a/src/libstd/sys/unix/memchr.rs b/src/libstd/sys/unix/memchr.rs
index 1984678bdde..a9273ea676c 100644
--- a/src/libstd/sys/unix/memchr.rs
+++ b/src/libstd/sys/unix/memchr.rs
@@ -6,32 +6,27 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
         libc::memchr(
             haystack.as_ptr() as *const libc::c_void,
             needle as libc::c_int,
-            haystack.len())
+            haystack.len(),
+        )
     };
-    if p.is_null() {
-        None
-    } else {
-        Some(p as usize - (haystack.as_ptr() as usize))
-    }
+    if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) }
 }
 
 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
-
     #[cfg(target_os = "linux")]
     fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option<usize> {
         // GNU's memrchr() will - unlike memchr() - error if haystack is empty.
-        if haystack.is_empty() {return None}
+        if haystack.is_empty() {
+            return None;
+        }
         let p = unsafe {
             libc::memrchr(
                 haystack.as_ptr() as *const libc::c_void,
                 needle as libc::c_int,
-                haystack.len())
+                haystack.len(),
+            )
         };
-        if p.is_null() {
-            None
-        } else {
-            Some(p as usize - (haystack.as_ptr() as usize))
-        }
+        if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) }
     }
 
     #[cfg(not(target_os = "linux"))]
diff --git a/src/libstd/sys/unix/net.rs b/src/libstd/sys/unix/net.rs
index 75750b5c4e5..946b2b9d8de 100644
--- a/src/libstd/sys/unix/net.rs
+++ b/src/libstd/sys/unix/net.rs
@@ -1,13 +1,13 @@
+use crate::cmp;
 use crate::ffi::CStr;
 use crate::io::{self, IoSlice, IoSliceMut};
 use crate::mem;
-use crate::net::{SocketAddr, Shutdown};
+use crate::net::{Shutdown, SocketAddr};
 use crate::str;
 use crate::sys::fd::FileDesc;
-use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
+use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::{Duration, Instant};
-use crate::cmp;
 
 use libc::{c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
 
@@ -42,23 +42,23 @@ pub fn init() {}
 
 pub fn cvt_gai(err: c_int) -> io::Result<()> {
     if err == 0 {
-        return Ok(())
+        return Ok(());
     }
 
     // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
     on_resolver_failure();
 
     if err == EAI_SYSTEM {
-        return Err(io::Error::last_os_error())
+        return Err(io::Error::last_os_error());
     }
 
     let detail = unsafe {
-        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
-            .to_owned()
+        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
     };
-    Err(io::Error::new(io::ErrorKind::Other,
-                       &format!("failed to lookup address information: {}",
-                                detail)[..]))
+    Err(io::Error::new(
+        io::ErrorKind::Other,
+        &format!("failed to lookup address information: {}", detail)[..],
+    ))
 }
 
 impl Socket {
@@ -106,7 +106,7 @@ impl Socket {
                     Ok(_) => {
                         return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))));
                     }
-                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
+                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
                     Err(e) => return Err(e),
                 }
             }
@@ -135,15 +135,13 @@ impl Socket {
             Err(e) => return Err(e),
         }
 
-        let mut pollfd = libc::pollfd {
-            fd: self.0.raw(),
-            events: libc::POLLOUT,
-            revents: 0,
-        };
+        let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 };
 
         if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
-            return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                      "cannot set a 0 duration timeout"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "cannot set a 0 duration timeout",
+            ));
         }
 
         let start = Instant::now();
@@ -155,7 +153,8 @@ impl Socket {
             }
 
             let timeout = timeout - elapsed;
-            let mut timeout = timeout.as_secs()
+            let mut timeout = timeout
+                .as_secs()
                 .saturating_mul(1_000)
                 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
             if timeout == 0 {
@@ -176,10 +175,9 @@ impl Socket {
                     // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
                     // for POLLHUP rather than read readiness
                     if pollfd.revents & libc::POLLHUP != 0 {
-                        let e = self.take_error()?
-                            .unwrap_or_else(|| {
-                                io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
-                            });
+                        let e = self.take_error()?.unwrap_or_else(|| {
+                            io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
+                        });
                         return Err(e);
                     }
 
@@ -189,8 +187,7 @@ impl Socket {
         }
     }
 
-    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
-                  -> io::Result<Socket> {
+    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
         // Unfortunately the only known way right now to accept a socket and
         // atomically set the CLOEXEC flag is to use the `accept4` syscall on
         // Linux. This was added in 2.6.28, however, and because we support
@@ -204,9 +201,7 @@ impl Socket {
                     flags: c_int
                 ) -> c_int
             }
-            let res = cvt_r(|| unsafe {
-                accept4(self.0.raw(), storage, len, SOCK_CLOEXEC)
-            });
+            let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, SOCK_CLOEXEC) });
             match res {
                 Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
                 Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
@@ -214,9 +209,7 @@ impl Socket {
             }
         }
 
-        let fd = cvt_r(|| unsafe {
-            libc::accept(self.0.raw(), storage, len)
-        })?;
+        let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?;
         let fd = FileDesc::new(fd);
         fd.set_cloexec()?;
         Ok(Socket(fd))
@@ -228,10 +221,7 @@ impl Socket {
 
     fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::recv(self.0.raw(),
-                       buf.as_mut_ptr() as *mut c_void,
-                       buf.len(),
-                       flags)
+            libc::recv(self.0.raw(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
         })?;
         Ok(ret as usize)
     }
@@ -248,18 +238,23 @@ impl Socket {
         self.0.read_vectored(bufs)
     }
 
-    fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
-                            -> io::Result<(usize, SocketAddr)> {
+    fn recv_from_with_flags(
+        &self,
+        buf: &mut [u8],
+        flags: c_int,
+    ) -> io::Result<(usize, SocketAddr)> {
         let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
         let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
 
         let n = cvt(unsafe {
-            libc::recvfrom(self.0.raw(),
-                        buf.as_mut_ptr() as *mut c_void,
-                        buf.len(),
-                        flags,
-                        &mut storage as *mut _ as *mut _,
-                        &mut addrlen)
+            libc::recvfrom(
+                self.0.raw(),
+                buf.as_mut_ptr() as *mut c_void,
+                buf.len(),
+                flags,
+                &mut storage as *mut _ as *mut _,
+                &mut addrlen,
+            )
         })?;
         Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
     }
@@ -284,8 +279,10 @@ impl Socket {
         let timeout = match dur {
             Some(dur) => {
                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
-                    return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                              "cannot set a 0 duration timeout"));
+                    return Err(io::Error::new(
+                        io::ErrorKind::InvalidInput,
+                        "cannot set a 0 duration timeout",
+                    ));
                 }
 
                 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
@@ -302,12 +299,7 @@ impl Socket {
                 }
                 timeout
             }
-            None => {
-                libc::timeval {
-                    tv_sec: 0,
-                    tv_usec: 0,
-                }
-            }
+            None => libc::timeval { tv_sec: 0, tv_usec: 0 },
         };
         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
     }
@@ -349,24 +341,26 @@ impl Socket {
 
     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
-        if raw == 0 {
-            Ok(None)
-        } else {
-            Ok(Some(io::Error::from_raw_os_error(raw as i32)))
-        }
+        if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
     }
 }
 
 impl AsInner<c_int> for Socket {
-    fn as_inner(&self) -> &c_int { self.0.as_inner() }
+    fn as_inner(&self) -> &c_int {
+        self.0.as_inner()
+    }
 }
 
 impl FromInner<c_int> for Socket {
-    fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
+    fn from_inner(fd: c_int) -> Socket {
+        Socket(FileDesc::new(fd))
+    }
 }
 
 impl IntoInner<c_int> for Socket {
-    fn into_inner(self) -> c_int { self.0.into_raw() }
+    fn into_inner(self) -> c_int {
+        self.0.into_raw()
+    }
 }
 
 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
diff --git a/src/libstd/sys/unix/path.rs b/src/libstd/sys/unix/path.rs
index 7a183956107..840a7ae0426 100644
--- a/src/libstd/sys/unix/path.rs
+++ b/src/libstd/sys/unix/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs
index 029f4216b7e..77fefef8a18 100644
--- a/src/libstd/sys/unix/pipe.rs
+++ b/src/libstd/sys/unix/pipe.rs
@@ -22,15 +22,15 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
     // CLOEXEC flag is to use the `pipe2` syscall on Linux. This was added in
     // 2.6.27, however, and because we support 2.6.18 we must detect this
     // support dynamically.
-    if cfg!(any(target_os = "dragonfly",
-                target_os = "freebsd",
-                target_os = "linux",
-                target_os = "netbsd",
-                target_os = "openbsd",
-                target_os = "redox")) &&
-       !INVALID.load(Ordering::SeqCst)
+    if cfg!(any(
+        target_os = "dragonfly",
+        target_os = "freebsd",
+        target_os = "linux",
+        target_os = "netbsd",
+        target_os = "openbsd",
+        target_os = "redox"
+    )) && !INVALID.load(Ordering::SeqCst)
     {
-
         // Note that despite calling a glibc function here we may still
         // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to
         // emulate on older kernels, so if you happen to be running on
@@ -38,8 +38,7 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> {
         // see the syscall.
         match cvt(unsafe { pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }) {
             Ok(_) => {
-                return Ok((AnonPipe(FileDesc::new(fds[0])),
-                            AnonPipe(FileDesc::new(fds[1]))));
+                return Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1]))));
             }
             Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {
                 INVALID.store(true, Ordering::SeqCst);
@@ -73,15 +72,15 @@ impl AnonPipe {
         self.0.write_vectored(bufs)
     }
 
-    pub fn fd(&self) -> &FileDesc { &self.0 }
-    pub fn into_fd(self) -> FileDesc { self.0 }
+    pub fn fd(&self) -> &FileDesc {
+        &self.0
+    }
+    pub fn into_fd(self) -> FileDesc {
+        self.0
+    }
 }
 
-pub fn read2(p1: AnonPipe,
-             v1: &mut Vec<u8>,
-             p2: AnonPipe,
-             v2: &mut Vec<u8>) -> io::Result<()> {
-
+pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
     // Set both pipes into nonblocking mode as we're gonna be reading from both
     // in the `select` loop below, and we wouldn't want one to block the other!
     let p1 = p1.into_fd();
@@ -117,8 +116,9 @@ pub fn read2(p1: AnonPipe,
         match fd.read_to_end(dst) {
             Ok(_) => Ok(true),
             Err(e) => {
-                if e.raw_os_error() == Some(libc::EWOULDBLOCK) ||
-                   e.raw_os_error() == Some(libc::EAGAIN) {
+                if e.raw_os_error() == Some(libc::EWOULDBLOCK)
+                    || e.raw_os_error() == Some(libc::EAGAIN)
+                {
                     Ok(false)
                 } else {
                     Err(e)
diff --git a/src/libstd/sys/unix/process/process_common.rs b/src/libstd/sys/unix/process/process_common.rs
index 0e6f96bb228..c9109b0c9d4 100644
--- a/src/libstd/sys/unix/process/process_common.rs
+++ b/src/libstd/sys/unix/process/process_common.rs
@@ -1,6 +1,7 @@
 use crate::os::unix::prelude::*;
 
-use crate::ffi::{OsString, OsStr, CString, CStr};
+use crate::collections::BTreeMap;
+use crate::ffi::{CStr, CString, OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::ptr;
@@ -8,12 +9,11 @@ use crate::sys::fd::FileDesc;
 use crate::sys::fs::File;
 use crate::sys::pipe::{self, AnonPipe};
 use crate::sys_common::process::CommandEnv;
-use crate::collections::BTreeMap;
 
 #[cfg(not(target_os = "fuchsia"))]
 use crate::sys::fs::OpenOptions;
 
-use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
+use libc::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS};
 
 cfg_if::cfg_if! {
     if #[cfg(target_os = "fuchsia")] {
@@ -204,10 +204,7 @@ impl Command {
         &mut self.closures
     }
 
-    pub unsafe fn pre_exec(
-        &mut self,
-        f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
-    ) {
+    pub unsafe fn pre_exec(&mut self, f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
         self.closures.push(f);
     }
 
@@ -236,26 +233,21 @@ impl Command {
         self.env.have_changed_path()
     }
 
-    pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
-                -> io::Result<(StdioPipes, ChildPipes)> {
+    pub fn setup_io(
+        &self,
+        default: Stdio,
+        needs_stdin: bool,
+    ) -> io::Result<(StdioPipes, ChildPipes)> {
         let null = Stdio::Null;
-        let default_stdin = if needs_stdin {&default} else {&null};
+        let default_stdin = if needs_stdin { &default } else { &null };
         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
         let stdout = self.stdout.as_ref().unwrap_or(&default);
         let stderr = self.stderr.as_ref().unwrap_or(&default);
         let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
         let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
         let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
-        let ours = StdioPipes {
-            stdin: our_stdin,
-            stdout: our_stdout,
-            stderr: our_stderr,
-        };
-        let theirs = ChildPipes {
-            stdin: their_stdin,
-            stdout: their_stdout,
-            stderr: their_stderr,
-        };
+        let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
+        let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
         Ok((ours, theirs))
     }
 }
@@ -270,21 +262,21 @@ fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
 // Helper type to manage ownership of the strings within a C-style array.
 pub struct CStringArray {
     items: Vec<CString>,
-    ptrs: Vec<*const c_char>
+    ptrs: Vec<*const c_char>,
 }
 
 impl CStringArray {
     pub fn with_capacity(capacity: usize) -> Self {
         let mut result = CStringArray {
             items: Vec::with_capacity(capacity),
-            ptrs: Vec::with_capacity(capacity+1)
+            ptrs: Vec::with_capacity(capacity + 1),
         };
         result.ptrs.push(ptr::null());
         result
     }
     pub fn push(&mut self, item: CString) {
         let l = self.ptrs.len();
-        self.ptrs[l-1] = item.as_ptr();
+        self.ptrs[l - 1] = item.as_ptr();
         self.ptrs.push(ptr::null());
         self.items.push(item);
     }
@@ -315,12 +307,9 @@ fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStr
 }
 
 impl Stdio {
-    pub fn to_child_stdio(&self, readable: bool)
-                      -> io::Result<(ChildStdio, Option<AnonPipe>)> {
+    pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
         match *self {
-            Stdio::Inherit => {
-                Ok((ChildStdio::Inherit, None))
-            },
+            Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
 
             // Make sure that the source descriptors are not an stdio
             // descriptor, otherwise the order which we set the child's
@@ -339,11 +328,7 @@ impl Stdio {
 
             Stdio::MakePipe => {
                 let (reader, writer) = pipe::anon_pipe()?;
-                let (ours, theirs) = if readable {
-                    (writer, reader)
-                } else {
-                    (reader, writer)
-                };
+                let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
                 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
             }
 
@@ -352,17 +337,13 @@ impl Stdio {
                 let mut opts = OpenOptions::new();
                 opts.read(readable);
                 opts.write(!readable);
-                let path = unsafe {
-                    CStr::from_ptr(DEV_NULL.as_ptr() as *const _)
-                };
+                let path = unsafe { CStr::from_ptr(DEV_NULL.as_ptr() as *const _) };
                 let fd = File::open_c(&path, &opts)?;
                 Ok((ChildStdio::Owned(fd.into_fd()), None))
             }
 
             #[cfg(target_os = "fuchsia")]
-            Stdio::Null => {
-                Ok((ChildStdio::Null, None))
-            }
+            Stdio::Null => Ok((ChildStdio::Null, None)),
         }
     }
 }
@@ -430,7 +411,7 @@ mod tests {
                 Ok(t) => t,
                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
             }
-        }
+        };
     }
 
     // See #14232 for more information, but it appears that signal delivery to a
@@ -461,8 +442,7 @@ mod tests {
             let stdin_write = pipes.stdin.take().unwrap();
             let stdout_read = pipes.stdout.take().unwrap();
 
-            t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(),
-                                         ptr::null_mut())));
+            t!(cvt(libc::pthread_sigmask(libc::SIG_SETMASK, old_set.as_ptr(), ptr::null_mut())));
 
             t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT)));
             // We need to wait until SIGINT is definitely delivered. The
diff --git a/src/libstd/sys/unix/process/process_fuchsia.rs b/src/libstd/sys/unix/process/process_fuchsia.rs
index 486c12f9bf8..f0bd1cdfed5 100644
--- a/src/libstd/sys/unix/process/process_fuchsia.rs
+++ b/src/libstd/sys/unix/process/process_fuchsia.rs
@@ -1,11 +1,11 @@
 use crate::convert::TryInto;
-use crate::io;
 use crate::fmt;
+use crate::io;
 use crate::mem;
 use crate::ptr;
 
-use crate::sys::process::zircon::{Handle, zx_handle_t};
 use crate::sys::process::process_common::*;
+use crate::sys::process::zircon::{zx_handle_t, Handle};
 
 use libc::{c_int, size_t};
 
@@ -14,13 +14,18 @@ use libc::{c_int, size_t};
 ////////////////////////////////////////////////////////////////////////////////
 
 impl Command {
-    pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
-                 -> io::Result<(Process, StdioPipes)> {
+    pub fn spawn(
+        &mut self,
+        default: Stdio,
+        needs_stdin: bool,
+    ) -> io::Result<(Process, StdioPipes)> {
         let envp = self.capture_env();
 
         if self.saw_nul() {
-            return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                      "nul byte found in provided data"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "nul byte found in provided data",
+            ));
         }
 
         let (ours, theirs) = self.setup_io(default, needs_stdin)?;
@@ -32,21 +37,23 @@ impl Command {
 
     pub fn exec(&mut self, default: Stdio) -> io::Error {
         if self.saw_nul() {
-            return io::Error::new(io::ErrorKind::InvalidInput,
-                                  "nul byte found in provided data")
+            return io::Error::new(io::ErrorKind::InvalidInput, "nul byte found in provided data");
         }
 
         match self.setup_io(default, true) {
             Ok((_, _)) => {
                 // FIXME: This is tough because we don't support the exec syscalls
                 unimplemented!();
-            },
+            }
             Err(e) => e,
         }
     }
 
-    unsafe fn do_exec(&mut self, stdio: ChildPipes, maybe_envp: Option<&CStringArray>)
-                      -> io::Result<zx_handle_t> {
+    unsafe fn do_exec(
+        &mut self,
+        stdio: ChildPipes,
+        maybe_envp: Option<&CStringArray>,
+    ) -> io::Result<zx_handle_t> {
         use crate::sys::process::zircon::*;
 
         let envp = match maybe_envp {
@@ -108,10 +115,15 @@ impl Command {
         let mut process_handle: zx_handle_t = 0;
         zx_cvt(fdio_spawn_etc(
             ZX_HANDLE_INVALID,
-            FDIO_SPAWN_CLONE_JOB | FDIO_SPAWN_CLONE_LDSVC | FDIO_SPAWN_CLONE_NAMESPACE
-            | FDIO_SPAWN_CLONE_ENVIRON,  // this is ignored when envp is non-null
-            self.get_program().as_ptr(), self.get_argv().as_ptr(), envp,
-            actions.len() as size_t, actions.as_ptr(),
+            FDIO_SPAWN_CLONE_JOB
+                | FDIO_SPAWN_CLONE_LDSVC
+                | FDIO_SPAWN_CLONE_NAMESPACE
+                | FDIO_SPAWN_CLONE_ENVIRON, // this is ignored when envp is non-null
+            self.get_program().as_ptr(),
+            self.get_argv().as_ptr(),
+            envp,
+            actions.len() as size_t,
+            actions.as_ptr(),
             &mut process_handle,
             ptr::null_mut(),
         ))?;
@@ -137,7 +149,9 @@ impl Process {
     pub fn kill(&mut self) -> io::Result<()> {
         use crate::sys::process::zircon::*;
 
-        unsafe { zx_cvt(zx_task_kill(self.handle.raw()))?; }
+        unsafe {
+            zx_cvt(zx_task_kill(self.handle.raw()))?;
+        }
 
         Ok(())
     }
@@ -151,16 +165,26 @@ impl Process {
         let mut avail: size_t = 0;
 
         unsafe {
-            zx_cvt(zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED,
-                                      ZX_TIME_INFINITE, ptr::null_mut()))?;
-            zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS,
-                                      &mut proc_info as *mut _ as *mut libc::c_void,
-                                      mem::size_of::<zx_info_process_t>(), &mut actual,
-                                      &mut avail))?;
+            zx_cvt(zx_object_wait_one(
+                self.handle.raw(),
+                ZX_TASK_TERMINATED,
+                ZX_TIME_INFINITE,
+                ptr::null_mut(),
+            ))?;
+            zx_cvt(zx_object_get_info(
+                self.handle.raw(),
+                ZX_INFO_PROCESS,
+                &mut proc_info as *mut _ as *mut libc::c_void,
+                mem::size_of::<zx_info_process_t>(),
+                &mut actual,
+                &mut avail,
+            ))?;
         }
         if actual != 1 {
-            return Err(io::Error::new(io::ErrorKind::InvalidData,
-                                      "Failed to get exit status of process"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "Failed to get exit status of process",
+            ));
         }
         Ok(ExitStatus(proc_info.return_code))
     }
@@ -174,23 +198,31 @@ impl Process {
         let mut avail: size_t = 0;
 
         unsafe {
-            let status = zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED,
-                                            0, ptr::null_mut());
+            let status =
+                zx_object_wait_one(self.handle.raw(), ZX_TASK_TERMINATED, 0, ptr::null_mut());
             match status {
-                0 => { }, // Success
+                0 => {} // Success
                 x if x == ERR_TIMED_OUT => {
                     return Ok(None);
-                },
-                _ => { panic!("Failed to wait on process handle: {}", status); },
+                }
+                _ => {
+                    panic!("Failed to wait on process handle: {}", status);
+                }
             }
-            zx_cvt(zx_object_get_info(self.handle.raw(), ZX_INFO_PROCESS,
-                                      &mut proc_info as *mut _ as *mut libc::c_void,
-                                      mem::size_of::<zx_info_process_t>(), &mut actual,
-                                      &mut avail))?;
+            zx_cvt(zx_object_get_info(
+                self.handle.raw(),
+                ZX_INFO_PROCESS,
+                &mut proc_info as *mut _ as *mut libc::c_void,
+                mem::size_of::<zx_info_process_t>(),
+                &mut actual,
+                &mut avail,
+            ))?;
         }
         if actual != 1 {
-            return Err(io::Error::new(io::ErrorKind::InvalidData,
-                                      "Failed to get exit status of process"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "Failed to get exit status of process",
+            ));
         }
         Ok(Some(ExitStatus(proc_info.return_code)))
     }
diff --git a/src/libstd/sys/unix/process/zircon.rs b/src/libstd/sys/unix/process/zircon.rs
index 188a6b5f2da..750b8f0762a 100644
--- a/src/libstd/sys/unix/process/zircon.rs
+++ b/src/libstd/sys/unix/process/zircon.rs
@@ -1,8 +1,8 @@
 #![allow(non_camel_case_types, unused)]
 
 use crate::convert::TryInto;
-use crate::io;
 use crate::i64;
+use crate::io;
 use crate::mem::MaybeUninit;
 use crate::os::raw::c_char;
 
@@ -16,27 +16,26 @@ pub type zx_status_t = i32;
 pub const ZX_HANDLE_INVALID: zx_handle_t = 0;
 
 pub type zx_time_t = i64;
-pub const ZX_TIME_INFINITE : zx_time_t = i64::MAX;
+pub const ZX_TIME_INFINITE: zx_time_t = i64::MAX;
 
 pub type zx_signals_t = u32;
 
-pub const ZX_OBJECT_SIGNAL_3         : zx_signals_t = 1 << 3;
+pub const ZX_OBJECT_SIGNAL_3: zx_signals_t = 1 << 3;
 
-pub const ZX_TASK_TERMINATED        : zx_signals_t = ZX_OBJECT_SIGNAL_3;
+pub const ZX_TASK_TERMINATED: zx_signals_t = ZX_OBJECT_SIGNAL_3;
 
-pub const ZX_RIGHT_SAME_RIGHTS  : zx_rights_t = 1 << 31;
+pub const ZX_RIGHT_SAME_RIGHTS: zx_rights_t = 1 << 31;
 
 pub type zx_object_info_topic_t = u32;
 
-pub const ZX_INFO_PROCESS         : zx_object_info_topic_t = 3;
+pub const ZX_INFO_PROCESS: zx_object_info_topic_t = 3;
 
-pub fn zx_cvt<T>(t: T) -> io::Result<T> where T: TryInto<zx_status_t>+Copy {
+pub fn zx_cvt<T>(t: T) -> io::Result<T>
+where
+    T: TryInto<zx_status_t> + Copy,
+{
     if let Ok(status) = TryInto::try_into(t) {
-        if status < 0 {
-            Err(io::Error::from_raw_os_error(status))
-        } else {
-            Ok(t)
-        }
+        if status < 0 { Err(io::Error::from_raw_os_error(status)) } else { Ok(t) }
     } else {
         Err(io::Error::last_os_error())
     }
@@ -49,9 +48,7 @@ pub struct Handle {
 
 impl Handle {
     pub fn new(raw: zx_handle_t) -> Handle {
-        Handle {
-            raw,
-        }
+        Handle { raw }
     }
 
     pub fn raw(&self) -> zx_handle_t {
@@ -61,7 +58,9 @@ impl Handle {
 
 impl Drop for Handle {
     fn drop(&mut self) {
-        unsafe { zx_cvt(zx_handle_close(self.raw)).expect("Failed to close zx_handle_t"); }
+        unsafe {
+            zx_cvt(zx_handle_close(self.raw)).expect("Failed to close zx_handle_t");
+        }
     }
 }
 
@@ -75,22 +74,34 @@ pub struct zx_info_process_t {
     pub debugger_attached: bool,
 }
 
-extern {
+extern "C" {
     pub fn zx_job_default() -> zx_handle_t;
 
     pub fn zx_task_kill(handle: zx_handle_t) -> zx_status_t;
 
     pub fn zx_handle_close(handle: zx_handle_t) -> zx_status_t;
 
-    pub fn zx_handle_duplicate(handle: zx_handle_t, rights: zx_rights_t,
-                               out: *const zx_handle_t) -> zx_handle_t;
-
-    pub fn zx_object_wait_one(handle: zx_handle_t, signals: zx_signals_t, timeout: zx_time_t,
-                              pending: *mut zx_signals_t) -> zx_status_t;
-
-    pub fn zx_object_get_info(handle: zx_handle_t, topic: u32, buffer: *mut c_void,
-                              buffer_size: size_t, actual_size: *mut size_t,
-                              avail: *mut size_t) -> zx_status_t;
+    pub fn zx_handle_duplicate(
+        handle: zx_handle_t,
+        rights: zx_rights_t,
+        out: *const zx_handle_t,
+    ) -> zx_handle_t;
+
+    pub fn zx_object_wait_one(
+        handle: zx_handle_t,
+        signals: zx_signals_t,
+        timeout: zx_time_t,
+        pending: *mut zx_signals_t,
+    ) -> zx_status_t;
+
+    pub fn zx_object_get_info(
+        handle: zx_handle_t,
+        topic: u32,
+        buffer: *mut c_void,
+        buffer_size: size_t,
+        actual_size: *mut size_t,
+        avail: *mut size_t,
+    ) -> zx_status_t;
 }
 
 #[derive(Default)]
@@ -103,11 +114,18 @@ pub struct fdio_spawn_action_t {
     pub reserved1: u64,
 }
 
-extern {
-    pub fn fdio_spawn_etc(job: zx_handle_t, flags: u32, path: *const c_char,
-                          argv: *const *const c_char, envp: *const *const c_char,
-                          action_count: size_t, actions: *const fdio_spawn_action_t,
-                          process: *mut zx_handle_t, err_msg: *mut c_char) -> zx_status_t;
+extern "C" {
+    pub fn fdio_spawn_etc(
+        job: zx_handle_t,
+        flags: u32,
+        path: *const c_char,
+        argv: *const *const c_char,
+        envp: *const *const c_char,
+        action_count: size_t,
+        actions: *const fdio_spawn_action_t,
+        process: *mut zx_handle_t,
+        err_msg: *mut c_char,
+    ) -> zx_status_t;
 
     pub fn fdio_fd_clone(fd: c_int, out_handle: *mut zx_handle_t) -> zx_status_t;
     pub fn fdio_fd_create(handle: zx_handle_t, fd: *mut c_int) -> zx_status_t;
@@ -129,60 +147,74 @@ pub const FDIO_SPAWN_ACTION_TRANSFER_FD: u32 = 0x0002;
 
 // Errors
 
-#[allow(unused)] pub const ERR_INTERNAL: zx_status_t = -1;
+#[allow(unused)]
+pub const ERR_INTERNAL: zx_status_t = -1;
 
 // ERR_NOT_SUPPORTED: The operation is not implemented, supported,
 // or enabled.
-#[allow(unused)] pub const ERR_NOT_SUPPORTED: zx_status_t = -2;
+#[allow(unused)]
+pub const ERR_NOT_SUPPORTED: zx_status_t = -2;
 
 // ERR_NO_RESOURCES: The system was not able to allocate some resource
 // needed for the operation.
-#[allow(unused)] pub const ERR_NO_RESOURCES: zx_status_t = -3;
+#[allow(unused)]
+pub const ERR_NO_RESOURCES: zx_status_t = -3;
 
 // ERR_NO_MEMORY: The system was not able to allocate memory needed
 // for the operation.
-#[allow(unused)] pub const ERR_NO_MEMORY: zx_status_t = -4;
+#[allow(unused)]
+pub const ERR_NO_MEMORY: zx_status_t = -4;
 
 // ERR_CALL_FAILED: The second phase of zx_channel_call(; did not complete
 // successfully.
-#[allow(unused)] pub const ERR_CALL_FAILED: zx_status_t = -5;
+#[allow(unused)]
+pub const ERR_CALL_FAILED: zx_status_t = -5;
 
 // ERR_INTERRUPTED_RETRY: The system call was interrupted, but should be
 // retried.  This should not be seen outside of the VDSO.
-#[allow(unused)] pub const ERR_INTERRUPTED_RETRY: zx_status_t = -6;
+#[allow(unused)]
+pub const ERR_INTERRUPTED_RETRY: zx_status_t = -6;
 
 // ======= Parameter errors =======
 // ERR_INVALID_ARGS: an argument is invalid, ex. null pointer
-#[allow(unused)] pub const ERR_INVALID_ARGS: zx_status_t = -10;
+#[allow(unused)]
+pub const ERR_INVALID_ARGS: zx_status_t = -10;
 
 // ERR_BAD_HANDLE: A specified handle value does not refer to a handle.
-#[allow(unused)] pub const ERR_BAD_HANDLE: zx_status_t = -11;
+#[allow(unused)]
+pub const ERR_BAD_HANDLE: zx_status_t = -11;
 
 // ERR_WRONG_TYPE: The subject of the operation is the wrong type to
 // perform the operation.
 // Example: Attempting a message_read on a thread handle.
-#[allow(unused)] pub const ERR_WRONG_TYPE: zx_status_t = -12;
+#[allow(unused)]
+pub const ERR_WRONG_TYPE: zx_status_t = -12;
 
 // ERR_BAD_SYSCALL: The specified syscall number is invalid.
-#[allow(unused)] pub const ERR_BAD_SYSCALL: zx_status_t = -13;
+#[allow(unused)]
+pub const ERR_BAD_SYSCALL: zx_status_t = -13;
 
 // ERR_OUT_OF_RANGE: An argument is outside the valid range for this
 // operation.
-#[allow(unused)] pub const ERR_OUT_OF_RANGE: zx_status_t = -14;
+#[allow(unused)]
+pub const ERR_OUT_OF_RANGE: zx_status_t = -14;
 
 // ERR_BUFFER_TOO_SMALL: A caller provided buffer is too small for
 // this operation.
-#[allow(unused)] pub const ERR_BUFFER_TOO_SMALL: zx_status_t = -15;
+#[allow(unused)]
+pub const ERR_BUFFER_TOO_SMALL: zx_status_t = -15;
 
 // ======= Precondition or state errors =======
 // ERR_BAD_STATE: operation failed because the current state of the
 // object does not allow it, or a precondition of the operation is
 // not satisfied
-#[allow(unused)] pub const ERR_BAD_STATE: zx_status_t = -20;
+#[allow(unused)]
+pub const ERR_BAD_STATE: zx_status_t = -20;
 
 // ERR_TIMED_OUT: The time limit for the operation elapsed before
 // the operation completed.
-#[allow(unused)] pub const ERR_TIMED_OUT: zx_status_t = -21;
+#[allow(unused)]
+pub const ERR_TIMED_OUT: zx_status_t = -21;
 
 // ERR_SHOULD_WAIT: The operation cannot be performed currently but
 // potentially could succeed if the caller waits for a prerequisite
@@ -192,67 +224,84 @@ pub const FDIO_SPAWN_ACTION_TRANSFER_FD: u32 = 0x0002;
 // messages waiting but has an open remote will return ERR_SHOULD_WAIT.
 // Attempting to read from a message pipe that has no messages waiting
 // and has a closed remote end will return ERR_REMOTE_CLOSED.
-#[allow(unused)] pub const ERR_SHOULD_WAIT: zx_status_t = -22;
+#[allow(unused)]
+pub const ERR_SHOULD_WAIT: zx_status_t = -22;
 
 // ERR_CANCELED: The in-progress operation (e.g., a wait) has been
 // // canceled.
-#[allow(unused)] pub const ERR_CANCELED: zx_status_t = -23;
+#[allow(unused)]
+pub const ERR_CANCELED: zx_status_t = -23;
 
 // ERR_PEER_CLOSED: The operation failed because the remote end
 // of the subject of the operation was closed.
-#[allow(unused)] pub const ERR_PEER_CLOSED: zx_status_t = -24;
+#[allow(unused)]
+pub const ERR_PEER_CLOSED: zx_status_t = -24;
 
 // ERR_NOT_FOUND: The requested entity is not found.
-#[allow(unused)] pub const ERR_NOT_FOUND: zx_status_t = -25;
+#[allow(unused)]
+pub const ERR_NOT_FOUND: zx_status_t = -25;
 
 // ERR_ALREADY_EXISTS: An object with the specified identifier
 // already exists.
 // Example: Attempting to create a file when a file already exists
 // with that name.
-#[allow(unused)] pub const ERR_ALREADY_EXISTS: zx_status_t = -26;
+#[allow(unused)]
+pub const ERR_ALREADY_EXISTS: zx_status_t = -26;
 
 // ERR_ALREADY_BOUND: The operation failed because the named entity
 // is already owned or controlled by another entity. The operation
 // could succeed later if the current owner releases the entity.
-#[allow(unused)] pub const ERR_ALREADY_BOUND: zx_status_t = -27;
+#[allow(unused)]
+pub const ERR_ALREADY_BOUND: zx_status_t = -27;
 
 // ERR_UNAVAILABLE: The subject of the operation is currently unable
 // to perform the operation.
 // Note: This is used when there's no direct way for the caller to
 // observe when the subject will be able to perform the operation
 // and should thus retry.
-#[allow(unused)] pub const ERR_UNAVAILABLE: zx_status_t = -28;
+#[allow(unused)]
+pub const ERR_UNAVAILABLE: zx_status_t = -28;
 
 // ======= Permission check errors =======
 // ERR_ACCESS_DENIED: The caller did not have permission to perform
 // the specified operation.
-#[allow(unused)] pub const ERR_ACCESS_DENIED: zx_status_t = -30;
+#[allow(unused)]
+pub const ERR_ACCESS_DENIED: zx_status_t = -30;
 
 // ======= Input-output errors =======
 // ERR_IO: Otherwise unspecified error occurred during I/O.
-#[allow(unused)] pub const ERR_IO: zx_status_t = -40;
+#[allow(unused)]
+pub const ERR_IO: zx_status_t = -40;
 
 // ERR_REFUSED: The entity the I/O operation is being performed on
 // rejected the operation.
 // Example: an I2C device NAK'ing a transaction or a disk controller
 // rejecting an invalid command.
-#[allow(unused)] pub const ERR_IO_REFUSED: zx_status_t = -41;
+#[allow(unused)]
+pub const ERR_IO_REFUSED: zx_status_t = -41;
 
 // ERR_IO_DATA_INTEGRITY: The data in the operation failed an integrity
 // check and is possibly corrupted.
 // Example: CRC or Parity error.
-#[allow(unused)] pub const ERR_IO_DATA_INTEGRITY: zx_status_t = -42;
+#[allow(unused)]
+pub const ERR_IO_DATA_INTEGRITY: zx_status_t = -42;
 
 // ERR_IO_DATA_LOSS: The data in the operation is currently unavailable
 // and may be permanently lost.
 // Example: A disk block is irrecoverably damaged.
-#[allow(unused)] pub const ERR_IO_DATA_LOSS: zx_status_t = -43;
+#[allow(unused)]
+pub const ERR_IO_DATA_LOSS: zx_status_t = -43;
 
 // Filesystem specific errors
-#[allow(unused)] pub const ERR_BAD_PATH: zx_status_t = -50;
-#[allow(unused)] pub const ERR_NOT_DIR: zx_status_t = -51;
-#[allow(unused)] pub const ERR_NOT_FILE: zx_status_t = -52;
+#[allow(unused)]
+pub const ERR_BAD_PATH: zx_status_t = -50;
+#[allow(unused)]
+pub const ERR_NOT_DIR: zx_status_t = -51;
+#[allow(unused)]
+pub const ERR_NOT_FILE: zx_status_t = -52;
 // ERR_FILE_BIG: A file exceeds a filesystem-specific size limit.
-#[allow(unused)] pub const ERR_FILE_BIG: zx_status_t = -53;
+#[allow(unused)]
+pub const ERR_FILE_BIG: zx_status_t = -53;
 // ERR_NO_SPACE: Filesystem or device space is exhausted.
-#[allow(unused)] pub const ERR_NO_SPACE: zx_status_t = -54;
+#[allow(unused)]
+pub const ERR_NO_SPACE: zx_status_t = -54;
diff --git a/src/libstd/sys/unix/rand.rs b/src/libstd/sys/unix/rand.rs
index bc387544c4c..9ce5f3d014c 100644
--- a/src/libstd/sys/unix/rand.rs
+++ b/src/libstd/sys/unix/rand.rs
@@ -4,20 +4,21 @@ use crate::slice;
 pub fn hashmap_random_keys() -> (u64, u64) {
     let mut v = (0, 0);
     unsafe {
-        let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8,
-                                             mem::size_of_val(&v));
+        let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
         imp::fill_bytes(view);
     }
     v
 }
 
-#[cfg(all(unix,
-          not(target_os = "ios"),
-          not(target_os = "openbsd"),
-          not(target_os = "freebsd"),
-          not(target_os = "netbsd"),
-          not(target_os = "fuchsia"),
-          not(target_os = "redox")))]
+#[cfg(all(
+    unix,
+    not(target_os = "ios"),
+    not(target_os = "openbsd"),
+    not(target_os = "freebsd"),
+    not(target_os = "netbsd"),
+    not(target_os = "fuchsia"),
+    not(target_os = "redox")
+))]
 mod imp {
     use crate::fs::File;
     use crate::io::Read;
@@ -30,7 +31,9 @@ mod imp {
     }
 
     #[cfg(not(any(target_os = "linux", target_os = "android")))]
-    fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false }
+    fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
+        false
+    }
 
     #[cfg(any(target_os = "linux", target_os = "android"))]
     fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
@@ -96,9 +99,7 @@ mod imp {
     pub fn fill_bytes(v: &mut [u8]) {
         // getentropy(2) permits a maximum buffer size of 256 bytes
         for s in v.chunks_mut(256) {
-            let ret = unsafe {
-                libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
-            };
+            let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
             if ret == -1 {
                 panic!("unexpected getentropy error: {}", errno());
             }
@@ -124,21 +125,14 @@ mod imp {
     #[allow(non_upper_case_globals)]
     const kSecRandomDefault: *const SecRandom = ptr::null();
 
-    extern {
-        fn SecRandomCopyBytes(rnd: *const SecRandom,
-                              count: size_t,
-                              bytes: *mut u8) -> c_int;
+    extern "C" {
+        fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
     }
 
     pub fn fill_bytes(v: &mut [u8]) {
-        let ret = unsafe {
-            SecRandomCopyBytes(kSecRandomDefault,
-                               v.len(),
-                               v.as_mut_ptr())
-        };
+        let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
         if ret == -1 {
-            panic!("couldn't generate random bytes: {}",
-                   io::Error::last_os_error());
+            panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
         }
     }
 }
@@ -153,13 +147,22 @@ mod imp {
         for s in v.chunks_mut(256) {
             let mut s_len = s.len();
             let ret = unsafe {
-                libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
-                             s.as_mut_ptr() as *mut _, &mut s_len,
-                             ptr::null(), 0)
+                libc::sysctl(
+                    mib.as_ptr(),
+                    mib.len() as libc::c_uint,
+                    s.as_mut_ptr() as *mut _,
+                    &mut s_len,
+                    ptr::null(),
+                    0,
+                )
             };
             if ret == -1 || s_len != s.len() {
-                panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
-                       ret, s.len(), s_len);
+                panic!(
+                    "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
+                    ret,
+                    s.len(),
+                    s_len
+                );
             }
         }
     }
@@ -168,7 +171,7 @@ mod imp {
 #[cfg(target_os = "fuchsia")]
 mod imp {
     #[link(name = "zircon")]
-    extern {
+    extern "C" {
         fn zx_cprng_draw(buffer: *mut u8, len: usize);
     }
 
diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs
index fe1095fa0c2..528fe321efb 100644
--- a/src/libstd/sys/unix/stack_overflow.rs
+++ b/src/libstd/sys/unix/stack_overflow.rs
@@ -1,12 +1,12 @@
 #![cfg_attr(test, allow(dead_code))]
 
-use self::imp::{make_handler, drop_handler};
+use self::imp::{drop_handler, make_handler};
 
 pub use self::imp::cleanup;
 pub use self::imp::init;
 
 pub struct Handler {
-    _data: *mut libc::c_void
+    _data: *mut libc::c_void,
 }
 
 impl Handler {
@@ -23,28 +23,28 @@ impl Drop for Handler {
     }
 }
 
-#[cfg(any(target_os = "linux",
-          target_os = "macos",
-          target_os = "dragonfly",
-          target_os = "freebsd",
-          target_os = "solaris",
-          all(target_os = "netbsd", not(target_vendor = "rumprun")),
-          target_os = "openbsd"))]
+#[cfg(any(
+    target_os = "linux",
+    target_os = "macos",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "solaris",
+    all(target_os = "netbsd", not(target_vendor = "rumprun")),
+    target_os = "openbsd"
+))]
 mod imp {
     use super::Handler;
     use crate::mem;
     use crate::ptr;
 
-    use libc::{sigaltstack, SIGSTKSZ, SS_DISABLE};
-    use libc::{sigaction, SIGBUS, SIG_DFL,
-               SA_SIGINFO, SA_ONSTACK, sighandler_t};
-    use libc::{mmap, munmap};
-    use libc::{SIGSEGV, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON};
     use libc::MAP_FAILED;
+    use libc::{mmap, munmap};
+    use libc::{sigaction, sighandler_t, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIG_DFL};
+    use libc::{sigaltstack, SIGSTKSZ, SS_DISABLE};
+    use libc::{MAP_ANON, MAP_PRIVATE, PROT_READ, PROT_WRITE, SIGSEGV};
 
     use crate::sys_common::thread_info;
 
-
     #[cfg(any(target_os = "linux", target_os = "android"))]
     unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> usize {
         #[repr(C)]
@@ -82,9 +82,11 @@ mod imp {
     // out many large systems and all implementations allow returning from a
     // signal handler to work. For a more detailed explanation see the
     // comments on #26458.
-    unsafe extern fn signal_handler(signum: libc::c_int,
-                                    info: *mut libc::siginfo_t,
-                                    _data: *mut libc::c_void) {
+    unsafe extern "C" fn signal_handler(
+        signum: libc::c_int,
+        info: *mut libc::siginfo_t,
+        _data: *mut libc::c_void,
+    ) {
         use crate::sys_common::util::report_overflow;
 
         let guard = thread_info::stack_guard().unwrap_or(0..0);
@@ -124,24 +126,22 @@ mod imp {
     }
 
     unsafe fn get_stackp() -> *mut libc::c_void {
-        let stackp = mmap(ptr::null_mut(),
-                          SIGSTKSZ,
-                          PROT_READ | PROT_WRITE,
-                          MAP_PRIVATE | MAP_ANON,
-                          -1,
-                          0);
+        let stackp =
+            mmap(ptr::null_mut(), SIGSTKSZ, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
         if stackp == MAP_FAILED {
             panic!("failed to allocate an alternative stack");
         }
         stackp
     }
 
-    #[cfg(any(target_os = "linux",
-              target_os = "macos",
-              target_os = "freebsd",
-              target_os = "netbsd",
-              target_os = "openbsd",
-              target_os = "solaris"))]
+    #[cfg(any(
+        target_os = "linux",
+        target_os = "macos",
+        target_os = "freebsd",
+        target_os = "netbsd",
+        target_os = "openbsd",
+        target_os = "solaris"
+    ))]
     unsafe fn get_stack() -> libc::stack_t {
         libc::stack_t { ss_sp: get_stackp(), ss_flags: 0, ss_size: SIGSTKSZ }
     }
@@ -166,7 +166,7 @@ mod imp {
 
     pub unsafe fn drop_handler(handler: &mut Handler) {
         if !handler._data.is_null() {
-            let stack =  libc::stack_t {
+            let stack = libc::stack_t {
                 ss_sp: ptr::null_mut(),
                 ss_flags: SS_DISABLE,
                 // Workaround for bug in macOS implementation of sigaltstack
@@ -181,26 +181,25 @@ mod imp {
     }
 }
 
-#[cfg(not(any(target_os = "linux",
-              target_os = "macos",
-              target_os = "dragonfly",
-              target_os = "freebsd",
-              target_os = "solaris",
-              all(target_os = "netbsd", not(target_vendor = "rumprun")),
-              target_os = "openbsd")))]
+#[cfg(not(any(
+    target_os = "linux",
+    target_os = "macos",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "solaris",
+    all(target_os = "netbsd", not(target_vendor = "rumprun")),
+    target_os = "openbsd"
+)))]
 mod imp {
     use crate::ptr;
 
-    pub unsafe fn init() {
-    }
+    pub unsafe fn init() {}
 
-    pub unsafe fn cleanup() {
-    }
+    pub unsafe fn cleanup() {}
 
     pub unsafe fn make_handler() -> super::Handler {
         super::Handler { _data: ptr::null_mut() }
     }
 
-    pub unsafe fn drop_handler(_handler: &mut super::Handler) {
-    }
+    pub unsafe fn drop_handler(_handler: &mut super::Handler) {}
 }
diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs
index f9b017df240..b9c56963885 100644
--- a/src/libstd/sys/unix/stdio.rs
+++ b/src/libstd/sys/unix/stdio.rs
@@ -1,13 +1,15 @@
 use crate::io::{self, IoSlice, IoSliceMut};
-use crate::sys::fd::FileDesc;
 use crate::mem::ManuallyDrop;
+use crate::sys::fd::FileDesc;
 
 pub struct Stdin(());
 pub struct Stdout(());
 pub struct Stderr(());
 
 impl Stdin {
-    pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
+    pub fn new() -> io::Result<Stdin> {
+        Ok(Stdin(()))
+    }
 }
 
 impl io::Read for Stdin {
@@ -21,7 +23,9 @@ impl io::Read for Stdin {
 }
 
 impl Stdout {
-    pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
+    pub fn new() -> io::Result<Stdout> {
+        Ok(Stdout(()))
+    }
 }
 
 impl io::Write for Stdout {
@@ -39,7 +43,9 @@ impl io::Write for Stdout {
 }
 
 impl Stderr {
-    pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
+    pub fn new() -> io::Result<Stderr> {
+        Ok(Stderr(()))
+    }
 }
 
 impl io::Write for Stderr {
diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs
index 72b0ac493da..a5b34eeec28 100644
--- a/src/libstd/sys/unix/thread.rs
+++ b/src/libstd/sys/unix/thread.rs
@@ -25,21 +25,24 @@ unsafe impl Sync for Thread {}
 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
 #[cfg(not(target_os = "emscripten"))]
-unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
-                                    stack_size: libc::size_t) -> libc::c_int {
+unsafe fn pthread_attr_setstacksize(
+    attr: *mut libc::pthread_attr_t,
+    stack_size: libc::size_t,
+) -> libc::c_int {
     libc::pthread_attr_setstacksize(attr, stack_size)
 }
 
 #[cfg(target_os = "emscripten")]
-unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t,
-                                    _stack_size: libc::size_t) -> libc::c_int {
+unsafe fn pthread_attr_setstacksize(
+    _attr: *mut libc::pthread_attr_t,
+    _stack_size: libc::size_t,
+) -> libc::c_int {
     panic!()
 }
 
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
-    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>)
-                          -> io::Result<Thread> {
+    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         let p = box p;
         let mut native: libc::pthread_t = mem::zeroed();
         let mut attr: libc::pthread_attr_t = mem::zeroed();
@@ -47,8 +50,7 @@ impl Thread {
 
         let stack_size = cmp::max(stack, min_stack_size(&attr));
 
-        match pthread_attr_setstacksize(&mut attr,
-                                        stack_size) {
+        match pthread_attr_setstacksize(&mut attr, stack_size) {
             0 => {}
             n => {
                 assert_eq!(n, libc::EINVAL);
@@ -57,15 +59,13 @@ impl Thread {
                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
                 // Round up to the nearest page and try again.
                 let page_size = os::page_size();
-                let stack_size = (stack_size + page_size - 1) &
-                                 (-(page_size as isize - 1) as usize - 1);
-                assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
-                                                           stack_size), 0);
+                let stack_size =
+                    (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
+                assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
             }
         };
 
-        let ret = libc::pthread_create(&mut native, &attr, thread_start,
-                                       &*p as *const _ as *mut _);
+        let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
 
         return if ret != 0 {
@@ -75,8 +75,10 @@ impl Thread {
             Ok(Thread { id: native })
         };
 
-        extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
-            unsafe { start_thread(main as *mut u8); }
+        extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
+            unsafe {
+                start_thread(main as *mut u8);
+            }
             ptr::null_mut()
         }
     }
@@ -86,8 +88,7 @@ impl Thread {
         debug_assert_eq!(ret, 0);
     }
 
-    #[cfg(any(target_os = "linux",
-              target_os = "android"))]
+    #[cfg(any(target_os = "linux", target_os = "android"))]
     pub fn set_name(name: &CStr) {
         const PR_SET_NAME: libc::c_int = 15;
         // pthread wrapper only appeared in glibc 2.12, so we use syscall
@@ -97,9 +98,7 @@ impl Thread {
         }
     }
 
-    #[cfg(any(target_os = "freebsd",
-              target_os = "dragonfly",
-              target_os = "openbsd"))]
+    #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
     pub fn set_name(name: &CStr) {
         unsafe {
             libc::pthread_set_name_np(libc::pthread_self(), name.as_ptr());
@@ -118,8 +117,11 @@ impl Thread {
         use crate::ffi::CString;
         let cname = CString::new(&b"%s"[..]).unwrap();
         unsafe {
-            libc::pthread_setname_np(libc::pthread_self(), cname.as_ptr(),
-                                     name.as_ptr() as *mut libc::c_void);
+            libc::pthread_setname_np(
+                libc::pthread_self(),
+                cname.as_ptr(),
+                name.as_ptr() as *mut libc::c_void,
+            );
         }
     }
 
@@ -132,15 +134,19 @@ impl Thread {
         }
 
         if let Some(f) = pthread_setname_np.get() {
-            unsafe { f(libc::pthread_self(), name.as_ptr()); }
+            unsafe {
+                f(libc::pthread_self(), name.as_ptr());
+            }
         }
     }
 
-    #[cfg(any(target_env = "newlib",
-              target_os = "haiku",
-              target_os = "l4re",
-              target_os = "emscripten",
-              target_os = "redox"))]
+    #[cfg(any(
+        target_env = "newlib",
+        target_os = "haiku",
+        target_os = "l4re",
+        target_os = "emscripten",
+        target_os = "redox"
+    ))]
     pub fn set_name(_name: &CStr) {
         // Newlib, Illumos, Haiku, and Emscripten have no way to set a thread name.
     }
@@ -177,12 +183,13 @@ impl Thread {
         unsafe {
             let ret = libc::pthread_join(self.id, ptr::null_mut());
             mem::forget(self);
-            assert!(ret == 0,
-                    "failed to join thread: {}", io::Error::from_raw_os_error(ret));
+            assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
         }
     }
 
-    pub fn id(&self) -> libc::pthread_t { self.id }
+    pub fn id(&self) -> libc::pthread_t {
+        self.id
+    }
 
     pub fn into_id(self) -> libc::pthread_t {
         let id = self.id;
@@ -198,31 +205,38 @@ impl Drop for Thread {
     }
 }
 
-#[cfg(all(not(all(target_os = "linux", not(target_env = "musl"))),
-          not(target_os = "freebsd"),
-          not(target_os = "macos"),
-          not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
-          not(target_os = "openbsd"),
-          not(target_os = "solaris")))]
+#[cfg(all(
+    not(all(target_os = "linux", not(target_env = "musl"))),
+    not(target_os = "freebsd"),
+    not(target_os = "macos"),
+    not(all(target_os = "netbsd", not(target_vendor = "rumprun"))),
+    not(target_os = "openbsd"),
+    not(target_os = "solaris")
+))]
 #[cfg_attr(test, allow(dead_code))]
 pub mod guard {
     use crate::ops::Range;
     pub type Guard = Range<usize>;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
 }
 
-
-#[cfg(any(all(target_os = "linux", not(target_env = "musl")),
-          target_os = "freebsd",
-          target_os = "macos",
-          all(target_os = "netbsd", not(target_vendor = "rumprun")),
-          target_os = "openbsd",
-          target_os = "solaris"))]
+#[cfg(any(
+    all(target_os = "linux", not(target_env = "musl")),
+    target_os = "freebsd",
+    target_os = "macos",
+    all(target_os = "netbsd", not(target_vendor = "rumprun")),
+    target_os = "openbsd",
+    target_os = "solaris"
+))]
 #[cfg_attr(test, allow(dead_code))]
 pub mod guard {
     use libc::{mmap, mprotect};
-    use libc::{PROT_NONE, PROT_READ, PROT_WRITE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED};
+    use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE};
 
     use crate::ops::Range;
     use crate::sys::os;
@@ -241,16 +255,15 @@ pub mod guard {
 
     #[cfg(target_os = "macos")]
     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
-        let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize -
-             libc::pthread_get_stacksize_np(libc::pthread_self());
+        let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize
+            - libc::pthread_get_stacksize_np(libc::pthread_self());
         Some(stackaddr as *mut libc::c_void)
     }
 
     #[cfg(target_os = "openbsd")]
     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
         let mut current_stack: libc::stack_t = crate::mem::zeroed();
-        assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(),
-                                             &mut current_stack), 0);
+        assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), &mut current_stack), 0);
 
         let stackaddr = if libc::pthread_main_np() == 1 {
             // main thread
@@ -262,21 +275,25 @@ pub mod guard {
         Some(stackaddr as *mut libc::c_void)
     }
 
-    #[cfg(any(target_os = "android", target_os = "freebsd",
-              target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
+    #[cfg(any(
+        target_os = "android",
+        target_os = "freebsd",
+        target_os = "linux",
+        target_os = "netbsd",
+        target_os = "l4re"
+    ))]
     unsafe fn get_stack_start() -> Option<*mut libc::c_void> {
         let mut ret = None;
         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
         #[cfg(target_os = "freebsd")]
-            let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
+        let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
         #[cfg(not(target_os = "freebsd"))]
-            let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
+        let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
         if e == 0 {
             let mut stackaddr = crate::ptr::null_mut();
             let mut stacksize = 0;
-            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
-                                                   &mut stacksize), 0);
+            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize), 0);
             ret = Some(stackaddr);
         }
         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
@@ -329,8 +346,14 @@ pub mod guard {
             // than the initial mmap() used, so we mmap() here with
             // read/write permissions and only then mprotect() it to
             // no permissions at all. See issue #50313.
-            let result = mmap(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE,
-                              MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0);
+            let result = mmap(
+                stackaddr,
+                PAGE_SIZE,
+                PROT_READ | PROT_WRITE,
+                MAP_PRIVATE | MAP_ANON | MAP_FIXED,
+                -1,
+                0,
+            );
             if result != stackaddr || result == MAP_FAILED {
                 panic!("failed to allocate a guard page");
             }
@@ -341,34 +364,33 @@ pub mod guard {
             }
 
             let guardaddr = stackaddr as usize;
-            let offset = if cfg!(target_os = "freebsd") {
-                2
-            } else {
-                1
-            };
+            let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 };
 
             Some(guardaddr..guardaddr + offset * PAGE_SIZE)
         }
     }
 
-    #[cfg(any(target_os = "macos",
-              target_os = "openbsd",
-              target_os = "solaris"))]
+    #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "solaris"))]
     pub unsafe fn current() -> Option<Guard> {
         let stackaddr = get_stack_start()? as usize;
         Some(stackaddr - PAGE_SIZE..stackaddr)
     }
 
-    #[cfg(any(target_os = "android", target_os = "freebsd",
-              target_os = "linux", target_os = "netbsd", target_os = "l4re"))]
+    #[cfg(any(
+        target_os = "android",
+        target_os = "freebsd",
+        target_os = "linux",
+        target_os = "netbsd",
+        target_os = "l4re"
+    ))]
     pub unsafe fn current() -> Option<Guard> {
         let mut ret = None;
         let mut attr: libc::pthread_attr_t = crate::mem::zeroed();
         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
         #[cfg(target_os = "freebsd")]
-            let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
+        let e = libc::pthread_attr_get_np(libc::pthread_self(), &mut attr);
         #[cfg(not(target_os = "freebsd"))]
-            let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
+        let e = libc::pthread_getattr_np(libc::pthread_self(), &mut attr);
         if e == 0 {
             let mut guardsize = 0;
             assert_eq!(libc::pthread_attr_getguardsize(&attr, &mut guardsize), 0);
@@ -377,8 +399,7 @@ pub mod guard {
             }
             let mut stackaddr = crate::ptr::null_mut();
             let mut size = 0;
-            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr,
-                                                   &mut size), 0);
+            assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0);
 
             let stackaddr = stackaddr as usize;
             ret = if cfg!(target_os = "freebsd") {
@@ -422,8 +443,7 @@ fn min_stack_size(attr: *const libc::pthread_attr_t) -> usize {
 
 // No point in looking up __pthread_get_minstack() on non-glibc
 // platforms.
-#[cfg(all(not(target_os = "linux"),
-          not(target_os = "netbsd")))]
+#[cfg(all(not(target_os = "linux"), not(target_os = "netbsd")))]
 fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
     libc::PTHREAD_STACK_MIN
 }
diff --git a/src/libstd/sys/unix/thread_local.rs b/src/libstd/sys/unix/thread_local.rs
index ac615b76b36..2c5b94b1e61 100644
--- a/src/libstd/sys/unix/thread_local.rs
+++ b/src/libstd/sys/unix/thread_local.rs
@@ -5,7 +5,7 @@ use crate::mem;
 pub type Key = libc::pthread_key_t;
 
 #[inline]
-pub unsafe fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+pub unsafe fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
     let mut key = 0;
     assert_eq!(libc::pthread_key_create(&mut key, mem::transmute(dtor)), 0);
     key
diff --git a/src/libstd/sys/unix/weak.rs b/src/libstd/sys/unix/weak.rs
index 9a7691e54bc..08cbe596174 100644
--- a/src/libstd/sys/unix/weak.rs
+++ b/src/libstd/sys/unix/weak.rs
@@ -36,11 +36,7 @@ pub struct Weak<F> {
 
 impl<F> Weak<F> {
     pub const fn new(name: &'static str) -> Weak<F> {
-        Weak {
-            name,
-            addr: AtomicUsize::new(1),
-            _marker: marker::PhantomData,
-        }
+        Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData }
     }
 
     pub fn get(&self) -> Option<F> {
diff --git a/src/libstd/sys/vxworks/alloc.rs b/src/libstd/sys/vxworks/alloc.rs
index e0c560b9214..97a191d7232 100644
--- a/src/libstd/sys/vxworks/alloc.rs
+++ b/src/libstd/sys/vxworks/alloc.rs
@@ -1,6 +1,6 @@
-use crate::ptr;
-use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
 use crate::alloc::{GlobalAlloc, Layout, System};
+use crate::ptr;
+use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN};
 
 #[stable(feature = "alloc_system_type", since = "1.28.0")]
 unsafe impl GlobalAlloc for System {
@@ -45,9 +45,5 @@ unsafe impl GlobalAlloc for System {
 unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
     let mut out = ptr::null_mut();
     let ret = libc::posix_memalign(&mut out, layout.align(), layout.size());
-    if ret != 0 {
-        ptr::null_mut()
-    } else {
-        out as *mut u8
-    }
+    if ret != 0 { ptr::null_mut() } else { out as *mut u8 }
 }
diff --git a/src/libstd/sys/vxworks/args.rs b/src/libstd/sys/vxworks/args.rs
index 11c3cb78819..efd615f404d 100644
--- a/src/libstd/sys/vxworks/args.rs
+++ b/src/libstd/sys/vxworks/args.rs
@@ -4,10 +4,14 @@ use crate::marker::PhantomData;
 use crate::vec;
 
 /// One-time global initialization.
-pub unsafe fn init(argc: isize, argv: *const *const u8) { imp::init(argc, argv) }
+pub unsafe fn init(argc: isize, argv: *const *const u8) {
+    imp::init(argc, argv)
+}
 
 /// One-time global cleanup.
-pub unsafe fn cleanup() { imp::cleanup() }
+pub unsafe fn cleanup() {
+    imp::cleanup()
+}
 
 /// Returns the command line arguments
 pub fn args() -> Args {
@@ -27,24 +31,32 @@ impl Args {
 
 impl Iterator for Args {
     type Item = OsString;
-    fn next(&mut self) -> Option<OsString> { self.iter.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<OsString> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
 }
 
 impl ExactSizeIterator for Args {
-    fn len(&self) -> usize { self.iter.len() }
+    fn len(&self) -> usize {
+        self.iter.len()
+    }
 }
 
 impl DoubleEndedIterator for Args {
-    fn next_back(&mut self) -> Option<OsString> { self.iter.next_back() }
+    fn next_back(&mut self) -> Option<OsString> {
+        self.iter.next_back()
+    }
 }
 
 mod imp {
-    use crate::ptr;
+    use super::Args;
     use crate::ffi::{CStr, OsString};
     use crate::marker::PhantomData;
+    use crate::ptr;
     use libc;
-    use super::Args;
 
     use crate::sys_common::mutex::Mutex;
 
@@ -65,21 +77,20 @@ mod imp {
     }
 
     pub fn args() -> Args {
-        Args {
-            iter: clone().into_iter(),
-            _dont_send_or_sync_me: PhantomData
-        }
+        Args { iter: clone().into_iter(), _dont_send_or_sync_me: PhantomData }
     }
 
     fn clone() -> Vec<OsString> {
         unsafe {
             let _guard = LOCK.lock();
-            let ret = (0..ARGC).map(|i| {
-                let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char);
-                use crate::sys::vxworks::ext::ffi::OsStringExt;
-                OsStringExt::from_vec(cstr.to_bytes().to_vec())
-            }).collect();
-            return ret
+            let ret = (0..ARGC)
+                .map(|i| {
+                    let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char);
+                    use crate::sys::vxworks::ext::ffi::OsStringExt;
+                    OsStringExt::from_vec(cstr.to_bytes().to_vec())
+                })
+                .collect();
+            return ret;
         }
     }
 }
diff --git a/src/libstd/sys/vxworks/cmath.rs b/src/libstd/sys/vxworks/cmath.rs
index f6bb58934fc..2916ebe4440 100644
--- a/src/libstd/sys/vxworks/cmath.rs
+++ b/src/libstd/sys/vxworks/cmath.rs
@@ -1,9 +1,9 @@
 #![cfg(not(test))]
 
-use libc::{c_float, c_double};
+use libc::{c_double, c_float};
 
 #[link_name = "m"]
-extern {
+extern "C" {
     pub fn acos(n: c_double) -> c_double;
     pub fn acosf(n: c_float) -> c_float;
     pub fn asin(n: c_double) -> c_double;
diff --git a/src/libstd/sys/vxworks/condvar.rs b/src/libstd/sys/vxworks/condvar.rs
index 783c3eb7c76..f2a1d681529 100644
--- a/src/libstd/sys/vxworks/condvar.rs
+++ b/src/libstd/sys/vxworks/condvar.rs
@@ -2,15 +2,15 @@ use crate::cell::UnsafeCell;
 use crate::sys::mutex::{self, Mutex};
 use crate::time::Duration;
 
-pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
+pub struct Condvar {
+    inner: UnsafeCell<libc::pthread_cond_t>,
+}
 
 unsafe impl Send for Condvar {}
 unsafe impl Sync for Condvar {}
 
-const TIMESPEC_MAX: libc::timespec = libc::timespec {
-    tv_sec: <libc::time_t>::max_value(),
-    tv_nsec: 1_000_000_000 - 1,
-};
+const TIMESPEC_MAX: libc::timespec =
+    libc::timespec { tv_sec: <libc::time_t>::max_value(), tv_nsec: 1_000_000_000 - 1 };
 
 fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
     if value > <libc::time_t>::max_value() as u64 {
@@ -77,17 +77,14 @@ impl Condvar {
             .and_then(|s| s.checked_add(now.tv_sec));
         let nsec = nsec % 1_000_000_000;
 
-        let timeout = sec.map(|s| {
-            libc::timespec { tv_sec: s, tv_nsec: nsec as _}
-        }).unwrap_or(TIMESPEC_MAX);
+        let timeout =
+            sec.map(|s| libc::timespec { tv_sec: s, tv_nsec: nsec as _ }).unwrap_or(TIMESPEC_MAX);
 
-        let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
-                                            &timeout);
+        let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex), &timeout);
         assert!(r == libc::ETIMEDOUT || r == 0);
         r == 0
     }
 
-
     #[inline]
     pub unsafe fn destroy(&self) {
         let r = libc::pthread_cond_destroy(self.inner.get());
diff --git a/src/libstd/sys/vxworks/ext/fs.rs b/src/libstd/sys/vxworks/ext/fs.rs
index 4a9cc3bd069..9864a855df7 100644
--- a/src/libstd/sys/vxworks/ext/fs.rs
+++ b/src/libstd/sys/vxworks/ext/fs.rs
@@ -2,11 +2,11 @@
 
 use crate::fs::{self, Permissions};
 use crate::io;
-use libc;
 use crate::path::Path;
 use crate::sys;
-use crate::sys_common::{FromInner, AsInner, AsInnerMut};
 use crate::sys::platform::fs::MetadataExt as UnixMetadataExt;
+use crate::sys_common::{AsInner, AsInnerMut, FromInner};
+use libc;
 
 /// Unix-specific extensions to [`File`].
 ///
@@ -112,8 +112,7 @@ pub trait FileExt {
             }
         }
         if !buf.is_empty() {
-            Err(io::Error::new(io::ErrorKind::UnexpectedEof,
-                               "failed to fill whole buffer"))
+            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
         } else {
             Ok(())
         }
@@ -196,8 +195,12 @@ pub trait FileExt {
     fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
         while !buf.is_empty() {
             match self.write_at(buf, offset) {
-                Ok(0) => return Err(io::Error::new(io::ErrorKind::WriteZero,
-                                                   "failed to write whole buffer")),
+                Ok(0) => {
+                    return Err(io::Error::new(
+                        io::ErrorKind::WriteZero,
+                        "failed to write whole buffer",
+                    ));
+                }
                 Ok(n) => {
                     buf = &buf[n..];
                     offset += n as u64
@@ -604,20 +607,48 @@ pub trait MetadataExt {
 
 #[stable(feature = "metadata_ext", since = "1.1.0")]
 impl MetadataExt for fs::Metadata {
-    fn dev(&self) -> u64 { self.st_dev() }
-    fn ino(&self) -> u64 { self.st_ino() }
-    fn mode(&self) -> u32 { self.st_mode() }
-    fn nlink(&self) -> u64 { self.st_nlink() }
-    fn uid(&self) -> u32 { self.st_uid() }
-    fn gid(&self) -> u32 { self.st_gid() }
-    fn rdev(&self) -> u64 { self.st_rdev() }
-    fn size(&self) -> u64 { self.st_size() }
-    fn atime(&self) -> i64 { self.st_atime() }
-    fn mtime(&self) -> i64 { self.st_mtime() }
-    fn ctime(&self) -> i64 { self.st_ctime() }
-    fn blksize(&self) -> u64 { self.st_blksize() }
-    fn blocks(&self) -> u64 { self.st_blocks() }
-    fn attrib(&self) -> u8 {self.st_attrib() }
+    fn dev(&self) -> u64 {
+        self.st_dev()
+    }
+    fn ino(&self) -> u64 {
+        self.st_ino()
+    }
+    fn mode(&self) -> u32 {
+        self.st_mode()
+    }
+    fn nlink(&self) -> u64 {
+        self.st_nlink()
+    }
+    fn uid(&self) -> u32 {
+        self.st_uid()
+    }
+    fn gid(&self) -> u32 {
+        self.st_gid()
+    }
+    fn rdev(&self) -> u64 {
+        self.st_rdev()
+    }
+    fn size(&self) -> u64 {
+        self.st_size()
+    }
+    fn atime(&self) -> i64 {
+        self.st_atime()
+    }
+    fn mtime(&self) -> i64 {
+        self.st_mtime()
+    }
+    fn ctime(&self) -> i64 {
+        self.st_ctime()
+    }
+    fn blksize(&self) -> u64 {
+        self.st_blksize()
+    }
+    fn blocks(&self) -> u64 {
+        self.st_blocks()
+    }
+    fn attrib(&self) -> u8 {
+        self.st_attrib()
+    }
 }
 
 /// Unix-specific extensions for [`FileType`].
@@ -704,10 +735,18 @@ pub trait FileTypeExt {
 
 #[stable(feature = "file_type_ext", since = "1.5.0")]
 impl FileTypeExt for fs::FileType {
-    fn is_block_device(&self) -> bool { self.as_inner().is(libc::S_IFBLK) }
-    fn is_char_device(&self) -> bool { self.as_inner().is(libc::S_IFCHR) }
-    fn is_fifo(&self) -> bool { self.as_inner().is(libc::S_IFIFO) }
-    fn is_socket(&self) -> bool { self.as_inner().is(libc::S_IFSOCK) }
+    fn is_block_device(&self) -> bool {
+        self.as_inner().is(libc::S_IFBLK)
+    }
+    fn is_char_device(&self) -> bool {
+        self.as_inner().is(libc::S_IFCHR)
+    }
+    fn is_fifo(&self) -> bool {
+        self.as_inner().is(libc::S_IFIFO)
+    }
+    fn is_socket(&self) -> bool {
+        self.as_inner().is(libc::S_IFSOCK)
+    }
 }
 
 /// Unix-specific extension methods for [`fs::DirEntry`].
@@ -739,7 +778,9 @@ pub trait DirEntryExt {
 
 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
 impl DirEntryExt for fs::DirEntry {
-    fn ino(&self) -> u64 { self.as_inner().ino() }
+    fn ino(&self) -> u64 {
+        self.as_inner().ino()
+    }
 }
 
 /// Creates a new symbolic link on the filesystem.
@@ -766,8 +807,7 @@ impl DirEntryExt for fs::DirEntry {
 /// }
 /// ```
 #[stable(feature = "symlink", since = "1.1.0")]
-pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>
-{
+pub fn symlink<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
     sys::fs::symlink(src.as_ref(), dst.as_ref())
 }
 
diff --git a/src/libstd/sys/vxworks/ext/io.rs b/src/libstd/sys/vxworks/ext/io.rs
index df6255a3e9e..25c6e26d96e 100644
--- a/src/libstd/sys/vxworks/ext/io.rs
+++ b/src/libstd/sys/vxworks/ext/io.rs
@@ -3,11 +3,11 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use crate::fs;
+use crate::io;
+use crate::net;
 use crate::os::raw;
 use crate::sys;
-use crate::io;
 use crate::sys_common::{self, AsInner, FromInner, IntoInner};
-use crate::net;
 
 /// Raw file descriptors.
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -84,47 +84,65 @@ impl IntoRawFd for fs::File {
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stdin {
-    fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDIN_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stdout {
-    fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDOUT_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio", since = "1.21.0")]
 impl AsRawFd for io::Stderr {
-    fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDERR_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StdinLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDIN_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StdoutLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDOUT_FILENO
+    }
 }
 
 #[stable(feature = "asraw_stdio_locks", since = "1.35.0")]
 impl<'a> AsRawFd for io::StderrLock<'a> {
-    fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO }
+    fn as_raw_fd(&self) -> RawFd {
+        libc::STDERR_FILENO
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl AsRawFd for net::TcpStream {
-    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
+    fn as_raw_fd(&self) -> RawFd {
+        *self.as_inner().socket().as_inner()
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl AsRawFd for net::TcpListener {
-    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
+    fn as_raw_fd(&self) -> RawFd {
+        *self.as_inner().socket().as_inner()
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl AsRawFd for net::UdpSocket {
-    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
+    fn as_raw_fd(&self) -> RawFd {
+        *self.as_inner().socket().as_inner()
+    }
 }
 
 #[stable(feature = "from_raw_os", since = "1.1.0")]
diff --git a/src/libstd/sys/vxworks/ext/mod.rs b/src/libstd/sys/vxworks/ext/mod.rs
index d0f467b303f..251a198f821 100644
--- a/src/libstd/sys/vxworks/ext/mod.rs
+++ b/src/libstd/sys/vxworks/ext/mod.rs
@@ -1,18 +1,21 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 #![allow(missing_docs)]
 
-pub mod io;
 pub mod ffi;
 pub mod fs;
-pub mod raw;
+pub mod io;
 pub mod process;
+pub mod raw;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub mod prelude {
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use super::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub use super::ffi::{OsStrExt, OsStringExt};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use super::fs::{PermissionsExt, OpenOptionsExt, MetadataExt, FileTypeExt};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use super::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use super::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
 }
diff --git a/src/libstd/sys/vxworks/ext/process.rs b/src/libstd/sys/vxworks/ext/process.rs
index 4de72fa1816..e535c4aa122 100644
--- a/src/libstd/sys/vxworks/ext/process.rs
+++ b/src/libstd/sys/vxworks/ext/process.rs
@@ -3,10 +3,10 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use crate::io;
-use crate::sys::vxworks::ext::io::{FromRawFd, RawFd, AsRawFd, IntoRawFd};
 use crate::process;
 use crate::sys;
-use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner};
+use crate::sys::vxworks::ext::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
+use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
 
 /// Unix-specific extensions to the [`process::Command`] builder.
 ///
@@ -55,7 +55,8 @@ pub trait CommandExt {
     /// locations may not appear where intended.
     #[stable(feature = "process_pre_exec", since = "1.34.0")]
     unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static;
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static;
 
     /// Schedules a closure to be run just before the `exec` function is
     /// invoked.
@@ -67,7 +68,8 @@ pub trait CommandExt {
     #[stable(feature = "process_exec", since = "1.15.0")]
     #[rustc_deprecated(since = "1.37.0", reason = "should be unsafe, use `pre_exec` instead")]
     fn before_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static,
     {
         unsafe { self.pre_exec(f) }
     }
@@ -118,7 +120,8 @@ impl CommandExt for process::Command {
     }
 
     unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
-        where F: FnMut() -> io::Result<()> + Send + Sync + 'static
+    where
+        F: FnMut() -> io::Result<()> + Send + Sync + 'static,
     {
         self.as_inner_mut().pre_exec(Box::new(f));
         self
diff --git a/src/libstd/sys/vxworks/fast_thread_local.rs b/src/libstd/sys/vxworks/fast_thread_local.rs
index 8b55939b8e5..387ebd0520a 100644
--- a/src/libstd/sys/vxworks/fast_thread_local.rs
+++ b/src/libstd/sys/vxworks/fast_thread_local.rs
@@ -1,7 +1,7 @@
 #![cfg(target_thread_local)]
 #![unstable(feature = "thread_local_internals", issue = "0")]
 
-pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) {
+pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
     use crate::sys_common::thread_local::register_dtor_fallback;
     register_dtor_fallback(t, dtor);
 }
diff --git a/src/libstd/sys/vxworks/fd.rs b/src/libstd/sys/vxworks/fd.rs
index db2865d2529..9b649aa7ef4 100644
--- a/src/libstd/sys/vxworks/fd.rs
+++ b/src/libstd/sys/vxworks/fd.rs
@@ -1,7 +1,7 @@
 #![unstable(reason = "not public", issue = "0", feature = "fd")]
 
 use crate::cmp;
-use crate::io::{self, Read, Initializer, IoSlice, IoSliceMut};
+use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read};
 use crate::mem;
 use crate::sys::cvt;
 use crate::sys_common::AsInner;
@@ -25,7 +25,9 @@ impl FileDesc {
         FileDesc { fd: fd }
     }
 
-    pub fn raw(&self) -> c_int { self.fd }
+    pub fn raw(&self) -> c_int {
+        self.fd
+    }
 
     /// Extracts the actual filedescriptor without closing it.
     pub fn into_raw(self) -> c_int {
@@ -36,18 +38,18 @@ impl FileDesc {
 
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::read(self.fd,
-                       buf.as_mut_ptr() as *mut c_void,
-                       cmp::min(buf.len(), max_len()))
+            libc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len()))
         })?;
         Ok(ret as usize)
     }
 
     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::readv(self.fd,
-                        bufs.as_ptr() as *const libc::iovec,
-                        cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
+            libc::readv(
+                self.fd,
+                bufs.as_ptr() as *const libc::iovec,
+                cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
+            )
         })?;
         Ok(ret as usize)
     }
@@ -58,61 +60,69 @@ impl FileDesc {
     }
 
     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
-        unsafe fn cvt_pread(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
-            -> io::Result<isize>
-        {
+        unsafe fn cvt_pread(
+            fd: c_int,
+            buf: *mut c_void,
+            count: usize,
+            offset: i64,
+        ) -> io::Result<isize> {
             use libc::pread;
             cvt(pread(fd, buf, count, offset))
         }
 
         unsafe {
-            cvt_pread(self.fd,
+            cvt_pread(
+                self.fd,
                 buf.as_mut_ptr() as *mut c_void,
                 cmp::min(buf.len(), max_len()),
-                offset as i64)
+                offset as i64,
+            )
             .map(|n| n as usize)
         }
     }
 
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::write(self.fd,
-            buf.as_ptr() as *const c_void,
-            cmp::min(buf.len(), max_len()))
+            libc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len()))
         })?;
         Ok(ret as usize)
     }
 
     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::writev(self.fd,
-                         bufs.as_ptr() as *const libc::iovec,
-                         cmp::min(bufs.len(), c_int::max_value() as usize) as c_int)
+            libc::writev(
+                self.fd,
+                bufs.as_ptr() as *const libc::iovec,
+                cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
+            )
         })?;
         Ok(ret as usize)
     }
 
     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
-        unsafe fn cvt_pwrite(fd: c_int, buf: *const c_void, count: usize, offset: i64)
-            -> io::Result<isize>
-        {
+        unsafe fn cvt_pwrite(
+            fd: c_int,
+            buf: *const c_void,
+            count: usize,
+            offset: i64,
+        ) -> io::Result<isize> {
             use libc::pwrite;
             cvt(pwrite(fd, buf, count, offset))
         }
 
         unsafe {
-            cvt_pwrite(self.fd,
+            cvt_pwrite(
+                self.fd,
                 buf.as_ptr() as *const c_void,
                 cmp::min(buf.len(), max_len()),
-                offset as i64)
-                .map(|n| n as usize)
+                offset as i64,
+            )
+            .map(|n| n as usize)
         }
     }
 
     pub fn get_cloexec(&self) -> io::Result<bool> {
-        unsafe {
-            Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0)
-        }
+        unsafe { Ok((cvt(libc::fcntl(self.fd, libc::F_GETFD))? & libc::FD_CLOEXEC) != 0) }
     }
 
     pub fn set_cloexec(&self) -> io::Result<()> {
@@ -139,23 +149,16 @@ impl FileDesc {
     pub fn set_nonblocking_pipe(&self, nonblocking: bool) -> io::Result<()> {
         unsafe {
             let mut flags = cvt(libc::fcntl(self.fd, libc::F_GETFL, 0))?;
-            flags = if nonblocking {
-                flags | libc::O_NONBLOCK
-            } else {
-                flags & !libc::O_NONBLOCK
-            };
+            flags = if nonblocking { flags | libc::O_NONBLOCK } else { flags & !libc::O_NONBLOCK };
             cvt(libc::fcntl(self.fd, libc::F_SETFL, flags))?;
             Ok(())
         }
     }
 
-
     pub fn duplicate(&self) -> io::Result<FileDesc> {
         let fd = self.raw();
         match cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }) {
-            Ok(newfd) => {
-                Ok(FileDesc::new(newfd))
-            }
+            Ok(newfd) => Ok(FileDesc::new(newfd)),
             Err(e) => return Err(e),
         }
     }
@@ -173,7 +176,9 @@ impl<'a> Read for &'a FileDesc {
 }
 
 impl AsInner<c_int> for FileDesc {
-    fn as_inner(&self) -> &c_int { &self.fd }
+    fn as_inner(&self) -> &c_int {
+        &self.fd
+    }
 }
 
 impl Drop for FileDesc {
diff --git a/src/libstd/sys/vxworks/fs.rs b/src/libstd/sys/vxworks/fs.rs
index adb08d8005a..6c2dfb79d6f 100644
--- a/src/libstd/sys/vxworks/fs.rs
+++ b/src/libstd/sys/vxworks/fs.rs
@@ -1,19 +1,19 @@
 // copies from linuxx
-use crate::ffi::{CString, CStr, OsString, OsStr};
-use crate::sys::vxworks::ext::ffi::OsStrExt;
+use crate::ffi::{CStr, CString, OsStr, OsString};
 use crate::fmt;
-use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom};
 use crate::mem;
 use crate::path::{Path, PathBuf};
 use crate::ptr;
 use crate::sync::Arc;
 use crate::sys::fd::FileDesc;
 use crate::sys::time::SystemTime;
+use crate::sys::vxworks::ext::ffi::OsStrExt;
+use crate::sys::vxworks::ext::ffi::OsStringExt;
 use crate::sys::{cvt, cvt_r};
 use crate::sys_common::{AsInner, FromInner};
-use libc::{self, c_int, mode_t, stat64, off_t};
-use libc::{ftruncate, lseek, dirent, readdir_r as readdir64_r, open};
-use crate::sys::vxworks::ext::ffi::OsStringExt;
+use libc::{self, c_int, mode_t, off_t, stat64};
+use libc::{dirent, ftruncate, lseek, open, readdir_r as readdir64_r};
 pub struct File(FileDesc);
 
 #[derive(Clone)]
@@ -58,16 +58,24 @@ pub struct OpenOptions {
 }
 
 #[derive(Clone, PartialEq, Eq, Debug)]
-pub struct FilePermissions { mode: mode_t }
+pub struct FilePermissions {
+    mode: mode_t,
+}
 
 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
-pub struct FileType { mode: mode_t }
+pub struct FileType {
+    mode: mode_t,
+}
 
 #[derive(Debug)]
-pub struct DirBuilder { mode: mode_t }
+pub struct DirBuilder {
+    mode: mode_t,
+}
 
 impl FileAttr {
-    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
+    pub fn size(&self) -> u64 {
+        self.stat.st_size as u64
+    }
     pub fn perm(&self) -> FilePermissions {
         FilePermissions { mode: (self.stat.st_mode as mode_t) }
     }
@@ -85,20 +93,23 @@ impl FileAttr {
 
     pub fn accessed(&self) -> io::Result<SystemTime> {
         Ok(SystemTime::from(libc::timespec {
-        tv_sec: self.stat.st_atime as libc::time_t,
-        tv_nsec: 0, // hack - a proper fix would be better
+            tv_sec: self.stat.st_atime as libc::time_t,
+            tv_nsec: 0, // hack - a proper fix would be better
         }))
     }
 
     pub fn created(&self) -> io::Result<SystemTime> {
-        Err(io::Error::new(io::ErrorKind::Other,
-                           "creation time is not available on this platform currently"))
+        Err(io::Error::new(
+            io::ErrorKind::Other,
+            "creation time is not available on this platform currently",
+        ))
     }
-
 }
 
 impl AsInner<stat64> for FileAttr {
-    fn as_inner(&self) -> &stat64 { &self.stat }
+    fn as_inner(&self) -> &stat64 {
+        &self.stat
+    }
 }
 
 impl FilePermissions {
@@ -116,15 +127,25 @@ impl FilePermissions {
             self.mode |= 0o222;
         }
     }
-    pub fn mode(&self) -> u32 { self.mode as u32 }
+    pub fn mode(&self) -> u32 {
+        self.mode as u32
+    }
 }
 
 impl FileType {
-    pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
-    pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
-    pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
+    pub fn is_dir(&self) -> bool {
+        self.is(libc::S_IFDIR)
+    }
+    pub fn is_file(&self) -> bool {
+        self.is(libc::S_IFREG)
+    }
+    pub fn is_symlink(&self) -> bool {
+        self.is(libc::S_IFLNK)
+    }
 
-    pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
+    pub fn is(&self, mode: mode_t) -> bool {
+        self.mode & libc::S_IFMT == mode
+    }
 }
 
 impl FromInner<u32> for FilePermissions {
@@ -149,10 +170,7 @@ impl Iterator for ReadDir {
         }
 
         unsafe {
-            let mut ret = DirEntry {
-                entry: mem::zeroed(),
-                dir: self.clone(),
-            };
+            let mut ret = DirEntry { entry: mem::zeroed(), dir: self.clone() };
             let mut entry_ptr = ptr::null_mut();
             loop {
                 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
@@ -163,13 +181,13 @@ impl Iterator for ReadDir {
                         // (instead of looping forever)
                         self.end_of_stream = true;
                     }
-                    return Some(Err(Error::last_os_error()))
+                    return Some(Err(Error::last_os_error()));
                 }
                 if entry_ptr.is_null() {
-                    return None
+                    return None;
                 }
                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
-                    return Some(Ok(ret))
+                    return Some(Ok(ret));
                 }
             }
         }
@@ -185,22 +203,20 @@ impl Drop for Dir {
 
 impl DirEntry {
     pub fn path(&self) -> PathBuf {
-            use crate::sys::vxworks::ext::ffi::OsStrExt;
-            self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
+        use crate::sys::vxworks::ext::ffi::OsStrExt;
+        self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
     }
 
     pub fn file_name(&self) -> OsString {
         OsStr::from_bytes(self.name_bytes()).to_os_string()
     }
 
-
     pub fn metadata(&self) -> io::Result<FileAttr> {
         lstat(&self.path())
     }
 
     pub fn file_type(&self) -> io::Result<FileType> {
         lstat(&self.path()).map(|m| m.file_type())
-
     }
 
     pub fn ino(&self) -> u64 {
@@ -231,21 +247,35 @@ impl OpenOptions {
         }
     }
 
-    pub fn read(&mut self, read: bool) { self.read = read; }
-    pub fn write(&mut self, write: bool) { self.write = write; }
-    pub fn append(&mut self, append: bool) { self.append = append; }
-    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
-    pub fn create(&mut self, create: bool) { self.create = create; }
-    pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
-    pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+    pub fn append(&mut self, append: bool) {
+        self.append = append;
+    }
+    pub fn truncate(&mut self, truncate: bool) {
+        self.truncate = truncate;
+    }
+    pub fn create(&mut self, create: bool) {
+        self.create = create;
+    }
+    pub fn create_new(&mut self, create_new: bool) {
+        self.create_new = create_new;
+    }
+    pub fn mode(&mut self, mode: u32) {
+        self.mode = mode as mode_t;
+    }
 
     fn get_access_mode(&self) -> io::Result<c_int> {
         match (self.read, self.write, self.append) {
-            (true,  false, false) => Ok(libc::O_RDONLY),
-            (false, true,  false) => Ok(libc::O_WRONLY),
-            (true,  true,  false) => Ok(libc::O_RDWR),
-            (false, _,     true)  => Ok(libc::O_WRONLY | libc::O_APPEND),
-            (true,  _,     true)  => Ok(libc::O_RDWR | libc::O_APPEND),
+            (true, false, false) => Ok(libc::O_RDONLY),
+            (false, true, false) => Ok(libc::O_WRONLY),
+            (true, true, false) => Ok(libc::O_RDWR),
+            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
+            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
             (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
         }
     }
@@ -253,23 +283,25 @@ impl OpenOptions {
     fn get_creation_mode(&self) -> io::Result<c_int> {
         match (self.write, self.append) {
             (true, false) => {}
-            (false, false) =>
+            (false, false) => {
                 if self.truncate || self.create || self.create_new {
                     return Err(Error::from_raw_os_error(libc::EINVAL));
-                },
-            (_, true) =>
+                }
+            }
+            (_, true) => {
                 if self.truncate && !self.create_new {
                     return Err(Error::from_raw_os_error(libc::EINVAL));
-                },
+                }
+            }
         }
 
         Ok(match (self.create, self.truncate, self.create_new) {
-                (false, false, false) => 0,
-                (true,  false, false) => libc::O_CREAT,
-                (false, true,  false) => libc::O_TRUNC,
-                (true,  true,  false) => libc::O_CREAT | libc::O_TRUNC,
-                (_,      _,    true)  => libc::O_CREAT | libc::O_EXCL,
-           })
+            (false, false, false) => 0,
+            (true, false, false) => libc::O_CREAT,
+            (false, true, false) => libc::O_TRUNC,
+            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
+            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
+        })
     }
 }
 
@@ -280,21 +312,17 @@ impl File {
     }
 
     pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
-        let flags = libc::O_CLOEXEC |
-                opts.get_access_mode()? |
-                opts.get_creation_mode()? |
-                (opts.custom_flags as c_int & !libc::O_ACCMODE);
-        let fd = cvt_r(|| unsafe {
-            open(path.as_ptr(), flags, opts.mode as c_int)
-        })?;
+        let flags = libc::O_CLOEXEC
+            | opts.get_access_mode()?
+            | opts.get_creation_mode()?
+            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
+        let fd = cvt_r(|| unsafe { open(path.as_ptr(), flags, opts.mode as c_int) })?;
         Ok(File(FileDesc::new(fd)))
     }
 
     pub fn file_attr(&self) -> io::Result<FileAttr> {
         let mut stat: stat64 = unsafe { mem::zeroed() };
-        cvt(unsafe {
-            ::libc::fstat(self.0.raw(), &mut stat)
-        })?;
+        cvt(unsafe { ::libc::fstat(self.0.raw(), &mut stat) })?;
         Ok(FileAttr { stat: stat })
     }
 
@@ -306,13 +334,13 @@ impl File {
     pub fn datasync(&self) -> io::Result<()> {
         cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
         return Ok(());
-        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) } //not supported
+        unsafe fn os_datasync(fd: c_int) -> c_int {
+            libc::fsync(fd)
+        } //not supported
     }
 
     pub fn truncate(&self, size: u64) -> io::Result<()> {
-        return cvt_r(|| unsafe {
-            ftruncate(self.0.raw(), size as off_t)
-        }).map(|_| ());
+        return cvt_r(|| unsafe { ftruncate(self.0.raw(), size as off_t) }).map(|_| ());
     }
 
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
@@ -339,7 +367,9 @@ impl File {
         self.0.write_at(buf, offset)
     }
 
-    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+    pub fn flush(&self) -> io::Result<()> {
+        Ok(())
+    }
 
     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
         let (whence, pos) = match pos {
@@ -357,9 +387,13 @@ impl File {
         self.0.duplicate().map(File)
     }
 
-    pub fn fd(&self) -> &FileDesc { &self.0 }
+    pub fn fd(&self) -> &FileDesc {
+        &self.0
+    }
 
-    pub fn into_fd(self) -> FileDesc { self.0 }
+    pub fn into_fd(self) -> FileDesc {
+        self.0
+    }
 
     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
         cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
@@ -401,7 +435,7 @@ impl FromInner<c_int> for File {
 impl fmt::Debug for File {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         fn get_path(fd: c_int) -> Option<PathBuf> {
-            let mut buf = vec![0;libc::PATH_MAX as usize];
+            let mut buf = vec![0; libc::PATH_MAX as usize];
             let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
             if n == -1 {
                 return None;
@@ -419,7 +453,7 @@ impl fmt::Debug for File {
                 libc::O_RDONLY => Some((true, false)),
                 libc::O_RDWR => Some((true, true)),
                 libc::O_WRONLY => Some((false, true)),
-                _ => None
+                _ => None,
             }
         }
 
@@ -445,10 +479,7 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> {
             Err(Error::last_os_error())
         } else {
             let inner = InnerReadDir { dirp: Dir(ptr), root };
-            Ok(ReadDir{
-                inner: Arc::new(inner),
-                end_of_stream: false,
-            })
+            Ok(ReadDir { inner: Arc::new(inner), end_of_stream: false })
         }
     }
 }
@@ -480,11 +511,7 @@ pub fn rmdir(p: &Path) -> io::Result<()> {
 
 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
     let filetype = lstat(path)?.file_type();
-    if filetype.is_symlink() {
-        unlink(path)
-    } else {
-        remove_dir_all_recursive(path)
-    }
+    if filetype.is_symlink() { unlink(path) } else { remove_dir_all_recursive(path) }
 }
 
 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
@@ -506,11 +533,12 @@ pub fn readlink(p: &Path) -> io::Result<PathBuf> {
     let mut buf = Vec::with_capacity(256);
 
     loop {
-        let buf_read = cvt(unsafe {
-            libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
-        })? as usize;
+        let buf_read =
+            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
 
-        unsafe { buf.set_len(buf_read); }
+        unsafe {
+            buf.set_len(buf_read);
+        }
 
         if buf_read != buf.capacity() {
             buf.shrink_to_fit();
@@ -542,18 +570,14 @@ pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
 pub fn stat(p: &Path) -> io::Result<FileAttr> {
     let p = cstr(p)?;
     let mut stat: stat64 = unsafe { mem::zeroed() };
-    cvt(unsafe {
-        libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _)
-    })?;
+    cvt(unsafe { libc::stat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?;
     Ok(FileAttr { stat })
 }
 
 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
     let p = cstr(p)?;
     let mut stat: stat64 = unsafe { mem::zeroed() };
-    cvt(unsafe {
-        ::libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _)
-    })?;
+    cvt(unsafe { ::libc::lstat(p.as_ptr(), &mut stat as *mut _ as *mut _) })?;
     Ok(FileAttr { stat })
 }
 
@@ -564,7 +588,7 @@ pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
     unsafe {
         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
         if r.is_null() {
-            return Err(io::Error::last_os_error())
+            return Err(io::Error::last_os_error());
         }
         buf = CStr::from_ptr(r).to_bytes().to_vec();
         libc::free(r as *mut _);
@@ -575,8 +599,10 @@ pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
     use crate::fs::File;
     if !from.is_file() {
-        return Err(Error::new(ErrorKind::InvalidInput,
-                              "the source path is not an existing regular file"))
+        return Err(Error::new(
+            ErrorKind::InvalidInput,
+            "the source path is not an existing regular file",
+        ));
     }
 
     let mut reader = File::open(from)?;
diff --git a/src/libstd/sys/vxworks/io.rs b/src/libstd/sys/vxworks/io.rs
index 8cd11cbf5df..f1a2c8446ff 100644
--- a/src/libstd/sys/vxworks/io.rs
+++ b/src/libstd/sys/vxworks/io.rs
@@ -1,7 +1,7 @@
 use crate::marker::PhantomData;
 use crate::slice;
 
-use libc::{iovec, c_void};
+use libc::{c_void, iovec};
 
 #[repr(transparent)]
 pub struct IoSlice<'a> {
@@ -13,10 +13,7 @@ impl<'a> IoSlice<'a> {
     #[inline]
     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
         IoSlice {
-            vec: iovec {
-                iov_base: buf.as_ptr() as *mut u8 as *mut c_void,
-                iov_len: buf.len()
-            },
+            vec: iovec { iov_base: buf.as_ptr() as *mut u8 as *mut c_void, iov_len: buf.len() },
             _p: PhantomData,
         }
     }
@@ -35,9 +32,7 @@ impl<'a> IoSlice<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 }
 
@@ -50,10 +45,7 @@ impl<'a> IoSliceMut<'a> {
     #[inline]
     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
         IoSliceMut {
-            vec: iovec {
-                iov_base: buf.as_mut_ptr() as *mut c_void,
-                iov_len: buf.len()
-            },
+            vec: iovec { iov_base: buf.as_mut_ptr() as *mut c_void, iov_len: buf.len() },
             _p: PhantomData,
         }
     }
@@ -72,15 +64,11 @@ impl<'a> IoSliceMut<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 
     #[inline]
     pub fn as_mut_slice(&mut self) -> &mut [u8] {
-        unsafe {
-            slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len)
-        }
+        unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
     }
 }
diff --git a/src/libstd/sys/vxworks/memchr.rs b/src/libstd/sys/vxworks/memchr.rs
index b5b4e6d9c13..928100c92ff 100644
--- a/src/libstd/sys/vxworks/memchr.rs
+++ b/src/libstd/sys/vxworks/memchr.rs
@@ -6,13 +6,10 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
         libc::memchr(
             haystack.as_ptr() as *const libc::c_void,
             needle as libc::c_int,
-            haystack.len())
+            haystack.len(),
+        )
     };
-    if p.is_null() {
-        None
-    } else {
-        Some(p as usize - (haystack.as_ptr() as usize))
-    }
+    if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) }
 }
 
 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
diff --git a/src/libstd/sys/vxworks/mod.rs b/src/libstd/sys/vxworks/mod.rs
index 1eff4fbcd83..f102e4d6adf 100644
--- a/src/libstd/sys/vxworks/mod.rs
+++ b/src/libstd/sys/vxworks/mod.rs
@@ -3,8 +3,8 @@
 
 use crate::io::ErrorKind;
 
-pub use crate::os::vxworks as platform;
 pub use self::rand::hashmap_random_keys;
+pub use crate::os::vxworks as platform;
 pub use libc::strlen;
 
 pub mod alloc;
@@ -16,8 +16,8 @@ pub mod ext;
 pub mod fast_thread_local;
 pub mod fd;
 pub mod fs;
-pub mod memchr;
 pub mod io;
+pub mod memchr;
 pub mod mutex;
 pub mod net;
 pub mod os;
@@ -27,10 +27,10 @@ pub mod process;
 pub mod rand;
 pub mod rwlock;
 pub mod stack_overflow;
+pub mod stdio;
 pub mod thread;
 pub mod thread_local;
 pub mod time;
-pub mod stdio;
 
 pub use crate::sys_common::os_str_bytes as os_str;
 
@@ -47,7 +47,7 @@ pub fn init() {
         reset_sigpipe();
     }
 
-    unsafe fn reset_sigpipe() { }
+    unsafe fn reset_sigpipe() {}
 }
 
 pub use libc::signal;
@@ -71,8 +71,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind {
         // These two constants can have the same value on some systems,
         // but different values on others, so we can't use a match
         // clause
-        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
-            ErrorKind::WouldBlock,
+        x if x == libc::EAGAIN || x == libc::EWOULDBLOCK => ErrorKind::WouldBlock,
 
         _ => ErrorKind::Other,
     }
@@ -94,16 +93,13 @@ macro_rules! impl_is_minus_one {
 impl_is_minus_one! { i8 i16 i32 i64 isize }
 
 pub fn cvt<T: IsMinusOne>(t: T) -> crate::io::Result<T> {
-    if t.is_minus_one() {
-        Err(crate::io::Error::last_os_error())
-    } else {
-        Ok(t)
-    }
+    if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) }
 }
 
 pub fn cvt_r<T, F>(mut f: F) -> crate::io::Result<T>
-    where T: IsMinusOne,
-          F: FnMut() -> T
+where
+    T: IsMinusOne,
+    F: FnMut() -> T,
 {
     loop {
         match cvt(f()) {
diff --git a/src/libstd/sys/vxworks/mutex.rs b/src/libstd/sys/vxworks/mutex.rs
index b43af8fdcaa..b38375a2e03 100644
--- a/src/libstd/sys/vxworks/mutex.rs
+++ b/src/libstd/sys/vxworks/mutex.rs
@@ -1,7 +1,9 @@
 use crate::cell::UnsafeCell;
 use crate::mem::MaybeUninit;
 
-pub struct Mutex { inner: UnsafeCell<libc::pthread_mutex_t> }
+pub struct Mutex {
+    inner: UnsafeCell<libc::pthread_mutex_t>,
+}
 
 #[inline]
 pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t {
@@ -82,7 +84,9 @@ impl Mutex {
     }
 }
 
-pub struct ReentrantMutex { inner: UnsafeCell<libc::pthread_mutex_t> }
+pub struct ReentrantMutex {
+    inner: UnsafeCell<libc::pthread_mutex_t>,
+}
 
 unsafe impl Send for ReentrantMutex {}
 unsafe impl Sync for ReentrantMutex {}
@@ -96,8 +100,8 @@ impl ReentrantMutex {
         let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
         let result = libc::pthread_mutexattr_init(attr.as_mut_ptr());
         debug_assert_eq!(result, 0);
-        let result = libc::pthread_mutexattr_settype(attr.as_mut_ptr(),
-                                                    libc::PTHREAD_MUTEX_RECURSIVE);
+        let result =
+            libc::pthread_mutexattr_settype(attr.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE);
         debug_assert_eq!(result, 0);
         let result = libc::pthread_mutex_init(self.inner.get(), attr.as_ptr());
         debug_assert_eq!(result, 0);
diff --git a/src/libstd/sys/vxworks/net.rs b/src/libstd/sys/vxworks/net.rs
index 56962e11dcf..85f5fcff2c2 100644
--- a/src/libstd/sys/vxworks/net.rs
+++ b/src/libstd/sys/vxworks/net.rs
@@ -1,15 +1,15 @@
+use crate::cmp;
 use crate::ffi::CStr;
 use crate::io;
 use crate::io::{IoSlice, IoSliceMut};
-use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
 use crate::mem;
-use crate::net::{SocketAddr, Shutdown};
+use crate::net::{Shutdown, SocketAddr};
 use crate::str;
 use crate::sys::fd::FileDesc;
-use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr};
+use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::{Duration, Instant};
-use crate::cmp;
+use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
 
 pub use crate::sys::{cvt, cvt_r};
 
@@ -18,7 +18,6 @@ pub extern crate libc as netc;
 
 pub type wrlen_t = size_t;
 
-
 const SOCK_CLOEXEC: c_int = 0;
 const SO_NOSIGPIPE: c_int = 0;
 
@@ -28,23 +27,23 @@ pub fn init() {}
 
 pub fn cvt_gai(err: c_int) -> io::Result<()> {
     if err == 0 {
-        return Ok(())
+        return Ok(());
     }
 
     // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
     on_resolver_failure();
 
     if err == EAI_SYSTEM {
-        return Err(io::Error::last_os_error())
+        return Err(io::Error::last_os_error());
     }
 
     let detail = unsafe {
-        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
-            .to_owned()
+        str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap().to_owned()
     };
-    Err(io::Error::new(io::ErrorKind::Other,
-                       &format!("failed to lookup address information: {}",
-                                detail)[..]))
+    Err(io::Error::new(
+        io::ErrorKind::Other,
+        &format!("failed to lookup address information: {}", detail)[..],
+    ))
 }
 
 impl Socket {
@@ -67,7 +66,7 @@ impl Socket {
     }
 
     pub fn new_pair(_fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
-            unimplemented!();
+        unimplemented!();
     }
 
     pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
@@ -85,15 +84,13 @@ impl Socket {
             Err(e) => return Err(e),
         }
 
-        let mut pollfd = libc::pollfd {
-            fd: self.0.raw(),
-            events: libc::POLLOUT,
-            revents: 0,
-        };
+        let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 };
 
         if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
-            return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                      "cannot set a 0 duration timeout"));
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "cannot set a 0 duration timeout",
+            ));
         }
 
         let start = Instant::now();
@@ -105,7 +102,8 @@ impl Socket {
             }
 
             let timeout = timeout - elapsed;
-            let mut timeout = timeout.as_secs()
+            let mut timeout = timeout
+                .as_secs()
                 .saturating_mul(1_000)
                 .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
             if timeout == 0 {
@@ -126,10 +124,9 @@ impl Socket {
                     // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
                     // for POLLHUP rather than read readiness
                     if pollfd.revents & libc::POLLHUP != 0 {
-                        let e = self.take_error()?
-                            .unwrap_or_else(|| {
-                                io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
-                            });
+                        let e = self.take_error()?.unwrap_or_else(|| {
+                            io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
+                        });
                         return Err(e);
                     }
 
@@ -139,11 +136,8 @@ impl Socket {
         }
     }
 
-    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
-                  -> io::Result<Socket> {
-        let fd = cvt_r(|| unsafe {
-            libc::accept(self.0.raw(), storage, len)
-        })?;
+    pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result<Socket> {
+        let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?;
         let fd = FileDesc::new(fd);
         fd.set_cloexec()?;
         Ok(Socket(fd))
@@ -155,10 +149,7 @@ impl Socket {
 
     fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
         let ret = cvt(unsafe {
-            libc::recv(self.0.raw(),
-                       buf.as_mut_ptr() as *mut c_void,
-                       buf.len(),
-                       flags)
+            libc::recv(self.0.raw(), buf.as_mut_ptr() as *mut c_void, buf.len(), flags)
         })?;
         Ok(ret as usize)
     }
@@ -175,18 +166,23 @@ impl Socket {
         self.0.read_vectored(bufs)
     }
 
-    fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
-                            -> io::Result<(usize, SocketAddr)> {
+    fn recv_from_with_flags(
+        &self,
+        buf: &mut [u8],
+        flags: c_int,
+    ) -> io::Result<(usize, SocketAddr)> {
         let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
         let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
 
         let n = cvt(unsafe {
-            libc::recvfrom(self.0.raw(),
-                        buf.as_mut_ptr() as *mut c_void,
-                        buf.len(),
-                        flags,
-                        &mut storage as *mut _ as *mut _,
-                        &mut addrlen)
+            libc::recvfrom(
+                self.0.raw(),
+                buf.as_mut_ptr() as *mut c_void,
+                buf.len(),
+                flags,
+                &mut storage as *mut _ as *mut _,
+                &mut addrlen,
+            )
         })?;
         Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
     }
@@ -211,8 +207,10 @@ impl Socket {
         let timeout = match dur {
             Some(dur) => {
                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
-                    return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                              "cannot set a 0 duration timeout"));
+                    return Err(io::Error::new(
+                        io::ErrorKind::InvalidInput,
+                        "cannot set a 0 duration timeout",
+                    ));
                 }
 
                 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
@@ -229,12 +227,7 @@ impl Socket {
                 }
                 timeout
             }
-            None => {
-                libc::timeval {
-                    tv_sec: 0,
-                    tv_usec: 0,
-                }
-            }
+            None => libc::timeval { tv_sec: 0, tv_usec: 0 },
         };
         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
     }
@@ -276,24 +269,26 @@ impl Socket {
 
     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
-        if raw == 0 {
-            Ok(None)
-        } else {
-            Ok(Some(io::Error::from_raw_os_error(raw as i32)))
-        }
+        if raw == 0 { Ok(None) } else { Ok(Some(io::Error::from_raw_os_error(raw as i32))) }
     }
 }
 
 impl AsInner<c_int> for Socket {
-    fn as_inner(&self) -> &c_int { self.0.as_inner() }
+    fn as_inner(&self) -> &c_int {
+        self.0.as_inner()
+    }
 }
 
 impl FromInner<c_int> for Socket {
-    fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
+    fn from_inner(fd: c_int) -> Socket {
+        Socket(FileDesc::new(fd))
+    }
 }
 
 impl IntoInner<c_int> for Socket {
-    fn into_inner(self) -> c_int { self.0.into_raw() }
+    fn into_inner(self) -> c_int {
+        self.0.into_raw()
+    }
 }
 
 // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
@@ -314,7 +309,7 @@ impl IntoInner<c_int> for Socket {
 // believe it's thread-safe).
 #[cfg(target_env = "gnu")]
 fn on_resolver_failure() {
-/*
+    /*
     use crate::sys;
 
     // If the version fails to parse, we treat it the same as "not glibc".
diff --git a/src/libstd/sys/vxworks/path.rs b/src/libstd/sys/vxworks/path.rs
index 7a183956107..840a7ae0426 100644
--- a/src/libstd/sys/vxworks/path.rs
+++ b/src/libstd/sys/vxworks/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/vxworks/pipe.rs b/src/libstd/sys/vxworks/pipe.rs
index e09dbe6e99b..b72a6554551 100644
--- a/src/libstd/sys/vxworks/pipe.rs
+++ b/src/libstd/sys/vxworks/pipe.rs
@@ -1,9 +1,9 @@
 use crate::io::{self, IoSlice, IoSliceMut};
-use libc::{self /*, c_int apparently not used? */};
 use crate::mem;
-use crate::sync::atomic::{AtomicBool};
+use crate::sync::atomic::AtomicBool;
 use crate::sys::fd::FileDesc;
 use crate::sys::{cvt, cvt_r};
+use libc::{self /*, c_int apparently not used? */};
 
 pub struct AnonPipe(FileDesc);
 
@@ -25,29 +25,29 @@ impl AnonPipe {
         self.0.read(buf)
     }
     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
-                self.0.read_vectored(bufs)
-        }
+        self.0.read_vectored(bufs)
+    }
 
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         self.0.write(buf)
     }
 
-        pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
-                self.0.write_vectored(bufs)
-        }
+    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
+        self.0.write_vectored(bufs)
+    }
 
-    pub fn fd(&self) -> &FileDesc { &self.0 }
-    pub fn into_fd(self) -> FileDesc { self.0 }
+    pub fn fd(&self) -> &FileDesc {
+        &self.0
+    }
+    pub fn into_fd(self) -> FileDesc {
+        self.0
+    }
     pub fn diverge(&self) -> ! {
         panic!()
-     }
+    }
 }
 
-pub fn read2(p1: AnonPipe,
-             v1: &mut Vec<u8>,
-             p2: AnonPipe,
-             v2: &mut Vec<u8>) -> io::Result<()> {
-
+pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
     // Set both pipes into nonblocking mode as we're gonna be reading from both
     // in the `select` loop below, and we wouldn't want one to block the other!
     let p1 = p1.into_fd();
@@ -83,8 +83,9 @@ pub fn read2(p1: AnonPipe,
         match fd.read_to_end(dst) {
             Ok(_) => Ok(true),
             Err(e) => {
-                if e.raw_os_error() == Some(libc::EWOULDBLOCK) ||
-                   e.raw_os_error() == Some(libc::EAGAIN) {
+                if e.raw_os_error() == Some(libc::EWOULDBLOCK)
+                    || e.raw_os_error() == Some(libc::EAGAIN)
+                {
                     Ok(false)
                 } else {
                     Err(e)
diff --git a/src/libstd/sys/vxworks/process/mod.rs b/src/libstd/sys/vxworks/process/mod.rs
index 3ecbe4e3b28..c59782ff44b 100644
--- a/src/libstd/sys/vxworks/process/mod.rs
+++ b/src/libstd/sys/vxworks/process/mod.rs
@@ -1,4 +1,4 @@
-pub use self::process_common::{Command, ExitStatus, ExitCode, Stdio, StdioPipes};
+pub use self::process_common::{Command, ExitCode, ExitStatus, Stdio, StdioPipes};
 pub use self::process_inner::Process;
 pub use crate::ffi::OsString as EnvKey;
 
diff --git a/src/libstd/sys/vxworks/process/process_common.rs b/src/libstd/sys/vxworks/process/process_common.rs
index 13648abd1e4..a8139a27537 100644
--- a/src/libstd/sys/vxworks/process/process_common.rs
+++ b/src/libstd/sys/vxworks/process/process_common.rs
@@ -1,6 +1,7 @@
 use crate::os::unix::prelude::*;
 
-use crate::ffi::{OsString, OsStr, CString, CStr};
+use crate::collections::BTreeMap;
+use crate::ffi::{CStr, CString, OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::ptr;
@@ -8,9 +9,8 @@ use crate::sys::fd::FileDesc;
 use crate::sys::fs::{File, OpenOptions};
 use crate::sys::pipe::{self, AnonPipe};
 use crate::sys_common::process::CommandEnv;
-use crate::collections::BTreeMap;
 
-use libc::{c_int, gid_t, uid_t, c_char, EXIT_SUCCESS, EXIT_FAILURE};
+use libc::{c_char, c_int, gid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS};
 
 ////////////////////////////////////////////////////////////////////////////////
 // Command
@@ -150,10 +150,7 @@ impl Command {
         &mut self.closures
     }
 
-    pub unsafe fn pre_exec(
-        &mut self,
-        _f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>,
-    ) {
+    pub unsafe fn pre_exec(&mut self, _f: Box<dyn FnMut() -> io::Result<()> + Send + Sync>) {
         // Fork() is not supported in vxWorks so no way to run the closure in the new procecss.
         unimplemented!();
     }
@@ -183,26 +180,21 @@ impl Command {
         self.env.have_changed_path()
     }
 
-    pub fn setup_io(&self, default: Stdio, needs_stdin: bool)
-                -> io::Result<(StdioPipes, ChildPipes)> {
+    pub fn setup_io(
+        &self,
+        default: Stdio,
+        needs_stdin: bool,
+    ) -> io::Result<(StdioPipes, ChildPipes)> {
         let null = Stdio::Null;
-        let default_stdin = if needs_stdin {&default} else {&null};
+        let default_stdin = if needs_stdin { &default } else { &null };
         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
         let stdout = self.stdout.as_ref().unwrap_or(&default);
         let stderr = self.stderr.as_ref().unwrap_or(&default);
         let (their_stdin, our_stdin) = stdin.to_child_stdio(true)?;
         let (their_stdout, our_stdout) = stdout.to_child_stdio(false)?;
         let (their_stderr, our_stderr) = stderr.to_child_stdio(false)?;
-        let ours = StdioPipes {
-            stdin: our_stdin,
-            stdout: our_stdout,
-            stderr: our_stderr,
-        };
-        let theirs = ChildPipes {
-            stdin: their_stdin,
-            stdout: their_stdout,
-            stderr: their_stderr,
-        };
+        let ours = StdioPipes { stdin: our_stdin, stdout: our_stdout, stderr: our_stderr };
+        let theirs = ChildPipes { stdin: their_stdin, stdout: their_stdout, stderr: their_stderr };
         Ok((ours, theirs))
     }
 }
@@ -217,21 +209,21 @@ fn os2c(s: &OsStr, saw_nul: &mut bool) -> CString {
 // Helper type to manage ownership of the strings within a C-style array.
 pub struct CStringArray {
     items: Vec<CString>,
-    ptrs: Vec<*const c_char>
+    ptrs: Vec<*const c_char>,
 }
 
 impl CStringArray {
     pub fn with_capacity(capacity: usize) -> Self {
         let mut result = CStringArray {
             items: Vec::with_capacity(capacity),
-            ptrs: Vec::with_capacity(capacity+1)
+            ptrs: Vec::with_capacity(capacity + 1),
         };
         result.ptrs.push(ptr::null());
         result
     }
     pub fn push(&mut self, item: CString) {
         let l = self.ptrs.len();
-        self.ptrs[l-1] = item.as_ptr();
+        self.ptrs[l - 1] = item.as_ptr();
         self.ptrs.push(ptr::null());
         self.items.push(item);
     }
@@ -262,12 +254,9 @@ fn construct_envp(env: BTreeMap<OsString, OsString>, saw_nul: &mut bool) -> CStr
 }
 
 impl Stdio {
-    pub fn to_child_stdio(&self, readable: bool)
-                      -> io::Result<(ChildStdio, Option<AnonPipe>)> {
+    pub fn to_child_stdio(&self, readable: bool) -> io::Result<(ChildStdio, Option<AnonPipe>)> {
         match *self {
-            Stdio::Inherit => {
-                Ok((ChildStdio::Inherit, None))
-            },
+            Stdio::Inherit => Ok((ChildStdio::Inherit, None)),
 
             // Make sure that the source descriptors are not an stdio
             // descriptor, otherwise the order which we set the child's
@@ -286,11 +275,7 @@ impl Stdio {
 
             Stdio::MakePipe => {
                 let (reader, writer) = pipe::anon_pipe()?;
-                let (ours, theirs) = if readable {
-                    (writer, reader)
-                } else {
-                    (reader, writer)
-                };
+                let (ours, theirs) = if readable { (writer, reader) } else { (reader, writer) };
                 Ok((ChildStdio::Owned(theirs.into_fd()), Some(ours)))
             }
 
@@ -298,9 +283,7 @@ impl Stdio {
                 let mut opts = OpenOptions::new();
                 opts.read(readable);
                 opts.write(!readable);
-                let path = unsafe {
-                    CStr::from_ptr("/null\0".as_ptr() as *const _)
-                };
+                let path = unsafe { CStr::from_ptr("/null\0".as_ptr() as *const _) };
                 let fd = File::open_c(&path, &opts)?;
                 Ok((ChildStdio::Owned(fd.into_fd()), None))
             }
@@ -350,7 +333,8 @@ impl ExitStatus {
     }
 
     fn exited(&self) -> bool {
-        /*unsafe*/ { libc::WIFEXITED(self.0) }
+        /*unsafe*/
+        { libc::WIFEXITED(self.0) }
     }
 
     pub fn success(&self) -> bool {
diff --git a/src/libstd/sys/vxworks/rand.rs b/src/libstd/sys/vxworks/rand.rs
index c22880db2bf..87ebd2c9593 100644
--- a/src/libstd/sys/vxworks/rand.rs
+++ b/src/libstd/sys/vxworks/rand.rs
@@ -4,17 +4,16 @@ use crate::slice;
 pub fn hashmap_random_keys() -> (u64, u64) {
     let mut v = (0, 0);
     unsafe {
-        let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8,
-                                             mem::size_of_val(&v));
+        let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
         imp::fill_bytes(view);
     }
-    return v
+    return v;
 }
 
 mod imp {
-    use libc;
     use crate::io;
     use core::sync::atomic::{AtomicBool, Ordering::Relaxed};
+    use libc;
 
     pub fn fill_bytes(v: &mut [u8]) {
         static RNG_INIT: AtomicBool = AtomicBool::new(false);
diff --git a/src/libstd/sys/vxworks/rwlock.rs b/src/libstd/sys/vxworks/rwlock.rs
index 19b123f2b61..fd2e1a6e7bc 100644
--- a/src/libstd/sys/vxworks/rwlock.rs
+++ b/src/libstd/sys/vxworks/rwlock.rs
@@ -1,6 +1,6 @@
-use libc;
 use crate::cell::UnsafeCell;
 use crate::sync::atomic::{AtomicUsize, Ordering};
+use libc;
 
 pub struct RWLock {
     inner: UnsafeCell<libc::pthread_rwlock_t>,
@@ -29,7 +29,7 @@ impl RWLock {
             if r == 0 {
                 self.raw_unlock();
             }
-        panic!("rwlock read lock would result in deadlock");
+            panic!("rwlock read lock would result in deadlock");
         } else {
             debug_assert_eq!(r, 0);
             self.num_readers.fetch_add(1, Ordering::Relaxed);
@@ -57,12 +57,14 @@ impl RWLock {
         let r = libc::pthread_rwlock_wrlock(self.inner.get());
         // See comments above for why we check for EDEADLK and write_locked. We
         // also need to check that num_readers is 0.
-        if r == libc::EDEADLK || *self.write_locked.get() ||
-            self.num_readers.load(Ordering::Relaxed) != 0 {
+        if r == libc::EDEADLK
+            || *self.write_locked.get()
+            || self.num_readers.load(Ordering::Relaxed) != 0
+        {
             if r == 0 {
                 self.raw_unlock();
             }
-        panic!("rwlock write lock would result in deadlock");
+            panic!("rwlock write lock would result in deadlock");
         } else {
             debug_assert_eq!(r, 0);
         }
@@ -80,8 +82,8 @@ impl RWLock {
                 *self.write_locked.get() = true;
                 true
             }
-            } else {
-                false
+        } else {
+            false
         }
     }
 
@@ -98,7 +100,7 @@ impl RWLock {
         self.raw_unlock();
     }
 
-     #[inline]
+    #[inline]
     pub unsafe fn write_unlock(&self) {
         debug_assert_eq!(self.num_readers.load(Ordering::Relaxed), 0);
         debug_assert!(*self.write_locked.get());
diff --git a/src/libstd/sys/vxworks/stack_overflow.rs b/src/libstd/sys/vxworks/stack_overflow.rs
index 08e7b310ca1..7b58c83193b 100644
--- a/src/libstd/sys/vxworks/stack_overflow.rs
+++ b/src/libstd/sys/vxworks/stack_overflow.rs
@@ -1,12 +1,12 @@
 #![cfg_attr(test, allow(dead_code))]
 
-use self::imp::{make_handler, drop_handler};
+use self::imp::{drop_handler, make_handler};
 
 pub use self::imp::cleanup;
 pub use self::imp::init;
 
 pub struct Handler {
-    _data: *mut libc::c_void
+    _data: *mut libc::c_void,
 }
 
 impl Handler {
@@ -26,16 +26,13 @@ impl Drop for Handler {
 mod imp {
     use crate::ptr;
 
-    pub unsafe fn init() {
-    }
+    pub unsafe fn init() {}
 
-    pub unsafe fn cleanup() {
-    }
+    pub unsafe fn cleanup() {}
 
     pub unsafe fn make_handler() -> super::Handler {
         super::Handler { _data: ptr::null_mut() }
     }
 
-    pub unsafe fn drop_handler(_handler: &mut super::Handler) {
-    }
+    pub unsafe fn drop_handler(_handler: &mut super::Handler) {}
 }
diff --git a/src/libstd/sys/vxworks/stdio.rs b/src/libstd/sys/vxworks/stdio.rs
index 35f163bbdb1..622444ccafd 100644
--- a/src/libstd/sys/vxworks/stdio.rs
+++ b/src/libstd/sys/vxworks/stdio.rs
@@ -6,7 +6,9 @@ pub struct Stdout(());
 pub struct Stderr(());
 
 impl Stdin {
-    pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
+    pub fn new() -> io::Result<Stdin> {
+        Ok(Stdin(()))
+    }
 }
 
 impl io::Read for Stdin {
@@ -19,7 +21,9 @@ impl io::Read for Stdin {
 }
 
 impl Stdout {
-    pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
+    pub fn new() -> io::Result<Stdout> {
+        Ok(Stdout(()))
+    }
 }
 
 impl io::Write for Stdout {
@@ -36,7 +40,9 @@ impl io::Write for Stdout {
 }
 
 impl Stderr {
-    pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
+    pub fn new() -> io::Result<Stderr> {
+        Ok(Stderr(()))
+    }
 }
 
 impl io::Write for Stderr {
diff --git a/src/libstd/sys/vxworks/thread.rs b/src/libstd/sys/vxworks/thread.rs
index e4396b05c00..e0d104b5f3e 100644
--- a/src/libstd/sys/vxworks/thread.rs
+++ b/src/libstd/sys/vxworks/thread.rs
@@ -21,15 +21,16 @@ unsafe impl Sync for Thread {}
 
 // The pthread_attr_setstacksize symbol doesn't exist in the emscripten libc,
 // so we have to not link to it to satisfy emcc's ERROR_ON_UNDEFINED_SYMBOLS.
-unsafe fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
-                                    stack_size: libc::size_t) -> libc::c_int {
+unsafe fn pthread_attr_setstacksize(
+    attr: *mut libc::pthread_attr_t,
+    stack_size: libc::size_t,
+) -> libc::c_int {
     libc::pthread_attr_setstacksize(attr, stack_size)
 }
 
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
-    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>)
-                          -> io::Result<Thread> {
+    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         let p = box p;
         let mut native: libc::pthread_t = mem::zeroed();
         let mut attr: libc::pthread_attr_t = mem::zeroed();
@@ -37,8 +38,7 @@ impl Thread {
 
         let stack_size = cmp::max(stack, min_stack_size(&attr));
 
-        match pthread_attr_setstacksize(&mut attr,
-                                        stack_size) {
+        match pthread_attr_setstacksize(&mut attr, stack_size) {
             0 => {}
             n => {
                 assert_eq!(n, libc::EINVAL);
@@ -47,15 +47,13 @@ impl Thread {
                 // >= PTHREAD_STACK_MIN, it must be an alignment issue.
                 // Round up to the nearest page and try again.
                 let page_size = os::page_size();
-                let stack_size = (stack_size + page_size - 1) &
-                                 (-(page_size as isize - 1) as usize - 1);
-                assert_eq!(libc::pthread_attr_setstacksize(&mut attr,
-                                                           stack_size), 0);
+                let stack_size =
+                    (stack_size + page_size - 1) & (-(page_size as isize - 1) as usize - 1);
+                assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
             }
         };
 
-        let ret = libc::pthread_create(&mut native, &attr, thread_start,
-                                       &*p as *const _ as *mut _);
+        let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
 
         return if ret != 0 {
@@ -65,8 +63,10 @@ impl Thread {
             Ok(Thread { id: native })
         };
 
-        extern fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
-            unsafe { start_thread(main as *mut u8); }
+        extern "C" fn thread_start(main: *mut libc::c_void) -> *mut libc::c_void {
+            unsafe {
+                start_thread(main as *mut u8);
+            }
             ptr::null_mut()
         }
     }
@@ -108,12 +108,13 @@ impl Thread {
         unsafe {
             let ret = libc::pthread_join(self.id, ptr::null_mut());
             mem::forget(self);
-            assert!(ret == 0,
-                    "failed to join thread: {}", io::Error::from_raw_os_error(ret));
+            assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret));
         }
     }
 
-    pub fn id(&self) -> libc::pthread_t { self.id }
+    pub fn id(&self) -> libc::pthread_t {
+        self.id
+    }
 
     pub fn into_id(self) -> libc::pthread_t {
         let id = self.id;
@@ -133,8 +134,12 @@ impl Drop for Thread {
 pub mod guard {
     use crate::ops::Range;
     pub type Guard = Range<usize>;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
     pub unsafe fn deinit() {}
 }
 
diff --git a/src/libstd/sys/vxworks/thread_local.rs b/src/libstd/sys/vxworks/thread_local.rs
index ac615b76b36..2c5b94b1e61 100644
--- a/src/libstd/sys/vxworks/thread_local.rs
+++ b/src/libstd/sys/vxworks/thread_local.rs
@@ -5,7 +5,7 @@ use crate::mem;
 pub type Key = libc::pthread_key_t;
 
 #[inline]
-pub unsafe fn create(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+pub unsafe fn create(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
     let mut key = 0;
     assert_eq!(libc::pthread_key_create(&mut key, mem::transmute(dtor)), 0);
     key
diff --git a/src/libstd/sys/vxworks/time.rs b/src/libstd/sys/vxworks/time.rs
index cb3a4241ea6..8ebbf89213f 100644
--- a/src/libstd/sys/vxworks/time.rs
+++ b/src/libstd/sys/vxworks/time.rs
@@ -1,7 +1,7 @@
 use crate::cmp::Ordering;
-use libc;
 use crate::time::Duration;
 use ::core::hash::{Hash, Hasher};
+use libc;
 
 pub use self::inner::{Instant, SystemTime, UNIX_EPOCH};
 use crate::convert::TryInto;
@@ -15,20 +15,21 @@ struct Timespec {
 
 impl Timespec {
     const fn zero() -> Timespec {
-        Timespec {
-            t: libc::timespec { tv_sec: 0, tv_nsec: 0 },
-        }
+        Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } }
     }
     fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
         if self >= other {
             Ok(if self.t.tv_nsec >= other.t.tv_nsec {
-                Duration::new((self.t.tv_sec - other.t.tv_sec) as u64,
-                                (self.t.tv_nsec - other.t.tv_nsec) as u32)
-                } else {
-                    Duration::new((self.t.tv_sec - 1 - other.t.tv_sec) as u64,
-                        self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) -
-                        other.t.tv_nsec as u32)
-                })
+                Duration::new(
+                    (self.t.tv_sec - other.t.tv_sec) as u64,
+                    (self.t.tv_nsec - other.t.tv_nsec) as u32,
+                )
+            } else {
+                Duration::new(
+                    (self.t.tv_sec - 1 - other.t.tv_sec) as u64,
+                    self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32,
+                )
+            })
         } else {
             match other.sub_timespec(self) {
                 Ok(d) => Err(d),
@@ -51,12 +52,7 @@ impl Timespec {
             nsec -= NSEC_PER_SEC as u32;
             secs = secs.checked_add(1)?;
         }
-        Some(Timespec {
-            t: libc::timespec {
-                tv_sec: secs,
-                tv_nsec: nsec as _,
-            },
-        })
+        Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
     }
 
     fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
@@ -72,12 +68,7 @@ impl Timespec {
             nsec += NSEC_PER_SEC as i32;
             secs = secs.checked_sub(1)?;
         }
-        Some(Timespec {
-            t: libc::timespec {
-                tv_sec: secs,
-                tv_nsec: nsec as _,
-            },
-        })
+        Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
     }
 }
 
@@ -104,16 +95,16 @@ impl Ord for Timespec {
 }
 
 impl Hash for Timespec {
-    fn hash<H : Hasher>(&self, state: &mut H) {
+    fn hash<H: Hasher>(&self, state: &mut H) {
         self.t.tv_sec.hash(state);
         self.t.tv_nsec.hash(state);
     }
 }
 mod inner {
     use crate::fmt;
-    use libc;
     use crate::sys::cvt;
     use crate::time::Duration;
+    use libc;
 
     use super::Timespec;
 
@@ -127,14 +118,8 @@ mod inner {
         t: Timespec,
     }
 
-    pub const UNIX_EPOCH: SystemTime = SystemTime {
-        t: Timespec {
-            t: libc::timespec {
-                tv_sec: 0,
-                tv_nsec: 0,
-            },
-        },
-    };
+    pub const UNIX_EPOCH: SystemTime =
+        SystemTime { t: Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } } };
 
     impl Instant {
         pub fn now() -> Instant {
@@ -142,9 +127,7 @@ mod inner {
         }
 
         pub const fn zero() -> Instant {
-            Instant {
-                t: Timespec::zero(),
-            }
+            Instant { t: Timespec::zero() }
         }
 
         pub fn actually_monotonic() -> bool {
@@ -167,9 +150,9 @@ mod inner {
     impl fmt::Debug for Instant {
         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
             f.debug_struct("Instant")
-             .field("tv_sec", &self.t.t.tv_sec)
-             .field("tv_nsec", &self.t.t.tv_nsec)
-             .finish()
+                .field("tv_sec", &self.t.t.tv_sec)
+                .field("tv_nsec", &self.t.t.tv_nsec)
+                .finish()
         }
     }
 
@@ -178,8 +161,7 @@ mod inner {
             SystemTime { t: now(libc::CLOCK_REALTIME) }
         }
 
-        pub fn sub_time(&self, other: &SystemTime)
-                        -> Result<Duration, Duration> {
+        pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
             self.t.sub_timespec(&other.t)
         }
 
@@ -201,24 +183,17 @@ mod inner {
     impl fmt::Debug for SystemTime {
         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
             f.debug_struct("SystemTime")
-             .field("tv_sec", &self.t.t.tv_sec)
-             .field("tv_nsec", &self.t.t.tv_nsec)
-             .finish()
+                .field("tv_sec", &self.t.t.tv_sec)
+                .field("tv_nsec", &self.t.t.tv_nsec)
+                .finish()
         }
     }
 
     pub type clock_t = libc::c_int;
 
     fn now(clock: clock_t) -> Timespec {
-        let mut t = Timespec {
-            t: libc::timespec {
-                tv_sec: 0,
-                tv_nsec: 0,
-            }
-        };
-        cvt(unsafe {
-            libc::clock_gettime(clock, &mut t.t)
-        }).unwrap();
+        let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } };
+        cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap();
         t
     }
 }
diff --git a/src/libstd/sys/vxworks/weak.rs b/src/libstd/sys/vxworks/weak.rs
index 284f2116423..4c6fddefd3f 100644
--- a/src/libstd/sys/vxworks/weak.rs
+++ b/src/libstd/sys/vxworks/weak.rs
@@ -29,11 +29,7 @@ pub struct Weak<F> {
 
 impl<F> Weak<F> {
     pub const fn new(name: &'static str) -> Weak<F> {
-        Weak {
-            name,
-            addr: AtomicUsize::new(1),
-            _marker: marker::PhantomData,
-        }
+        Weak { name, addr: AtomicUsize::new(1), _marker: marker::PhantomData }
     }
 
     pub fn get(&self) -> Option<F> {
@@ -56,5 +52,5 @@ unsafe fn fetch(name: &str) -> usize {
         Err(..) => return 0,
     };
     assert!(false, "FIXME: fetch");
-   libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
+    libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize
 }
diff --git a/src/libstd/sys/wasi/alloc.rs b/src/libstd/sys/wasi/alloc.rs
index c8529937bbd..e9760d050e1 100644
--- a/src/libstd/sys/wasi/alloc.rs
+++ b/src/libstd/sys/wasi/alloc.rs
@@ -1,6 +1,6 @@
 use crate::alloc::{GlobalAlloc, Layout, System};
 use crate::ptr;
-use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
+use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN};
 use libc;
 
 #[stable(feature = "alloc_system_type", since = "1.28.0")]
diff --git a/src/libstd/sys/wasi/ext/mod.rs b/src/libstd/sys/wasi/ext/mod.rs
index 1c24b244b8c..5f8b1cbfa0b 100644
--- a/src/libstd/sys/wasi/ext/mod.rs
+++ b/src/libstd/sys/wasi/ext/mod.rs
@@ -7,12 +7,16 @@ pub mod io;
 /// Includes all extension traits, and some important type definitions.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub mod prelude {
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use crate::sys::ext::ffi::{OsStringExt, OsStrExt};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use crate::sys::ext::fs::{FileExt, DirEntryExt, MetadataExt, OpenOptionsExt};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use crate::sys::ext::ffi::{OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub use crate::sys::ext::fs::FileTypeExt;
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use crate::sys::ext::io::{AsRawFd, IntoRawFd, FromRawFd};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use crate::sys::ext::fs::{DirEntryExt, FileExt, MetadataExt, OpenOptionsExt};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use crate::sys::ext::io::{AsRawFd, FromRawFd, IntoRawFd};
 }
diff --git a/src/libstd/sys/wasi/net.rs b/src/libstd/sys/wasi/net.rs
index 80f633a8e1f..8a69028ff1d 100644
--- a/src/libstd/sys/wasi/net.rs
+++ b/src/libstd/sys/wasi/net.rs
@@ -1,11 +1,11 @@
+use crate::convert::TryFrom;
 use crate::fmt;
 use crate::io::{self, IoSlice, IoSliceMut};
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
-use crate::time::Duration;
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
+use crate::sys::fd::WasiFd;
 use crate::sys::{unsupported, Void};
-use crate::convert::TryFrom;
-use crate::sys::fd::{WasiFd};
 use crate::sys_common::FromInner;
+use crate::time::Duration;
 
 pub struct TcpStream {
     fd: WasiFd,
@@ -107,24 +107,18 @@ impl TcpStream {
 
 impl FromInner<u32> for TcpStream {
     fn from_inner(fd: u32) -> TcpStream {
-        unsafe {
-            TcpStream {
-                fd: WasiFd::from_raw(fd),
-            }
-        }
+        unsafe { TcpStream { fd: WasiFd::from_raw(fd) } }
     }
 }
 
 impl fmt::Debug for TcpStream {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("TcpStream")
-            .field("fd", &self.fd.as_raw())
-            .finish()
+        f.debug_struct("TcpStream").field("fd", &self.fd.as_raw()).finish()
     }
 }
 
 pub struct TcpListener {
-    fd: WasiFd
+    fd: WasiFd,
 }
 
 impl TcpListener {
@@ -179,19 +173,13 @@ impl TcpListener {
 
 impl FromInner<u32> for TcpListener {
     fn from_inner(fd: u32) -> TcpListener {
-        unsafe {
-            TcpListener {
-                fd: WasiFd::from_raw(fd),
-            }
-        }
+        unsafe { TcpListener { fd: WasiFd::from_raw(fd) } }
     }
 }
 
 impl fmt::Debug for TcpListener {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("TcpListener")
-            .field("fd", &self.fd.as_raw())
-            .finish()
+        f.debug_struct("TcpListener").field("fd", &self.fd.as_raw()).finish()
     }
 }
 
@@ -276,23 +264,19 @@ impl UdpSocket {
         unsupported()
     }
 
-    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         unsupported()
     }
 
-    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         unsupported()
     }
 
-    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         unsupported()
     }
 
-    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         unsupported()
     }
 
@@ -339,19 +323,13 @@ impl UdpSocket {
 
 impl FromInner<u32> for UdpSocket {
     fn from_inner(fd: u32) -> UdpSocket {
-        unsafe {
-            UdpSocket {
-                fd: WasiFd::from_raw(fd),
-            }
-        }
+        unsafe { UdpSocket { fd: WasiFd::from_raw(fd) } }
     }
 }
 
 impl fmt::Debug for UdpSocket {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_struct("UdpSocket")
-            .field("fd", &self.fd.as_raw())
-            .finish()
+        f.debug_struct("UdpSocket").field("fd", &self.fd.as_raw()).finish()
     }
 }
 
@@ -419,8 +397,7 @@ pub mod netc {
     }
 
     #[derive(Copy, Clone)]
-    pub struct sockaddr {
-    }
+    pub struct sockaddr {}
 
     pub type socklen_t = usize;
 }
diff --git a/src/libstd/sys/wasi/os.rs b/src/libstd/sys/wasi/os.rs
index feee8407825..338fbe89765 100644
--- a/src/libstd/sys/wasi/os.rs
+++ b/src/libstd/sys/wasi/os.rs
@@ -1,6 +1,6 @@
 use crate::any::Any;
 use crate::error::Error as StdError;
-use crate::ffi::{OsString, OsStr, CString, CStr};
+use crate::ffi::{CStr, CString, OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::marker::PhantomData;
@@ -19,7 +19,7 @@ pub unsafe fn env_lock() -> impl Any {
 }
 
 pub fn errno() -> i32 {
-    extern {
+    extern "C" {
         #[thread_local]
         static errno: libc::c_int;
     }
@@ -64,7 +64,9 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     Err(JoinPathsError)
 }
@@ -91,11 +93,14 @@ pub struct Env {
 
 impl Iterator for Env {
     type Item = (OsString, OsString);
-    fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+    fn next(&mut self) -> Option<(OsString, OsString)> {
+        self.iter.next()
+    }
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        self.iter.size_hint()
+    }
 }
 
-
 pub fn env() -> Env {
     unsafe {
         let _guard = env_lock();
@@ -107,10 +112,7 @@ pub fn env() -> Env {
             }
             environ = environ.offset(1);
         }
-        return Env {
-            iter: result.into_iter(),
-            _dont_send_or_sync_me: PhantomData,
-        }
+        return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData };
     }
 
     // See src/libstd/sys/unix/os.rs, same as that
@@ -119,10 +121,12 @@ pub fn env() -> Env {
             return None;
         }
         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
-        pos.map(|p| (
-            OsStringExt::from_vec(input[..p].to_vec()),
-            OsStringExt::from_vec(input[p+1..].to_vec()),
-        ))
+        pos.map(|p| {
+            (
+                OsStringExt::from_vec(input[..p].to_vec()),
+                OsStringExt::from_vec(input[p + 1..].to_vec()),
+            )
+        })
     }
 }
 
@@ -168,9 +172,7 @@ pub fn home_dir() -> Option<PathBuf> {
 }
 
 pub fn exit(code: i32) -> ! {
-    unsafe {
-        libc::exit(code)
-    }
+    unsafe { libc::exit(code) }
 }
 
 pub fn getpid() -> u32 {
@@ -193,9 +195,5 @@ macro_rules! impl_is_minus_one {
 impl_is_minus_one! { i8 i16 i32 i64 isize }
 
 fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
-    if t.is_minus_one() {
-        Err(io::Error::last_os_error())
-    } else {
-        Ok(t)
-    }
+    if t.is_minus_one() { Err(io::Error::last_os_error()) } else { Ok(t) }
 }
diff --git a/src/libstd/sys/wasi/path.rs b/src/libstd/sys/wasi/path.rs
index 7a183956107..840a7ae0426 100644
--- a/src/libstd/sys/wasi/path.rs
+++ b/src/libstd/sys/wasi/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/wasi/pipe.rs b/src/libstd/sys/wasi/pipe.rs
index 9f07f054362..fb14dc59101 100644
--- a/src/libstd/sys/wasi/pipe.rs
+++ b/src/libstd/sys/wasi/pipe.rs
@@ -25,9 +25,6 @@ impl AnonPipe {
     }
 }
 
-pub fn read2(p1: AnonPipe,
-             _v1: &mut Vec<u8>,
-             _p2: AnonPipe,
-             _v2: &mut Vec<u8>) -> io::Result<()> {
+pub fn read2(p1: AnonPipe, _v1: &mut Vec<u8>, _p2: AnonPipe, _v2: &mut Vec<u8>) -> io::Result<()> {
     match p1.0 {}
 }
diff --git a/src/libstd/sys/wasi/process.rs b/src/libstd/sys/wasi/process.rs
index 1c4d028b761..7156c9ab92f 100644
--- a/src/libstd/sys/wasi/process.rs
+++ b/src/libstd/sys/wasi/process.rs
@@ -13,7 +13,7 @@ pub use crate::ffi::OsString as EnvKey;
 ////////////////////////////////////////////////////////////////////////////////
 
 pub struct Command {
-    env: CommandEnv
+    env: CommandEnv,
 }
 
 // passed back to std::process with the pipes connected to the child, if any
@@ -32,32 +32,28 @@ pub enum Stdio {
 
 impl Command {
     pub fn new(_program: &OsStr) -> Command {
-        Command {
-            env: Default::default()
-        }
+        Command { env: Default::default() }
     }
 
-    pub fn arg(&mut self, _arg: &OsStr) {
-    }
+    pub fn arg(&mut self, _arg: &OsStr) {}
 
     pub fn env_mut(&mut self) -> &mut CommandEnv {
         &mut self.env
     }
 
-    pub fn cwd(&mut self, _dir: &OsStr) {
-    }
+    pub fn cwd(&mut self, _dir: &OsStr) {}
 
-    pub fn stdin(&mut self, _stdin: Stdio) {
-    }
+    pub fn stdin(&mut self, _stdin: Stdio) {}
 
-    pub fn stdout(&mut self, _stdout: Stdio) {
-    }
+    pub fn stdout(&mut self, _stdout: Stdio) {}
 
-    pub fn stderr(&mut self, _stderr: Stdio) {
-    }
+    pub fn stderr(&mut self, _stderr: Stdio) {}
 
-    pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool)
-        -> io::Result<(Process, StdioPipes)> {
+    pub fn spawn(
+        &mut self,
+        _default: Stdio,
+        _needs_stdin: bool,
+    ) -> io::Result<(Process, StdioPipes)> {
         unsupported()
     }
 }
@@ -106,8 +102,7 @@ impl PartialEq for ExitStatus {
     }
 }
 
-impl Eq for ExitStatus {
-}
+impl Eq for ExitStatus {}
 
 impl fmt::Debug for ExitStatus {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/src/libstd/sys/wasm/alloc.rs b/src/libstd/sys/wasm/alloc.rs
index c1af6ec1262..05e55334ac0 100644
--- a/src/libstd/sys/wasm/alloc.rs
+++ b/src/libstd/sys/wasm/alloc.rs
@@ -67,7 +67,7 @@ mod lock {
             //
             //     unsafe {
             //         let r = core::arch::wasm32::i32_atomic_wait(
-            //             &LOCKED as *const AtomicI32 as *mut i32,
+            //             LOCKED.as_mut_ptr(),
             //             1,  //     expected value
             //             -1, //     timeout
             //         );
@@ -143,7 +143,7 @@ mod lock {
             //
             //     unsafe {
             //         core::arch::wasm32::atomic_notify(
-            //             &LOCKED as *const AtomicI32 as *mut i32,
+            //             LOCKED.as_mut_ptr(),
             //             1, //     only one thread
             //         );
             //     }
diff --git a/src/libstd/sys/wasm/args.rs b/src/libstd/sys/wasm/args.rs
index 8279e5280e9..3b6557ae325 100644
--- a/src/libstd/sys/wasm/args.rs
+++ b/src/libstd/sys/wasm/args.rs
@@ -6,14 +6,10 @@ pub unsafe fn init(_argc: isize, _argv: *const *const u8) {
     // On wasm these should always be null, so there's nothing for us to do here
 }
 
-pub unsafe fn cleanup() {
-}
+pub unsafe fn cleanup() {}
 
 pub fn args() -> Args {
-    Args {
-        iter: Vec::new().into_iter(),
-        _dont_send_or_sync_me: PhantomData,
-    }
+    Args { iter: Vec::new().into_iter(), _dont_send_or_sync_me: PhantomData }
 }
 
 pub struct Args {
diff --git a/src/libstd/sys/wasm/cmath.rs b/src/libstd/sys/wasm/cmath.rs
index fa7783122c2..304cf906b2a 100644
--- a/src/libstd/sys/wasm/cmath.rs
+++ b/src/libstd/sys/wasm/cmath.rs
@@ -1,5 +1,5 @@
 // These symbols are all defined in `compiler-builtins`
-extern {
+extern "C" {
     pub fn acos(n: f64) -> f64;
     pub fn acosf(n: f32) -> f32;
     pub fn asin(n: f64) -> f64;
diff --git a/src/libstd/sys/wasm/condvar_atomics.rs b/src/libstd/sys/wasm/condvar_atomics.rs
index 580d2121844..f452bbd3487 100644
--- a/src/libstd/sys/wasm/condvar_atomics.rs
+++ b/src/libstd/sys/wasm/condvar_atomics.rs
@@ -89,6 +89,6 @@ impl Condvar {
     #[inline]
     fn ptr(&self) -> *mut i32 {
         assert_eq!(mem::size_of::<usize>(), mem::size_of::<i32>());
-        &self.cnt as *const AtomicUsize as *mut i32
+        self.cnt.as_mut_ptr() as *mut i32
     }
 }
diff --git a/src/libstd/sys/wasm/fs.rs b/src/libstd/sys/wasm/fs.rs
index e9095b375fe..e6160d1457d 100644
--- a/src/libstd/sys/wasm/fs.rs
+++ b/src/libstd/sys/wasm/fs.rs
@@ -1,7 +1,7 @@
 use crate::ffi::OsString;
 use crate::fmt;
 use crate::hash::{Hash, Hasher};
-use crate::io::{self, SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, IoSlice, IoSliceMut, SeekFrom};
 use crate::path::{Path, PathBuf};
 use crate::sys::time::SystemTime;
 use crate::sys::{unsupported, Void};
@@ -15,14 +15,14 @@ pub struct ReadDir(Void);
 pub struct DirEntry(Void);
 
 #[derive(Clone, Debug)]
-pub struct OpenOptions { }
+pub struct OpenOptions {}
 
 pub struct FilePermissions(Void);
 
 pub struct FileType(Void);
 
 #[derive(Debug)]
-pub struct DirBuilder { }
+pub struct DirBuilder {}
 
 impl FileAttr {
     pub fn size(&self) -> u64 {
@@ -78,8 +78,7 @@ impl PartialEq for FilePermissions {
     }
 }
 
-impl Eq for FilePermissions {
-}
+impl Eq for FilePermissions {}
 
 impl fmt::Debug for FilePermissions {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -115,8 +114,7 @@ impl PartialEq for FileType {
     }
 }
 
-impl Eq for FileType {
-}
+impl Eq for FileType {}
 
 impl Hash for FileType {
     fn hash<H: Hasher>(&self, _h: &mut H) {
@@ -164,15 +162,15 @@ impl DirEntry {
 
 impl OpenOptions {
     pub fn new() -> OpenOptions {
-        OpenOptions { }
+        OpenOptions {}
     }
 
-    pub fn read(&mut self, _read: bool) { }
-    pub fn write(&mut self, _write: bool) { }
-    pub fn append(&mut self, _append: bool) { }
-    pub fn truncate(&mut self, _truncate: bool) { }
-    pub fn create(&mut self, _create: bool) { }
-    pub fn create_new(&mut self, _create_new: bool) { }
+    pub fn read(&mut self, _read: bool) {}
+    pub fn write(&mut self, _write: bool) {}
+    pub fn append(&mut self, _append: bool) {}
+    pub fn truncate(&mut self, _truncate: bool) {}
+    pub fn create(&mut self, _create: bool) {}
+    pub fn create_new(&mut self, _create_new: bool) {}
 }
 
 impl File {
@@ -235,7 +233,7 @@ impl File {
 
 impl DirBuilder {
     pub fn new() -> DirBuilder {
-        DirBuilder { }
+        DirBuilder {}
     }
 
     pub fn mkdir(&self, _p: &Path) -> io::Result<()> {
diff --git a/src/libstd/sys/wasm/mutex_atomics.rs b/src/libstd/sys/wasm/mutex_atomics.rs
index 0e4f3d80aa9..cddd584dd22 100644
--- a/src/libstd/sys/wasm/mutex_atomics.rs
+++ b/src/libstd/sys/wasm/mutex_atomics.rs
@@ -56,7 +56,7 @@ impl Mutex {
     #[inline]
     fn ptr(&self) -> *mut i32 {
         assert_eq!(mem::size_of::<usize>(), mem::size_of::<i32>());
-        &self.locked as *const AtomicUsize as *mut isize as *mut i32
+        self.locked.as_mut_ptr() as *mut i32
     }
 }
 
@@ -145,6 +145,6 @@ impl ReentrantMutex {
 
     #[inline]
     fn ptr(&self) -> *mut i32 {
-        &self.owner as *const AtomicU32 as *mut i32
+        self.owner.as_mut_ptr() as *mut i32
     }
 }
diff --git a/src/libstd/sys/wasm/net.rs b/src/libstd/sys/wasm/net.rs
index d50f989d2bb..b7c3108f172 100644
--- a/src/libstd/sys/wasm/net.rs
+++ b/src/libstd/sys/wasm/net.rs
@@ -1,9 +1,9 @@
+use crate::convert::TryFrom;
 use crate::fmt;
 use crate::io::{self, IoSlice, IoSliceMut};
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
-use crate::time::Duration;
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
 use crate::sys::{unsupported, Void};
-use crate::convert::TryFrom;
+use crate::time::Duration;
 
 pub struct TcpStream(Void);
 
@@ -228,23 +228,19 @@ impl UdpSocket {
         match self.0 {}
     }
 
-    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
         match self.0 {}
     }
 
-    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
         match self.0 {}
     }
 
@@ -351,8 +347,7 @@ pub mod netc {
     }
 
     #[derive(Copy, Clone)]
-    pub struct sockaddr {
-    }
+    pub struct sockaddr {}
 
     pub type socklen_t = usize;
 }
diff --git a/src/libstd/sys/wasm/os.rs b/src/libstd/sys/wasm/os.rs
index 890049e8bfa..193c3892743 100644
--- a/src/libstd/sys/wasm/os.rs
+++ b/src/libstd/sys/wasm/os.rs
@@ -1,5 +1,5 @@
 use crate::error::Error as StdError;
-use crate::ffi::{OsString, OsStr};
+use crate::ffi::{OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::path::{self, PathBuf};
@@ -39,7 +39,9 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(_paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     Err(JoinPathsError)
 }
diff --git a/src/libstd/sys/wasm/path.rs b/src/libstd/sys/wasm/path.rs
index 7a183956107..840a7ae0426 100644
--- a/src/libstd/sys/wasm/path.rs
+++ b/src/libstd/sys/wasm/path.rs
@@ -1,5 +1,5 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
+use crate::path::Prefix;
 
 #[inline]
 pub fn is_sep_byte(b: u8) -> bool {
diff --git a/src/libstd/sys/wasm/pipe.rs b/src/libstd/sys/wasm/pipe.rs
index 9f07f054362..fb14dc59101 100644
--- a/src/libstd/sys/wasm/pipe.rs
+++ b/src/libstd/sys/wasm/pipe.rs
@@ -25,9 +25,6 @@ impl AnonPipe {
     }
 }
 
-pub fn read2(p1: AnonPipe,
-             _v1: &mut Vec<u8>,
-             _p2: AnonPipe,
-             _v2: &mut Vec<u8>) -> io::Result<()> {
+pub fn read2(p1: AnonPipe, _v1: &mut Vec<u8>, _p2: AnonPipe, _v2: &mut Vec<u8>) -> io::Result<()> {
     match p1.0 {}
 }
diff --git a/src/libstd/sys/wasm/process.rs b/src/libstd/sys/wasm/process.rs
index edf933d10e0..4702e5c5492 100644
--- a/src/libstd/sys/wasm/process.rs
+++ b/src/libstd/sys/wasm/process.rs
@@ -32,32 +32,28 @@ pub enum Stdio {
 
 impl Command {
     pub fn new(_program: &OsStr) -> Command {
-        Command {
-            env: Default::default()
-        }
+        Command { env: Default::default() }
     }
 
-    pub fn arg(&mut self, _arg: &OsStr) {
-    }
+    pub fn arg(&mut self, _arg: &OsStr) {}
 
     pub fn env_mut(&mut self) -> &mut CommandEnv {
         &mut self.env
     }
 
-    pub fn cwd(&mut self, _dir: &OsStr) {
-    }
+    pub fn cwd(&mut self, _dir: &OsStr) {}
 
-    pub fn stdin(&mut self, _stdin: Stdio) {
-    }
+    pub fn stdin(&mut self, _stdin: Stdio) {}
 
-    pub fn stdout(&mut self, _stdout: Stdio) {
-    }
+    pub fn stdout(&mut self, _stdout: Stdio) {}
 
-    pub fn stderr(&mut self, _stderr: Stdio) {
-    }
+    pub fn stderr(&mut self, _stderr: Stdio) {}
 
-    pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool)
-        -> io::Result<(Process, StdioPipes)> {
+    pub fn spawn(
+        &mut self,
+        _default: Stdio,
+        _needs_stdin: bool,
+    ) -> io::Result<(Process, StdioPipes)> {
         unsupported()
     }
 }
@@ -106,8 +102,7 @@ impl PartialEq for ExitStatus {
     }
 }
 
-impl Eq for ExitStatus {
-}
+impl Eq for ExitStatus {}
 
 impl fmt::Debug for ExitStatus {
     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/src/libstd/sys/wasm/stack_overflow.rs b/src/libstd/sys/wasm/stack_overflow.rs
index c0e7c824615..cbf62b6e5b7 100644
--- a/src/libstd/sys/wasm/stack_overflow.rs
+++ b/src/libstd/sys/wasm/stack_overflow.rs
@@ -6,8 +6,6 @@ impl Handler {
     }
 }
 
-pub unsafe fn init() {
-}
+pub unsafe fn init() {}
 
-pub unsafe fn cleanup() {
-}
+pub unsafe fn cleanup() {}
diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs
index d06965f3278..0e0e78a8276 100644
--- a/src/libstd/sys/wasm/thread.rs
+++ b/src/libstd/sys/wasm/thread.rs
@@ -9,9 +9,7 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
 
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
-    pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>)
-        -> io::Result<Thread>
-    {
+    pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         unsupported()
     }
 
@@ -55,8 +53,12 @@ impl Thread {
 
 pub mod guard {
     pub type Guard = !;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
 }
 
 // This is only used by atomics primitives when the `atomics` feature is
@@ -84,9 +86,7 @@ pub fn my_id() -> u32 {
         if MY_ID == 0 {
             let mut cur = NEXT_ID.load(SeqCst);
             MY_ID = loop {
-                let next = cur.checked_add(1).unwrap_or_else(|| {
-                    crate::arch::wasm32::unreachable()
-                });
+                let next = cur.checked_add(1).unwrap_or_else(|| crate::arch::wasm32::unreachable());
                 match NEXT_ID.compare_exchange(cur, next, SeqCst, SeqCst) {
                     Ok(_) => break next,
                     Err(i) => cur = i,
diff --git a/src/libstd/sys/wasm/thread_local.rs b/src/libstd/sys/wasm/thread_local.rs
index 8a0ca6f3d25..f8be9863ed5 100644
--- a/src/libstd/sys/wasm/thread_local.rs
+++ b/src/libstd/sys/wasm/thread_local.rs
@@ -1,7 +1,7 @@
 pub type Key = usize;
 
 #[inline]
-pub unsafe fn create(_dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+pub unsafe fn create(_dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
     panic!("should not be used on the wasm target");
 }
 
diff --git a/src/libstd/sys/wasm/time.rs b/src/libstd/sys/wasm/time.rs
index dd9ad3760b0..d9edc7fdc44 100644
--- a/src/libstd/sys/wasm/time.rs
+++ b/src/libstd/sys/wasm/time.rs
@@ -39,8 +39,7 @@ impl SystemTime {
         panic!("time not implemented on wasm32-unknown-unknown")
     }
 
-    pub fn sub_time(&self, other: &SystemTime)
-                    -> Result<Duration, Duration> {
+    pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
         self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
     }
 
diff --git a/src/libstd/sys/windows/alloc.rs b/src/libstd/sys/windows/alloc.rs
index a33c4019a2e..99b4d6c72a0 100644
--- a/src/libstd/sys/windows/alloc.rs
+++ b/src/libstd/sys/windows/alloc.rs
@@ -1,6 +1,6 @@
 use crate::alloc::{GlobalAlloc, Layout, System};
 use crate::sys::c;
-use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
+use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN};
 
 #[repr(C)]
 struct Header(*mut u8);
@@ -18,16 +18,12 @@ unsafe fn align_ptr(ptr: *mut u8, align: usize) -> *mut u8 {
 #[inline]
 unsafe fn allocate_with_flags(layout: Layout, flags: c::DWORD) -> *mut u8 {
     if layout.align() <= MIN_ALIGN {
-        return c::HeapAlloc(c::GetProcessHeap(), flags, layout.size()) as *mut u8
+        return c::HeapAlloc(c::GetProcessHeap(), flags, layout.size()) as *mut u8;
     }
 
     let size = layout.size() + layout.align();
     let ptr = c::HeapAlloc(c::GetProcessHeap(), flags, size);
-    if ptr.is_null() {
-        ptr as *mut u8
-    } else {
-        align_ptr(ptr as *mut u8, layout.align())
-    }
+    if ptr.is_null() { ptr as *mut u8 } else { align_ptr(ptr as *mut u8, layout.align()) }
 }
 
 #[stable(feature = "alloc_system_type", since = "1.28.0")]
@@ -46,13 +42,11 @@ unsafe impl GlobalAlloc for System {
     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
         if layout.align() <= MIN_ALIGN {
             let err = c::HeapFree(c::GetProcessHeap(), 0, ptr as c::LPVOID);
-            debug_assert!(err != 0, "Failed to free heap memory: {}",
-                          c::GetLastError());
+            debug_assert!(err != 0, "Failed to free heap memory: {}", c::GetLastError());
         } else {
             let header = get_header(ptr);
             let err = c::HeapFree(c::GetProcessHeap(), 0, header.0 as c::LPVOID);
-            debug_assert!(err != 0, "Failed to free heap memory: {}",
-                          c::GetLastError());
+            debug_assert!(err != 0, "Failed to free heap memory: {}", c::GetLastError());
         }
     }
 
diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs
index b04bb484eed..5fbea2a2910 100644
--- a/src/libstd/sys/windows/args.rs
+++ b/src/libstd/sys/windows/args.rs
@@ -1,26 +1,26 @@
 #![allow(dead_code)] // runtime init functions not used during testing
 
-use crate::os::windows::prelude::*;
-use crate::sys::windows::os::current_exe;
-use crate::sys::c;
 use crate::ffi::OsString;
 use crate::fmt;
-use crate::vec;
-use crate::slice;
+use crate::os::windows::prelude::*;
 use crate::path::PathBuf;
+use crate::slice;
+use crate::sys::c;
+use crate::sys::windows::os::current_exe;
+use crate::vec;
 
 use core::iter;
 
-pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }
+pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
 
-pub unsafe fn cleanup() { }
+pub unsafe fn cleanup() {}
 
 pub fn args() -> Args {
     unsafe {
         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()));
+        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())
+        });
 
         Args { parsed_args_list: parsed_args_list.into_iter() }
     }
@@ -40,8 +40,10 @@ pub fn args() -> Args {
 /// 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> {
+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;
@@ -84,7 +86,7 @@ unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_na
         0..=SPACE => {
             ret_val.push(OsString::new());
             &cmd_line[1..]
-        },
+        }
         // The executable name ends at the next whitespace,
         // no matter what.
         _ => {
@@ -112,7 +114,7 @@ unsafe fn parse_lp_cmd_line<F: Fn() -> OsString>(lp_cmd_line: *const u16, exe_na
             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;
@@ -171,30 +173,36 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> {
 
 impl Args {
     pub fn inner_debug(&self) -> ArgsInnerDebug<'_> {
-        ArgsInnerDebug {
-            args: self
-        }
+        ArgsInnerDebug { args: self }
     }
 }
 
 impl Iterator for Args {
     type Item = OsString;
-    fn next(&mut self) -> Option<OsString> { self.parsed_args_list.next() }
-    fn size_hint(&self) -> (usize, Option<usize>) { self.parsed_args_list.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.parsed_args_list.next_back() }
+    fn next_back(&mut self) -> Option<OsString> {
+        self.parsed_args_list.next_back()
+    }
 }
 
 impl ExactSizeIterator for Args {
-    fn len(&self) -> usize { self.parsed_args_list.len() }
+    fn len(&self) -> usize {
+        self.parsed_args_list.len()
+    }
 }
 
 #[cfg(test)]
 mod tests {
-    use crate::sys::windows::args::*;
     use crate::ffi::OsString;
+    use crate::sys::windows::args::*;
 
     fn chk(string: &str, parts: &[&str]) {
         let mut wide: Vec<u16> = OsString::from(string).encode_wide().collect();
@@ -245,7 +253,7 @@ mod tests {
         chk(r#"EXE "" """"#, &["EXE", "", "\""]);
         chk(
             r#"EXE "this is """all""" in the same argument""#,
-            &["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"]);
@@ -253,6 +261,6 @@ mod tests {
         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"]);
+        chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#, "check"]);
     }
 }
diff --git a/src/libstd/sys/windows/cmath.rs b/src/libstd/sys/windows/cmath.rs
index e744cb219a8..7c5bfa1bd06 100644
--- a/src/libstd/sys/windows/cmath.rs
+++ b/src/libstd/sys/windows/cmath.rs
@@ -1,9 +1,9 @@
 #![cfg(not(test))]
 
-use libc::{c_float, c_double};
+use libc::{c_double, c_float};
 
 #[link_name = "m"]
-extern {
+extern "C" {
     pub fn acos(n: c_double) -> c_double;
     pub fn asin(n: c_double) -> c_double;
     pub fn atan(n: c_double) -> c_double;
@@ -32,7 +32,7 @@ pub use self::shims::*;
 mod shims {
     use libc::c_float;
 
-    extern {
+    extern "C" {
         pub fn acosf(n: c_float) -> c_float;
         pub fn asinf(n: c_float) -> c_float;
         pub fn atan2f(a: c_float, b: c_float) -> c_float;
diff --git a/src/libstd/sys/windows/compat.rs b/src/libstd/sys/windows/compat.rs
index 544b2087f92..d6d433f9d08 100644
--- a/src/libstd/sys/windows/compat.rs
+++ b/src/libstd/sys/windows/compat.rs
@@ -28,8 +28,7 @@ pub fn lookup(module: &str, symbol: &str) -> Option<usize> {
     }
 }
 
-pub fn store_func(ptr: &AtomicUsize, module: &str, symbol: &str,
-                  fallback: usize) -> usize {
+pub fn store_func(ptr: &AtomicUsize, module: &str, symbol: &str, fallback: usize) -> usize {
     let value = lookup(module, symbol).unwrap_or(fallback);
     ptr.store(value, Ordering::SeqCst);
     value
diff --git a/src/libstd/sys/windows/ext/ffi.rs b/src/libstd/sys/windows/ext/ffi.rs
index 1381825806f..6e78119383f 100644
--- a/src/libstd/sys/windows/ext/ffi.rs
+++ b/src/libstd/sys/windows/ext/ffi.rs
@@ -59,10 +59,10 @@
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-use crate::ffi::{OsString, OsStr};
+use crate::ffi::{OsStr, OsString};
 use crate::sys::os_str::Buf;
 use crate::sys_common::wtf8::Wtf8Buf;
-use crate::sys_common::{FromInner, AsInner};
+use crate::sys_common::{AsInner, FromInner};
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use crate::sys_common::wtf8::EncodeWide;
diff --git a/src/libstd/sys/windows/ext/fs.rs b/src/libstd/sys/windows/ext/fs.rs
index 23964dc5bd5..7eaff226a76 100644
--- a/src/libstd/sys/windows/ext/fs.rs
+++ b/src/libstd/sys/windows/ext/fs.rs
@@ -2,11 +2,11 @@
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
-use crate::fs::{self, OpenOptions, Metadata};
+use crate::fs::{self, Metadata, OpenOptions};
 use crate::io;
 use crate::path::Path;
 use crate::sys;
-use crate::sys_common::{AsInnerMut, AsInner};
+use crate::sys_common::{AsInner, AsInnerMut};
 
 /// Windows-specific extensions to [`File`].
 ///
@@ -265,23 +265,28 @@ pub trait OpenOptionsExt {
 #[stable(feature = "open_options_ext", since = "1.10.0")]
 impl OpenOptionsExt for OpenOptions {
     fn access_mode(&mut self, access: u32) -> &mut OpenOptions {
-        self.as_inner_mut().access_mode(access); self
+        self.as_inner_mut().access_mode(access);
+        self
     }
 
     fn share_mode(&mut self, share: u32) -> &mut OpenOptions {
-        self.as_inner_mut().share_mode(share); self
+        self.as_inner_mut().share_mode(share);
+        self
     }
 
     fn custom_flags(&mut self, flags: u32) -> &mut OpenOptions {
-        self.as_inner_mut().custom_flags(flags); self
+        self.as_inner_mut().custom_flags(flags);
+        self
     }
 
     fn attributes(&mut self, attributes: u32) -> &mut OpenOptions {
-        self.as_inner_mut().attributes(attributes); self
+        self.as_inner_mut().attributes(attributes);
+        self
     }
 
     fn security_qos_flags(&mut self, flags: u32) -> &mut OpenOptions {
-        self.as_inner_mut().security_qos_flags(flags); self
+        self.as_inner_mut().security_qos_flags(flags);
+        self
     }
 }
 
@@ -468,14 +473,30 @@ pub trait MetadataExt {
 
 #[stable(feature = "metadata_ext", since = "1.1.0")]
 impl MetadataExt for Metadata {
-    fn file_attributes(&self) -> u32 { self.as_inner().attrs() }
-    fn creation_time(&self) -> u64 { self.as_inner().created_u64() }
-    fn last_access_time(&self) -> u64 { self.as_inner().accessed_u64() }
-    fn last_write_time(&self) -> u64 { self.as_inner().modified_u64() }
-    fn file_size(&self) -> u64 { self.as_inner().size() }
-    fn volume_serial_number(&self) -> Option<u32> { self.as_inner().volume_serial_number() }
-    fn number_of_links(&self) -> Option<u32> { self.as_inner().number_of_links() }
-    fn file_index(&self) -> Option<u64> { self.as_inner().file_index() }
+    fn file_attributes(&self) -> u32 {
+        self.as_inner().attrs()
+    }
+    fn creation_time(&self) -> u64 {
+        self.as_inner().created_u64()
+    }
+    fn last_access_time(&self) -> u64 {
+        self.as_inner().accessed_u64()
+    }
+    fn last_write_time(&self) -> u64 {
+        self.as_inner().modified_u64()
+    }
+    fn file_size(&self) -> u64 {
+        self.as_inner().size()
+    }
+    fn volume_serial_number(&self) -> Option<u32> {
+        self.as_inner().volume_serial_number()
+    }
+    fn number_of_links(&self) -> Option<u32> {
+        self.as_inner().number_of_links()
+    }
+    fn file_index(&self) -> Option<u64> {
+        self.as_inner().file_index()
+    }
 }
 
 /// Windows-specific extensions to [`FileType`].
@@ -495,8 +516,12 @@ pub trait FileTypeExt {
 
 #[unstable(feature = "windows_file_type_ext", issue = "0")]
 impl FileTypeExt for fs::FileType {
-    fn is_symlink_dir(&self) -> bool { self.as_inner().is_symlink_dir() }
-    fn is_symlink_file(&self) -> bool { self.as_inner().is_symlink_file() }
+    fn is_symlink_dir(&self) -> bool {
+        self.as_inner().is_symlink_dir()
+    }
+    fn is_symlink_file(&self) -> bool {
+        self.as_inner().is_symlink_file()
+    }
 }
 
 /// Creates a new file symbolic link on the filesystem.
@@ -515,8 +540,7 @@ impl FileTypeExt for fs::FileType {
 /// }
 /// ```
 #[stable(feature = "symlink", since = "1.1.0")]
-pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
-                                                    -> io::Result<()> {
+pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
     sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), false)
 }
 
@@ -536,7 +560,6 @@ pub fn symlink_file<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
 /// }
 /// ```
 #[stable(feature = "symlink", since = "1.1.0")]
-pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q)
-                                                   -> io::Result<()> {
+pub fn symlink_dir<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
     sys::fs::symlink_inner(src.as_ref(), dst.as_ref(), true)
 }
diff --git a/src/libstd/sys/windows/ext/io.rs b/src/libstd/sys/windows/ext/io.rs
index ec47c2e9d5a..4573ee58932 100644
--- a/src/libstd/sys/windows/ext/io.rs
+++ b/src/libstd/sys/windows/ext/io.rs
@@ -1,12 +1,12 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use crate::fs;
-use crate::os::windows::raw;
+use crate::io;
 use crate::net;
-use crate::sys_common::{self, AsInner, FromInner, IntoInner};
+use crate::os::windows::raw;
 use crate::sys;
 use crate::sys::c;
-use crate::io;
+use crate::sys_common::{self, AsInner, FromInner, IntoInner};
 
 /// Raw HANDLEs.
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/src/libstd/sys/windows/ext/mod.rs b/src/libstd/sys/windows/ext/mod.rs
index 0a6d435d329..613d3dc189a 100644
--- a/src/libstd/sys/windows/ext/mod.rs
+++ b/src/libstd/sys/windows/ext/mod.rs
@@ -13,8 +13,8 @@
 pub mod ffi;
 pub mod fs;
 pub mod io;
-pub mod raw;
 pub mod process;
+pub mod raw;
 pub mod thread;
 
 /// A prelude for conveniently writing platform-specific code.
@@ -22,14 +22,19 @@ pub mod thread;
 /// Includes all extension traits, and some important type definitions.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub mod prelude {
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use super::io::{RawSocket, RawHandle, AsRawSocket, AsRawHandle};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use super::io::{FromRawSocket, FromRawHandle, IntoRawSocket, IntoRawHandle};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
     pub use super::ffi::{OsStrExt, OsStringExt};
-    #[doc(no_inline)] #[stable(feature = "rust1", since = "1.0.0")]
-    pub use super::fs::{OpenOptionsExt, MetadataExt};
-    #[doc(no_inline)] #[stable(feature = "file_offset", since = "1.15.0")]
+    #[doc(no_inline)]
+    #[stable(feature = "file_offset", since = "1.15.0")]
     pub use super::fs::FileExt;
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use super::fs::{MetadataExt, OpenOptionsExt};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use super::io::{AsRawHandle, AsRawSocket, RawHandle, RawSocket};
+    #[doc(no_inline)]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub use super::io::{FromRawHandle, FromRawSocket, IntoRawHandle, IntoRawSocket};
 }
diff --git a/src/libstd/sys/windows/ext/process.rs b/src/libstd/sys/windows/ext/process.rs
index b2e6cdead4f..ed35c5ff194 100644
--- a/src/libstd/sys/windows/ext/process.rs
+++ b/src/libstd/sys/windows/ext/process.rs
@@ -2,10 +2,10 @@
 
 #![stable(feature = "process_extensions", since = "1.2.0")]
 
-use crate::os::windows::io::{FromRawHandle, RawHandle, AsRawHandle, IntoRawHandle};
+use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
 use crate::process;
 use crate::sys;
-use crate::sys_common::{AsInnerMut, AsInner, FromInner, IntoInner};
+use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
 
 #[stable(feature = "process_extensions", since = "1.2.0")]
 impl FromRawHandle for process::Stdio {
diff --git a/src/libstd/sys/windows/ext/raw.rs b/src/libstd/sys/windows/ext/raw.rs
index d2bab272036..7f2a2877828 100644
--- a/src/libstd/sys/windows/ext/raw.rs
+++ b/src/libstd/sys/windows/ext/raw.rs
@@ -4,8 +4,11 @@
 
 use crate::os::raw::c_void;
 
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type HANDLE = *mut c_void;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type HANDLE = *mut c_void;
 #[cfg(target_pointer_width = "32")]
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type SOCKET = u32;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type SOCKET = u32;
 #[cfg(target_pointer_width = "64")]
-#[stable(feature = "raw_ext", since = "1.1.0")] pub type SOCKET = u64;
+#[stable(feature = "raw_ext", since = "1.1.0")]
+pub type SOCKET = u64;
diff --git a/src/libstd/sys/windows/ext/thread.rs b/src/libstd/sys/windows/ext/thread.rs
index fdc7e7fa32f..41c29f5b950 100644
--- a/src/libstd/sys/windows/ext/thread.rs
+++ b/src/libstd/sys/windows/ext/thread.rs
@@ -2,9 +2,9 @@
 
 #![stable(feature = "thread_extensions", since = "1.9.0")]
 
-use crate::os::windows::io::{RawHandle, AsRawHandle, IntoRawHandle};
-use crate::thread;
+use crate::os::windows::io::{AsRawHandle, IntoRawHandle, RawHandle};
 use crate::sys_common::{AsInner, IntoInner};
+use crate::thread;
 
 #[stable(feature = "thread_extensions", since = "1.9.0")]
 impl<T> AsRawHandle for thread::JoinHandle<T> {
@@ -14,7 +14,7 @@ impl<T> AsRawHandle for thread::JoinHandle<T> {
 }
 
 #[stable(feature = "thread_extensions", since = "1.9.0")]
-impl<T> IntoRawHandle for thread::JoinHandle<T>  {
+impl<T> IntoRawHandle for thread::JoinHandle<T> {
     fn into_raw_handle(self) -> RawHandle {
         self.into_inner().into_handle().into_raw() as *mut _
     }
diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs
index 4160123c9a2..e9c84c4e7c9 100644
--- a/src/libstd/sys/windows/fs.rs
+++ b/src/libstd/sys/windows/fs.rs
@@ -2,7 +2,7 @@ use crate::os::windows::prelude::*;
 
 use crate::ffi::OsString;
 use crate::fmt;
-use crate::io::{self, Error, SeekFrom, IoSlice, IoSliceMut};
+use crate::io::{self, Error, IoSlice, IoSliceMut, SeekFrom};
 use crate::mem;
 use crate::path::{Path, PathBuf};
 use crate::ptr;
@@ -15,7 +15,9 @@ use crate::sys_common::FromInner;
 
 use super::to_u16s;
 
-pub struct File { handle: Handle }
+pub struct File {
+    handle: Handle,
+}
 
 #[derive(Clone)]
 pub struct FileAttr {
@@ -71,7 +73,9 @@ pub struct OpenOptions {
 }
 
 #[derive(Clone, PartialEq, Eq, Debug)]
-pub struct FilePermissions { attrs: c::DWORD }
+pub struct FilePermissions {
+    attrs: c::DWORD,
+}
 
 #[derive(Debug)]
 pub struct DirBuilder;
@@ -97,13 +101,13 @@ impl Iterator for ReadDir {
             loop {
                 if c::FindNextFileW(self.handle.0, &mut wfd) == 0 {
                     if c::GetLastError() == c::ERROR_NO_MORE_FILES {
-                        return None
+                        return None;
                     } else {
-                        return Some(Err(Error::last_os_error()))
+                        return Some(Err(Error::last_os_error()));
                     }
                 }
                 if let Some(e) = DirEntry::new(&self.root, &wfd) {
-                    return Some(Ok(e))
+                    return Some(Ok(e));
                 }
             }
         }
@@ -121,15 +125,11 @@ impl DirEntry {
     fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> {
         match &wfd.cFileName[0..3] {
             // check for '.' and '..'
-            &[46, 0, ..] |
-            &[46, 46, 0, ..] => return None,
+            &[46, 0, ..] | &[46, 46, 0, ..] => return None,
             _ => {}
         }
 
-        Some(DirEntry {
-            root: root.clone(),
-            data: *wfd,
-        })
+        Some(DirEntry { root: root.clone(), data: *wfd })
     }
 
     pub fn path(&self) -> PathBuf {
@@ -142,8 +142,10 @@ impl DirEntry {
     }
 
     pub fn file_type(&self) -> io::Result<FileType> {
-        Ok(FileType::new(self.data.dwFileAttributes,
-                         /* reparse_tag = */ self.data.dwReserved0))
+        Ok(FileType::new(
+            self.data.dwFileAttributes,
+            /* reparse_tag = */ self.data.dwReserved0,
+        ))
     }
 
     pub fn metadata(&self) -> io::Result<FileAttr> {
@@ -154,11 +156,11 @@ impl DirEntry {
             last_write_time: self.data.ftLastWriteTime,
             file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64),
             reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
-                    // reserved unless this is a reparse point
-                    self.data.dwReserved0
-                } else {
-                    0
-                },
+                // reserved unless this is a reparse point
+                self.data.dwReserved0
+            } else {
+                0
+            },
             volume_serial_number: None,
             number_of_links: None,
             file_index: None,
@@ -186,17 +188,37 @@ impl OpenOptions {
         }
     }
 
-    pub fn read(&mut self, read: bool) { self.read = read; }
-    pub fn write(&mut self, write: bool) { self.write = write; }
-    pub fn append(&mut self, append: bool) { self.append = append; }
-    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
-    pub fn create(&mut self, create: bool) { self.create = create; }
-    pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+    pub fn append(&mut self, append: bool) {
+        self.append = append;
+    }
+    pub fn truncate(&mut self, truncate: bool) {
+        self.truncate = truncate;
+    }
+    pub fn create(&mut self, create: bool) {
+        self.create = create;
+    }
+    pub fn create_new(&mut self, create_new: bool) {
+        self.create_new = create_new;
+    }
 
-    pub fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; }
-    pub fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); }
-    pub fn share_mode(&mut self, share_mode: u32) { self.share_mode = share_mode; }
-    pub fn attributes(&mut self, attrs: u32) { self.attributes = attrs; }
+    pub fn custom_flags(&mut self, flags: u32) {
+        self.custom_flags = flags;
+    }
+    pub fn access_mode(&mut self, access_mode: u32) {
+        self.access_mode = Some(access_mode);
+    }
+    pub fn share_mode(&mut self, share_mode: u32) {
+        self.share_mode = share_mode;
+    }
+    pub fn attributes(&mut self, attrs: u32) {
+        self.attributes = attrs;
+    }
     pub fn security_qos_flags(&mut self, flags: u32) {
         // We have to set `SECURITY_SQOS_PRESENT` here, because one of the valid flags we can
         // receive is `SECURITY_ANONYMOUS = 0x0`, which we can't check for later on.
@@ -211,12 +233,13 @@ impl OpenOptions {
 
         match (self.read, self.write, self.append, self.access_mode) {
             (.., Some(mode)) => Ok(mode),
-            (true,  false, false, None) => Ok(c::GENERIC_READ),
-            (false, true,  false, None) => Ok(c::GENERIC_WRITE),
-            (true,  true,  false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
-            (false, _,     true,  None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
-            (true,  _,     true,  None) => Ok(c::GENERIC_READ |
-                                              (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA)),
+            (true, false, false, None) => Ok(c::GENERIC_READ),
+            (false, true, false, None) => Ok(c::GENERIC_WRITE),
+            (true, true, false, None) => Ok(c::GENERIC_READ | c::GENERIC_WRITE),
+            (false, _, true, None) => Ok(c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA),
+            (true, _, true, None) => {
+                Ok(c::GENERIC_READ | (c::FILE_GENERIC_WRITE & !c::FILE_WRITE_DATA))
+            }
             (false, false, false, None) => Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER)),
         }
     }
@@ -226,30 +249,32 @@ impl OpenOptions {
 
         match (self.write, self.append) {
             (true, false) => {}
-            (false, false) =>
+            (false, false) => {
                 if self.truncate || self.create || self.create_new {
                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
-                },
-            (_, true) =>
+                }
+            }
+            (_, true) => {
                 if self.truncate && !self.create_new {
                     return Err(Error::from_raw_os_error(ERROR_INVALID_PARAMETER));
-                },
+                }
+            }
         }
 
         Ok(match (self.create, self.truncate, self.create_new) {
-                (false, false, false) => c::OPEN_EXISTING,
-                (true,  false, false) => c::OPEN_ALWAYS,
-                (false, true,  false) => c::TRUNCATE_EXISTING,
-                (true,  true,  false) => c::CREATE_ALWAYS,
-                (_,      _,    true)  => c::CREATE_NEW,
-           })
+            (false, false, false) => c::OPEN_EXISTING,
+            (true, false, false) => c::OPEN_ALWAYS,
+            (false, true, false) => c::TRUNCATE_EXISTING,
+            (true, true, false) => c::CREATE_ALWAYS,
+            (_, _, true) => c::CREATE_NEW,
+        })
     }
 
     fn get_flags_and_attributes(&self) -> c::DWORD {
-        self.custom_flags |
-        self.attributes |
-        self.security_qos_flags |
-        if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
+        self.custom_flags
+            | self.attributes
+            | self.security_qos_flags
+            | if self.create_new { c::FILE_FLAG_OPEN_REPARSE_POINT } else { 0 }
     }
 }
 
@@ -257,13 +282,15 @@ impl File {
     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
         let path = to_u16s(path)?;
         let handle = unsafe {
-            c::CreateFileW(path.as_ptr(),
-                           opts.get_access_mode()?,
-                           opts.share_mode,
-                           opts.security_attributes as *mut _,
-                           opts.get_creation_mode()?,
-                           opts.get_flags_and_attributes(),
-                           ptr::null_mut())
+            c::CreateFileW(
+                path.as_ptr(),
+                opts.get_access_mode()?,
+                opts.share_mode,
+                opts.security_attributes as *mut _,
+                opts.get_creation_mode()?,
+                opts.get_flags_and_attributes(),
+                ptr::null_mut(),
+            )
         };
         if handle == c::INVALID_HANDLE_VALUE {
             Err(Error::last_os_error())
@@ -277,18 +304,20 @@ impl File {
         Ok(())
     }
 
-    pub fn datasync(&self) -> io::Result<()> { self.fsync() }
+    pub fn datasync(&self) -> io::Result<()> {
+        self.fsync()
+    }
 
     pub fn truncate(&self, size: u64) -> io::Result<()> {
-        let mut info = c::FILE_END_OF_FILE_INFO {
-            EndOfFile: size as c::LARGE_INTEGER,
-        };
+        let mut info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as c::LARGE_INTEGER };
         let size = mem::size_of_val(&info);
         cvt(unsafe {
-            c::SetFileInformationByHandle(self.handle.raw(),
-                                          c::FileEndOfFileInfo,
-                                          &mut info as *mut _ as *mut _,
-                                          size as c::DWORD)
+            c::SetFileInformationByHandle(
+                self.handle.raw(),
+                c::FileEndOfFileInfo,
+                &mut info as *mut _ as *mut _,
+                size as c::DWORD,
+            )
         })?;
         Ok(())
     }
@@ -314,8 +343,9 @@ impl File {
                 reparse_tag,
                 volume_serial_number: Some(info.dwVolumeSerialNumber),
                 number_of_links: Some(info.nNumberOfLinks),
-                file_index: Some((info.nFileIndexLow as u64) |
-                                 ((info.nFileIndexHigh as u64) << 32)),
+                file_index: Some(
+                    (info.nFileIndexLow as u64) | ((info.nFileIndexHigh as u64) << 32),
+                ),
             })
         }
     }
@@ -325,10 +355,12 @@ impl File {
         unsafe {
             let mut info: c::FILE_BASIC_INFO = mem::zeroed();
             let size = mem::size_of_val(&info);
-            cvt(c::GetFileInformationByHandleEx(self.handle.raw(),
-                                              c::FileBasicInfo,
-                                              &mut info as *mut _ as *mut libc::c_void,
-                                              size as c::DWORD))?;
+            cvt(c::GetFileInformationByHandleEx(
+                self.handle.raw(),
+                c::FileBasicInfo,
+                &mut info as *mut _ as *mut libc::c_void,
+                size as c::DWORD,
+            ))?;
             let mut attr = FileAttr {
                 attributes: info.FileAttributes,
                 creation_time: c::FILETIME {
@@ -351,10 +383,12 @@ impl File {
             };
             let mut info: c::FILE_STANDARD_INFO = mem::zeroed();
             let size = mem::size_of_val(&info);
-            cvt(c::GetFileInformationByHandleEx(self.handle.raw(),
-                                                c::FileStandardInfo,
-                                                &mut info as *mut _ as *mut libc::c_void,
-                                                size as c::DWORD))?;
+            cvt(c::GetFileInformationByHandleEx(
+                self.handle.raw(),
+                c::FileStandardInfo,
+                &mut info as *mut _ as *mut libc::c_void,
+                size as c::DWORD,
+            ))?;
             attr.file_size = info.AllocationSize as u64;
             attr.number_of_links = Some(info.NumberOfLinks);
             if attr.file_type().is_reparse_point() {
@@ -391,7 +425,9 @@ impl File {
         self.handle.write_at(buf, offset)
     }
 
-    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+    pub fn flush(&self) -> io::Result<()> {
+        Ok(())
+    }
 
     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
         let (whence, pos) = match pos {
@@ -403,37 +439,39 @@ impl File {
         };
         let pos = pos as c::LARGE_INTEGER;
         let mut newpos = 0;
-        cvt(unsafe {
-            c::SetFilePointerEx(self.handle.raw(), pos,
-                                &mut newpos, whence)
-        })?;
+        cvt(unsafe { c::SetFilePointerEx(self.handle.raw(), pos, &mut newpos, whence) })?;
         Ok(newpos as u64)
     }
 
     pub fn duplicate(&self) -> io::Result<File> {
-        Ok(File {
-            handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)?,
-        })
+        Ok(File { handle: self.handle.duplicate(0, false, c::DUPLICATE_SAME_ACCESS)? })
     }
 
-    pub fn handle(&self) -> &Handle { &self.handle }
+    pub fn handle(&self) -> &Handle {
+        &self.handle
+    }
 
-    pub fn into_handle(self) -> Handle { self.handle }
+    pub fn into_handle(self) -> Handle {
+        self.handle
+    }
 
-    fn reparse_point<'a>(&self,
-                         space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
-                         -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
+    fn reparse_point<'a>(
+        &self,
+        space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE],
+    ) -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
         unsafe {
             let mut bytes = 0;
             cvt({
-                c::DeviceIoControl(self.handle.raw(),
-                                   c::FSCTL_GET_REPARSE_POINT,
-                                   ptr::null_mut(),
-                                   0,
-                                   space.as_mut_ptr() as *mut _,
-                                   space.len() as c::DWORD,
-                                   &mut bytes,
-                                   ptr::null_mut())
+                c::DeviceIoControl(
+                    self.handle.raw(),
+                    c::FSCTL_GET_REPARSE_POINT,
+                    ptr::null_mut(),
+                    0,
+                    space.as_mut_ptr() as *mut _,
+                    space.len() as c::DWORD,
+                    &mut bytes,
+                    ptr::null_mut(),
+                )
             })?;
             Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
         }
@@ -447,21 +485,29 @@ impl File {
                 c::IO_REPARSE_TAG_SYMLINK => {
                     let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
                         &buf.rest as *const _ as *const _;
-                    (&(*info).PathBuffer as *const _ as *const u16,
-                     (*info).SubstituteNameOffset / 2,
-                     (*info).SubstituteNameLength / 2,
-                     (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0)
-                },
+                    (
+                        &(*info).PathBuffer as *const _ as *const u16,
+                        (*info).SubstituteNameOffset / 2,
+                        (*info).SubstituteNameLength / 2,
+                        (*info).Flags & c::SYMLINK_FLAG_RELATIVE != 0,
+                    )
+                }
                 c::IO_REPARSE_TAG_MOUNT_POINT => {
                     let info: *const c::MOUNT_POINT_REPARSE_BUFFER =
                         &buf.rest as *const _ as *const _;
-                    (&(*info).PathBuffer as *const _ as *const u16,
-                     (*info).SubstituteNameOffset / 2,
-                     (*info).SubstituteNameLength / 2,
-                     false)
-                },
-                _ => return Err(io::Error::new(io::ErrorKind::Other,
-                                               "Unsupported reparse point type"))
+                    (
+                        &(*info).PathBuffer as *const _ as *const u16,
+                        (*info).SubstituteNameOffset / 2,
+                        (*info).SubstituteNameLength / 2,
+                        false,
+                    )
+                }
+                _ => {
+                    return Err(io::Error::new(
+                        io::ErrorKind::Other,
+                        "Unsupported reparse point type",
+                    ));
+                }
             };
             let subst_ptr = path_buffer.offset(subst_off as isize);
             let mut subst = slice::from_raw_parts(subst_ptr, subst_len as usize);
@@ -484,10 +530,12 @@ impl File {
         };
         let size = mem::size_of_val(&info);
         cvt(unsafe {
-            c::SetFileInformationByHandle(self.handle.raw(),
-                                          c::FileBasicInfo,
-                                          &mut info as *mut _ as *mut _,
-                                          size as c::DWORD)
+            c::SetFileInformationByHandle(
+                self.handle.raw(),
+                c::FileBasicInfo,
+                &mut info as *mut _ as *mut _,
+                size as c::DWORD,
+            )
         })?;
         Ok(())
     }
@@ -585,10 +633,7 @@ impl FilePermissions {
 
 impl FileType {
     fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType {
-        FileType {
-            attributes: attrs,
-            reparse_tag: reparse_tag,
-        }
+        FileType { attributes: attrs, reparse_tag: reparse_tag }
     }
     pub fn is_dir(&self) -> bool {
         !self.is_symlink() && self.is_directory()
@@ -617,13 +662,13 @@ impl FileType {
 }
 
 impl DirBuilder {
-    pub fn new() -> DirBuilder { DirBuilder }
+    pub fn new() -> DirBuilder {
+        DirBuilder
+    }
 
     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
         let p = to_u16s(p)?;
-        cvt(unsafe {
-            c::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
-        })?;
+        cvt(unsafe { c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })?;
         Ok(())
     }
 }
@@ -657,9 +702,7 @@ pub fn unlink(p: &Path) -> io::Result<()> {
 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
     let old = to_u16s(old)?;
     let new = to_u16s(new)?;
-    cvt(unsafe {
-        c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING)
-    })?;
+    cvt(unsafe { c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })?;
     Ok(())
 }
 
@@ -701,8 +744,7 @@ pub fn readlink(path: &Path) -> io::Result<PathBuf> {
     // this is needed for a common case.
     let mut opts = OpenOptions::new();
     opts.access_mode(0);
-    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
-                      c::FILE_FLAG_BACKUP_SEMANTICS);
+    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
     let file = File::open(&path, &opts)?;
     file.readlink()
 }
@@ -720,16 +762,17 @@ pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
     // computer is in Developer Mode, but SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE must be
     // added to dwFlags to opt into this behaviour.
     let result = cvt(unsafe {
-        c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(),
-                               flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) as c::BOOL
+        c::CreateSymbolicLinkW(
+            dst.as_ptr(),
+            src.as_ptr(),
+            flags | c::SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
+        ) as c::BOOL
     });
     if let Err(err) = result {
         if err.raw_os_error() == Some(c::ERROR_INVALID_PARAMETER as i32) {
             // Older Windows objects to SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE,
             // so if we encounter ERROR_INVALID_PARAMETER, retry without that flag.
-            cvt(unsafe {
-                c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL
-            })?;
+            cvt(unsafe { c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL })?;
         } else {
             return Err(err);
         }
@@ -741,16 +784,13 @@ pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> {
 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
     let src = to_u16s(src)?;
     let dst = to_u16s(dst)?;
-    cvt(unsafe {
-        c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
-    })?;
+    cvt(unsafe { c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) })?;
     Ok(())
 }
 
 #[cfg(target_vendor = "uwp")]
 pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> {
-    return Err(io::Error::new(io::ErrorKind::Other,
-                            "hard link are not supported on UWP"));
+    return Err(io::Error::new(io::ErrorKind::Other, "hard link are not supported on UWP"));
 }
 
 pub fn stat(path: &Path) -> io::Result<FileAttr> {
@@ -781,12 +821,12 @@ pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
 }
 
 fn get_path(f: &File) -> io::Result<PathBuf> {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz,
-                                     c::VOLUME_NAME_DOS)
-    }, |buf| {
-        PathBuf::from(OsString::from_wide(buf))
-    })
+    super::fill_utf16_buf(
+        |buf, sz| unsafe {
+            c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, c::VOLUME_NAME_DOS)
+        },
+        |buf| PathBuf::from(OsString::from_wide(buf)),
+    )
 }
 
 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
@@ -811,15 +851,23 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
         _hDestinationFile: c::HANDLE,
         lpData: c::LPVOID,
     ) -> c::DWORD {
-        if dwStreamNumber == 1 {*(lpData as *mut i64) = StreamBytesTransferred;}
+        if dwStreamNumber == 1 {
+            *(lpData as *mut i64) = StreamBytesTransferred;
+        }
         c::PROGRESS_CONTINUE
     }
     let pfrom = to_u16s(from)?;
     let pto = to_u16s(to)?;
     let mut size = 0i64;
     cvt(unsafe {
-        c::CopyFileExW(pfrom.as_ptr(), pto.as_ptr(), Some(callback),
-                       &mut size as *mut _ as *mut _, ptr::null_mut(), 0)
+        c::CopyFileExW(
+            pfrom.as_ptr(),
+            pto.as_ptr(),
+            Some(callback),
+            &mut size as *mut _ as *mut _,
+            ptr::null_mut(),
+            0,
+        )
     })?;
     Ok(size as u64)
 }
@@ -841,15 +889,13 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
 
     let mut opts = OpenOptions::new();
     opts.write(true);
-    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT |
-                      c::FILE_FLAG_BACKUP_SEMANTICS);
+    opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
     let f = File::open(junction, &opts)?;
     let h = f.handle().raw();
 
     unsafe {
         let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
-        let db = data.as_mut_ptr()
-                    as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
+        let db = data.as_mut_ptr() as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
         let buf = &mut (*db).ReparseTarget as *mut c::WCHAR;
         let mut i = 0;
         // FIXME: this conversion is very hacky
@@ -864,16 +910,19 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> {
         (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
         (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD;
         (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD;
-        (*db).ReparseDataLength =
-                (*db).ReparseTargetLength as c::DWORD + 12;
+        (*db).ReparseDataLength = (*db).ReparseTargetLength as c::DWORD + 12;
 
         let mut ret = 0;
-        cvt(c::DeviceIoControl(h as *mut _,
-                               c::FSCTL_SET_REPARSE_POINT,
-                               data.as_ptr() as *mut _,
-                               (*db).ReparseDataLength + 8,
-                               ptr::null_mut(), 0,
-                               &mut ret,
-                               ptr::null_mut())).map(|_| ())
+        cvt(c::DeviceIoControl(
+            h as *mut _,
+            c::FSCTL_SET_REPARSE_POINT,
+            data.as_ptr() as *mut _,
+            (*db).ReparseDataLength + 8,
+            ptr::null_mut(),
+            0,
+            &mut ret,
+            ptr::null_mut(),
+        ))
+        .map(|_| ())
     }
 }
diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs
index 3986cda1a50..ebaa0783d60 100644
--- a/src/libstd/sys/windows/handle.rs
+++ b/src/libstd/sys/windows/handle.rs
@@ -1,7 +1,7 @@
 #![unstable(issue = "0", feature = "windows_handle")]
 
 use crate::cmp;
-use crate::io::{self, ErrorKind, Read, IoSlice, IoSliceMut};
+use crate::io::{self, ErrorKind, IoSlice, IoSliceMut, Read};
 use crate::mem;
 use crate::ops::Deref;
 use crate::ptr;
@@ -31,15 +31,9 @@ impl Handle {
 
     pub fn new_event(manual: bool, init: bool) -> io::Result<Handle> {
         unsafe {
-            let event = c::CreateEventW(ptr::null_mut(),
-                                        manual as c::BOOL,
-                                        init as c::BOOL,
-                                        ptr::null());
-            if event.is_null() {
-                Err(io::Error::last_os_error())
-            } else {
-                Ok(Handle::new(event))
-            }
+            let event =
+                c::CreateEventW(ptr::null_mut(), manual as c::BOOL, init as c::BOOL, ptr::null());
+            if event.is_null() { Err(io::Error::last_os_error()) } else { Ok(Handle::new(event)) }
         }
     }
 
@@ -52,12 +46,16 @@ impl Handle {
 
 impl Deref for Handle {
     type Target = RawHandle;
-    fn deref(&self) -> &RawHandle { &self.0 }
+    fn deref(&self) -> &RawHandle {
+        &self.0
+    }
 }
 
 impl Drop for Handle {
     fn drop(&mut self) {
-        unsafe { let _ = c::CloseHandle(self.raw()); }
+        unsafe {
+            let _ = c::CloseHandle(self.raw());
+        }
     }
 }
 
@@ -66,14 +64,15 @@ impl RawHandle {
         RawHandle(handle)
     }
 
-    pub fn raw(&self) -> c::HANDLE { self.0 }
+    pub fn raw(&self) -> c::HANDLE {
+        self.0
+    }
 
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
         let mut read = 0;
         let len = cmp::min(buf.len(), <c::DWORD>::max_value() as usize) as c::DWORD;
         let res = cvt(unsafe {
-            c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID,
-                        len, &mut read, ptr::null_mut())
+            c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, len, &mut read, ptr::null_mut())
         });
 
         match res {
@@ -85,7 +84,7 @@ impl RawHandle {
             // EOF on the pipe.
             Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0),
 
-            Err(e) => Err(e)
+            Err(e) => Err(e),
         }
     }
 
@@ -100,8 +99,7 @@ impl RawHandle {
             let mut overlapped: c::OVERLAPPED = mem::zeroed();
             overlapped.Offset = offset as u32;
             overlapped.OffsetHigh = (offset >> 32) as u32;
-            cvt(c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID,
-                            len, &mut read, &mut overlapped))
+            cvt(c::ReadFile(self.0, buf.as_mut_ptr() as c::LPVOID, len, &mut read, &mut overlapped))
         };
         match res {
             Ok(_) => Ok(read as usize),
@@ -110,16 +108,15 @@ impl RawHandle {
         }
     }
 
-    pub unsafe fn read_overlapped(&self,
-                                  buf: &mut [u8],
-                                  overlapped: *mut c::OVERLAPPED)
-                                  -> io::Result<Option<usize>> {
+    pub unsafe fn read_overlapped(
+        &self,
+        buf: &mut [u8],
+        overlapped: *mut c::OVERLAPPED,
+    ) -> io::Result<Option<usize>> {
         let len = cmp::min(buf.len(), <c::DWORD>::max_value() as usize) as c::DWORD;
         let mut amt = 0;
-        let res = cvt({
-            c::ReadFile(self.0, buf.as_ptr() as c::LPVOID,
-                        len, &mut amt, overlapped)
-        });
+        let res =
+            cvt({ c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, overlapped) });
         match res {
             Ok(_) => Ok(Some(amt as usize)),
             Err(e) => {
@@ -134,20 +131,21 @@ impl RawHandle {
         }
     }
 
-    pub fn overlapped_result(&self,
-                             overlapped: *mut c::OVERLAPPED,
-                             wait: bool) -> io::Result<usize> {
+    pub fn overlapped_result(
+        &self,
+        overlapped: *mut c::OVERLAPPED,
+        wait: bool,
+    ) -> io::Result<usize> {
         unsafe {
             let mut bytes = 0;
-            let wait = if wait {c::TRUE} else {c::FALSE};
-            let res = cvt({
-                c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait)
-            });
+            let wait = if wait { c::TRUE } else { c::FALSE };
+            let res = cvt({ c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait) });
             match res {
                 Ok(_) => Ok(bytes as usize),
                 Err(e) => {
-                    if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32) ||
-                       e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32) {
+                    if e.raw_os_error() == Some(c::ERROR_HANDLE_EOF as i32)
+                        || e.raw_os_error() == Some(c::ERROR_BROKEN_PIPE as i32)
+                    {
                         Ok(0)
                     } else {
                         Err(e)
@@ -158,17 +156,14 @@ impl RawHandle {
     }
 
     pub fn cancel_io(&self) -> io::Result<()> {
-        unsafe {
-            cvt(c::CancelIo(self.raw())).map(|_| ())
-        }
+        unsafe { cvt(c::CancelIo(self.raw())).map(|_| ()) }
     }
 
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         let mut amt = 0;
         let len = cmp::min(buf.len(), <c::DWORD>::max_value() as usize) as c::DWORD;
         cvt(unsafe {
-            c::WriteFile(self.0, buf.as_ptr() as c::LPVOID,
-                         len, &mut amt, ptr::null_mut())
+            c::WriteFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, ptr::null_mut())
         })?;
         Ok(amt as usize)
     }
@@ -184,20 +179,35 @@ impl RawHandle {
             let mut overlapped: c::OVERLAPPED = mem::zeroed();
             overlapped.Offset = offset as u32;
             overlapped.OffsetHigh = (offset >> 32) as u32;
-            cvt(c::WriteFile(self.0, buf.as_ptr() as c::LPVOID,
-                             len, &mut written, &mut overlapped))?;
+            cvt(c::WriteFile(
+                self.0,
+                buf.as_ptr() as c::LPVOID,
+                len,
+                &mut written,
+                &mut overlapped,
+            ))?;
         }
         Ok(written as usize)
     }
 
-    pub fn duplicate(&self, access: c::DWORD, inherit: bool,
-                     options: c::DWORD) -> io::Result<Handle> {
+    pub fn duplicate(
+        &self,
+        access: c::DWORD,
+        inherit: bool,
+        options: c::DWORD,
+    ) -> io::Result<Handle> {
         let mut ret = 0 as c::HANDLE;
         cvt(unsafe {
             let cur_proc = c::GetCurrentProcess();
-            c::DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret,
-                            access, inherit as c::BOOL,
-                            options)
+            c::DuplicateHandle(
+                cur_proc,
+                self.0,
+                cur_proc,
+                &mut ret,
+                access,
+                inherit as c::BOOL,
+                options,
+            )
         })?;
         Ok(Handle::new(ret))
     }
diff --git a/src/libstd/sys/windows/io.rs b/src/libstd/sys/windows/io.rs
index e44dcbe164d..9d8018fd5e8 100644
--- a/src/libstd/sys/windows/io.rs
+++ b/src/libstd/sys/windows/io.rs
@@ -35,9 +35,7 @@ impl<'a> IoSlice<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize)
-        }
+        unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
     }
 }
 
@@ -52,10 +50,7 @@ impl<'a> IoSliceMut<'a> {
     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
         assert!(buf.len() <= c::ULONG::max_value() as usize);
         IoSliceMut {
-            vec: c::WSABUF {
-                len: buf.len() as c::ULONG,
-                buf: buf.as_mut_ptr() as *mut c::CHAR,
-            },
+            vec: c::WSABUF { len: buf.len() as c::ULONG, buf: buf.as_mut_ptr() as *mut c::CHAR },
             _p: PhantomData,
         }
     }
@@ -74,15 +69,11 @@ impl<'a> IoSliceMut<'a> {
 
     #[inline]
     pub fn as_slice(&self) -> &[u8] {
-        unsafe {
-            slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize)
-        }
+        unsafe { slice::from_raw_parts(self.vec.buf as *mut u8, self.vec.len as usize) }
     }
 
     #[inline]
     pub fn as_mut_slice(&mut self) -> &mut [u8] {
-        unsafe {
-            slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize)
-        }
+        unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) }
     }
 }
diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs
index 7c400dce686..8631e50cf38 100644
--- a/src/libstd/sys/windows/os.rs
+++ b/src/libstd/sys/windows/os.rs
@@ -5,7 +5,7 @@
 use crate::os::windows::prelude::*;
 
 use crate::error::Error as StdError;
-use crate::ffi::{OsString, OsStr};
+use crate::ffi::{OsStr, OsString};
 use crate::fmt;
 use crate::io;
 use crate::os::windows::ffi::EncodeWide;
@@ -37,8 +37,10 @@ pub fn error_string(mut errnum: i32) -> String {
         // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
         if (errnum & c::FACILITY_NT_BIT as i32) != 0 {
             // format according to https://support.microsoft.com/en-us/help/259693
-            const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _,
-                                        '.' as _, 'D' as _, 'L' as _, 'L' as _, 0];
+            const NTDLL_DLL: &[u16] = &[
+                'N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _,
+                'L' as _, 0,
+            ];
             module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
 
             if module != ptr::null_mut() {
@@ -47,19 +49,19 @@ pub fn error_string(mut errnum: i32) -> String {
             }
         }
 
-        let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTEM |
-                                        c::FORMAT_MESSAGE_IGNORE_INSERTS,
-                                    module,
-                                    errnum as c::DWORD,
-                                    langId,
-                                    buf.as_mut_ptr(),
-                                    buf.len() as c::DWORD,
-                                    ptr::null()) as usize;
+        let res = c::FormatMessageW(
+            flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS,
+            module,
+            errnum as c::DWORD,
+            langId,
+            buf.as_mut_ptr(),
+            buf.len() as c::DWORD,
+            ptr::null(),
+        ) as usize;
         if res == 0 {
             // Sometimes FormatMessageW can fail e.g., system doesn't like langId,
             let fm_err = errno();
-            return format!("OS Error {} (FormatMessageW() returned error {})",
-                           errnum, fm_err);
+            return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
         }
 
         match String::from_utf16(&buf[..res]) {
@@ -68,9 +70,12 @@ pub fn error_string(mut errnum: i32) -> String {
                 let len = msg.trim_end().len();
                 msg.truncate(len);
                 msg
-            },
-            Err(..) => format!("OS Error {} (FormatMessageW() returned \
-                                invalid UTF-16)", errnum),
+            }
+            Err(..) => format!(
+                "OS Error {} (FormatMessageW() returned \
+                 invalid UTF-16)",
+                errnum
+            ),
         }
     }
 }
@@ -86,7 +91,9 @@ impl Iterator for Env {
     fn next(&mut self) -> Option<(OsString, OsString)> {
         loop {
             unsafe {
-                if *self.cur == 0 { return None }
+                if *self.cur == 0 {
+                    return None;
+                }
                 let p = &*self.cur as *const u16;
                 let mut len = 0;
                 while *p.offset(len) != 0 {
@@ -106,8 +113,8 @@ impl Iterator for Env {
                 };
                 return Some((
                     OsStringExt::from_wide(&s[..pos]),
-                    OsStringExt::from_wide(&s[pos+1..]),
-                ))
+                    OsStringExt::from_wide(&s[pos + 1..]),
+                ));
             }
         }
     }
@@ -115,7 +122,9 @@ impl Iterator for Env {
 
 impl Drop for Env {
     fn drop(&mut self) {
-        unsafe { c::FreeEnvironmentStringsW(self.base); }
+        unsafe {
+            c::FreeEnvironmentStringsW(self.base);
+        }
     }
 }
 
@@ -123,8 +132,7 @@ pub fn env() -> Env {
     unsafe {
         let ch = c::GetEnvironmentStringsW();
         if ch as usize == 0 {
-            panic!("failure getting env string from OS: {}",
-                   io::Error::last_os_error());
+            panic!("failure getting env string from OS: {}", io::Error::last_os_error());
         }
         Env { base: ch, cur: ch }
     }
@@ -136,10 +144,7 @@ pub struct SplitPaths<'a> {
 }
 
 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
-    SplitPaths {
-        data: unparsed.encode_wide(),
-        must_yield: true,
-    }
+    SplitPaths { data: unparsed.encode_wide(), must_yield: true }
 }
 
 impl<'a> Iterator for SplitPaths<'a> {
@@ -158,7 +163,6 @@ impl<'a> Iterator for SplitPaths<'a> {
         // (The above is based on testing; there is no clear reference available
         // for the grammar.)
 
-
         let must_yield = self.must_yield;
         self.must_yield = false;
 
@@ -169,7 +173,7 @@ impl<'a> Iterator for SplitPaths<'a> {
                 in_quote = !in_quote;
             } else if b == ';' as u16 && !in_quote {
                 self.must_yield = true;
-                break
+                break;
             } else {
                 in_progress.push(b)
             }
@@ -187,17 +191,21 @@ impl<'a> Iterator for SplitPaths<'a> {
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
-    where I: Iterator<Item=T>, T: AsRef<OsStr>
+where
+    I: Iterator<Item = T>,
+    T: AsRef<OsStr>,
 {
     let mut joined = Vec::new();
     let sep = b';' as u16;
 
     for (i, path) in paths.enumerate() {
         let path = path.as_ref();
-        if i > 0 { joined.push(sep) }
+        if i > 0 {
+            joined.push(sep)
+        }
         let v = path.encode_wide().collect::<Vec<u16>>();
         if v.contains(&(b'"' as u16)) {
-            return Err(JoinPathsError)
+            return Err(JoinPathsError);
         } else if v.contains(&sep) {
             joined.push(b'"' as u16);
             joined.extend_from_slice(&v[..]);
@@ -217,19 +225,20 @@ impl fmt::Display for JoinPathsError {
 }
 
 impl StdError for JoinPathsError {
-    fn description(&self) -> &str { "failed to join paths" }
+    fn description(&self) -> &str {
+        "failed to join paths"
+    }
 }
 
 pub fn current_exe() -> io::Result<PathBuf> {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetModuleFileNameW(ptr::null_mut(), buf, sz)
-    }, super::os2path)
+    super::fill_utf16_buf(
+        |buf, sz| unsafe { c::GetModuleFileNameW(ptr::null_mut(), buf, sz) },
+        super::os2path,
+    )
 }
 
 pub fn getcwd() -> io::Result<PathBuf> {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetCurrentDirectoryW(sz, buf)
-    }, super::os2path)
+    super::fill_utf16_buf(|buf, sz| unsafe { c::GetCurrentDirectoryW(sz, buf) }, super::os2path)
 }
 
 pub fn chdir(p: &path::Path) -> io::Result<()> {
@@ -237,18 +246,15 @@ pub fn chdir(p: &path::Path) -> io::Result<()> {
     let mut p = p.encode_wide().collect::<Vec<_>>();
     p.push(0);
 
-    cvt(unsafe {
-        c::SetCurrentDirectoryW(p.as_ptr())
-    }).map(|_| ())
+    cvt(unsafe { c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ())
 }
 
 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
     let k = to_u16s(k)?;
-    let res = super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetEnvironmentVariableW(k.as_ptr(), buf, sz)
-    }, |buf| {
-        OsStringExt::from_wide(buf)
-    });
+    let res = super::fill_utf16_buf(
+        |buf, sz| unsafe { c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) },
+        |buf| OsStringExt::from_wide(buf),
+    );
     match res {
         Ok(value) => Ok(Some(value)),
         Err(e) => {
@@ -265,22 +271,16 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
     let k = to_u16s(k)?;
     let v = to_u16s(v)?;
 
-    cvt(unsafe {
-        c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr())
-    }).map(|_| ())
+    cvt(unsafe { c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ())
 }
 
 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
     let v = to_u16s(n)?;
-    cvt(unsafe {
-        c::SetEnvironmentVariableW(v.as_ptr(), ptr::null())
-    }).map(|_| ())
+    cvt(unsafe { c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ())
 }
 
 pub fn temp_dir() -> PathBuf {
-    super::fill_utf16_buf(|buf, sz| unsafe {
-        c::GetTempPathW(sz, buf)
-    }, super::os2path).unwrap()
+    super::fill_utf16_buf(|buf, sz| unsafe { c::GetTempPathW(sz, buf) }, super::os2path).unwrap()
 }
 
 #[cfg(not(target_vendor = "uwp"))]
@@ -291,16 +291,20 @@ fn home_dir_crt() -> Option<PathBuf> {
         let me = c::GetCurrentProcess();
         let mut token = ptr::null_mut();
         if c::OpenProcessToken(me, c::TOKEN_READ, &mut token) == 0 {
-            return None
+            return None;
         }
         let _handle = Handle::new(token);
-        super::fill_utf16_buf(|buf, mut sz| {
-            match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
-                0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0,
-                0 => sz,
-                _ => sz - 1, // sz includes the null terminator
-            }
-        }, super::os2path).ok()
+        super::fill_utf16_buf(
+            |buf, mut sz| {
+                match c::GetUserProfileDirectoryW(token, buf, &mut sz) {
+                    0 if c::GetLastError() != c::ERROR_INSUFFICIENT_BUFFER => 0,
+                    0 => sz,
+                    _ => sz - 1, // sz includes the null terminator
+                }
+            },
+            super::os2path,
+        )
+        .ok()
     }
 }
 
@@ -310,9 +314,10 @@ fn home_dir_crt() -> Option<PathBuf> {
 }
 
 pub fn home_dir() -> Option<PathBuf> {
-    crate::env::var_os("HOME").or_else(|| {
-        crate::env::var_os("USERPROFILE")
-    }).map(PathBuf::from).or_else(|| home_dir_crt())
+    crate::env::var_os("HOME")
+        .or_else(|| crate::env::var_os("USERPROFILE"))
+        .map(PathBuf::from)
+        .or_else(|| home_dir_crt())
 }
 
 pub fn exit(code: i32) -> ! {
@@ -332,7 +337,10 @@ mod tests {
     #[test]
     fn ntstatus_error() {
         const STATUS_UNSUCCESSFUL: u32 = 0xc000_0001;
-        assert!(!Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
-            .to_string().contains("FormatMessageW() returned error"));
+        assert!(
+            !Error::from_raw_os_error((STATUS_UNSUCCESSFUL | c::FACILITY_NT_BIT) as _)
+                .to_string()
+                .contains("FormatMessageW() returned error")
+        );
     }
 }
diff --git a/src/libstd/sys/windows/os_str.rs b/src/libstd/sys/windows/os_str.rs
index c7a82e09252..e451e0cfb5b 100644
--- a/src/libstd/sys/windows/os_str.rs
+++ b/src/libstd/sys/windows/os_str.rs
@@ -1,17 +1,16 @@
 /// The underlying OsString/OsStr implementation on Windows is a
 /// wrapper around the "WTF-8" encoding; see the `wtf8` module for more.
-
 use crate::borrow::Cow;
 use crate::fmt;
-use crate::sys_common::wtf8::{Wtf8, Wtf8Buf};
 use crate::mem;
 use crate::rc::Rc;
 use crate::sync::Arc;
-use crate::sys_common::{AsInner, IntoInner, FromInner};
+use crate::sys_common::wtf8::{Wtf8, Wtf8Buf};
+use crate::sys_common::{AsInner, FromInner, IntoInner};
 
 #[derive(Clone, Hash)]
 pub struct Buf {
-    pub inner: Wtf8Buf
+    pub inner: Wtf8Buf,
 }
 
 impl IntoInner<Wtf8Buf> for Buf {
@@ -45,7 +44,7 @@ impl fmt::Display for Buf {
 }
 
 pub struct Slice {
-    pub inner: Wtf8
+    pub inner: Wtf8,
 }
 
 impl fmt::Debug for Slice {
@@ -62,9 +61,7 @@ impl fmt::Display for Slice {
 
 impl Buf {
     pub fn with_capacity(capacity: usize) -> Buf {
-        Buf {
-            inner: Wtf8Buf::with_capacity(capacity)
-        }
+        Buf { inner: Wtf8Buf::with_capacity(capacity) }
     }
 
     pub fn clear(&mut self) {
diff --git a/src/libstd/sys/windows/path.rs b/src/libstd/sys/windows/path.rs
index 7eae28cb14f..524f21f889b 100644
--- a/src/libstd/sys/windows/path.rs
+++ b/src/libstd/sys/windows/path.rs
@@ -1,6 +1,6 @@
-use crate::path::Prefix;
 use crate::ffi::OsStr;
 use crate::mem;
+use crate::path::Prefix;
 
 fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
     unsafe { mem::transmute(s) }
@@ -38,8 +38,9 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
                     // \\?\UNC\server\share
                     path = &path[4..];
                     let (server, share) = match parse_two_comps(path, is_verbatim_sep) {
-                        Some((server, share)) =>
-                            (u8_slice_as_os_str(server), u8_slice_as_os_str(share)),
+                        Some((server, share)) => {
+                            (u8_slice_as_os_str(server), u8_slice_as_os_str(share))
+                        }
                         None => (u8_slice_as_os_str(path), u8_slice_as_os_str(&[])),
                     };
                     return Some(VerbatimUNC(server, share));
@@ -70,7 +71,7 @@ pub fn parse_prefix(path: &OsStr) -> Option<Prefix<'_>> {
                 }
                 _ => (),
             }
-        } else if path.get(1) == Some(& b':') {
+        } else if path.get(1) == Some(&b':') {
             // C:
             let c = path[0];
             if c.is_ascii() && (c as char).is_alphabetic() {
diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs
index 041d5385eb6..992e634dea5 100644
--- a/src/libstd/sys/windows/pipe.rs
+++ b/src/libstd/sys/windows/pipe.rs
@@ -6,8 +6,8 @@ use crate::mem;
 use crate::path::Path;
 use crate::ptr;
 use crate::slice;
-use crate::sync::atomic::Ordering::SeqCst;
 use crate::sync::atomic::AtomicUsize;
+use crate::sync::atomic::Ordering::SeqCst;
 use crate::sys::c;
 use crate::sys::fs::{File, OpenOptions};
 use crate::sys::handle::Handle;
@@ -63,32 +63,32 @@ pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Res
         let mut reject_remote_clients_flag = c::PIPE_REJECT_REMOTE_CLIENTS;
         loop {
             tries += 1;
-            name = format!(r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}",
-                           c::GetCurrentProcessId(),
-                           random_number());
-            let wide_name = OsStr::new(&name)
-                                  .encode_wide()
-                                  .chain(Some(0))
-                                  .collect::<Vec<_>>();
-            let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE |
-                c::FILE_FLAG_OVERLAPPED;
+            name = format!(
+                r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}",
+                c::GetCurrentProcessId(),
+                random_number()
+            );
+            let wide_name = OsStr::new(&name).encode_wide().chain(Some(0)).collect::<Vec<_>>();
+            let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED;
             if ours_readable {
                 flags |= c::PIPE_ACCESS_INBOUND;
             } else {
                 flags |= c::PIPE_ACCESS_OUTBOUND;
             }
 
-            let handle = c::CreateNamedPipeW(wide_name.as_ptr(),
-                                             flags,
-                                             c::PIPE_TYPE_BYTE |
-                                             c::PIPE_READMODE_BYTE |
-                                             c::PIPE_WAIT |
-                                             reject_remote_clients_flag,
-                                             1,
-                                             4096,
-                                             4096,
-                                             0,
-                                             ptr::null_mut());
+            let handle = c::CreateNamedPipeW(
+                wide_name.as_ptr(),
+                flags,
+                c::PIPE_TYPE_BYTE
+                    | c::PIPE_READMODE_BYTE
+                    | c::PIPE_WAIT
+                    | reject_remote_clients_flag,
+                1,
+                4096,
+                4096,
+                0,
+                ptr::null_mut(),
+            );
 
             // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're
             // also just doing a best effort at selecting a unique name. If
@@ -112,18 +112,19 @@ pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Res
                 let raw_os_err = err.raw_os_error();
                 if tries < 10 {
                     if raw_os_err == Some(c::ERROR_ACCESS_DENIED as i32) {
-                        continue
-                    } else if reject_remote_clients_flag != 0 &&
-                        raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32) {
+                        continue;
+                    } else if reject_remote_clients_flag != 0
+                        && raw_os_err == Some(c::ERROR_INVALID_PARAMETER as i32)
+                    {
                         reject_remote_clients_flag = 0;
                         tries -= 1;
-                        continue
+                        continue;
                     }
                 }
-                return Err(err)
+                return Err(err);
             }
             ours = Handle::new(handle);
-            break
+            break;
         }
 
         // Connect to the named pipe we just created. This handle is going to be
@@ -158,7 +159,7 @@ fn random_number() -> usize {
     static N: AtomicUsize = AtomicUsize::new(0);
     loop {
         if N.load(SeqCst) != 0 {
-            return N.fetch_add(1, SeqCst)
+            return N.fetch_add(1, SeqCst);
         }
 
         N.store(hashmap_random_keys().0 as usize, SeqCst);
@@ -166,8 +167,12 @@ fn random_number() -> usize {
 }
 
 impl AnonPipe {
-    pub fn handle(&self) -> &Handle { &self.inner }
-    pub fn into_handle(self) -> Handle { self.inner }
+    pub fn handle(&self) -> &Handle {
+        &self.inner
+    }
+    pub fn into_handle(self) -> Handle {
+        self.inner
+    }
 
     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
         self.inner.read(buf)
@@ -186,10 +191,7 @@ impl AnonPipe {
     }
 }
 
-pub fn read2(p1: AnonPipe,
-             v1: &mut Vec<u8>,
-             p2: AnonPipe,
-             v2: &mut Vec<u8>) -> io::Result<()> {
+pub fn read2(p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>) -> io::Result<()> {
     let p1 = p1.into_handle();
     let p2 = p2.into_handle();
 
@@ -206,19 +208,17 @@ pub fn read2(p1: AnonPipe,
     // duration of the I/O operation (where tons of operations can also fail).
     // The destructor for `AsyncPipe` ends up taking care of most of this.
     loop {
-        let res = unsafe {
-            c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE)
-        };
+        let res = unsafe { c::WaitForMultipleObjects(2, objs.as_ptr(), c::FALSE, c::INFINITE) };
         if res == c::WAIT_OBJECT_0 {
             if !p1.result()? || !p1.schedule_read()? {
-                return p2.finish()
+                return p2.finish();
             }
         } else if res == c::WAIT_OBJECT_0 + 1 {
             if !p2.result()? || !p2.schedule_read()? {
-                return p1.finish()
+                return p1.finish();
             }
         } else {
-            return Err(io::Error::last_os_error())
+            return Err(io::Error::last_os_error());
         }
     }
 }
@@ -251,17 +251,9 @@ impl<'a> AsyncPipe<'a> {
         // and the only time an even will go back to "unset" will be once an
         // I/O operation is successfully scheduled (what we want).
         let event = Handle::new_event(true, true)?;
-        let mut overlapped: Box<c::OVERLAPPED> = unsafe {
-            Box::new(mem::zeroed())
-        };
+        let mut overlapped: Box<c::OVERLAPPED> = unsafe { Box::new(mem::zeroed()) };
         overlapped.hEvent = event.raw();
-        Ok(AsyncPipe {
-            pipe,
-            overlapped,
-            event,
-            dst,
-            state: State::NotReading,
-        })
+        Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading })
     }
 
     /// Executes an overlapped read operation.
@@ -306,9 +298,7 @@ impl<'a> AsyncPipe<'a> {
     fn result(&mut self) -> io::Result<bool> {
         let amt = match self.state {
             State::NotReading => return Ok(true),
-            State::Reading => {
-                self.pipe.overlapped_result(&mut *self.overlapped, true)?
-            }
+            State::Reading => self.pipe.overlapped_result(&mut *self.overlapped, true)?,
             State::Read(amt) => amt,
         };
         self.state = State::NotReading;
@@ -364,6 +354,5 @@ unsafe fn slice_to_end(v: &mut Vec<u8>) -> &mut [u8] {
     if v.capacity() == v.len() {
         v.reserve(1);
     }
-    slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()),
-                              v.capacity() - v.len())
+    slice::from_raw_parts_mut(v.as_mut_ptr().add(v.len()), v.capacity() - v.len())
 }
diff --git a/src/libstd/sys/windows/rand.rs b/src/libstd/sys/windows/rand.rs
index 993831bec18..87ea416bf67 100644
--- a/src/libstd/sys/windows/rand.rs
+++ b/src/libstd/sys/windows/rand.rs
@@ -5,13 +5,10 @@ use crate::sys::c;
 #[cfg(not(target_vendor = "uwp"))]
 pub fn hashmap_random_keys() -> (u64, u64) {
     let mut v = (0, 0);
-    let ret = unsafe {
-        c::RtlGenRandom(&mut v as *mut _ as *mut u8,
-                        mem::size_of_val(&v) as c::ULONG)
-    };
+    let ret =
+        unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) };
     if ret == 0 {
-        panic!("couldn't generate random bytes: {}",
-               io::Error::last_os_error());
+        panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
     }
     v
 }
@@ -22,13 +19,15 @@ pub fn hashmap_random_keys() -> (u64, u64) {
 
     let mut v = (0, 0);
     let ret = unsafe {
-        c::BCryptGenRandom(ptr::null_mut(), &mut v as *mut _ as *mut u8,
-                           mem::size_of_val(&v) as c::ULONG,
-                           c::BCRYPT_USE_SYSTEM_PREFERRED_RNG)
+        c::BCryptGenRandom(
+            ptr::null_mut(),
+            &mut v as *mut _ as *mut u8,
+            mem::size_of_val(&v) as c::ULONG,
+            c::BCRYPT_USE_SYSTEM_PREFERRED_RNG,
+        )
     };
     if ret != 0 {
-        panic!("couldn't generate random bytes: {}",
-               io::Error::last_os_error());
+        panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
     }
-    return v
+    return v;
 }
diff --git a/src/libstd/sys/windows/stack_overflow.rs b/src/libstd/sys/windows/stack_overflow.rs
index d5b7765f9ff..187ad4e66c3 100644
--- a/src/libstd/sys/windows/stack_overflow.rs
+++ b/src/libstd/sys/windows/stack_overflow.rs
@@ -1,7 +1,7 @@
 #![cfg_attr(test, allow(dead_code))]
 
-use crate::sys_common::util::report_overflow;
 use crate::sys::c;
+use crate::sys_common::util::report_overflow;
 
 pub struct Handler;
 
@@ -18,8 +18,7 @@ impl Handler {
     }
 }
 
-extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS)
-                                    -> c::LONG {
+extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) -> c::LONG {
     unsafe {
         let rec = &(*(*ExceptionInfo).ExceptionRecord);
         let code = rec.ExceptionCode;
diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs
index b1e76b3b755..f322c2b1d96 100644
--- a/src/libstd/sys/windows/stdio.rs
+++ b/src/libstd/sys/windows/stdio.rs
@@ -68,9 +68,11 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
     let utf8 = match str::from_utf8(&data[..len]) {
         Ok(s) => s,
         Err(ref e) if e.valid_up_to() == 0 => {
-            return Err(io::Error::new(io::ErrorKind::InvalidData,
-                "Windows stdio in console mode does not support writing non-UTF-8 byte sequences"))
-        },
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
+            ));
+        }
         Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(),
     };
     let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2];
@@ -93,18 +95,19 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
         // write the missing surrogate out now.
         // Buffering it would mean we have to lie about the number of bytes written.
         let first_char_remaining = utf16[written];
-        if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF { // low surrogate
+        if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF {
+            // low surrogate
             // We just hope this works, and give up otherwise
-            let _ = write_u16s(handle, &utf16[written..written+1]);
+            let _ = write_u16s(handle, &utf16[written..written + 1]);
             written += 1;
         }
         // Calculate the number of bytes of `utf8` that were actually written.
         let mut count = 0;
         for ch in utf16[..written].iter() {
             count += match ch {
-                0x0000 ..= 0x007F => 1,
-                0x0080 ..= 0x07FF => 2,
-                0xDCEE ..= 0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other.
+                0x0000..=0x007F => 1,
+                0x0080..=0x07FF => 2,
+                0xDCEE..=0xDFFF => 1, // Low surrogate. We already counted 3 bytes for the other.
                 _ => 3,
             };
         }
@@ -116,11 +119,13 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
 fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result<usize> {
     let mut written = 0;
     cvt(unsafe {
-        c::WriteConsoleW(handle,
-                         data.as_ptr() as c::LPCVOID,
-                         data.len() as u32,
-                         &mut written,
-                         ptr::null_mut())
+        c::WriteConsoleW(
+            handle,
+            data.as_ptr() as c::LPCVOID,
+            data.len() as u32,
+            &mut written,
+            ptr::null_mut(),
+        )
     })?;
     Ok(written as usize)
 }
@@ -144,9 +149,11 @@ impl io::Read for Stdin {
         if buf.len() == 0 {
             return Ok(0);
         } else if buf.len() < 4 {
-            return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                        "Windows stdin in console mode does not support a buffer too small to \
-                        guarantee holding one arbitrary UTF-8 character (4 bytes)"))
+            return Err(io::Error::new(
+                io::ErrorKind::InvalidInput,
+                "Windows stdin in console mode does not support a buffer too small to \
+                 guarantee holding one arbitrary UTF-8 character (4 bytes)",
+            ));
         }
 
         let mut utf16_buf = [0u16; MAX_BUFFER_SIZE / 2];
@@ -160,15 +167,15 @@ impl io::Read for Stdin {
     }
 }
 
-
 // We assume that if the last `u16` is an unpaired surrogate they got sliced apart by our
 // buffer size, and keep it around for the next read hoping to put them together.
 // This is a best effort, and may not work if we are not the only reader on Stdin.
-fn read_u16s_fixup_surrogates(handle: c::HANDLE,
-                              buf: &mut [u16],
-                              mut amount: usize,
-                              surrogate: &mut u16) -> io::Result<usize>
-{
+fn read_u16s_fixup_surrogates(
+    handle: c::HANDLE,
+    buf: &mut [u16],
+    mut amount: usize,
+    surrogate: &mut u16,
+) -> io::Result<usize> {
     // Insert possibly remaining unpaired surrogate from last read.
     let mut start = 0;
     if *surrogate != 0 {
@@ -186,7 +193,8 @@ fn read_u16s_fixup_surrogates(handle: c::HANDLE,
 
     if amount > 0 {
         let last_char = buf[amount - 1];
-        if last_char >= 0xD800 && last_char <= 0xDBFF { // high surrogate
+        if last_char >= 0xD800 && last_char <= 0xDBFF {
+            // high surrogate
             *surrogate = last_char;
             amount -= 1;
         }
@@ -209,11 +217,13 @@ fn read_u16s(handle: c::HANDLE, buf: &mut [u16]) -> io::Result<usize> {
 
     let mut amount = 0;
     cvt(unsafe {
-        c::ReadConsoleW(handle,
-                        buf.as_mut_ptr() as c::LPVOID,
-                        buf.len() as u32,
-                        &mut amount,
-                        &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL)
+        c::ReadConsoleW(
+            handle,
+            buf.as_mut_ptr() as c::LPVOID,
+            buf.len() as u32,
+            &mut amount,
+            &mut input_control as c::PCONSOLE_READCONSOLE_CONTROL,
+        )
     })?;
 
     if amount > 0 && buf[amount as usize - 1] == CTRL_Z {
@@ -233,9 +243,11 @@ fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
             }
             Err(_) => {
                 // We can't really do any better than forget all data and return an error.
-                return Err(io::Error::new(io::ErrorKind::InvalidData,
+                return Err(io::Error::new(
+                    io::ErrorKind::InvalidData,
                     "Windows stdin in console mode does not support non-UTF-16 input; \
-                    encountered unpaired surrogate"))
+                     encountered unpaired surrogate",
+                ));
             }
         }
     }
diff --git a/src/libstd/sys/windows/stdio_uwp.rs b/src/libstd/sys/windows/stdio_uwp.rs
index 489d3df2860..0f2178f7353 100644
--- a/src/libstd/sys/windows/stdio_uwp.rs
+++ b/src/libstd/sys/windows/stdio_uwp.rs
@@ -1,12 +1,11 @@
 #![unstable(issue = "0", feature = "windows_stdio")]
 
 use crate::io;
+use crate::mem::ManuallyDrop;
 use crate::sys::c;
 use crate::sys::handle::Handle;
-use crate::mem::ManuallyDrop;
 
-pub struct Stdin {
-}
+pub struct Stdin {}
 pub struct Stdout;
 pub struct Stderr;
 
@@ -32,7 +31,7 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
 
 impl Stdin {
     pub fn new() -> io::Result<Stdin> {
-        Ok(Stdin { })
+        Ok(Stdin {})
     }
 }
 
diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs
index ebdf3612e06..c828243a59b 100644
--- a/src/libstd/sys/windows/thread.rs
+++ b/src/libstd/sys/windows/thread.rs
@@ -1,5 +1,5 @@
-use crate::io;
 use crate::ffi::CStr;
+use crate::io;
 use crate::mem;
 use crate::ptr;
 use crate::sys::c;
@@ -14,13 +14,12 @@ use super::to_u16s;
 pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
 
 pub struct Thread {
-    handle: Handle
+    handle: Handle,
 }
 
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
-    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>)
-                          -> io::Result<Thread> {
+    pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
         let p = box p;
 
         // FIXME On UNIX, we guard against stack sizes that are too small but
@@ -31,10 +30,14 @@ impl Thread {
         // Round up to the next 64 kB because that's what the NT kernel does,
         // might as well make it explicit.
         let stack_size = (stack + 0xfffe) & (!0xfffe);
-        let ret = c::CreateThread(ptr::null_mut(), stack_size,
-                                  thread_start, &*p as *const _ as *mut _,
-                                  c::STACK_SIZE_PARAM_IS_A_RESERVATION,
-                                  ptr::null_mut());
+        let ret = c::CreateThread(
+            ptr::null_mut(),
+            stack_size,
+            thread_start,
+            &*p as *const _ as *mut _,
+            c::STACK_SIZE_PARAM_IS_A_RESERVATION,
+            ptr::null_mut(),
+        );
 
         return if ret as usize == 0 {
             Err(io::Error::last_os_error())
@@ -44,7 +47,9 @@ impl Thread {
         };
 
         extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
-            unsafe { start_thread(main as *mut u8); }
+            unsafe {
+                start_thread(main as *mut u8);
+            }
             0
         }
     }
@@ -52,7 +57,9 @@ impl Thread {
     pub fn set_name(name: &CStr) {
         if let Ok(utf8) = name.to_str() {
             if let Ok(utf16) = to_u16s(utf8) {
-                unsafe { c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr()); };
+                unsafe {
+                    c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
+                };
             };
         };
     }
@@ -60,8 +67,7 @@ impl Thread {
     pub fn join(self) {
         let rc = unsafe { c::WaitForSingleObject(self.handle.raw(), c::INFINITE) };
         if rc == c::WAIT_FAILED {
-            panic!("failed to join on thread: {}",
-                   io::Error::last_os_error());
+            panic!("failed to join on thread: {}", io::Error::last_os_error());
         }
     }
 
@@ -69,23 +75,31 @@ impl Thread {
         // This function will return 0 if there are no other threads to execute,
         // but this also means that the yield was useless so this isn't really a
         // case that needs to be worried about.
-        unsafe { c::SwitchToThread(); }
+        unsafe {
+            c::SwitchToThread();
+        }
     }
 
     pub fn sleep(dur: Duration) {
-        unsafe {
-            c::Sleep(super::dur2timeout(dur))
-        }
+        unsafe { c::Sleep(super::dur2timeout(dur)) }
     }
 
-    pub fn handle(&self) -> &Handle { &self.handle }
+    pub fn handle(&self) -> &Handle {
+        &self.handle
+    }
 
-    pub fn into_handle(self) -> Handle { self.handle }
+    pub fn into_handle(self) -> Handle {
+        self.handle
+    }
 }
 
 #[cfg_attr(test, allow(dead_code))]
 pub mod guard {
     pub type Guard = !;
-    pub unsafe fn current() -> Option<Guard> { None }
-    pub unsafe fn init() -> Option<Guard> { None }
+    pub unsafe fn current() -> Option<Guard> {
+        None
+    }
+    pub unsafe fn init() -> Option<Guard> {
+        None
+    }
 }
diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs
index 728257cdd4b..e0bb102b3af 100644
--- a/src/libstd/sys/windows/thread_local.rs
+++ b/src/libstd/sys/windows/thread_local.rs
@@ -5,7 +5,7 @@ use crate::sync::atomic::Ordering::SeqCst;
 use crate::sys::c;
 
 pub type Key = c::DWORD;
-pub type Dtor = unsafe extern fn(*mut u8);
+pub type Dtor = unsafe extern "C" fn(*mut u8);
 
 // Turns out, like pretty much everything, Windows is pretty close the
 // functionality that Unix provides, but slightly different! In the case of
@@ -111,11 +111,7 @@ struct Node {
 }
 
 unsafe fn register_dtor(key: Key, dtor: Dtor) {
-    let mut node = Box::new(Node {
-        key,
-        dtor,
-        next: ptr::null_mut(),
-    });
+    let mut node = Box::new(Node { key, dtor, next: ptr::null_mut() });
 
     let mut head = DTORS.load(SeqCst);
     loop {
@@ -192,15 +188,12 @@ unsafe fn register_dtor(key: Key, dtor: Dtor) {
 #[link_section = ".CRT$XLB"]
 #[allow(dead_code, unused_variables)]
 #[used] // we don't want LLVM eliminating this symbol for any reason, and
-        // when the symbol makes it to the linker the linker will take over
-pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD,
-                                                        c::LPVOID) =
-        on_tls_callback;
+// when the symbol makes it to the linker the linker will take over
+pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD, c::LPVOID) =
+    on_tls_callback;
 
 #[allow(dead_code, unused_variables)]
-unsafe extern "system" fn on_tls_callback(h: c::LPVOID,
-                                          dwReason: c::DWORD,
-                                          pv: c::LPVOID) {
+unsafe extern "system" fn on_tls_callback(h: c::LPVOID, dwReason: c::DWORD, pv: c::LPVOID) {
     if dwReason == c::DLL_THREAD_DETACH || dwReason == c::DLL_PROCESS_DETACH {
         run_dtors();
     }
@@ -210,7 +203,9 @@ unsafe extern "system" fn on_tls_callback(h: c::LPVOID,
     reference_tls_used();
     #[cfg(target_env = "msvc")]
     unsafe fn reference_tls_used() {
-        extern { static _tls_used: u8; }
+        extern "C" {
+            static _tls_used: u8;
+        }
         crate::intrinsics::volatile_load(&_tls_used);
     }
     #[cfg(not(target_env = "msvc"))]
@@ -222,7 +217,7 @@ unsafe fn run_dtors() {
     let mut any_run = true;
     for _ in 0..5 {
         if !any_run {
-            break
+            break;
         }
         any_run = false;
         let mut cur = DTORS.load(SeqCst);
diff --git a/src/libstd/sys_common/alloc.rs b/src/libstd/sys_common/alloc.rs
index 1cfc7ed17f2..713b9949f64 100644
--- a/src/libstd/sys_common/alloc.rs
+++ b/src/libstd/sys_common/alloc.rs
@@ -6,20 +6,24 @@ use crate::ptr;
 
 // The minimum alignment guaranteed by the architecture. This value is used to
 // add fast paths for low alignment values.
-#[cfg(all(any(target_arch = "x86",
-              target_arch = "arm",
-              target_arch = "mips",
-              target_arch = "powerpc",
-              target_arch = "powerpc64",
-              target_arch = "asmjs",
-              target_arch = "wasm32",
-              target_arch = "hexagon")))]
+#[cfg(all(any(
+    target_arch = "x86",
+    target_arch = "arm",
+    target_arch = "mips",
+    target_arch = "powerpc",
+    target_arch = "powerpc64",
+    target_arch = "asmjs",
+    target_arch = "wasm32",
+    target_arch = "hexagon"
+)))]
 pub const MIN_ALIGN: usize = 8;
-#[cfg(all(any(target_arch = "x86_64",
-              target_arch = "aarch64",
-              target_arch = "mips64",
-              target_arch = "s390x",
-              target_arch = "sparc64")))]
+#[cfg(all(any(
+    target_arch = "x86_64",
+    target_arch = "aarch64",
+    target_arch = "mips64",
+    target_arch = "s390x",
+    target_arch = "sparc64"
+)))]
 pub const MIN_ALIGN: usize = 16;
 
 pub unsafe fn realloc_fallback(
diff --git a/src/libstd/sys_common/bytestring.rs b/src/libstd/sys_common/bytestring.rs
index 429ecf6281b..dccc3bc4a19 100644
--- a/src/libstd/sys_common/bytestring.rs
+++ b/src/libstd/sys_common/bytestring.rs
@@ -25,7 +25,7 @@ pub fn debug_fmt_bytestring(slice: &[u8], f: &mut Formatter<'_>) -> Result {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use crate::fmt::{Formatter, Result, Debug};
+    use crate::fmt::{Debug, Formatter, Result};
 
     #[test]
     fn smoke() {
@@ -37,7 +37,7 @@ mod tests {
             }
         }
 
-        let input =      b"\xF0hello,\tworld";
+        let input = b"\xF0hello,\tworld";
         let expected = r#""\xF0hello,\tworld""#;
         let output = format!("{:?}", Helper(input));
 
diff --git a/src/libstd/sys_common/fs.rs b/src/libstd/sys_common/fs.rs
index 7152fcd215c..e30e8018a31 100644
--- a/src/libstd/sys_common/fs.rs
+++ b/src/libstd/sys_common/fs.rs
@@ -1,13 +1,15 @@
 #![allow(dead_code)] // not used on all platforms
 
-use crate::path::Path;
 use crate::fs;
 use crate::io::{self, Error, ErrorKind};
+use crate::path::Path;
 
 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
     if !from.is_file() {
-        return Err(Error::new(ErrorKind::InvalidInput,
-                              "the source path is not an existing regular file"))
+        return Err(Error::new(
+            ErrorKind::InvalidInput,
+            "the source path is not an existing regular file",
+        ));
     }
 
     let mut reader = fs::File::open(from)?;
@@ -21,11 +23,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
 
 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
     let filetype = fs::symlink_metadata(path)?.file_type();
-    if filetype.is_symlink() {
-        fs::remove_file(path)
-    } else {
-        remove_dir_all_recursive(path)
-    }
+    if filetype.is_symlink() { fs::remove_file(path) } else { remove_dir_all_recursive(path) }
 }
 
 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
diff --git a/src/libstd/sys_common/io.rs b/src/libstd/sys_common/io.rs
index 8789abe55c3..7c1d98a5abd 100644
--- a/src/libstd/sys_common/io.rs
+++ b/src/libstd/sys_common/io.rs
@@ -3,9 +3,9 @@ pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
 #[cfg(test)]
 #[allow(dead_code)] // not used on emscripten
 pub mod test {
-    use crate::path::{Path, PathBuf};
     use crate::env;
     use crate::fs;
+    use crate::path::{Path, PathBuf};
     use rand::RngCore;
 
     pub struct TempDir(PathBuf);
diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs
index 391f670346f..9d40d9f0afd 100644
--- a/src/libstd/sys_common/net.rs
+++ b/src/libstd/sys_common/net.rs
@@ -1,79 +1,119 @@
 use crate::cmp;
+use crate::convert::{TryFrom, TryInto};
 use crate::ffi::CString;
 use crate::fmt;
 use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut};
 use crate::mem;
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
 use crate::ptr;
-use crate::sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
 use crate::sys::net::netc as c;
+use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket};
 use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::Duration;
-use crate::convert::{TryFrom, TryInto};
 
 use libc::{c_int, c_void};
 
-#[cfg(any(target_os = "dragonfly", target_os = "freebsd",
-          target_os = "ios", target_os = "macos",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "solaris", target_os = "haiku", target_os = "l4re"))]
-use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
-#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
-              target_os = "ios", target_os = "macos",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "solaris", target_os = "haiku", target_os = "l4re")))]
+#[cfg(not(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+)))]
 use crate::sys::net::netc::IPV6_ADD_MEMBERSHIP;
-#[cfg(any(target_os = "dragonfly", target_os = "freebsd",
-          target_os = "ios", target_os = "macos",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "solaris", target_os = "haiku", target_os = "l4re"))]
-use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
-#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
-              target_os = "ios", target_os = "macos",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "solaris", target_os = "haiku", target_os = "l4re")))]
+#[cfg(not(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+)))]
 use crate::sys::net::netc::IPV6_DROP_MEMBERSHIP;
+#[cfg(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+))]
+use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
+#[cfg(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+))]
+use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
 
-#[cfg(any(target_os = "linux", target_os = "android",
-          target_os = "dragonfly", target_os = "freebsd",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "haiku"))]
+#[cfg(any(
+    target_os = "linux",
+    target_os = "android",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "haiku"
+))]
 use libc::MSG_NOSIGNAL;
-#[cfg(not(any(target_os = "linux", target_os = "android",
-              target_os = "dragonfly", target_os = "freebsd",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "haiku")))]
+#[cfg(not(any(
+    target_os = "linux",
+    target_os = "android",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "haiku"
+)))]
 const MSG_NOSIGNAL: c_int = 0x0;
 
 ////////////////////////////////////////////////////////////////////////////////
 // sockaddr and misc bindings
 ////////////////////////////////////////////////////////////////////////////////
 
-pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
-                     payload: T) -> io::Result<()> {
+pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> {
     unsafe {
         let payload = &payload as *const T as *const c_void;
-        cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
-                          mem::size_of::<T>() as c::socklen_t))?;
+        cvt(c::setsockopt(
+            *sock.as_inner(),
+            opt,
+            val,
+            payload,
+            mem::size_of::<T>() as c::socklen_t,
+        ))?;
         Ok(())
     }
 }
 
-pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
-                       val: c_int) -> io::Result<T> {
+pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, val: c_int) -> io::Result<T> {
     unsafe {
         let mut slot: T = mem::zeroed();
         let mut len = mem::size_of::<T>() as c::socklen_t;
-        cvt(c::getsockopt(*sock.as_inner(), opt, val,
-                          &mut slot as *mut _ as *mut _,
-                          &mut len))?;
+        cvt(c::getsockopt(*sock.as_inner(), opt, val, &mut slot as *mut _ as *mut _, &mut len))?;
         assert_eq!(len as usize, mem::size_of::<T>());
         Ok(slot)
     }
 }
 
 fn sockname<F>(f: F) -> io::Result<SocketAddr>
-    where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int
+where
+    F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int,
 {
     unsafe {
         let mut storage: c::sockaddr_storage = mem::zeroed();
@@ -83,8 +123,7 @@ fn sockname<F>(f: F) -> io::Result<SocketAddr>
     }
 }
 
-pub fn sockaddr_to_addr(storage: &c::sockaddr_storage,
-                    len: usize) -> io::Result<SocketAddr> {
+pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result<SocketAddr> {
     match storage.ss_family as c_int {
         c::AF_INET => {
             assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
@@ -98,9 +137,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage,
                 *(storage as *const _ as *const c::sockaddr_in6)
             })))
         }
-        _ => {
-            Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
-        }
+        _ => Err(Error::new(ErrorKind::InvalidInput, "invalid argument")),
     }
 }
 
@@ -121,7 +158,7 @@ fn to_ipv6mr_interface(value: u32) -> libc::c_uint {
 pub struct LookupHost {
     original: *mut c::addrinfo,
     cur: *mut c::addrinfo,
-    port: u16
+    port: u16,
 }
 
 impl LookupHost {
@@ -137,9 +174,7 @@ impl Iterator for LookupHost {
             unsafe {
                 let cur = self.cur.as_ref()?;
                 self.cur = cur.ai_next;
-                match sockaddr_to_addr(mem::transmute(cur.ai_addr),
-                                       cur.ai_addrlen as usize)
-                {
+                match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) {
                     Ok(addr) => return Some(addr),
                     Err(_) => continue,
                 }
@@ -162,13 +197,12 @@ impl TryFrom<&str> for LookupHost {
 
     fn try_from(s: &str) -> io::Result<LookupHost> {
         macro_rules! try_opt {
-            ($e:expr, $msg:expr) => (
+            ($e:expr, $msg:expr) => {
                 match $e {
                     Some(r) => r,
-                    None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                                      $msg)),
+                    None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)),
                 }
-            )
+            };
         }
 
         // split the string by ':' and convert the second part to u16
@@ -192,9 +226,8 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
         hints.ai_socktype = c::SOCK_STREAM;
         let mut res = ptr::null_mut();
         unsafe {
-            cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| {
-                LookupHost { original: res, cur: res, port }
-            })
+            cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res))
+                .map(|_| LookupHost { original: res, cur: res, port })
         }
     }
 }
@@ -228,9 +261,13 @@ impl TcpStream {
         Ok(TcpStream { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
         self.inner.set_timeout(dur, c::SO_RCVTIMEO)
@@ -263,10 +300,7 @@ impl TcpStream {
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let ret = cvt(unsafe {
-            c::send(*self.inner.as_inner(),
-                    buf.as_ptr() as *const c_void,
-                    len,
-                    MSG_NOSIGNAL)
+            c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
         })?;
         Ok(ret as usize)
     }
@@ -276,15 +310,11 @@ impl TcpStream {
     }
 
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getpeername(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
@@ -339,9 +369,8 @@ impl fmt::Debug for TcpStream {
             res.field("peer", &peer);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -365,8 +394,7 @@ impl TcpListener {
         // to quickly rebind a socket, without needing to wait for
         // the OS to clean up the previous one.
         if !cfg!(windows) {
-            setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
-                       1 as c_int)?;
+            setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?;
         }
 
         // Bind our new socket
@@ -378,23 +406,24 @@ impl TcpListener {
         Ok(TcpListener { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
         let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
         let mut len = mem::size_of_val(&storage) as c::socklen_t;
-        let sock = self.inner.accept(&mut storage as *mut _ as *mut _,
-                                     &mut len)?;
+        let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?;
         let addr = sockaddr_to_addr(&storage, len as usize)?;
-        Ok((TcpStream { inner: sock, }, addr))
+        Ok((TcpStream { inner: sock }, addr))
     }
 
     pub fn duplicate(&self) -> io::Result<TcpListener> {
@@ -442,9 +471,8 @@ impl fmt::Debug for TcpListener {
             res.field("addr", &addr);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -468,20 +496,20 @@ impl UdpSocket {
         Ok(UdpSocket { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getpeername(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
@@ -496,9 +524,14 @@ impl UdpSocket {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let (dstp, dstlen) = dst.into_inner();
         let ret = cvt(unsafe {
-            c::sendto(*self.inner.as_inner(),
-                      buf.as_ptr() as *const c_void, len,
-                      MSG_NOSIGNAL, dstp, dstlen)
+            c::sendto(
+                *self.inner.as_inner(),
+                buf.as_ptr() as *const c_void,
+                len,
+                MSG_NOSIGNAL,
+                dstp,
+                dstlen,
+            )
         })?;
         Ok(ret as usize)
     }
@@ -559,8 +592,7 @@ impl UdpSocket {
         Ok(raw != 0)
     }
 
-    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
         let mreq = c::ip_mreq {
             imr_multiaddr: *multiaddr.as_inner(),
             imr_interface: *interface.as_inner(),
@@ -568,8 +600,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
     }
 
-    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
         let mreq = c::ipv6_mreq {
             ipv6mr_multiaddr: *multiaddr.as_inner(),
             ipv6mr_interface: to_ipv6mr_interface(interface),
@@ -577,8 +608,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
     }
 
-    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
         let mreq = c::ip_mreq {
             imr_multiaddr: *multiaddr.as_inner(),
             imr_interface: *interface.as_inner(),
@@ -586,8 +616,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
     }
 
-    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
         let mreq = c::ipv6_mreq {
             ipv6mr_multiaddr: *multiaddr.as_inner(),
             ipv6mr_interface: to_ipv6mr_interface(interface),
@@ -623,10 +652,7 @@ impl UdpSocket {
     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let ret = cvt(unsafe {
-            c::send(*self.inner.as_inner(),
-                    buf.as_ptr() as *const c_void,
-                    len,
-                    MSG_NOSIGNAL)
+            c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
         })?;
         Ok(ret as usize)
     }
@@ -651,9 +677,8 @@ impl fmt::Debug for UdpSocket {
             res.field("addr", &addr);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -667,10 +692,15 @@ mod tests {
         let mut addrs = HashMap::new();
         let lh = match LookupHost::try_from(("localhost", 0)) {
             Ok(lh) => lh,
-            Err(e) => panic!("couldn't resolve `localhost': {}", e)
+            Err(e) => panic!("couldn't resolve `localhost': {}", e),
         };
-        for sa in lh { *addrs.entry(sa).or_insert(0) += 1; };
-        assert_eq!(addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(), vec![],
-                   "There should be no duplicate localhost entries");
+        for sa in lh {
+            *addrs.entry(sa).or_insert(0) += 1;
+        }
+        assert_eq!(
+            addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(),
+            vec![],
+            "There should be no duplicate localhost entries"
+        );
     }
 }
diff --git a/src/libstd/sys_common/os_str_bytes.rs b/src/libstd/sys_common/os_str_bytes.rs
index 3753269adfe..a2608ad4000 100644
--- a/src/libstd/sys_common/os_str_bytes.rs
+++ b/src/libstd/sys_common/os_str_bytes.rs
@@ -4,18 +4,18 @@
 use crate::borrow::Cow;
 use crate::ffi::{OsStr, OsString};
 use crate::fmt;
-use crate::str;
 use crate::mem;
 use crate::rc::Rc;
+use crate::str;
 use crate::sync::Arc;
-use crate::sys_common::{FromInner, IntoInner, AsInner};
 use crate::sys_common::bytestring::debug_fmt_bytestring;
+use crate::sys_common::{AsInner, FromInner, IntoInner};
 
 use core::str::lossy::Utf8Lossy;
 
 #[derive(Clone, Hash)]
 pub(crate) struct Buf {
-    pub inner: Vec<u8>
+    pub inner: Vec<u8>,
 }
 
 // FIXME:
@@ -25,7 +25,7 @@ pub(crate) struct Buf {
 // Anyway, `Slice` representation and layout are considered implementation detail, are
 // not documented and must not be relied upon.
 pub(crate) struct Slice {
-    pub inner: [u8]
+    pub inner: [u8],
 }
 
 impl fmt::Debug for Slice {
@@ -64,7 +64,6 @@ impl AsInner<[u8]> for Buf {
     }
 }
 
-
 impl Buf {
     pub fn from_string(s: String) -> Buf {
         Buf { inner: s.into_bytes() }
@@ -72,9 +71,7 @@ impl Buf {
 
     #[inline]
     pub fn with_capacity(capacity: usize) -> Buf {
-        Buf {
-            inner: Vec::with_capacity(capacity)
-        }
+        Buf { inner: Vec::with_capacity(capacity) }
     }
 
     #[inline]
@@ -112,7 +109,7 @@ impl Buf {
     }
 
     pub fn into_string(self) -> Result<String, Buf> {
-        String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } )
+        String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() })
     }
 
     pub fn push_slice(&mut self, s: &Slice) {
diff --git a/src/libstd/sys_common/poison.rs b/src/libstd/sys_common/poison.rs
index adac45f2d59..0157b952996 100644
--- a/src/libstd/sys_common/poison.rs
+++ b/src/libstd/sys_common/poison.rs
@@ -1,9 +1,11 @@
-use crate::error::{Error};
+use crate::error::Error;
 use crate::fmt;
 use crate::sync::atomic::{AtomicBool, Ordering};
 use crate::thread;
 
-pub struct Flag { failed: AtomicBool }
+pub struct Flag {
+    failed: AtomicBool,
+}
 
 // Note that the Ordering uses to access the `failed` field of `Flag` below is
 // always `Relaxed`, and that's because this isn't actually protecting any data,
@@ -24,11 +26,7 @@ impl Flag {
     #[inline]
     pub fn borrow(&self) -> LockResult<Guard> {
         let ret = Guard { panicking: thread::panicking() };
-        if self.get() {
-            Err(PoisonError::new(ret))
-        } else {
-            Ok(ret)
-        }
+        if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
     }
 
     #[inline]
@@ -192,17 +190,23 @@ impl<T> PoisonError<T> {
     /// println!("recovered {} items", data.len());
     /// ```
     #[stable(feature = "sync_poison", since = "1.2.0")]
-    pub fn into_inner(self) -> T { self.guard }
+    pub fn into_inner(self) -> T {
+        self.guard
+    }
 
     /// Reaches into this error indicating that a lock is poisoned, returning a
     /// reference to the underlying guard to allow access regardless.
     #[stable(feature = "sync_poison", since = "1.2.0")]
-    pub fn get_ref(&self) -> &T { &self.guard }
+    pub fn get_ref(&self) -> &T {
+        &self.guard
+    }
 
     /// Reaches into this error indicating that a lock is poisoned, returning a
     /// mutable reference to the underlying guard to allow access regardless.
     #[stable(feature = "sync_poison", since = "1.2.0")]
-    pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
+    pub fn get_mut(&mut self) -> &mut T {
+        &mut self.guard
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -217,7 +221,7 @@ impl<T> fmt::Debug for TryLockError<T> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
-            TryLockError::WouldBlock => "WouldBlock".fmt(f)
+            TryLockError::WouldBlock => "WouldBlock".fmt(f),
         }
     }
 }
@@ -227,8 +231,9 @@ impl<T> fmt::Display for TryLockError<T> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
-            TryLockError::WouldBlock => "try_lock failed because the operation would block"
-        }.fmt(f)
+            TryLockError::WouldBlock => "try_lock failed because the operation would block",
+        }
+        .fmt(f)
     }
 }
 
@@ -237,23 +242,24 @@ impl<T> Error for TryLockError<T> {
     fn description(&self) -> &str {
         match *self {
             TryLockError::Poisoned(ref p) => p.description(),
-            TryLockError::WouldBlock => "try_lock failed because the operation would block"
+            TryLockError::WouldBlock => "try_lock failed because the operation would block",
         }
     }
 
     fn cause(&self) -> Option<&dyn Error> {
         match *self {
             TryLockError::Poisoned(ref p) => Some(p),
-            _ => None
+            _ => None,
         }
     }
 }
 
-pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-                           -> LockResult<U>
-                           where F: FnOnce(T) -> U {
+pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
+where
+    F: FnOnce(T) -> U,
+{
     match result {
         Ok(t) => Ok(f(t)),
-        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
+        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
     }
 }
diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs
index bdf66fca359..55b421794c4 100644
--- a/src/libstd/sys_common/process.rs
+++ b/src/libstd/sys_common/process.rs
@@ -11,16 +11,12 @@ use crate::sys::process::EnvKey;
 pub struct CommandEnv {
     clear: bool,
     saw_path: bool,
-    vars: BTreeMap<EnvKey, Option<OsString>>
+    vars: BTreeMap<EnvKey, Option<OsString>>,
 }
 
 impl Default for CommandEnv {
     fn default() -> Self {
-        CommandEnv {
-            clear: false,
-            saw_path: false,
-            vars: Default::default()
-        }
+        CommandEnv { clear: false, saw_path: false, vars: Default::default() }
     }
 }
 
@@ -64,11 +60,7 @@ impl CommandEnv {
     }
 
     pub fn capture_if_changed(&self) -> Option<BTreeMap<EnvKey, OsString>> {
-        if self.is_unchanged() {
-            None
-        } else {
-            Some(self.capture())
-        }
+        if self.is_unchanged() { None } else { Some(self.capture()) }
     }
 
     // The following functions build up changes
diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs
index b3c21ec508a..f09d16c33e6 100644
--- a/src/libstd/sys_common/thread_info.rs
+++ b/src/libstd/sys_common/thread_info.rs
@@ -12,16 +12,19 @@ struct ThreadInfo {
 thread_local! { static THREAD_INFO: RefCell<Option<ThreadInfo>> = RefCell::new(None) }
 
 impl ThreadInfo {
-    fn with<R, F>(f: F) -> Option<R> where F: FnOnce(&mut ThreadInfo) -> R {
-        THREAD_INFO.try_with(move |c| {
-            if c.borrow().is_none() {
-                *c.borrow_mut() = Some(ThreadInfo {
-                    stack_guard: None,
-                    thread: Thread::new(None),
-                })
-            }
-            f(c.borrow_mut().as_mut().unwrap())
-        }).ok()
+    fn with<R, F>(f: F) -> Option<R>
+    where
+        F: FnOnce(&mut ThreadInfo) -> R,
+    {
+        THREAD_INFO
+            .try_with(move |c| {
+                if c.borrow().is_none() {
+                    *c.borrow_mut() =
+                        Some(ThreadInfo { stack_guard: None, thread: Thread::new(None) })
+                }
+                f(c.borrow_mut().as_mut().unwrap())
+            })
+            .ok()
     }
 }
 
@@ -35,10 +38,7 @@ pub fn stack_guard() -> Option<Guard> {
 
 pub fn set(stack_guard: Option<Guard>, thread: Thread) {
     THREAD_INFO.with(|c| assert!(c.borrow().is_none()));
-    THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{
-        stack_guard,
-        thread,
-    }));
+    THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo { stack_guard, thread }));
 }
 
 pub fn reset_guard(stack_guard: Option<Guard>) {
diff --git a/src/libstd/sys_common/util.rs b/src/libstd/sys_common/util.rs
index 7936dd35999..00f7db4c037 100644
--- a/src/libstd/sys_common/util.rs
+++ b/src/libstd/sys_common/util.rs
@@ -16,11 +16,15 @@ pub fn dumb_print(args: fmt::Arguments<'_>) {
 
 pub fn abort(args: fmt::Arguments<'_>) -> ! {
     dumb_print(format_args!("fatal runtime error: {}\n", args));
-    unsafe { crate::sys::abort_internal(); }
+    unsafe {
+        crate::sys::abort_internal();
+    }
 }
 
 #[allow(dead_code)] // stack overflow detection not enabled on all platforms
 pub unsafe fn report_overflow() {
-    dumb_print(format_args!("\nthread '{}' has overflowed its stack\n",
-                            thread::current().name().unwrap_or("<unknown>")));
+    dumb_print(format_args!(
+        "\nthread '{}' has overflowed its stack\n",
+        thread::current().name().unwrap_or("<unknown>")
+    ));
 }
diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs
index 81e606fc165..1d96cdfe460 100644
--- a/src/libstd/sys_common/wtf8.rs
+++ b/src/libstd/sys_common/wtf8.rs
@@ -39,7 +39,7 @@ const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}";
 /// a code point that is not a surrogate (U+D800 to U+DFFF).
 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
 pub struct CodePoint {
-    value: u32
+    value: u32,
 }
 
 /// Format the code point as `U+` followed by four to six hexadecimal digits.
@@ -66,8 +66,8 @@ impl CodePoint {
     #[inline]
     pub fn from_u32(value: u32) -> Option<CodePoint> {
         match value {
-            0 ..= 0x10FFFF => Some(CodePoint { value }),
-            _ => None
+            0..=0x10FFFF => Some(CodePoint { value }),
+            _ => None,
         }
     }
 
@@ -91,8 +91,8 @@ impl CodePoint {
     #[inline]
     pub fn to_char(&self) -> Option<char> {
         match self.value {
-            0xD800 ..= 0xDFFF => None,
-            _ => Some(unsafe { char::from_u32_unchecked(self.value) })
+            0xD800..=0xDFFF => None,
+            _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
         }
     }
 
@@ -112,7 +112,7 @@ impl CodePoint {
 /// if they’re not in a surrogate pair.
 #[derive(Eq, PartialEq, Ord, PartialOrd, Clone)]
 pub struct Wtf8Buf {
-    bytes: Vec<u8>
+    bytes: Vec<u8>,
 }
 
 impl ops::Deref for Wtf8Buf {
@@ -188,9 +188,7 @@ impl Wtf8Buf {
                 Err(surrogate) => {
                     let surrogate = surrogate.unpaired_surrogate();
                     // Surrogates are known to be in the code point range.
-                    let code_point = unsafe {
-                        CodePoint::from_u32_unchecked(surrogate as u32)
-                    };
+                    let code_point = unsafe { CodePoint::from_u32_unchecked(surrogate as u32) };
                     // Skip the WTF-8 concatenation check,
                     // surrogate pairs are already decoded by decode_utf16
                     string.push_code_point_unchecked(code_point)
@@ -203,9 +201,7 @@ impl Wtf8Buf {
     /// Copied from String::push
     /// This does **not** include the WTF-8 concatenation check.
     fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
-        let c = unsafe {
-            char::from_u32_unchecked(code_point.value)
-        };
+        let c = unsafe { char::from_u32_unchecked(code_point.value) };
         let mut bytes = [0; 4];
         let bytes = c.encode_utf8(&mut bytes).as_bytes();
         self.bytes.extend_from_slice(bytes)
@@ -278,7 +274,7 @@ impl Wtf8Buf {
                 self.push_char(decode_surrogate_pair(lead, trail));
                 self.bytes.extend_from_slice(other_without_trail_surrogate);
             }
-            _ => self.bytes.extend_from_slice(&other.bytes)
+            _ => self.bytes.extend_from_slice(&other.bytes),
         }
     }
 
@@ -300,7 +296,7 @@ impl Wtf8Buf {
                 let len_without_lead_surrogate = self.len() - 3;
                 self.bytes.truncate(len_without_lead_surrogate);
                 self.push_char(decode_surrogate_pair(lead, trail as u16));
-                return
+                return;
             }
         }
 
@@ -347,8 +343,8 @@ impl Wtf8Buf {
                     pos = surrogate_pos + 3;
                     self.bytes[surrogate_pos..pos]
                         .copy_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
-                },
-                None => return unsafe { String::from_utf8_unchecked(self.bytes) }
+                }
+                None => return unsafe { String::from_utf8_unchecked(self.bytes) },
             }
         }
     }
@@ -371,7 +367,7 @@ impl Wtf8Buf {
 /// This replaces surrogate code point pairs with supplementary code points,
 /// like concatenating ill-formed UTF-16 strings effectively would.
 impl FromIterator<CodePoint> for Wtf8Buf {
-    fn from_iter<T: IntoIterator<Item=CodePoint>>(iter: T) -> Wtf8Buf {
+    fn from_iter<T: IntoIterator<Item = CodePoint>>(iter: T) -> Wtf8Buf {
         let mut string = Wtf8Buf::new();
         string.extend(iter);
         string
@@ -383,7 +379,7 @@ impl FromIterator<CodePoint> for Wtf8Buf {
 /// This replaces surrogate code point pairs with supplementary code points,
 /// like concatenating ill-formed UTF-16 strings effectively would.
 impl Extend<CodePoint> for Wtf8Buf {
-    fn extend<T: IntoIterator<Item=CodePoint>>(&mut self, iter: T) {
+    fn extend<T: IntoIterator<Item = CodePoint>>(&mut self, iter: T) {
         let iterator = iter.into_iter();
         let (low, _high) = iterator.size_hint();
         // Lower bound of one byte per code point (ASCII only)
@@ -398,11 +394,13 @@ impl Extend<CodePoint> for Wtf8Buf {
 /// if they’re not in a surrogate pair.
 #[derive(Eq, Ord, PartialEq, PartialOrd)]
 pub struct Wtf8 {
-    bytes: [u8]
+    bytes: [u8],
 }
 
 impl AsInner<[u8]> for Wtf8 {
-    fn as_inner(&self) -> &[u8] { &self.bytes }
+    fn as_inner(&self) -> &[u8] {
+        &self.bytes
+    }
 }
 
 /// Format the slice with double quotes,
@@ -421,19 +419,13 @@ impl fmt::Debug for Wtf8 {
         formatter.write_str("\"")?;
         let mut pos = 0;
         while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) {
-            write_str_escaped(
-                formatter,
-                unsafe { str::from_utf8_unchecked(
-                    &self.bytes[pos .. surrogate_pos]
-                )},
-            )?;
+            write_str_escaped(formatter, unsafe {
+                str::from_utf8_unchecked(&self.bytes[pos..surrogate_pos])
+            })?;
             write!(formatter, "\\u{{{:x}}}", surrogate)?;
             pos = surrogate_pos + 3;
         }
-        write_str_escaped(
-            formatter,
-            unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) },
-        )?;
+        write_str_escaped(formatter, unsafe { str::from_utf8_unchecked(&self.bytes[pos..]) })?;
         formatter.write_str("\"")
     }
 }
@@ -446,20 +438,14 @@ impl fmt::Display for Wtf8 {
             match self.next_surrogate(pos) {
                 Some((surrogate_pos, _)) => {
                     formatter.write_str(unsafe {
-                        str::from_utf8_unchecked(&wtf8_bytes[pos .. surrogate_pos])
+                        str::from_utf8_unchecked(&wtf8_bytes[pos..surrogate_pos])
                     })?;
                     formatter.write_str(UTF8_REPLACEMENT_CHARACTER)?;
                     pos = surrogate_pos + 3;
-                },
+                }
                 None => {
-                    let s = unsafe {
-                        str::from_utf8_unchecked(&wtf8_bytes[pos..])
-                    };
-                    if pos == 0 {
-                        return s.fmt(formatter)
-                    } else {
-                        return formatter.write_str(s)
-                    }
+                    let s = unsafe { str::from_utf8_unchecked(&wtf8_bytes[pos..]) };
+                    if pos == 0 { return s.fmt(formatter) } else { return formatter.write_str(s) }
                 }
             }
         }
@@ -513,8 +499,8 @@ impl Wtf8 {
     #[inline]
     pub fn ascii_byte_at(&self, position: usize) -> u8 {
         match self.bytes[position] {
-            ascii_byte @ 0x00 ..= 0x7F => ascii_byte,
-            _ => 0xFF
+            ascii_byte @ 0x00..=0x7F => ascii_byte,
+            _ => 0xFF,
         }
     }
 
@@ -558,13 +544,13 @@ impl Wtf8 {
         loop {
             match self.next_surrogate(pos) {
                 Some((surrogate_pos, _)) => {
-                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos .. surrogate_pos]);
+                    utf8_bytes.extend_from_slice(&wtf8_bytes[pos..surrogate_pos]);
                     utf8_bytes.extend_from_slice(UTF8_REPLACEMENT_CHARACTER.as_bytes());
                     pos = surrogate_pos + 3;
-                },
+                }
                 None => {
                     utf8_bytes.extend_from_slice(&wtf8_bytes[pos..]);
-                    return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) })
+                    return Cow::Owned(unsafe { String::from_utf8_unchecked(utf8_bytes) });
                 }
             }
         }
@@ -594,9 +580,9 @@ impl Wtf8 {
             } else if b == 0xED {
                 match (iter.next(), iter.next()) {
                     (Some(&b2), Some(&b3)) if b2 >= 0xA0 => {
-                        return Some((pos, decode_surrogate(b2, b3)))
+                        return Some((pos, decode_surrogate(b2, b3)));
                     }
-                    _ => pos += 3
+                    _ => pos += 3,
                 }
             } else if b < 0xF0 {
                 iter.next();
@@ -615,11 +601,11 @@ impl Wtf8 {
     fn final_lead_surrogate(&self) -> Option<u16> {
         let len = self.len();
         if len < 3 {
-            return None
+            return None;
         }
         match &self.bytes[(len - 3)..] {
             &[0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)),
-            _ => None
+            _ => None,
         }
     }
 
@@ -627,11 +613,11 @@ impl Wtf8 {
     fn initial_trail_surrogate(&self) -> Option<u16> {
         let len = self.len();
         if len < 3 {
-            return None
+            return None;
         }
         match &self.bytes[..3] {
             &[0xED, b2 @ 0xB0..=0xBF, b3] => Some(decode_surrogate(b2, b3)),
-            _ => None
+            _ => None,
         }
     }
 
@@ -661,7 +647,6 @@ impl Wtf8 {
     }
 }
 
-
 /// Returns a slice of the given string for the byte range [`begin`..`end`).
 ///
 /// # Panics
@@ -674,9 +659,10 @@ impl ops::Index<ops::Range<usize>> for Wtf8 {
     #[inline]
     fn index(&self, range: ops::Range<usize>) -> &Wtf8 {
         // is_code_point_boundary checks that the index is in [0, .len()]
-        if range.start <= range.end &&
-           is_code_point_boundary(self, range.start) &&
-           is_code_point_boundary(self, range.end) {
+        if range.start <= range.end
+            && is_code_point_boundary(self, range.start)
+            && is_code_point_boundary(self, range.end)
+        {
             unsafe { slice_unchecked(self, range.start, range.end) }
         } else {
             slice_error_fail(self, range.start, range.end)
@@ -748,7 +734,9 @@ fn decode_surrogate_pair(lead: u16, trail: u16) -> char {
 /// Copied from core::str::StrPrelude::is_char_boundary
 #[inline]
 pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool {
-    if index == slice.len() { return true; }
+    if index == slice.len() {
+        return true;
+    }
     match slice.bytes.get(index) {
         None => false,
         Some(&b) => b < 128 || b >= 192,
@@ -759,18 +747,14 @@ pub fn is_code_point_boundary(slice: &Wtf8, index: usize) -> bool {
 #[inline]
 pub unsafe fn slice_unchecked(s: &Wtf8, begin: usize, end: usize) -> &Wtf8 {
     // memory layout of an &[u8] and &Wtf8 are the same
-    Wtf8::from_bytes_unchecked(slice::from_raw_parts(
-        s.bytes.as_ptr().add(begin),
-        end - begin
-    ))
+    Wtf8::from_bytes_unchecked(slice::from_raw_parts(s.bytes.as_ptr().add(begin), end - begin))
 }
 
 /// Copied from core::str::raw::slice_error_fail
 #[inline(never)]
 pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
     assert!(begin <= end);
-    panic!("index {} and/or {} in `{:?}` do not lie on character boundary",
-          begin, end, s);
+    panic!("index {} and/or {} in `{:?}` do not lie on character boundary", begin, end, s);
 }
 
 /// Iterator for the code points of a WTF-8 string.
@@ -778,7 +762,7 @@ pub fn slice_error_fail(s: &Wtf8, begin: usize, end: usize) -> ! {
 /// Created with the method `.code_points()`.
 #[derive(Clone)]
 pub struct Wtf8CodePoints<'a> {
-    bytes: slice::Iter<'a, u8>
+    bytes: slice::Iter<'a, u8>,
 }
 
 impl<'a> Iterator for Wtf8CodePoints<'a> {
@@ -801,7 +785,7 @@ impl<'a> Iterator for Wtf8CodePoints<'a> {
 #[derive(Clone)]
 pub struct EncodeWide<'a> {
     code_points: Wtf8CodePoints<'a>,
-    extra: u16
+    extra: u16,
 }
 
 // Copied from libunicode/u_str.rs
@@ -819,9 +803,7 @@ impl<'a> Iterator for EncodeWide<'a> {
 
         let mut buf = [0; 2];
         self.code_points.next().map(|code_point| {
-            let c = unsafe {
-                char::from_u32_unchecked(code_point.value)
-            };
+            let c = unsafe { char::from_u32_unchecked(code_point.value) };
             let n = c.encode_utf16(&mut buf).len();
             if n == 2 {
                 self.extra = buf[1];
@@ -864,13 +846,15 @@ impl Hash for Wtf8 {
 }
 
 impl Wtf8 {
-    pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() }
+    pub fn make_ascii_uppercase(&mut self) {
+        self.bytes.make_ascii_uppercase()
+    }
 }
 
 #[cfg(test)]
 mod tests {
-    use crate::borrow::Cow;
     use super::*;
+    use crate::borrow::Cow;
 
     #[test]
     fn code_point_from_u32() {
@@ -882,7 +866,9 @@ mod tests {
 
     #[test]
     fn code_point_to_u32() {
-        fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
+        fn c(value: u32) -> CodePoint {
+            CodePoint::from_u32(value).unwrap()
+        }
         assert_eq!(c(0).to_u32(), 0);
         assert_eq!(c(0xD800).to_u32(), 0xD800);
         assert_eq!(c(0x10FFFF).to_u32(), 0x10FFFF);
@@ -902,7 +888,9 @@ mod tests {
 
     #[test]
     fn code_point_to_char() {
-        fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
+        fn c(value: u32) -> CodePoint {
+            CodePoint::from_u32(value).unwrap()
+        }
         assert_eq!(c(0x61).to_char(), Some('a'));
         assert_eq!(c(0x1F4A9).to_char(), Some('💩'));
         assert_eq!(c(0xD800).to_char(), None);
@@ -910,7 +898,9 @@ mod tests {
 
     #[test]
     fn code_point_to_char_lossy() {
-        fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
+        fn c(value: u32) -> CodePoint {
+            CodePoint::from_u32(value).unwrap()
+        }
         assert_eq!(c(0x61).to_char_lossy(), 'a');
         assert_eq!(c(0x1F4A9).to_char_lossy(), '💩');
         assert_eq!(c(0xD800).to_char_lossy(), '\u{FFFD}');
@@ -924,23 +914,25 @@ mod tests {
     #[test]
     fn wtf8buf_from_str() {
         assert_eq!(Wtf8Buf::from_str("").bytes, b"");
-        assert_eq!(Wtf8Buf::from_str("aé 💩").bytes,
-                   b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(Wtf8Buf::from_str("aé 💩").bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
     }
 
     #[test]
     fn wtf8buf_from_string() {
         assert_eq!(Wtf8Buf::from_string(String::from("")).bytes, b"");
-        assert_eq!(Wtf8Buf::from_string(String::from("aé 💩")).bytes,
-                   b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(
+            Wtf8Buf::from_string(String::from("aé 💩")).bytes,
+            b"a\xC3\xA9 \xF0\x9F\x92\xA9"
+        );
     }
 
     #[test]
     fn wtf8buf_from_wide() {
         assert_eq!(Wtf8Buf::from_wide(&[]).bytes, b"");
-        assert_eq!(Wtf8Buf::from_wide(
-                      &[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
-                   b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9");
+        assert_eq!(
+            Wtf8Buf::from_wide(&[0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]).bytes,
+            b"a\xC3\xA9 \xED\xA0\xBD\xF0\x9F\x92\xA9"
+        );
     }
 
     #[test]
@@ -966,41 +958,43 @@ mod tests {
         string.push(CodePoint::from_char('💩'));
         assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
+        fn c(value: u32) -> CodePoint {
+            CodePoint::from_u32(value).unwrap()
+        }
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xD83D));  // lead
-        string.push(c(0xDCA9));  // trail
-        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        string.push(c(0xD83D)); // lead
+        string.push(c(0xDCA9)); // trail
+        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xD83D));  // lead
-        string.push(c(0x20));  // not surrogate
-        string.push(c(0xDCA9));  // trail
+        string.push(c(0xD83D)); // lead
+        string.push(c(0x20)); // not surrogate
+        string.push(c(0xDCA9)); // trail
         assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xD800));  // lead
-        string.push(c(0xDBFF));  // lead
+        string.push(c(0xD800)); // lead
+        string.push(c(0xDBFF)); // lead
         assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xD800));  // lead
-        string.push(c(0xE000));  // not surrogate
+        string.push(c(0xD800)); // lead
+        string.push(c(0xE000)); // not surrogate
         assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xD7FF));  // not surrogate
-        string.push(c(0xDC00));  // trail
+        string.push(c(0xD7FF)); // not surrogate
+        string.push(c(0xDC00)); // trail
         assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0x61));  // not surrogate, < 3 bytes
-        string.push(c(0xDC00));  // trail
+        string.push(c(0x61)); // not surrogate, < 3 bytes
+        string.push(c(0xDC00)); // trail
         assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push(c(0xDC00));  // trail
+        string.push(c(0xDC00)); // trail
         assert_eq!(string.bytes, b"\xED\xB0\x80");
     }
 
@@ -1011,41 +1005,43 @@ mod tests {
         string.push_wtf8(Wtf8::from_str(" 💩"));
         assert_eq!(string.bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        fn w(v: &[u8]) -> &Wtf8 { unsafe { Wtf8::from_bytes_unchecked(v) } }
+        fn w(v: &[u8]) -> &Wtf8 {
+            unsafe { Wtf8::from_bytes_unchecked(v) }
+        }
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
-        string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
-        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
+        string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
+        assert_eq!(string.bytes, b"\xF0\x9F\x92\xA9"); // Magic!
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\xA0\xBD"));  // lead
-        string.push_wtf8(w(b" "));  // not surrogate
-        string.push_wtf8(w(b"\xED\xB2\xA9"));  // trail
+        string.push_wtf8(w(b"\xED\xA0\xBD")); // lead
+        string.push_wtf8(w(b" ")); // not surrogate
+        string.push_wtf8(w(b"\xED\xB2\xA9")); // trail
         assert_eq!(string.bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
-        string.push_wtf8(w(b"\xED\xAF\xBF"));  // lead
+        string.push_wtf8(w(b"\xED\xA0\x80")); // lead
+        string.push_wtf8(w(b"\xED\xAF\xBF")); // lead
         assert_eq!(string.bytes, b"\xED\xA0\x80\xED\xAF\xBF");
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\xA0\x80"));  // lead
-        string.push_wtf8(w(b"\xEE\x80\x80"));  // not surrogate
+        string.push_wtf8(w(b"\xED\xA0\x80")); // lead
+        string.push_wtf8(w(b"\xEE\x80\x80")); // not surrogate
         assert_eq!(string.bytes, b"\xED\xA0\x80\xEE\x80\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\x9F\xBF"));  // not surrogate
-        string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
+        string.push_wtf8(w(b"\xED\x9F\xBF")); // not surrogate
+        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
         assert_eq!(string.bytes, b"\xED\x9F\xBF\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"a"));  // not surrogate, < 3 bytes
-        string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
+        string.push_wtf8(w(b"a")); // not surrogate, < 3 bytes
+        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
         assert_eq!(string.bytes, b"\x61\xED\xB0\x80");
 
         let mut string = Wtf8Buf::new();
-        string.push_wtf8(w(b"\xED\xB0\x80"));  // trail
+        string.push_wtf8(w(b"\xED\xB0\x80")); // trail
         assert_eq!(string.bytes, b"\xED\xB0\x80");
     }
 
@@ -1093,7 +1089,7 @@ mod tests {
         }
         assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
         assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
         assert_eq!(f(&[0xD800, 0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
         assert_eq!(f(&[0xD800, 0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
@@ -1105,16 +1101,17 @@ mod tests {
     #[test]
     fn wtf8buf_extend() {
         fn e(initial: &[u32], extended: &[u32]) -> Wtf8Buf {
-            fn c(value: &u32) -> CodePoint { CodePoint::from_u32(*value).unwrap() }
+            fn c(value: &u32) -> CodePoint {
+                CodePoint::from_u32(*value).unwrap()
+            }
             let mut string = initial.iter().map(c).collect::<Wtf8Buf>();
             string.extend(extended.iter().map(c));
             string
         }
 
-        assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes,
-                   b"a\xC3\xA9 \xF0\x9F\x92\xA9");
+        assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]).bytes, b"a\xC3\xA9 \xF0\x9F\x92\xA9");
 
-        assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9");  // Magic!
+        assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic!
         assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]).bytes, b"\xED\xA0\xBD \xED\xB2\xA9");
         assert_eq!(e(&[0xD800], &[0xDBFF]).bytes, b"\xED\xA0\x80\xED\xAF\xBF");
         assert_eq!(e(&[0xD800], &[0xE000]).bytes, b"\xED\xA0\x80\xEE\x80\x80");
@@ -1156,13 +1153,13 @@ mod tests {
 
     #[test]
     fn wtf8_slice() {
-        assert_eq!(&Wtf8::from_str("aé 💩")[1.. 4].bytes, b"\xC3\xA9 ");
+        assert_eq!(&Wtf8::from_str("aé 💩")[1..4].bytes, b"\xC3\xA9 ");
     }
 
     #[test]
     #[should_panic]
     fn wtf8_slice_not_code_point_boundary() {
-        &Wtf8::from_str("aé 💩")[2.. 4];
+        &Wtf8::from_str("aé 💩")[2..4];
     }
 
     #[test]
@@ -1199,7 +1196,9 @@ mod tests {
 
     #[test]
     fn wtf8_code_points() {
-        fn c(value: u32) -> CodePoint { CodePoint::from_u32(value).unwrap() }
+        fn c(value: u32) -> CodePoint {
+            CodePoint::from_u32(value).unwrap()
+        }
         fn cp(string: &Wtf8Buf) -> Vec<Option<char>> {
             string.code_points().map(|c| c.to_char()).collect::<Vec<_>>()
         }
@@ -1249,7 +1248,9 @@ mod tests {
         let mut string = Wtf8Buf::from_str("aé ");
         string.push(CodePoint::from_u32(0xD83D).unwrap());
         string.push_char('💩');
-        assert_eq!(string.encode_wide().collect::<Vec<_>>(),
-                   vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]);
+        assert_eq!(
+            string.encode_wide().collect::<Vec<_>>(),
+            vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9]
+        );
     }
 }
diff --git a/src/libstd/tests/env.rs b/src/libstd/tests/env.rs
index f8014cb2ad9..c94fc41178d 100644
--- a/src/libstd/tests/env.rs
+++ b/src/libstd/tests/env.rs
@@ -1,13 +1,12 @@
 use std::env::*;
-use std::ffi::{OsString, OsStr};
+use std::ffi::{OsStr, OsString};
 
-use rand::{thread_rng, Rng};
 use rand::distributions::Alphanumeric;
+use rand::{thread_rng, Rng};
 
 fn make_rand_name() -> OsString {
     let rng = thread_rng();
-    let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10)
-                                 .collect::<String>());
+    let n = format!("TEST{}", rng.sample_iter(&Alphanumeric).take(10).collect::<String>());
     let n = OsString::from(n);
     assert!(var_os(&n).is_none());
     n
@@ -73,11 +72,7 @@ fn test_env_set_var() {
 
     let mut e = vars_os();
     set_var(&n, "VALUE");
-    assert!(!e.any(|(k, v)| {
-        &*k == &*n && &*v == "VALUE"
-    }));
+    assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
 
-    assert!(vars_os().any(|(k, v)| {
-        &*k == &*n && &*v == "VALUE"
-    }));
+    assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" }));
 }
diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs
index 46453b47fca..9c530e7b324 100644
--- a/src/libstd/thread/local.rs
+++ b/src/libstd/thread/local.rs
@@ -142,9 +142,7 @@ macro_rules! thread_local {
 }
 
 #[doc(hidden)]
-#[unstable(feature = "thread_local_internals",
-           reason = "should not be necessary",
-           issue = "0")]
+#[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "0")]
 #[macro_export]
 #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
 #[allow_internal_unsafe]
@@ -214,13 +212,13 @@ impl Error for AccessError {}
 
 impl<T: 'static> LocalKey<T> {
     #[doc(hidden)]
-    #[unstable(feature = "thread_local_internals",
-               reason = "recently added to create a key",
-               issue = "0")]
+    #[unstable(
+        feature = "thread_local_internals",
+        reason = "recently added to create a key",
+        issue = "0"
+    )]
     pub const unsafe fn new(inner: unsafe fn() -> Option<&'static T>) -> LocalKey<T> {
-        LocalKey {
-            inner,
-        }
+        LocalKey { inner }
     }
 
     /// Acquires a reference to the value in this TLS key.
@@ -235,9 +233,13 @@ impl<T: 'static> LocalKey<T> {
     /// previously been run for this thread.
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn with<F, R>(&'static self, f: F) -> R
-                      where F: FnOnce(&T) -> R {
-        self.try_with(f).expect("cannot access a Thread Local Storage value \
-                                 during or after destruction")
+    where
+        F: FnOnce(&T) -> R,
+    {
+        self.try_with(f).expect(
+            "cannot access a Thread Local Storage value \
+             during or after destruction",
+        )
     }
 
     /// Acquires a reference to the value in this TLS key.
@@ -256,9 +258,7 @@ impl<T: 'static> LocalKey<T> {
         F: FnOnce(&T) -> R,
     {
         unsafe {
-            let thread_local = (self.inner)().ok_or(AccessError {
-                _private: (),
-            })?;
+            let thread_local = (self.inner)().ok_or(AccessError { _private: () })?;
             Ok(f(thread_local))
         }
     }
@@ -266,8 +266,8 @@ impl<T: 'static> LocalKey<T> {
 
 mod lazy {
     use crate::cell::UnsafeCell;
-    use crate::mem;
     use crate::hint;
+    use crate::mem;
 
     pub struct LazyKeyInner<T> {
         inner: UnsafeCell<Option<T>>,
@@ -275,9 +275,7 @@ mod lazy {
 
     impl<T> LazyKeyInner<T> {
         pub const fn new() -> LazyKeyInner<T> {
-            LazyKeyInner {
-                inner: UnsafeCell::new(None),
-            }
+            LazyKeyInner { inner: UnsafeCell::new(None) }
         }
 
         pub unsafe fn get(&self) -> Option<&'static T> {
@@ -334,7 +332,7 @@ pub mod statik {
         inner: LazyKeyInner<T>,
     }
 
-    unsafe impl<T> Sync for Key<T> { }
+    unsafe impl<T> Sync for Key<T> {}
 
     impl<T> fmt::Debug for Key<T> {
         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -344,9 +342,7 @@ pub mod statik {
 
     impl<T> Key<T> {
         pub const fn new() -> Key<T> {
-            Key {
-                inner: LazyKeyInner::new(),
-            }
+            Key { inner: LazyKeyInner::new() }
         }
 
         pub unsafe fn get(&self, init: fn() -> T) -> Option<&'static T> {
@@ -404,10 +400,7 @@ pub mod fast {
 
     impl<T> Key<T> {
         pub const fn new() -> Key<T> {
-            Key {
-                inner: LazyKeyInner::new(),
-                dtor_state: Cell::new(DtorState::Unregistered),
-            }
+            Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
         }
 
         pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
@@ -441,8 +434,7 @@ pub mod fast {
             match self.dtor_state.get() {
                 DtorState::Unregistered => {
                     // dtor registration happens before initialization.
-                    register_dtor(self as *const _ as *mut u8,
-                                destroy_value::<T>);
+                    register_dtor(self as *const _ as *mut u8, destroy_value::<T>);
                     self.dtor_state.set(DtorState::Registered);
                     true
                 }
@@ -450,14 +442,12 @@ pub mod fast {
                     // recursively initialized
                     true
                 }
-                DtorState::RunningOrHasRun => {
-                    false
-                }
+                DtorState::RunningOrHasRun => false,
             }
         }
     }
 
-    unsafe extern fn destroy_value<T>(ptr: *mut u8) {
+    unsafe extern "C" fn destroy_value<T>(ptr: *mut u8) {
         let ptr = ptr as *mut Key<T>;
 
         // Right before we run the user destructor be sure to set the
@@ -491,7 +481,7 @@ pub mod os {
         }
     }
 
-    unsafe impl<T> Sync for Key<T> { }
+    unsafe impl<T> Sync for Key<T> {}
 
     struct Value<T: 'static> {
         inner: LazyKeyInner<T>,
@@ -500,10 +490,7 @@ pub mod os {
 
     impl<T: 'static> Key<T> {
         pub const fn new() -> Key<T> {
-            Key {
-                os: OsStaticKey::new(Some(destroy_value::<T>)),
-                marker: marker::PhantomData
-            }
+            Key { os: OsStaticKey::new(Some(destroy_value::<T>)), marker: marker::PhantomData }
         }
 
         pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> {
@@ -523,16 +510,13 @@ pub mod os {
             let ptr = self.os.get() as *mut Value<T>;
             if ptr as usize == 1 {
                 // destructor is running
-                return None
+                return None;
             }
 
             let ptr = if ptr.is_null() {
                 // If the lookup returned null, we haven't initialized our own
                 // local copy, so do that now.
-                let ptr: Box<Value<T>> = box Value {
-                    inner: LazyKeyInner::new(),
-                    key: self,
-                };
+                let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
                 let ptr = Box::into_raw(ptr);
                 self.os.set(ptr as *mut u8);
                 ptr
@@ -545,7 +529,7 @@ pub mod os {
         }
     }
 
-    unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
+    unsafe extern "C" fn destroy_value<T: 'static>(ptr: *mut u8) {
         // The OS TLS ensures that this key contains a NULL value when this
         // destructor starts to run. We set it back to a sentinel value of 1 to
         // ensure that any future calls to `get` for this thread will return
@@ -563,8 +547,8 @@ pub mod os {
 
 #[cfg(all(test, not(target_os = "emscripten")))]
 mod tests {
-    use crate::sync::mpsc::{channel, Sender};
     use crate::cell::{Cell, UnsafeCell};
+    use crate::sync::mpsc::{channel, Sender};
     use crate::thread;
 
     struct Foo(Sender<()>);
@@ -585,7 +569,7 @@ mod tests {
             f.set(2);
         });
         let (tx, rx) = channel();
-        let _t = thread::spawn(move|| {
+        let _t = thread::spawn(move || {
             FOO.with(|f| {
                 assert_eq!(f.get(), 1);
             });
@@ -610,7 +594,10 @@ mod tests {
 
         thread::spawn(|| {
             assert!(FOO.try_with(|_| ()).is_ok());
-        }).join().ok().expect("thread panicked");
+        })
+        .join()
+        .ok()
+        .expect("thread panicked");
     }
 
     #[test]
@@ -618,7 +605,7 @@ mod tests {
         thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
 
         let (tx, rx) = channel();
-        let _t = thread::spawn(move|| unsafe {
+        let _t = thread::spawn(move || unsafe {
             let mut tx = Some(tx);
             FOO.with(|f| {
                 *f.get() = Some(Foo(tx.take().unwrap()));
@@ -662,9 +649,12 @@ mod tests {
             }
         }
 
-        thread::spawn(move|| {
+        thread::spawn(move || {
             drop(S1);
-        }).join().ok().expect("thread panicked");
+        })
+        .join()
+        .ok()
+        .expect("thread panicked");
     }
 
     #[test]
@@ -678,9 +668,12 @@ mod tests {
             }
         }
 
-        thread::spawn(move|| unsafe {
+        thread::spawn(move || unsafe {
             K1.with(|s| *s.get() = Some(S1));
-        }).join().ok().expect("thread panicked");
+        })
+        .join()
+        .ok()
+        .expect("thread panicked");
     }
 
     // Note that this test will deadlock if TLS destructors aren't run (this
@@ -701,7 +694,7 @@ mod tests {
         }
 
         let (tx, rx) = channel();
-        let _t = thread::spawn(move|| unsafe {
+        let _t = thread::spawn(move || unsafe {
             let mut tx = Some(tx);
             K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
         });
@@ -716,7 +709,9 @@ mod dynamic_tests {
 
     #[test]
     fn smoke() {
-        fn square(i: i32) -> i32 { i * i }
+        fn square(i: i32) -> i32 {
+            i * i
+        }
         thread_local!(static FOO: i32 = square(3));
 
         FOO.with(|f| {
diff --git a/src/libsyntax/Cargo.toml b/src/libsyntax/Cargo.toml
index dff23076c82..085c1760c80 100644
--- a/src/libsyntax/Cargo.toml
+++ b/src/libsyntax/Cargo.toml
@@ -18,6 +18,7 @@ lazy_static = "1.0.0"
 syntax_pos = { path = "../libsyntax_pos" }
 errors = { path = "../librustc_errors", package = "rustc_errors" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_index = { path = "../librustc_index" }
 rustc_lexer = { path = "../librustc_lexer" }
 rustc_macros = { path = "../librustc_macros" }
diff --git a/src/libsyntax/attr/builtin.rs b/src/libsyntax/attr/builtin.rs
index c10541c8c7e..3c10f27b60a 100644
--- a/src/libsyntax/attr/builtin.rs
+++ b/src/libsyntax/attr/builtin.rs
@@ -1,7 +1,8 @@
 //! Parsing and validation of builtin attributes
 
+use super::{mark_used, MetaItemKind};
 use crate::ast::{self, Attribute, MetaItem, NestedMetaItem};
-use crate::feature_gate::{Features, GatedCfg};
+use crate::feature_gate::feature_err;
 use crate::print::pprust;
 use crate::sess::ParseSess;
 
@@ -9,12 +10,15 @@ use errors::{Applicability, Handler};
 use std::num::NonZeroU32;
 use syntax_pos::hygiene::Transparency;
 use syntax_pos::{symbol::Symbol, symbol::sym, Span};
+use rustc_feature::{Features, find_gated_cfg, GatedCfg, is_builtin_attr_name};
 use rustc_macros::HashStable_Generic;
 
-use super::{mark_used, MetaItemKind};
-
 use rustc_error_codes::*;
 
+pub fn is_builtin_attr(attr: &Attribute) -> bool {
+    attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some()
+}
+
 enum AttrError {
     MultipleItem(String),
     UnknownMetaItem(String, &'static [&'static str]),
@@ -24,31 +28,6 @@ enum AttrError {
     UnsupportedLiteral(&'static str, /* is_bytestr */ bool),
 }
 
-/// A template that the attribute input must match.
-/// Only top-level shape (`#[attr]` vs `#[attr(...)]` vs `#[attr = ...]`) is considered now.
-#[derive(Clone, Copy)]
-pub struct AttributeTemplate {
-    pub word: bool,
-    pub list: Option<&'static str>,
-    pub name_value_str: Option<&'static str>,
-}
-
-impl AttributeTemplate {
-    pub fn only_word() -> Self {
-        Self { word: true, list: None, name_value_str: None }
-    }
-
-    /// Checks that the given meta-item is compatible with this template.
-    pub fn compatible(&self, meta_item_kind: &ast::MetaItemKind) -> bool {
-        match meta_item_kind {
-            ast::MetaItemKind::Word => self.word,
-            ast::MetaItemKind::List(..) => self.list.is_some(),
-            ast::MetaItemKind::NameValue(lit) if lit.kind.is_str() => self.name_value_str.is_some(),
-            ast::MetaItemKind::NameValue(..) => false,
-        }
-    }
-}
-
 fn handle_errors(sess: &ParseSess, span: Span, error: AttrError) {
     let diag = &sess.span_diagnostic;
     match error {
@@ -555,8 +534,9 @@ pub fn find_crate_name(attrs: &[Attribute]) -> Option<Symbol> {
 /// Tests if a cfg-pattern matches the cfg set
 pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Features>) -> bool {
     eval_condition(cfg, sess, &mut |cfg| {
-        if let (Some(feats), Some(gated_cfg)) = (features, GatedCfg::gate(cfg)) {
-            gated_cfg.check_and_emit(sess, feats);
+        let gate = find_gated_cfg(|sym| cfg.check_name(sym));
+        if let (Some(feats), Some(gated_cfg)) = (features, gate) {
+            gate_cfg(&gated_cfg, cfg.span, sess, feats);
         }
         let error = |span, msg| { sess.span_diagnostic.span_err(span, msg); true };
         if cfg.path.segments.len() != 1 {
@@ -585,12 +565,21 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat
     })
 }
 
+fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &ParseSess, features: &Features) {
+    let (cfg, feature, has_feature) = gated_cfg;
+    if !has_feature(features) && !cfg_span.allows_unstable(*feature) {
+        let explain = format!("`cfg({})` is experimental and subject to change", cfg);
+        feature_err(sess, *feature, cfg_span, &explain).emit()
+    }
+}
+
 /// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
 /// evaluate individual items.
-pub fn eval_condition<F>(cfg: &ast::MetaItem, sess: &ParseSess, eval: &mut F)
-                         -> bool
-    where F: FnMut(&ast::MetaItem) -> bool
-{
+pub fn eval_condition(
+    cfg: &ast::MetaItem,
+    sess: &ParseSess,
+    eval: &mut impl FnMut(&ast::MetaItem) -> bool,
+) -> bool {
     match cfg.kind {
         ast::MetaItemKind::List(ref mis) => {
             for mi in mis.iter() {
diff --git a/src/libsyntax/expand/allocator.rs b/src/libsyntax/expand/allocator.rs
index 20487b9af03..cc3eeed04a6 100644
--- a/src/libsyntax/expand/allocator.rs
+++ b/src/libsyntax/expand/allocator.rs
@@ -5,16 +5,14 @@ use syntax_pos::Span;
 #[derive(Clone, Copy)]
 pub enum AllocatorKind {
     Global,
-    DefaultLib,
-    DefaultExe,
+    Default,
 }
 
 impl AllocatorKind {
     pub fn fn_name(&self, base: &str) -> String {
         match *self {
             AllocatorKind::Global => format!("__rg_{}", base),
-            AllocatorKind::DefaultLib => format!("__rdl_{}", base),
-            AllocatorKind::DefaultExe => format!("__rde_{}", base),
+            AllocatorKind::Default => format!("__rdl_{}", base),
         }
     }
 }
diff --git a/src/libsyntax/feature_gate/check.rs b/src/libsyntax/feature_gate/check.rs
index ec0eaa56812..3d2c3b1d4f9 100644
--- a/src/libsyntax/feature_gate/check.rs
+++ b/src/libsyntax/feature_gate/check.rs
@@ -1,7 +1,7 @@
-use super::{active::{ACTIVE_FEATURES, Features}, Feature, State as FeatureState};
-use super::accepted::ACCEPTED_FEATURES;
-use super::removed::{REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
-use super::builtin_attrs::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
+use rustc_feature::{ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES};
+use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP};
+use rustc_feature::{Features, Feature, State as FeatureState, UnstableFeatures};
+use rustc_feature::{find_feature_issue, GateIssue};
 
 use crate::ast::{self, AssocTyConstraint, AssocTyConstraintKind, NodeId};
 use crate::ast::{GenericParam, GenericParamKind, PatKind, RangeEnd, VariantData};
@@ -19,18 +19,6 @@ use log::debug;
 
 use rustc_error_codes::*;
 
-
-use std::env;
-use std::num::NonZeroU32;
-
-#[derive(Copy, Clone, Debug)]
-pub enum Stability {
-    Unstable,
-    // First argument is tracking issue link; second argument is an optional
-    // help message, which defaults to "remove this attribute"
-    Deprecated(&'static str, Option<&'static str>),
-}
-
 macro_rules! gate_feature_fn {
     ($cx: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $level: expr) => {{
         let (cx, has_feature, span,
@@ -59,30 +47,6 @@ pub fn check_attribute(attr: &ast::Attribute, parse_sess: &ParseSess, features:
     PostExpansionVisitor { parse_sess, features }.visit_attribute(attr)
 }
 
-fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
-    if let Some(info) = ACTIVE_FEATURES.iter().find(|t| t.name == feature) {
-        // FIXME (#28244): enforce that active features have issue numbers
-        // assert!(info.issue().is_some())
-        info.issue()
-    } else {
-        // search in Accepted, Removed, or Stable Removed features
-        let found = ACCEPTED_FEATURES
-            .iter()
-            .chain(REMOVED_FEATURES)
-            .chain(STABLE_REMOVED_FEATURES)
-            .find(|t| t.name == feature);
-        match found {
-            Some(found) => found.issue(),
-            None => panic!("feature `{}` is not declared anywhere", feature),
-        }
-    }
-}
-
-pub enum GateIssue {
-    Language,
-    Library(Option<NonZeroU32>)
-}
-
 #[derive(Debug, Copy, Clone, PartialEq)]
 pub enum GateStrength {
     /// A hard error. (Most feature gates should use this.)
@@ -91,41 +55,35 @@ pub enum GateStrength {
     Soft,
 }
 
-pub fn emit_feature_err(
-    sess: &ParseSess,
+pub fn feature_err<'a>(
+    sess: &'a ParseSess,
     feature: Symbol,
-    span: Span,
-    issue: GateIssue,
+    span: impl Into<MultiSpan>,
     explain: &str,
-) {
-    feature_err(sess, feature, span, issue, explain).emit();
+) -> DiagnosticBuilder<'a> {
+    feature_err_issue(sess, feature, span, GateIssue::Language, explain)
 }
 
-pub fn feature_err<'a, S: Into<MultiSpan>>(
+pub fn feature_err_issue<'a>(
     sess: &'a ParseSess,
     feature: Symbol,
-    span: S,
+    span: impl Into<MultiSpan>,
     issue: GateIssue,
     explain: &str,
 ) -> DiagnosticBuilder<'a> {
     leveled_feature_err(sess, feature, span, issue, explain, GateStrength::Hard)
 }
 
-fn leveled_feature_err<'a, S: Into<MultiSpan>>(
+fn leveled_feature_err<'a>(
     sess: &'a ParseSess,
     feature: Symbol,
-    span: S,
+    span: impl Into<MultiSpan>,
     issue: GateIssue,
     explain: &str,
     level: GateStrength,
 ) -> DiagnosticBuilder<'a> {
     let diag = &sess.span_diagnostic;
 
-    let issue = match issue {
-        GateIssue::Language => find_lang_feature_issue(feature),
-        GateIssue::Library(lib) => lib,
-    };
-
     let mut err = match level {
         GateStrength::Hard => {
             diag.struct_span_err_with_code(span, explain, stringify_error_code!(E0658))
@@ -133,7 +91,7 @@ fn leveled_feature_err<'a, S: Into<MultiSpan>>(
         GateStrength::Soft => diag.struct_span_warn(span, explain),
     };
 
-    if let Some(n) = issue {
+    if let Some(n) = find_feature_issue(feature, issue) {
         err.note(&format!(
             "for more information, see https://github.com/rust-lang/rust/issues/{}",
             n,
@@ -156,20 +114,6 @@ fn leveled_feature_err<'a, S: Into<MultiSpan>>(
 
 }
 
-const EXPLAIN_BOX_SYNTAX: &str =
-    "box expression syntax is experimental; you can call `Box::new` instead";
-
-pub const EXPLAIN_STMT_ATTR_SYNTAX: &str =
-    "attributes on expressions are experimental";
-
-pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str =
-    "allow_internal_unstable side-steps feature gating and stability checks";
-pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str =
-    "allow_internal_unsafe side-steps the unsafe_code lint";
-
-pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str =
-    "unsized tuple coercion is not stable enough for use and is subject to change";
-
 struct PostExpansionVisitor<'a> {
     parse_sess: &'a ParseSess,
     features: &'a Features,
@@ -282,7 +226,6 @@ impl<'a> PostExpansionVisitor<'a> {
                 self.parse_sess,
                 sym::arbitrary_enum_discriminant,
                 discriminant_spans.clone(),
-                crate::feature_gate::GateIssue::Language,
                 "custom discriminant values are not allowed in enums with tuple or struct variants",
             );
             for sp in discriminant_spans {
@@ -529,7 +472,10 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
     fn visit_expr(&mut self, e: &'a ast::Expr) {
         match e.kind {
             ast::ExprKind::Box(_) => {
-                gate_feature_post!(&self, box_syntax, e.span, EXPLAIN_BOX_SYNTAX);
+                gate_feature_post!(
+                    &self, box_syntax, e.span,
+                    "box expression syntax is experimental; you can call `Box::new` instead"
+                );
             }
             ast::ExprKind::Type(..) => {
                 // To avoid noise about type ascription in common syntax errors, only emit if it
@@ -695,7 +641,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
         err.emit();
     }
 
-    let mut features = Features::new();
+    let mut features = Features::default();
     let mut edition_enabled_features = FxHashMap::default();
 
     for &edition in ALL_EDITIONS {
@@ -900,40 +846,6 @@ pub fn check_crate(krate: &ast::Crate,
     visit::walk_crate(&mut visitor, krate);
 }
 
-#[derive(Clone, Copy, Hash)]
-pub enum UnstableFeatures {
-    /// Hard errors for unstable features are active, as on beta/stable channels.
-    Disallow,
-    /// Allow features to be activated, as on nightly.
-    Allow,
-    /// Errors are bypassed for bootstrapping. This is required any time
-    /// during the build that feature-related lints are set to warn or above
-    /// because the build turns on warnings-as-errors and uses lots of unstable
-    /// features. As a result, this is always required for building Rust itself.
-    Cheat
-}
-
-impl UnstableFeatures {
-    pub fn from_environment() -> UnstableFeatures {
-        // `true` if this is a feature-staged build, i.e., on the beta or stable channel.
-        let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
-        // `true` if we should enable unstable features for bootstrapping.
-        let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok();
-        match (disable_unstable_features, bootstrap) {
-            (_, true) => UnstableFeatures::Cheat,
-            (true, _) => UnstableFeatures::Disallow,
-            (false, _) => UnstableFeatures::Allow
-        }
-    }
-
-    pub fn is_nightly_build(&self) -> bool {
-        match *self {
-            UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
-            UnstableFeatures::Disallow => false,
-        }
-    }
-}
-
 fn maybe_stage_features(span_handler: &Handler, krate: &ast::Crate, unstable: UnstableFeatures) {
     if !unstable.is_nightly_build() {
         for attr in krate.attrs.iter().filter(|attr| attr.check_name(sym::feature)) {
diff --git a/src/libsyntax/feature_gate/mod.rs b/src/libsyntax/feature_gate/mod.rs
deleted file mode 100644
index c4418c0f0f6..00000000000
--- a/src/libsyntax/feature_gate/mod.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-//! # Feature gating
-//!
-//! This module implements the gating necessary for preventing certain compiler
-//! features from being used by default. This module will crawl a pre-expanded
-//! AST to ensure that there are no features which are used that are not
-//! enabled.
-//!
-//! Features are enabled in programs via the crate-level attributes of
-//! `#![feature(...)]` with a comma-separated list of features.
-//!
-//! For the purpose of future feature-tracking, once code for detection of feature
-//! gate usage is added, *do not remove it again* even once the feature
-//! becomes stable.
-
-mod accepted;
-mod removed;
-mod active;
-mod builtin_attrs;
-mod check;
-
-use crate::{edition::Edition, symbol::Symbol};
-use std::fmt;
-use std::num::NonZeroU32;
-use syntax_pos::Span;
-
-#[derive(Clone, Copy)]
-pub enum State {
-    Accepted,
-    Active { set: fn(&mut Features, Span) },
-    Removed { reason: Option<&'static str> },
-    Stabilized { reason: Option<&'static str> },
-}
-
-impl fmt::Debug for State {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        match self {
-            State::Accepted { .. } => write!(f, "accepted"),
-            State::Active { .. } => write!(f, "active"),
-            State::Removed { .. } => write!(f, "removed"),
-            State::Stabilized { .. } => write!(f, "stabilized"),
-        }
-    }
-}
-
-#[derive(Debug, Clone)]
-pub struct Feature {
-    state: State,
-    name: Symbol,
-    since: &'static str,
-    issue: Option<u32>,  // FIXME: once #58732 is done make this an Option<NonZeroU32>
-    edition: Option<Edition>,
-    description: &'static str,
-}
-
-impl Feature {
-    fn issue(&self) -> Option<NonZeroU32> {
-        self.issue.and_then(|i| NonZeroU32::new(i))
-    }
-}
-
-pub use active::{Features, INCOMPLETE_FEATURES};
-pub use builtin_attrs::{
-    AttributeGate, AttributeType, GatedCfg,
-    BuiltinAttribute, BUILTIN_ATTRIBUTES, BUILTIN_ATTRIBUTE_MAP,
-    deprecated_attributes, is_builtin_attr,  is_builtin_attr_name,
-};
-pub use check::{
-    check_crate, check_attribute, get_features, feature_err, emit_feature_err,
-    Stability, GateIssue, UnstableFeatures,
-    EXPLAIN_STMT_ATTR_SYNTAX, EXPLAIN_UNSIZED_TUPLE_COERCION,
-};
diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs
index 22b49862f49..3d4a5d624c1 100644
--- a/src/libsyntax/lib.rs
+++ b/src/libsyntax/lib.rs
@@ -92,7 +92,10 @@ pub mod attr;
 pub mod expand;
 pub use syntax_pos::source_map;
 pub mod entry;
-pub mod feature_gate;
+pub mod feature_gate {
+    mod check;
+    pub use check::{check_crate, check_attribute, get_features, feature_err, feature_err_issue};
+}
 pub mod mut_visit;
 pub mod ptr;
 pub mod show_span;
diff --git a/src/libsyntax/sess.rs b/src/libsyntax/sess.rs
index 740e9dfe459..aa9217c1b69 100644
--- a/src/libsyntax/sess.rs
+++ b/src/libsyntax/sess.rs
@@ -3,15 +3,15 @@
 
 use crate::ast::{CrateConfig, NodeId};
 use crate::early_buffered_lints::{BufferedEarlyLint, BufferedEarlyLintId};
-use crate::source_map::{SourceMap, FilePathMapping};
-use crate::feature_gate::UnstableFeatures;
 
 use errors::{Applicability, emitter::SilentEmitter, Handler, ColorConfig, DiagnosticBuilder};
 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
 use rustc_data_structures::sync::{Lrc, Lock, Once};
+use rustc_feature::UnstableFeatures;
 use syntax_pos::{Symbol, Span, MultiSpan};
 use syntax_pos::edition::Edition;
 use syntax_pos::hygiene::ExpnId;
+use syntax_pos::source_map::{SourceMap, FilePathMapping};
 
 use std::path::PathBuf;
 use std::str;
diff --git a/src/libsyntax_expand/Cargo.toml b/src/libsyntax_expand/Cargo.toml
index 653b87f0d82..897d5a65ba3 100644
--- a/src/libsyntax_expand/Cargo.toml
+++ b/src/libsyntax_expand/Cargo.toml
@@ -16,6 +16,7 @@ log = "0.4"
 syntax_pos = { path = "../libsyntax_pos" }
 errors = { path = "../librustc_errors", package = "rustc_errors" }
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_lexer = { path = "../librustc_lexer" }
 rustc_parse = { path = "../librustc_parse" }
 smallvec = { version = "1.0", features = ["union", "may_dangle"] }
diff --git a/src/libsyntax_expand/expand.rs b/src/libsyntax_expand/expand.rs
index 4f05b0147bf..a6ced1439c5 100644
--- a/src/libsyntax_expand/expand.rs
+++ b/src/libsyntax_expand/expand.rs
@@ -4,16 +4,17 @@ use crate::hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind};
 use crate::mbe::macro_rules::annotate_err_with_kind;
 use crate::placeholders::{placeholder, PlaceholderExpander};
 use crate::config::StripUnconfigured;
-use rustc_parse::configure;
 
+use rustc_feature::Features;
+use rustc_parse::configure;
 use rustc_parse::DirectoryOwnership;
 use rustc_parse::parser::Parser;
 use rustc_parse::validate_attr;
 use syntax::ast::{self, AttrItem, Block, Ident, LitKind, NodeId, PatKind, Path};
 use syntax::ast::{MacStmtStyle, StmtKind, ItemKind};
-use syntax::attr::{self, HasAttrs};
+use syntax::attr::{self, HasAttrs, is_builtin_attr};
 use syntax::source_map::respan;
-use syntax::feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
+use syntax::feature_gate::{self, feature_err};
 use syntax::mut_visit::*;
 use syntax::print::pprust;
 use syntax::ptr::P;
@@ -726,13 +727,13 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
         if self.cx.ecfg.proc_macro_hygiene() {
             return
         }
-        emit_feature_err(
+        feature_err(
             self.cx.parse_sess,
             sym::proc_macro_hygiene,
             span,
-            GateIssue::Language,
             &format!("custom attributes cannot be applied to {}", kind),
-        );
+        )
+        .emit();
     }
 
     fn gate_proc_macro_input(&self, annotatable: &Annotatable) {
@@ -744,13 +745,13 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
             fn visit_item(&mut self, item: &'ast ast::Item) {
                 match &item.kind {
                     ast::ItemKind::Mod(module) if !module.inline => {
-                        emit_feature_err(
+                        feature_err(
                             self.parse_sess,
                             sym::proc_macro_hygiene,
                             item.span,
-                            GateIssue::Language,
                             "non-inline modules in proc macro input are unstable",
-                        );
+                        )
+                        .emit();
                     }
                     _ => {}
                 }
@@ -789,13 +790,13 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
         if self.cx.ecfg.proc_macro_hygiene() {
             return
         }
-        emit_feature_err(
+        feature_err(
             self.cx.parse_sess,
             sym::proc_macro_hygiene,
             span,
-            GateIssue::Language,
             &format!("procedural macros cannot be expanded to {}", kind),
-        );
+        )
+        .emit();
     }
 
     fn parse_ast_fragment(
@@ -991,9 +992,11 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
         if let Some(attr) = &attr {
             if !self.cx.ecfg.custom_inner_attributes() &&
                attr.style == ast::AttrStyle::Inner && !attr.has_name(sym::test) {
-                emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
-                                 attr.span, GateIssue::Language,
-                                 "non-builtin inner attributes are unstable");
+                feature_err(
+                    &self.cx.parse_sess, sym::custom_inner_attributes, attr.span,
+                    "non-builtin inner attributes are unstable"
+                )
+                .emit();
             }
         }
         attr
diff --git a/src/libsyntax_expand/mbe/macro_rules.rs b/src/libsyntax_expand/mbe/macro_rules.rs
index a1d8b5a5338..b191527df19 100644
--- a/src/libsyntax_expand/mbe/macro_rules.rs
+++ b/src/libsyntax_expand/mbe/macro_rules.rs
@@ -8,12 +8,12 @@ use crate::mbe::macro_parser::{Error, Failure, Success};
 use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq, NamedParseResult};
 use crate::mbe::transcribe::transcribe;
 
+use rustc_feature::Features;
 use rustc_parse::parser::Parser;
 use rustc_parse::Directory;
 use syntax::ast;
 use syntax::attr::{self, TransparencyError};
 use syntax::edition::Edition;
-use syntax::feature_gate::Features;
 use syntax::print::pprust;
 use syntax::sess::ParseSess;
 use syntax::symbol::{kw, sym, Symbol};
diff --git a/src/libsyntax_ext/Cargo.toml b/src/libsyntax_ext/Cargo.toml
index 2ebdac8ef7c..d73a9ea6cdb 100644
--- a/src/libsyntax_ext/Cargo.toml
+++ b/src/libsyntax_ext/Cargo.toml
@@ -14,6 +14,7 @@ errors = { path = "../librustc_errors", package = "rustc_errors" }
 fmt_macros = { path = "../libfmt_macros" }
 log = "0.4"
 rustc_data_structures = { path = "../librustc_data_structures" }
+rustc_feature = { path = "../librustc_feature" }
 rustc_parse = { path = "../librustc_parse" }
 rustc_target = { path = "../librustc_target" }
 smallvec = { version = "1.0", features = ["union", "may_dangle"] }
diff --git a/src/libsyntax_ext/test_harness.rs b/src/libsyntax_ext/test_harness.rs
index 659780d7a43..4c1eec38c6e 100644
--- a/src/libsyntax_ext/test_harness.rs
+++ b/src/libsyntax_ext/test_harness.rs
@@ -2,13 +2,13 @@
 
 use log::debug;
 use smallvec::{smallvec, SmallVec};
+use rustc_feature::Features;
 use rustc_target::spec::PanicStrategy;
 use syntax::ast::{self, Ident};
 use syntax::attr;
 use syntax::entry::{self, EntryPointType};
 use syntax_expand::base::{ExtCtxt, Resolver};
 use syntax_expand::expand::{AstFragment, ExpansionConfig};
-use syntax::feature_gate::Features;
 use syntax::mut_visit::{*, ExpectOne};
 use syntax::ptr::P;
 use syntax::sess::ParseSess;
diff --git a/src/libsyntax_ext/util.rs b/src/libsyntax_ext/util.rs
index e59daab1770..f7bd9a05604 100644
--- a/src/libsyntax_ext/util.rs
+++ b/src/libsyntax_ext/util.rs
@@ -1,7 +1,7 @@
 use rustc_parse::validate_attr;
+use rustc_feature::AttributeTemplate;
 use syntax_pos::Symbol;
 use syntax::ast::MetaItem;
-use syntax::attr::AttributeTemplate;
 use syntax_expand::base::ExtCtxt;
 
 pub fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, name: Symbol) {
diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs
index 7d43c3c8d07..3059b059691 100644
--- a/src/libsyntax_pos/symbol.rs
+++ b/src/libsyntax_pos/symbol.rs
@@ -177,6 +177,7 @@ symbols! {
         cfg_attr,
         cfg_attr_multi,
         cfg_doctest,
+        cfg_sanitize,
         cfg_target_feature,
         cfg_target_has_atomic,
         cfg_target_thread_local,
@@ -634,6 +635,7 @@ symbols! {
         rust_eh_unwind_resume,
         rust_oom,
         rvalue_static_promotion,
+        sanitize,
         sanitizer_runtime,
         _Self,
         self_in_typedefs,
diff --git a/src/libtest/test_result.rs b/src/libtest/test_result.rs
index 80ca9dea18f..bfabe1722db 100644
--- a/src/libtest/test_result.rs
+++ b/src/libtest/test_result.rs
@@ -37,22 +37,30 @@ pub fn calc_result<'a>(
     let result = match (&desc.should_panic, task_result) {
         (&ShouldPanic::No, Ok(())) | (&ShouldPanic::Yes, Err(_)) => TestResult::TrOk,
         (&ShouldPanic::YesWithMessage(msg), Err(ref err)) => {
-            if err
+            let maybe_panic_str = err
                 .downcast_ref::<String>()
                 .map(|e| &**e)
-                .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e))
-                .map(|e| e.contains(msg))
-                .unwrap_or(false)
-            {
+                .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e));
+
+            if maybe_panic_str.map(|e| e.contains(msg)).unwrap_or(false) {
                 TestResult::TrOk
+            } else if desc.allow_fail {
+                TestResult::TrAllowedFail
+            } else if let Some(panic_str) = maybe_panic_str {
+                TestResult::TrFailedMsg(format!(
+                    r#"panic did not contain expected string
+      panic message: `{:?}`,
+ expected substring: `{:?}`"#,
+                    panic_str, msg
+                ))
             } else {
-                if desc.allow_fail {
-                    TestResult::TrAllowedFail
-                } else {
-                    TestResult::TrFailedMsg(
-                        format!("panic did not include expected string '{}'", msg)
-                    )
-                }
+                TestResult::TrFailedMsg(format!(
+                    r#"expected panic with string value,
+ found non-string value: `{:?}`
+     expected substring: `{:?}`"#,
+                    (**err).type_id(),
+                    msg
+                ))
             }
         }
         (&ShouldPanic::Yes, Ok(())) => {
diff --git a/src/libtest/tests.rs b/src/libtest/tests.rs
index 5f55b647f5e..0bea2b80ecf 100644
--- a/src/libtest/tests.rs
+++ b/src/libtest/tests.rs
@@ -15,6 +15,7 @@ use crate::{
         // TestType, TrFailedMsg, TrIgnored, TrOk,
     },
 };
+use std::any::TypeId;
 use std::sync::mpsc::channel;
 use std::time::Duration;
 
@@ -84,7 +85,7 @@ pub fn do_not_run_ignored_tests() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result != TrOk);
+    assert_ne!(result, TrOk);
 }
 
 #[test]
@@ -103,7 +104,7 @@ pub fn ignored_tests_result_in_ignored() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result == TrIgnored);
+    assert_eq!(result, TrIgnored);
 }
 
 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
@@ -126,7 +127,7 @@ fn test_should_panic() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result == TrOk);
+    assert_eq!(result, TrOk);
 }
 
 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
@@ -149,7 +150,7 @@ fn test_should_panic_good_message() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result == TrOk);
+    assert_eq!(result, TrOk);
 }
 
 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
@@ -161,7 +162,9 @@ fn test_should_panic_bad_message() {
         panic!("an error message");
     }
     let expected = "foobar";
-    let failed_msg = "panic did not include expected string";
+    let failed_msg = r#"panic did not contain expected string
+      panic message: `"an error message"`,
+ expected substring: `"foobar"`"#;
     let desc = TestDescAndFn {
         desc: TestDesc {
             name: StaticTestName("whatever"),
@@ -175,7 +178,35 @@ fn test_should_panic_bad_message() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result == TrFailedMsg(format!("{} '{}'", failed_msg, expected)));
+    assert_eq!(result, TrFailedMsg(failed_msg.to_string()));
+}
+
+// FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
+#[test]
+#[cfg(not(target_os = "emscripten"))]
+fn test_should_panic_non_string_message_type() {
+    use crate::tests::TrFailedMsg;
+    fn f() {
+        panic!(1i32);
+    }
+    let expected = "foobar";
+    let failed_msg = format!(r#"expected panic with string value,
+ found non-string value: `{:?}`
+     expected substring: `"foobar"`"#, TypeId::of::<i32>());
+    let desc = TestDescAndFn {
+        desc: TestDesc {
+            name: StaticTestName("whatever"),
+            ignore: false,
+            should_panic: ShouldPanic::YesWithMessage(expected),
+            allow_fail: false,
+            test_type: TestType::Unknown,
+        },
+        testfn: DynTestFn(Box::new(f)),
+    };
+    let (tx, rx) = channel();
+    run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
+    let result = rx.recv().unwrap().result;
+    assert_eq!(result, TrFailedMsg(failed_msg));
 }
 
 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
@@ -196,7 +227,7 @@ fn test_should_panic_but_succeeds() {
     let (tx, rx) = channel();
     run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No);
     let result = rx.recv().unwrap().result;
-    assert!(result == TrFailedMsg("test did not panic as expected".to_string()));
+    assert_eq!(result, TrFailedMsg("test did not panic as expected".to_string()));
 }
 
 fn report_time_test_template(report_time: bool) -> Option<TestExecTime> {
@@ -570,7 +601,7 @@ pub fn sort_tests() {
     ];
 
     for (a, b) in expected.iter().zip(filtered) {
-        assert!(*a == b.desc.name.to_string());
+        assert_eq!(*a, b.desc.name.to_string());
     }
 }
 
diff --git a/src/rustllvm/PassWrapper.cpp b/src/rustllvm/PassWrapper.cpp
index e2bb49699e9..a116ed282ac 100644
--- a/src/rustllvm/PassWrapper.cpp
+++ b/src/rustllvm/PassWrapper.cpp
@@ -445,17 +445,6 @@ extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) {
   delete unwrap(TM);
 }
 
-// Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis
-// passes for a target to a pass manager. We export that functionality through
-// this function.
-extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM,
-                                          LLVMPassManagerRef PMR,
-                                          LLVMModuleRef M) {
-  PassManagerBase *PM = unwrap(PMR);
-  PM->add(
-      createTargetTransformInfoWrapperPass(unwrap(TM)->getTargetIRAnalysis()));
-}
-
 extern "C" void LLVMRustConfigurePassManagerBuilder(
     LLVMPassManagerBuilderRef PMBR, LLVMRustCodeGenOptLevel OptLevel,
     bool MergeFunctions, bool SLPVectorize, bool LoopVectorize, bool PrepareForThinLTO,
diff --git a/src/test/codegen/function-arguments.rs b/src/test/codegen/function-arguments.rs
index 7e1791cd4f2..5c9aa48c0a5 100644
--- a/src/test/codegen/function-arguments.rs
+++ b/src/test/codegen/function-arguments.rs
@@ -65,7 +65,9 @@ pub fn indirect_struct(_: S) {
 pub fn borrowed_struct(_: &S) {
 }
 
-// CHECK: noalias align 4 dereferenceable(4) i32* @_box(i32* noalias align 4 dereferenceable(4) %x)
+// `Box` can get deallocated during execution of the function, so it should
+// not get `dereferenceable`.
+// CHECK: noalias nonnull align 4 i32* @_box(i32* noalias nonnull align 4 %x)
 #[no_mangle]
 pub fn _box(x: Box<i32>) -> Box<i32> {
   x
diff --git a/src/test/mir-opt/inline-closure-borrows-arg.rs b/src/test/mir-opt/inline-closure-borrows-arg.rs
index b5bfeef5e9c..768f4953228 100644
--- a/src/test/mir-opt/inline-closure-borrows-arg.rs
+++ b/src/test/mir-opt/inline-closure-borrows-arg.rs
@@ -21,8 +21,8 @@ fn foo<T: Copy>(_t: T, q: &i32) -> i32 {
 //     debug _t => _1;
 //     debug q => _2;
 //     let mut _0: i32;
-//     let _3: [closure@HirId { owner: DefIndex(4), local_id: 31 }];
-//     let mut _4: &[closure@HirId { owner: DefIndex(4), local_id: 31 }];
+//     let _3: [closure@foo<T>::{{closure}}#0];
+//     let mut _4: &[closure@foo<T>::{{closure}}#0];
 //     let mut _5: (&i32, &i32);
 //     let mut _6: &i32;
 //     let mut _7: &i32;
@@ -40,7 +40,7 @@ fn foo<T: Copy>(_t: T, q: &i32) -> i32 {
 //     }
 //     bb0: {
 //         ...
-//         _3 = [closure@HirId { owner: DefIndex(4), local_id: 31 }];
+//         _3 = [closure@foo::<T>::{{closure}}#0];
 //         ...
 //         _4 = &_3;
 //         ...
diff --git a/src/test/mir-opt/inline-closure-captures.rs b/src/test/mir-opt/inline-closure-captures.rs
index e73dbe48bd1..e000a418d90 100644
--- a/src/test/mir-opt/inline-closure-captures.rs
+++ b/src/test/mir-opt/inline-closure-captures.rs
@@ -17,10 +17,10 @@ fn foo<T: Copy>(t: T, q: i32) -> (i32, T) {
 //     debug t => _1;
 //     debug q => _2;
 //     let mut _0: (i32, T);
-//     let _3: [closure@HirId { owner: DefIndex(4), local_id: 15 } q:&i32, t:&T];
+//     let _3: [closure@foo<T>::{{closure}}#0 q:&i32, t:&T];
 //     let mut _4: &i32;
 //     let mut _5: &T;
-//     let mut _6: &[closure@HirId { owner: DefIndex(4), local_id: 15 } q:&i32, t:&T];
+//     let mut _6: &[closure@foo<T>::{{closure}}#0 q:&i32, t:&T];
 //     let mut _7: (i32,);
 //     let mut _8: i32;
 //     let mut _11: i32;
@@ -39,7 +39,7 @@ fn foo<T: Copy>(t: T, q: i32) -> (i32, T) {
 //         _4 = &_2;
 //         ...
 //         _5 = &_1;
-//         _3 = [closure@HirId { owner: DefIndex(4), local_id: 15 }] { q: move _4, t: move _5 };
+//         _3 = [closure@foo::<T>::{{closure}}#0] { q: move _4, t: move _5 };
 //         ...
 //         _6 = &_3;
 //         ...
diff --git a/src/test/mir-opt/inline-closure.rs b/src/test/mir-opt/inline-closure.rs
index ddf027f4be3..bd36e77818e 100644
--- a/src/test/mir-opt/inline-closure.rs
+++ b/src/test/mir-opt/inline-closure.rs
@@ -17,8 +17,8 @@ fn foo<T: Copy>(_t: T, q: i32) -> i32 {
 //     debug _t => _1;
 //     debug q => _2;
 //     let mut _0: i32;
-//     let _3: [closure@HirId { owner: DefIndex(4), local_id: 15 }];
-//     let mut _4: &[closure@HirId { owner: DefIndex(4), local_id: 15 }];
+//     let _3: [closure@foo<T>::{{closure}}#0];
+//     let mut _4: &[closure@foo<T>::{{closure}}#0];
 //     let mut _5: (i32, i32);
 //     let mut _6: i32;
 //     let mut _7: i32;
@@ -33,7 +33,7 @@ fn foo<T: Copy>(_t: T, q: i32) -> i32 {
 //     }
 //     bb0: {
 //         ...
-//         _3 = [closure@HirId { owner: DefIndex(4), local_id: 15 }];
+//         _3 = [closure@foo::<T>::{{closure}}#0];
 //         ...
 //         _4 = &_3;
 //         ...
diff --git a/src/test/mir-opt/retag.rs b/src/test/mir-opt/retag.rs
index 96b848eb1d4..32995448a21 100644
--- a/src/test/mir-opt/retag.rs
+++ b/src/test/mir-opt/retag.rs
@@ -100,7 +100,7 @@ fn main() {
 // }
 // END rustc.main.EraseRegions.after.mir
 // START rustc.main-{{closure}}.EraseRegions.after.mir
-// fn main::{{closure}}#0(_1: &[closure@HirId { owner: DefIndex(13), local_id: 72 }], _2: &i32) -> &i32 {
+// fn main::{{closure}}#0(_1: &[closure@main::{{closure}}#0], _2: &i32) -> &i32 {
 //     ...
 //     bb0: {
 //         Retag([fn entry] _1);
diff --git a/src/test/mir-opt/simplify-arm-identity.rs b/src/test/mir-opt/simplify-arm-identity.rs
new file mode 100644
index 00000000000..a8fa64255fb
--- /dev/null
+++ b/src/test/mir-opt/simplify-arm-identity.rs
@@ -0,0 +1,75 @@
+// Checks that `SimplifyArmIdentity` is not applied if enums have incompatible layouts.
+// Regression test for issue #66856.
+//
+// compile-flags: -Zmir-opt-level=2
+
+enum Src {
+    Foo(u8),
+    Bar,
+}
+
+enum Dst {
+    Foo(u8),
+}
+
+fn main() {
+    let e: Src = Src::Foo(0);
+    let _: Dst = match e {
+        Src::Foo(x) => Dst::Foo(x),
+        Src::Bar => Dst::Foo(0),
+    };
+}
+
+// END RUST SOURCE
+// START rustc.main.SimplifyArmIdentity.before.mir
+// fn main() -> () {
+//     ...
+//     bb0: {
+//         StorageLive(_1);
+//         ((_1 as Foo).0: u8) = const 0u8;
+//         discriminant(_1) = 0;
+//         StorageLive(_2);
+//         _3 = discriminant(_1);
+//         switchInt(move _3) -> [0isize: bb3, 1isize: bb1, otherwise: bb2];
+//     }
+//     bb1: {
+//         ((_2 as Foo).0: u8) = const 0u8;
+//         discriminant(_2) = 0;
+//         goto -> bb4;
+//     }
+//     ...
+//     bb3: {
+//         _4 = ((_1 as Foo).0: u8);
+//         ((_2 as Foo).0: u8) = move _4;
+//         discriminant(_2) = 0;
+//         goto -> bb4;
+//     }
+//     ...
+// }
+// END rustc.main.SimplifyArmIdentity.before.mir
+// START rustc.main.SimplifyArmIdentity.after.mir
+// fn main() -> () {
+//     ...
+//     bb0: {
+//         StorageLive(_1);
+//         ((_1 as Foo).0: u8) = const 0u8;
+//         discriminant(_1) = 0;
+//         StorageLive(_2);
+//         _3 = discriminant(_1);
+//         switchInt(move _3) -> [0isize: bb3, 1isize: bb1, otherwise: bb2];
+//     }
+//     bb1: {
+//         ((_2 as Foo).0: u8) = const 0u8;
+//         discriminant(_2) = 0;
+//         goto -> bb4;
+//     }
+//     ...
+//     bb3: {
+//         _4 = ((_1 as Foo).0: u8);
+//         ((_2 as Foo).0: u8) = move _4;
+//         discriminant(_2) = 0;
+//         goto -> bb4;
+//     }
+//     ...
+// }
+// END rustc.main.SimplifyArmIdentity.after.mir
diff --git a/src/test/run-make-fulldeps/glibc-staticlib-args/Makefile b/src/test/run-make-fulldeps/glibc-staticlib-args/Makefile
new file mode 100644
index 00000000000..ad841ec6101
--- /dev/null
+++ b/src/test/run-make-fulldeps/glibc-staticlib-args/Makefile
@@ -0,0 +1,12 @@
+# only-gnu
+# only-linux
+
+-include ../tools.mk
+
+# This ensures that std::env::args works in a library called from C on glibc Linux.
+
+all:
+	$(RUSTC) --crate-type=staticlib library.rs
+	$(CC) program.c $(call STATICLIB,library) $(call OUT_EXE,program) \
+		$(EXTRACFLAGS) $(EXTRACXXFLAGS)
+	$(call RUN,program)
diff --git a/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs b/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs
new file mode 100644
index 00000000000..991981dc096
--- /dev/null
+++ b/src/test/run-make-fulldeps/glibc-staticlib-args/library.rs
@@ -0,0 +1,4 @@
+#[no_mangle]
+pub extern fn args_check() {
+    assert_ne!(std::env::args_os().count(), 0);
+}
diff --git a/src/test/run-make-fulldeps/glibc-staticlib-args/program.c b/src/test/run-make-fulldeps/glibc-staticlib-args/program.c
new file mode 100644
index 00000000000..d704c39d5c4
--- /dev/null
+++ b/src/test/run-make-fulldeps/glibc-staticlib-args/program.c
@@ -0,0 +1,7 @@
+// ignore-license
+void args_check();
+
+int main() {
+    args_check();
+    return 0;
+}
diff --git a/src/test/run-make-fulldeps/issue-19371/foo.rs b/src/test/run-make-fulldeps/issue-19371/foo.rs
index f9ecff2abaa..62a66aefd2d 100644
--- a/src/test/run-make-fulldeps/issue-19371/foo.rs
+++ b/src/test/run-make-fulldeps/issue-19371/foo.rs
@@ -66,6 +66,11 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
 
     interface::run_compiler(config, |compiler| {
         // This runs all the passes prior to linking, too.
-        compiler.link().ok();
+        let linker = compiler.enter(|queries| {
+            queries.linker()
+        });
+        if let Ok(linker) = linker {
+            linker.link();
+        }
     });
 }
diff --git a/src/test/ui-fulldeps/auxiliary/llvm-pass-plugin.rs b/src/test/ui-fulldeps/auxiliary/llvm-pass-plugin.rs
deleted file mode 100644
index 2ff1c2e363d..00000000000
--- a/src/test/ui-fulldeps/auxiliary/llvm-pass-plugin.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-// force-host
-
-#![feature(plugin_registrar)]
-#![feature(rustc_private)]
-
-extern crate rustc;
-extern crate rustc_driver;
-
-use rustc_driver::plugin::Registry;
-
-#[plugin_registrar]
-pub fn plugin_registrar(reg: &mut Registry) {
-    // This pass is built in to LLVM.
-    //
-    // Normally, we would name a pass that was registered through
-    // C++ static object constructors in the same .so file as the
-    // plugin registrar.
-    reg.register_llvm_pass("gvn");
-}
diff --git a/src/test/ui/feature-gates/feature-gate-plugin.rs b/src/test/ui-fulldeps/feature-gate-plugin.rs
index 8904ec0448a..85eaf533643 100644
--- a/src/test/ui/feature-gates/feature-gate-plugin.rs
+++ b/src/test/ui-fulldeps/feature-gate-plugin.rs
@@ -1,6 +1,7 @@
-// Test that `#![plugin(...)]` attribute is gated by `plugin` feature gate
+// aux-build:empty-plugin.rs
+// ignore-stage1
 
-#![plugin(foo)]
+#![plugin(empty_plugin)]
 //~^ ERROR compiler plugins are deprecated
 //~| WARN use of deprecated attribute `plugin`: compiler plugins are deprecated
 
diff --git a/src/test/ui/feature-gates/feature-gate-plugin.stderr b/src/test/ui-fulldeps/feature-gate-plugin.stderr
index f89ddf995c4..c922325c341 100644
--- a/src/test/ui/feature-gates/feature-gate-plugin.stderr
+++ b/src/test/ui-fulldeps/feature-gate-plugin.stderr
@@ -1,17 +1,17 @@
 error[E0658]: compiler plugins are deprecated
-  --> $DIR/feature-gate-plugin.rs:3:1
+  --> $DIR/feature-gate-plugin.rs:4:1
    |
-LL | #![plugin(foo)]
-   | ^^^^^^^^^^^^^^^
+LL | #![plugin(empty_plugin)]
+   | ^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: for more information, see https://github.com/rust-lang/rust/issues/29597
    = help: add `#![feature(plugin)]` to the crate attributes to enable
 
 warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
-  --> $DIR/feature-gate-plugin.rs:3:1
+  --> $DIR/feature-gate-plugin.rs:4:1
    |
-LL | #![plugin(foo)]
-   | ^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
+LL | #![plugin(empty_plugin)]
+   | ^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
    |
    = note: `#[warn(deprecated)]` on by default
 
diff --git a/src/test/ui-fulldeps/lint-plugin-cmdline-load.rs b/src/test/ui-fulldeps/lint-plugin-cmdline-load.rs
index fd681536b5b..0bd95dfbd14 100644
--- a/src/test/ui-fulldeps/lint-plugin-cmdline-load.rs
+++ b/src/test/ui-fulldeps/lint-plugin-cmdline-load.rs
@@ -1,9 +1,9 @@
-// run-pass
+// check-pass
 // aux-build:lint-plugin-test.rs
 // ignore-stage1
-// compile-flags: -Z extra-plugins=lint_plugin_test
+// compile-flags: -Z crate-attr=plugin(lint_plugin_test)
 
-#![allow(dead_code)]
+#![feature(plugin)]
 
 fn lintme() { } //~ WARNING item is named 'lintme'
 
diff --git a/src/test/ui-fulldeps/lint-plugin-cmdline-load.stderr b/src/test/ui-fulldeps/lint-plugin-cmdline-load.stderr
index 5a6b35433ac..1263a0efe62 100644
--- a/src/test/ui-fulldeps/lint-plugin-cmdline-load.stderr
+++ b/src/test/ui-fulldeps/lint-plugin-cmdline-load.stderr
@@ -1,3 +1,11 @@
+warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
+  --> <crate attribute>:1:1
+   |
+LL | plugin(lint_plugin_test)
+   | ^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
+   |
+   = note: `#[warn(deprecated)]` on by default
+
 warning: item is named 'lintme'
   --> $DIR/lint-plugin-cmdline-load.rs:8:1
    |
diff --git a/src/test/ui-fulldeps/llvm-pass-plugin.rs b/src/test/ui-fulldeps/llvm-pass-plugin.rs
deleted file mode 100644
index fa5cbc1e808..00000000000
--- a/src/test/ui-fulldeps/llvm-pass-plugin.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-// run-pass
-// aux-build:llvm-pass-plugin.rs
-// ignore-stage1
-
-#![feature(plugin)]
-#![plugin(llvm_pass_plugin)] //~ WARNING compiler plugins are deprecated
-
-pub fn main() { }
diff --git a/src/test/ui-fulldeps/llvm-pass-plugin.stderr b/src/test/ui-fulldeps/llvm-pass-plugin.stderr
deleted file mode 100644
index 61b53bb2b7c..00000000000
--- a/src/test/ui-fulldeps/llvm-pass-plugin.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
-  --> $DIR/llvm-pass-plugin.rs:6:1
-   |
-LL | #![plugin(llvm_pass_plugin)]
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
-   |
-   = note: `#[warn(deprecated)]` on by default
-
diff --git a/src/test/ui-fulldeps/macro-crate-multi-decorator.rs b/src/test/ui-fulldeps/macro-crate-multi-decorator.rs
index e396cf01615..f21617be5d2 100644
--- a/src/test/ui-fulldeps/macro-crate-multi-decorator.rs
+++ b/src/test/ui-fulldeps/macro-crate-multi-decorator.rs
@@ -1,9 +1,4 @@
-// run-pass
-
-#![allow(plugin_as_library)]
-#![allow(dead_code)]
-#![allow(unused_variables)]
-#![allow(unused_imports)]
+// check-pass
 // aux-build:macro-crate-test.rs
 // ignore-stage1
 
diff --git a/src/test/ui-fulldeps/plugin-args-1.rs b/src/test/ui-fulldeps/plugin-args-1.rs
deleted file mode 100644
index 1865819053e..00000000000
--- a/src/test/ui-fulldeps/plugin-args-1.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-// check-pass
-// aux-build:empty-plugin.rs
-// ignore-stage1
-
-#![feature(plugin)]
-#![plugin(empty_plugin)] //~ WARNING compiler plugins are deprecated
-
-fn main() {}
diff --git a/src/test/ui-fulldeps/plugin-args-1.stderr b/src/test/ui-fulldeps/plugin-args-1.stderr
deleted file mode 100644
index 4e82961acc2..00000000000
--- a/src/test/ui-fulldeps/plugin-args-1.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
-  --> $DIR/plugin-args-1.rs:6:1
-   |
-LL | #![plugin(empty_plugin)]
-   | ^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
-   |
-   = note: `#[warn(deprecated)]` on by default
-
diff --git a/src/test/ui-fulldeps/plugin-args-2.rs b/src/test/ui-fulldeps/plugin-args-2.rs
deleted file mode 100644
index c4bd1916b85..00000000000
--- a/src/test/ui-fulldeps/plugin-args-2.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-// check-pass
-// aux-build:empty-plugin.rs
-// ignore-stage1
-
-#![feature(plugin)]
-#![plugin(empty_plugin())] //~ WARNING compiler plugins are deprecated
-
-fn main() {}
diff --git a/src/test/ui-fulldeps/plugin-args-2.stderr b/src/test/ui-fulldeps/plugin-args-2.stderr
deleted file mode 100644
index 92bd69b0e4b..00000000000
--- a/src/test/ui-fulldeps/plugin-args-2.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
-  --> $DIR/plugin-args-2.rs:6:1
-   |
-LL | #![plugin(empty_plugin())]
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
-   |
-   = note: `#[warn(deprecated)]` on by default
-
diff --git a/src/test/ui-fulldeps/plugin-args-3.rs b/src/test/ui-fulldeps/plugin-args-3.rs
deleted file mode 100644
index c8818cc6c31..00000000000
--- a/src/test/ui-fulldeps/plugin-args-3.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-// check-pass
-// aux-build:empty-plugin.rs
-// ignore-stage1
-
-#![feature(plugin)]
-#![plugin(empty_plugin(hello(there), how(are="you")))] //~ WARNING compiler plugins are deprecated
-
-fn main() {}
diff --git a/src/test/ui-fulldeps/plugin-args-3.stderr b/src/test/ui-fulldeps/plugin-args-3.stderr
deleted file mode 100644
index 278853e0881..00000000000
--- a/src/test/ui-fulldeps/plugin-args-3.stderr
+++ /dev/null
@@ -1,8 +0,0 @@
-warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
-  --> $DIR/plugin-args-3.rs:6:1
-   |
-LL | #![plugin(empty_plugin(hello(there), how(are="you")))]
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
-   |
-   = note: `#[warn(deprecated)]` on by default
-
diff --git a/src/test/ui-fulldeps/plugin-args.rs b/src/test/ui-fulldeps/plugin-args.rs
new file mode 100644
index 00000000000..488f2b775bf
--- /dev/null
+++ b/src/test/ui-fulldeps/plugin-args.rs
@@ -0,0 +1,9 @@
+// aux-build:empty-plugin.rs
+// ignore-stage1
+
+#![feature(plugin)]
+#![plugin(empty_plugin(args))]
+//~^ ERROR malformed `plugin` attribute
+//~| WARNING compiler plugins are deprecated
+
+fn main() {}
diff --git a/src/test/ui-fulldeps/plugin-args.stderr b/src/test/ui-fulldeps/plugin-args.stderr
new file mode 100644
index 00000000000..2b9094c4c44
--- /dev/null
+++ b/src/test/ui-fulldeps/plugin-args.stderr
@@ -0,0 +1,16 @@
+error[E0498]: malformed `plugin` attribute
+  --> $DIR/plugin-args.rs:5:11
+   |
+LL | #![plugin(empty_plugin(args))]
+   |           ^^^^^^^^^^^^^^^^^^ malformed attribute
+
+warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
+  --> $DIR/plugin-args.rs:5:1
+   |
+LL | #![plugin(empty_plugin(args))]
+   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: may be removed in a future compiler version
+   |
+   = note: `#[warn(deprecated)]` on by default
+
+error: aborting due to previous error
+
diff --git a/src/test/ui-fulldeps/plugin-as-extern-crate.rs b/src/test/ui-fulldeps/plugin-as-extern-crate.rs
index fa7826c9df7..f231efc0a9a 100644
--- a/src/test/ui-fulldeps/plugin-as-extern-crate.rs
+++ b/src/test/ui-fulldeps/plugin-as-extern-crate.rs
@@ -1,11 +1,10 @@
+// check-pass
 // aux-build:empty-plugin.rs
 // ignore-cross-compile
 //
 // empty_plugin will not compile on a cross-compiled target because
 // libsyntax is not compiled for it.
 
-#![deny(plugin_as_library)]
+extern crate empty_plugin; // OK, plugin crates are still crates
 
-extern crate empty_plugin; //~ ERROR compiler plugin used as an ordinary library
-
-fn main() { }
+fn main() {}
diff --git a/src/test/ui-fulldeps/plugin-as-extern-crate.stderr b/src/test/ui-fulldeps/plugin-as-extern-crate.stderr
deleted file mode 100644
index d2fbb5d3517..00000000000
--- a/src/test/ui-fulldeps/plugin-as-extern-crate.stderr
+++ /dev/null
@@ -1,14 +0,0 @@
-error: compiler plugin used as an ordinary library
-  --> $DIR/plugin-as-extern-crate.rs:9:1
-   |
-LL | extern crate empty_plugin;
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^
-   |
-note: lint level defined here
-  --> $DIR/plugin-as-extern-crate.rs:7:9
-   |
-LL | #![deny(plugin_as_library)]
-   |         ^^^^^^^^^^^^^^^^^
-
-error: aborting due to previous error
-
diff --git a/src/test/ui/allocator/two-allocators3.stderr b/src/test/ui/allocator/two-allocators3.stderr
index ecffb192e2a..a3079113d01 100644
--- a/src/test/ui/allocator/two-allocators3.stderr
+++ b/src/test/ui/allocator/two-allocators3.stderr
@@ -1,4 +1,4 @@
-error: the `#[global_allocator]` in system_allocator conflicts with this global allocator in: system_allocator2
+error: the `#[global_allocator]` in system_allocator conflicts with global allocator in: system_allocator2
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
index 22610fe54a4..4ae3971e90e 100644
--- a/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
+++ b/src/test/ui/async-await/issues/issue-63388-1.nll.stderr
@@ -12,12 +12,12 @@ error: lifetime may not live long enough
 LL |       async fn do_sth<'a>(
    |                       -- lifetime `'a` defined here
 LL |           &'a self, foo: &dyn Foo
-   |                          - lifetime `'_` defined here
+   |                          - let's call the lifetime of this reference `'1`
 LL |       ) -> &dyn Foo
 LL | /     {
 LL | |         foo
 LL | |     }
-   | |_____^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'_`
+   | |_____^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-completion.rs b/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-completion.rs
new file mode 100644
index 00000000000..ade386a605d
--- /dev/null
+++ b/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-completion.rs
@@ -0,0 +1,46 @@
+// issue 65419 - Attempting to run an async fn after completion mentions generators when it should
+// be talking about `async fn`s instead.
+
+// run-fail
+// error-pattern: thread 'main' panicked at '`async fn` resumed after completion'
+// edition:2018
+// ignore-wasm no panic or subprocess support
+// ignore-emscripten no panic or subprocess support
+
+#![feature(generators, generator_trait)]
+
+async fn foo() {
+}
+
+fn main() {
+    let mut future = Box::pin(foo());
+    executor::block_on(future.as_mut());
+    executor::block_on(future.as_mut());
+}
+
+mod executor {
+    use core::{
+        future::Future,
+        pin::Pin,
+        task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
+    };
+
+    pub fn block_on<F: Future>(mut future: F) -> F::Output {
+        let mut future = unsafe { Pin::new_unchecked(&mut future) };
+
+        static VTABLE: RawWakerVTable = RawWakerVTable::new(
+            |_| unimplemented!("clone"),
+            |_| unimplemented!("wake"),
+            |_| unimplemented!("wake_by_ref"),
+            |_| (),
+        );
+        let waker = unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) };
+        let mut context = Context::from_waker(&waker);
+
+        loop {
+            if let Poll::Ready(val) = future.as_mut().poll(&mut context) {
+                break val;
+            }
+        }
+    }
+}
diff --git a/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-panic.rs b/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-panic.rs
new file mode 100644
index 00000000000..f8caebcb876
--- /dev/null
+++ b/src/test/ui/async-await/issues/issue-65419/issue-65419-async-fn-resume-after-panic.rs
@@ -0,0 +1,52 @@
+// issue 65419 - Attempting to run an async fn after completion mentions generators when it should
+// be talking about `async fn`s instead. Should also test what happens when it panics.
+
+// run-fail
+// error-pattern: thread 'main' panicked at '`async fn` resumed after panicking'
+// edition:2018
+// ignore-wasm no panic or subprocess support
+// ignore-emscripten no panic or subprocess support
+
+#![feature(generators, generator_trait)]
+
+use std::panic;
+
+async fn foo() {
+    panic!();
+}
+
+fn main() {
+    let mut future = Box::pin(foo());
+    panic::catch_unwind(panic::AssertUnwindSafe(|| {
+        executor::block_on(future.as_mut());
+    }));
+
+    executor::block_on(future.as_mut());
+}
+
+mod executor {
+    use core::{
+        future::Future,
+        pin::Pin,
+        task::{Context, Poll, RawWaker, RawWakerVTable, Waker},
+    };
+
+    pub fn block_on<F: Future>(mut future: F) -> F::Output {
+        let mut future = unsafe { Pin::new_unchecked(&mut future) };
+
+        static VTABLE: RawWakerVTable = RawWakerVTable::new(
+            |_| unimplemented!("clone"),
+            |_| unimplemented!("wake"),
+            |_| unimplemented!("wake_by_ref"),
+            |_| (),
+        );
+        let waker = unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) };
+        let mut context = Context::from_waker(&waker);
+
+        loop {
+            if let Poll::Ready(val) = future.as_mut().poll(&mut context) {
+                break val;
+            }
+        }
+    }
+}
diff --git a/src/test/ui/async-await/issues/issue-65419/issue-65419-generator-resume-after-completion.rs b/src/test/ui/async-await/issues/issue-65419/issue-65419-generator-resume-after-completion.rs
new file mode 100644
index 00000000000..23e3483e01c
--- /dev/null
+++ b/src/test/ui/async-await/issues/issue-65419/issue-65419-generator-resume-after-completion.rs
@@ -0,0 +1,25 @@
+// issue 65419 - Attempting to run an `async fn` after completion mentions generators when it should
+// be talking about `async fn`s instead. Regression test added to make sure generators still
+// panic when resumed after completion.
+
+// run-fail
+// error-pattern:generator resumed after completion
+// edition:2018
+// ignore-wasm no panic or subprocess support
+// ignore-emscripten no panic or subprocess support
+
+#![feature(generators, generator_trait)]
+
+use std::{
+    ops::Generator,
+    pin::Pin,
+};
+
+fn main() {
+    let mut g = || {
+        yield;
+    };
+    Pin::new(&mut g).resume(); // Yields once.
+    Pin::new(&mut g).resume(); // Completes here.
+    Pin::new(&mut g).resume(); // Panics here.
+}
diff --git a/src/test/ui/async-await/issues/issue-66695-static-refs.rs b/src/test/ui/async-await/issues/issue-66695-static-refs.rs
new file mode 100644
index 00000000000..f0609713b4d
--- /dev/null
+++ b/src/test/ui/async-await/issues/issue-66695-static-refs.rs
@@ -0,0 +1,24 @@
+// build-pass
+// edition:2018
+
+static A: [i32; 5] = [1, 2, 3, 4, 5];
+
+async fn fun() {
+    let u = A[async { 1 }.await];
+    match A {
+        i if async { true }.await => (),
+        _ => (),
+    }
+}
+
+fn main() {
+    async {
+        let u = A[async { 1 }.await];
+    };
+    async {
+        match A {
+            i if async { true }.await => (),
+            _ => (),
+        }
+    };
+}
diff --git a/src/test/ui/binop/binop-consume-args.stderr b/src/test/ui/binop/binop-consume-args.stderr
index 5751af27fcb..876e984ecb0 100644
--- a/src/test/ui/binop/binop-consume-args.stderr
+++ b/src/test/ui/binop/binop-consume-args.stderr
@@ -2,9 +2,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:7:10
    |
 LL | fn add<A: Add<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs + rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -16,7 +16,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn add<A: Add<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs + rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -27,9 +27,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:13:10
    |
 LL | fn sub<A: Sub<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs - rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -41,7 +41,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn sub<A: Sub<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs - rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -52,9 +52,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:19:10
    |
 LL | fn mul<A: Mul<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs * rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -66,7 +66,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn mul<A: Mul<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs * rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -77,9 +77,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:25:10
    |
 LL | fn div<A: Div<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs / rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -91,7 +91,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn div<A: Div<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs / rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -102,9 +102,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:31:10
    |
 LL | fn rem<A: Rem<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs % rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -116,7 +116,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn rem<A: Rem<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs % rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -127,9 +127,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:37:10
    |
 LL | fn bitand<A: BitAnd<B, Output=()>, B>(lhs: A, rhs: B) {
-   |           -                           --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |           --                          --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |           |
-   |           consider adding a `Copy` constraint to this type argument
+   |           help: consider further restricting this bound: `A: Copy +`
 LL |     lhs & rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -141,7 +141,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn bitand<A: BitAnd<B, Output=()>, B>(lhs: A, rhs: B) {
    |                                    -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                                    |
-   |                                    consider adding a `Copy` constraint to this type argument
+   |                                    help: consider restricting this bound: `B: Copy`
 LL |     lhs & rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -152,9 +152,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:43:10
    |
 LL | fn bitor<A: BitOr<B, Output=()>, B>(lhs: A, rhs: B) {
-   |          -                          --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |          --                         --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |          |
-   |          consider adding a `Copy` constraint to this type argument
+   |          help: consider further restricting this bound: `A: Copy +`
 LL |     lhs | rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -166,7 +166,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn bitor<A: BitOr<B, Output=()>, B>(lhs: A, rhs: B) {
    |                                  -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                                  |
-   |                                  consider adding a `Copy` constraint to this type argument
+   |                                  help: consider restricting this bound: `B: Copy`
 LL |     lhs | rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -177,9 +177,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:49:10
    |
 LL | fn bitxor<A: BitXor<B, Output=()>, B>(lhs: A, rhs: B) {
-   |           -                           --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |           --                          --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |           |
-   |           consider adding a `Copy` constraint to this type argument
+   |           help: consider further restricting this bound: `A: Copy +`
 LL |     lhs ^ rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -191,7 +191,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn bitxor<A: BitXor<B, Output=()>, B>(lhs: A, rhs: B) {
    |                                    -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                                    |
-   |                                    consider adding a `Copy` constraint to this type argument
+   |                                    help: consider restricting this bound: `B: Copy`
 LL |     lhs ^ rhs;
    |           --- value moved here
 LL |     drop(lhs);
@@ -202,9 +202,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:55:10
    |
 LL | fn shl<A: Shl<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs << rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -216,7 +216,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn shl<A: Shl<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs << rhs;
    |            --- value moved here
 LL |     drop(lhs);
@@ -227,9 +227,9 @@ error[E0382]: use of moved value: `lhs`
   --> $DIR/binop-consume-args.rs:61:10
    |
 LL | fn shr<A: Shr<B, Output=()>, B>(lhs: A, rhs: B) {
-   |        -                        --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
+   |        --                       --- move occurs because `lhs` has type `A`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `A: Copy +`
 LL |     lhs >> rhs;
    |     --- value moved here
 LL |     drop(lhs);
@@ -241,7 +241,7 @@ error[E0382]: use of moved value: `rhs`
 LL | fn shr<A: Shr<B, Output=()>, B>(lhs: A, rhs: B) {
    |                              -          --- move occurs because `rhs` has type `B`, which does not implement the `Copy` trait
    |                              |
-   |                              consider adding a `Copy` constraint to this type argument
+   |                              help: consider restricting this bound: `B: Copy`
 LL |     lhs >> rhs;
    |            --- value moved here
 LL |     drop(lhs);
diff --git a/src/test/ui/binop/binop-move-semantics.stderr b/src/test/ui/binop/binop-move-semantics.stderr
index 897607dc2d8..7552dc66974 100644
--- a/src/test/ui/binop/binop-move-semantics.stderr
+++ b/src/test/ui/binop/binop-move-semantics.stderr
@@ -2,9 +2,9 @@ error[E0382]: use of moved value: `x`
   --> $DIR/binop-move-semantics.rs:8:5
    |
 LL | fn double_move<T: Add<Output=()>>(x: T) {
-   |                -                  - move occurs because `x` has type `T`, which does not implement the `Copy` trait
+   |                --                 - move occurs because `x` has type `T`, which does not implement the `Copy` trait
    |                |
-   |                consider adding a `Copy` constraint to this type argument
+   |                help: consider further restricting this bound: `T: Copy +`
 LL |     x
    |     - value moved here
 LL |     +
@@ -15,9 +15,9 @@ error[E0382]: borrow of moved value: `x`
   --> $DIR/binop-move-semantics.rs:14:5
    |
 LL | fn move_then_borrow<T: Add<Output=()> + Clone>(x: T) {
-   |                     -                          - move occurs because `x` has type `T`, which does not implement the `Copy` trait
+   |                     --                         - move occurs because `x` has type `T`, which does not implement the `Copy` trait
    |                     |
-   |                     consider adding a `Copy` constraint to this type argument
+   |                     help: consider further restricting this bound: `T: Copy +`
 LL |     x
    |     - value moved here
 LL |     +
diff --git a/src/test/ui/borrowck/borrowck-unboxed-closures.stderr b/src/test/ui/borrowck/borrowck-unboxed-closures.stderr
index 40b8e313484..5cd0471cd0d 100644
--- a/src/test/ui/borrowck/borrowck-unboxed-closures.stderr
+++ b/src/test/ui/borrowck/borrowck-unboxed-closures.stderr
@@ -20,9 +20,9 @@ error[E0382]: use of moved value: `f`
   --> $DIR/borrowck-unboxed-closures.rs:12:5
    |
 LL | fn c<F:FnOnce(isize, isize) -> isize>(f: F) {
-   |      -                                - move occurs because `f` has type `F`, which does not implement the `Copy` trait
+   |      --                               - move occurs because `f` has type `F`, which does not implement the `Copy` trait
    |      |
-   |      consider adding a `Copy` constraint to this type argument
+   |      help: consider further restricting this bound: `F: Copy +`
 LL |     f(1, 2);
    |     - value moved here
 LL |     f(1, 2);
diff --git a/src/test/ui/consts/const-fn-zst-args.rs b/src/test/ui/consts/const-fn-zst-args.rs
new file mode 100644
index 00000000000..82c27b37573
--- /dev/null
+++ b/src/test/ui/consts/const-fn-zst-args.rs
@@ -0,0 +1,14 @@
+// build-pass
+
+// Check that the evaluation of const-functions with
+// zero-sized types as arguments compiles successfully
+
+struct Zst {}
+
+const fn foo(val: Zst) -> Zst { val }
+
+const FOO: Zst = foo(Zst {});
+
+fn main() {
+    const _: Zst = FOO;
+}
diff --git a/src/test/ui/consts/const-multi-ref.rs b/src/test/ui/consts/const-multi-ref.rs
index 498e99e668b..5e2be0d4f3f 100644
--- a/src/test/ui/consts/const-multi-ref.rs
+++ b/src/test/ui/consts/const-multi-ref.rs
@@ -1,11 +1,24 @@
-const _X: i32 = {
+// Ensure that we point the user to the erroneous borrow but not to any subsequent borrows of that
+// initial one.
+
+const _: i32 = {
     let mut a = 5;
-    let p = &mut a;      //~ ERROR references in constants may only refer to immutable values
+    let p = &mut a; //~ ERROR references in constants may only refer to immutable values
 
-    let reborrow = {p};  //~ ERROR references in constants may only refer to immutable values
+    let reborrow = {p};
     let pp = &reborrow;
     let ppp = &pp;
     ***ppp
 };
 
+const _: std::cell::Cell<i32> = {
+    let mut a = std::cell::Cell::new(5);
+    let p = &a; //~ ERROR cannot borrow a constant which may contain interior mutability
+
+    let reborrow = {p};
+    let pp = &reborrow;
+    let ppp = &pp;
+    a
+};
+
 fn main() {}
diff --git a/src/test/ui/consts/const-multi-ref.stderr b/src/test/ui/consts/const-multi-ref.stderr
index 9e525ef9aac..ed3837e9c9e 100644
--- a/src/test/ui/consts/const-multi-ref.stderr
+++ b/src/test/ui/consts/const-multi-ref.stderr
@@ -1,15 +1,16 @@
 error[E0017]: references in constants may only refer to immutable values
-  --> $DIR/const-multi-ref.rs:3:13
+  --> $DIR/const-multi-ref.rs:6:13
    |
 LL |     let p = &mut a;
    |             ^^^^^^ constants require immutable values
 
-error[E0017]: references in constants may only refer to immutable values
-  --> $DIR/const-multi-ref.rs:5:21
+error[E0492]: cannot borrow a constant which may contain interior mutability, create a static instead
+  --> $DIR/const-multi-ref.rs:16:13
    |
-LL |     let reborrow = {p};
-   |                     ^ constants require immutable values
+LL |     let p = &a;
+   |             ^^
 
 error: aborting due to 2 previous errors
 
-For more information about this error, try `rustc --explain E0017`.
+Some errors have detailed explanations: E0017, E0492.
+For more information about an error, try `rustc --explain E0017`.
diff --git a/src/test/ui/consts/const-size_of-cycle.stderr b/src/test/ui/consts/const-size_of-cycle.stderr
index 5b06ade44c5..db1932a9209 100644
--- a/src/test/ui/consts/const-size_of-cycle.stderr
+++ b/src/test/ui/consts/const-size_of-cycle.stderr
@@ -10,6 +10,11 @@ note: ...which requires const-evaluating + checking `Foo::bytes::{{constant}}#0`
 LL |     bytes: [u8; std::mem::size_of::<Foo>()]
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
 note: ...which requires const-evaluating `Foo::bytes::{{constant}}#0`...
+  --> $DIR/const-size_of-cycle.rs:5:17
+   |
+LL |     bytes: [u8; std::mem::size_of::<Foo>()]
+   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^
+note: ...which requires const-evaluating `std::mem::size_of`...
   --> $SRC_DIR/libcore/mem/mod.rs:LL:COL
    |
 LL |     intrinsics::size_of::<T>()
diff --git a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.rs b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.rs
deleted file mode 100644
index 68a9227dea9..00000000000
--- a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-// ignore-tidy-linelength
-// ignore-compare-mode-nll
-#![feature(const_in_array_repeat_expressions, nll)]
-#![allow(warnings)]
-
-// Some type that is not copyable.
-struct Bar;
-
-const fn type_no_copy() -> Option<Bar> {
-    None
-}
-
-const fn type_copy() -> u32 {
-    3
-}
-
-fn no_copy() {
-    const ARR: [Option<Bar>; 2] = [type_no_copy(); 2];
-    //~^ ERROR the trait bound `std::option::Option<Bar>: std::marker::Copy` is not satisfied [E0277]
-}
-
-fn copy() {
-    const ARR: [u32; 2] = [type_copy(); 2];
-}
-
-fn main() {}
diff --git a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-const.rs b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-const.rs
new file mode 100644
index 00000000000..da1bae1be8d
--- /dev/null
+++ b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-const.rs
@@ -0,0 +1,23 @@
+// run-pass
+
+#![allow(unused)]
+#![feature(const_in_array_repeat_expressions)]
+
+// Some type that is not copyable.
+struct Bar;
+
+const fn type_no_copy() -> Option<Bar> {
+    None
+}
+
+const fn type_copy() -> u32 {
+    3
+}
+
+const _: [u32; 2] = [type_copy(); 2];
+
+// This is allowed because all promotion contexts use the explicit rules for promotability when
+// inside an explicit const context.
+const _: [Option<Bar>; 2] = [type_no_copy(); 2];
+
+fn main() {}
diff --git a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.rs b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.rs
new file mode 100644
index 00000000000..38f744e99aa
--- /dev/null
+++ b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.rs
@@ -0,0 +1,18 @@
+#![feature(const_in_array_repeat_expressions)]
+
+// Some type that is not copyable.
+struct Bar;
+
+const fn no_copy() -> Option<Bar> {
+    None
+}
+
+const fn copy() -> u32 {
+    3
+}
+
+fn main() {
+    let _: [u32; 2] = [copy(); 2];
+    let _: [Option<Bar>; 2] = [no_copy(); 2];
+    //~^ ERROR the trait bound `std::option::Option<Bar>: std::marker::Copy` is not satisfied
+}
diff --git a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.stderr b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.stderr
index 82272af958a..8219d836a20 100644
--- a/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/const-fns.stderr
+++ b/src/test/ui/consts/rfc-2203-const-array-repeat-exprs/fn-call-in-non-const.stderr
@@ -1,8 +1,8 @@
 error[E0277]: the trait bound `std::option::Option<Bar>: std::marker::Copy` is not satisfied
-  --> $DIR/const-fns.rs:18:35
+  --> $DIR/fn-call-in-non-const.rs:16:31
    |
-LL |     const ARR: [Option<Bar>; 2] = [type_no_copy(); 2];
-   |                                   ^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::option::Option<Bar>`
+LL |     let _: [Option<Bar>; 2] = [no_copy(); 2];
+   |                               ^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::option::Option<Bar>`
    |
    = help: the following implementations were found:
              <std::option::Option<T> as std::marker::Copy>
diff --git a/src/test/ui/consts/uninhabited-const-issue-61744.rs b/src/test/ui/consts/uninhabited-const-issue-61744.rs
index 4509ebc6338..e10b38a614a 100644
--- a/src/test/ui/consts/uninhabited-const-issue-61744.rs
+++ b/src/test/ui/consts/uninhabited-const-issue-61744.rs
@@ -1,11 +1,11 @@
 // compile-fail
 
 pub const unsafe fn fake_type<T>() -> T {
-    hint_unreachable() //~ ERROR any use of this value will cause an error
+    hint_unreachable()
 }
 
 pub const unsafe fn hint_unreachable() -> ! {
-    fake_type()
+    fake_type() //~ ERROR cycle detected when const-evaluating `hint_unreachable` [E0391]
 }
 
 trait Const {
@@ -15,5 +15,5 @@ trait Const {
 impl <T> Const for T {}
 
 pub fn main() -> () {
-    dbg!(i32::CONSTANT); //~ ERROR erroneous constant used
+    dbg!(i32::CONSTANT);
 }
diff --git a/src/test/ui/consts/uninhabited-const-issue-61744.stderr b/src/test/ui/consts/uninhabited-const-issue-61744.stderr
index f390676fda6..2a25ecc55e8 100644
--- a/src/test/ui/consts/uninhabited-const-issue-61744.stderr
+++ b/src/test/ui/consts/uninhabited-const-issue-61744.stderr
@@ -1,73 +1,21 @@
-error: any use of this value will cause an error
+error[E0391]: cycle detected when const-evaluating `hint_unreachable`
+  --> $DIR/uninhabited-const-issue-61744.rs:8:5
+   |
+LL |     fake_type()
+   |     ^^^^^^^^^^^
+   |
+note: ...which requires const-evaluating `fake_type`...
   --> $DIR/uninhabited-const-issue-61744.rs:4:5
    |
 LL |     hint_unreachable()
    |     ^^^^^^^^^^^^^^^^^^
-   |     |
-   |     reached the configured maximum number of stack frames
-   |     inside call to `hint_unreachable` at $DIR/uninhabited-const-issue-61744.rs:4:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<!>` at $DIR/uninhabited-const-issue-61744.rs:8:5
-   |     inside call to `fake_type::<i32>` at $DIR/uninhabited-const-issue-61744.rs:12:36
-...
-LL |     const CONSTANT: i32 = unsafe { fake_type() };
-   |     ---------------------------------------------
-   |
-   = note: `#[deny(const_err)]` on by default
-
-error[E0080]: erroneous constant used
-  --> $DIR/uninhabited-const-issue-61744.rs:18:10
+   = note: ...which again requires const-evaluating `hint_unreachable`, completing the cycle
+note: cycle used when const-evaluating `fake_type`
+  --> $DIR/uninhabited-const-issue-61744.rs:4:5
    |
-LL |     dbg!(i32::CONSTANT);
-   |          ^^^^^^^^^^^^^ referenced constant has errors
+LL |     hint_unreachable()
+   |     ^^^^^^^^^^^^^^^^^^
 
-error: aborting due to 2 previous errors
+error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0080`.
+For more information about this error, try `rustc --explain E0391`.
diff --git a/src/test/ui/error-codes/E0017.rs b/src/test/ui/error-codes/E0017.rs
index 94b6587eb81..3bc518c2c2b 100644
--- a/src/test/ui/error-codes/E0017.rs
+++ b/src/test/ui/error-codes/E0017.rs
@@ -1,8 +1,11 @@
 static X: i32 = 1;
 const C: i32 = 2;
+static mut M: i32 = 3;
 
 const CR: &'static mut i32 = &mut C; //~ ERROR E0017
 static STATIC_REF: &'static mut i32 = &mut X; //~ ERROR E0017
+                                              //~| ERROR E0019
                                               //~| ERROR cannot borrow
 static CONST_REF: &'static mut i32 = &mut C; //~ ERROR E0017
+static STATIC_MUT_REF: &'static mut i32 = unsafe { &mut M }; //~ ERROR E0017
 fn main() {}
diff --git a/src/test/ui/error-codes/E0017.stderr b/src/test/ui/error-codes/E0017.stderr
index 47863f02214..8c8660adceb 100644
--- a/src/test/ui/error-codes/E0017.stderr
+++ b/src/test/ui/error-codes/E0017.stderr
@@ -1,28 +1,40 @@
 error[E0017]: references in constants may only refer to immutable values
-  --> $DIR/E0017.rs:4:30
+  --> $DIR/E0017.rs:5:30
    |
 LL | const CR: &'static mut i32 = &mut C;
    |                              ^^^^^^ constants require immutable values
 
+error[E0019]: static contains unimplemented expression type
+  --> $DIR/E0017.rs:6:39
+   |
+LL | static STATIC_REF: &'static mut i32 = &mut X;
+   |                                       ^^^^^^
+
 error[E0017]: references in statics may only refer to immutable values
-  --> $DIR/E0017.rs:5:39
+  --> $DIR/E0017.rs:6:39
    |
 LL | static STATIC_REF: &'static mut i32 = &mut X;
    |                                       ^^^^^^ statics require immutable values
 
 error[E0596]: cannot borrow immutable static item `X` as mutable
-  --> $DIR/E0017.rs:5:39
+  --> $DIR/E0017.rs:6:39
    |
 LL | static STATIC_REF: &'static mut i32 = &mut X;
    |                                       ^^^^^^ cannot borrow as mutable
 
 error[E0017]: references in statics may only refer to immutable values
-  --> $DIR/E0017.rs:7:38
+  --> $DIR/E0017.rs:9:38
    |
 LL | static CONST_REF: &'static mut i32 = &mut C;
    |                                      ^^^^^^ statics require immutable values
 
-error: aborting due to 4 previous errors
+error[E0017]: references in statics may only refer to immutable values
+  --> $DIR/E0017.rs:10:52
+   |
+LL | static STATIC_MUT_REF: &'static mut i32 = unsafe { &mut M };
+   |                                                    ^^^^^^ statics require immutable values
+
+error: aborting due to 6 previous errors
 
-Some errors have detailed explanations: E0017, E0596.
+Some errors have detailed explanations: E0017, E0019, E0596.
 For more information about an error, try `rustc --explain E0017`.
diff --git a/src/test/ui/error-codes/E0388.rs b/src/test/ui/error-codes/E0388.rs
deleted file mode 100644
index 3aa4ac9655c..00000000000
--- a/src/test/ui/error-codes/E0388.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-static X: i32 = 1;
-const C: i32 = 2;
-
-const CR: &'static mut i32 = &mut C; //~ ERROR E0017
-static STATIC_REF: &'static mut i32 = &mut X; //~ ERROR E0017
-                                              //~| ERROR cannot borrow
-static CONST_REF: &'static mut i32 = &mut C; //~ ERROR E0017
-
-fn main() {}
diff --git a/src/test/ui/error-codes/E0388.stderr b/src/test/ui/error-codes/E0388.stderr
deleted file mode 100644
index b52d5260b13..00000000000
--- a/src/test/ui/error-codes/E0388.stderr
+++ /dev/null
@@ -1,28 +0,0 @@
-error[E0017]: references in constants may only refer to immutable values
-  --> $DIR/E0388.rs:4:30
-   |
-LL | const CR: &'static mut i32 = &mut C;
-   |                              ^^^^^^ constants require immutable values
-
-error[E0017]: references in statics may only refer to immutable values
-  --> $DIR/E0388.rs:5:39
-   |
-LL | static STATIC_REF: &'static mut i32 = &mut X;
-   |                                       ^^^^^^ statics require immutable values
-
-error[E0596]: cannot borrow immutable static item `X` as mutable
-  --> $DIR/E0388.rs:5:39
-   |
-LL | static STATIC_REF: &'static mut i32 = &mut X;
-   |                                       ^^^^^^ cannot borrow as mutable
-
-error[E0017]: references in statics may only refer to immutable values
-  --> $DIR/E0388.rs:7:38
-   |
-LL | static CONST_REF: &'static mut i32 = &mut C;
-   |                                      ^^^^^^ statics require immutable values
-
-error: aborting due to 4 previous errors
-
-Some errors have detailed explanations: E0017, E0596.
-For more information about an error, try `rustc --explain E0017`.
diff --git a/src/test/ui/feature-gates/feature-gate-cfg_sanitize.rs b/src/test/ui/feature-gates/feature-gate-cfg_sanitize.rs
new file mode 100644
index 00000000000..c3e7cc9ed8a
--- /dev/null
+++ b/src/test/ui/feature-gates/feature-gate-cfg_sanitize.rs
@@ -0,0 +1,3 @@
+#[cfg(not(sanitize = "thread"))]
+//~^ `cfg(sanitize)` is experimental
+fn main() {}
diff --git a/src/test/ui/feature-gates/feature-gate-cfg_sanitize.stderr b/src/test/ui/feature-gates/feature-gate-cfg_sanitize.stderr
new file mode 100644
index 00000000000..f67a0d83bdd
--- /dev/null
+++ b/src/test/ui/feature-gates/feature-gate-cfg_sanitize.stderr
@@ -0,0 +1,12 @@
+error[E0658]: `cfg(sanitize)` is experimental and subject to change
+  --> $DIR/feature-gate-cfg_sanitize.rs:1:11
+   |
+LL | #[cfg(not(sanitize = "thread"))]
+   |           ^^^^^^^^^^^^^^^^^^^
+   |
+   = note: for more information, see https://github.com/rust-lang/rust/issues/39699
+   = help: add `#![feature(cfg_sanitize)]` to the crate attributes to enable
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0658`.
diff --git a/src/test/ui/fmt/format-string-error.rs b/src/test/ui/fmt/format-string-error.rs
index 691c06a2402..eae4f3cb547 100644
--- a/src/test/ui/fmt/format-string-error.rs
+++ b/src/test/ui/fmt/format-string-error.rs
@@ -6,10 +6,12 @@ fn main() {
     println!("{{}}");
     println!("}");
     //~^ ERROR invalid format string: unmatched `}` found
-    let _ = format!("{_foo}", _foo = 6usize);
-    //~^ ERROR invalid format string: invalid argument name `_foo`
     let _ = format!("{_}", _ = 6usize);
     //~^ ERROR invalid format string: invalid argument name `_`
+    let _ = format!("{a:_}", a = "", _ = 0);
+    //~^ ERROR invalid format string: invalid argument name `_`
+    let _ = format!("{a:._$}", a = "", _ = 0);
+    //~^ ERROR invalid format string: invalid argument name `_`
     let _ = format!("{");
     //~^ ERROR invalid format string: expected `'}'` but string was terminated
     let _ = format!("}");
diff --git a/src/test/ui/fmt/format-string-error.stderr b/src/test/ui/fmt/format-string-error.stderr
index 32119b18774..8b018480fb0 100644
--- a/src/test/ui/fmt/format-string-error.stderr
+++ b/src/test/ui/fmt/format-string-error.stderr
@@ -16,24 +16,32 @@ LL |     println!("}");
    |
    = note: if you intended to print `}`, you can escape it using `}}`
 
-error: invalid format string: invalid argument name `_foo`
+error: invalid format string: invalid argument name `_`
   --> $DIR/format-string-error.rs:9:23
    |
-LL |     let _ = format!("{_foo}", _foo = 6usize);
-   |                       ^^^^ invalid argument name in format string
+LL |     let _ = format!("{_}", _ = 6usize);
+   |                       ^ invalid argument name in format string
    |
-   = note: argument names cannot start with an underscore
+   = note: argument name cannot be a single underscore
 
 error: invalid format string: invalid argument name `_`
-  --> $DIR/format-string-error.rs:11:23
+  --> $DIR/format-string-error.rs:11:25
    |
-LL |     let _ = format!("{_}", _ = 6usize);
-   |                       ^ invalid argument name in format string
+LL |     let _ = format!("{a:_}", a = "", _ = 0);
+   |                         ^ invalid argument name in format string
+   |
+   = note: argument name cannot be a single underscore
+
+error: invalid format string: invalid argument name `_`
+  --> $DIR/format-string-error.rs:13:26
+   |
+LL |     let _ = format!("{a:._$}", a = "", _ = 0);
+   |                          ^ invalid argument name in format string
    |
-   = note: argument names cannot start with an underscore
+   = note: argument name cannot be a single underscore
 
 error: invalid format string: expected `'}'` but string was terminated
-  --> $DIR/format-string-error.rs:13:23
+  --> $DIR/format-string-error.rs:15:23
    |
 LL |     let _ = format!("{");
    |                      -^ expected `'}'` in format string
@@ -43,7 +51,7 @@ LL |     let _ = format!("{");
    = note: if you intended to print `{`, you can escape it using `{{`
 
 error: invalid format string: unmatched `}` found
-  --> $DIR/format-string-error.rs:15:22
+  --> $DIR/format-string-error.rs:17:22
    |
 LL |     let _ = format!("}");
    |                      ^ unmatched `}` in format string
@@ -51,7 +59,7 @@ LL |     let _ = format!("}");
    = note: if you intended to print `}`, you can escape it using `}}`
 
 error: invalid format string: expected `'}'`, found `'\'`
-  --> $DIR/format-string-error.rs:17:23
+  --> $DIR/format-string-error.rs:19:23
    |
 LL |     let _ = format!("{\}");
    |                      -^ expected `}` in format string
@@ -61,7 +69,7 @@ LL |     let _ = format!("{\}");
    = note: if you intended to print `{`, you can escape it using `{{`
 
 error: invalid format string: expected `'}'` but string was terminated
-  --> $DIR/format-string-error.rs:19:35
+  --> $DIR/format-string-error.rs:21:35
    |
 LL |     let _ = format!("\n\n\n{\n\n\n");
    |                            -      ^ expected `'}'` in format string
@@ -71,7 +79,7 @@ LL |     let _ = format!("\n\n\n{\n\n\n");
    = note: if you intended to print `{`, you can escape it using `{{`
 
 error: invalid format string: expected `'}'` but string was terminated
-  --> $DIR/format-string-error.rs:25:3
+  --> $DIR/format-string-error.rs:27:3
    |
 LL |     {"###);
    |     -^ expected `'}'` in format string
@@ -81,7 +89,7 @@ LL |     {"###);
    = note: if you intended to print `{`, you can escape it using `{{`
 
 error: invalid format string: expected `'}'` but string was terminated
-  --> $DIR/format-string-error.rs:33:1
+  --> $DIR/format-string-error.rs:35:1
    |
 LL |     {
    |     - because of this opening brace
@@ -92,7 +100,7 @@ LL | "###);
    = note: if you intended to print `{`, you can escape it using `{{`
 
 error: invalid format string: unmatched `}` found
-  --> $DIR/format-string-error.rs:39:2
+  --> $DIR/format-string-error.rs:41:2
    |
 LL |     }
    |     ^ unmatched `}` in format string
@@ -100,7 +108,7 @@ LL |     }
    = note: if you intended to print `}`, you can escape it using `}}`
 
 error: invalid format string: unmatched `}` found
-  --> $DIR/format-string-error.rs:47:9
+  --> $DIR/format-string-error.rs:49:9
    |
 LL |         }
    |         ^ unmatched `}` in format string
@@ -108,10 +116,10 @@ LL |         }
    = note: if you intended to print `}`, you can escape it using `}}`
 
 error: 3 positional arguments in format string, but there are 2 arguments
-  --> $DIR/format-string-error.rs:51:15
+  --> $DIR/format-string-error.rs:53:15
    |
 LL |     println!("{} {} {}", 1, 2);
    |               ^^ ^^ ^^   -  -
 
-error: aborting due to 13 previous errors
+error: aborting due to 14 previous errors
 
diff --git a/src/test/ui/generator/static-reference-across-yield.rs b/src/test/ui/generator/static-reference-across-yield.rs
new file mode 100644
index 00000000000..23b11593bb5
--- /dev/null
+++ b/src/test/ui/generator/static-reference-across-yield.rs
@@ -0,0 +1,16 @@
+// build-pass
+#![feature(generators)]
+
+static A: [i32; 5] = [1, 2, 3, 4, 5];
+
+fn main() {
+    static || {
+        let u = A[{yield; 1}];
+    };
+    static || {
+        match A {
+            i if { yield; true } => (),
+            _ => (),
+        }
+    };
+}
diff --git a/src/test/ui/hrtb/hrtb-higher-ranker-supertraits-transitive.stderr b/src/test/ui/hrtb/hrtb-higher-ranker-supertraits-transitive.stderr
index afcb467ad47..5c38f47b363 100644
--- a/src/test/ui/hrtb/hrtb-higher-ranker-supertraits-transitive.stderr
+++ b/src/test/ui/hrtb/hrtb-higher-ranker-supertraits-transitive.stderr
@@ -7,7 +7,7 @@ LL |     where B : for<'ccx> Bar<'ccx>
    |               ------------------- required by this bound in `want_bar_for_any_ccx`
 ...
 LL |     where B : Qux
-   |                  - help: consider further restricting type parameter `B`: `, for<'ccx> B: Bar<'ccx>`
+   |                  - help: consider further restricting type parameter `B`: `, B: for<'ccx> Bar<'ccx>`
 ...
 LL |     want_bar_for_any_ccx(b);
    |                          ^ the trait `for<'ccx> Bar<'ccx>` is not implemented for `B`
diff --git a/src/test/ui/hrtb/hrtb-higher-ranker-supertraits.stderr b/src/test/ui/hrtb/hrtb-higher-ranker-supertraits.stderr
index 20913b4f28c..768bc6c7184 100644
--- a/src/test/ui/hrtb/hrtb-higher-ranker-supertraits.stderr
+++ b/src/test/ui/hrtb/hrtb-higher-ranker-supertraits.stderr
@@ -2,7 +2,7 @@ error[E0277]: the trait bound `for<'tcx> F: Foo<'tcx>` is not satisfied
   --> $DIR/hrtb-higher-ranker-supertraits.rs:18:26
    |
 LL |     where F : Foo<'x>
-   |                      - help: consider further restricting type parameter `F`: `, for<'tcx> F: Foo<'tcx>`
+   |                      - help: consider further restricting type parameter `F`: `, F: for<'tcx> Foo<'tcx>`
 ...
 LL |     want_foo_for_any_tcx(f);
    |                          ^ the trait `for<'tcx> Foo<'tcx>` is not implemented for `F`
@@ -16,7 +16,7 @@ error[E0277]: the trait bound `for<'ccx> B: Bar<'ccx>` is not satisfied
   --> $DIR/hrtb-higher-ranker-supertraits.rs:35:26
    |
 LL |     where B : Bar<'x>
-   |                      - help: consider further restricting type parameter `B`: `, for<'ccx> B: Bar<'ccx>`
+   |                      - help: consider further restricting type parameter `B`: `, B: for<'ccx> Bar<'ccx>`
 ...
 LL |     want_bar_for_any_ccx(b);
    |                          ^ the trait `for<'ccx> Bar<'ccx>` is not implemented for `B`
diff --git a/src/test/ui/ifmt.rs b/src/test/ui/ifmt.rs
index 841be20ef86..1a070843cc4 100644
--- a/src/test/ui/ifmt.rs
+++ b/src/test/ui/ifmt.rs
@@ -90,6 +90,7 @@ pub fn main() {
     t!(format!("{foo} {bar}", foo=0, bar=1), "0 1");
     t!(format!("{foo} {1} {bar} {0}", 0, 1, foo=2, bar=3), "2 1 3 0");
     t!(format!("{} {0}", "a"), "a a");
+    t!(format!("{_foo}", _foo = 6usize), "6");
     t!(format!("{foo_bar}", foo_bar=1), "1");
     t!(format!("{}", 5 + 5), "10");
     t!(format!("{:#4}", C), "☃123");
@@ -125,6 +126,7 @@ pub fn main() {
     t!(format!("{:.*}", 4, "aaaaaaaaaaaaaaaaaa"), "aaaa");
     t!(format!("{:.1$}", "aaaaaaaaaaaaaaaaaa", 4), "aaaa");
     t!(format!("{:.a$}", "aaaaaaaaaaaaaaaaaa", a=4), "aaaa");
+    t!(format!("{:._a$}", "aaaaaaaaaaaaaaaaaa", _a=4), "aaaa");
     t!(format!("{:1$}", "a", 4), "a   ");
     t!(format!("{1:0$}", 4, "a"), "a   ");
     t!(format!("{:a$}", "a", a=4), "a   ");
diff --git a/src/test/ui/infinite/infinite-recursion-const-fn.rs b/src/test/ui/infinite/infinite-recursion-const-fn.rs
index 020c417bf61..8289a3db6fc 100644
--- a/src/test/ui/infinite/infinite-recursion-const-fn.rs
+++ b/src/test/ui/infinite/infinite-recursion-const-fn.rs
@@ -1,6 +1,6 @@
 //https://github.com/rust-lang/rust/issues/31364
 
-const fn a() -> usize { b() } //~ ERROR evaluation of constant value failed
+const fn a() -> usize { b() } //~ ERROR cycle detected when const-evaluating `a` [E0391]
 const fn b() -> usize { a() }
 const ARR: [i32; a()] = [5; 6];
 
diff --git a/src/test/ui/infinite/infinite-recursion-const-fn.stderr b/src/test/ui/infinite/infinite-recursion-const-fn.stderr
index 9e0530de425..6bd5e035f57 100644
--- a/src/test/ui/infinite/infinite-recursion-const-fn.stderr
+++ b/src/test/ui/infinite/infinite-recursion-const-fn.stderr
@@ -1,66 +1,21 @@
-error[E0080]: evaluation of constant value failed
+error[E0391]: cycle detected when const-evaluating `a`
   --> $DIR/infinite-recursion-const-fn.rs:3:25
    |
 LL | const fn a() -> usize { b() }
    |                         ^^^
-   |                         |
-   |                         reached the configured maximum number of stack frames
-   |                         inside call to `b` at $DIR/infinite-recursion-const-fn.rs:3:25
+   |
+note: ...which requires const-evaluating `b`...
+  --> $DIR/infinite-recursion-const-fn.rs:4:25
+   |
 LL | const fn b() -> usize { a() }
-   |                         ---
-   |                         |
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
-   |                         inside call to `a` at $DIR/infinite-recursion-const-fn.rs:4:25
+   |                         ^^^
+   = note: ...which again requires const-evaluating `a`, completing the cycle
+note: cycle used when const-evaluating `ARR::{{constant}}#0`
+  --> $DIR/infinite-recursion-const-fn.rs:5:18
+   |
 LL | const ARR: [i32; a()] = [5; 6];
-   |                  --- inside call to `a` at $DIR/infinite-recursion-const-fn.rs:5:18
+   |                  ^^^
 
 error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0080`.
+For more information about this error, try `rustc --explain E0391`.
diff --git a/src/test/ui/invalid_const_promotion.rs b/src/test/ui/invalid_const_promotion.rs
index 6d59bb385dc..91115ef74b8 100644
--- a/src/test/ui/invalid_const_promotion.rs
+++ b/src/test/ui/invalid_const_promotion.rs
@@ -17,12 +17,16 @@ use std::env;
 use std::process::{Command, Stdio};
 
 // this will panic in debug mode and overflow in release mode
+//
+// NB we give bar an unused argument because otherwise memoization
+// of the const fn kicks in, causing a different code path in the
+// compiler to be executed (see PR #66294).
 #[stable(feature = "rustc", since = "1.0.0")]
 #[rustc_promotable]
-const fn bar() -> usize { 0 - 1 }
+const fn bar(_: bool) -> usize { 0 - 1 }
 
 fn foo() {
-    let _: &'static _ = &bar();
+    let _: &'static _ = &bar(true);
 }
 
 #[cfg(unix)]
diff --git a/src/test/ui/issues/issue-27033.stderr b/src/test/ui/issues/issue-27033.stderr
index 2d6d2ef41bd..d3f8407f8e2 100644
--- a/src/test/ui/issues/issue-27033.stderr
+++ b/src/test/ui/issues/issue-27033.stderr
@@ -6,8 +6,8 @@ LL |         None @ _ => {}
    | 
   ::: $SRC_DIR/libstd/prelude/v1.rs:LL:COL
    |
-LL | pub use crate::option::Option::{self, Some, None};
-   |                                             ---- the unit variant `None` is defined here
+LL | pub use crate::option::Option::{self, None, Some};
+   |                                       ---- the unit variant `None` is defined here
 
 error[E0530]: match bindings cannot shadow constants
   --> $DIR/issue-27033.rs:8:9
diff --git a/src/test/ui/issues/issue-34721.fixed b/src/test/ui/issues/issue-34721.fixed
new file mode 100644
index 00000000000..ba2810ee3d7
--- /dev/null
+++ b/src/test/ui/issues/issue-34721.fixed
@@ -0,0 +1,34 @@
+// run-rustfix
+
+pub trait Foo {
+    fn zero(self) -> Self;
+}
+
+impl Foo for u32 {
+    fn zero(self) -> u32 { 0u32 }
+}
+
+pub mod bar {
+    pub use Foo;
+    pub fn bar<T: Foo>(x: T) -> T {
+      x.zero()
+    }
+}
+
+mod baz {
+    use bar;
+    use Foo;
+    pub fn baz<T: Copy +  Foo>(x: T) -> T {
+        if 0 == 1 {
+            bar::bar(x.zero())
+        } else {
+            x.zero()
+        };
+        x.zero()
+        //~^ ERROR use of moved value
+    }
+}
+
+fn main() {
+    let _ = baz::baz(0u32);
+}
diff --git a/src/test/ui/issues/issue-34721.rs b/src/test/ui/issues/issue-34721.rs
index bdc9fe43a8b..14dd01766aa 100644
--- a/src/test/ui/issues/issue-34721.rs
+++ b/src/test/ui/issues/issue-34721.rs
@@ -1,3 +1,5 @@
+// run-rustfix
+
 pub trait Foo {
     fn zero(self) -> Self;
 }
diff --git a/src/test/ui/issues/issue-34721.stderr b/src/test/ui/issues/issue-34721.stderr
index d5cede990a3..3002b07e8c9 100644
--- a/src/test/ui/issues/issue-34721.stderr
+++ b/src/test/ui/issues/issue-34721.stderr
@@ -1,10 +1,10 @@
 error[E0382]: use of moved value: `x`
-  --> $DIR/issue-34721.rs:25:9
+  --> $DIR/issue-34721.rs:27:9
    |
 LL |     pub fn baz<T: Foo>(x: T) -> T {
-   |                -       - move occurs because `x` has type `T`, which does not implement the `Copy` trait
+   |                --      - move occurs because `x` has type `T`, which does not implement the `Copy` trait
    |                |
-   |                consider adding a `Copy` constraint to this type argument
+   |                help: consider further restricting this bound: `T: Copy +`
 LL |         if 0 == 1 {
 LL |             bar::bar(x.zero())
    |                      - value moved here
diff --git a/src/test/ui/issues/issue-4335.rs b/src/test/ui/issues/issue-4335.rs
index a10ae9a1243..c5914a17cf9 100644
--- a/src/test/ui/issues/issue-4335.rs
+++ b/src/test/ui/issues/issue-4335.rs
@@ -4,8 +4,7 @@ fn id<T>(t: T) -> T { t }
 
 fn f<'r, T>(v: &'r T) -> Box<dyn FnMut() -> T + 'r> {
     id(Box::new(|| *v))
-        //~^ ERROR E0373
-        //~| ERROR E0507
+        //~^ ERROR E0507
 }
 
 fn main() {
diff --git a/src/test/ui/issues/issue-4335.stderr b/src/test/ui/issues/issue-4335.stderr
index ca1c0b68d2a..f187969ff4e 100644
--- a/src/test/ui/issues/issue-4335.stderr
+++ b/src/test/ui/issues/issue-4335.stderr
@@ -6,25 +6,6 @@ LL | fn f<'r, T>(v: &'r T) -> Box<dyn FnMut() -> T + 'r> {
 LL |     id(Box::new(|| *v))
    |                    ^^ move occurs because `*v` has type `T`, which does not implement the `Copy` trait
 
-error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
-  --> $DIR/issue-4335.rs:6:17
-   |
-LL |     id(Box::new(|| *v))
-   |                 ^^  - `v` is borrowed here
-   |                 |
-   |                 may outlive borrowed value `v`
-   |
-note: closure is returned here
-  --> $DIR/issue-4335.rs:6:5
-   |
-LL |     id(Box::new(|| *v))
-   |     ^^^^^^^^^^^^^^^^^^^
-help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
-   |
-LL |     id(Box::new(move || *v))
-   |                 ^^^^^^^
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
 
-Some errors have detailed explanations: E0373, E0507.
-For more information about an error, try `rustc --explain E0373`.
+For more information about this error, try `rustc --explain E0507`.
diff --git a/src/test/ui/issues/issue-66851.rs b/src/test/ui/issues/issue-66851.rs
new file mode 100644
index 00000000000..72d62a30a33
--- /dev/null
+++ b/src/test/ui/issues/issue-66851.rs
@@ -0,0 +1,20 @@
+// This used to mis-compile because the mir-opt `SimplifyArmIdentity`
+// did not check that the types matched up in the `Ok(r)` branch.
+//
+// run-pass
+// compile-flags: -Zmir-opt-level=2
+
+#[derive(Debug, PartialEq, Eq)]
+enum SpecialsRes { Res(u64) }
+
+fn e103() -> SpecialsRes {
+    if let Ok(r) = "1".parse() {
+        SpecialsRes::Res(r)
+    } else {
+        SpecialsRes::Res(42)
+    }
+}
+
+fn main() {
+    assert_eq!(e103(), SpecialsRes::Res(1));
+}
diff --git a/src/test/ui/malformed/malformed-plugin-1.stderr b/src/test/ui/malformed/malformed-plugin-1.stderr
index 3860864bd13..2a4f772850e 100644
--- a/src/test/ui/malformed/malformed-plugin-1.stderr
+++ b/src/test/ui/malformed/malformed-plugin-1.stderr
@@ -2,7 +2,7 @@ error: malformed `plugin` attribute input
   --> $DIR/malformed-plugin-1.rs:2:1
    |
 LL | #![plugin]
-   | ^^^^^^^^^^ help: must be of the form: `#[plugin(name|name(args))]`
+   | ^^^^^^^^^^ help: must be of the form: `#[plugin(name)]`
 
 warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
   --> $DIR/malformed-plugin-1.rs:2:1
diff --git a/src/test/ui/malformed/malformed-plugin-2.stderr b/src/test/ui/malformed/malformed-plugin-2.stderr
index e4bca93f13b..fe116a40610 100644
--- a/src/test/ui/malformed/malformed-plugin-2.stderr
+++ b/src/test/ui/malformed/malformed-plugin-2.stderr
@@ -2,7 +2,7 @@ error: malformed `plugin` attribute input
   --> $DIR/malformed-plugin-2.rs:2:1
    |
 LL | #![plugin="bleh"]
-   | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[plugin(name|name(args))]`
+   | ^^^^^^^^^^^^^^^^^ help: must be of the form: `#[plugin(name)]`
 
 warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
   --> $DIR/malformed-plugin-2.rs:2:1
diff --git a/src/test/ui/malformed/malformed-plugin-3.stderr b/src/test/ui/malformed/malformed-plugin-3.stderr
index 7393072cb1c..4af933c15f6 100644
--- a/src/test/ui/malformed/malformed-plugin-3.stderr
+++ b/src/test/ui/malformed/malformed-plugin-3.stderr
@@ -1,8 +1,8 @@
 error[E0498]: malformed `plugin` attribute
-  --> $DIR/malformed-plugin-3.rs:2:1
+  --> $DIR/malformed-plugin-3.rs:2:11
    |
 LL | #![plugin(foo="bleh")]
-   | ^^^^^^^^^^^^^^^^^^^^^^ malformed attribute
+   |           ^^^^^^^^^^ malformed attribute
 
 warning: use of deprecated attribute `plugin`: compiler plugins are deprecated. See https://github.com/rust-lang/rust/pull/64675
   --> $DIR/malformed-plugin-3.rs:2:1
diff --git a/src/test/ui/maybe-bounds-where.stderr b/src/test/ui/maybe-bounds-where.stderr
index 15cbce46f0a..19f9cd28a9a 100644
--- a/src/test/ui/maybe-bounds-where.stderr
+++ b/src/test/ui/maybe-bounds-where.stderr
@@ -42,3 +42,4 @@ LL | struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized;
 
 error: aborting due to 6 previous errors
 
+For more information about this error, try `rustc --explain E0203`.
diff --git a/src/test/ui/moves/moves-based-on-type-no-recursive-stack-closure.stderr b/src/test/ui/moves/moves-based-on-type-no-recursive-stack-closure.stderr
index 483c364752b..ead2cceebf8 100644
--- a/src/test/ui/moves/moves-based-on-type-no-recursive-stack-closure.stderr
+++ b/src/test/ui/moves/moves-based-on-type-no-recursive-stack-closure.stderr
@@ -11,9 +11,9 @@ error[E0382]: borrow of moved value: `f`
   --> $DIR/moves-based-on-type-no-recursive-stack-closure.rs:32:5
    |
 LL | fn conspirator<F>(mut f: F) where F: FnMut(&mut R, bool) {
-   |                -  ----- move occurs because `f` has type `F`, which does not implement the `Copy` trait
-   |                |
-   |                consider adding a `Copy` constraint to this type argument
+   |                   -----                                 - help: consider further restricting type parameter `F`: `, F: Copy`
+   |                   |
+   |                   move occurs because `f` has type `F`, which does not implement the `Copy` trait
 LL |     let mut r = R {c: Box::new(f)};
    |                                - value moved here
 LL |     f(&mut r, false)
diff --git a/src/test/ui/nll/closure-requirements/escape-argument-callee.stderr b/src/test/ui/nll/closure-requirements/escape-argument-callee.stderr
index 1f15ce5c212..abeffee4d3f 100644
--- a/src/test/ui/nll/closure-requirements/escape-argument-callee.stderr
+++ b/src/test/ui/nll/closure-requirements/escape-argument-callee.stderr
@@ -6,7 +6,7 @@ LL |         let mut closure = expect_sig(|p, y| *p = y);
    |
    = note: defining type: DefId(0:4 ~ escape_argument_callee[317d]::test[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) mut &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) i32, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) i32)),
+               for<'r, 's, 't0> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) mut &ReLateBound(DebruijnIndex(0), BrNamed('s)) i32, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) i32)),
            ]
 
 error: lifetime may not live long enough
diff --git a/src/test/ui/nll/closure-requirements/escape-argument.stderr b/src/test/ui/nll/closure-requirements/escape-argument.stderr
index 610a4aed796..f750d15533b 100644
--- a/src/test/ui/nll/closure-requirements/escape-argument.stderr
+++ b/src/test/ui/nll/closure-requirements/escape-argument.stderr
@@ -6,7 +6,7 @@ LL |         let mut closure = expect_sig(|p, y| *p = y);
    |
    = note: defining type: DefId(0:4 ~ escape_argument[317d]::test[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) mut &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) i32, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) i32)),
+               for<'r, 's> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) mut &ReLateBound(DebruijnIndex(0), BrNamed('s)) i32, &ReLateBound(DebruijnIndex(0), BrNamed('s)) i32)),
            ]
 
 note: No external requirements
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr
index 43406c05a25..92f30d400f2 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr
@@ -10,7 +10,7 @@ LL | |         },
    |
    = note: defining type: DefId(0:18 ~ propagate_approximated_fail_no_postdom[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&'_#2r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) &'_#3r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>)),
+               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&'_#2r &ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) &'_#3r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>)),
            ]
    = note: late-bound region is '_#4r
    = note: late-bound region is '_#5r
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-ref.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-ref.stderr
index 6f5b813e85e..00bb66afbe5 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-ref.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-ref.stderr
@@ -11,7 +11,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_approximated_ref[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) &'_#2r u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) u32>)),
+               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) &'_#2r u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) u32>)),
            ]
    = note: late-bound region is '_#3r
    = note: late-bound region is '_#4r
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr
index 5ebc22da036..2b05503b58d 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr
@@ -10,7 +10,7 @@ LL | |     })
    |
    = note: defining type: DefId(0:9 ~ propagate_approximated_shorter_to_static_comparing_against_free[317d]::case1[0]::{{closure}}[0]) with closure substs [
                i32,
-               for<'r> extern "rust-call" fn((std::cell::Cell<&'_#1r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>)),
+               for<'r> extern "rust-call" fn((std::cell::Cell<&'_#1r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>)),
            ]
 
 error[E0521]: borrowed data escapes outside of closure
@@ -48,7 +48,7 @@ LL | |     })
    |
    = note: defining type: DefId(0:11 ~ propagate_approximated_shorter_to_static_comparing_against_free[317d]::case2[0]::{{closure}}[0]) with closure substs [
                i32,
-               for<'r> extern "rust-call" fn((std::cell::Cell<&'_#1r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>)),
+               for<'r> extern "rust-call" fn((std::cell::Cell<&'_#1r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>)),
            ]
    = note: number of external vids: 2
    = note: where '_#1r: '_#0r
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr
index 5ebf8e248b3..ee0f0b7e65d 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr
@@ -12,7 +12,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_approximated_shorter_to_static_no_bound[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0, 't1, 't2> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't2)) u32>)),
+               for<'r, 's, 't0, 't1, 't2> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t1)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t2)) u32>)),
            ]
    = note: late-bound region is '_#2r
    = note: late-bound region is '_#3r
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr
index 91caa42c9bf..611a129e00c 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr
@@ -12,7 +12,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_approximated_shorter_to_static_wrong_bound[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) std::cell::Cell<&'_#2r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) u32>)),
+               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) std::cell::Cell<&'_#2r &ReLateBound(DebruijnIndex(0), BrNamed('t1)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) u32>)),
            ]
    = note: late-bound region is '_#3r
    = note: late-bound region is '_#4r
diff --git a/src/test/ui/nll/closure-requirements/propagate-approximated-val.stderr b/src/test/ui/nll/closure-requirements/propagate-approximated-val.stderr
index 243c8b12ecb..9328d05518c 100644
--- a/src/test/ui/nll/closure-requirements/propagate-approximated-val.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-approximated-val.stderr
@@ -11,7 +11,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_approximated_val[317d]::test[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) &'_#2r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>)),
+               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) &'_#2r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>)),
            ]
    = note: late-bound region is '_#3r
    = note: late-bound region is '_#4r
diff --git a/src/test/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr b/src/test/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr
index c5468e73cfa..afac5267c48 100644
--- a/src/test/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr
@@ -10,7 +10,7 @@ LL | |         },
    |
    = note: defining type: DefId(0:14 ~ propagate_despite_same_free_region[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) &'_#2r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>)),
+               for<'r, 's> extern "rust-call" fn((std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) &'_#2r u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('r)) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>)),
            ]
    = note: late-bound region is '_#3r
    = note: number of external vids: 4
diff --git a/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr b/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr
index bf43c893865..9699e8fbdf8 100644
--- a/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr
@@ -11,7 +11,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_fail_to_approximate_longer_no_bounds[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0, 't1, 't2> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) &'_#1r u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>)),
+               for<'r, 's, 't0, 't1, 't2> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) &'_#1r u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>)),
            ]
    = note: late-bound region is '_#2r
    = note: late-bound region is '_#3r
diff --git a/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr b/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr
index 569bae999dd..2a18079cdc3 100644
--- a/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr
+++ b/src/test/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr
@@ -11,7 +11,7 @@ LL | |     });
    |
    = note: defining type: DefId(0:16 ~ propagate_fail_to_approximate_longer_wrong_bounds[317d]::supply[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) &'_#1r u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) &'_#2r u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 't1)) u32>)),
+               for<'r, 's, 't0, 't1, 't2, 't3> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) &'_#1r u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t0)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) &'_#2r u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t2)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('s)) u32>, &ReLateBound(DebruijnIndex(0), BrNamed('t3)) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BrNamed('t1)) u32>)),
            ]
    = note: late-bound region is '_#3r
    = note: late-bound region is '_#4r
diff --git a/src/test/ui/nll/closure-requirements/return-wrong-bound-region.stderr b/src/test/ui/nll/closure-requirements/return-wrong-bound-region.stderr
index 00c56a796d1..8ce0b7758b0 100644
--- a/src/test/ui/nll/closure-requirements/return-wrong-bound-region.stderr
+++ b/src/test/ui/nll/closure-requirements/return-wrong-bound-region.stderr
@@ -6,7 +6,7 @@ LL |     expect_sig(|a, b| b); // ought to return `a`
    |
    = note: defining type: DefId(0:4 ~ return_wrong_bound_region[317d]::test[0]::{{closure}}[0]) with closure substs [
                i16,
-               for<'r, 's> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) i32, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) i32)) -> &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) i32,
+               for<'r, 's> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BrNamed('r)) i32, &ReLateBound(DebruijnIndex(0), BrNamed('s)) i32)) -> &ReLateBound(DebruijnIndex(0), BrNamed('r)) i32,
            ]
 
 error: lifetime may not live long enough
diff --git a/src/test/ui/nll/ty-outlives/projection-one-region-closure.stderr b/src/test/ui/nll/ty-outlives/projection-one-region-closure.stderr
index d33f6722298..d9cbc71f954 100644
--- a/src/test/ui/nll/ty-outlives/projection-one-region-closure.stderr
+++ b/src/test/ui/nll/ty-outlives/projection-one-region-closure.stderr
@@ -38,7 +38,7 @@ error[E0309]: the parameter type `T` may not live long enough
 LL |     with_signature(cell, t, |cell, t| require(cell, t));
    |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
-   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:15 ~ projection_one_region_closure[317d]::no_relationships_late[0]), BrNamed(crate0:DefIndex(16), 'a))`...
+   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:15 ~ projection_one_region_closure[317d]::no_relationships_late[0]), BrNamed(DefId(0:16 ~ projection_one_region_closure[317d]::no_relationships_late[0]::'a[0]), 'a))`...
 
 error: lifetime may not live long enough
   --> $DIR/projection-one-region-closure.rs:45:39
diff --git a/src/test/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr b/src/test/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr
index ed548a3b4e2..ed53ce91133 100644
--- a/src/test/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr
+++ b/src/test/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr
@@ -39,7 +39,7 @@ error[E0309]: the associated type `<T as Anything<'_#5r, '_#6r>>::AssocType` may
 LL |     with_signature(cell, t, |cell, t| require(cell, t));
    |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
-   = help: consider adding an explicit lifetime bound `<T as Anything<'_#5r, '_#6r>>::AssocType: ReFree(DefId(0:17 ~ projection_two_region_trait_bound_closure[317d]::no_relationships_late[0]), BrNamed(crate0:DefIndex(18), 'a))`...
+   = help: consider adding an explicit lifetime bound `<T as Anything<'_#5r, '_#6r>>::AssocType: ReFree(DefId(0:17 ~ projection_two_region_trait_bound_closure[317d]::no_relationships_late[0]), BrNamed(DefId(0:18 ~ projection_two_region_trait_bound_closure[317d]::no_relationships_late[0]::'a[0]), 'a))`...
 
 note: External requirements
   --> $DIR/projection-two-region-trait-bound-closure.rs:48:29
diff --git a/src/test/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr b/src/test/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr
index fd8d8917c18..e2a9bd7e3cd 100644
--- a/src/test/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr
+++ b/src/test/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr
@@ -7,7 +7,7 @@ LL |     twice(cell, value, |a, b| invoke(a, b));
    = note: defining type: DefId(0:11 ~ ty_param_closure_approximate_lower_bound[317d]::generic[0]::{{closure}}[0]) with closure substs [
                T,
                i16,
-               for<'r, 's> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) ()>>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) T)),
+               for<'r, 's> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('r)) ()>>, &ReLateBound(DebruijnIndex(0), BrNamed('s)) T)),
            ]
    = note: number of external vids: 2
    = note: where T: '_#1r
@@ -34,7 +34,7 @@ LL |     twice(cell, value, |a, b| invoke(a, b));
    = note: defining type: DefId(0:15 ~ ty_param_closure_approximate_lower_bound[317d]::generic_fail[0]::{{closure}}[0]) with closure substs [
                T,
                i16,
-               for<'r, 's> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 'r)) ()>>, &ReLateBound(DebruijnIndex(0), BrNamed(crate0:DefIndex(0), 's)) T)),
+               for<'r, 's> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'_#1r &ReLateBound(DebruijnIndex(0), BrNamed('r)) ()>>, &ReLateBound(DebruijnIndex(0), BrNamed('s)) T)),
            ]
    = note: late-bound region is '_#2r
    = note: number of external vids: 3
@@ -59,7 +59,7 @@ error[E0309]: the parameter type `T` may not live long enough
 LL |     twice(cell, value, |a, b| invoke(a, b));
    |                        ^^^^^^^^^^^^^^^^^^^
    |
-   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:12 ~ ty_param_closure_approximate_lower_bound[317d]::generic_fail[0]), BrNamed(crate0:DefIndex(13), 'a))`...
+   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:12 ~ ty_param_closure_approximate_lower_bound[317d]::generic_fail[0]), BrNamed(DefId(0:13 ~ ty_param_closure_approximate_lower_bound[317d]::generic_fail[0]::'a[0]), 'a))`...
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr b/src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr
index 97b84d1bdf8..ffd936b58be 100644
--- a/src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr
+++ b/src/test/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr
@@ -49,7 +49,7 @@ LL | |         require(&x, &y)
 LL | |     })
    | |_____^
    |
-   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:11 ~ ty_param_closure_outlives_from_where_clause[317d]::no_region[0]), BrNamed(crate0:DefIndex(12), 'a))`...
+   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:11 ~ ty_param_closure_outlives_from_where_clause[317d]::no_region[0]), BrNamed(DefId(0:12 ~ ty_param_closure_outlives_from_where_clause[317d]::no_region[0]::'a[0]), 'a))`...
 
 note: External requirements
   --> $DIR/ty-param-closure-outlives-from-where-clause.rs:43:26
@@ -139,7 +139,7 @@ LL | |         require(&x, &y)
 LL | |     })
    | |_____^
    |
-   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:19 ~ ty_param_closure_outlives_from_where_clause[317d]::wrong_region[0]), BrNamed(crate0:DefIndex(20), 'a))`...
+   = help: consider adding an explicit lifetime bound `T: ReFree(DefId(0:19 ~ ty_param_closure_outlives_from_where_clause[317d]::wrong_region[0]), BrNamed(DefId(0:20 ~ ty_param_closure_outlives_from_where_clause[317d]::wrong_region[0]::'a[0]), 'a))`...
 
 note: External requirements
   --> $DIR/ty-param-closure-outlives-from-where-clause.rs:77:26
diff --git a/src/test/ui/once-cant-call-twice-on-heap.stderr b/src/test/ui/once-cant-call-twice-on-heap.stderr
index f98d3d83845..fd998060218 100644
--- a/src/test/ui/once-cant-call-twice-on-heap.stderr
+++ b/src/test/ui/once-cant-call-twice-on-heap.stderr
@@ -2,9 +2,9 @@ error[E0382]: use of moved value: `blk`
   --> $DIR/once-cant-call-twice-on-heap.rs:9:5
    |
 LL | fn foo<F:FnOnce()>(blk: F) {
-   |        -           --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
+   |        --          --- move occurs because `blk` has type `F`, which does not implement the `Copy` trait
    |        |
-   |        consider adding a `Copy` constraint to this type argument
+   |        help: consider further restricting this bound: `F: Copy +`
 LL |     blk();
    |     --- value moved here
 LL |     blk();
diff --git a/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.rs b/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.rs
new file mode 100644
index 00000000000..d7c191bb5a2
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.rs
@@ -0,0 +1,26 @@
+#![feature(or_patterns)]
+#![feature(slice_patterns)]
+#![allow(incomplete_features)]
+#![deny(unreachable_patterns)]
+
+// We wrap patterns in a tuple because top-level or-patterns are special-cased for now.
+fn main() {
+    // Get the fatal error out of the way
+    match (0u8,) {
+        (0 | _,) => {}
+        //~^ ERROR or-patterns are not fully implemented yet
+    }
+
+    match (0u8, 0u8) {
+        //~^ ERROR non-exhaustive patterns: `(2u8..=std::u8::MAX, _)`
+        (0 | 1, 2 | 3) => {}
+    }
+    match ((0u8,),) {
+        //~^ ERROR non-exhaustive patterns: `((4u8..=std::u8::MAX))`
+        ((0 | 1,) | (2 | 3,),) => {},
+    }
+    match (Some(0u8),) {
+        //~^ ERROR non-exhaustive patterns: `(Some(2u8..=std::u8::MAX))`
+        (None | Some(0 | 1),) => {}
+    }
+}
diff --git a/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.stderr b/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.stderr
new file mode 100644
index 00000000000..e6aa157d278
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-non-exhaustive.stderr
@@ -0,0 +1,33 @@
+error[E0004]: non-exhaustive patterns: `(2u8..=std::u8::MAX, _)` not covered
+  --> $DIR/exhaustiveness-non-exhaustive.rs:14:11
+   |
+LL |     match (0u8, 0u8) {
+   |           ^^^^^^^^^^ pattern `(2u8..=std::u8::MAX, _)` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error[E0004]: non-exhaustive patterns: `((4u8..=std::u8::MAX))` not covered
+  --> $DIR/exhaustiveness-non-exhaustive.rs:18:11
+   |
+LL |     match ((0u8,),) {
+   |           ^^^^^^^^^ pattern `((4u8..=std::u8::MAX))` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error[E0004]: non-exhaustive patterns: `(Some(2u8..=std::u8::MAX))` not covered
+  --> $DIR/exhaustiveness-non-exhaustive.rs:22:11
+   |
+LL |     match (Some(0u8),) {
+   |           ^^^^^^^^^^^^ pattern `(Some(2u8..=std::u8::MAX))` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error: or-patterns are not fully implemented yet
+  --> $DIR/exhaustiveness-non-exhaustive.rs:10:10
+   |
+LL |         (0 | _,) => {}
+   |          ^^^^^
+
+error: aborting due to 4 previous errors
+
+For more information about this error, try `rustc --explain E0004`.
diff --git a/src/test/ui/or-patterns/exhaustiveness-pass.rs b/src/test/ui/or-patterns/exhaustiveness-pass.rs
new file mode 100644
index 00000000000..62a851719f9
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-pass.rs
@@ -0,0 +1,40 @@
+#![feature(or_patterns)]
+#![feature(slice_patterns)]
+#![allow(incomplete_features)]
+#![deny(unreachable_patterns)]
+
+// We wrap patterns in a tuple because top-level or-patterns are special-cased for now.
+fn main() {
+    // Get the fatal error out of the way
+    match (0u8,) {
+        (0 | _,) => {}
+        //~^ ERROR or-patterns are not fully implemented yet
+    }
+
+    match (0u8,) {
+        (1 | 2,) => {}
+        _ => {}
+    }
+
+    match (0u8,) {
+        (1 | 1,) => {} // FIXME(or_patterns): redundancy not detected for now.
+        _ => {}
+    }
+    match (0u8, 0u8) {
+        (1 | 2, 3 | 4) => {}
+        (1, 2) => {}
+        (2, 1) => {}
+        _ => {}
+    }
+    match (Some(0u8),) {
+        (None | Some(0 | 1),) => {}
+        (Some(2..=255),) => {}
+    }
+    match ((0u8,),) {
+        ((0 | 1,) | (2 | 3,),) => {},
+        ((_,),) => {},
+    }
+    match (&[0u8][..],) {
+        ([] | [0 | 1..=255] | [_, ..],) => {},
+    }
+}
diff --git a/src/test/ui/or-patterns/exhaustiveness-pass.stderr b/src/test/ui/or-patterns/exhaustiveness-pass.stderr
new file mode 100644
index 00000000000..1f4278c4b80
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-pass.stderr
@@ -0,0 +1,8 @@
+error: or-patterns are not fully implemented yet
+  --> $DIR/exhaustiveness-pass.rs:10:10
+   |
+LL |         (0 | _,) => {}
+   |          ^^^^^
+
+error: aborting due to previous error
+
diff --git a/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.rs b/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.rs
new file mode 100644
index 00000000000..2cd8ca2dbac
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.rs
@@ -0,0 +1,51 @@
+#![feature(or_patterns)]
+#![feature(slice_patterns)]
+#![allow(incomplete_features)]
+#![deny(unreachable_patterns)]
+
+// We wrap patterns in a tuple because top-level or-patterns are special-cased for now.
+fn main() {
+    // Get the fatal error out of the way
+    match (0u8,) {
+        (0 | _,) => {}
+        //~^ ERROR or-patterns are not fully implemented yet
+    }
+
+    match (0u8,) {
+        (1 | 2,) => {}
+        (1,) => {} //~ ERROR unreachable pattern
+        _ => {}
+    }
+    match (0u8,) {
+        (1 | 2,) => {}
+        (2,) => {} //~ ERROR unreachable pattern
+        _ => {}
+    }
+    match (0u8,) {
+        (1,) => {}
+        (2,) => {}
+        (1 | 2,) => {} //~ ERROR unreachable pattern
+        _ => {}
+    }
+    match (0u8, 0u8) {
+        (1 | 2, 3 | 4) => {}
+        (1, 3) => {} //~ ERROR unreachable pattern
+        (1, 4) => {} //~ ERROR unreachable pattern
+        (2, 4) => {} //~ ERROR unreachable pattern
+        (2 | 1, 4) => {} //~ ERROR unreachable pattern
+        (1, 5 | 6) => {}
+        (1, 4 | 5) => {} //~ ERROR unreachable pattern
+        _ => {}
+    }
+    match (Some(0u8),) {
+        (None | Some(1 | 2),) => {}
+        (Some(1),) => {} //~ ERROR unreachable pattern
+        (None,) => {} //~ ERROR unreachable pattern
+        _ => {}
+    }
+    match ((0u8,),) {
+        ((1 | 2,) | (3 | 4,),) => {},
+        ((1..=4,),) => {}, //~ ERROR unreachable pattern
+        _ => {},
+    }
+}
diff --git a/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.stderr b/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.stderr
new file mode 100644
index 00000000000..a4d55d805c3
--- /dev/null
+++ b/src/test/ui/or-patterns/exhaustiveness-unreachable-pattern.stderr
@@ -0,0 +1,80 @@
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:16:9
+   |
+LL |         (1,) => {}
+   |         ^^^^
+   |
+note: lint level defined here
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:4:9
+   |
+LL | #![deny(unreachable_patterns)]
+   |         ^^^^^^^^^^^^^^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:21:9
+   |
+LL |         (2,) => {}
+   |         ^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:27:9
+   |
+LL |         (1 | 2,) => {}
+   |         ^^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:32:9
+   |
+LL |         (1, 3) => {}
+   |         ^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:33:9
+   |
+LL |         (1, 4) => {}
+   |         ^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:34:9
+   |
+LL |         (2, 4) => {}
+   |         ^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:35:9
+   |
+LL |         (2 | 1, 4) => {}
+   |         ^^^^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:37:9
+   |
+LL |         (1, 4 | 5) => {}
+   |         ^^^^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:42:9
+   |
+LL |         (Some(1),) => {}
+   |         ^^^^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:43:9
+   |
+LL |         (None,) => {}
+   |         ^^^^^^^
+
+error: unreachable pattern
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:48:9
+   |
+LL |         ((1..=4,),) => {},
+   |         ^^^^^^^^^^^
+
+error: or-patterns are not fully implemented yet
+  --> $DIR/exhaustiveness-unreachable-pattern.rs:10:10
+   |
+LL |         (0 | _,) => {}
+   |          ^^^^^
+
+error: aborting due to 12 previous errors
+
diff --git a/src/test/ui/pattern/usefulness/65413-constants-and-slices-exhaustiveness.rs b/src/test/ui/pattern/usefulness/65413-constants-and-slices-exhaustiveness.rs
new file mode 100644
index 00000000000..6c54c938bf1
--- /dev/null
+++ b/src/test/ui/pattern/usefulness/65413-constants-and-slices-exhaustiveness.rs
@@ -0,0 +1,15 @@
+// check-pass
+#![feature(slice_patterns)]
+#![deny(unreachable_patterns)]
+
+const C0: &'static [u8] = b"\x00";
+
+fn main() {
+    let x: &[u8] = &[0];
+    match x {
+        &[] => {}
+        &[1..=255] => {}
+        C0 => {}
+        &[_, _, ..] => {}
+    }
+}
diff --git a/src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr b/src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr
index 63ed49094fc..539aa854f9e 100644
--- a/src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr
+++ b/src/test/ui/pattern/usefulness/match-byte-array-patterns-2.stderr
@@ -1,16 +1,16 @@
-error[E0004]: non-exhaustive patterns: `&[..]` not covered
+error[E0004]: non-exhaustive patterns: `&[0u8..=64u8, _, _, _]` and `&[66u8..=std::u8::MAX, _, _, _]` not covered
   --> $DIR/match-byte-array-patterns-2.rs:4:11
    |
 LL |     match buf {
-   |           ^^^ pattern `&[..]` not covered
+   |           ^^^ patterns `&[0u8..=64u8, _, _, _]` and `&[66u8..=std::u8::MAX, _, _, _]` not covered
    |
    = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
 
-error[E0004]: non-exhaustive patterns: `&[..]` not covered
+error[E0004]: non-exhaustive patterns: `&[]`, `&[_]`, `&[_, _]` and 2 more not covered
   --> $DIR/match-byte-array-patterns-2.rs:10:11
    |
 LL |     match buf {
-   |           ^^^ pattern `&[..]` not covered
+   |           ^^^ patterns `&[]`, `&[_]`, `&[_, _]` and 2 more not covered
    |
    = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
 
diff --git a/src/test/ui/pattern/usefulness/slice-pattern-const.rs b/src/test/ui/pattern/usefulness/slice-pattern-const.rs
index f0a04513f91..89195d5b11e 100644
--- a/src/test/ui/pattern/usefulness/slice-pattern-const.rs
+++ b/src/test/ui/pattern/usefulness/slice-pattern-const.rs
@@ -44,4 +44,11 @@ fn main() {
         b"" => (), //~ ERROR unreachable pattern
         _ => (), //~ ERROR unreachable pattern
     }
+
+    const CONST1: &[bool; 1] = &[true];
+    match &[false] {
+        CONST1 => {}
+        [true] => {} //~ ERROR unreachable pattern
+        [false] => {}
+    }
 }
diff --git a/src/test/ui/pattern/usefulness/slice-pattern-const.stderr b/src/test/ui/pattern/usefulness/slice-pattern-const.stderr
index 2dd10a0478a..d274d6d7c67 100644
--- a/src/test/ui/pattern/usefulness/slice-pattern-const.stderr
+++ b/src/test/ui/pattern/usefulness/slice-pattern-const.stderr
@@ -52,5 +52,11 @@ error: unreachable pattern
 LL |         _ => (),
    |         ^
 
-error: aborting due to 8 previous errors
+error: unreachable pattern
+  --> $DIR/slice-pattern-const.rs:51:9
+   |
+LL |         [true] => {}
+   |         ^^^^^^
+
+error: aborting due to 9 previous errors
 
diff --git a/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs b/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs
index eb3dfac950f..41ba2cc4501 100644
--- a/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs
+++ b/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.rs
@@ -82,4 +82,26 @@ fn main() {
         [_, _] => {}
         [false, .., false] => {}
     }
+
+    const CONST: &[bool] = &[true];
+    match s {
+    //~^ ERROR `&[..]` not covered
+        CONST => {}
+    }
+    match s {
+    //~^ ERROR `&[true]` not covered
+        [] => {},
+        [false] => {},
+        CONST => {},
+        [_, _, ..] => {}
+    }
+    const CONST1: &[bool; 1] = &[true];
+    match s1 {
+    //~^ ERROR `&[false]` not covered
+        CONST1 => {}
+    }
+    match s1 {
+        CONST1 => {}
+        [false] => {}
+    }
 }
diff --git a/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr b/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr
index ebadedccfea..8cb342f33df 100644
--- a/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr
+++ b/src/test/ui/pattern/usefulness/slice-patterns-exhaustiveness.stderr
@@ -102,6 +102,30 @@ LL |     match s {
    |
    = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
 
-error: aborting due to 13 previous errors
+error[E0004]: non-exhaustive patterns: `&[..]` not covered
+  --> $DIR/slice-patterns-exhaustiveness.rs:87:11
+   |
+LL |     match s {
+   |           ^ pattern `&[..]` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error[E0004]: non-exhaustive patterns: `&[true]` not covered
+  --> $DIR/slice-patterns-exhaustiveness.rs:91:11
+   |
+LL |     match s {
+   |           ^ pattern `&[true]` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error[E0004]: non-exhaustive patterns: `&[false]` not covered
+  --> $DIR/slice-patterns-exhaustiveness.rs:99:11
+   |
+LL |     match s1 {
+   |           ^^ pattern `&[false]` not covered
+   |
+   = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
+
+error: aborting due to 16 previous errors
 
 For more information about this error, try `rustc --explain E0004`.
diff --git a/src/test/ui/pattern/usefulness/slice-patterns-reachability.rs b/src/test/ui/pattern/usefulness/slice-patterns-reachability.rs
index 35d9dc91aee..cd229a0fcbe 100644
--- a/src/test/ui/pattern/usefulness/slice-patterns-reachability.rs
+++ b/src/test/ui/pattern/usefulness/slice-patterns-reachability.rs
@@ -2,7 +2,7 @@
 #![deny(unreachable_patterns)]
 
 fn main() {
-    let s: &[bool] = &[true; 0];
+    let s: &[bool] = &[];
 
     match s {
         [true, ..] => {}
diff --git a/src/test/ui/regions/regions-addr-of-upvar-self.stderr b/src/test/ui/regions/regions-addr-of-upvar-self.stderr
index 7a051b8ac83..005800d50a4 100644
--- a/src/test/ui/regions/regions-addr-of-upvar-self.stderr
+++ b/src/test/ui/regions/regions-addr-of-upvar-self.stderr
@@ -9,7 +9,7 @@ note: first, the lifetime cannot outlive the lifetime `'_` as defined on the bod
    |
 LL |         let _f = || {
    |                  ^^
-note: ...so that reference does not outlive borrowed content
+note: ...so that closure can access `self`
   --> $DIR/regions-addr-of-upvar-self.rs:10:41
    |
 LL |             let p: &'static mut usize = &mut self.food;
diff --git a/src/test/ui/sanitize-cfg.rs b/src/test/ui/sanitize-cfg.rs
new file mode 100644
index 00000000000..9c198543a86
--- /dev/null
+++ b/src/test/ui/sanitize-cfg.rs
@@ -0,0 +1,26 @@
+// Verifies that when compiling with -Zsanitizer=option,
+// the `#[cfg(sanitize = "option")]` attribute is configured.
+
+// needs-sanitizer-support
+// only-linux
+// only-x86_64
+// check-pass
+// revisions: address leak memory thread
+//[address]compile-flags: -Zsanitizer=address --cfg address
+//[leak]compile-flags:    -Zsanitizer=leak    --cfg leak
+//[memory]compile-flags:  -Zsanitizer=memory  --cfg memory
+//[thread]compile-flags:  -Zsanitizer=thread  --cfg thread
+
+#![feature(cfg_sanitize)]
+
+#[cfg(all(sanitize = "address", address))]
+fn main() {}
+
+#[cfg(all(sanitize = "leak", leak))]
+fn main() {}
+
+#[cfg(all(sanitize = "memory", memory))]
+fn main() {}
+
+#[cfg(all(sanitize = "thread", thread))]
+fn main() {}
diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr
index 713d4b75909..5a63553adc5 100644
--- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr
+++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_impl_trait-async.nll.stderr
@@ -2,11 +2,11 @@ error: lifetime may not live long enough
   --> $DIR/arbitrary_self_types_pin_lifetime_impl_trait-async.rs:8:48
    |
 LL |     async fn f(self: Pin<&Self>) -> impl Clone { self }
-   |                          -                     ^^^^^^^^ returning this value requires that `'_` must outlive `'static`
+   |                          -                     ^^^^^^^^ returning this value requires that `'1` must outlive `'static`
    |                          |
-   |                          lifetime `'_` defined here
+   |                          let's call the lifetime of this reference `'1`
    |
-help: to allow this `impl Trait` to capture borrowed data with lifetime `'_`, add `'_` as a constraint
+help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as a constraint
    |
 LL |     async fn f(self: Pin<&Self>) -> impl Clone + '_ { self }
    |                                     ^^^^^^^^^^^^^^^
diff --git a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
index 7eec31d36e3..b05940fd273 100644
--- a/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
+++ b/src/test/ui/self/arbitrary_self_types_pin_lifetime_mismatch-async.nll.stderr
@@ -10,19 +10,19 @@ error: lifetime may not live long enough
   --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:8:52
    |
 LL |     async fn a(self: Pin<&Foo>, f: &Foo) -> &Foo { f }
-   |                          -                         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
-   |                          |
-   |                          lifetime `'_` defined here
-   |                          lifetime `'_` defined here
+   |                          -         -               ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
+   |                          |         |
+   |                          |         let's call the lifetime of this reference `'1`
+   |                          let's call the lifetime of this reference `'2`
 
 error: lifetime may not live long enough
   --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:11:75
    |
 LL |     async fn c(self: Pin<&Self>, f: &Foo, g: &Foo) -> (Pin<&Foo>, &Foo) { (self, f) }
-   |                          -                                                ^^^^^^^^^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
-   |                          |
-   |                          lifetime `'_` defined here
-   |                          lifetime `'_` defined here
+   |                          -          -                                     ^^^^^^^^^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
+   |                          |          |
+   |                          |          let's call the lifetime of this reference `'1`
+   |                          let's call the lifetime of this reference `'2`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:17:58
@@ -36,8 +36,9 @@ error: lifetime may not live long enough
   --> $DIR/arbitrary_self_types_pin_lifetime_mismatch-async.rs:17:64
    |
 LL |     async fn bar<'a>(self: Alias<&Self>, arg: &'a ()) -> &() { arg }
-   |                  --              - lifetime `'_` defined here  ^^^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'a`
-   |                  |
+   |                  --              -                             ^^^ function was supposed to return data with lifetime `'1` but it is returning data with lifetime `'a`
+   |                  |               |
+   |                  |               let's call the lifetime of this reference `'1`
    |                  lifetime `'a` defined here
 
 error: aborting due to 5 previous errors
diff --git a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
index 1288759703f..8dd823a2204 100644
--- a/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
+++ b/src/test/ui/self/elision/lt-ref-self-async.nll.stderr
@@ -10,12 +10,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:13:9
    |
 LL |     async fn ref_self(&self, f: &u32) -> &u32 {
-   |                       -
+   |                       -         - let's call the lifetime of this reference `'1`
    |                       |
-   |                       lifetime `'_` defined here
-   |                       lifetime `'_` defined here
+   |                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/lt-ref-self-async.rs:18:48
@@ -29,12 +28,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:19:9
    |
 LL |     async fn ref_Self(self: &Self, f: &u32) -> &u32 {
-   |                             -
+   |                             -         - let's call the lifetime of this reference `'1`
    |                             |
-   |                             lifetime `'_` defined here
-   |                             lifetime `'_` defined here
+   |                             let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/lt-ref-self-async.rs:22:57
@@ -48,12 +46,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:23:9
    |
 LL |     async fn box_ref_Self(self: Box<&Self>, f: &u32) -> &u32 {
-   |                                     -
+   |                                     -          - let's call the lifetime of this reference `'1`
    |                                     |
-   |                                     lifetime `'_` defined here
-   |                                     lifetime `'_` defined here
+   |                                     let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/lt-ref-self-async.rs:26:57
@@ -67,12 +64,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:27:9
    |
 LL |     async fn pin_ref_Self(self: Pin<&Self>, f: &u32) -> &u32 {
-   |                                     -
+   |                                     -          - let's call the lifetime of this reference `'1`
    |                                     |
-   |                                     lifetime `'_` defined here
-   |                                     lifetime `'_` defined here
+   |                                     let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/lt-ref-self-async.rs:30:66
@@ -86,12 +82,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:31:9
    |
 LL |     async fn box_box_ref_Self(self: Box<Box<&Self>>, f: &u32) -> &u32 {
-   |                                             -
+   |                                             -           - let's call the lifetime of this reference `'1`
    |                                             |
-   |                                             lifetime `'_` defined here
-   |                                             lifetime `'_` defined here
+   |                                             let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/lt-ref-self-async.rs:34:62
@@ -105,12 +100,11 @@ error: lifetime may not live long enough
   --> $DIR/lt-ref-self-async.rs:35:9
    |
 LL |     async fn box_pin_Self(self: Box<Pin<&Self>>, f: &u32) -> &u32 {
-   |                                         -
+   |                                         -           - let's call the lifetime of this reference `'1`
    |                                         |
-   |                                         lifetime `'_` defined here
-   |                                         lifetime `'_` defined here
+   |                                         let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error: aborting due to 12 previous errors
 
diff --git a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
index 24e3f7a098f..768f532c183 100644
--- a/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-mut-self-async.nll.stderr
@@ -10,12 +10,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:13:9
    |
 LL |     async fn ref_self(&mut self, f: &u32) -> &u32 {
-   |                       -
+   |                       -             - let's call the lifetime of this reference `'1`
    |                       |
-   |                       lifetime `'_` defined here
-   |                       lifetime `'_` defined here
+   |                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-self-async.rs:18:52
@@ -29,12 +28,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:19:9
    |
 LL |     async fn ref_Self(self: &mut Self, f: &u32) -> &u32 {
-   |                             -
+   |                             -             - let's call the lifetime of this reference `'1`
    |                             |
-   |                             lifetime `'_` defined here
-   |                             lifetime `'_` defined here
+   |                             let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-self-async.rs:22:61
@@ -48,12 +46,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:23:9
    |
 LL |     async fn box_ref_Self(self: Box<&mut Self>, f: &u32) -> &u32 {
-   |                                     -
+   |                                     -              - let's call the lifetime of this reference `'1`
    |                                     |
-   |                                     lifetime `'_` defined here
-   |                                     lifetime `'_` defined here
+   |                                     let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-self-async.rs:26:61
@@ -67,12 +64,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:27:9
    |
 LL |     async fn pin_ref_Self(self: Pin<&mut Self>, f: &u32) -> &u32 {
-   |                                     -
+   |                                     -              - let's call the lifetime of this reference `'1`
    |                                     |
-   |                                     lifetime `'_` defined here
-   |                                     lifetime `'_` defined here
+   |                                     let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-self-async.rs:30:70
@@ -86,12 +82,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:31:9
    |
 LL |     async fn box_box_ref_Self(self: Box<Box<&mut Self>>, f: &u32) -> &u32 {
-   |                                             -
+   |                                             -               - let's call the lifetime of this reference `'1`
    |                                             |
-   |                                             lifetime `'_` defined here
-   |                                             lifetime `'_` defined here
+   |                                             let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-self-async.rs:34:70
@@ -105,12 +100,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-self-async.rs:35:9
    |
 LL |     async fn box_pin_ref_Self(self: Box<Pin<&mut Self>>, f: &u32) -> &u32 {
-   |                                             -
+   |                                             -               - let's call the lifetime of this reference `'1`
    |                                             |
-   |                                             lifetime `'_` defined here
-   |                                             lifetime `'_` defined here
+   |                                             let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error: aborting due to 12 previous errors
 
diff --git a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
index c0423d1d3e6..9e26e411d30 100644
--- a/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-mut-struct-async.nll.stderr
@@ -10,12 +10,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-struct-async.rs:13:9
    |
 LL |     async fn ref_Struct(self: &mut Struct, f: &u32) -> &u32 {
-   |                               -
+   |                               -               - let's call the lifetime of this reference `'1`
    |                               |
-   |                               lifetime `'_` defined here
-   |                               lifetime `'_` defined here
+   |                               let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-struct-async.rs:16:65
@@ -29,12 +28,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-struct-async.rs:17:9
    |
 LL |     async fn box_ref_Struct(self: Box<&mut Struct>, f: &u32) -> &u32 {
-   |                                       -
+   |                                       -                - let's call the lifetime of this reference `'1`
    |                                       |
-   |                                       lifetime `'_` defined here
-   |                                       lifetime `'_` defined here
+   |                                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-struct-async.rs:20:65
@@ -48,12 +46,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-struct-async.rs:21:9
    |
 LL |     async fn pin_ref_Struct(self: Pin<&mut Struct>, f: &u32) -> &u32 {
-   |                                       -
+   |                                       -                - let's call the lifetime of this reference `'1`
    |                                       |
-   |                                       lifetime `'_` defined here
-   |                                       lifetime `'_` defined here
+   |                                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-struct-async.rs:24:74
@@ -67,12 +64,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-struct-async.rs:25:9
    |
 LL |     async fn box_box_ref_Struct(self: Box<Box<&mut Struct>>, f: &u32) -> &u32 {
-   |                                               -
+   |                                               -                 - let's call the lifetime of this reference `'1`
    |                                               |
-   |                                               lifetime `'_` defined here
-   |                                               lifetime `'_` defined here
+   |                                               let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-mut-struct-async.rs:28:74
@@ -86,12 +82,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-mut-struct-async.rs:29:9
    |
 LL |     async fn box_pin_ref_Struct(self: Box<Pin<&mut Struct>>, f: &u32) -> &u32 {
-   |                                               -
+   |                                               -                 - let's call the lifetime of this reference `'1`
    |                                               |
-   |                                               lifetime `'_` defined here
-   |                                               lifetime `'_` defined here
+   |                                               let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error: aborting due to 10 previous errors
 
diff --git a/src/test/ui/self/elision/ref-struct-async.nll.stderr b/src/test/ui/self/elision/ref-struct-async.nll.stderr
index 6f413a7f49f..cbf051205ed 100644
--- a/src/test/ui/self/elision/ref-struct-async.nll.stderr
+++ b/src/test/ui/self/elision/ref-struct-async.nll.stderr
@@ -10,12 +10,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-struct-async.rs:13:9
    |
 LL |     async fn ref_Struct(self: &Struct, f: &u32) -> &u32 {
-   |                               -
+   |                               -           - let's call the lifetime of this reference `'1`
    |                               |
-   |                               lifetime `'_` defined here
-   |                               lifetime `'_` defined here
+   |                               let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-struct-async.rs:16:61
@@ -29,12 +28,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-struct-async.rs:17:9
    |
 LL |     async fn box_ref_Struct(self: Box<&Struct>, f: &u32) -> &u32 {
-   |                                       -
+   |                                       -            - let's call the lifetime of this reference `'1`
    |                                       |
-   |                                       lifetime `'_` defined here
-   |                                       lifetime `'_` defined here
+   |                                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-struct-async.rs:20:61
@@ -48,12 +46,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-struct-async.rs:21:9
    |
 LL |     async fn pin_ref_Struct(self: Pin<&Struct>, f: &u32) -> &u32 {
-   |                                       -
+   |                                       -            - let's call the lifetime of this reference `'1`
    |                                       |
-   |                                       lifetime `'_` defined here
-   |                                       lifetime `'_` defined here
+   |                                       let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-struct-async.rs:24:70
@@ -67,12 +64,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-struct-async.rs:25:9
    |
 LL |     async fn box_box_ref_Struct(self: Box<Box<&Struct>>, f: &u32) -> &u32 {
-   |                                               -
+   |                                               -             - let's call the lifetime of this reference `'1`
    |                                               |
-   |                                               lifetime `'_` defined here
-   |                                               lifetime `'_` defined here
+   |                                               let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
   --> $DIR/ref-struct-async.rs:28:66
@@ -86,12 +82,11 @@ error: lifetime may not live long enough
   --> $DIR/ref-struct-async.rs:29:9
    |
 LL |     async fn box_pin_Struct(self: Box<Pin<&Struct>>, f: &u32) -> &u32 {
-   |                                           -
+   |                                           -             - let's call the lifetime of this reference `'1`
    |                                           |
-   |                                           lifetime `'_` defined here
-   |                                           lifetime `'_` defined here
+   |                                           let's call the lifetime of this reference `'2`
 LL |         f
-   |         ^ function was supposed to return data with lifetime `'_` but it is returning data with lifetime `'_`
+   |         ^ function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
 
 error: aborting due to 10 previous errors
 
diff --git a/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.rs b/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.rs
new file mode 100644
index 00000000000..cc94680530c
--- /dev/null
+++ b/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.rs
@@ -0,0 +1,7 @@
+// ignore-tidy-linelength
+
+fn main() {
+    let unicode_is_fun = "؁‱ஹ௸௵꧄.ဪ꧅⸻𒈙𒐫﷽𒌄𒈟𒍼𒁎𒀱𒌧𒅃 𒈓𒍙𒊎𒄡𒅌𒁏𒀰𒐪𒐩𒈙𒐫𪚥";
+    let _ = "ༀ༁༂༃༄༅༆༇༈༉༊་༌།༎༏༐༑༒༓༔༕༖༗༘༙༚༛༜༝༞༟༠༡༢༣༤༥༦༧༨༩༪༫༬༭༮༯༰༱༲༳༴༵༶༷༸༹༺༻༼༽༾༿ཀཁགགྷངཅཆཇ཈ཉཊཋཌཌྷཎཏཐདདྷནཔཕབབྷམཙཚཛཛྷཝཞཟའཡརལཤཥསཧཨཀྵཪཫཬ཭཮཯཰ཱཱཱིིུུྲྀཷླྀཹེཻོཽཾཿ྄ཱྀྀྂྃ྅྆྇ྈྉྊྋྌྍྎྏྐྑྒྒྷྔྕྖྗ྘ྙྚྛྜྜྷྞྟྠྡྡྷྣྤྥྦྦྷྨྩྪྫྫྷྭྮྯྰྱྲླྴྵྶྷྸྐྵྺྻྼ྽྾྿࿀࿁࿂࿃࿄࿅࿆࿇࿈࿉࿊࿋࿌࿍࿎࿏࿐࿑࿒࿓࿔࿕࿖࿗࿘࿙࿚"; let _a = unicode_is_fun + " really fun!";
+    //~^ ERROR binary operation `+` cannot be applied to type `&str`
+}
diff --git a/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.stderr b/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.stderr
new file mode 100644
index 00000000000..9f0f990670f
--- /dev/null
+++ b/src/test/ui/terminal-width/non-1-width-unicode-multiline-label.stderr
@@ -0,0 +1,17 @@
+error[E0369]: binary operation `+` cannot be applied to type `&str`
+  --> $DIR/non-1-width-unicode-multiline-label.rs:5:260
+   |
+LL | ...ཽཾཿ྄ཱྀྀྂྃ྅྆྇ྈྉྊྋྌྍྎྏྐྑྒྒྷྔྕྖྗ྘ྙྚྛྜྜྷྞྟྠྡྡྷྣྤྥྦྦྷྨྩྪྫྫྷྭྮྯྰྱྲླྴྵྶྷྸྐྵྺྻྼ྽྾྿࿀࿁࿂࿃࿄࿅࿆࿇...࿋࿌࿍࿎࿏࿐࿑࿒࿓࿔࿕࿖࿗࿘࿙࿚"; let _a = unicode_is_fun + " really fun!";
+   |                                                  -------------- ^ -------------- &str
+   |                                                  |              |
+   |                                                  |              `+` cannot be used to concatenate two `&str` strings
+   |                                                  &str
+   |
+help: `to_owned()` can be used to create an owned `String` from a string reference. String concatenation appends the string on the right to the string on the left and may require reallocation. This requires ownership of the string on the left
+   |
+LL |     let _ = "ༀ༁༂༃༄༅༆༇༈༉༊་༌།༎༏༐༑༒༓༔༕༖༗༘༙༚༛༜༝༞༟༠༡༢༣༤༥༦༧༨༩༪༫༬༭༮༯༰༱༲༳༴༵༶༷༸༹༺༻༼༽༾༿ཀཁགགྷངཅཆཇ཈ཉཊཋཌཌྷཎཏཐདདྷནཔཕབབྷམཙཚཛཛྷཝཞཟའཡརལཤཥསཧཨཀྵཪཫཬ཭཮཯཰ཱཱཱིིུུྲྀཷླྀཹེཻོཽཾཿ྄ཱྀྀྂྃ྅྆྇ྈྉྊྋྌྍྎྏྐྑྒྒྷྔྕྖྗ྘ྙྚྛྜྜྷྞྟྠྡྡྷྣྤྥྦྦྷྨྩྪྫྫྷྭྮྯྰྱྲླྴྵྶྷྸྐྵྺྻྼ྽྾྿࿀࿁࿂࿃࿄࿅࿆࿇࿈࿉࿊࿋࿌࿍࿎࿏࿐࿑࿒࿓࿔࿕࿖࿗࿘࿙࿚"; let _a = unicode_is_fun.to_owned() + " really fun!";
+   |                                                                                                                                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0369`.
diff --git a/src/test/ui/terminal-width/non-whitespace-trimming-unicode.stderr b/src/test/ui/terminal-width/non-whitespace-trimming-unicode.stderr
index d4993fad15c..1e5ff939832 100644
--- a/src/test/ui/terminal-width/non-whitespace-trimming-unicode.stderr
+++ b/src/test/ui/terminal-width/non-whitespace-trimming-unicode.stderr
@@ -3,7 +3,7 @@ error[E0308]: mismatched types
    |
 LL | ...♭♮♯♰♱♲♳♴♵♶♷♸♹♺♻♼♽♾♿⚀⚁⚂⚃⚄⚅⚆⚈⚉4"; let _: () = 42;  let _: &str = "🦀☀☁☂☃☄★☆☇☈☉☊☋☌☍☎☏☐☑☒☓  ☖☗☘☙☚☛☜☝☞☟☠☡☢☣☤☥☦☧☨☩☪☫☬☭☮☯☰☱☲☳☴☵☶☷☸☹☺☻☼☽☾☿♀♁♂♃♄...
    |                                            --   ^^ expected `()`, found integer
-   |                                                     |
+   |                                            |
    |                                            expected due to this
 
 error: aborting due to previous error
diff --git a/src/test/ui/type-alias-impl-trait/issue-66580-closure-coherence.rs b/src/test/ui/type-alias-impl-trait/issue-66580-closure-coherence.rs
new file mode 100644
index 00000000000..1d95cc7530c
--- /dev/null
+++ b/src/test/ui/type-alias-impl-trait/issue-66580-closure-coherence.rs
@@ -0,0 +1,19 @@
+// Regression test for issue #66580
+// Ensures that we don't try to determine whether a closure
+// is foreign when it's the underlying type of an opaque type
+// check-pass
+#![feature(type_alias_impl_trait)]
+
+type Closure = impl FnOnce();
+
+fn closure() -> Closure {
+    || {}
+}
+
+struct Wrap<T> { f: T }
+
+impl Wrap<Closure> {}
+
+impl<T> Wrap<T> {}
+
+fn main() {}
diff --git a/src/test/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr b/src/test/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr
index 9287353245e..68ec8d2ba82 100644
--- a/src/test/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr
+++ b/src/test/ui/unboxed-closures/unboxed-closures-infer-fn-once-move-from-projection.stderr
@@ -2,7 +2,7 @@ error[E0525]: expected a closure that implements the `Fn` trait, but this closur
   --> $DIR/unboxed-closures-infer-fn-once-move-from-projection.rs:14:13
    |
 LL |     let c = || drop(y.0);
-   |             ^^^^^^^^-^^^
+   |             ^^^^^^^^---^
    |             |       |
    |             |       closure is `FnOnce` because it moves the variable `y` out of its environment
    |             this closure implements `FnOnce`, not `Fn`
diff --git a/src/test/ui/unop-move-semantics.stderr b/src/test/ui/unop-move-semantics.stderr
index 6aa3d0b0989..092c419d7cb 100644
--- a/src/test/ui/unop-move-semantics.stderr
+++ b/src/test/ui/unop-move-semantics.stderr
@@ -2,9 +2,9 @@ error[E0382]: borrow of moved value: `x`
   --> $DIR/unop-move-semantics.rs:8:5
    |
 LL | fn move_then_borrow<T: Not<Output=T> + Clone>(x: T) {
-   |                     -                         - move occurs because `x` has type `T`, which does not implement the `Copy` trait
+   |                     --                        - move occurs because `x` has type `T`, which does not implement the `Copy` trait
    |                     |
-   |                     consider adding a `Copy` constraint to this type argument
+   |                     help: consider further restricting this bound: `T: Copy +`
 LL |     !x;
    |      - value moved here
 LL | 
diff --git a/src/tools/miri b/src/tools/miri
-Subproject 644e2a76a87a129f597dc40b47593fc8f72539c
+Subproject 3bf51f591f7ffdd45f51cd1d42a4002482af2bd
diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs
index defe85ef46a..4ea101296b7 100644
--- a/src/tools/tidy/src/features.rs
+++ b/src/tools/tidy/src/features.rs
@@ -231,7 +231,7 @@ pub fn collect_lang_features(base_src_path: &Path, bad: &mut bool) -> Features {
 }
 
 fn collect_lang_features_in(base: &Path, file: &str, bad: &mut bool) -> Features {
-    let path = base.join("libsyntax/feature_gate").join(file);
+    let path = base.join("librustc_feature").join(file);
     let contents = t!(fs::read_to_string(&path));
 
     // We allow rustc-internal features to omit a tracking issue.