]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #51670 - estebank:issue-51634, r=oli-obk
authorbors <bors@rust-lang.org>
Fri, 22 Jun 2018 17:51:02 +0000 (17:51 +0000)
committerbors <bors@rust-lang.org>
Fri, 22 Jun 2018 17:51:02 +0000 (17:51 +0000)
Don't suggest incorrect syntax

Fix #51634.

330 files changed:
RELEASES.md
config.toml.example
src/Cargo.lock
src/bootstrap/builder.rs
src/bootstrap/config.rs
src/bootstrap/configure.py
src/bootstrap/dist.rs
src/bootstrap/lib.rs
src/bootstrap/native.rs
src/doc/rustdoc/src/documentation-tests.md
src/liballoc/alloc.rs
src/liballoc/arc.rs
src/liballoc/raw_vec.rs
src/liballoc/rc.rs
src/liballoc/vec.rs
src/libcore/alloc.rs
src/libcore/cmp.rs
src/libcore/iter/mod.rs
src/libcore/iter/traits.rs
src/libcore/marker.rs
src/libcore/ops/index.rs
src/libcore/tests/iter.rs
src/librustc/Cargo.toml
src/librustc/hir/intravisit.rs
src/librustc/hir/lowering.rs
src/librustc/hir/map/collector.rs
src/librustc/hir/map/def_collector.rs
src/librustc/hir/map/definitions.rs
src/librustc/hir/map/mod.rs
src/librustc/hir/mod.rs
src/librustc/hir/print.rs
src/librustc/ich/impls_hir.rs
src/librustc/ich/impls_ty.rs
src/librustc/infer/anon_types/mod.rs
src/librustc/infer/error_reporting/mod.rs
src/librustc/middle/expr_use_visitor.rs
src/librustc/middle/mem_categorization.rs
src/librustc/middle/reachable.rs
src/librustc/middle/resolve_lifetime.rs
src/librustc/mir/mod.rs
src/librustc/traits/auto_trait.rs
src/librustc/traits/mod.rs
src/librustc/traits/structural_impls.rs
src/librustc/ty/binding.rs
src/librustc/ty/item_path.rs
src/librustc/util/ppaux.rs
src/librustc_codegen_llvm/Cargo.toml
src/librustc_codegen_llvm/attributes.rs
src/librustc_codegen_llvm/back/link.rs
src/librustc_codegen_llvm/lib.rs
src/librustc_driver/pretty.rs
src/librustc_lint/bad_style.rs
src/librustc_lint/builtin.rs
src/librustc_lint/types.rs
src/librustc_metadata/creader.rs
src/librustc_metadata/encoder.rs
src/librustc_mir/borrow_check/error_reporting.rs
src/librustc_mir/borrow_check/mod.rs
src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs
src/librustc_mir/borrow_check/path_utils.rs
src/librustc_mir/borrow_check/used_muts.rs [new file with mode: 0644]
src/librustc_mir/build/block.rs
src/librustc_mir/build/expr/into.rs
src/librustc_mir/build/matches/mod.rs
src/librustc_mir/build/mod.rs
src/librustc_mir/dataflow/at_location.rs
src/librustc_mir/hair/pattern/check_match.rs
src/librustc_mir/monomorphize/collector.rs
src/librustc_mir/shim.rs
src/librustc_mir/transform/generator.rs
src/librustc_mir/util/collect_writes.rs
src/librustc_passes/ast_validation.rs
src/librustc_passes/hir_stats.rs
src/librustc_privacy/lib.rs
src/librustc_resolve/lib.rs
src/librustc_resolve/macros.rs
src/librustc_save_analysis/dump_visitor.rs
src/librustc_save_analysis/lib.rs
src/librustc_save_analysis/sig.rs
src/librustc_traits/chalk_context.rs
src/librustc_traits/lowering.rs
src/librustc_typeck/astconv.rs
src/librustc_typeck/check/compare_method.rs
src/librustc_typeck/check/method/confirm.rs
src/librustc_typeck/check/mod.rs
src/librustc_typeck/check/wfcheck.rs
src/librustc_typeck/coherence/unsafety.rs
src/librustc_typeck/collect.rs
src/librustc_typeck/diagnostics.rs
src/librustc_typeck/lib.rs
src/librustdoc/Cargo.toml
src/librustdoc/clean/auto_trait.rs
src/librustdoc/clean/inline.rs
src/librustdoc/clean/mod.rs
src/librustdoc/clean/simplify.rs
src/librustdoc/core.rs
src/librustdoc/doctree.rs
src/librustdoc/html/format.rs
src/librustdoc/html/render.rs
src/librustdoc/lib.rs
src/librustdoc/test.rs
src/libstd/alloc.rs
src/libstd/collections/hash/table.rs
src/libstd/io/mod.rs
src/libstd/panic.rs
src/libstd/sys/unix/rand.rs
src/libsyntax/ast.rs
src/libsyntax/attr.rs
src/libsyntax/diagnostic_list.rs
src/libsyntax/ext/build.rs
src/libsyntax/feature_gate.rs
src/libsyntax/fold.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pprust.rs
src/libsyntax/test.rs
src/libsyntax/util/node_count.rs
src/libsyntax/visit.rs
src/libsyntax_ext/deriving/clone.rs
src/libsyntax_ext/deriving/cmp/eq.rs
src/libsyntax_ext/deriving/generic/mod.rs
src/libsyntax_ext/deriving/generic/ty.rs
src/libsyntax_ext/deriving/mod.rs
src/libsyntax_ext/env.rs
src/test/compile-fail/assign-imm-local-twice.rs
src/test/compile-fail/associated-types-unsized.rs
src/test/compile-fail/bad-method-typaram-kind.rs
src/test/compile-fail/bad-sized.rs
src/test/compile-fail/borrowck/borrowck-issue-14498.rs
src/test/compile-fail/borrowck/borrowck-overloaded-index-ref-index.rs
src/test/compile-fail/builtin-superkinds-double-superkind.rs
src/test/compile-fail/builtin-superkinds-in-metadata.rs
src/test/compile-fail/builtin-superkinds-simple.rs
src/test/compile-fail/builtin-superkinds-typaram-not-send.rs
src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs
src/test/compile-fail/dst-bad-assign-2.rs
src/test/compile-fail/dst-bad-assign-3.rs
src/test/compile-fail/dst-bad-assign.rs
src/test/compile-fail/dst-bad-deep-2.rs
src/test/compile-fail/dst-bad-deep.rs
src/test/compile-fail/dst-object-from-unsized-type.rs
src/test/compile-fail/dst-sized-trait-param.rs
src/test/compile-fail/extern-types-not-sync-send.rs
src/test/compile-fail/extern-types-unsized.rs
src/test/compile-fail/issue-14366.rs
src/test/compile-fail/issue-15756.rs
src/test/compile-fail/issue-17651.rs
src/test/compile-fail/issue-18107.rs
src/test/compile-fail/issue-18919.rs
src/test/compile-fail/issue-1900.rs
src/test/compile-fail/issue-20005.rs
src/test/compile-fail/issue-20433.rs
src/test/compile-fail/issue-20605.rs
src/test/compile-fail/issue-21763.rs
src/test/compile-fail/issue-22874.rs
src/test/compile-fail/issue-23281.rs
src/test/compile-fail/issue-24446.rs
src/test/compile-fail/issue-27060-2.rs
src/test/compile-fail/issue-27078.rs
src/test/compile-fail/issue-35988.rs
src/test/compile-fail/issue-38954.rs
src/test/compile-fail/issue-41229-ref-str.rs
src/test/compile-fail/issue-42312.rs
src/test/compile-fail/issue-45199.rs
src/test/compile-fail/issue-5883.rs
src/test/compile-fail/issue-7013.rs
src/test/compile-fail/kindck-impl-type-params.rs
src/test/compile-fail/kindck-nonsendable-1.rs
src/test/compile-fail/kindck-send-object.rs
src/test/compile-fail/kindck-send-object1.rs
src/test/compile-fail/kindck-send-object2.rs
src/test/compile-fail/kindck-send-owned.rs
src/test/compile-fail/kindck-send-unsafe.rs
src/test/compile-fail/liveness-assign-imm-local-in-loop.rs
src/test/compile-fail/liveness-assign-imm-local-in-op-eq.rs
src/test/compile-fail/liveness-assign-imm-local-with-drop.rs
src/test/compile-fail/liveness-assign-imm-local-with-init.rs
src/test/compile-fail/no-send-res-ports.rs
src/test/compile-fail/no_send-enum.rs
src/test/compile-fail/no_send-rc.rs
src/test/compile-fail/no_send-struct.rs
src/test/compile-fail/not-panic-safe-2.rs
src/test/compile-fail/not-panic-safe-3.rs
src/test/compile-fail/not-panic-safe-4.rs
src/test/compile-fail/not-panic-safe-6.rs
src/test/compile-fail/not-panic-safe.rs
src/test/compile-fail/range-1.rs
src/test/compile-fail/range_traits-1.rs
src/test/compile-fail/str-idx.rs
src/test/compile-fail/str-mut-idx.rs
src/test/compile-fail/substs-ppaux.rs
src/test/compile-fail/trait-bounds-not-on-bare-trait.rs
src/test/compile-fail/traits-negative-impls.rs
src/test/compile-fail/typeck-default-trait-impl-negation-send.rs
src/test/compile-fail/unboxed-closures-mutated-upvar-from-fn-closure.rs
src/test/compile-fail/union/union-unsized.rs
src/test/compile-fail/unsized-bare-typaram.rs
src/test/compile-fail/unsized-enum.rs
src/test/compile-fail/unsized-inherent-impl-self-type.rs
src/test/compile-fail/unsized-struct.rs
src/test/compile-fail/unsized-trait-impl-self-type.rs
src/test/compile-fail/unsized-trait-impl-trait-arg.rs
src/test/compile-fail/unsized3.rs
src/test/compile-fail/unsized5.rs
src/test/compile-fail/unsized6.rs
src/test/compile-fail/unsized7.rs
src/test/run-pass/allocator-alloc-one.rs
src/test/run-pass/issue-22777.rs
src/test/run-pass/realloc-16687.rs
src/test/run-pass/regions-mock-codegen.rs
src/test/ui/asm-out-assign-imm.nll.stderr [new file with mode: 0644]
src/test/ui/augmented-assignments.nll.stderr
src/test/ui/borrowck/immutable-arg.stderr
src/test/ui/borrowck/issue-45983.nll.stderr
src/test/ui/borrowck/issue-51415.nll.stderr [new file with mode: 0644]
src/test/ui/borrowck/issue-51415.rs [new file with mode: 0644]
src/test/ui/borrowck/issue-51415.stderr [new file with mode: 0644]
src/test/ui/borrowck/mut-borrow-of-mut-ref.nll.stderr
src/test/ui/chalkify/lower_struct.rs [new file with mode: 0644]
src/test/ui/chalkify/lower_struct.stderr [new file with mode: 0644]
src/test/ui/chalkify/lower_trait_higher_rank.stderr
src/test/ui/codemap_tests/huge_multispan_highlight.nll.stderr
src/test/ui/codemap_tests/unicode.stderr
src/test/ui/command-line-diagnostics.nll.stderr
src/test/ui/const-unsized.rs
src/test/ui/const-unsized.stderr
src/test/ui/did_you_mean/issue-31424.nll.stderr
src/test/ui/did_you_mean/issue-34126.nll.stderr
src/test/ui/did_you_mean/issue-34337.nll.stderr
src/test/ui/did_you_mean/issue-35937.nll.stderr
src/test/ui/did_you_mean/issue-37139.nll.stderr
src/test/ui/did_you_mean/issue-38147-1.nll.stderr
src/test/ui/did_you_mean/issue-38147-4.nll.stderr
src/test/ui/did_you_mean/issue-39544.nll.stderr
src/test/ui/did_you_mean/issue-40823.nll.stderr
src/test/ui/dropck/dropck-eyepatch-extern-crate.nll.stderr
src/test/ui/dropck/dropck-eyepatch-reorder.nll.stderr
src/test/ui/dropck/dropck-eyepatch.nll.stderr
src/test/ui/error-codes/E0110.stderr
src/test/ui/error-codes/E0131.stderr
src/test/ui/error-codes/E0277-2.rs
src/test/ui/error-codes/E0277-2.stderr
src/test/ui/error-codes/E0277.rs
src/test/ui/error-codes/E0277.stderr
src/test/ui/error-codes/E0389.nll.stderr
src/test/ui/error-codes/E0597.nll.stderr
src/test/ui/error-codes/E0657.rs
src/test/ui/error-codes/E0657.stderr
src/test/ui/feature-gate-trivial_bounds.stderr
src/test/ui/generator/dropck.nll.stderr
src/test/ui/generator/sized-yield.rs
src/test/ui/generator/sized-yield.stderr
src/test/ui/impl-trait/auto-trait-leak.rs
src/test/ui/impl-trait/auto-trait-leak.stderr
src/test/ui/impl-trait/auto-trait-leak2.rs
src/test/ui/impl-trait/auto-trait-leak2.stderr
src/test/ui/impl_trait_projections.rs
src/test/ui/impl_trait_projections.stderr
src/test/ui/interior-mutability/interior-mutability.rs
src/test/ui/interior-mutability/interior-mutability.stderr
src/test/ui/issue-36400.nll.stderr
src/test/ui/issue-51022.rs
src/test/ui/issue-51022.stderr
src/test/ui/lifetime-errors/ex3-both-anon-regions-one-is-struct-2.nll.stderr
src/test/ui/lifetime-errors/ex3-both-anon-regions-using-fn-items.nll.stderr
src/test/ui/lifetime-errors/ex3-both-anon-regions-using-trait-objects.nll.stderr
src/test/ui/lifetime-errors/liveness-assign-imm-local-notes.stderr
src/test/ui/macros/span-covering-argument-1.nll.stderr
src/test/ui/mismatched_types/binops.rs
src/test/ui/mismatched_types/binops.stderr
src/test/ui/mismatched_types/cast-rfc0401.rs
src/test/ui/mismatched_types/cast-rfc0401.stderr
src/test/ui/missing-allocator.rs [new file with mode: 0644]
src/test/ui/missing-allocator.stderr [new file with mode: 0644]
src/test/ui/nll/issue-47388.stderr
src/test/ui/nll/issue-51268.rs [new file with mode: 0644]
src/test/ui/nll/issue-51268.stderr [new file with mode: 0644]
src/test/ui/parser/expected-comma-found-token.rs [new file with mode: 0644]
src/test/ui/parser/expected-comma-found-token.stderr [new file with mode: 0644]
src/test/ui/partialeq_help.stderr
src/test/ui/pub/pub-restricted.stderr
src/test/ui/reassign-ref-mut.rs [new file with mode: 0644]
src/test/ui/reassign-ref-mut.stderr [new file with mode: 0644]
src/test/ui/resolve/issue-5035-2.rs
src/test/ui/resolve/issue-5035-2.stderr
src/test/ui/rfc-2005-default-binding-mode/enum.nll.stderr
src/test/ui/rfc-2005-default-binding-mode/explicit-mut.nll.stderr
src/test/ui/rfc1598-generic-associated-types/collections.stderr
src/test/ui/rfc1598-generic-associated-types/construct_with_other_type.stderr
src/test/ui/rfc1598-generic-associated-types/generic_associated_type_undeclared_lifetimes.stderr
src/test/ui/rfc1598-generic-associated-types/iterable.stderr
src/test/ui/rfc1598-generic-associated-types/parameter_number_and_kind.stderr
src/test/ui/rfc1598-generic-associated-types/streaming_iterator.stderr
src/test/ui/span/borrowck-borrow-overloaded-auto-deref-mut.nll.stderr
src/test/ui/span/borrowck-borrow-overloaded-deref-mut.nll.stderr
src/test/ui/span/borrowck-call-is-borrow-issue-12224.nll.stderr
src/test/ui/span/borrowck-call-method-from-mut-aliasable.nll.stderr
src/test/ui/span/borrowck-fn-in-const-b.nll.stderr
src/test/ui/span/borrowck-object-mutability.nll.stderr
src/test/ui/span/dropck-object-cycle.nll.stderr
src/test/ui/span/dropck_direct_cycle_with_drop.nll.stderr
src/test/ui/span/dropck_misc_variants.nll.stderr
src/test/ui/span/issue-24805-dropck-child-has-items-via-parent.nll.stderr
src/test/ui/span/issue-24805-dropck-trait-has-items.nll.stderr
src/test/ui/span/issue-24895-copy-clone-dropck.nll.stderr
src/test/ui/span/issue-26656.nll.stderr
src/test/ui/span/issue28498-reject-ex1.nll.stderr
src/test/ui/span/issue28498-reject-lifetime-param.nll.stderr
src/test/ui/span/issue28498-reject-passed-to-fn.nll.stderr
src/test/ui/span/issue28498-reject-trait-bound.nll.stderr
src/test/ui/span/mut-arg-hint.nll.stderr
src/test/ui/span/send-is-not-static-std-sync.nll.stderr
src/test/ui/span/vec_refs_data_with_early_death.nll.stderr
src/test/ui/struct-duplicate-comma.rs [new file with mode: 0644]
src/test/ui/struct-duplicate-comma.stderr [new file with mode: 0644]
src/test/ui/suggestions/closure-immutable-outer-variable.nll.stderr
src/test/ui/suggestions/fn-closure-mutable-capture.nll.stderr
src/test/ui/suggestions/str-array-assignment.rs
src/test/ui/suggestions/str-array-assignment.stderr
src/test/ui/trait-suggest-where-clause.rs
src/test/ui/trait-suggest-where-clause.stderr
src/test/ui/trivial-bounds-inconsistent-copy-reborrow.nll.stderr
src/test/ui/trivial-bounds-leak.stderr
src/test/ui/type-check-defaults.rs
src/test/ui/type-check-defaults.stderr
src/test/ui/union/union-sized-field.rs
src/test/ui/union/union-sized-field.stderr
src/test/ui/unsized-enum2.rs
src/test/ui/unsized-enum2.stderr
src/tools/build-manifest/src/main.rs
src/tools/tidy/src/deps.rs

index 9c501dc05dcf5af54948e401e9b16b6ae284b87e..068e9e7263e7d891cef422776d5d9c7405f0d19c 100644 (file)
@@ -131,17 +131,15 @@ Compatibility Notes
 [`Option::filter`]: https://doc.rust-lang.org/std/option/enum.Option.html#method.filter
 [`String::replace_range`]: https://doc.rust-lang.org/std/string/struct.String.html#method.replace_range
 [`Take::set_limit`]: https://doc.rust-lang.org/std/io/struct.Take.html#method.set_limit
+[`hint::unreachable_unchecked`]: https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html
+[`os::unix::process::parent_id`]: https://doc.rust-lang.org/std/os/unix/process/fn.parent_id.html
+[`process::id`]: https://doc.rust-lang.org/std/process/fn.id.html
+[`ptr::swap_nonoverlapping`]: https://doc.rust-lang.org/std/ptr/fn.swap_nonoverlapping.html
 [`slice::rsplit_mut`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit_mut
 [`slice::rsplit`]: https://doc.rust-lang.org/std/primitive.slice.html#method.rsplit
 [`slice::swap_with_slice`]: https://doc.rust-lang.org/std/primitive.slice.html#method.swap_with_slice
 [`arch::x86_64`]: https://doc.rust-lang.org/std/arch/x86_64/index.html
 [`arch::x86`]: https://doc.rust-lang.org/std/arch/x86/index.html
-[`fs::read`]:
-[`fs::write`]:
-[`hint::unreachable_unchecked`]: https://doc.rust-lang.org/std/hint/fn.unreachable_unchecked.html
-[`os::unix::process::parent_id`]: https://doc.rust-lang.org/std/os/unix/process/fn.parent_id.html
-[`ptr::swap_nonoverlapping`]: https://doc.rust-lang.org/std/ptr/fn.swap_nonoverlapping.html
-[`process::id`]: https://doc.rust-lang.org/std/process/fn.id.html
 [“The Rustc book”]: https://doc.rust-lang.org/rustc
 
 
index feb55d57ef3e18e38727baedac38f7356ddcf073..0578f929224d99a0cbbaf97e64a2f29477dc7b60 100644 (file)
 # rustc to execute.
 #lld = false
 
+# Indicates whether some LLVM tools, like llvm-objdump, will be made available in the
+# sysroot.
+#llvm-tools = false
+
 # Whether to deny warnings in crates
 #deny-warnings = true
 
index d4544ffa3244fe73049385198b21d41df08a7382..615d36b8ee558174a7eae6f4783fb30a463f155b 100644 (file)
@@ -1800,7 +1800,7 @@ dependencies = [
  "serialize 0.0.0",
  "syntax 0.0.0",
  "syntax_pos 0.0.0",
- "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
@@ -2103,7 +2103,7 @@ dependencies = [
  "serialize 0.0.0",
  "syntax 0.0.0",
  "syntax_pos 0.0.0",
- "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
@@ -2427,7 +2427,7 @@ version = "0.0.0"
 dependencies = [
  "minifier 0.0.11 (registry+https://github.com/rust-lang/crates.io-index)",
  "pulldown-cmark 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
- "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
@@ -2831,15 +2831,6 @@ dependencies = [
  "xattr 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
-[[package]]
-name = "tempdir"
-version = "0.3.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-dependencies = [
- "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
- "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
-]
-
 [[package]]
 name = "tempfile"
 version = "3.0.2"
@@ -3380,7 +3371,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 "checksum syntex_pos 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)" = "955ef4b16af4c468e4680d1497f873ff288f557d338180649e18f915af5e15ac"
 "checksum syntex_syntax 0.52.0 (registry+https://github.com/rust-lang/crates.io-index)" = "76a302e717e348aa372ff577791c3832395650073b8d8432f8b3cb170b34afde"
 "checksum tar 0.4.15 (registry+https://github.com/rust-lang/crates.io-index)" = "6af6b94659f9a571bf769a5b71f54079393585ee0bfdd71b691be22d7d6b1d18"
-"checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
 "checksum tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "47776f63b85777d984a50ce49d6b9e58826b6a3766a449fc95bc66cd5663c15b"
 "checksum tendril 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9de21546595a0873061940d994bbbc5c35f024ae4fd61ec5c5b159115684f508"
 "checksum term 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "fa63644f74ce96fbeb9b794f66aff2a52d601cbd5e80f4b97123e3899f4570f1"
index ec7eebd1d0189508364b331e15c817029f969719..08bdff364f84be0315e7e10e100bc717eb46dbc5 100644 (file)
@@ -453,6 +453,7 @@ macro_rules! describe {
                 dist::Cargo,
                 dist::Rls,
                 dist::Rustfmt,
+                dist::LlvmTools,
                 dist::Extended,
                 dist::HashSign
             ),
index 11e0b6900b0060f083763ce1378795c718ca0e10..e4d467c9272458b17813452ac9a8ec466cdba9c0 100644 (file)
@@ -88,6 +88,7 @@ pub struct Config {
     pub llvm_link_jobs: Option<u32>,
 
     pub lld_enabled: bool,
+    pub llvm_tools_enabled: bool,
 
     // rust codegen options
     pub rust_optimize: bool,
@@ -309,6 +310,7 @@ struct Rust {
     codegen_backends_dir: Option<String>,
     wasm_syscall: Option<bool>,
     lld: Option<bool>,
+    llvm_tools: Option<bool>,
     deny_warnings: Option<bool>,
     backtrace_on_ice: Option<bool>,
 }
@@ -536,6 +538,7 @@ pub fn parse(args: &[String]) -> Config {
             }
             set(&mut config.wasm_syscall, rust.wasm_syscall);
             set(&mut config.lld_enabled, rust.lld);
+            set(&mut config.llvm_tools_enabled, rust.llvm_tools);
             config.rustc_parallel_queries = rust.experimental_parallel_queries.unwrap_or(false);
             config.rustc_default_linker = rust.default_linker.clone();
             config.musl_root = rust.musl_root.clone().map(PathBuf::from);
index 446db9c0a9e28a7feff8ab5f99a07f3b74bea1fd..80fa96509bd87f2a13cd563ebfd4086fdef2a306 100755 (executable)
@@ -335,6 +335,7 @@ for key in known_args:
     elif option.name == 'full-tools':
         set('rust.codegen-backends', ['llvm', 'emscripten'])
         set('rust.lld', True)
+        set('rust.llvm-tools', True)
         set('build.extended', True)
     elif option.name == 'option-checking':
         # this was handled above
index 7341137e20d721101ac286ad00da1d844d51a607..cbb42a04bdd52a838f2a3433f396193ee6e394c8 100644 (file)
@@ -26,7 +26,7 @@
 
 use build_helper::output;
 
-use {Compiler, Mode};
+use {Compiler, Mode, LLVM_TOOLS};
 use channel;
 use util::{libdir, is_dylib, exe};
 use builder::{Builder, RunConfig, ShouldRun, Step};
@@ -43,6 +43,8 @@ pub fn pkgname(builder: &Builder, component: &str) -> String {
         format!("{}-{}", component, builder.rls_package_vers())
     } else if component == "rustfmt" {
         format!("{}-{}", component, builder.rustfmt_package_vers())
+    } else if component == "llvm-tools" {
+        format!("{}-{}", component, builder.llvm_tools_vers())
     } else {
         assert!(component.starts_with("rust"));
         format!("{}-{}", component, builder.rust_package_vers())
@@ -394,7 +396,7 @@ fn run(self, builder: &Builder) -> PathBuf {
         let compiler = self.compiler;
         let host = self.compiler.host;
 
-        builder.info(&format!("Dist rustc stage{} ({})", compiler.stage, compiler.host));
+        builder.info(&format!("Dist rustc stage{} ({})", compiler.stage, host));
         let name = pkgname(builder, "rustc");
         let image = tmpdir(builder).join(format!("{}-{}-image", name, host));
         let _ = fs::remove_dir_all(&image);
@@ -1738,6 +1740,7 @@ fn run(self, builder: &Builder) {
         cmd.arg(builder.package_vers(&builder.release_num("cargo")));
         cmd.arg(builder.package_vers(&builder.release_num("rls")));
         cmd.arg(builder.package_vers(&builder.release_num("rustfmt")));
+        cmd.arg(builder.llvm_tools_vers());
         cmd.arg(addr);
 
         builder.create_dir(&distdir(builder));
@@ -1748,3 +1751,78 @@ fn run(self, builder: &Builder) {
         assert!(status.success());
     }
 }
+
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub struct LlvmTools {
+    pub stage: u32,
+    pub compiler: Compiler,
+    pub target: Interned<String>,
+}
+
+impl Step for LlvmTools {
+    type Output = Option<PathBuf>;
+    const ONLY_HOSTS: bool = true;
+
+    fn should_run(run: ShouldRun) -> ShouldRun {
+        run.path("llvm-tools")
+    }
+
+    fn make_run(run: RunConfig) {
+        run.builder.ensure(LlvmTools {
+            stage: run.builder.top_stage,
+            compiler: run.builder.compiler(run.builder.top_stage, run.target),
+            target: run.target,
+        });
+    }
+
+    fn run(self, builder: &Builder) -> Option<PathBuf> {
+        let compiler = self.compiler;
+        let host = compiler.host;
+
+        let stage = self.stage;
+        assert!(builder.config.extended);
+
+        builder.info(&format!("Dist LlvmTools stage{} ({})", stage, host));
+        let src = builder.src.join("src/llvm");
+        let name = pkgname(builder, "llvm-tools");
+
+        let tmp = tmpdir(builder);
+        let image = tmp.join("llvm-tools-image");
+        drop(fs::remove_dir_all(&image));
+        t!(fs::create_dir_all(&image.join("bin")));
+
+        // Prepare the image directory
+        for tool in LLVM_TOOLS {
+            let exe = builder
+                .llvm_out(host)
+                .join("bin")
+                .join(exe(tool, &compiler.host));
+            builder.install(&exe, &image.join("bin"), 0o755);
+        }
+
+        // Prepare the overlay
+        let overlay = tmp.join("llvm-tools-overlay");
+        drop(fs::remove_dir_all(&overlay));
+        builder.create_dir(&overlay);
+        builder.install(&src.join("README.txt"), &overlay, 0o644);
+        builder.install(&src.join("LICENSE.TXT"), &overlay, 0o644);
+
+        // Generate the installer tarball
+        let mut cmd = rust_installer(builder);
+        cmd.arg("generate")
+            .arg("--product-name=Rust")
+            .arg("--rel-manifest-dir=rustlib")
+            .arg("--success-message=llvm-tools-installed.")
+            .arg("--image-dir").arg(&image)
+            .arg("--work-dir").arg(&tmpdir(builder))
+            .arg("--output-dir").arg(&distdir(builder))
+            .arg("--non-installed-overlay").arg(&overlay)
+            .arg(format!("--package-name={}-{}", name, host))
+            .arg("--legacy-manifest-dirs=rustlib,cargo")
+            .arg("--component-name=llvm-tools");
+
+
+        builder.run(&mut cmd);
+        Some(distdir(builder).join(format!("{}-{}.tar.gz", name, host)))
+    }
+}
index 6e77413f06188804b5fbb4503d1e0a157052df41..ae37d67e5d7bc8310ccd9af5598be8ce70d00902 100644 (file)
@@ -199,6 +199,14 @@ pub unsafe fn setup(_build: &mut ::Build) {
 use cache::{Interned, INTERNER};
 use toolstate::ToolState;
 
+const LLVM_TOOLS: &[&str] = &[
+    "llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
+    "llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
+    "llvm-objdump", // used to disassemble programs
+    "llvm-profdata", // used to inspect and merge files generated by profiles
+    "llvm-size", // prints the size of the linker sections of a program
+];
+
 /// A structure representing a Rust compiler.
 ///
 /// Each compiler has a `stage` that it is associated with and a `host` that
@@ -965,6 +973,27 @@ fn rustfmt_package_vers(&self) -> String {
         self.package_vers(&self.release_num("rustfmt"))
     }
 
+    fn llvm_tools_vers(&self) -> String {
+        // japaric: should we use LLVM version here?
+        // let stdout = build_helper::output(
+        //     Command::new(self.llvm_out(self.config.build).join("build/bin/llvm-size"))
+        //         .arg("--version"),
+        // );
+
+        // for line in stdout.lines() {
+        //     if line.contains("LLVM version") {
+        //         if let Some(vers) = line.split_whitespace().nth(2) {
+        //             return vers.to_string();
+        //         }
+        //     }
+        // }
+
+        // panic!("The output of $LLVM_TOOL has changed; \
+        //         please fix `bootstrap::Build.llvm_tools_vers`");
+
+        self.rust_version()
+    }
+
     /// Returns the `version` string associated with this compiler for Rust
     /// itself.
     ///
index 93292c658bad251f2d2874ef8bd60e4b5183863e..7dcdbe9c931cf23984fa9816759f51ddac79b098 100644 (file)
@@ -167,8 +167,22 @@ fn run(self, builder: &Builder) -> PathBuf {
         // which saves both memory during parallel links and overall disk space
         // for the tools.  We don't distribute any of those tools, so this is
         // just a local concern.  However, it doesn't work well everywhere.
-        if target.contains("linux-gnu") || target.contains("apple-darwin") {
-           cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
+        //
+        // If we are shipping llvm tools then we statically link them LLVM
+        if (target.contains("linux-gnu") || target.contains("apple-darwin")) &&
+            !builder.config.llvm_tools_enabled {
+                cfg.define("LLVM_LINK_LLVM_DYLIB", "ON");
+        }
+
+        // For distribution we want the LLVM tools to be *statically* linked to libstdc++
+        if builder.config.llvm_tools_enabled {
+            if !target.contains("windows") {
+                if target.contains("apple") {
+                    cfg.define("CMAKE_EXE_LINKER_FLAGS", "-static-libstdc++");
+                } else {
+                    cfg.define("CMAKE_EXE_LINKER_FLAGS", "-Wl,-Bsymbolic -static-libstdc++");
+                }
+            }
         }
 
         if target.contains("msvc") {
index cb233cc84cbed8fd95ddbce645dcabfe35a0cd45..7639537fc553539055e976c897388d278221fce1 100644 (file)
@@ -305,3 +305,27 @@ environment that has no network access.
 compiles, then the test will fail. However please note that code failing
 with the current Rust release may work in a future release, as new features
 are added.
+
+## Syntax reference
+
+The *exact* syntax for code blocks, including the edge cases, can be found
+in the [Fenced Code Blocks](https://spec.commonmark.org/0.28/#fenced-code-blocks)
+section of the CommonMark specification.
+
+Rustdoc also accepts *indented* code blocks as an alternative to fenced
+code blocks: instead of surrounding your code with three backticks, you
+can indent each line by four or more spaces.
+
+``````markdown
+    let foo = "foo";
+    assert_eq!(foo, "foo");
+``````
+
+These, too, are documented in the CommonMark specification, in the
+[Indented Code Blocks](https://spec.commonmark.org/0.28/#indented-code-blocks)
+section.
+
+However, it's preferable to use fenced code blocks over indented code blocks.
+Not only are fenced code blocks considered more idiomatic for Rust code,
+but there is no way to use directives such as `ignore` or `should_panic` with
+indented code blocks.
index 04c8063ffebc5dbc613fab0bfc48f9d35b80c16a..84bd275df347c9c73b376c37e900ff3212be6900 100644 (file)
@@ -158,7 +158,7 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
         if !ptr.is_null() {
             ptr
         } else {
-            oom(layout)
+            handle_alloc_error(layout)
         }
     }
 }
@@ -184,13 +184,13 @@ pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
 ///
 /// The default behavior of this function is to print a message to standard error
 /// and abort the process.
-/// It can be replaced with [`set_oom_hook`] and [`take_oom_hook`].
+/// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
 ///
-/// [`set_oom_hook`]: ../../std/alloc/fn.set_oom_hook.html
-/// [`take_oom_hook`]: ../../std/alloc/fn.take_oom_hook.html
+/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
+/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
 #[stable(feature = "global_alloc", since = "1.28.0")]
 #[rustc_allocator_nounwind]
-pub fn oom(layout: Layout) -> ! {
+pub fn handle_alloc_error(layout: Layout) -> ! {
     #[allow(improper_ctypes)]
     extern "Rust" {
         #[lang = "oom"]
@@ -204,14 +204,14 @@ mod tests {
     extern crate test;
     use self::test::Bencher;
     use boxed::Box;
-    use alloc::{Global, Alloc, Layout, oom};
+    use alloc::{Global, Alloc, Layout, handle_alloc_error};
 
     #[test]
     fn allocate_zeroed() {
         unsafe {
             let layout = Layout::from_size_align(1024, 1).unwrap();
             let ptr = Global.alloc_zeroed(layout.clone())
-                .unwrap_or_else(|_| oom(layout));
+                .unwrap_or_else(|_| handle_alloc_error(layout));
 
             let mut i = ptr.cast::<u8>().as_ptr();
             let end = i.offset(layout.size() as isize);
index e3369f0a5b5bf52524b6e11d7e211ffdc4ac3f7c..0fbd1408f644f9e3f2da1e0e709ec8509d182738 100644 (file)
@@ -32,7 +32,7 @@
 use core::{isize, usize};
 use core::convert::From;
 
-use alloc::{Global, Alloc, Layout, box_free, oom};
+use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
 use boxed::Box;
 use string::String;
 use vec::Vec;
@@ -554,7 +554,7 @@ unsafe fn allocate_for_ptr(ptr: *const T) -> *mut ArcInner<T> {
         let layout = Layout::for_value(&*fake_ptr);
 
         let mem = Global.alloc(layout)
-            .unwrap_or_else(|_| oom(layout));
+            .unwrap_or_else(|_| handle_alloc_error(layout));
 
         // Initialize the real ArcInner
         let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut ArcInner<T>;
index d1f140e96a3ae45c456a4a25211f289c17bc0f9b..2369ce648fda56ee64d5b92a097d9d7be7c25748 100644 (file)
@@ -14,7 +14,7 @@
 use core::ptr::{self, NonNull, Unique};
 use core::slice;
 
-use alloc::{Alloc, Layout, Global, oom};
+use alloc::{Alloc, Layout, Global, handle_alloc_error};
 use alloc::CollectionAllocErr;
 use alloc::CollectionAllocErr::*;
 use boxed::Box;
@@ -104,7 +104,7 @@ fn allocate_in(cap: usize, zeroed: bool, mut a: A) -> Self {
                 };
                 match result {
                     Ok(ptr) => ptr.cast(),
-                    Err(_) => oom(layout),
+                    Err(_) => handle_alloc_error(layout),
                 }
             };
 
@@ -319,7 +319,9 @@ pub fn double(&mut self) {
                                                  new_size);
                     match ptr_res {
                         Ok(ptr) => (new_cap, ptr.cast().into()),
-                        Err(_) => oom(Layout::from_size_align_unchecked(new_size, cur.align())),
+                        Err(_) => handle_alloc_error(
+                            Layout::from_size_align_unchecked(new_size, cur.align())
+                        ),
                     }
                 }
                 None => {
@@ -328,7 +330,7 @@ pub fn double(&mut self) {
                     let new_cap = if elem_size > (!0) / 8 { 1 } else { 4 };
                     match self.a.alloc_array::<T>(new_cap) {
                         Ok(ptr) => (new_cap, ptr.into()),
-                        Err(_) => oom(Layout::array::<T>(new_cap).unwrap()),
+                        Err(_) => handle_alloc_error(Layout::array::<T>(new_cap).unwrap()),
                     }
                 }
             };
@@ -611,7 +613,9 @@ pub fn shrink_to_fit(&mut self, amount: usize) {
                                      old_layout,
                                      new_size) {
                     Ok(p) => self.ptr = p.cast().into(),
-                    Err(_) => oom(Layout::from_size_align_unchecked(new_size, align)),
+                    Err(_) => handle_alloc_error(
+                        Layout::from_size_align_unchecked(new_size, align)
+                    ),
                 }
             }
             self.cap = amount;
@@ -673,7 +677,7 @@ fn reserve_internal(
             };
 
             match (&res, fallibility) {
-                (Err(AllocErr), Infallible) => oom(new_layout),
+                (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
                 _ => {}
             }
 
index 84a6ecf710399d0f0fc923101da92599f7e567c4..32d624e8fbc7942f32660a2275a4ba8ec72ef43c 100644 (file)
 use core::ptr::{self, NonNull};
 use core::convert::From;
 
-use alloc::{Global, Alloc, Layout, box_free, oom};
+use alloc::{Global, Alloc, Layout, box_free, handle_alloc_error};
 use string::String;
 use vec::Vec;
 
@@ -662,7 +662,7 @@ unsafe fn allocate_for_ptr(ptr: *const T) -> *mut RcBox<T> {
         let layout = Layout::for_value(&*fake_ptr);
 
         let mem = Global.alloc(layout)
-            .unwrap_or_else(|_| oom(layout));
+            .unwrap_or_else(|_| handle_alloc_error(layout));
 
         // Initialize the real RcBox
         let inner = set_data_ptr(ptr as *mut T, mem.as_ptr() as *mut u8) as *mut RcBox<T>;
index b5739e1a825538ceffa016bd3f2a550d5e39ae28..752a6c966d51a35bcd4de701b6055f640255d4f9 100644 (file)
@@ -1693,7 +1693,10 @@ fn hash<H: hash::Hasher>(&self, state: &mut H) {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented = "vector indices are of type `usize` or ranges of `usize`"]
+#[rustc_on_unimplemented(
+    message="vector indices are of type `usize` or ranges of `usize`",
+    label="vector indices are of type `usize` or ranges of `usize`",
+)]
 impl<T, I> Index<I> for Vec<T>
 where
     I: ::core::slice::SliceIndex<[T]>,
@@ -1707,7 +1710,10 @@ fn index(&self, index: I) -> &Self::Output {
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented = "vector indices are of type `usize` or ranges of `usize`"]
+#[rustc_on_unimplemented(
+    message="vector indices are of type `usize` or ranges of `usize`",
+    label="vector indices are of type `usize` or ranges of `usize`",
+)]
 impl<T, I> IndexMut<I> for Vec<T>
 where
     I: ::core::slice::SliceIndex<[T]>,
index 353688d1b85583bd3b2f18e23049aee16872e062..0c074582281d6414617a30050bd82d5a20290160 100644 (file)
@@ -492,10 +492,10 @@ pub unsafe trait GlobalAlloc {
     /// library that aborts on memory exhaustion.)
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     #[stable(feature = "global_alloc", since = "1.28.0")]
     unsafe fn alloc(&self, layout: Layout) -> *mut u8;
 
@@ -529,10 +529,10 @@ pub unsafe trait GlobalAlloc {
     /// just as in `alloc`.
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     #[stable(feature = "global_alloc", since = "1.28.0")]
     unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
         let size = layout.size();
@@ -589,10 +589,10 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
     /// library that aborts on memory exhaustion.)
     ///
     /// Clients wishing to abort computation in response to a
-    /// reallocation error are encouraged to call the [`oom`] function,
+    /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     #[stable(feature = "global_alloc", since = "1.28.0")]
     unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
         let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
@@ -733,10 +733,10 @@ pub unsafe trait Alloc {
     /// library that aborts on memory exhaustion.)
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr>;
 
     /// Deallocate the memory referenced by `ptr`.
@@ -843,10 +843,10 @@ fn usable_size(&self, layout: &Layout) -> (usize, usize) {
     /// library that aborts on memory exhaustion.)
     ///
     /// Clients wishing to abort computation in response to a
-    /// reallocation error are encouraged to call the [`oom`] function,
+    /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn realloc(&mut self,
                       ptr: NonNull<u8>,
                       layout: Layout,
@@ -889,10 +889,10 @@ unsafe fn realloc(&mut self,
     /// constraints, just as in `alloc`.
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
         let size = layout.size();
         let p = self.alloc(layout);
@@ -917,10 +917,10 @@ unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocEr
     /// constraints, just as in `alloc`.
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
         let usable_size = self.usable_size(&layout);
         self.alloc(layout).map(|p| Excess(p, usable_size.1))
@@ -941,10 +941,10 @@ unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
     /// constraints, just as in `realloc`.
     ///
     /// Clients wishing to abort computation in response to a
-    /// reallocation error are encouraged to call the [`oom`] function,
+    /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn realloc_excess(&mut self,
                              ptr: NonNull<u8>,
                              layout: Layout,
@@ -986,7 +986,7 @@ unsafe fn realloc_excess(&mut self,
     /// unable to assert that the memory block referenced by `ptr`
     /// could fit `layout`.
     ///
-    /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
+    /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
     /// function; clients are expected either to be able to recover from
     /// `grow_in_place` failures without aborting, or to fall back on
     /// another reallocation method before resorting to an abort.
@@ -1041,7 +1041,7 @@ unsafe fn grow_in_place(&mut self,
     /// unable to assert that the memory block referenced by `ptr`
     /// could fit `layout`.
     ///
-    /// Note that one cannot pass `CannotReallocInPlace` to the `oom`
+    /// Note that one cannot pass `CannotReallocInPlace` to the `handle_alloc_error`
     /// function; clients are expected either to be able to recover from
     /// `shrink_in_place` failures without aborting, or to fall back
     /// on another reallocation method before resorting to an abort.
@@ -1090,10 +1090,10 @@ unsafe fn shrink_in_place(&mut self,
     /// will *not* yield undefined behavior.
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     fn alloc_one<T>(&mut self) -> Result<NonNull<T>, AllocErr>
         where Self: Sized
     {
@@ -1159,10 +1159,10 @@ unsafe fn dealloc_one<T>(&mut self, ptr: NonNull<T>)
     /// Always returns `Err` on arithmetic overflow.
     ///
     /// Clients wishing to abort computation in response to an
-    /// allocation error are encouraged to call the [`oom`] function,
+    /// allocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
         where Self: Sized
     {
@@ -1206,10 +1206,10 @@ fn alloc_array<T>(&mut self, n: usize) -> Result<NonNull<T>, AllocErr>
     /// Always returns `Err` on arithmetic overflow.
     ///
     /// Clients wishing to abort computation in response to a
-    /// reallocation error are encouraged to call the [`oom`] function,
+    /// reallocation error are encouraged to call the [`handle_alloc_error`] function,
     /// rather than directly invoking `panic!` or similar.
     ///
-    /// [`oom`]: ../../alloc/alloc/fn.oom.html
+    /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
     unsafe fn realloc_array<T>(&mut self,
                                ptr: NonNull<T>,
                                n_old: usize,
index 13e838773a5875faf0a0da4117644d9f45776c94..3626a266ad5d3f0d86cd059ede2c21fbae92c816 100644 (file)
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(alias = "==")]
 #[doc(alias = "!=")]
-#[rustc_on_unimplemented = "can't compare `{Self}` with `{Rhs}`"]
+#[rustc_on_unimplemented(
+    message="can't compare `{Self}` with `{Rhs}`",
+    label="no implementation for `{Self} == {Rhs}`",
+)]
 pub trait PartialEq<Rhs: ?Sized = Self> {
     /// This method tests for `self` and `other` values to be equal, and is used
     /// by `==`.
@@ -611,7 +614,10 @@ fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
 #[doc(alias = "<")]
 #[doc(alias = "<=")]
 #[doc(alias = ">=")]
-#[rustc_on_unimplemented = "can't compare `{Self}` with `{Rhs}`"]
+#[rustc_on_unimplemented(
+    message="can't compare `{Self}` with `{Rhs}`",
+    label="no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`",
+)]
 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
     /// This method returns an ordering between `self` and `other` values if one exists.
     ///
index 840d45ff1cc15847e52c00040aec606e0a8e0282..c4132270d5923664cfc69a1467d54e27a73ffd1a 100644 (file)
 use cmp;
 use fmt;
 use iter_private::TrustedRandomAccess;
-use ops::Try;
+use ops::{self, Try};
 use usize;
 use intrinsics;
+use mem;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 pub use self::iterator::Iterator;
@@ -672,12 +673,7 @@ impl<I> Iterator for StepBy<I> where I: Iterator {
 
     #[inline]
     fn next(&mut self) -> Option<Self::Item> {
-        if self.first_take {
-            self.first_take = false;
-            self.iter.next()
-        } else {
-            self.iter.nth(self.step)
-        }
+        <Self as StepBySpecIterator>::spec_next(self)
     }
 
     #[inline]
@@ -737,6 +733,76 @@ fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
     }
 }
 
+// hidden trait for specializing iterator methods
+// could be generalized but is currently only used for StepBy
+trait StepBySpecIterator {
+    type Item;
+    fn spec_next(&mut self) -> Option<Self::Item>;
+}
+
+impl<I> StepBySpecIterator for StepBy<I>
+where
+    I: Iterator,
+{
+    type Item = I::Item;
+
+    #[inline]
+    default fn spec_next(&mut self) -> Option<I::Item> {
+        if self.first_take {
+            self.first_take = false;
+            self.iter.next()
+        } else {
+            self.iter.nth(self.step)
+        }
+    }
+}
+
+impl<T> StepBySpecIterator for StepBy<ops::Range<T>>
+where
+    T: Step,
+{
+    #[inline]
+    fn spec_next(&mut self) -> Option<Self::Item> {
+        self.first_take = false;
+        if !(self.iter.start < self.iter.end) {
+            return None;
+        }
+        // add 1 to self.step to get original step size back
+        // it was decremented for the general case on construction
+        if let Some(n) = self.iter.start.add_usize(self.step+1) {
+            let next = mem::replace(&mut self.iter.start, n);
+            Some(next)
+        } else {
+            let last = self.iter.start.clone();
+            self.iter.start = self.iter.end.clone();
+            Some(last)
+        }
+    }
+}
+
+impl<T> StepBySpecIterator for StepBy<ops::RangeInclusive<T>>
+where
+    T: Step,
+{
+    #[inline]
+    fn spec_next(&mut self) -> Option<Self::Item> {
+        self.first_take = false;
+        if !(self.iter.start <= self.iter.end) {
+            return None;
+        }
+        // add 1 to self.step to get original step size back
+        // it was decremented for the general case on construction
+        if let Some(n) = self.iter.start.add_usize(self.step+1) {
+            let next = mem::replace(&mut self.iter.start, n);
+            Some(next)
+        } else {
+            let last = self.iter.start.replace_one();
+            self.iter.end.replace_zero();
+            Some(last)
+        }
+    }
+}
+
 // StepBy can only make the iterator shorter, so the len will still fit.
 #[stable(feature = "iterator_step_by", since = "1.28.0")]
 impl<I> ExactSizeIterator for StepBy<I> where I: ExactSizeIterator {}
index 3d2ce9e6b104bc9aae32559816e10a81eb9bf9bb..4b2c1aa551e994ad7470de7480abea31edb20e42 100644 (file)
 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
 /// ```
 #[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
-                          built from an iterator over elements of type `{A}`"]
+#[rustc_on_unimplemented(
+    message="a collection of type `{Self}` cannot be built from an iterator \
+             over elements of type `{A}`",
+    label="a collection of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`",
+)]
 pub trait FromIterator<A>: Sized {
     /// Creates a value from an iterator.
     ///
index 3d3f63ecf37d57e1c5eb46ca640ef449ef336ab2..5db5d88d4a5ff9bc2e3036ba5e9d1ecb46ed7c7b 100644 (file)
 /// [arc]: ../../std/sync/struct.Arc.html
 /// [ub]: ../../reference/behavior-considered-undefined.html
 #[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
+#[rustc_on_unimplemented(
+    message="`{Self}` cannot be sent between threads safely",
+    label="`{Self}` cannot be sent between threads safely"
+)]
 pub unsafe auto trait Send {
     // empty.
 }
@@ -88,7 +91,12 @@ impl<T: ?Sized> !Send for *mut T { }
 /// [trait object]: ../../book/first-edition/trait-objects.html
 #[stable(feature = "rust1", since = "1.0.0")]
 #[lang = "sized"]
-#[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
+#[rustc_on_unimplemented(
+    message="the size for value values of type `{Self}` cannot be known at compilation time",
+    label="doesn't have a size known at compile-time",
+    note="to learn more, visit <https://doc.rust-lang.org/book/second-edition/\
+          ch19-04-advanced-types.html#dynamically-sized-types--sized>",
+)]
 #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable
 pub trait Sized {
     // Empty.
index 0a0e92a91800614a75608bd7099eb2e4fe79ab54..1ac80ecc96ffeb775cd6fc3ffc2d52f018aacbb2 100644 (file)
 /// assert_eq!(nucleotide_count[Nucleotide::T], 12);
 /// ```
 #[lang = "index"]
-#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
+#[rustc_on_unimplemented(
+    message="the type `{Self}` cannot be indexed by `{Idx}`",
+    label="`{Self}` cannot be indexed by `{Idx}`",
+)]
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(alias = "]")]
 #[doc(alias = "[")]
@@ -147,7 +150,10 @@ pub trait Index<Idx: ?Sized> {
 /// balance[Side::Left] = Weight::Kilogram(3.0);
 /// ```
 #[lang = "index_mut"]
-#[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"]
+#[rustc_on_unimplemented(
+    message="the type `{Self}` cannot be mutably indexed by `{Idx}`",
+    label="`{Self}` cannot be mutably indexed by `{Idx}`",
+)]
 #[stable(feature = "rust1", since = "1.0.0")]
 #[doc(alias = "[")]
 #[doc(alias = "]")]
index 9b8d7031f8e7507d7cfacbbc89deef69637a84ec..72b115f8b5f7705c6ee97a32921624e5011fff46 100644 (file)
@@ -1618,6 +1618,14 @@ fn test_range_step() {
     assert_eq!((isize::MIN..isize::MAX).step_by(1).size_hint(), (usize::MAX, Some(usize::MAX)));
 }
 
+#[test]
+fn test_range_inclusive_step() {
+    assert_eq!((0..=50).step_by(10).collect::<Vec<_>>(), [0, 10, 20, 30, 40, 50]);
+    assert_eq!((0..=5).step_by(1).collect::<Vec<_>>(), [0, 1, 2, 3, 4, 5]);
+    assert_eq!((200..=255u8).step_by(10).collect::<Vec<_>>(), [200, 210, 220, 230, 240, 250]);
+    assert_eq!((250..=255u8).step_by(1).collect::<Vec<_>>(), [250, 251, 252, 253, 254, 255]);
+}
+
 #[test]
 fn test_range_last_max() {
     assert_eq!((0..20).last(), Some(19));
index 0ff4dc2eace816f45e55c43f1a380339108ba511..457a9f2f625ec1eb5d433828989f252227c35753 100644 (file)
@@ -61,6 +61,4 @@ chalk-engine = { version = "0.6.0", default-features=false }
 #        later crate stop compiling. If you can remove this and everything
 #        compiles, then please feel free to do so!
 flate2 = "1.0"
-tempdir = "0.3"
-
-
+tempfile = "3.0"
index 12ccb329e06ff2cd541b0ae6b3c6c325f4cde16f..ed86ef705649b651de8f718032c5f3cdb615c8cf 100644 (file)
@@ -314,8 +314,8 @@ fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) {
     fn visit_trait_ref(&mut self, t: &'v TraitRef) {
         walk_trait_ref(self, t)
     }
-    fn visit_ty_param_bound(&mut self, bounds: &'v TyParamBound) {
-        walk_ty_param_bound(self, bounds)
+    fn visit_param_bound(&mut self, bounds: &'v GenericBound) {
+        walk_param_bound(self, bounds)
     }
     fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) {
         walk_poly_trait_ref(self, t, m)
@@ -344,6 +344,12 @@ fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics, item_id: NodeId) {
     fn visit_label(&mut self, label: &'v Label) {
         walk_label(self, label)
     }
+    fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg) {
+        match generic_arg {
+            GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
+            GenericArg::Type(ty) => self.visit_ty(ty),
+        }
+    }
     fn visit_lifetime(&mut self, lifetime: &'v Lifetime) {
         walk_lifetime(self, lifetime)
     }
@@ -356,8 +362,8 @@ fn visit_path(&mut self, path: &'v Path, _id: NodeId) {
     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) {
         walk_path_segment(self, path_span, path_segment)
     }
-    fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'v PathParameters) {
-        walk_path_parameters(self, path_span, path_parameters)
+    fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs) {
+        walk_generic_args(self, path_span, generic_args)
     }
     fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding) {
         walk_assoc_type_binding(self, type_binding)
@@ -427,10 +433,10 @@ pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) {
 pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) {
     visitor.visit_id(lifetime.id);
     match lifetime.name {
-        LifetimeName::Name(name) => {
+        LifetimeName::Param(ParamName::Plain(name)) => {
             visitor.visit_name(lifetime.span, name);
         }
-        LifetimeName::Fresh(_) |
+        LifetimeName::Param(ParamName::Fresh(_)) |
         LifetimeName::Static |
         LifetimeName::Implicit |
         LifetimeName::Underscore => {}
@@ -505,7 +511,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) {
         ItemExistential(ExistTy {ref generics, ref bounds, impl_trait_fn}) => {
             visitor.visit_id(item.id);
             walk_generics(visitor, generics);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             if let Some(impl_trait_fn) = impl_trait_fn {
                 visitor.visit_def_mention(Def::Fn(impl_trait_fn))
             }
@@ -531,13 +537,13 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) {
         ItemTrait(.., ref generics, ref bounds, ref trait_item_refs) => {
             visitor.visit_id(item.id);
             visitor.visit_generics(generics);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_trait_item_ref, trait_item_refs);
         }
         ItemTraitAlias(ref generics, ref bounds) => {
             visitor.visit_id(item.id);
             visitor.visit_generics(generics);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
         }
     }
     walk_list!(visitor, visit_attribute, &item.attrs);
@@ -642,17 +648,16 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V,
                                              path_span: Span,
                                              segment: &'v PathSegment) {
     visitor.visit_name(path_span, segment.name);
-    if let Some(ref parameters) = segment.parameters {
-        visitor.visit_path_parameters(path_span, parameters);
+    if let Some(ref args) = segment.args {
+        visitor.visit_generic_args(path_span, args);
     }
 }
 
-pub fn walk_path_parameters<'v, V: Visitor<'v>>(visitor: &mut V,
-                                                _path_span: Span,
-                                                path_parameters: &'v PathParameters) {
-    walk_list!(visitor, visit_lifetime, &path_parameters.lifetimes);
-    walk_list!(visitor, visit_ty, &path_parameters.types);
-    walk_list!(visitor, visit_assoc_type_binding, &path_parameters.bindings);
+pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V,
+                                             _path_span: Span,
+                                             generic_args: &'v GenericArgs) {
+    walk_list!(visitor, visit_generic_arg, &generic_args.args);
+    walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings);
 }
 
 pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V,
@@ -726,40 +731,27 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v
     walk_list!(visitor, visit_attribute, &foreign_item.attrs);
 }
 
-pub fn walk_ty_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v TyParamBound) {
+pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound) {
     match *bound {
-        TraitTyParamBound(ref typ, modifier) => {
+        GenericBound::Trait(ref typ, modifier) => {
             visitor.visit_poly_trait_ref(typ, modifier);
         }
-        RegionTyParamBound(ref lifetime) => {
-            visitor.visit_lifetime(lifetime);
-        }
+        GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime),
     }
 }
 
 pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) {
-    match *param {
-        GenericParam::Lifetime(ref ld) => {
-            visitor.visit_id(ld.lifetime.id);
-            match ld.lifetime.name {
-                LifetimeName::Name(name) => {
-                    visitor.visit_name(ld.lifetime.span, name);
-                }
-                LifetimeName::Fresh(_) |
-                LifetimeName::Static |
-                LifetimeName::Implicit |
-                LifetimeName::Underscore => {}
-            }
-            walk_list!(visitor, visit_lifetime, &ld.bounds);
-        }
-        GenericParam::Type(ref ty_param) => {
-            visitor.visit_id(ty_param.id);
-            visitor.visit_name(ty_param.span, ty_param.name);
-            walk_list!(visitor, visit_ty_param_bound, &ty_param.bounds);
-            walk_list!(visitor, visit_ty, &ty_param.default);
-            walk_list!(visitor, visit_attribute, ty_param.attrs.iter());
-        }
+    visitor.visit_id(param.id);
+    walk_list!(visitor, visit_attribute, &param.attrs);
+    match param.name {
+        ParamName::Plain(name) => visitor.visit_name(param.span, name),
+        ParamName::Fresh(_) => {}
+    }
+    match param.kind {
+        GenericParamKind::Lifetime { .. } => {}
+        GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default),
     }
+    walk_list!(visitor, visit_param_bound, &param.bounds);
 }
 
 pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
@@ -778,14 +770,14 @@ pub fn walk_where_predicate<'v, V: Visitor<'v>>(
                                                             ref bound_generic_params,
                                                             ..}) => {
             visitor.visit_ty(bounded_ty);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_generic_param, bound_generic_params);
         }
         &WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime,
                                                               ref bounds,
                                                               ..}) => {
             visitor.visit_lifetime(lifetime);
-            walk_list!(visitor, visit_lifetime, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
         }
         &WherePredicate::EqPredicate(WhereEqPredicate{id,
                                                       ref lhs_ty,
@@ -862,7 +854,7 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai
         }
         TraitItemKind::Type(ref bounds, ref default) => {
             visitor.visit_id(trait_item.id);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_ty, default);
         }
     }
index dd12edb73027a39e72cb727e362207c0cb128754..6291e0eb113728dc8a8711baec6e7dfe5f7f3ca2 100644 (file)
 //! in the HIR, especially for multiple identifiers.
 
 use dep_graph::DepGraph;
-use hir;
+use hir::{self, ParamName};
 use hir::HirVec;
 use hir::map::{DefKey, DefPathData, Definitions};
 use hir::def_id::{DefId, DefIndex, DefIndexAddressSpace, CRATE_DEF_INDEX};
 use hir::def::{Def, PathResolution, PerNS};
+use hir::GenericArg;
 use lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES};
 use middle::cstore::CrateStore;
 use rustc_data_structures::indexed_vec::IndexVec;
@@ -58,6 +59,7 @@
 use std::iter;
 use std::mem;
 use syntax::attr;
+use syntax::ast;
 use syntax::ast::*;
 use syntax::errors;
 use syntax::ext::hygiene::{Mark, SyntaxContext};
@@ -114,7 +116,7 @@ pub struct LoweringContext<'a> {
     // When traversing a signature such as `fn foo(x: impl Trait)`,
     // we record `impl Trait` as a new type parameter, then later
     // add it on to `foo`s generics.
-    in_band_ty_params: Vec<hir::TyParam>,
+    in_band_ty_params: Vec<hir::GenericParam>,
 
     // Used to create lifetime definitions from in-band lifetime usages.
     // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8`
@@ -123,7 +125,7 @@ pub struct LoweringContext<'a> {
     // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added
     // to this list. The results of this list are then added to the list of
     // lifetime definitions in the corresponding impl or function generics.
-    lifetimes_to_define: Vec<(Span, hir::LifetimeName)>,
+    lifetimes_to_define: Vec<(Span, ParamName)>,
 
     // Whether or not in-band lifetimes are being collected. This is used to
     // indicate whether or not we're in a place where new lifetimes will result
@@ -322,7 +324,10 @@ fn visit_item(&mut self, item: &'lcx Item) {
                         let count = generics
                             .params
                             .iter()
-                            .filter(|param| param.is_lifetime_param())
+                            .filter(|param| match param.kind {
+                                ast::GenericParamKind::Lifetime { .. } => true,
+                                _ => false,
+                            })
                             .count();
                         self.lctx.type_def_lifetime_params.insert(def_id, count);
                     }
@@ -374,25 +379,24 @@ fn visit_item(&mut self, item: &'lcx Item) {
                 });
 
                 if item_lowered {
-                    let item_lifetimes = match self.lctx.items.get(&item.id).unwrap().node {
+                    let item_generics = match self.lctx.items.get(&item.id).unwrap().node {
                         hir::Item_::ItemImpl(_, _, _, ref generics, ..)
                         | hir::Item_::ItemTrait(_, _, ref generics, ..) => {
-                            generics.lifetimes().cloned().collect::<Vec<_>>()
+                            generics.params.clone()
                         }
-                        _ => Vec::new(),
+                        _ => HirVec::new(),
                     };
 
-                    self.lctx
-                        .with_parent_impl_lifetime_defs(&item_lifetimes, |this| {
-                            let this = &mut ItemLowerer { lctx: this };
-                            if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
-                                this.with_trait_impl_ref(opt_trait_ref, |this| {
-                                    visit::walk_item(this, item)
-                                });
-                            } else {
-                                visit::walk_item(this, item);
-                            }
-                        });
+                    self.lctx.with_parent_impl_lifetime_defs(&item_generics, |this| {
+                        let this = &mut ItemLowerer { lctx: this };
+                        if let ItemKind::Impl(_, _, _, _, ref opt_trait_ref, _, _) = item.node {
+                            this.with_trait_impl_ref(opt_trait_ref, |this| {
+                                visit::walk_item(this, item)
+                            });
+                        } else {
+                            visit::walk_item(this, item);
+                        }
+                    });
                 }
             }
 
@@ -674,41 +678,31 @@ fn collect_in_band_defs<T, F>(
                 // that collisions are ok here and this shouldn't
                 // really show up for end-user.
                 let str_name = match hir_name {
-                    hir::LifetimeName::Name(n) => n.as_str(),
-                    hir::LifetimeName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
-                    hir::LifetimeName::Implicit
-                    | hir::LifetimeName::Underscore
-                    | hir::LifetimeName::Static => {
-                        span_bug!(span, "unexpected in-band lifetime name: {:?}", hir_name)
-                    }
+                    ParamName::Plain(name) => name.as_str(),
+                    ParamName::Fresh(_) => keywords::UnderscoreLifetime.name().as_str(),
                 };
 
                 // Add a definition for the in-band lifetime def
                 self.resolver.definitions().create_def_with_parent(
                     parent_id.index,
                     def_node_id,
-                    DefPathData::LifetimeDef(str_name.as_interned_str()),
+                    DefPathData::LifetimeParam(str_name.as_interned_str()),
                     DefIndexAddressSpace::High,
                     Mark::root(),
                     span,
                 );
 
-                hir::GenericParam::Lifetime(hir::LifetimeDef {
-                    lifetime: hir::Lifetime {
-                        id: def_node_id,
-                        span,
-                        name: hir_name,
-                    },
-                    bounds: Vec::new().into(),
+                hir::GenericParam {
+                    id: def_node_id,
+                    name: hir_name,
+                    attrs: hir_vec![],
+                    bounds: hir_vec![],
+                    span,
                     pure_wrt_drop: false,
-                    in_band: true,
-                })
+                    kind: hir::GenericParamKind::Lifetime { in_band: true }
+                }
             })
-            .chain(
-                in_band_ty_params
-                    .into_iter()
-                    .map(|tp| hir::GenericParam::Type(tp)),
-            )
+            .chain(in_band_ty_params.into_iter())
             .collect();
 
         (params, res)
@@ -727,12 +721,9 @@ fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
             return;
         }
 
-        let hir_name = hir::LifetimeName::Name(name);
+        let hir_name = ParamName::Plain(name);
 
-        if self.lifetimes_to_define
-            .iter()
-            .any(|(_, lt_name)| *lt_name == hir_name)
-        {
+        if self.lifetimes_to_define.iter().any(|(_, lt_name)| *lt_name == hir_name) {
             return;
         }
 
@@ -741,28 +732,27 @@ fn maybe_collect_in_band_lifetime(&mut self, span: Span, name: Name) {
 
     /// When we have either an elided or `'_` lifetime in an impl
     /// header, we convert it to
-    fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> hir::LifetimeName {
+    fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName {
         assert!(self.is_collecting_in_band_lifetimes);
         let index = self.lifetimes_to_define.len();
-        let hir_name = hir::LifetimeName::Fresh(index);
+        let hir_name = ParamName::Fresh(index);
         self.lifetimes_to_define.push((span, hir_name));
         hir_name
     }
 
-    // Evaluates `f` with the lifetimes in `lt_defs` in-scope.
+    // Evaluates `f` with the lifetimes in `params` in-scope.
     // This is used to track which lifetimes have already been defined, and
     // which are new in-band lifetimes that need to have a definition created
     // for them.
-    fn with_in_scope_lifetime_defs<'l, T, F>(
-        &mut self,
-        lt_defs: impl Iterator<Item = &'l LifetimeDef>,
-        f: F,
-    ) -> T
+    fn with_in_scope_lifetime_defs<T, F>(&mut self, params: &Vec<GenericParam>, f: F) -> T
     where
         F: FnOnce(&mut LoweringContext) -> T,
     {
         let old_len = self.in_scope_lifetimes.len();
-        let lt_def_names = lt_defs.map(|lt_def| lt_def.lifetime.ident.name);
+        let lt_def_names = params.iter().filter_map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => Some(param.ident.name),
+            _ => None,
+        });
         self.in_scope_lifetimes.extend(lt_def_names);
 
         let res = f(self);
@@ -771,17 +761,22 @@ fn with_in_scope_lifetime_defs<'l, T, F>(
         res
     }
 
-    // Same as the method above, but accepts `hir::LifetimeDef`s
-    // instead of `ast::LifetimeDef`s.
+    // Same as the method above, but accepts `hir::GenericParam`s
+    // instead of `ast::GenericParam`s.
     // This should only be used with generics that have already had their
     // in-band lifetimes added. In practice, this means that this function is
     // only used when lowering a child item of a trait or impl.
-    fn with_parent_impl_lifetime_defs<T, F>(&mut self, lt_defs: &[hir::LifetimeDef], f: F) -> T
-    where
+    fn with_parent_impl_lifetime_defs<T, F>(&mut self,
+        params: &HirVec<hir::GenericParam>,
+        f: F
+    ) -> T where
         F: FnOnce(&mut LoweringContext) -> T,
     {
         let old_len = self.in_scope_lifetimes.len();
-        let lt_def_names = lt_defs.iter().map(|lt_def| lt_def.lifetime.name.name());
+        let lt_def_names = params.iter().filter_map(|param| match param.kind {
+            hir::GenericParamKind::Lifetime { .. } => Some(param.name.name()),
+            _ => None,
+        });
         self.in_scope_lifetimes.extend(lt_def_names);
 
         let res = f(self);
@@ -807,10 +802,7 @@ fn add_in_band_defs<F, T>(
         F: FnOnce(&mut LoweringContext) -> T,
     {
         let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs(
-            generics.params.iter().filter_map(|p| match p {
-                GenericParam::Lifetime(ld) => Some(ld),
-                _ => None,
-            }),
+            &generics.params,
             |this| {
                 let itctx = ImplTraitContext::Universal(parent_id);
                 this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
@@ -1037,6 +1029,16 @@ fn lower_ty_binding(&mut self, b: &TypeBinding, itctx: ImplTraitContext) -> hir:
         }
     }
 
+    fn lower_generic_arg(&mut self,
+                        arg: &ast::GenericArg,
+                        itctx: ImplTraitContext)
+                        -> hir::GenericArg {
+        match arg {
+            ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
+            ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty(&ty, itctx)),
+        }
+    }
+
     fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
         let kind = match t.node {
             TyKind::Infer => hir::TyInfer,
@@ -1052,10 +1054,7 @@ fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
                 hir::TyRptr(lifetime, self.lower_mt(mt, itctx))
             }
             TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(
-                f.generic_params.iter().filter_map(|p| match p {
-                    GenericParam::Lifetime(ld) => Some(ld),
-                    _ => None,
-                }),
+                &f.generic_params,
                 |this| {
                     this.with_anonymous_lifetime_mode(
                         AnonymousLifetimeMode::PassThrough,
@@ -1110,11 +1109,11 @@ fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
                 let bounds = bounds
                     .iter()
                     .filter_map(|bound| match *bound {
-                        TraitTyParamBound(ref ty, TraitBoundModifier::None) => {
+                        GenericBound::Trait(ref ty, TraitBoundModifier::None) => {
                             Some(self.lower_poly_trait_ref(ty, itctx))
                         }
-                        TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
-                        RegionTyParamBound(ref lifetime) => {
+                        GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
+                        GenericBound::Outlives(ref lifetime) => {
                             if lifetime_bound.is_none() {
                                 lifetime_bound = Some(self.lower_lifetime(lifetime));
                             }
@@ -1166,7 +1165,7 @@ fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
                         self.allocate_hir_id_counter(exist_ty_node_id, t);
 
                         let hir_bounds = self.with_hir_id_owner(exist_ty_node_id, |lctx| {
-                            lctx.lower_bounds(bounds, itctx)
+                            lctx.lower_param_bounds(bounds, itctx)
                         });
 
                         let (lifetimes, lifetime_defs) = self.lifetimes_from_impl_trait_bounds(
@@ -1233,18 +1232,20 @@ fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext) -> P<hir::Ty> {
                             span,
                         );
 
-                        let hir_bounds = self.lower_bounds(bounds, itctx);
+                        let hir_bounds = self.lower_param_bounds(bounds, itctx);
                         // Set the name to `impl Bound1 + Bound2`
                         let name = Symbol::intern(&pprust::ty_to_string(t));
-                        self.in_band_ty_params.push(hir::TyParam {
-                            name,
+                        self.in_band_ty_params.push(hir::GenericParam {
                             id: def_node_id,
-                            bounds: hir_bounds,
-                            default: None,
+                            name: ParamName::Plain(name),
                             span,
                             pure_wrt_drop: false,
-                            synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
-                            attrs: P::new(),
+                            attrs: hir_vec![],
+                            bounds: hir_bounds,
+                            kind: hir::GenericParamKind::Type {
+                                default: None,
+                                synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
+                            }
                         });
 
                         hir::TyPath(hir::QPath::Resolved(
@@ -1284,7 +1285,7 @@ fn lifetimes_from_impl_trait_bounds(
         &mut self,
         exist_ty_id: NodeId,
         parent_index: DefIndex,
-        bounds: &hir::TyParamBounds,
+        bounds: &hir::GenericBounds,
     ) -> (HirVec<hir::Lifetime>, HirVec<hir::GenericParam>) {
         // This visitor walks over impl trait bounds and creates defs for all lifetimes which
         // appear in the bounds, excluding lifetimes that are created within the bounds.
@@ -1307,15 +1308,15 @@ fn nested_visit_map<'this>(
                 hir::intravisit::NestedVisitorMap::None
             }
 
-            fn visit_path_parameters(&mut self, span: Span, parameters: &'v hir::PathParameters) {
+            fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) {
                 // Don't collect elided lifetimes used inside of `Fn()` syntax.
                 if parameters.parenthesized {
                     let old_collect_elided_lifetimes = self.collect_elided_lifetimes;
                     self.collect_elided_lifetimes = false;
-                    hir::intravisit::walk_path_parameters(self, span, parameters);
+                    hir::intravisit::walk_generic_args(self, span, parameters);
                     self.collect_elided_lifetimes = old_collect_elided_lifetimes;
                 } else {
-                    hir::intravisit::walk_path_parameters(self, span, parameters);
+                    hir::intravisit::walk_generic_args(self, span, parameters);
                 }
             }
 
@@ -1351,10 +1352,11 @@ fn visit_poly_trait_ref(
 
             fn visit_generic_param(&mut self, param: &'v hir::GenericParam) {
                 // Record the introduction of 'a in `for<'a> ...`
-                if let hir::GenericParam::Lifetime(ref lt_def) = *param {
+                if let hir::GenericParamKind::Lifetime { .. } = param.kind {
                     // Introduce lifetimes one at a time so that we can handle
                     // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`
-                    self.currently_bound_lifetimes.push(lt_def.lifetime.name);
+                    let lt_name = hir::LifetimeName::Param(param.name);
+                    self.currently_bound_lifetimes.push(lt_name);
                 }
 
                 hir::intravisit::walk_generic_param(self, param);
@@ -1371,14 +1373,12 @@ fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
                             return;
                         }
                     }
-                    name @ hir::LifetimeName::Fresh(_) => name,
-                    name @ hir::LifetimeName::Name(_) => name,
+                    hir::LifetimeName::Param(_) => lifetime.name,
                     hir::LifetimeName::Static => return,
                 };
 
                 if !self.currently_bound_lifetimes.contains(&name)
-                    && !self.already_defined_lifetimes.contains(&name)
-                {
+                    && !self.already_defined_lifetimes.contains(&name) {
                     self.already_defined_lifetimes.insert(name);
 
                     self.output_lifetimes.push(hir::Lifetime {
@@ -1395,23 +1395,31 @@ fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
                     self.context.resolver.definitions().create_def_with_parent(
                         self.parent,
                         def_node_id,
-                        DefPathData::LifetimeDef(name.name().as_interned_str()),
+                        DefPathData::LifetimeParam(name.name().as_interned_str()),
                         DefIndexAddressSpace::High,
                         Mark::root(),
                         lifetime.span,
                     );
-                    let def_lifetime = hir::Lifetime {
+
+                    let name = match name {
+                        hir::LifetimeName::Underscore => {
+                            hir::ParamName::Plain(keywords::UnderscoreLifetime.name())
+                        }
+                        hir::LifetimeName::Param(param_name) => param_name,
+                        _ => bug!("expected LifetimeName::Param or ParamName::Plain"),
+                    };
+
+                    self.output_lifetime_params.push(hir::GenericParam {
                         id: def_node_id,
-                        span: lifetime.span,
                         name,
-                    };
-                    self.output_lifetime_params
-                        .push(hir::GenericParam::Lifetime(hir::LifetimeDef {
-                            lifetime: def_lifetime,
-                            bounds: Vec::new().into(),
-                            pure_wrt_drop: false,
+                        span: lifetime.span,
+                        pure_wrt_drop: false,
+                        attrs: hir_vec![],
+                        bounds: hir_vec![],
+                        kind: hir::GenericParamKind::Lifetime {
                             in_band: false,
-                        }));
+                        }
+                    });
                 }
             }
         }
@@ -1428,7 +1436,7 @@ fn visit_lifetime(&mut self, lifetime: &'v hir::Lifetime) {
         };
 
         for bound in bounds {
-            hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
+            hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
         }
 
         (
@@ -1669,13 +1677,13 @@ fn lower_path_segment(
         parenthesized_generic_args: ParenthesizedGenericArgs,
         itctx: ImplTraitContext,
     ) -> hir::PathSegment {
-        let (mut parameters, infer_types) = if let Some(ref parameters) = segment.parameters {
+        let (mut generic_args, infer_types) = if let Some(ref generic_args) = segment.args {
             let msg = "parenthesized parameters may only be used with a trait";
-            match **parameters {
-                PathParameters::AngleBracketed(ref data) => {
+            match **generic_args {
+                GenericArgs::AngleBracketed(ref data) => {
                     self.lower_angle_bracketed_parameter_data(data, param_mode, itctx)
                 }
-                PathParameters::Parenthesized(ref data) => match parenthesized_generic_args {
+                GenericArgs::Parenthesized(ref data) => match parenthesized_generic_args {
                     ParenthesizedGenericArgs::Ok => self.lower_parenthesized_parameter_data(data),
                     ParenthesizedGenericArgs::Warn => {
                         self.sess.buffer_lint(
@@ -1684,13 +1692,13 @@ fn lower_path_segment(
                             data.span,
                             msg.into(),
                         );
-                        (hir::PathParameters::none(), true)
+                        (hir::GenericArgs::none(), true)
                     }
                     ParenthesizedGenericArgs::Err => {
                         struct_span_err!(self.sess, data.span, E0214, "{}", msg)
                             .span_label(data.span, "only traits may use parentheses")
                             .emit();
-                        (hir::PathParameters::none(), true)
+                        (hir::GenericArgs::none(), true)
                     }
                 },
             }
@@ -1698,47 +1706,49 @@ fn lower_path_segment(
             self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
         };
 
-        if !parameters.parenthesized && parameters.lifetimes.is_empty() {
-            parameters.lifetimes = self.elided_path_lifetimes(path_span, expected_lifetimes);
+        let has_lifetimes = generic_args.args.iter().any(|arg| match arg {
+            GenericArg::Lifetime(_) => true,
+            _ => false,
+        });
+        if !generic_args.parenthesized && !has_lifetimes {
+            generic_args.args =
+                self.elided_path_lifetimes(path_span, expected_lifetimes)
+                    .into_iter()
+                    .map(|lt| GenericArg::Lifetime(lt))
+                    .chain(generic_args.args.into_iter())
+                    .collect();
         }
 
         hir::PathSegment::new(
             self.lower_ident(segment.ident),
-            parameters,
+            generic_args,
             infer_types,
         )
     }
 
     fn lower_angle_bracketed_parameter_data(
         &mut self,
-        data: &AngleBracketedParameterData,
+        data: &AngleBracketedArgs,
         param_mode: ParamMode,
         itctx: ImplTraitContext,
-    ) -> (hir::PathParameters, bool) {
-        let &AngleBracketedParameterData {
-            ref lifetimes,
-            ref types,
-            ref bindings,
-            ..
-        } = data;
-        (
-            hir::PathParameters {
-                lifetimes: self.lower_lifetimes(lifetimes),
-                types: types.iter().map(|ty| self.lower_ty(ty, itctx)).collect(),
-                bindings: bindings
-                    .iter()
-                    .map(|b| self.lower_ty_binding(b, itctx))
-                    .collect(),
-                parenthesized: false,
-            },
-            types.is_empty() && param_mode == ParamMode::Optional,
-        )
+    ) -> (hir::GenericArgs, bool) {
+        let &AngleBracketedArgs { ref args, ref bindings, .. } = data;
+        let has_types = args.iter().any(|arg| match arg {
+            ast::GenericArg::Type(_) => true,
+            _ => false,
+        });
+        (hir::GenericArgs {
+            args: args.iter().map(|a| self.lower_generic_arg(a, itctx)).collect(),
+            bindings: bindings.iter().map(|b| self.lower_ty_binding(b, itctx)).collect(),
+            parenthesized: false,
+        },
+        !has_types && param_mode == ParamMode::Optional)
     }
 
     fn lower_parenthesized_parameter_data(
         &mut self,
-        data: &ParenthesizedParameterData,
-    ) -> (hir::PathParameters, bool) {
+        data: &ParenthesisedArgs,
+    ) -> (hir::GenericArgs, bool) {
         // Switch to `PassThrough` mode for anonymous lifetimes: this
         // means that we permit things like `&Ref<T>`, where `Ref` has
         // a hidden lifetime parameter. This is needed for backwards
@@ -1748,29 +1758,16 @@ fn lower_parenthesized_parameter_data(
             AnonymousLifetimeMode::PassThrough,
             |this| {
                 const DISALLOWED: ImplTraitContext = ImplTraitContext::Disallowed;
-                let &ParenthesizedParameterData {
-                    ref inputs,
-                    ref output,
-                    span,
-                } = data;
-                let inputs = inputs
-                    .iter()
-                    .map(|ty| this.lower_ty(ty, DISALLOWED))
-                    .collect();
+                let &ParenthesisedArgs { ref inputs, ref output, span } = data;
+                let inputs = inputs.iter().map(|ty| this.lower_ty(ty, DISALLOWED)).collect();
                 let mk_tup = |this: &mut Self, tys, span| {
                     let LoweredNodeId { node_id, hir_id } = this.next_id();
-                    P(hir::Ty {
-                        node: hir::TyTup(tys),
-                        id: node_id,
-                        hir_id,
-                        span,
-                    })
+                    P(hir::Ty { node: hir::TyTup(tys), id: node_id, hir_id, span })
                 };
 
                 (
-                    hir::PathParameters {
-                        lifetimes: hir::HirVec::new(),
-                        types: hir_vec![mk_tup(this, inputs, span)],
+                    hir::GenericArgs {
+                        args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))],
                         bindings: hir_vec![
                             hir::TypeBinding {
                                 id: this.next_id().node_id,
@@ -1874,63 +1871,22 @@ fn lower_fn_decl(
         })
     }
 
-    fn lower_ty_param_bound(
+    fn lower_param_bound(
         &mut self,
-        tpb: &TyParamBound,
+        tpb: &GenericBound,
         itctx: ImplTraitContext,
-    ) -> hir::TyParamBound {
+    ) -> hir::GenericBound {
         match *tpb {
-            TraitTyParamBound(ref ty, modifier) => hir::TraitTyParamBound(
+            GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait(
                 self.lower_poly_trait_ref(ty, itctx),
                 self.lower_trait_bound_modifier(modifier),
             ),
-            RegionTyParamBound(ref lifetime) => {
-                hir::RegionTyParamBound(self.lower_lifetime(lifetime))
+            GenericBound::Outlives(ref lifetime) => {
+                hir::GenericBound::Outlives(self.lower_lifetime(lifetime))
             }
         }
     }
 
-    fn lower_ty_param(
-        &mut self,
-        tp: &TyParam,
-        add_bounds: &[TyParamBound],
-        itctx: ImplTraitContext,
-    ) -> hir::TyParam {
-        let mut name = self.lower_ident(tp.ident);
-
-        // Don't expose `Self` (recovered "keyword used as ident" parse error).
-        // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
-        // Instead, use gensym("Self") to create a distinct name that looks the same.
-        if name == keywords::SelfType.name() {
-            name = Symbol::gensym("Self");
-        }
-
-        let mut bounds = self.lower_bounds(&tp.bounds, itctx);
-        if !add_bounds.is_empty() {
-            bounds = bounds
-                .into_iter()
-                .chain(self.lower_bounds(add_bounds, itctx).into_iter())
-                .collect();
-        }
-
-        hir::TyParam {
-            id: self.lower_node_id(tp.id).node_id,
-            name,
-            bounds,
-            default: tp.default
-                .as_ref()
-                .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
-            span: tp.ident.span,
-            pure_wrt_drop: attr::contains_name(&tp.attrs, "may_dangle"),
-            synthetic: tp.attrs
-                .iter()
-                .filter(|attr| attr.check_name("rustc_synthetic"))
-                .map(|_| hir::SyntheticTyParamKind::ImplTrait)
-                .nth(0),
-            attrs: self.lower_attrs(&tp.attrs),
-        }
-    }
-
     fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
         let span = l.ident.span;
         match self.lower_ident(l.ident) {
@@ -1938,7 +1894,7 @@ fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
             x if x == "'_" => match self.anonymous_lifetime_mode {
                 AnonymousLifetimeMode::CreateParameter => {
                     let fresh_name = self.collect_fresh_in_band_lifetime(span);
-                    self.new_named_lifetime(l.id, span, fresh_name)
+                    self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name))
                 }
 
                 AnonymousLifetimeMode::PassThrough => {
@@ -1947,7 +1903,8 @@ fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime {
             },
             name => {
                 self.maybe_collect_in_band_lifetime(span, name);
-                self.new_named_lifetime(l.id, span, hir::LifetimeName::Name(name))
+                let param_name = ParamName::Plain(name);
+                self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(param_name))
             }
         }
     }
@@ -1965,57 +1922,98 @@ fn new_named_lifetime(
         }
     }
 
-    fn lower_lifetime_def(&mut self, l: &LifetimeDef) -> hir::LifetimeDef {
-        let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
-        self.is_collecting_in_band_lifetimes = false;
-
-        let def = hir::LifetimeDef {
-            lifetime: self.lower_lifetime(&l.lifetime),
-            bounds: self.lower_lifetimes(&l.bounds),
-            pure_wrt_drop: attr::contains_name(&l.attrs, "may_dangle"),
-            in_band: false,
-        };
-
-        self.is_collecting_in_band_lifetimes = was_collecting_in_band;
-
-        def
-    }
-
-    fn lower_lifetimes(&mut self, lts: &Vec<Lifetime>) -> hir::HirVec<hir::Lifetime> {
-        lts.iter().map(|l| self.lower_lifetime(l)).collect()
-    }
-
     fn lower_generic_params(
         &mut self,
         params: &Vec<GenericParam>,
-        add_bounds: &NodeMap<Vec<TyParamBound>>,
+        add_bounds: &NodeMap<Vec<GenericBound>>,
         itctx: ImplTraitContext,
     ) -> hir::HirVec<hir::GenericParam> {
-        params
-            .iter()
-            .map(|param| match *param {
-                GenericParam::Lifetime(ref lifetime_def) => {
-                    hir::GenericParam::Lifetime(self.lower_lifetime_def(lifetime_def))
+        params.iter().map(|param| self.lower_generic_param(param, add_bounds, itctx)).collect()
+    }
+
+    fn lower_generic_param(&mut self,
+                           param: &GenericParam,
+                           add_bounds: &NodeMap<Vec<GenericBound>>,
+                           itctx: ImplTraitContext)
+                           -> hir::GenericParam {
+        let mut bounds = self.lower_param_bounds(&param.bounds, itctx);
+        match param.kind {
+            GenericParamKind::Lifetime => {
+                let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
+                self.is_collecting_in_band_lifetimes = false;
+
+                let lt = self.lower_lifetime(&Lifetime { id: param.id, ident: param.ident });
+                let param_name = match lt.name {
+                    hir::LifetimeName::Param(param_name) => param_name,
+                    _ => hir::ParamName::Plain(lt.name.name()),
+                };
+                let param = hir::GenericParam {
+                    id: lt.id,
+                    name: param_name,
+                    span: lt.span,
+                    pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
+                    attrs: self.lower_attrs(&param.attrs),
+                    bounds,
+                    kind: hir::GenericParamKind::Lifetime { in_band: false }
+                };
+
+                self.is_collecting_in_band_lifetimes = was_collecting_in_band;
+
+                param
+            }
+            GenericParamKind::Type { ref default, .. } => {
+                let mut name = self.lower_ident(param.ident);
+
+                // Don't expose `Self` (recovered "keyword used as ident" parse error).
+                // `rustc::ty` expects `Self` to be only used for a trait's `Self`.
+                // Instead, use gensym("Self") to create a distinct name that looks the same.
+                if name == keywords::SelfType.name() {
+                    name = Symbol::gensym("Self");
                 }
-                GenericParam::Type(ref ty_param) => hir::GenericParam::Type(self.lower_ty_param(
-                    ty_param,
-                    add_bounds.get(&ty_param.id).map_or(&[][..], |x| &x),
-                    itctx,
-                )),
-            })
-            .collect()
+
+                let add_bounds = add_bounds.get(&param.id).map_or(&[][..], |x| &x);
+                if !add_bounds.is_empty() {
+                    bounds = bounds.into_iter()
+                                   .chain(self.lower_param_bounds(add_bounds, itctx).into_iter())
+                                   .collect();
+                }
+
+                hir::GenericParam {
+                    id: self.lower_node_id(param.id).node_id,
+                    name: hir::ParamName::Plain(name),
+                    span: param.ident.span,
+                    pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
+                    attrs: self.lower_attrs(&param.attrs),
+                    bounds,
+                    kind: hir::GenericParamKind::Type {
+                        default: default.as_ref().map(|x| {
+                            self.lower_ty(x, ImplTraitContext::Disallowed)
+                        }),
+                        synthetic: param.attrs.iter()
+                                              .filter(|attr| attr.check_name("rustc_synthetic"))
+                                              .map(|_| hir::SyntheticTyParamKind::ImplTrait)
+                                              .next(),
+                    }
+                }
+            }
+        }
     }
 
-    fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Generics {
+    fn lower_generics(
+        &mut self,
+        generics: &Generics,
+        itctx: ImplTraitContext)
+        -> hir::Generics
+    {
         // Collect `?Trait` bounds in where clause and move them to parameter definitions.
         // FIXME: This could probably be done with less rightward drift. Also looks like two control
         //        paths where report_error is called are also the only paths that advance to after
         //        the match statement, so the error reporting could probably just be moved there.
         let mut add_bounds = NodeMap();
-        for pred in &g.where_clause.predicates {
+        for pred in &generics.where_clause.predicates {
             if let WherePredicate::BoundPredicate(ref bound_pred) = *pred {
                 'next_bound: for bound in &bound_pred.bounds {
-                    if let TraitTyParamBound(_, TraitBoundModifier::Maybe) = *bound {
+                    if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound {
                         let report_error = |this: &mut Self| {
                             this.diagnostic().span_err(
                                 bound_pred.bounded_ty.span,
@@ -2036,15 +2034,17 @@ fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Gene
                                     if let Some(node_id) =
                                         self.resolver.definitions().as_local_node_id(def_id)
                                     {
-                                        for param in &g.params {
-                                            if let GenericParam::Type(ref ty_param) = *param {
-                                                if node_id == ty_param.id {
-                                                    add_bounds
-                                                        .entry(ty_param.id)
-                                                        .or_insert(Vec::new())
-                                                        .push(bound.clone());
-                                                    continue 'next_bound;
+                                        for param in &generics.params {
+                                            match param.kind {
+                                                GenericParamKind::Type { .. } => {
+                                                    if node_id == param.id {
+                                                        add_bounds.entry(param.id)
+                                                            .or_insert(Vec::new())
+                                                            .push(bound.clone());
+                                                        continue 'next_bound;
+                                                    }
                                                 }
+                                                _ => {}
                                             }
                                         }
                                     }
@@ -2059,9 +2059,9 @@ fn lower_generics(&mut self, g: &Generics, itctx: ImplTraitContext) -> hir::Gene
         }
 
         hir::Generics {
-            params: self.lower_generic_params(&g.params, &add_bounds, itctx),
-            where_clause: self.lower_where_clause(&g.where_clause),
-            span: g.span,
+            params: self.lower_generic_params(&generics.params, &add_bounds, itctx),
+            where_clause: self.lower_where_clause(&generics.where_clause),
+            span: generics.span,
         }
     }
 
@@ -2084,10 +2084,7 @@ fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicat
                 span,
             }) => {
                 self.with_in_scope_lifetime_defs(
-                    bound_generic_params.iter().filter_map(|p| match p {
-                        GenericParam::Lifetime(ld) => Some(ld),
-                        _ => None,
-                    }),
+                    &bound_generic_params,
                     |this| {
                         hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
                             bound_generic_params: this.lower_generic_params(
@@ -2101,8 +2098,8 @@ fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicat
                                 .filter_map(|bound| match *bound {
                                     // Ignore `?Trait` bounds.
                                     // Tthey were copied into type parameters already.
-                                    TraitTyParamBound(_, TraitBoundModifier::Maybe) => None,
-                                    _ => Some(this.lower_ty_param_bound(
+                                    GenericBound::Trait(_, TraitBoundModifier::Maybe) => None,
+                                    _ => Some(this.lower_param_bound(
                                         bound,
                                         ImplTraitContext::Disallowed,
                                     )),
@@ -2120,10 +2117,7 @@ fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicat
             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
                 span,
                 lifetime: self.lower_lifetime(lifetime),
-                bounds: bounds
-                    .iter()
-                    .map(|bound| self.lower_lifetime(bound))
-                    .collect(),
+                bounds: self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
             }),
             WherePredicate::EqPredicate(WhereEqPredicate {
                 id,
@@ -2180,13 +2174,7 @@ fn lower_poly_trait_ref(
         let bound_generic_params =
             self.lower_generic_params(&p.bound_generic_params, &NodeMap(), itctx);
         let trait_ref = self.with_parent_impl_lifetime_defs(
-            &bound_generic_params
-                .iter()
-                .filter_map(|p| match *p {
-                    hir::GenericParam::Lifetime(ref ld) => Some(ld.clone()),
-                    _ => None,
-                })
-                .collect::<Vec<_>>(),
+            &bound_generic_params,
             |this| this.lower_trait_ref(&p.trait_ref, itctx),
         );
 
@@ -2229,15 +2217,9 @@ fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy {
         }
     }
 
-    fn lower_bounds(
-        &mut self,
-        bounds: &[TyParamBound],
-        itctx: ImplTraitContext,
-    ) -> hir::TyParamBounds {
-        bounds
-            .iter()
-            .map(|bound| self.lower_ty_param_bound(bound, itctx))
-            .collect()
+    fn lower_param_bounds(&mut self, bounds: &[GenericBound], itctx: ImplTraitContext)
+        -> hir::GenericBounds {
+        bounds.iter().map(|bound| self.lower_param_bound(bound, itctx)).collect()
     }
 
     fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
@@ -2403,10 +2385,7 @@ fn lower_item_kind(
                 );
 
                 let new_impl_items = self.with_in_scope_lifetime_defs(
-                    ast_generics.params.iter().filter_map(|p| match p {
-                        GenericParam::Lifetime(ld) => Some(ld),
-                        _ => None,
-                    }),
+                    &ast_generics.params,
                     |this| {
                         impl_items
                             .iter()
@@ -2426,7 +2405,7 @@ fn lower_item_kind(
                 )
             }
             ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref items) => {
-                let bounds = self.lower_bounds(bounds, ImplTraitContext::Disallowed);
+                let bounds = self.lower_param_bounds(bounds, ImplTraitContext::Disallowed);
                 let items = items
                     .iter()
                     .map(|item| self.lower_trait_item_ref(item))
@@ -2441,7 +2420,7 @@ fn lower_item_kind(
             }
             ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemTraitAlias(
                 self.lower_generics(generics, ImplTraitContext::Disallowed),
-                self.lower_bounds(bounds, ImplTraitContext::Disallowed),
+                self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
             ),
             ItemKind::MacroDef(..) | ItemKind::Mac(..) => panic!("Shouldn't still be around"),
         }
@@ -2668,7 +2647,7 @@ fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem {
             TraitItemKind::Type(ref bounds, ref default) => (
                 self.lower_generics(&i.generics, ImplTraitContext::Disallowed),
                 hir::TraitItemKind::Type(
-                    self.lower_bounds(bounds, ImplTraitContext::Disallowed),
+                    self.lower_param_bounds(bounds, ImplTraitContext::Disallowed),
                     default
                         .as_ref()
                         .map(|x| self.lower_ty(x, ImplTraitContext::Disallowed)),
@@ -4217,7 +4196,7 @@ fn elided_ref_lifetime(&mut self, span: Span) -> hir::Lifetime {
                 hir::Lifetime {
                     id: self.next_id().node_id,
                     span,
-                    name: fresh_name,
+                    name: hir::LifetimeName::Param(fresh_name),
                 }
             }
 
index 7835d4e782c430e86ad8231f98007a3833b53804..14cecba490d0ab3c99258ab9f7ab2429ce46d8f2 100644 (file)
@@ -212,7 +212,7 @@ fn insert(&mut self, id: NodeId, node: Node<'hir>) {
             NodeBlock(n) => EntryBlock(parent, dep_node_index, n),
             NodeStructCtor(n) => EntryStructCtor(parent, dep_node_index, n),
             NodeLifetime(n) => EntryLifetime(parent, dep_node_index, n),
-            NodeTyParam(n) => EntryTyParam(parent, dep_node_index, n),
+            NodeGenericParam(n) => EntryGenericParam(parent, dep_node_index, n),
             NodeVisibility(n) => EntryVisibility(parent, dep_node_index, n),
             NodeLocal(n) => EntryLocal(parent, dep_node_index, n),
             NodeMacroDef(n) => EntryMacroDef(dep_node_index, n),
@@ -347,14 +347,7 @@ fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem) {
     }
 
     fn visit_generic_param(&mut self, param: &'hir GenericParam) {
-        match *param {
-            GenericParam::Lifetime(ref ld) => {
-                self.insert(ld.lifetime.id, NodeLifetime(&ld.lifetime));
-            }
-            GenericParam::Type(ref ty_param) => {
-                self.insert(ty_param.id, NodeTyParam(ty_param));
-            }
-        }
+        self.insert(param.id, NodeGenericParam(param));
         intravisit::walk_generic_param(self, param);
     }
 
index 48d959b4f8e4199552ebef77831731fbc39830f0..8aa5dd4ad80fd36c6a2a1fa54395bd62bbcba6ba 100644 (file)
@@ -171,24 +171,12 @@ fn visit_variant_data(&mut self, data: &'a VariantData, _: Ident,
     }
 
     fn visit_generic_param(&mut self, param: &'a GenericParam) {
-        match *param {
-            GenericParam::Lifetime(ref lifetime_def) => {
-                self.create_def(
-                    lifetime_def.lifetime.id,
-                    DefPathData::LifetimeDef(lifetime_def.lifetime.ident.name.as_interned_str()),
-                    REGULAR_SPACE,
-                    lifetime_def.lifetime.ident.span
-                );
-            }
-            GenericParam::Type(ref ty_param) => {
-                self.create_def(
-                    ty_param.id,
-                    DefPathData::TypeParam(ty_param.ident.name.as_interned_str()),
-                    REGULAR_SPACE,
-                    ty_param.ident.span
-                );
-            }
-        }
+        let name = param.ident.name.as_interned_str();
+        let def_path_data = match param.kind {
+            GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name),
+            GenericParamKind::Type { .. } => DefPathData::TypeParam(name),
+        };
+        self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
 
         visit::walk_generic_param(self, param);
     }
index 99023a168674179cf37721c05f9362cbea53307f..b1cb9d7fbd4a5aa201ebc1735c1fd109b29af5f8 100644 (file)
@@ -360,7 +360,7 @@ pub enum DefPathData {
     /// A type parameter (generic parameter)
     TypeParam(InternedString),
     /// A lifetime definition
-    LifetimeDef(InternedString),
+    LifetimeParam(InternedString),
     /// A variant of a enum
     EnumVariant(InternedString),
     /// A struct field
@@ -625,7 +625,7 @@ pub fn get_opt_name(&self) -> Option<InternedString> {
             Module(name) |
             MacroDef(name) |
             TypeParam(name) |
-            LifetimeDef(name) |
+            LifetimeParam(name) |
             EnumVariant(name) |
             Field(name) |
             GlobalMetaData(name) => Some(name),
@@ -652,7 +652,7 @@ pub fn as_interned_str(&self) -> InternedString {
             Module(name) |
             MacroDef(name) |
             TypeParam(name) |
-            LifetimeDef(name) |
+            LifetimeParam(name) |
             EnumVariant(name) |
             Field(name) |
             GlobalMetaData(name) => {
index 9df55e52061634962c67b5e5dcd338cf497f1fea..c2c8c7a391b9c02c417cc33b199a2e6a3dc8a2c3 100644 (file)
@@ -68,7 +68,7 @@ pub enum Node<'hir> {
     NodeStructCtor(&'hir VariantData),
 
     NodeLifetime(&'hir Lifetime),
-    NodeTyParam(&'hir TyParam),
+    NodeGenericParam(&'hir GenericParam),
     NodeVisibility(&'hir Visibility),
 }
 
@@ -96,7 +96,7 @@ enum MapEntry<'hir> {
     EntryBlock(NodeId, DepNodeIndex, &'hir Block),
     EntryStructCtor(NodeId, DepNodeIndex, &'hir VariantData),
     EntryLifetime(NodeId, DepNodeIndex, &'hir Lifetime),
-    EntryTyParam(NodeId, DepNodeIndex, &'hir TyParam),
+    EntryGenericParam(NodeId, DepNodeIndex, &'hir GenericParam),
     EntryVisibility(NodeId, DepNodeIndex, &'hir Visibility),
     EntryLocal(NodeId, DepNodeIndex, &'hir Local),
 
@@ -132,7 +132,7 @@ fn parent_node(self) -> Option<NodeId> {
             EntryBlock(id, _, _) => id,
             EntryStructCtor(id, _, _) => id,
             EntryLifetime(id, _, _) => id,
-            EntryTyParam(id, _, _) => id,
+            EntryGenericParam(id, _, _) => id,
             EntryVisibility(id, _, _) => id,
             EntryLocal(id, _, _) => id,
 
@@ -160,7 +160,7 @@ fn to_node(self) -> Option<Node<'hir>> {
             EntryBlock(_, _, n) => NodeBlock(n),
             EntryStructCtor(_, _, n) => NodeStructCtor(n),
             EntryLifetime(_, _, n) => NodeLifetime(n),
-            EntryTyParam(_, _, n) => NodeTyParam(n),
+            EntryGenericParam(_, _, n) => NodeGenericParam(n),
             EntryVisibility(_, _, n) => NodeVisibility(n),
             EntryLocal(_, _, n) => NodeLocal(n),
             EntryMacroDef(_, n) => NodeMacroDef(n),
@@ -170,6 +170,40 @@ fn to_node(self) -> Option<Node<'hir>> {
         })
     }
 
+    fn fn_decl(&self) -> Option<&FnDecl> {
+        match self {
+            EntryItem(_, _, ref item) => {
+                match item.node {
+                    ItemFn(ref fn_decl, _, _, _, _, _) => Some(&fn_decl),
+                    _ => None,
+                }
+            }
+
+            EntryTraitItem(_, _, ref item) => {
+                match item.node {
+                    TraitItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
+                    _ => None
+                }
+            }
+
+            EntryImplItem(_, _, ref item) => {
+                match item.node {
+                    ImplItemKind::Method(ref method_sig, _) => Some(&method_sig.decl),
+                    _ => None,
+                }
+            }
+
+            EntryExpr(_, _, ref expr) => {
+                match expr.node {
+                    ExprClosure(_, ref fn_decl, ..) => Some(&fn_decl),
+                    _ => None,
+                }
+            }
+
+            _ => None
+        }
+    }
+
     fn associated_body(self) -> Option<BodyId> {
         match self {
             EntryItem(_, _, item) => {
@@ -294,7 +328,7 @@ pub fn read(&self, id: NodeId) {
             EntryBlock(_, dep_node_index, _) |
             EntryStructCtor(_, dep_node_index, _) |
             EntryLifetime(_, dep_node_index, _) |
-            EntryTyParam(_, dep_node_index, _) |
+            EntryGenericParam(_, dep_node_index, _) |
             EntryVisibility(_, dep_node_index, _) |
             EntryAnonConst(_, dep_node_index, _) |
             EntryExpr(_, dep_node_index, _) |
@@ -460,8 +494,11 @@ pub fn describe_def(&self, node_id: NodeId) -> Option<Def> {
                 Some(Def::Macro(self.local_def_id(macro_def.id),
                                 MacroKind::Bang))
             }
-            NodeTyParam(param) => {
-                Some(Def::TyParam(self.local_def_id(param.id)))
+            NodeGenericParam(param) => {
+                Some(match param.kind {
+                    GenericParamKind::Lifetime { .. } => Def::Local(param.id),
+                    GenericParamKind::Type { .. } => Def::TyParam(self.local_def_id(param.id)),
+                })
             }
         }
     }
@@ -502,6 +539,14 @@ pub fn body(&self, id: BodyId) -> &'hir Body {
         self.forest.krate.body(id)
     }
 
+    pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
+        if let Some(entry) = self.find_entry(node_id) {
+            entry.fn_decl().map(|fd| fd.clone())
+        } else {
+            bug!("no entry for node_id `{}`", node_id)
+        }
+    }
+
     /// Returns the `NodeId` that corresponds to the definition of
     /// which this is the body of, i.e. a `fn`, `const` or `static`
     /// item (possibly associated), a closure, or a `hir::AnonConst`.
@@ -558,7 +603,7 @@ pub fn body_owner_kind(&self, id: NodeId) -> BodyOwnerKind {
     pub fn ty_param_owner(&self, id: NodeId) -> NodeId {
         match self.get(id) {
             NodeItem(&Item { node: ItemTrait(..), .. }) => id,
-            NodeTyParam(_) => self.get_parent_node(id),
+            NodeGenericParam(_) => self.get_parent_node(id),
             _ => {
                 bug!("ty_param_owner: {} not a type parameter",
                     self.node_to_string(id))
@@ -571,11 +616,8 @@ pub fn ty_param_name(&self, id: NodeId) -> Name {
             NodeItem(&Item { node: ItemTrait(..), .. }) => {
                 keywords::SelfType.name()
             }
-            NodeTyParam(tp) => tp.name,
-            _ => {
-                bug!("ty_param_name: {} not a type parameter",
-                    self.node_to_string(id))
-            }
+            NodeGenericParam(param) => param.name.name(),
+            _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
         }
     }
 
@@ -912,7 +954,7 @@ pub fn name(&self, id: NodeId) -> Name {
             NodeVariant(v) => v.node.name,
             NodeField(f) => f.ident.name,
             NodeLifetime(lt) => lt.name.name(),
-            NodeTyParam(tp) => tp.name,
+            NodeGenericParam(param) => param.name.name(),
             NodeBinding(&Pat { node: PatKind::Binding(_,_,l,_), .. }) => l.node,
             NodeStructCtor(_) => self.name(self.get_parent(id)),
             _ => bug!("no name for {}", self.node_to_string(id))
@@ -932,7 +974,7 @@ pub fn attrs(&self, id: NodeId) -> &'hir [ast::Attribute] {
             Some(NodeField(ref f)) => Some(&f.attrs[..]),
             Some(NodeExpr(ref e)) => Some(&*e.attrs),
             Some(NodeStmt(ref s)) => Some(s.node.attrs()),
-            Some(NodeTyParam(tp)) => Some(&tp.attrs[..]),
+            Some(NodeGenericParam(param)) => Some(&param.attrs[..]),
             // unit/tuple structs take the attributes straight from
             // the struct definition.
             Some(NodeStructCtor(_)) => {
@@ -979,7 +1021,7 @@ pub fn span(&self, id: NodeId) -> Span {
             Some(EntryBlock(_, _, block)) => block.span,
             Some(EntryStructCtor(_, _, _)) => self.expect_item(self.get_parent(id)).span,
             Some(EntryLifetime(_, _, lifetime)) => lifetime.span,
-            Some(EntryTyParam(_, _, ty_param)) => ty_param.span,
+            Some(EntryGenericParam(_, _, param)) => param.span,
             Some(EntryVisibility(_, _, &Visibility::Restricted { ref path, .. })) => path.span,
             Some(EntryVisibility(_, _, v)) => bug!("unexpected Visibility {:?}", v),
             Some(EntryLocal(_, _, local)) => local.span,
@@ -1184,19 +1226,19 @@ fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<
 impl<'a> print::State<'a> {
     pub fn print_node(&mut self, node: Node) -> io::Result<()> {
         match node {
-            NodeItem(a)        => self.print_item(&a),
-            NodeForeignItem(a) => self.print_foreign_item(&a),
-            NodeTraitItem(a)   => self.print_trait_item(a),
-            NodeImplItem(a)    => self.print_impl_item(a),
-            NodeVariant(a)     => self.print_variant(&a),
-            NodeAnonConst(a)   => self.print_anon_const(&a),
-            NodeExpr(a)        => self.print_expr(&a),
-            NodeStmt(a)        => self.print_stmt(&a),
-            NodeTy(a)          => self.print_type(&a),
-            NodeTraitRef(a)    => self.print_trait_ref(&a),
+            NodeItem(a)         => self.print_item(&a),
+            NodeForeignItem(a)  => self.print_foreign_item(&a),
+            NodeTraitItem(a)    => self.print_trait_item(a),
+            NodeImplItem(a)     => self.print_impl_item(a),
+            NodeVariant(a)      => self.print_variant(&a),
+            NodeAnonConst(a)    => self.print_anon_const(&a),
+            NodeExpr(a)         => self.print_expr(&a),
+            NodeStmt(a)         => self.print_stmt(&a),
+            NodeTy(a)           => self.print_type(&a),
+            NodeTraitRef(a)     => self.print_trait_ref(&a),
             NodeBinding(a)       |
-            NodePat(a)         => self.print_pat(&a),
-            NodeBlock(a)       => {
+            NodePat(a)          => self.print_pat(&a),
+            NodeBlock(a)        => {
                 use syntax::print::pprust::PrintState;
 
                 // containing cbox, will be closed by print-block at }
@@ -1205,16 +1247,16 @@ pub fn print_node(&mut self, node: Node) -> io::Result<()> {
                 self.ibox(0)?;
                 self.print_block(&a)
             }
-            NodeLifetime(a)    => self.print_lifetime(&a),
-            NodeVisibility(a)  => self.print_visibility(&a),
-            NodeTyParam(_)     => bug!("cannot print TyParam"),
-            NodeField(_)       => bug!("cannot print StructField"),
+            NodeLifetime(a)     => self.print_lifetime(&a),
+            NodeVisibility(a)   => self.print_visibility(&a),
+            NodeGenericParam(_) => bug!("cannot print NodeGenericParam"),
+            NodeField(_)        => bug!("cannot print StructField"),
             // these cases do not carry enough information in the
             // hir_map to reconstruct their full structure for pretty
             // printing.
-            NodeStructCtor(_)  => bug!("cannot print isolated StructCtor"),
-            NodeLocal(a)       => self.print_local_decl(&a),
-            NodeMacroDef(_)    => bug!("cannot print MacroDef"),
+            NodeStructCtor(_)   => bug!("cannot print isolated StructCtor"),
+            NodeLocal(a)        => self.print_local_decl(&a),
+            NodeMacroDef(_)     => bug!("cannot print MacroDef"),
         }
     }
 }
@@ -1329,8 +1371,8 @@ fn node_id_to_string(map: &Map, id: NodeId, include_id: bool) -> String {
         Some(NodeLifetime(_)) => {
             format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
         }
-        Some(NodeTyParam(ref ty_param)) => {
-            format!("typaram {:?}{}", ty_param, id_str)
+        Some(NodeGenericParam(ref param)) => {
+            format!("generic_param {:?}{}", param, id_str)
         }
         Some(NodeVisibility(ref vis)) => {
             format!("visibility {:?}{}", vis, id_str)
index 833090c3ee092342a836cad6eafdc9a059a9fd83..f6876113c1176a0ca2f924694499b1b710780449 100644 (file)
@@ -22,7 +22,6 @@
 pub use self::PrimTy::*;
 pub use self::Stmt_::*;
 pub use self::Ty_::*;
-pub use self::TyParamBound::*;
 pub use self::UnOp::*;
 pub use self::UnsafeSource::*;
 pub use self::Visibility::{Public, Inherited};
@@ -53,8 +52,6 @@
 use serialize::{self, Encoder, Encodable, Decoder, Decodable};
 use std::collections::BTreeMap;
 use std::fmt;
-use std::iter;
-use std::slice;
 
 /// HIR doesn't commit to a concrete storage type and has its own alias for a vector.
 /// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar
@@ -203,12 +200,9 @@ pub struct Lifetime {
 }
 
 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
-pub enum LifetimeName {
-    /// User typed nothing. e.g. the lifetime in `&u32`.
-    Implicit,
-
-    /// User typed `'_`.
-    Underscore,
+pub enum ParamName {
+    /// Some user-given name like `T` or `'x`.
+    Plain(Name),
 
     /// Synthetic name generated when user elided a lifetime in an impl header,
     /// e.g. the lifetimes in cases like these:
@@ -224,12 +218,30 @@ pub enum LifetimeName {
     /// where `'f` is something like `Fresh(0)`. The indices are
     /// unique per impl, but not necessarily continuous.
     Fresh(usize),
+}
+
+impl ParamName {
+    pub fn name(&self) -> Name {
+        match *self {
+            ParamName::Plain(name) => name,
+            ParamName::Fresh(_) => keywords::UnderscoreLifetime.name(),
+        }
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)]
+pub enum LifetimeName {
+    /// User-given names or fresh (synthetic) names.
+    Param(ParamName),
+
+    /// User typed nothing. e.g. the lifetime in `&u32`.
+    Implicit,
+
+    /// User typed `'_`.
+    Underscore,
 
     /// User wrote `'static`
     Static,
-
-    /// Some user-given name like `'x`
-    Name(Name),
 }
 
 impl LifetimeName {
@@ -237,11 +249,29 @@ pub fn name(&self) -> Name {
         use self::LifetimeName::*;
         match *self {
             Implicit => keywords::Invalid.name(),
-            Fresh(_) | Underscore => keywords::UnderscoreLifetime.name(),
+            Underscore => keywords::UnderscoreLifetime.name(),
             Static => keywords::StaticLifetime.name(),
-            Name(name) => name,
+            Param(param_name) => param_name.name(),
         }
     }
+
+    fn is_elided(&self) -> bool {
+        use self::LifetimeName::*;
+        match self {
+            Implicit | Underscore => true,
+
+            // It might seem surprising that `Fresh(_)` counts as
+            // *not* elided -- but this is because, as far as the code
+            // in the compiler is concerned -- `Fresh(_)` variants act
+            // equivalently to "some fresh name". They correspond to
+            // early-bound regions on an impl, in other words.
+            Param(_) | Static => false,
+        }
+    }
+
+    fn is_static(&self) -> bool {
+        self == &LifetimeName::Static
+    }
 }
 
 impl fmt::Debug for Lifetime {
@@ -255,36 +285,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 impl Lifetime {
     pub fn is_elided(&self) -> bool {
-        use self::LifetimeName::*;
-        match self.name {
-            Implicit | Underscore => true,
-
-            // It might seem surprising that `Fresh(_)` counts as
-            // *not* elided -- but this is because, as far as the code
-            // in the compiler is concerned -- `Fresh(_)` variants act
-            // equivalently to "some fresh name". They correspond to
-            // early-bound regions on an impl, in other words.
-            Fresh(_) | Static | Name(_) => false,
-        }
+        self.name.is_elided()
     }
 
     pub fn is_static(&self) -> bool {
-        self.name == LifetimeName::Static
+        self.name.is_static()
     }
 }
 
-/// A lifetime definition, eg `'a: 'b+'c+'d`
-#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct LifetimeDef {
-    pub lifetime: Lifetime,
-    pub bounds: HirVec<Lifetime>,
-    pub pure_wrt_drop: bool,
-    // Indicates that the lifetime definition was synthetically added
-    // as a result of an in-band lifetime usage like
-    // `fn foo(x: &'a u8) -> &'a u8 { x }`
-    pub in_band: bool,
-}
-
 /// A "Path" is essentially Rust's notion of a name; for instance:
 /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers,
 /// along with a bunch of supporting information.
@@ -327,7 +335,7 @@ pub struct PathSegment {
     /// this is more than just simple syntactic sugar; the use of
     /// parens affects the region binding rules, so we preserve the
     /// distinction.
-    pub parameters: Option<P<PathParameters>>,
+    pub args: Option<P<GenericArgs>>,
 
     /// Whether to infer remaining type parameters, if any.
     /// This only applies to expression and pattern paths, and
@@ -342,30 +350,30 @@ pub fn from_name(name: Name) -> PathSegment {
         PathSegment {
             name,
             infer_types: true,
-            parameters: None
+            args: None,
         }
     }
 
-    pub fn new(name: Name, parameters: PathParameters, infer_types: bool) -> Self {
+    pub fn new(name: Name, args: GenericArgs, infer_types: bool) -> Self {
         PathSegment {
             name,
             infer_types,
-            parameters: if parameters.is_empty() {
+            args: if args.is_empty() {
                 None
             } else {
-                Some(P(parameters))
+                Some(P(args))
             }
         }
     }
 
     // FIXME: hack required because you can't create a static
-    // PathParameters, so you can't just return a &PathParameters.
-    pub fn with_parameters<F, R>(&self, f: F) -> R
-        where F: FnOnce(&PathParameters) -> R
+    // GenericArgs, so you can't just return a &GenericArgs.
+    pub fn with_generic_args<F, R>(&self, f: F) -> R
+        where F: FnOnce(&GenericArgs) -> R
     {
-        let dummy = PathParameters::none();
-        f(if let Some(ref params) = self.parameters {
-            &params
+        let dummy = GenericArgs::none();
+        f(if let Some(ref args) = self.args {
+            &args
         } else {
             &dummy
         })
@@ -373,142 +381,114 @@ pub fn with_parameters<F, R>(&self, f: F) -> R
 }
 
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct PathParameters {
-    /// The lifetime parameters for this path segment.
-    pub lifetimes: HirVec<Lifetime>,
-    /// The type parameters for this path segment, if present.
-    pub types: HirVec<P<Ty>>,
+pub enum GenericArg {
+    Lifetime(Lifetime),
+    Type(P<Ty>),
+}
+
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
+pub struct GenericArgs {
+    /// The generic arguments for this path segment.
+    pub args: HirVec<GenericArg>,
     /// Bindings (equality constraints) on associated types, if present.
     /// E.g., `Foo<A=Bar>`.
     pub bindings: HirVec<TypeBinding>,
-    /// Were parameters written in parenthesized form `Fn(T) -> U`?
+    /// Were arguments written in parenthesized form `Fn(T) -> U`?
     /// This is required mostly for pretty-printing and diagnostics,
     /// but also for changing lifetime elision rules to be "function-like".
     pub parenthesized: bool,
 }
 
-impl PathParameters {
+impl GenericArgs {
     pub fn none() -> Self {
         Self {
-            lifetimes: HirVec::new(),
-            types: HirVec::new(),
+            args: HirVec::new(),
             bindings: HirVec::new(),
             parenthesized: false,
         }
     }
 
     pub fn is_empty(&self) -> bool {
-        self.lifetimes.is_empty() && self.types.is_empty() &&
-            self.bindings.is_empty() && !self.parenthesized
+        self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized
     }
 
     pub fn inputs(&self) -> &[P<Ty>] {
         if self.parenthesized {
-            if let Some(ref ty) = self.types.get(0) {
-                if let TyTup(ref tys) = ty.node {
-                    return tys;
+            for arg in &self.args {
+                match arg {
+                    GenericArg::Lifetime(_) => {}
+                    GenericArg::Type(ref ty) => {
+                        if let TyTup(ref tys) = ty.node {
+                            return tys;
+                        }
+                        break;
+                    }
                 }
             }
         }
-        bug!("PathParameters::inputs: not a `Fn(T) -> U`");
+        bug!("GenericArgs::inputs: not a `Fn(T) -> U`");
     }
 }
 
+/// A modifier on a bound, currently this is only used for `?Sized`, where the
+/// modifier is `Maybe`. Negative bounds should also be handled here.
+#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
+pub enum TraitBoundModifier {
+    None,
+    Maybe,
+}
+
 /// The AST represents all type param bounds as types.
 /// typeck::collect::compute_bounds matches these against
 /// the "special" built-in traits (see middle::lang_items) and
 /// detects Copy, Send and Sync.
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum TyParamBound {
-    TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
-    RegionTyParamBound(Lifetime),
+pub enum GenericBound {
+    Trait(PolyTraitRef, TraitBoundModifier),
+    Outlives(Lifetime),
 }
 
-impl TyParamBound {
+impl GenericBound {
     pub fn span(&self) -> Span {
         match self {
-            &TraitTyParamBound(ref t, ..) => t.span,
-            &RegionTyParamBound(ref l) => l.span,
+            &GenericBound::Trait(ref t, ..) => t.span,
+            &GenericBound::Outlives(ref l) => l.span,
         }
     }
 }
 
-/// A modifier on a bound, currently this is only used for `?Sized`, where the
-/// modifier is `Maybe`. Negative bounds should also be handled here.
-#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum TraitBoundModifier {
-    None,
-    Maybe,
-}
+pub type GenericBounds = HirVec<GenericBound>;
 
-pub type TyParamBounds = HirVec<TyParamBound>;
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
+pub enum GenericParamKind {
+    /// A lifetime definition, eg `'a: 'b + 'c + 'd`.
+    Lifetime {
+        // Indicates that the lifetime definition was synthetically added
+        // as a result of an in-band lifetime usage like:
+        // `fn foo(x: &'a u8) -> &'a u8 { x }`
+        in_band: bool,
+    },
+    Type {
+        default: Option<P<Ty>>,
+        synthetic: Option<SyntheticTyParamKind>,
+    }
+}
 
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct TyParam {
-    pub name: Name,
+pub struct GenericParam {
     pub id: NodeId,
-    pub bounds: TyParamBounds,
-    pub default: Option<P<Ty>>,
+    pub name: ParamName,
+    pub attrs: HirVec<Attribute>,
+    pub bounds: GenericBounds,
     pub span: Span,
     pub pure_wrt_drop: bool,
-    pub synthetic: Option<SyntheticTyParamKind>,
-    pub attrs: HirVec<Attribute>,
-}
 
-#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum GenericParam {
-    Lifetime(LifetimeDef),
-    Type(TyParam),
+    pub kind: GenericParamKind,
 }
 
-impl GenericParam {
-    pub fn is_lifetime_param(&self) -> bool {
-        match *self {
-            GenericParam::Lifetime(_) => true,
-            _ => false,
-        }
-    }
-
-    pub fn is_type_param(&self) -> bool {
-        match *self {
-            GenericParam::Type(_) => true,
-            _ => false,
-        }
-    }
-}
-
-pub trait GenericParamsExt {
-    fn lifetimes<'a>(&'a self) -> iter::FilterMap<
-        slice::Iter<GenericParam>,
-        fn(&GenericParam) -> Option<&LifetimeDef>,
-    >;
-
-    fn ty_params<'a>(&'a self) -> iter::FilterMap<
-        slice::Iter<GenericParam>,
-        fn(&GenericParam) -> Option<&TyParam>,
-    >;
-}
-
-impl GenericParamsExt for [GenericParam] {
-    fn lifetimes<'a>(&'a self) -> iter::FilterMap<
-        slice::Iter<GenericParam>,
-        fn(&GenericParam) -> Option<&LifetimeDef>,
-    > {
-        self.iter().filter_map(|param| match *param {
-            GenericParam::Lifetime(ref l) => Some(l),
-            _ => None,
-        })
-    }
-
-    fn ty_params<'a>(&'a self) -> iter::FilterMap<
-        slice::Iter<GenericParam>,
-        fn(&GenericParam) -> Option<&TyParam>,
-    > {
-        self.iter().filter_map(|param| match *param {
-            GenericParam::Type(ref t) => Some(t),
-            _ => None,
-        })
-    }
+pub struct GenericParamCount {
+    pub lifetimes: usize,
+    pub types: usize,
 }
 
 /// Represents lifetimes and type parameters attached to a declaration
@@ -532,55 +512,23 @@ pub fn empty() -> Generics {
         }
     }
 
-    pub fn is_lt_parameterized(&self) -> bool {
-        self.params.iter().any(|param| param.is_lifetime_param())
-    }
-
-    pub fn is_type_parameterized(&self) -> bool {
-        self.params.iter().any(|param| param.is_type_param())
-    }
-
-    pub fn lifetimes<'a>(&'a self) -> impl Iterator<Item = &'a LifetimeDef> {
-        self.params.lifetimes()
-    }
-
-    pub fn ty_params<'a>(&'a self) -> impl Iterator<Item = &'a TyParam> {
-        self.params.ty_params()
-    }
-}
-
-pub enum UnsafeGeneric {
-    Region(LifetimeDef, &'static str),
-    Type(TyParam, &'static str),
-}
+    pub fn own_counts(&self) -> GenericParamCount {
+        // We could cache this as a property of `GenericParamCount`, but
+        // the aim is to refactor this away entirely eventually and the
+        // presence of this method will be a constant reminder.
+        let mut own_counts = GenericParamCount {
+            lifetimes: 0,
+            types: 0,
+        };
 
-impl UnsafeGeneric {
-    pub fn attr_name(&self) -> &'static str {
-        match *self {
-            UnsafeGeneric::Region(_, s) => s,
-            UnsafeGeneric::Type(_, s) => s,
-        }
-    }
-}
-
-impl Generics {
-    pub fn carries_unsafe_attr(&self) -> Option<UnsafeGeneric> {
         for param in &self.params {
-            match *param {
-                GenericParam::Lifetime(ref l) => {
-                    if l.pure_wrt_drop {
-                        return Some(UnsafeGeneric::Region(l.clone(), "may_dangle"));
-                    }
-                }
-                GenericParam::Type(ref t) => {
-                    if t.pure_wrt_drop {
-                        return Some(UnsafeGeneric::Type(t.clone(), "may_dangle"));
-                    }
-                }
-            }
+            match param.kind {
+                GenericParamKind::Lifetime { .. } => own_counts.lifetimes += 1,
+                GenericParamKind::Type { .. } => own_counts.types += 1,
+            };
         }
 
-        None
+        own_counts
     }
 }
 
@@ -640,7 +588,7 @@ pub struct WhereBoundPredicate {
     /// The type being bounded
     pub bounded_ty: P<Ty>,
     /// Trait and lifetime bounds (`Clone+Send+'static`)
-    pub bounds: TyParamBounds,
+    pub bounds: GenericBounds,
 }
 
 /// A lifetime predicate, e.g. `'a: 'b+'c`
@@ -648,7 +596,7 @@ pub struct WhereBoundPredicate {
 pub struct WhereRegionPredicate {
     pub span: Span,
     pub lifetime: Lifetime,
-    pub bounds: HirVec<Lifetime>,
+    pub bounds: GenericBounds,
 }
 
 /// An equality predicate (unsupported), e.g. `T=int`
@@ -1607,7 +1555,7 @@ pub enum TraitItemKind {
     Method(MethodSig, TraitMethod),
     /// An associated type with (possibly empty) bounds and optional concrete
     /// type
-    Type(TyParamBounds, Option<P<Ty>>),
+    Type(GenericBounds, Option<P<Ty>>),
 }
 
 // The bodies for items are stored "out of line", in a separate
@@ -1692,7 +1640,7 @@ pub struct BareFnTy {
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
 pub struct ExistTy {
     pub generics: Generics,
-    pub bounds: TyParamBounds,
+    pub bounds: GenericBounds,
     pub impl_trait_fn: Option<DefId>,
 }
 
@@ -2101,9 +2049,9 @@ pub enum Item_ {
     /// A union definition, e.g. `union Foo<A, B> {x: A, y: B}`
     ItemUnion(VariantData, Generics),
     /// Represents a Trait Declaration
-    ItemTrait(IsAuto, Unsafety, Generics, TyParamBounds, HirVec<TraitItemRef>),
+    ItemTrait(IsAuto, Unsafety, Generics, GenericBounds, HirVec<TraitItemRef>),
     /// Represents a Trait Alias Declaration
-    ItemTraitAlias(Generics, TyParamBounds),
+    ItemTraitAlias(Generics, GenericBounds),
 
     /// An implementation, eg `impl<A> Trait for Foo { .. }`
     ItemImpl(Unsafety,
index 1beef3f715e22098c8a50c33f131f590846a434a..14f780fab7f2e5d0b1de06a763fb95115dfd6677 100644 (file)
@@ -24,7 +24,8 @@
 use syntax_pos::{self, BytePos, FileName};
 
 use hir;
-use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier, RangeEnd};
+use hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
+use hir::{GenericParam, GenericParamKind, GenericArg};
 
 use std::cell::Cell;
 use std::io::{self, Write, Read};
@@ -513,7 +514,7 @@ fn print_associated_const(&mut self,
 
     fn print_associated_type(&mut self,
                              name: ast::Name,
-                             bounds: Option<&hir::TyParamBounds>,
+                             bounds: Option<&hir::GenericBounds>,
                              ty: Option<&hir::Ty>)
                              -> io::Result<()> {
         self.word_space("type")?;
@@ -661,7 +662,7 @@ pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
                 self.word_space(":")?;
                 let mut real_bounds = Vec::with_capacity(exist.bounds.len());
                 for b in exist.bounds.iter() {
-                    if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
+                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
                         self.s.space()?;
                         self.word_space("for ?")?;
                         self.print_trait_ref(&ptr.trait_ref)?;
@@ -739,7 +740,7 @@ pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
                 self.print_generic_params(&generics.params)?;
                 let mut real_bounds = Vec::with_capacity(bounds.len());
                 for b in bounds.iter() {
-                    if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
+                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
                         self.s.space()?;
                         self.word_space("for ?")?;
                         self.print_trait_ref(&ptr.trait_ref)?;
@@ -765,7 +766,7 @@ pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
                 let mut real_bounds = Vec::with_capacity(bounds.len());
                 // FIXME(durka) this seems to be some quite outdated syntax
                 for b in bounds.iter() {
-                    if let TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
+                    if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
                         self.s.space()?;
                         self.word_space("for ?")?;
                         self.print_trait_ref(&ptr.trait_ref)?;
@@ -1268,15 +1269,11 @@ fn print_expr_method_call(&mut self,
         self.s.word(".")?;
         self.print_name(segment.name)?;
 
-        segment.with_parameters(|parameters| {
-            if !parameters.lifetimes.is_empty() ||
-                !parameters.types.is_empty() ||
-                !parameters.bindings.is_empty()
-            {
-                self.print_path_parameters(&parameters, segment.infer_types, true)
-            } else {
-                Ok(())
+        segment.with_generic_args(|generic_args| {
+            if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
+                return self.print_generic_args(&generic_args, segment.infer_types, true);
             }
+            Ok(())
         })?;
         self.print_call_post(base_args)
     }
@@ -1641,10 +1638,9 @@ pub fn print_path(&mut self,
             if segment.name != keywords::CrateRoot.name() &&
                segment.name != keywords::DollarCrate.name() {
                self.print_name(segment.name)?;
-               segment.with_parameters(|parameters| {
-                   self.print_path_parameters(parameters,
-                                              segment.infer_types,
-                                              colons_before_params)
+               segment.with_generic_args(|generic_args| {
+                   self.print_generic_args(generic_args, segment.infer_types,
+                                           colons_before_params)
                })?;
             }
         }
@@ -1673,10 +1669,10 @@ pub fn print_qpath(&mut self,
                     if segment.name != keywords::CrateRoot.name() &&
                        segment.name != keywords::DollarCrate.name() {
                         self.print_name(segment.name)?;
-                        segment.with_parameters(|parameters| {
-                            self.print_path_parameters(parameters,
-                                                       segment.infer_types,
-                                                       colons_before_params)
+                        segment.with_generic_args(|generic_args| {
+                            self.print_generic_args(generic_args,
+                                                    segment.infer_types,
+                                                    colons_before_params)
                         })?;
                     }
                 }
@@ -1685,10 +1681,10 @@ pub fn print_qpath(&mut self,
                 self.s.word("::")?;
                 let item_segment = path.segments.last().unwrap();
                 self.print_name(item_segment.name)?;
-                item_segment.with_parameters(|parameters| {
-                    self.print_path_parameters(parameters,
-                                               item_segment.infer_types,
-                                               colons_before_params)
+                item_segment.with_generic_args(|generic_args| {
+                    self.print_generic_args(generic_args,
+                                            item_segment.infer_types,
+                                            colons_before_params)
                 })
             }
             hir::QPath::TypeRelative(ref qself, ref item_segment) => {
@@ -1697,28 +1693,28 @@ pub fn print_qpath(&mut self,
                 self.s.word(">")?;
                 self.s.word("::")?;
                 self.print_name(item_segment.name)?;
-                item_segment.with_parameters(|parameters| {
-                    self.print_path_parameters(parameters,
-                                               item_segment.infer_types,
-                                               colons_before_params)
+                item_segment.with_generic_args(|generic_args| {
+                    self.print_generic_args(generic_args,
+                                            item_segment.infer_types,
+                                            colons_before_params)
                 })
             }
         }
     }
 
-    fn print_path_parameters(&mut self,
-                             parameters: &hir::PathParameters,
+    fn print_generic_args(&mut self,
+                             generic_args: &hir::GenericArgs,
                              infer_types: bool,
                              colons_before_params: bool)
                              -> io::Result<()> {
-        if parameters.parenthesized {
+        if generic_args.parenthesized {
             self.s.word("(")?;
-            self.commasep(Inconsistent, parameters.inputs(), |s, ty| s.print_type(&ty))?;
+            self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty))?;
             self.s.word(")")?;
 
             self.space_if_not_bol()?;
             self.word_space("->")?;
-            self.print_type(&parameters.bindings[0].ty)?;
+            self.print_type(&generic_args.bindings[0].ty)?;
         } else {
             let start = if colons_before_params { "::<" } else { "<" };
             let empty = Cell::new(true);
@@ -1731,16 +1727,31 @@ fn print_path_parameters(&mut self,
                 }
             };
 
-            if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) {
-                for lifetime in &parameters.lifetimes {
-                    start_or_comma(self)?;
-                    self.print_lifetime(lifetime)?;
+            let mut types = vec![];
+            let mut elide_lifetimes = true;
+            for arg in &generic_args.args {
+                match arg {
+                    GenericArg::Lifetime(lt) => {
+                        if !lt.is_elided() {
+                            elide_lifetimes = false;
+                        }
+                    }
+                    GenericArg::Type(ty) => {
+                        types.push(ty);
+                    }
                 }
             }
-
-            if !parameters.types.is_empty() {
+            if !elide_lifetimes {
+                start_or_comma(self)?;
+                self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
+                    match generic_arg {
+                        GenericArg::Lifetime(lt) => s.print_lifetime(lt),
+                        GenericArg::Type(ty) => s.print_type(ty),
+                    }
+                })?;
+            } else if !types.is_empty() {
                 start_or_comma(self)?;
-                self.commasep(Inconsistent, &parameters.types, |s, ty| s.print_type(&ty))?;
+                self.commasep(Inconsistent, &types, |s, ty| s.print_type(&ty))?;
             }
 
             // FIXME(eddyb) This would leak into error messages, e.g.:
@@ -1750,7 +1761,7 @@ fn print_path_parameters(&mut self,
                 self.s.word("..")?;
             }
 
-            for binding in parameters.bindings.iter() {
+            for binding in generic_args.bindings.iter() {
                 start_or_comma(self)?;
                 self.print_name(binding.name)?;
                 self.s.space()?;
@@ -2060,7 +2071,7 @@ pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureClause) -> io
         }
     }
 
-    pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io::Result<()> {
+    pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::GenericBound]) -> io::Result<()> {
         if !bounds.is_empty() {
             self.s.word(prefix)?;
             let mut first = true;
@@ -2075,13 +2086,13 @@ pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io
                 }
 
                 match bound {
-                    TraitTyParamBound(tref, modifier) => {
+                    GenericBound::Trait(tref, modifier) => {
                         if modifier == &TraitBoundModifier::Maybe {
                             self.s.word("?")?;
                         }
                         self.print_poly_trait_ref(tref)?;
                     }
-                    RegionTyParamBound(lt) => {
+                    GenericBound::Outlives(lt) => {
                         self.print_lifetime(lt)?;
                     }
                 }
@@ -2090,30 +2101,12 @@ pub fn print_bounds(&mut self, prefix: &str, bounds: &[hir::TyParamBound]) -> io
         Ok(())
     }
 
-    pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
-        self.print_name(lifetime.name.name())
-    }
-
-    pub fn print_lifetime_def(&mut self, lifetime: &hir::LifetimeDef) -> io::Result<()> {
-        self.print_lifetime(&lifetime.lifetime)?;
-        let mut sep = ":";
-        for v in &lifetime.bounds {
-            self.s.word(sep)?;
-            self.print_lifetime(v)?;
-            sep = "+";
-        }
-        Ok(())
-    }
-
-    pub fn print_generic_params(&mut self, generic_params: &[hir::GenericParam]) -> io::Result<()> {
+    pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) -> io::Result<()> {
         if !generic_params.is_empty() {
             self.s.word("<")?;
 
             self.commasep(Inconsistent, generic_params, |s, param| {
-                match *param {
-                    hir::GenericParam::Lifetime(ref ld) => s.print_lifetime_def(ld),
-                    hir::GenericParam::Type(ref tp) => s.print_ty_param(tp),
-                }
+                s.print_generic_param(param)
             })?;
 
             self.s.word(">")?;
@@ -2121,19 +2114,41 @@ pub fn print_generic_params(&mut self, generic_params: &[hir::GenericParam]) ->
         Ok(())
     }
 
-    pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
-        self.print_name(param.name)?;
-        self.print_bounds(":", &param.bounds)?;
-        match param.default {
-            Some(ref default) => {
-                self.s.space()?;
-                self.word_space("=")?;
-                self.print_type(&default)
+    pub fn print_generic_param(&mut self, param: &GenericParam) -> io::Result<()> {
+        self.print_name(param.name.name())?;
+        match param.kind {
+            GenericParamKind::Lifetime { .. } => {
+                let mut sep = ":";
+                for bound in &param.bounds {
+                    match bound {
+                        GenericBound::Outlives(lt) => {
+                            self.s.word(sep)?;
+                            self.print_lifetime(lt)?;
+                            sep = "+";
+                        }
+                        _ => bug!(),
+                    }
+                }
+                Ok(())
+            }
+            GenericParamKind::Type { ref default, .. } => {
+                self.print_bounds(":", &param.bounds)?;
+                match default {
+                    Some(default) => {
+                        self.s.space()?;
+                        self.word_space("=")?;
+                        self.print_type(&default)
+                    }
+                    _ => Ok(()),
+                }
             }
-            _ => Ok(()),
         }
     }
 
+    pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) -> io::Result<()> {
+        self.print_name(lifetime.name.name())
+    }
+
     pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Result<()> {
         if where_clause.predicates.is_empty() {
             return Ok(());
@@ -2165,7 +2180,12 @@ pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) -> io::Res
                     self.s.word(":")?;
 
                     for (i, bound) in bounds.iter().enumerate() {
-                        self.print_lifetime(bound)?;
+                        match bound {
+                            GenericBound::Outlives(lt) => {
+                                self.print_lifetime(lt)?;
+                            }
+                            _ => bug!(),
+                        }
 
                         if i != 0 {
                             self.s.word(":")?;
index ed259b2854511bd8c34eb994b0cc6a39ce990a4a..882194ae64e79df096a3df67768edc4a432b512c 100644 (file)
@@ -142,12 +142,16 @@ fn hash_stable<W: StableHasherResult>(&self,
     }
 }
 
+impl_stable_hash_for!(enum hir::ParamName {
+    Plain(name),
+    Fresh(index)
+});
+
 impl_stable_hash_for!(enum hir::LifetimeName {
+    Param(param_name),
     Implicit,
     Underscore,
-    Fresh(index),
     Static,
-    Name(name)
 });
 
 impl_stable_hash_for!(struct hir::Label {
@@ -161,13 +165,6 @@ fn hash_stable<W: StableHasherResult>(&self,
     name
 });
 
-impl_stable_hash_for!(struct hir::LifetimeDef {
-    lifetime,
-    bounds,
-    pure_wrt_drop,
-    in_band
-});
-
 impl_stable_hash_for!(struct hir::Path {
     span,
     def,
@@ -177,19 +174,23 @@ fn hash_stable<W: StableHasherResult>(&self,
 impl_stable_hash_for!(struct hir::PathSegment {
     name,
     infer_types,
-    parameters
+    args
 });
 
-impl_stable_hash_for!(struct hir::PathParameters {
-    lifetimes,
-    types,
+impl_stable_hash_for!(enum hir::GenericArg {
+    Lifetime(lt),
+    Type(ty)
+});
+
+impl_stable_hash_for!(struct hir::GenericArgs {
+    args,
     bindings,
     parenthesized
 });
 
-impl_stable_hash_for!(enum hir::TyParamBound {
-    TraitTyParamBound(poly_trait_ref, trait_bound_modifier),
-    RegionTyParamBound(lifetime)
+impl_stable_hash_for!(enum hir::GenericBound {
+    Trait(poly_trait_ref, trait_bound_modifier),
+    Outlives(lifetime)
 });
 
 impl_stable_hash_for!(enum hir::TraitBoundModifier {
@@ -197,21 +198,32 @@ fn hash_stable<W: StableHasherResult>(&self,
     Maybe
 });
 
-impl_stable_hash_for!(struct hir::TyParam {
-    name,
+impl_stable_hash_for!(struct hir::GenericParam {
     id,
-    bounds,
-    default,
+    name,
     span,
     pure_wrt_drop,
-    synthetic,
-    attrs
+    attrs,
+    bounds,
+    kind
 });
 
-impl_stable_hash_for!(enum hir::GenericParam {
-    Lifetime(lifetime_def),
-    Type(ty_param)
-});
+impl<'a> HashStable<StableHashingContext<'a>> for hir::GenericParamKind {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut StableHashingContext<'a>,
+                                          hasher: &mut StableHasher<W>) {
+        mem::discriminant(self).hash_stable(hcx, hasher);
+        match self {
+            hir::GenericParamKind::Lifetime { in_band } => {
+                in_band.hash_stable(hcx, hasher);
+            }
+            hir::GenericParamKind::Type { ref default, synthetic } => {
+                default.hash_stable(hcx, hasher);
+                synthetic.hash_stable(hcx, hasher);
+            }
+        }
+    }
+}
 
 impl_stable_hash_for!(struct hir::Generics {
     params,
index 5e67065d1c13fcbf1656b29f3c2c54c596f55ac8..684a1d2965838e2bda85440abf9f9c3d63762bba 100644 (file)
@@ -1373,16 +1373,46 @@ impl<'tcx, R> for struct infer::canonical::QueryResult<'tcx, R> {
     Proven, Ambiguous
 });
 
-impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for traits::WhereClauseAtom<'tcx> {
+impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for traits::WhereClause<'tcx> {
     fn hash_stable<W: StableHasherResult>(&self,
                                           hcx: &mut StableHashingContext<'a>,
                                           hasher: &mut StableHasher<W>) {
-        use traits::WhereClauseAtom::*;
+        use traits::WhereClause::*;
 
         mem::discriminant(self).hash_stable(hcx, hasher);
         match self {
             Implemented(trait_ref) => trait_ref.hash_stable(hcx, hasher),
             ProjectionEq(projection) => projection.hash_stable(hcx, hasher),
+            TypeOutlives(ty_outlives) => ty_outlives.hash_stable(hcx, hasher),
+            RegionOutlives(region_outlives) => region_outlives.hash_stable(hcx, hasher),
+        }
+    }
+}
+
+impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for traits::WellFormed<'tcx> {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut StableHashingContext<'a>,
+                                          hasher: &mut StableHasher<W>) {
+        use traits::WellFormed::*;
+
+        mem::discriminant(self).hash_stable(hcx, hasher);
+        match self {
+            Trait(trait_ref) => trait_ref.hash_stable(hcx, hasher),
+            Ty(ty) => ty.hash_stable(hcx, hasher),
+        }
+    }
+}
+
+impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for traits::FromEnv<'tcx> {
+    fn hash_stable<W: StableHasherResult>(&self,
+                                          hcx: &mut StableHashingContext<'a>,
+                                          hasher: &mut StableHasher<W>) {
+        use traits::FromEnv::*;
+
+        mem::discriminant(self).hash_stable(hcx, hasher);
+        match self {
+            Trait(trait_ref) => trait_ref.hash_stable(hcx, hasher),
+            Ty(ty) => ty.hash_stable(hcx, hasher),
         }
     }
 }
@@ -1395,15 +1425,10 @@ fn hash_stable<W: StableHasherResult>(&self,
 
         mem::discriminant(self).hash_stable(hcx, hasher);
         match self {
-            Holds(where_clause) |
-            WellFormed(where_clause) |
-            FromEnv(where_clause) => where_clause.hash_stable(hcx, hasher),
-
-            WellFormedTy(ty) => ty.hash_stable(hcx, hasher),
+            Holds(wc) => wc.hash_stable(hcx, hasher),
+            WellFormed(wf) => wf.hash_stable(hcx, hasher),
+            FromEnv(from_env) => from_env.hash_stable(hcx, hasher),
             Normalize(projection) => projection.hash_stable(hcx, hasher),
-            FromEnvTy(ty) => ty.hash_stable(hcx, hasher),
-            RegionOutlives(predicate) => predicate.hash_stable(hcx, hasher),
-            TypeOutlives(predicate) => predicate.hash_stable(hcx, hasher),
         }
     }
 }
index f068a54ce44479f27a49ce8a1e49d9416f1da2e1..5487da97d5b2a137348e04041e0e11af62ebf484 100644 (file)
@@ -434,8 +434,8 @@ pub fn infer_anon_definition_from_instantiation(
         instantiated_ty: Ty<'gcx>,
     ) -> Ty<'gcx> {
         debug!(
-            "infer_anon_definition_from_instantiation(instantiated_ty={:?})",
-            instantiated_ty
+            "infer_anon_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
+            def_id, instantiated_ty
         );
 
         let gcx = self.tcx.global_tcx();
index 4bde363672dcc68f4f08b845e4d75fe3dc0644b2..4d6f2fb41b05d7e5c5fa5512071b9aa2f9e0eacc 100644 (file)
@@ -1036,15 +1036,14 @@ pub fn report_generic_bound_failure(
                             // Get the `hir::TyParam` to verify whether it already has any bounds.
                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
                             // instead we suggest `T: 'a + 'b` in that case.
-                            let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) {
-                                p.bounds.len() > 0
-                            } else {
-                                false
-                            };
+                            let mut has_bounds = false;
+                            if let hir_map::NodeGenericParam(ref param) = hir.get(id) {
+                                has_bounds = !param.bounds.is_empty();
+                            }
                             let sp = hir.span(id);
                             // `sp` only covers `T`, change it so that it covers
                             // `T:` when appropriate
-                            let sp = if has_lifetimes {
+                            let sp = if has_bounds {
                                 sp.to(self.tcx
                                     .sess
                                     .codemap()
@@ -1052,7 +1051,7 @@ pub fn report_generic_bound_failure(
                             } else {
                                 sp
                             };
-                            (sp, has_lifetimes)
+                            (sp, has_bounds)
                         })
                     } else {
                         None
index 9fb7d31ed6f75d178128989b8ed8f643da5afc47..8ef45a966da85647992a661820e2af1c2aeb6a23 100644 (file)
@@ -313,7 +313,8 @@ pub fn consume_body(&mut self, body: &hir::Body) {
         debug!("consume_body(body={:?})", body);
 
         for arg in &body.arguments {
-            let arg_ty = return_if_err!(self.mc.node_ty(arg.pat.hir_id));
+            let arg_ty = return_if_err!(self.mc.pat_ty_adjusted(&arg.pat));
+            debug!("consume_body: arg_ty = {:?}", arg_ty);
 
             let fn_body_scope_r =
                 self.tcx().mk_region(ty::ReScope(region::Scope::Node(body.value.hir_id.local_id)));
index 959dda69e30ed81d69ab2f88b9ab4e35adb45339..597872ef45de047aade45f0ca805cbe8b5104acc 100644 (file)
@@ -517,7 +517,7 @@ pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
     ///   implicit deref patterns attached (e.g., it is really
     ///   `&Some(x)`). In that case, we return the "outermost" type
     ///   (e.g., `&Option<T>).
-    fn pat_ty(&self, pat: &hir::Pat) -> McResult<Ty<'tcx>> {
+    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
@@ -1300,7 +1300,7 @@ fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McR
             };
 
             for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
-                let subpat_ty = self.pat_ty(&subpat)?; // see (*2)
+                let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
                 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
                 let subcmt = Rc::new(self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
                 self.cat_pattern_(subcmt, &subpat, op)?;
@@ -1323,7 +1323,7 @@ fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McR
             };
 
             for fp in field_pats {
-                let field_ty = self.pat_ty(&fp.node.pat)?; // see (*2)
+                let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
                 let f_index = self.tcx.field_index(fp.node.id, self.tables);
                 let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
                                                        fp.node.ident, field_ty));
@@ -1342,7 +1342,7 @@ fn cat_pattern_<F>(&self, mut cmt: cmt<'tcx>, pat: &hir::Pat, op: &mut F) -> McR
                 ref ty => 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(&subpat)?; // see (*2)
+                let subpat_ty = self.pat_ty_unadjusted(&subpat)?; // see (*2)
                 let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
                 let subcmt = Rc::new(self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
                 self.cat_pattern_(subcmt, &subpat, op)?;
index 40cf78edaecaebef9dd958c2f3bba0083c9bb510..7f81af7e46c7d28eba9d3e59007261fef30e62f8 100644 (file)
@@ -20,7 +20,7 @@
 use hir::def::Def;
 use hir::def_id::{DefId, CrateNum};
 use rustc_data_structures::sync::Lrc;
-use ty::{self, TyCtxt};
+use ty::{self, TyCtxt, GenericParamDefKind};
 use ty::query::Providers;
 use middle::privacy;
 use session::config;
 
 // Returns true if the given set of generics implies that the item it's
 // associated with must be inlined.
-fn generics_require_inlining(generics: &hir::Generics) -> bool {
-    generics.params.iter().any(|param| param.is_type_param())
+fn generics_require_inlining(generics: &ty::Generics) -> bool {
+    for param in &generics.params {
+        match param.kind {
+            GenericParamDefKind::Lifetime { .. } => {}
+            GenericParamDefKind::Type { .. } => return true,
+        }
+    }
+    false
 }
 
 // Returns true if the given item must be inlined because it may be
 // monomorphized or it was marked with `#[inline]`. This will only return
 // true for functions.
-fn item_might_be_inlined(item: &hir::Item, attrs: CodegenFnAttrs) -> bool {
+fn item_might_be_inlined(tcx: TyCtxt<'a, 'tcx, 'tcx>,
+                         item: &hir::Item,
+                         attrs: CodegenFnAttrs) -> bool {
     if attrs.requests_inline() {
         return true
     }
 
     match item.node {
-        hir::ItemImpl(_, _, _, ref generics, ..) |
-        hir::ItemFn(.., ref generics, _) => {
+        hir::ItemImpl(..) |
+        hir::ItemFn(..) => {
+            let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
             generics_require_inlining(generics)
         }
         _ => false,
@@ -62,14 +71,14 @@ fn method_might_be_inlined<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                      impl_item: &hir::ImplItem,
                                      impl_src: DefId) -> bool {
     let codegen_fn_attrs = tcx.codegen_fn_attrs(impl_item.hir_id.owner_def_id());
-    if codegen_fn_attrs.requests_inline() ||
-        generics_require_inlining(&impl_item.generics) {
+    let generics = tcx.generics_of(tcx.hir.local_def_id(impl_item.id));
+    if codegen_fn_attrs.requests_inline() || generics_require_inlining(generics) {
         return true
     }
     if let Some(impl_node_id) = tcx.hir.as_local_node_id(impl_src) {
         match tcx.hir.find(impl_node_id) {
             Some(hir_map::NodeItem(item)) =>
-                item_might_be_inlined(&item, codegen_fn_attrs),
+                item_might_be_inlined(tcx, &item, codegen_fn_attrs),
             Some(..) | None =>
                 span_bug!(impl_item.span, "impl did is not an item")
         }
@@ -163,7 +172,7 @@ fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
             Some(hir_map::NodeItem(item)) => {
                 match item.node {
                     hir::ItemFn(..) =>
-                        item_might_be_inlined(&item, self.tcx.codegen_fn_attrs(def_id)),
+                        item_might_be_inlined(self.tcx, &item, self.tcx.codegen_fn_attrs(def_id)),
                     _ => false,
                 }
             }
@@ -180,7 +189,8 @@ fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
                     hir::ImplItemKind::Const(..) => true,
                     hir::ImplItemKind::Method(..) => {
                         let attrs = self.tcx.codegen_fn_attrs(def_id);
-                        if generics_require_inlining(&impl_item.generics) ||
+                        let generics = self.tcx.generics_of(def_id);
+                        if generics_require_inlining(&generics) ||
                                 attrs.requests_inline() {
                             true
                         } else {
@@ -192,8 +202,9 @@ fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
                             // does too.
                             let impl_node_id = self.tcx.hir.as_local_node_id(impl_did).unwrap();
                             match self.tcx.hir.expect_item(impl_node_id).node {
-                                hir::ItemImpl(_, _, _, ref generics, ..) => {
-                                    generics_require_inlining(generics)
+                                hir::ItemImpl(..) => {
+                                    let generics = self.tcx.generics_of(impl_did);
+                                    generics_require_inlining(&generics)
                                 }
                                 _ => false
                             }
@@ -251,7 +262,9 @@ fn propagate_node(&mut self, node: &hir_map::Node<'tcx>,
                 match item.node {
                     hir::ItemFn(.., body) => {
                         let def_id = self.tcx.hir.local_def_id(item.id);
-                        if item_might_be_inlined(&item, self.tcx.codegen_fn_attrs(def_id)) {
+                        if item_might_be_inlined(self.tcx,
+                                                 &item,
+                                                 self.tcx.codegen_fn_attrs(def_id)) {
                             self.visit_nested_body(body);
                         }
                     }
index f251a3d5f38380ab42226b9041aff44cc228cce7..f73e0ab2a9d774bcd2ed12ad896f0dea57597ccb 100644 (file)
@@ -18,8 +18,7 @@
 use hir::def::Def;
 use hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
 use hir::map::Map;
-use hir::ItemLocalId;
-use hir::LifetimeName;
+use hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, ParamName};
 use ty::{self, TyCtxt, GenericParamDefKind};
 
 use errors::DiagnosticBuilder;
 use session::Session;
 use std::cell::Cell;
 use std::mem::replace;
-use std::slice;
 use syntax::ast;
 use syntax::attr;
 use syntax::ptr::P;
+use syntax::symbol::keywords;
 use syntax_pos::Span;
 use util::nodemap::{DefIdMap, FxHashMap, FxHashSet, NodeMap, NodeSet};
 
 use hir::intravisit::{self, NestedVisitorMap, Visitor};
-use hir::{self, GenericParamsExt};
+use hir::{self, GenericParamKind};
 
 /// The origin of a named lifetime definition.
 ///
@@ -50,11 +49,16 @@ pub enum LifetimeDefOrigin {
 }
 
 impl LifetimeDefOrigin {
-    fn from_is_in_band(is_in_band: bool) -> Self {
-        if is_in_band {
-            LifetimeDefOrigin::InBand
-        } else {
-            LifetimeDefOrigin::Explicit
+    fn from_param(param: &GenericParam) -> Self {
+        match param.kind {
+            GenericParamKind::Lifetime { in_band } => {
+                if in_band {
+                    LifetimeDefOrigin::InBand
+                } else {
+                    LifetimeDefOrigin::Explicit
+                }
+            }
+            _ => bug!("expected a lifetime param"),
         }
     }
 }
@@ -84,31 +88,27 @@ pub enum Region {
 }
 
 impl Region {
-    fn early(
-        hir_map: &Map,
-        index: &mut u32,
-        def: &hir::LifetimeDef,
-    ) -> (hir::LifetimeName, Region) {
+    fn early(hir_map: &Map, index: &mut u32, param: &GenericParam) -> (ParamName, Region) {
         let i = *index;
         *index += 1;
-        let def_id = hir_map.local_def_id(def.lifetime.id);
-        let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
+        let def_id = hir_map.local_def_id(param.id);
+        let origin = LifetimeDefOrigin::from_param(param);
         debug!("Region::early: index={} def_id={:?}", i, def_id);
-        (def.lifetime.name, Region::EarlyBound(i, def_id, origin))
+        (param.name, Region::EarlyBound(i, def_id, origin))
     }
 
-    fn late(hir_map: &Map, def: &hir::LifetimeDef) -> (hir::LifetimeName, Region) {
+    fn late(hir_map: &Map, param: &GenericParam) -> (ParamName, Region) {
         let depth = ty::INNERMOST;
-        let def_id = hir_map.local_def_id(def.lifetime.id);
-        let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
+        let def_id = hir_map.local_def_id(param.id);
+        let origin = LifetimeDefOrigin::from_param(param);
         debug!(
-            "Region::late: def={:?} depth={:?} def_id={:?} origin={:?}",
-            def,
+            "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}",
+            param,
             depth,
             def_id,
             origin,
         );
-        (def.lifetime.name, Region::LateBound(depth, def_id, origin))
+        (param.name, Region::LateBound(depth, def_id, origin))
     }
 
     fn late_anon(index: &Cell<u32>) -> Region {
@@ -155,11 +155,10 @@ fn shifted_out_to_binder(self, binder: ty::DebruijnIndex) -> Region {
         }
     }
 
-    fn subst(self, params: &[hir::Lifetime], map: &NamedRegionMap) -> Option<Region> {
+    fn subst<'a, L>(self, mut params: L, map: &NamedRegionMap) -> Option<Region>
+            where L: Iterator<Item = &'a hir::Lifetime>  {
         if let Region::EarlyBound(index, _, _) = self {
-            params
-                .get(index as usize)
-                .and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
+            params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.id).cloned())
         } else {
             Some(self)
         }
@@ -270,7 +269,7 @@ enum Scope<'a> {
     /// it should be shifted by the number of `Binder`s in between the
     /// declaration `Binder` and the location it's referenced from.
     Binder {
-        lifetimes: FxHashMap<hir::LifetimeName, Region>,
+        lifetimes: FxHashMap<hir::ParamName, Region>,
 
         /// if we extend this scope with another scope, what is the next index
         /// we should use for an early-bound region?
@@ -524,14 +523,19 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
                 } else {
                     0
                 };
-                let lifetimes = generics
-                    .lifetimes()
-                    .map(|def| Region::early(&self.tcx.hir, &mut index, def))
-                    .collect();
-                let next_early_index = index + generics.ty_params().count() as u32;
+                let mut type_count = 0;
+                let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => {
+                        Some(Region::early(&self.tcx.hir, &mut index, param))
+                    }
+                    GenericParamKind::Type { .. } => {
+                        type_count += 1;
+                        None
+                    }
+                }).collect();
                 let scope = Scope::Binder {
                     lifetimes,
-                    next_early_index,
+                    next_early_index: index + type_count,
                     abstract_type_parent: true,
                     track_lifetime_uses,
                     s: ROOT_SCOPE,
@@ -568,10 +572,12 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                 let was_in_fn_syntax = self.is_in_fn_syntax;
                 self.is_in_fn_syntax = true;
                 let scope = Scope::Binder {
-                    lifetimes: c.generic_params
-                        .lifetimes()
-                        .map(|def| Region::late(&self.tcx.hir, def))
-                        .collect(),
+                    lifetimes: c.generic_params.iter().filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::late(&self.tcx.hir, param))
+                        }
+                        _ => None,
+                    }).collect(),
                     s: self.scope,
                     next_early_index,
                     track_lifetime_uses: true,
@@ -603,9 +609,9 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                         // resolved the same as the `'_` in `&'_ Foo`.
                         //
                         // cc #48468
-                        self.resolve_elided_lifetimes(slice::from_ref(lifetime), false)
+                        self.resolve_elided_lifetimes(vec![lifetime], false)
                     }
-                    LifetimeName::Fresh(_) | LifetimeName::Static | LifetimeName::Name(_) => {
+                    LifetimeName::Param(_) | LifetimeName::Static => {
                         // If the user wrote an explicit name, use that.
                         self.visit_lifetime(lifetime);
                     }
@@ -632,8 +638,8 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                     // and ban them. Type variables instantiated inside binders aren't
                     // well-supported at the moment, so this doesn't work.
                     // In the future, this should be fixed and this error should be removed.
-                    let def = self.map.defs.get(&lifetime.id);
-                    if let Some(&Region::LateBound(_, def_id, _)) = def {
+                    let def = self.map.defs.get(&lifetime.id).cloned();
+                    if let Some(Region::LateBound(_, def_id, _)) = def {
                         if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
                             // Ensure that the parent of the def is an item, not HRTB
                             let parent_id = self.tcx.hir.get_parent_node(node_id);
@@ -651,6 +657,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                                     "`impl Trait` can only capture lifetimes \
                                      bound at the fn or impl level"
                                 );
+                                self.uninsert_lifetime_on_error(lifetime, def.unwrap());
                             }
                         }
                     }
@@ -676,18 +683,29 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
 
                 let mut elision = None;
                 let mut lifetimes = FxHashMap();
-                for lt_def in generics.lifetimes() {
-                    let (lt_name, region) = Region::early(&self.tcx.hir, &mut index, &lt_def);
-                    if let hir::LifetimeName::Underscore = lt_name {
-                        // Pick the elided lifetime "definition" if one exists and use it to make
-                        // an elision scope.
-                        elision = Some(region);
-                    } else {
-                        lifetimes.insert(lt_name, region);
+                let mut type_count = 0;
+                for param in &generics.params {
+                    match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            let (name, reg) = Region::early(&self.tcx.hir, &mut index, &param);
+                            if let hir::ParamName::Plain(param_name) = name {
+                                if param_name == keywords::UnderscoreLifetime.name() {
+                                    // Pick the elided lifetime "definition" if one exists
+                                    // and use it to make an elision scope.
+                                    elision = Some(reg);
+                                } else {
+                                    lifetimes.insert(name, reg);
+                                }
+                            } else {
+                                lifetimes.insert(name, reg);
+                            }
+                        }
+                        GenericParamKind::Type { .. } => {
+                            type_count += 1;
+                        }
                     }
                 }
-
-                let next_early_index = index + generics.ty_params().count() as u32;
+                let next_early_index = index + type_count;
 
                 if let Some(elision_region) = elision {
                     let scope = Scope::Elision {
@@ -705,7 +723,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                         this.with(scope, |_old_scope, this| {
                             this.visit_generics(generics);
                             for bound in bounds {
-                                this.visit_ty_param_bound(bound);
+                                this.visit_param_bound(bound);
                             }
                         });
                     });
@@ -720,7 +738,7 @@ fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
                     self.with(scope, |_old_scope, this| {
                         this.visit_generics(generics);
                         for bound in bounds {
-                            this.visit_ty_param_bound(bound);
+                            this.visit_param_bound(bound);
                         }
                     });
                 }
@@ -745,15 +763,19 @@ fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
                 let generics = &trait_item.generics;
                 let mut index = self.next_early_index();
                 debug!("visit_ty: index = {}", index);
-                let lifetimes = generics
-                    .lifetimes()
-                    .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def))
-                    .collect();
-
-                let next_early_index = index + generics.ty_params().count() as u32;
+                let mut type_count = 0;
+                let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => {
+                        Some(Region::early(&self.tcx.hir, &mut index, param))
+                    }
+                    GenericParamKind::Type { .. } => {
+                        type_count += 1;
+                        None
+                    }
+                }).collect();
                 let scope = Scope::Binder {
                     lifetimes,
-                    next_early_index,
+                    next_early_index: index + type_count,
                     s: self.scope,
                     track_lifetime_uses: true,
                     abstract_type_parent: true,
@@ -761,7 +783,7 @@ fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
                 self.with(scope, |_old_scope, this| {
                     this.visit_generics(generics);
                     for bound in bounds {
-                        this.visit_ty_param_bound(bound);
+                        this.visit_param_bound(bound);
                     }
                     if let Some(ty) = ty {
                         this.visit_ty(ty);
@@ -791,13 +813,17 @@ fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
             Type(ref ty) => {
                 let generics = &impl_item.generics;
                 let mut index = self.next_early_index();
+                let mut next_early_index = index;
                 debug!("visit_ty: index = {}", index);
-                let lifetimes = generics
-                    .lifetimes()
-                    .map(|lt_def| Region::early(&self.tcx.hir, &mut index, lt_def))
-                    .collect();
-
-                let next_early_index = index + generics.ty_params().count() as u32;
+                let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => {
+                        Some(Region::early(&self.tcx.hir, &mut index, param))
+                    }
+                    GenericParamKind::Type { .. } => {
+                        next_early_index += 1;
+                        None
+                    }
+                }).collect();
                 let scope = Scope::Binder {
                     lifetimes,
                     next_early_index,
@@ -820,7 +846,7 @@ fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
 
     fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
         if lifetime_ref.is_elided() {
-            self.resolve_elided_lifetimes(slice::from_ref(lifetime_ref), false);
+            self.resolve_elided_lifetimes(vec![lifetime_ref], false);
             return;
         }
         if lifetime_ref.is_static() {
@@ -833,8 +859,8 @@ fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
     fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
         for (i, segment) in path.segments.iter().enumerate() {
             let depth = path.segments.len() - i - 1;
-            if let Some(ref parameters) = segment.parameters {
-                self.visit_segment_parameters(path.def, depth, parameters);
+            if let Some(ref args) = segment.args {
+                self.visit_segment_args(path.def, depth, args);
             }
         }
     }
@@ -848,14 +874,16 @@ fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) {
     }
 
     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
-        check_mixed_explicit_and_in_band_defs(
-            self.tcx,
-            &generics.lifetimes().cloned().collect::<Vec<_>>(),
-        );
-        for ty_param in generics.ty_params() {
-            walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
-            if let Some(ref ty) = ty_param.default {
-                self.visit_ty(&ty);
+        check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params);
+        for param in &generics.params {
+            match param.kind {
+                GenericParamKind::Lifetime { .. } => {}
+                GenericParamKind::Type { ref default, .. } => {
+                    walk_list!(self, visit_param_bound, &param.bounds);
+                    if let Some(ref ty) = default {
+                        self.visit_ty(&ty);
+                    }
+                }
             }
         }
         for predicate in &generics.where_clause.predicates {
@@ -866,14 +894,18 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
                     ref bound_generic_params,
                     ..
                 }) => {
-                    if bound_generic_params.iter().any(|p| p.is_lifetime_param()) {
+                    let lifetimes: FxHashMap<_, _> = bound_generic_params.iter()
+                        .filter_map(|param| match param.kind {
+                            GenericParamKind::Lifetime { .. } => {
+                                Some(Region::late(&self.tcx.hir, param))
+                            }
+                            _ => None,
+                        }).collect();
+                    if !lifetimes.is_empty() {
                         self.trait_ref_hack = true;
                         let next_early_index = self.next_early_index();
                         let scope = Scope::Binder {
-                            lifetimes: bound_generic_params
-                                .lifetimes()
-                                .map(|def| Region::late(&self.tcx.hir, def))
-                                .collect(),
+                            lifetimes,
                             s: self.scope,
                             next_early_index,
                             track_lifetime_uses: true,
@@ -882,13 +914,13 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
                         let result = self.with(scope, |old_scope, this| {
                             this.check_lifetime_params(old_scope, &bound_generic_params);
                             this.visit_ty(&bounded_ty);
-                            walk_list!(this, visit_ty_param_bound, bounds);
+                            walk_list!(this, visit_param_bound, bounds);
                         });
                         self.trait_ref_hack = false;
                         result
                     } else {
                         self.visit_ty(&bounded_ty);
-                        walk_list!(self, visit_ty_param_bound, bounds);
+                        walk_list!(self, visit_param_bound, bounds);
                     }
                 }
                 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
@@ -897,9 +929,7 @@ fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
                     ..
                 }) => {
                     self.visit_lifetime(lifetime);
-                    for bound in bounds {
-                        self.visit_lifetime(bound);
-                    }
+                    walk_list!(self, visit_param_bound, bounds);
                 }
                 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
                     ref lhs_ty,
@@ -924,7 +954,10 @@ fn visit_poly_trait_ref(
             || trait_ref
                 .bound_generic_params
                 .iter()
-                .any(|p| p.is_lifetime_param())
+                .any(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => true,
+                    _ => false,
+                })
         {
             if self.trait_ref_hack {
                 span_err!(
@@ -936,11 +969,13 @@ fn visit_poly_trait_ref(
             }
             let next_early_index = self.next_early_index();
             let scope = Scope::Binder {
-                lifetimes: trait_ref
-                    .bound_generic_params
-                    .lifetimes()
-                    .map(|def| Region::late(&self.tcx.hir, def))
-                    .collect(),
+                lifetimes: trait_ref.bound_generic_params.iter()
+                    .filter_map(|param| match param.kind {
+                        GenericParamKind::Lifetime { .. } => {
+                            Some(Region::late(&self.tcx.hir, param))
+                        }
+                        _ => None,
+                    }).collect(),
                 s: self.scope,
                 next_early_index,
                 track_lifetime_uses: true,
@@ -989,10 +1024,10 @@ fn original_lifetime(span: Span) -> Original {
         span: span,
     }
 }
-fn shadower_lifetime(l: &hir::Lifetime) -> Shadower {
+fn shadower_lifetime(param: &hir::GenericParam) -> Shadower {
     Shadower {
         kind: ShadowKind::Lifetime,
-        span: l.span,
+        span: param.span,
     }
 }
 
@@ -1007,23 +1042,27 @@ fn desc(&self) -> &'static str {
 
 fn check_mixed_explicit_and_in_band_defs(
     tcx: TyCtxt<'_, '_, '_>,
-    lifetime_defs: &[hir::LifetimeDef],
+    params: &P<[hir::GenericParam]>,
 ) {
-    let oob_def = lifetime_defs.iter().find(|lt| !lt.in_band);
-    let in_band_def = lifetime_defs.iter().find(|lt| lt.in_band);
-
-    if let (Some(oob_def), Some(in_band_def)) = (oob_def, in_band_def) {
+    let in_bands: Vec<_> = params.iter().filter_map(|param| match param.kind {
+        GenericParamKind::Lifetime { in_band, .. } => Some((in_band, param.span)),
+        _ => None,
+    }).collect();
+    let out_of_band = in_bands.iter().find(|(in_band, _)| !in_band);
+    let in_band = in_bands.iter().find(|(in_band, _)| *in_band);
+
+    if let (Some((_, out_of_band_span)), Some((_, in_band_span)))
+        = (out_of_band, in_band) {
         struct_span_err!(
             tcx.sess,
-            in_band_def.lifetime.span,
+            *in_band_span,
             E0688,
             "cannot mix in-band and explicit lifetime definitions"
         ).span_label(
-            in_band_def.lifetime.span,
+            *in_band_span,
             "in-band lifetime definition here",
-        )
-            .span_label(oob_def.lifetime.span, "explicit lifetime definition here")
-            .emit();
+        ).span_label(*out_of_band_span, "explicit lifetime definition here")
+        .emit();
     }
 }
 
@@ -1138,7 +1177,8 @@ fn check_if_label_shadows_lifetime(
                     ref lifetimes, s, ..
                 } => {
                     // FIXME (#24278): non-hygienic comparison
-                    if let Some(def) = lifetimes.get(&hir::LifetimeName::Name(label)) {
+                    let param_name = hir::ParamName::Plain(label);
+                    if let Some(def) = lifetimes.get(&param_name) {
                         let node_id = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
 
                         signal_shadowing_problem(
@@ -1176,14 +1216,18 @@ fn compute_object_lifetime_defaults(
                         .map(|set| match *set {
                             Set1::Empty => "BaseDefault".to_string(),
                             Set1::One(Region::Static) => "'static".to_string(),
-                            Set1::One(Region::EarlyBound(i, _, _)) => generics
-                                .lifetimes()
-                                .nth(i as usize)
-                                .unwrap()
-                                .lifetime
-                                .name
-                                .name()
-                                .to_string(),
+                            Set1::One(Region::EarlyBound(mut i, _, _)) => {
+                                generics.params.iter().find_map(|param| match param.kind {
+                                        GenericParamKind::Lifetime { .. } => {
+                                            if i == 0 {
+                                                return Some(param.name.name().to_string());
+                                            }
+                                            i -= 1;
+                                            None
+                                        }
+                                        _ => None,
+                                    }).unwrap()
+                            }
                             Set1::One(_) => bug!(),
                             Set1::Many => "Ambiguous".to_string(),
                         })
@@ -1207,17 +1251,17 @@ fn object_lifetime_defaults_for_item(
     tcx: TyCtxt<'_, '_, '_>,
     generics: &hir::Generics,
 ) -> Vec<ObjectLifetimeDefault> {
-    fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::TyParamBound]) {
+    fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::GenericBound]) {
         for bound in bounds {
-            if let hir::RegionTyParamBound(ref lifetime) = *bound {
+            if let hir::GenericBound::Outlives(ref lifetime) = *bound {
                 set.insert(lifetime.name);
             }
         }
     }
 
-    generics
-        .ty_params()
-        .map(|param| {
+    generics.params.iter().filter_map(|param| match param.kind {
+        GenericParamKind::Lifetime { .. } => None,
+        GenericParamKind::Type { .. } => {
             let mut set = Set1::Empty;
 
             add_bounds(&mut set, &param.bounds);
@@ -1246,27 +1290,35 @@ fn add_bounds(set: &mut Set1<hir::LifetimeName>, bounds: &[hir::TyParamBound]) {
                 }
             }
 
-            match set {
+            Some(match set {
                 Set1::Empty => Set1::Empty,
                 Set1::One(name) => {
                     if name == hir::LifetimeName::Static {
                         Set1::One(Region::Static)
                     } else {
-                        generics
-                            .lifetimes()
-                            .enumerate()
-                            .find(|&(_, def)| def.lifetime.name == name)
-                            .map_or(Set1::Many, |(i, def)| {
-                                let def_id = tcx.hir.local_def_id(def.lifetime.id);
-                                let origin = LifetimeDefOrigin::from_is_in_band(def.in_band);
-                                Set1::One(Region::EarlyBound(i as u32, def_id, origin))
-                            })
+                        generics.params.iter().filter_map(|param| match param.kind {
+                            GenericParamKind::Lifetime { .. } => {
+                                Some((
+                                    param.id,
+                                    hir::LifetimeName::Param(param.name),
+                                    LifetimeDefOrigin::from_param(param),
+                                ))
+                            }
+                            _ => None,
+                        })
+                        .enumerate()
+                        .find(|&(_, (_, lt_name, _))| lt_name == name)
+                        .map_or(Set1::Many, |(i, (id, _, origin))| {
+                            let def_id = tcx.hir.local_def_id(id);
+                            Set1::One(Region::EarlyBound(i as u32, def_id, origin))
+                        })
                     }
                 }
                 Set1::Many => Set1::Many,
-            }
-        })
-        .collect()
+            })
+        }
+    })
+    .collect()
 }
 
 impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
@@ -1346,25 +1398,22 @@ fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
                 Some(LifetimeUseSet::One(_)) => {
                     let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
                     debug!("node id first={:?}", node_id);
-                    if let hir::map::NodeLifetime(hir_lifetime) = self.tcx.hir.get(node_id) {
-                        let span = hir_lifetime.span;
-                        let id = hir_lifetime.id;
-                        debug!(
-                            "id ={:?} span = {:?} hir_lifetime = {:?}",
-                            node_id, span, hir_lifetime
-                        );
-
-                        self.tcx
-                            .struct_span_lint_node(
-                                lint::builtin::SINGLE_USE_LIFETIMES,
-                                id,
-                                span,
-                                &format!(
-                                    "lifetime parameter `{}` only used once",
-                                    hir_lifetime.name.name()
-                                ),
-                            )
-                            .emit();
+                    if let Some((id, span, name)) = match self.tcx.hir.get(node_id) {
+                        hir::map::NodeLifetime(hir_lifetime) => {
+                            Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name()))
+                        }
+                        hir::map::NodeGenericParam(param) => {
+                            Some((param.id, param.span, param.name.name()))
+                        }
+                        _ => None,
+                    } {
+                        debug!("id = {:?} span = {:?} name = {:?}", node_id, span, name);
+                        self.tcx.struct_span_lint_node(
+                            lint::builtin::SINGLE_USE_LIFETIMES,
+                            id,
+                            span,
+                            &format!("lifetime parameter `{}` only used once", name),
+                        ).emit();
                     }
                 }
                 Some(LifetimeUseSet::Many) => {
@@ -1372,21 +1421,22 @@ fn check_uses_for_lifetimes_defined_by_scope(&mut self) {
                 }
                 None => {
                     let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
-                    if let hir::map::NodeLifetime(hir_lifetime) = self.tcx.hir.get(node_id) {
-                        let span = hir_lifetime.span;
-                        let id = hir_lifetime.id;
-
-                        self.tcx
-                            .struct_span_lint_node(
-                                lint::builtin::UNUSED_LIFETIMES,
-                                id,
-                                span,
-                                &format!(
-                                    "lifetime parameter `{}` never used",
-                                    hir_lifetime.name.name()
-                                ),
-                            )
-                            .emit();
+                    if let Some((id, span, name)) = match self.tcx.hir.get(node_id) {
+                        hir::map::NodeLifetime(hir_lifetime) => {
+                            Some((hir_lifetime.id, hir_lifetime.span, hir_lifetime.name.name()))
+                        }
+                        hir::map::NodeGenericParam(param) => {
+                            Some((param.id, param.span, param.name.name()))
+                        }
+                        _ => None,
+                    } {
+                        debug!("id ={:?} span = {:?} name = {:?}", node_id, span, name);
+                        self.tcx.struct_span_lint_node(
+                            lint::builtin::UNUSED_LIFETIMES,
+                            id,
+                            span,
+                            &format!("lifetime parameter `{}` never used", name)
+                        ).emit();
                     }
                 }
             }
@@ -1438,18 +1488,21 @@ fn visit_early_late<F>(
             }
         }
 
-        let lifetimes = generics
-            .lifetimes()
-            .map(|def| {
-                if self.map.late_bound.contains(&def.lifetime.id) {
-                    Region::late(&self.tcx.hir, def)
+        let mut type_count = 0;
+        let lifetimes = generics.params.iter().filter_map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => {
+                if self.map.late_bound.contains(&param.id) {
+                    Some(Region::late(&self.tcx.hir, param))
                 } else {
-                    Region::early(&self.tcx.hir, &mut index, def)
+                    Some(Region::early(&self.tcx.hir, &mut index, param))
                 }
-            })
-            .collect();
-
-        let next_early_index = index + generics.ty_params().count() as u32;
+            }
+            GenericParamKind::Type { .. } => {
+                type_count += 1;
+                None
+            }
+        }).collect();
+        let next_early_index = index + type_count;
 
         let scope = Scope::Binder {
             lifetimes,
@@ -1521,10 +1574,12 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
                     break None;
                 }
 
-                Scope::Binder {
-                    ref lifetimes, s, ..
-                } => {
-                    if let Some(&def) = lifetimes.get(&lifetime_ref.name) {
+                Scope::Binder { ref lifetimes, s, .. } => {
+                    let name = match lifetime_ref.name {
+                        LifetimeName::Param(param_name) => param_name,
+                        _ => bug!("expected LifetimeName::Param"),
+                    };
+                    if let Some(&def) = lifetimes.get(&name) {
                         break Some(def.shifted(late_depth));
                     } else {
                         late_depth += 1;
@@ -1599,26 +1654,35 @@ fn resolve_lifetime_ref(&mut self, lifetime_ref: &'tcx hir::Lifetime) {
         }
     }
 
-    fn visit_segment_parameters(
+    fn visit_segment_args(
         &mut self,
         def: Def,
         depth: usize,
-        params: &'tcx hir::PathParameters,
+        generic_args: &'tcx hir::GenericArgs,
     ) {
-        if params.parenthesized {
+        if generic_args.parenthesized {
             let was_in_fn_syntax = self.is_in_fn_syntax;
             self.is_in_fn_syntax = true;
-            self.visit_fn_like_elision(params.inputs(), Some(&params.bindings[0].ty));
+            self.visit_fn_like_elision(generic_args.inputs(),
+                                       Some(&generic_args.bindings[0].ty));
             self.is_in_fn_syntax = was_in_fn_syntax;
             return;
         }
 
-        if params.lifetimes.iter().all(|l| l.is_elided()) {
-            self.resolve_elided_lifetimes(&params.lifetimes, true);
-        } else {
-            for l in &params.lifetimes {
-                self.visit_lifetime(l);
+        let mut elide_lifetimes = true;
+        let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
+            hir::GenericArg::Lifetime(lt) => {
+                if !lt.is_elided() {
+                    elide_lifetimes = false;
+                }
+                Some(lt)
             }
+            _ => None,
+        }).collect();
+        if elide_lifetimes {
+            self.resolve_elided_lifetimes(lifetimes, true);
+        } else {
+            lifetimes.iter().for_each(|lt| self.visit_lifetime(lt));
         }
 
         // Figure out if this is a type/trait segment,
@@ -1680,33 +1744,45 @@ fn visit_segment_parameters(
                         }).collect()
                     })
             };
-            unsubst
-                .iter()
-                .map(|set| match *set {
-                    Set1::Empty => if in_body {
-                        None
-                    } else {
-                        Some(Region::Static)
-                    },
-                    Set1::One(r) => r.subst(&params.lifetimes, map),
-                    Set1::Many => None,
-                })
-                .collect()
+            unsubst.iter()
+                   .map(|set| match *set {
+                       Set1::Empty => if in_body {
+                           None
+                       } else {
+                           Some(Region::Static)
+                       },
+                       Set1::One(r) => {
+                           let lifetimes = generic_args.args.iter().filter_map(|arg| match arg {
+                               GenericArg::Lifetime(lt) => Some(lt),
+                               _ => None,
+                           });
+                           r.subst(lifetimes, map)
+                       }
+                       Set1::Many => None,
+                   })
+                   .collect()
         });
 
-        for (i, ty) in params.types.iter().enumerate() {
-            if let Some(&lt) = object_lifetime_defaults.get(i) {
-                let scope = Scope::ObjectLifetimeDefault {
-                    lifetime: lt,
-                    s: self.scope,
-                };
-                self.with(scope, |_, this| this.visit_ty(ty));
-            } else {
-                self.visit_ty(ty);
+        let mut i = 0;
+        for arg in &generic_args.args {
+            match arg {
+                GenericArg::Lifetime(_) => {}
+                GenericArg::Type(ty) => {
+                    if let Some(&lt) = object_lifetime_defaults.get(i) {
+                        let scope = Scope::ObjectLifetimeDefault {
+                            lifetime: lt,
+                            s: self.scope,
+                        };
+                        self.with(scope, |_, this| this.visit_ty(ty));
+                    } else {
+                        self.visit_ty(ty);
+                    }
+                    i += 1;
+                }
             }
         }
 
-        for b in &params.bindings {
+        for b in &generic_args.bindings {
             self.visit_assoc_type_binding(b);
         }
     }
@@ -1944,7 +2020,7 @@ fn visit_ty(&mut self, ty: &hir::Ty) {
             }
 
             fn visit_generic_param(&mut self, param: &hir::GenericParam) {
-                if let hir::GenericParam::Lifetime(_) = *param {
+                if let hir::GenericParamKind::Lifetime { .. } = param.kind {
                     // FIXME(eddyb) Do we want this? It only makes a difference
                     // if this `for<'a>` lifetime parameter is never used.
                     self.have_bound_regions = true;
@@ -1981,7 +2057,9 @@ fn visit_lifetime(&mut self, lifetime_ref: &hir::Lifetime) {
         }
     }
 
-    fn resolve_elided_lifetimes(&mut self, lifetime_refs: &'tcx [hir::Lifetime], deprecated: bool) {
+    fn resolve_elided_lifetimes(&mut self,
+                                lifetime_refs: Vec<&'tcx hir::Lifetime>,
+                                deprecated: bool) {
         if lifetime_refs.is_empty() {
             return;
         }
@@ -2159,100 +2237,99 @@ fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime)
     }
 
     fn check_lifetime_params(&mut self, old_scope: ScopeRef, params: &'tcx [hir::GenericParam]) {
-        for (i, lifetime_i) in params.lifetimes().enumerate() {
-            match lifetime_i.lifetime.name {
-                hir::LifetimeName::Static | hir::LifetimeName::Underscore => {
-                    let lifetime = lifetime_i.lifetime;
-                    let name = lifetime.name.name();
+        let lifetimes: Vec<_> = params.iter().filter_map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => Some((param, param.name)),
+            _ => None,
+        }).collect();
+        for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() {
+            if let hir::ParamName::Plain(_) = lifetime_i_name {
+                let name = lifetime_i_name.name();
+                if name == keywords::UnderscoreLifetime.name() ||
+                   name == keywords::StaticLifetime.name() {
                     let mut err = struct_span_err!(
                         self.tcx.sess,
-                        lifetime.span,
+                        lifetime_i.span,
                         E0262,
                         "invalid lifetime parameter name: `{}`",
                         name
                     );
                     err.span_label(
-                        lifetime.span,
+                        lifetime_i.span,
                         format!("{} is a reserved lifetime name", name),
                     );
                     err.emit();
                 }
-                hir::LifetimeName::Fresh(_)
-                | hir::LifetimeName::Implicit
-                | hir::LifetimeName::Name(_) => {}
             }
 
             // It is a hard error to shadow a lifetime within the same scope.
-            for lifetime_j in params.lifetimes().skip(i + 1) {
-                if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
+            for (lifetime_j, lifetime_j_name) in lifetimes.iter().skip(i + 1) {
+                if lifetime_i_name == lifetime_j_name {
                     struct_span_err!(
                         self.tcx.sess,
-                        lifetime_j.lifetime.span,
+                        lifetime_j.span,
                         E0263,
                         "lifetime name `{}` declared twice in the same scope",
-                        lifetime_j.lifetime.name.name()
-                    ).span_label(lifetime_j.lifetime.span, "declared twice")
-                        .span_label(lifetime_i.lifetime.span, "previous declaration here")
-                        .emit();
+                        lifetime_j.name.name()
+                    ).span_label(lifetime_j.span, "declared twice")
+                     .span_label(lifetime_i.span, "previous declaration here")
+                     .emit();
                 }
             }
 
             // It is a soft error to shadow a lifetime within a parent scope.
-            self.check_lifetime_def_for_shadowing(old_scope, &lifetime_i.lifetime);
+            self.check_lifetime_param_for_shadowing(old_scope, &lifetime_i);
 
             for bound in &lifetime_i.bounds {
-                match bound.name {
-                    hir::LifetimeName::Underscore => {
-                        let mut err = struct_span_err!(
-                            self.tcx.sess,
-                            bound.span,
-                            E0637,
-                            "invalid lifetime bound name: `'_`"
-                        );
-                        err.span_label(bound.span, "`'_` is a reserved lifetime name");
-                        err.emit();
-                    }
-                    hir::LifetimeName::Static => {
-                        self.insert_lifetime(bound, Region::Static);
-                        self.tcx
-                            .sess
-                            .struct_span_warn(
-                                lifetime_i.lifetime.span.to(bound.span),
+                match bound {
+                    hir::GenericBound::Outlives(lt) => match lt.name {
+                        hir::LifetimeName::Underscore => {
+                            let mut err = struct_span_err!(
+                                self.tcx.sess,
+                                lt.span,
+                                E0637,
+                                "invalid lifetime bound name: `'_`"
+                            );
+                            err.span_label(lt.span, "`'_` is a reserved lifetime name");
+                            err.emit();
+                        }
+                        hir::LifetimeName::Static => {
+                            self.insert_lifetime(lt, Region::Static);
+                            self.tcx.sess.struct_span_warn(
+                                lifetime_i.span.to(lt.span),
                                 &format!(
                                     "unnecessary lifetime parameter `{}`",
-                                    lifetime_i.lifetime.name.name()
+                                    lifetime_i.name.name(),
                                 ),
-                            )
-                            .help(&format!(
+                            ).help(&format!(
                                 "you can use the `'static` lifetime directly, in place \
-                                 of `{}`",
-                                lifetime_i.lifetime.name.name()
-                            ))
-                            .emit();
-                    }
-                    hir::LifetimeName::Fresh(_)
-                    | hir::LifetimeName::Implicit
-                    | hir::LifetimeName::Name(_) => {
-                        self.resolve_lifetime_ref(bound);
+                                    of `{}`",
+                                lifetime_i.name.name(),
+                            )).emit();
+                        }
+                        hir::LifetimeName::Param(_)
+                        | hir::LifetimeName::Implicit => {
+                            self.resolve_lifetime_ref(lt);
+                        }
                     }
+                    _ => bug!(),
                 }
             }
         }
     }
 
-    fn check_lifetime_def_for_shadowing(
+    fn check_lifetime_param_for_shadowing(
         &self,
         mut old_scope: ScopeRef,
-        lifetime: &'tcx hir::Lifetime,
+        param: &'tcx hir::GenericParam,
     ) {
         for &(label, label_span) in &self.labels_in_fn {
             // FIXME (#24278): non-hygienic comparison
-            if lifetime.name.name() == label {
+            if param.name.name() == label {
                 signal_shadowing_problem(
                     self.tcx,
                     label,
                     original_label(label_span),
-                    shadower_lifetime(&lifetime),
+                    shadower_lifetime(&param),
                 );
                 return;
             }
@@ -2273,14 +2350,14 @@ fn check_lifetime_def_for_shadowing(
                 Scope::Binder {
                     ref lifetimes, s, ..
                 } => {
-                    if let Some(&def) = lifetimes.get(&lifetime.name) {
+                    if let Some(&def) = lifetimes.get(&param.name) {
                         let node_id = self.tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
 
                         signal_shadowing_problem(
                             self.tcx,
-                            lifetime.name.name(),
+                            param.name.name(),
                             original_lifetime(self.tcx.hir.span(node_id)),
-                            shadower_lifetime(&lifetime),
+                            shadower_lifetime(&param),
                         );
                         return;
                     }
@@ -2377,6 +2454,14 @@ fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) {
             }
         }
     }
+
+    /// Sometimes we resolve a lifetime, but later find that it is an
+    /// error (esp. around impl trait). In that case, we remove the
+    /// entry into `map.defs` so as not to confuse later code.
+    fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) {
+        let old_value = self.map.defs.remove(&lifetime_ref.id);
+        assert_eq!(old_value, Some(bad_def));
+    }
 }
 
 ///////////////////////////////////////////////////////////////////////////
@@ -2428,14 +2513,14 @@ fn insert_late_bound_lifetimes(
     appears_in_where_clause.visit_generics(generics);
 
     for param in &generics.params {
-        match *param {
-            hir::GenericParam::Lifetime(ref lifetime_def) => {
-                if !lifetime_def.bounds.is_empty() {
+        match param.kind {
+            hir::GenericParamKind::Lifetime { .. } => {
+                if !param.bounds.is_empty() {
                     // `'a: 'b` means both `'a` and `'b` are referenced
-                    appears_in_where_clause.regions.insert(lifetime_def.lifetime.name);
+                    appears_in_where_clause.regions.insert(hir::LifetimeName::Param(param.name));
                 }
             }
-            hir::GenericParam::Type(_) => {}
+            hir::GenericParamKind::Type { .. } => {}
         }
     }
 
@@ -2448,33 +2533,26 @@ fn insert_late_bound_lifetimes(
     // - appear in the inputs
     // - do not appear in the where-clauses
     // - are not implicitly captured by `impl Trait`
-    for lifetime in generics.lifetimes() {
-        let name = lifetime.lifetime.name;
-
+    for param in &generics.params {
+        let lt_name = hir::LifetimeName::Param(param.name);
         // appears in the where clauses? early-bound.
-        if appears_in_where_clause.regions.contains(&name) {
+        if appears_in_where_clause.regions.contains(&lt_name) {
             continue;
         }
 
         // does not appear in the inputs, but appears in the return type? early-bound.
-        if !constrained_by_input.regions.contains(&name)
-            && appears_in_output.regions.contains(&name)
+        if !constrained_by_input.regions.contains(&lt_name)
+            && appears_in_output.regions.contains(&lt_name)
         {
             continue;
         }
 
-        debug!(
-            "insert_late_bound_lifetimes: \
-             lifetime {:?} with id {:?} is late-bound",
-            lifetime.lifetime.name, lifetime.lifetime.id
-        );
+        debug!("insert_late_bound_lifetimes: lifetime {:?} with id {:?} is late-bound",
+               param.name.name(),
+               param.id);
 
-        let inserted = map.late_bound.insert(lifetime.lifetime.id);
-        assert!(
-            inserted,
-            "visited lifetime {:?} twice",
-            lifetime.lifetime.id
-        );
+        let inserted = map.late_bound.insert(param.id);
+        assert!(inserted, "visited lifetime {:?} twice", param.id);
     }
 
     return;
index b2ff36cb87c78f8876a6613c5e5038ecaa39b777..87fb0a6b70ace31e42352020b9097e26520dc754 100644 (file)
 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir.html
 
 use graphviz::IntoCow;
-use middle::region;
-use rustc_data_structures::sync::{Lrc};
-use rustc_data_structures::indexed_vec::{IndexVec, Idx};
-use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators};
-use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
-use rustc_data_structures::control_flow_graph::ControlFlowGraph;
-use rustc_data_structures::small_vec::SmallVec;
-use rustc_serialize as serialize;
 use hir::def::CtorKind;
 use hir::def_id::DefId;
-use mir::visit::MirVisitable;
-use mir::interpret::{Value, Scalar, EvalErrorKind};
-use ty::subst::{Subst, Substs};
-use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
-use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
-use util::ppaux;
-use std::slice;
 use hir::{self, InlineAsm};
-use std::borrow::{Cow};
+use middle::region;
+use mir::interpret::{EvalErrorKind, Scalar, Value};
+use mir::visit::MirVisitable;
+use rustc_apfloat::ieee::{Double, Single};
+use rustc_apfloat::Float;
+use rustc_data_structures::control_flow_graph::dominators::{dominators, Dominators};
+use rustc_data_structures::control_flow_graph::ControlFlowGraph;
+use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors};
+use rustc_data_structures::indexed_vec::{Idx, IndexVec};
+use rustc_data_structures::small_vec::SmallVec;
+use rustc_data_structures::sync::Lrc;
 use rustc_data_structures::sync::ReadGuard;
+use rustc_serialize as serialize;
+use std::borrow::Cow;
 use std::fmt::{self, Debug, Formatter, Write};
-use std::{iter, mem, option, u32};
 use std::ops::{Index, IndexMut};
+use std::slice;
 use std::vec::IntoIter;
+use std::{iter, mem, option, u32};
 use syntax::ast::{self, Name};
 use syntax::symbol::InternedString;
 use syntax_pos::{Span, DUMMY_SP};
-use rustc_apfloat::ieee::{Single, Double};
-use rustc_apfloat::Float;
+use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
+use ty::subst::{Subst, Substs};
+use ty::{self, AdtDef, CanonicalTy, ClosureSubsts, GeneratorSubsts, Region, Ty, TyCtxt};
+use util::ppaux;
 
 pub use mir::interpret::AssertMessage;
 
 mod cache;
-pub mod tcx;
-pub mod visit;
-pub mod traversal;
 pub mod interpret;
 pub mod mono;
+pub mod tcx;
+pub mod traversal;
+pub mod visit;
 
 /// Types for locals
 type LocalDecls<'tcx> = IndexVec<Local, LocalDecl<'tcx>>;
@@ -129,27 +129,31 @@ pub struct Mir<'tcx> {
     pub span: Span,
 
     /// A cache for various calculations
-    cache: cache::Cache
+    cache: cache::Cache,
 }
 
 /// where execution begins
 pub const START_BLOCK: BasicBlock = BasicBlock(0);
 
 impl<'tcx> Mir<'tcx> {
-    pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
-               source_scopes: IndexVec<SourceScope, SourceScopeData>,
-               source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope,
-                                                                 SourceScopeLocalData>>,
-               promoted: IndexVec<Promoted, Mir<'tcx>>,
-               yield_ty: Option<Ty<'tcx>>,
-               local_decls: IndexVec<Local, LocalDecl<'tcx>>,
-               arg_count: usize,
-               upvar_decls: Vec<UpvarDecl>,
-               span: Span) -> Self
-    {
+    pub fn new(
+        basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
+        source_scopes: IndexVec<SourceScope, SourceScopeData>,
+        source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
+        promoted: IndexVec<Promoted, Mir<'tcx>>,
+        yield_ty: Option<Ty<'tcx>>,
+        local_decls: IndexVec<Local, LocalDecl<'tcx>>,
+        arg_count: usize,
+        upvar_decls: Vec<UpvarDecl>,
+        span: Span,
+    ) -> Self {
         // We need `arg_count` locals, and one for the return place
-        assert!(local_decls.len() >= arg_count + 1,
-            "expected at least {} locals, got {}", arg_count + 1, local_decls.len());
+        assert!(
+            local_decls.len() >= arg_count + 1,
+            "expected at least {} locals, got {}",
+            arg_count + 1,
+            local_decls.len()
+        );
 
         Mir {
             basic_blocks,
@@ -164,7 +168,7 @@ pub fn new(basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
             upvar_decls,
             spread_arg: None,
             span,
-            cache: cache::Cache::new()
+            cache: cache::Cache::new(),
         }
     }
 
@@ -180,7 +184,9 @@ pub fn basic_blocks_mut(&mut self) -> &mut IndexVec<BasicBlock, BasicBlockData<'
     }
 
     #[inline]
-    pub fn basic_blocks_and_local_decls_mut(&mut self) -> (
+    pub fn basic_blocks_and_local_decls_mut(
+        &mut self,
+    ) -> (
         &mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
         &mut LocalDecls<'tcx>,
     ) {
@@ -207,8 +213,10 @@ pub fn dominators(&self) -> Dominators<BasicBlock> {
     pub fn local_kind(&self, local: Local) -> LocalKind {
         let index = local.0 as usize;
         if index == 0 {
-            debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
-                          "return place should be mutable");
+            debug_assert!(
+                self.local_decls[local].mutability == Mutability::Mut,
+                "return place should be mutable"
+            );
 
             LocalKind::ReturnPointer
         } else if index < self.arg_count + 1 {
@@ -216,8 +224,10 @@ pub fn local_kind(&self, local: Local) -> LocalKind {
         } else if self.local_decls[local].name.is_some() {
             LocalKind::Var
         } else {
-            debug_assert!(self.local_decls[local].mutability == Mutability::Mut,
-                          "temp should be mutable");
+            debug_assert!(
+                self.local_decls[local].mutability == Mutability::Mut,
+                "temp should be mutable"
+            );
 
             LocalKind::Temp
         }
@@ -225,10 +235,10 @@ pub fn local_kind(&self, local: Local) -> LocalKind {
 
     /// Returns an iterator over all temporaries.
     #[inline]
-    pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
-        (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
+    pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
+        (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
             let local = Local::new(index);
-            if self.local_decls[local].is_user_variable {
+            if self.local_decls[local].is_user_variable.is_some() {
                 None
             } else {
                 Some(local)
@@ -238,10 +248,10 @@ pub fn temps_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
 
     /// Returns an iterator over all user-declared locals.
     #[inline]
-    pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
-        (self.arg_count+1..self.local_decls.len()).filter_map(move |index| {
+    pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
+        (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| {
             let local = Local::new(index);
-            if self.local_decls[local].is_user_variable {
+            if self.local_decls[local].is_user_variable.is_some() {
                 Some(local)
             } else {
                 None
@@ -251,12 +261,12 @@ pub fn vars_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
 
     /// Returns an iterator over all user-declared mutable arguments and locals.
     #[inline]
-    pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
+    pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item = Local> + 'a {
         (1..self.local_decls.len()).filter_map(move |index| {
             let local = Local::new(index);
             let decl = &self.local_decls[local];
-            if (decl.is_user_variable || index < self.arg_count + 1)
-               && decl.mutability == Mutability::Mut
+            if (decl.is_user_variable.is_some() || index < self.arg_count + 1)
+                && decl.mutability == Mutability::Mut
             {
                 Some(local)
             } else {
@@ -267,18 +277,18 @@ pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator<Item=Local> + 'a {
 
     /// Returns an iterator over all function arguments.
     #[inline]
-    pub fn args_iter(&self) -> impl Iterator<Item=Local> {
+    pub fn args_iter(&self) -> impl Iterator<Item = Local> {
         let arg_count = self.arg_count;
-        (1..arg_count+1).map(Local::new)
+        (1..arg_count + 1).map(Local::new)
     }
 
     /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all
     /// locals that are neither arguments nor the return place).
     #[inline]
-    pub fn vars_and_temps_iter(&self) -> impl Iterator<Item=Local> {
+    pub fn vars_and_temps_iter(&self) -> impl Iterator<Item = Local> {
         let arg_count = self.arg_count;
         let local_count = self.local_decls.len();
-        (arg_count+1..local_count).map(Local::new)
+        (arg_count + 1..local_count).map(Local::new)
     }
 
     /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
@@ -302,6 +312,19 @@ pub fn source_info(&self, location: Location) -> &SourceInfo {
         }
     }
 
+    /// Check if `sub` is a sub scope of `sup`
+    pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
+        loop {
+            if sub == sup {
+                return true;
+            }
+            match self.source_scopes[sub].parent_scope {
+                None => return false,
+                Some(p) => sub = p,
+            }
+        }
+    }
+
     /// Return the return type, it always return first element from `local_decls` array
     pub fn return_ty(&self) -> Ty<'tcx> {
         self.local_decls[RETURN_PLACE].ty
@@ -316,7 +339,7 @@ pub enum Safety {
     /// Unsafe because of an unsafe fn
     FnUnsafe,
     /// Unsafe because of an `unsafe` block
-    ExplicitUnsafe(ast::NodeId)
+    ExplicitUnsafe(ast::NodeId),
 }
 
 impl_stable_hash_for!(struct Mir<'tcx> {
@@ -351,10 +374,10 @@ fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> {
     }
 }
 
-#[derive(Clone, Debug)]
+#[derive(Copy, Clone, Debug)]
 pub enum ClearCrossCrate<T> {
     Clear,
-    Set(T)
+    Set(T),
 }
 
 impl<T: serialize::Encodable> serialize::UseSpecializedEncodable for ClearCrossCrate<T> {}
@@ -370,7 +393,7 @@ pub struct SourceInfo {
 
     /// The source scope, keeping track of which bindings can be
     /// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
-    pub scope: SourceScope
+    pub scope: SourceScope,
 }
 
 ///////////////////////////////////////////////////////////////////////////
@@ -382,6 +405,15 @@ pub enum Mutability {
     Not,
 }
 
+impl From<Mutability> for hir::Mutability {
+    fn from(m: Mutability) -> Self {
+        match m {
+            Mutability::Mut => hir::MutMutable,
+            Mutability::Not => hir::MutImmutable,
+        }
+    }
+}
+
 #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
 pub enum BorrowKind {
     /// Data must be immutable and is aliasable.
@@ -428,15 +460,17 @@ pub enum BorrowKind {
     Mut {
         /// True if this borrow arose from method-call auto-ref
         /// (i.e. `adjustment::Adjust::Borrow`)
-        allow_two_phase_borrow: bool
-    }
+        allow_two_phase_borrow: bool,
+    },
 }
 
 impl BorrowKind {
     pub fn allows_two_phase_borrow(&self) -> bool {
         match *self {
             BorrowKind::Shared | BorrowKind::Unique => false,
-            BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
+            BorrowKind::Mut {
+                allow_two_phase_borrow,
+            } => allow_two_phase_borrow,
         }
     }
 }
@@ -463,6 +497,33 @@ pub enum LocalKind {
     ReturnPointer,
 }
 
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
+pub struct VarBindingForm {
+    /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`?
+    pub binding_mode: ty::BindingMode,
+    /// If an explicit type was provided for this variable binding,
+    /// this holds the source Span of that type.
+    ///
+    /// NOTE: If you want to change this to a `HirId`, be wary that
+    /// doing so breaks incremental compilation (as of this writing),
+    /// while a `Span` does not cause our tests to fail.
+    pub opt_ty_info: Option<Span>,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
+pub enum BindingForm {
+    /// This is a binding for a non-`self` binding, or a `self` that has an explicit type.
+    Var(VarBindingForm),
+    /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit.
+    ImplicitSelf,
+}
+
+CloneTypeFoldableAndLiftImpls! { BindingForm, }
+
+impl_stable_hash_for!(struct self::VarBindingForm { binding_mode, opt_ty_info });
+
+impl_stable_hash_for!(enum self::BindingForm { Var(binding), ImplicitSelf, });
+
 /// A MIR local.
 ///
 /// This can be a binding declared by the user, a temporary inserted by the compiler, a function
@@ -474,8 +535,14 @@ pub struct LocalDecl<'tcx> {
     /// Temporaries and the return place are always mutable.
     pub mutability: Mutability,
 
-    /// True if this corresponds to a user-declared local variable.
-    pub is_user_variable: bool,
+    /// Some(binding_mode) if this corresponds to a user-declared local variable.
+    ///
+    /// This is solely used for local diagnostics when generating
+    /// warnings/errors when compiling the current crate, and
+    /// therefore it need not be visible across crates. pnkfelix
+    /// currently hypothesized we *need* to wrap this in a
+    /// `ClearCrossCrate` as long as it carries as `HirId`.
+    pub is_user_variable: Option<ClearCrossCrate<BindingForm>>,
 
     /// True if this is an internal local
     ///
@@ -592,6 +659,43 @@ pub struct LocalDecl<'tcx> {
 }
 
 impl<'tcx> LocalDecl<'tcx> {
+    /// Returns true only if local is a binding that can itself be
+    /// made mutable via the addition of the `mut` keyword, namely
+    /// something like the occurrences of `x` in:
+    /// - `fn foo(x: Type) { ... }`,
+    /// - `let x = ...`,
+    /// - or `match ... { C(x) => ... }`
+    pub fn can_be_made_mutable(&self) -> bool {
+        match self.is_user_variable {
+            Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
+                binding_mode: ty::BindingMode::BindByValue(_),
+                opt_ty_info: _,
+            }))) => true,
+
+            // FIXME: might be able to thread the distinction between
+            // `self`/`mut self`/`&self`/`&mut self` into the
+            // `BindingForm::ImplicitSelf` variant, (and then return
+            // true here for solely the first case).
+            _ => false,
+        }
+    }
+
+    /// Returns true if local is definitely not a `ref ident` or
+    /// `ref mut ident` binding. (Such bindings cannot be made into
+    /// mutable bindings, but the inverse does not necessarily hold).
+    pub fn is_nonref_binding(&self) -> bool {
+        match self.is_user_variable {
+            Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
+                binding_mode: ty::BindingMode::BindByValue(_),
+                opt_ty_info: _,
+            }))) => true,
+
+            Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf)) => true,
+
+            _ => false,
+        }
+    }
+
     /// Create a new `LocalDecl` for a temporary.
     #[inline]
     pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
@@ -601,11 +705,11 @@ pub fn new_temp(ty: Ty<'tcx>, span: Span) -> Self {
             name: None,
             source_info: SourceInfo {
                 span,
-                scope: OUTERMOST_SOURCE_SCOPE
+                scope: OUTERMOST_SOURCE_SCOPE,
             },
             visibility_scope: OUTERMOST_SOURCE_SCOPE,
             internal: false,
-            is_user_variable: false
+            is_user_variable: None,
         }
     }
 
@@ -618,11 +722,11 @@ pub fn new_internal(ty: Ty<'tcx>, span: Span) -> Self {
             name: None,
             source_info: SourceInfo {
                 span,
-                scope: OUTERMOST_SOURCE_SCOPE
+                scope: OUTERMOST_SOURCE_SCOPE,
             },
             visibility_scope: OUTERMOST_SOURCE_SCOPE,
             internal: true,
-            is_user_variable: false
+            is_user_variable: None,
         }
     }
 
@@ -636,12 +740,12 @@ pub fn new_return_place(return_ty: Ty, span: Span) -> LocalDecl {
             ty: return_ty,
             source_info: SourceInfo {
                 span,
-                scope: OUTERMOST_SOURCE_SCOPE
+                scope: OUTERMOST_SOURCE_SCOPE,
             },
             visibility_scope: OUTERMOST_SOURCE_SCOPE,
             internal: false,
-            name: None,     // FIXME maybe we do want some name here?
-            is_user_variable: false
+            name: None, // FIXME maybe we do want some name here?
+            is_user_variable: None,
         }
     }
 }
@@ -699,15 +803,13 @@ pub struct BasicBlockData<'tcx> {
 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
 pub struct Terminator<'tcx> {
     pub source_info: SourceInfo,
-    pub kind: TerminatorKind<'tcx>
+    pub kind: TerminatorKind<'tcx>,
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable)]
 pub enum TerminatorKind<'tcx> {
     /// block should have one successor in the graph; we jump there
-    Goto {
-        target: BasicBlock,
-    },
+    Goto { target: BasicBlock },
 
     /// operand evaluates to an integer; jump depending on its value
     /// to one of the targets, and otherwise fallback to `otherwise`
@@ -755,7 +857,7 @@ pub enum TerminatorKind<'tcx> {
     Drop {
         location: Place<'tcx>,
         target: BasicBlock,
-        unwind: Option<BasicBlock>
+        unwind: Option<BasicBlock>,
     },
 
     /// Drop the Place and assign the new value over it. This ensures
@@ -803,7 +905,7 @@ pub enum TerminatorKind<'tcx> {
         /// Destination for the return value. If some, the call is converging.
         destination: Option<(Place<'tcx>, BasicBlock)>,
         /// Cleanups to be done if the call unwinds.
-        cleanup: Option<BasicBlock>
+        cleanup: Option<BasicBlock>,
     },
 
     /// Jump to the target if the condition has the expected value,
@@ -813,7 +915,7 @@ pub enum TerminatorKind<'tcx> {
         expected: bool,
         msg: AssertMessage<'tcx>,
         target: BasicBlock,
-        cleanup: Option<BasicBlock>
+        cleanup: Option<BasicBlock>,
     },
 
     /// A suspend point
@@ -874,8 +976,12 @@ pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
 }
 
 impl<'tcx> TerminatorKind<'tcx> {
-    pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
-                         t: BasicBlock, f: BasicBlock) -> TerminatorKind<'tcx> {
+    pub fn if_<'a, 'gcx>(
+        tcx: TyCtxt<'a, 'gcx, 'tcx>,
+        cond: Operand<'tcx>,
+        t: BasicBlock,
+        f: BasicBlock,
+    ) -> TerminatorKind<'tcx> {
         static BOOL_SWITCH_FALSE: &'static [u128] = &[0];
         TerminatorKind::SwitchInt {
             discr: cond,
@@ -888,91 +994,199 @@ pub fn if_<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, cond: Operand<'tcx>,
     pub fn successors(&self) -> Successors {
         use self::TerminatorKind::*;
         match *self {
-            Resume | Abort | GeneratorDrop | Return | Unreachable |
-            Call { destination: None, cleanup: None, .. } => {
-                None.into_iter().chain(&[])
+            Resume
+            | Abort
+            | GeneratorDrop
+            | Return
+            | Unreachable
+            | Call {
+                destination: None,
+                cleanup: None,
+                ..
+            } => None.into_iter().chain(&[]),
+            Goto { target: ref t }
+            | Call {
+                destination: None,
+                cleanup: Some(ref t),
+                ..
+            }
+            | Call {
+                destination: Some((_, ref t)),
+                cleanup: None,
+                ..
             }
-            Goto { target: ref t } |
-            Call { destination: None, cleanup: Some(ref t), .. } |
-            Call { destination: Some((_, ref t)), cleanup: None, .. } |
-            Yield { resume: ref t, drop: None, .. } |
-            DropAndReplace { target: ref t, unwind: None, .. } |
-            Drop { target: ref t, unwind: None, .. } |
-            Assert { target: ref t, cleanup: None, .. } |
-            FalseUnwind { real_target: ref t, unwind: None } => {
-                Some(t).into_iter().chain(&[])
+            | Yield {
+                resume: ref t,
+                drop: None,
+                ..
             }
-            Call { destination: Some((_, ref t)), cleanup: Some(ref u), .. } |
-            Yield { resume: ref t, drop: Some(ref u), .. } |
-            DropAndReplace { target: ref t, unwind: Some(ref u), .. } |
-            Drop { target: ref t, unwind: Some(ref u), .. } |
-            Assert { target: ref t, cleanup: Some(ref u), .. } |
-            FalseUnwind { real_target: ref t, unwind: Some(ref u) } => {
-                Some(t).into_iter().chain(slice::from_ref(u))
+            | DropAndReplace {
+                target: ref t,
+                unwind: None,
+                ..
             }
-            SwitchInt { ref targets, .. } => {
-                None.into_iter().chain(&targets[..])
+            | Drop {
+                target: ref t,
+                unwind: None,
+                ..
             }
-            FalseEdges { ref real_target, ref imaginary_targets } => {
-                Some(real_target).into_iter().chain(&imaginary_targets[..])
+            | Assert {
+                target: ref t,
+                cleanup: None,
+                ..
             }
+            | FalseUnwind {
+                real_target: ref t,
+                unwind: None,
+            } => Some(t).into_iter().chain(&[]),
+            Call {
+                destination: Some((_, ref t)),
+                cleanup: Some(ref u),
+                ..
+            }
+            | Yield {
+                resume: ref t,
+                drop: Some(ref u),
+                ..
+            }
+            | DropAndReplace {
+                target: ref t,
+                unwind: Some(ref u),
+                ..
+            }
+            | Drop {
+                target: ref t,
+                unwind: Some(ref u),
+                ..
+            }
+            | Assert {
+                target: ref t,
+                cleanup: Some(ref u),
+                ..
+            }
+            | FalseUnwind {
+                real_target: ref t,
+                unwind: Some(ref u),
+            } => Some(t).into_iter().chain(slice::from_ref(u)),
+            SwitchInt { ref targets, .. } => None.into_iter().chain(&targets[..]),
+            FalseEdges {
+                ref real_target,
+                ref imaginary_targets,
+            } => Some(real_target).into_iter().chain(&imaginary_targets[..]),
         }
     }
 
     pub fn successors_mut(&mut self) -> SuccessorsMut {
         use self::TerminatorKind::*;
         match *self {
-            Resume | Abort | GeneratorDrop | Return | Unreachable |
-            Call { destination: None, cleanup: None, .. } => {
-                None.into_iter().chain(&mut [])
+            Resume
+            | Abort
+            | GeneratorDrop
+            | Return
+            | Unreachable
+            | Call {
+                destination: None,
+                cleanup: None,
+                ..
+            } => None.into_iter().chain(&mut []),
+            Goto { target: ref mut t }
+            | Call {
+                destination: None,
+                cleanup: Some(ref mut t),
+                ..
+            }
+            | Call {
+                destination: Some((_, ref mut t)),
+                cleanup: None,
+                ..
+            }
+            | Yield {
+                resume: ref mut t,
+                drop: None,
+                ..
+            }
+            | DropAndReplace {
+                target: ref mut t,
+                unwind: None,
+                ..
+            }
+            | Drop {
+                target: ref mut t,
+                unwind: None,
+                ..
             }
-            Goto { target: ref mut t } |
-            Call { destination: None, cleanup: Some(ref mut t), .. } |
-            Call { destination: Some((_, ref mut t)), cleanup: None, .. } |
-            Yield { resume: ref mut t, drop: None, .. } |
-            DropAndReplace { target: ref mut t, unwind: None, .. } |
-            Drop { target: ref mut t, unwind: None, .. } |
-            Assert { target: ref mut t, cleanup: None, .. } |
-            FalseUnwind { real_target: ref mut t, unwind: None } => {
-                Some(t).into_iter().chain(&mut [])
+            | Assert {
+                target: ref mut t,
+                cleanup: None,
+                ..
             }
-            Call { destination: Some((_, ref mut t)), cleanup: Some(ref mut u), .. } |
-            Yield { resume: ref mut t, drop: Some(ref mut u), .. } |
-            DropAndReplace { target: ref mut t, unwind: Some(ref mut u), .. } |
-            Drop { target: ref mut t, unwind: Some(ref mut u), .. } |
-            Assert { target: ref mut t, cleanup: Some(ref mut u), .. } |
-            FalseUnwind { real_target: ref mut t, unwind: Some(ref mut u) } => {
-                Some(t).into_iter().chain(slice::from_mut(u))
+            | FalseUnwind {
+                real_target: ref mut t,
+                unwind: None,
+            } => Some(t).into_iter().chain(&mut []),
+            Call {
+                destination: Some((_, ref mut t)),
+                cleanup: Some(ref mut u),
+                ..
             }
-            SwitchInt { ref mut targets, .. } => {
-                None.into_iter().chain(&mut targets[..])
+            | Yield {
+                resume: ref mut t,
+                drop: Some(ref mut u),
+                ..
             }
-            FalseEdges { ref mut real_target, ref mut imaginary_targets } => {
-                Some(real_target).into_iter().chain(&mut imaginary_targets[..])
+            | DropAndReplace {
+                target: ref mut t,
+                unwind: Some(ref mut u),
+                ..
             }
+            | Drop {
+                target: ref mut t,
+                unwind: Some(ref mut u),
+                ..
+            }
+            | Assert {
+                target: ref mut t,
+                cleanup: Some(ref mut u),
+                ..
+            }
+            | FalseUnwind {
+                real_target: ref mut t,
+                unwind: Some(ref mut u),
+            } => Some(t).into_iter().chain(slice::from_mut(u)),
+            SwitchInt {
+                ref mut targets, ..
+            } => None.into_iter().chain(&mut targets[..]),
+            FalseEdges {
+                ref mut real_target,
+                ref mut imaginary_targets,
+            } => Some(real_target)
+                .into_iter()
+                .chain(&mut imaginary_targets[..]),
         }
     }
 
     pub fn unwind_mut(&mut self) -> Option<&mut Option<BasicBlock>> {
         match *self {
-            TerminatorKind::Goto { .. } |
-            TerminatorKind::Resume |
-            TerminatorKind::Abort |
-            TerminatorKind::Return |
-            TerminatorKind::Unreachable |
-            TerminatorKind::GeneratorDrop |
-            TerminatorKind::Yield { .. } |
-            TerminatorKind::SwitchInt { .. } |
-            TerminatorKind::FalseEdges { .. } => {
-                None
-            },
-            TerminatorKind::Call { cleanup: ref mut unwind, .. } |
-            TerminatorKind::Assert { cleanup: ref mut unwind, .. } |
-            TerminatorKind::DropAndReplace { ref mut unwind, .. } |
-            TerminatorKind::Drop { ref mut unwind, .. } |
-            TerminatorKind::FalseUnwind { ref mut unwind, .. } => {
-                Some(unwind)
+            TerminatorKind::Goto { .. }
+            | TerminatorKind::Resume
+            | TerminatorKind::Abort
+            | TerminatorKind::Return
+            | TerminatorKind::Unreachable
+            | TerminatorKind::GeneratorDrop
+            | TerminatorKind::Yield { .. }
+            | TerminatorKind::SwitchInt { .. }
+            | TerminatorKind::FalseEdges { .. } => None,
+            TerminatorKind::Call {
+                cleanup: ref mut unwind,
+                ..
+            }
+            | TerminatorKind::Assert {
+                cleanup: ref mut unwind,
+                ..
             }
+            | TerminatorKind::DropAndReplace { ref mut unwind, .. }
+            | TerminatorKind::Drop { ref mut unwind, .. }
+            | TerminatorKind::FalseUnwind { ref mut unwind, .. } => Some(unwind),
         }
     }
 }
@@ -998,7 +1212,10 @@ pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> {
         self.terminator.as_mut().expect("invalid terminator state")
     }
 
-    pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement) -> bool {
+    pub fn retain_statements<F>(&mut self, mut f: F)
+    where
+        F: FnMut(&mut Statement) -> bool,
+    {
         for s in &mut self.statements {
             if !f(s) {
                 s.make_nop();
@@ -1007,8 +1224,9 @@ pub fn retain_statements<F>(&mut self, mut f: F) where F: FnMut(&mut Statement)
     }
 
     pub fn expand_statements<F, I>(&mut self, mut f: F)
-        where F: FnMut(&mut Statement<'tcx>) -> Option<I>,
-              I: iter::TrustedLen<Item = Statement<'tcx>>
+    where
+        F: FnMut(&mut Statement<'tcx>) -> Option<I>,
+        I: iter::TrustedLen<Item = Statement<'tcx>>,
     {
         // Gather all the iterators we'll need to splice in, and their positions.
         let mut splices: Vec<(usize, I)> = vec![];
@@ -1037,14 +1255,17 @@ pub fn expand_statements<F, I>(&mut self, mut f: F)
         // splicing adding new elements to the end of that gap and moving
         // existing elements from before the gap to the end of the gap.
         // For now, this is safe code, emulating a gap but initializing it.
-        let mut gap = self.statements.len()..self.statements.len()+extra_stmts;
-        self.statements.resize(gap.end, Statement {
-            source_info: SourceInfo {
-                span: DUMMY_SP,
-                scope: OUTERMOST_SOURCE_SCOPE
+        let mut gap = self.statements.len()..self.statements.len() + extra_stmts;
+        self.statements.resize(
+            gap.end,
+            Statement {
+                source_info: SourceInfo {
+                    span: DUMMY_SP,
+                    scope: OUTERMOST_SOURCE_SCOPE,
+                },
+                kind: StatementKind::Nop,
             },
-            kind: StatementKind::Nop
-        });
+        );
         for (splice_start, new_stmts) in splices.into_iter().rev() {
             let splice_end = splice_start + new_stmts.size_hint().0;
             while gap.end > splice_end {
@@ -1088,7 +1309,6 @@ fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
                 }
                 write!(fmt, "]")
             }
-
         }
     }
 }
@@ -1101,7 +1321,9 @@ pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
         use self::TerminatorKind::*;
         match *self {
             Goto { .. } => write!(fmt, "goto"),
-            SwitchInt { discr: ref place, .. } => write!(fmt, "switchInt({:?})", place),
+            SwitchInt {
+                discr: ref place, ..
+            } => write!(fmt, "switchInt({:?})", place),
             Return => write!(fmt, "return"),
             GeneratorDrop => write!(fmt, "generator_drop"),
             Resume => write!(fmt, "resume"),
@@ -1109,9 +1331,17 @@ pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
             Yield { ref value, .. } => write!(fmt, "_1 = suspend({:?})", value),
             Unreachable => write!(fmt, "unreachable"),
             Drop { ref location, .. } => write!(fmt, "drop({:?})", location),
-            DropAndReplace { ref location, ref value, .. } =>
-                write!(fmt, "replace({:?} <- {:?})", location, value),
-            Call { ref func, ref args, ref destination, .. } => {
+            DropAndReplace {
+                ref location,
+                ref value,
+                ..
+            } => write!(fmt, "replace({:?} <- {:?})", location, value),
+            Call {
+                ref func,
+                ref args,
+                ref destination,
+                ..
+            } => {
                 if let Some((ref destination, _)) = *destination {
                     write!(fmt, "{:?} = ", destination)?;
                 }
@@ -1124,13 +1354,18 @@ pub fn fmt_head<W: Write>(&self, fmt: &mut W) -> fmt::Result {
                 }
                 write!(fmt, ")")
             }
-            Assert { ref cond, expected, ref msg, .. } => {
+            Assert {
+                ref cond,
+                expected,
+                ref msg,
+                ..
+            } => {
                 write!(fmt, "assert(")?;
                 if !expected {
                     write!(fmt, "!")?;
                 }
                 write!(fmt, "{:?}, \"{:?}\")", cond, msg)
-            },
+            }
             FalseEdges { .. } => write!(fmt, "falseEdges"),
             FalseUnwind { .. } => write!(fmt, "falseUnwind"),
         }
@@ -1142,48 +1377,77 @@ pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
         match *self {
             Return | Resume | Abort | Unreachable | GeneratorDrop => vec![],
             Goto { .. } => vec!["".into()],
-            SwitchInt { ref values, switch_ty, .. } => {
+            SwitchInt {
+                ref values,
+                switch_ty,
+                ..
+            } => {
                 let size = ty::tls::with(|tcx| {
                     let param_env = ty::ParamEnv::empty();
                     let switch_ty = tcx.lift_to_global(&switch_ty).unwrap();
                     tcx.layout_of(param_env.and(switch_ty)).unwrap().size
                 });
-                values.iter()
-                      .map(|&u| {
-                          let mut s = String::new();
-                          print_miri_value(
-                              Value::Scalar(Scalar::Bits { bits: u, defined: size.bits() as u8 }),
-                              switch_ty,
-                              &mut s,
-                          ).unwrap();
-                          s.into()
-                      })
-                      .chain(iter::once(String::from("otherwise").into()))
-                      .collect()
+                values
+                    .iter()
+                    .map(|&u| {
+                        let mut s = String::new();
+                        print_miri_value(
+                            Value::Scalar(Scalar::Bits {
+                                bits: u,
+                                defined: size.bits() as u8,
+                            }),
+                            switch_ty,
+                            &mut s,
+                        ).unwrap();
+                        s.into()
+                    })
+                    .chain(iter::once(String::from("otherwise").into()))
+                    .collect()
             }
-            Call { destination: Some(_), cleanup: Some(_), .. } =>
-                vec!["return".into_cow(), "unwind".into_cow()],
-            Call { destination: Some(_), cleanup: None, .. } => vec!["return".into_cow()],
-            Call { destination: None, cleanup: Some(_), .. } => vec!["unwind".into_cow()],
-            Call { destination: None, cleanup: None, .. } => vec![],
-            Yield { drop: Some(_), .. } =>
-                vec!["resume".into_cow(), "drop".into_cow()],
+            Call {
+                destination: Some(_),
+                cleanup: Some(_),
+                ..
+            } => vec!["return".into_cow(), "unwind".into_cow()],
+            Call {
+                destination: Some(_),
+                cleanup: None,
+                ..
+            } => vec!["return".into_cow()],
+            Call {
+                destination: None,
+                cleanup: Some(_),
+                ..
+            } => vec!["unwind".into_cow()],
+            Call {
+                destination: None,
+                cleanup: None,
+                ..
+            } => vec![],
+            Yield { drop: Some(_), .. } => vec!["resume".into_cow(), "drop".into_cow()],
             Yield { drop: None, .. } => vec!["resume".into_cow()],
-            DropAndReplace { unwind: None, .. } |
-            Drop { unwind: None, .. } => vec!["return".into_cow()],
-            DropAndReplace { unwind: Some(_), .. } |
-            Drop { unwind: Some(_), .. } => {
-                vec!["return".into_cow(), "unwind".into_cow()]
+            DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
+                vec!["return".into_cow()]
+            }
+            DropAndReplace {
+                unwind: Some(_), ..
             }
+            | Drop {
+                unwind: Some(_), ..
+            } => vec!["return".into_cow(), "unwind".into_cow()],
             Assert { cleanup: None, .. } => vec!["".into()],
-            Assert { .. } =>
-                vec!["success".into_cow(), "unwind".into_cow()],
-            FalseEdges { ref imaginary_targets, .. } => {
+            Assert { .. } => vec!["success".into_cow(), "unwind".into_cow()],
+            FalseEdges {
+                ref imaginary_targets,
+                ..
+            } => {
                 let mut l = vec!["real".into()];
                 l.resize(imaginary_targets.len() + 1, "imaginary".into());
                 l
             }
-            FalseUnwind { unwind: Some(_), .. } => vec!["real".into(), "cleanup".into()],
+            FalseUnwind {
+                unwind: Some(_), ..
+            } => vec!["real".into(), "cleanup".into()],
             FalseUnwind { unwind: None, .. } => vec!["real".into()],
         }
     }
@@ -1209,7 +1473,7 @@ pub fn make_nop(&mut self) {
     pub fn replace_nop(&mut self) -> Self {
         Statement {
             source_info: self.source_info,
-            kind: mem::replace(&mut self.kind, StatementKind::Nop)
+            kind: mem::replace(&mut self.kind, StatementKind::Nop),
         }
     }
 }
@@ -1224,7 +1488,10 @@ pub enum StatementKind<'tcx> {
     ReadForMatch(Place<'tcx>),
 
     /// Write the discriminant for a variant to the enum Place.
-    SetDiscriminant { place: Place<'tcx>, variant_index: usize },
+    SetDiscriminant {
+        place: Place<'tcx>,
+        variant_index: usize,
+    },
 
     /// Start a live range for the storage of the local.
     StorageLive(Local),
@@ -1236,7 +1503,7 @@ pub enum StatementKind<'tcx> {
     InlineAsm {
         asm: Box<InlineAsm>,
         outputs: Vec<Place<'tcx>>,
-        inputs: Vec<Operand<'tcx>>
+        inputs: Vec<Operand<'tcx>>,
     },
 
     /// Assert the given places to be valid inhabitants of their type.  These statements are
@@ -1331,14 +1598,18 @@ fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
             Validate(ref op, ref places) => write!(fmt, "Validate({:?}, {:?})", op, places),
             StorageLive(ref place) => write!(fmt, "StorageLive({:?})", place),
             StorageDead(ref place) => write!(fmt, "StorageDead({:?})", place),
-            SetDiscriminant { ref place, variant_index } => {
-                write!(fmt, "discriminant({:?}) = {:?}", place, variant_index)
-            },
-            InlineAsm { ref asm, ref outputs, ref inputs } => {
-                write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs)
-            },
-            UserAssertTy(ref c_ty, ref local) => write!(fmt, "UserAssertTy({:?}, {:?})",
-                                                        c_ty, local),
+            SetDiscriminant {
+                ref place,
+                variant_index,
+            } => write!(fmt, "discriminant({:?}) = {:?}", place, variant_index),
+            InlineAsm {
+                ref asm,
+                ref outputs,
+                ref inputs,
+            } => write!(fmt, "asm!({:?} : {:?} : {:?})", asm, outputs, inputs),
+            UserAssertTy(ref c_ty, ref local) => {
+                write!(fmt, "UserAssertTy({:?}, {:?})", c_ty, local)
+            }
             Nop => write!(fmt, "nop"),
         }
     }
@@ -1450,10 +1721,7 @@ pub fn index(self, index: Local) -> Place<'tcx> {
     }
 
     pub fn elem(self, elem: PlaceElem<'tcx>) -> Place<'tcx> {
-        Place::Projection(Box::new(PlaceProjection {
-            base: self,
-            elem,
-        }))
+        Place::Projection(Box::new(PlaceProjection { base: self, elem }))
     }
 }
 
@@ -1463,31 +1731,41 @@ fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
 
         match *self {
             Local(id) => write!(fmt, "{:?}", id),
-            Static(box self::Static { def_id, ty }) =>
-                write!(fmt, "({}: {:?})", ty::tls::with(|tcx| tcx.item_path_str(def_id)), ty),
-            Projection(ref data) =>
-                match data.elem {
-                    ProjectionElem::Downcast(ref adt_def, index) =>
-                        write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name),
-                    ProjectionElem::Deref =>
-                        write!(fmt, "(*{:?})", data.base),
-                    ProjectionElem::Field(field, ty) =>
-                        write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty),
-                    ProjectionElem::Index(ref index) =>
-                        write!(fmt, "{:?}[{:?}]", data.base, index),
-                    ProjectionElem::ConstantIndex { offset, min_length, from_end: false } =>
-                        write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
-                    ProjectionElem::ConstantIndex { offset, min_length, from_end: true } =>
-                        write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
-                    ProjectionElem::Subslice { from, to } if to == 0 =>
-                        write!(fmt, "{:?}[{:?}:]", data.base, from),
-                    ProjectionElem::Subslice { from, to } if from == 0 =>
-                        write!(fmt, "{:?}[:-{:?}]", data.base, to),
-                    ProjectionElem::Subslice { from, to } =>
-                        write!(fmt, "{:?}[{:?}:-{:?}]", data.base,
-                               from, to),
-
-                },
+            Static(box self::Static { def_id, ty }) => write!(
+                fmt,
+                "({}: {:?})",
+                ty::tls::with(|tcx| tcx.item_path_str(def_id)),
+                ty
+            ),
+            Projection(ref data) => match data.elem {
+                ProjectionElem::Downcast(ref adt_def, index) => {
+                    write!(fmt, "({:?} as {})", data.base, adt_def.variants[index].name)
+                }
+                ProjectionElem::Deref => write!(fmt, "(*{:?})", data.base),
+                ProjectionElem::Field(field, ty) => {
+                    write!(fmt, "({:?}.{:?}: {:?})", data.base, field.index(), ty)
+                }
+                ProjectionElem::Index(ref index) => write!(fmt, "{:?}[{:?}]", data.base, index),
+                ProjectionElem::ConstantIndex {
+                    offset,
+                    min_length,
+                    from_end: false,
+                } => write!(fmt, "{:?}[{:?} of {:?}]", data.base, offset, min_length),
+                ProjectionElem::ConstantIndex {
+                    offset,
+                    min_length,
+                    from_end: true,
+                } => write!(fmt, "{:?}[-{:?} of {:?}]", data.base, offset, min_length),
+                ProjectionElem::Subslice { from, to } if to == 0 => {
+                    write!(fmt, "{:?}[{:?}:]", data.base, from)
+                }
+                ProjectionElem::Subslice { from, to } if from == 0 => {
+                    write!(fmt, "{:?}[:-{:?}]", data.base, to)
+                }
+                ProjectionElem::Subslice { from, to } => {
+                    write!(fmt, "{:?}[{:?}:-{:?}]", data.base, from, to)
+                }
+            },
         }
     }
 }
@@ -1568,7 +1846,7 @@ pub fn function_handle<'a>(
     pub fn to_copy(&self) -> Self {
         match *self {
             Operand::Copy(_) | Operand::Constant(_) => self.clone(),
-            Operand::Move(ref place) => Operand::Copy(place.clone())
+            Operand::Move(ref place) => Operand::Copy(place.clone()),
         }
     }
 }
@@ -1693,7 +1971,7 @@ pub fn is_checkable(self) -> bool {
         use self::BinOp::*;
         match self {
             Add | Sub | Mul | Shl | Shr => true,
-            _ => false
+            _ => false,
         }
     }
 }
@@ -1741,7 +2019,9 @@ fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
                 // When printing regions, add trailing space if necessary.
                 let region = if ppaux::verbose() || ppaux::identify_regions() {
                     let mut region = format!("{}", region);
-                    if region.len() > 0 { region.push(' '); }
+                    if region.len() > 0 {
+                        region.push(' ');
+                    }
                     region
                 } else {
                     // Do not even print 'static
@@ -1762,13 +2042,11 @@ fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
                 match **kind {
                     AggregateKind::Array(_) => write!(fmt, "{:?}", places),
 
-                    AggregateKind::Tuple => {
-                        match places.len() {
-                            0 => write!(fmt, "()"),
-                            1 => write!(fmt, "({:?},)", places[0]),
-                            _ => fmt_tuple(fmt, places),
-                        }
-                    }
+                    AggregateKind::Tuple => match places.len() {
+                        0 => write!(fmt, "()"),
+                        1 => write!(fmt, "({:?},)", places[0]),
+                        _ => fmt_tuple(fmt, places),
+                    },
 
                     AggregateKind::Adt(adt_def, variant, substs, _) => {
                         let variant_def = &adt_def.variants[variant];
@@ -1822,8 +2100,8 @@ fn fmt_tuple(fmt: &mut Formatter, places: &[Operand]) -> fmt::Result {
                                 }
                                 struct_fmt.field("$state", &places[freevars.len()]);
                                 for i in (freevars.len() + 1)..places.len() {
-                                    struct_fmt.field(&format!("${}", i - freevars.len() - 1),
-                                                     &places[i]);
+                                    struct_fmt
+                                        .field(&format!("${}", i - freevars.len() - 1), &places[i]);
                                 }
                             });
 
@@ -1854,7 +2132,6 @@ pub struct Constant<'tcx> {
 
 newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
 
-
 #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
 pub enum Literal<'tcx> {
     Value {
@@ -1862,7 +2139,7 @@ pub enum Literal<'tcx> {
     },
     Promoted {
         // Index into the `promoted` vector of `Mir`.
-        index: Promoted
+        index: Promoted,
     },
 }
 
@@ -1880,9 +2157,7 @@ fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
                 write!(fmt, "const ")?;
                 fmt_const_val(fmt, value)
             }
-            Promoted { index } => {
-                write!(fmt, "{:?}", index)
-            }
+            Promoted { index } => write!(fmt, "{:?}", index),
         }
     }
 }
@@ -1898,7 +2173,7 @@ pub fn fmt_const_val<W: Write>(fmt: &mut W, const_val: &ty::Const) -> fmt::Resul
             } else {
                 write!(fmt, "{:?}:{}", val, const_val.ty)
             }
-        },
+        }
     }
 }
 
@@ -1907,38 +2182,40 @@ pub fn print_miri_value<W: Write>(value: Value, ty: Ty, f: &mut W) -> fmt::Resul
     match (value, &ty.sty) {
         (Value::Scalar(Scalar::Bits { bits: 0, .. }), &TyBool) => write!(f, "false"),
         (Value::Scalar(Scalar::Bits { bits: 1, .. }), &TyBool) => write!(f, "true"),
-        (Value::Scalar(Scalar::Bits { bits, .. }), &TyFloat(ast::FloatTy::F32)) =>
-            write!(f, "{}f32", Single::from_bits(bits)),
-        (Value::Scalar(Scalar::Bits { bits, .. }), &TyFloat(ast::FloatTy::F64)) =>
-            write!(f, "{}f64", Double::from_bits(bits)),
+        (Value::Scalar(Scalar::Bits { bits, .. }), &TyFloat(ast::FloatTy::F32)) => {
+            write!(f, "{}f32", Single::from_bits(bits))
+        }
+        (Value::Scalar(Scalar::Bits { bits, .. }), &TyFloat(ast::FloatTy::F64)) => {
+            write!(f, "{}f64", Double::from_bits(bits))
+        }
         (Value::Scalar(Scalar::Bits { bits, .. }), &TyUint(ui)) => write!(f, "{:?}{}", bits, ui),
         (Value::Scalar(Scalar::Bits { bits, .. }), &TyInt(i)) => {
             let bit_width = ty::tls::with(|tcx| {
-                 let ty = tcx.lift_to_global(&ty).unwrap();
-                 tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bits()
+                let ty = tcx.lift_to_global(&ty).unwrap();
+                tcx.layout_of(ty::ParamEnv::empty().and(ty))
+                    .unwrap()
+                    .size
+                    .bits()
             });
             let shift = 128 - bit_width;
             write!(f, "{:?}{}", ((bits as i128) << shift) >> shift, i)
-        },
-        (Value::Scalar(Scalar::Bits { bits, .. }), &TyChar) =>
-            write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap()),
-        (_, &TyFnDef(did, _)) =>
-            write!(f, "{}", item_path_str(did)),
-        (Value::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: len, .. }),
-         &TyRef(_, &ty::TyS { sty: TyStr, .. }, _)) => {
-            ty::tls::with(|tcx| {
-                match tcx.alloc_map.lock().get(ptr.alloc_id) {
-                    Some(interpret::AllocType::Memory(alloc)) => {
-                        assert_eq!(len as usize as u128, len);
-                        let slice = &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
-                        let s = ::std::str::from_utf8(slice)
-                            .expect("non utf8 str from miri");
-                        write!(f, "{:?}", s)
-                    }
-                    _ => write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len),
-                }
-            })
-        },
+        }
+        (Value::Scalar(Scalar::Bits { bits, .. }), &TyChar) => {
+            write!(f, "{:?}", ::std::char::from_u32(bits as u32).unwrap())
+        }
+        (_, &TyFnDef(did, _)) => write!(f, "{}", item_path_str(did)),
+        (
+            Value::ScalarPair(Scalar::Ptr(ptr), Scalar::Bits { bits: len, .. }),
+            &TyRef(_, &ty::TyS { sty: TyStr, .. }, _),
+        ) => ty::tls::with(|tcx| match tcx.alloc_map.lock().get(ptr.alloc_id) {
+            Some(interpret::AllocType::Memory(alloc)) => {
+                assert_eq!(len as usize as u128, len);
+                let slice = &alloc.bytes[(ptr.offset.bytes() as usize)..][..(len as usize)];
+                let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
+                write!(f, "{:?}", s)
+            }
+            _ => write!(f, "pointer to erroneous constant {:?}, {:?}", ptr, len),
+        }),
         _ => write!(f, "{:?}:{}", value, ty),
     }
 }
@@ -1948,21 +2225,26 @@ fn item_path_str(def_id: DefId) -> String {
 }
 
 impl<'tcx> ControlFlowGraph for Mir<'tcx> {
-
     type Node = BasicBlock;
 
-    fn num_nodes(&self) -> usize { self.basic_blocks.len() }
+    fn num_nodes(&self) -> usize {
+        self.basic_blocks.len()
+    }
 
-    fn start_node(&self) -> Self::Node { START_BLOCK }
+    fn start_node(&self) -> Self::Node {
+        START_BLOCK
+    }
 
-    fn predecessors<'graph>(&'graph self, node: Self::Node)
-                            -> <Self as GraphPredecessors<'graph>>::Iter
-    {
+    fn predecessors<'graph>(
+        &'graph self,
+        node: Self::Node,
+    ) -> <Self as GraphPredecessors<'graph>>::Iter {
         self.predecessors_for(node).clone().into_iter()
     }
-    fn successors<'graph>(&'graph self, node: Self::Node)
-                          -> <Self as GraphSuccessors<'graph>>::Iter
-    {
+    fn successors<'graph>(
+        &'graph self,
+        node: Self::Node,
+    ) -> <Self as GraphSuccessors<'graph>>::Iter {
         self.basic_blocks[node].terminator().successors().cloned()
     }
 }
@@ -1972,7 +2254,7 @@ impl<'a, 'b> GraphPredecessors<'b> for Mir<'a> {
     type Iter = IntoIter<BasicBlock>;
 }
 
-impl<'a, 'b>  GraphSuccessors<'b> for Mir<'a> {
+impl<'a, 'b> GraphSuccessors<'b> for Mir<'a> {
     type Item = BasicBlock;
     type Iter = iter::Cloned<Successors<'b>>;
 }
@@ -2004,7 +2286,10 @@ impl Location {
     /// Note that if this location represents a terminator, then the
     /// resulting location would be out of bounds and invalid.
     pub fn successor_within_block(&self) -> Location {
-        Location { block: self.block, statement_index: self.statement_index + 1 }
+        Location {
+            block: self.block,
+            statement_index: self.statement_index + 1,
+        }
     }
 
     pub fn dominates(&self, other: Location, dominators: &Dominators<BasicBlock>) -> bool {
@@ -2244,32 +2529,55 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
 
         let kind = match self.kind {
             Goto { target } => Goto { target: target },
-            SwitchInt { ref discr, switch_ty, ref values, ref targets } => SwitchInt {
+            SwitchInt {
+                ref discr,
+                switch_ty,
+                ref values,
+                ref targets,
+            } => SwitchInt {
                 discr: discr.fold_with(folder),
                 switch_ty: switch_ty.fold_with(folder),
                 values: values.clone(),
-                targets: targets.clone()
+                targets: targets.clone(),
             },
-            Drop { ref location, target, unwind } => Drop {
+            Drop {
+                ref location,
+                target,
+                unwind,
+            } => Drop {
                 location: location.fold_with(folder),
                 target,
                 unwind,
             },
-            DropAndReplace { ref location, ref value, target, unwind } => DropAndReplace {
+            DropAndReplace {
+                ref location,
+                ref value,
+                target,
+                unwind,
+            } => DropAndReplace {
                 location: location.fold_with(folder),
                 value: value.fold_with(folder),
                 target,
                 unwind,
             },
-            Yield { ref value, resume, drop } => Yield {
+            Yield {
+                ref value,
+                resume,
+                drop,
+            } => Yield {
                 value: value.fold_with(folder),
                 resume: resume,
                 drop: drop,
             },
-            Call { ref func, ref args, ref destination, cleanup } => {
-                let dest = destination.as_ref().map(|&(ref loc, dest)| {
-                    (loc.fold_with(folder), dest)
-                });
+            Call {
+                ref func,
+                ref args,
+                ref destination,
+                cleanup,
+            } => {
+                let dest = destination
+                    .as_ref()
+                    .map(|&(ref loc, dest)| (loc.fold_with(folder), dest));
 
                 Call {
                     func: func.fold_with(folder),
@@ -2277,8 +2585,14 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
                     destination: dest,
                     cleanup,
                 }
-            },
-            Assert { ref cond, expected, ref msg, target, cleanup } => {
+            }
+            Assert {
+                ref cond,
+                expected,
+                ref msg,
+                target,
+                cleanup,
+            } => {
                 let msg = if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
                     EvalErrorKind::BoundsCheck {
                         len: len.fold_with(folder),
@@ -2294,15 +2608,26 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
                     target,
                     cleanup,
                 }
-            },
+            }
             GeneratorDrop => GeneratorDrop,
             Resume => Resume,
             Abort => Abort,
             Return => Return,
             Unreachable => Unreachable,
-            FalseEdges { real_target, ref imaginary_targets } =>
-                FalseEdges { real_target, imaginary_targets: imaginary_targets.clone() },
-            FalseUnwind { real_target, unwind } => FalseUnwind { real_target, unwind },
+            FalseEdges {
+                real_target,
+                ref imaginary_targets,
+            } => FalseEdges {
+                real_target,
+                imaginary_targets: imaginary_targets.clone(),
+            },
+            FalseUnwind {
+                real_target,
+                unwind,
+            } => FalseUnwind {
+                real_target,
+                unwind,
+            },
         };
         Terminator {
             source_info: self.source_info,
@@ -2314,20 +2639,34 @@ fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
         use mir::TerminatorKind::*;
 
         match self.kind {
-            SwitchInt { ref discr, switch_ty, .. } =>
-                discr.visit_with(visitor) || switch_ty.visit_with(visitor),
-            Drop { ref location, ..} => location.visit_with(visitor),
-            DropAndReplace { ref location, ref value, ..} =>
-                location.visit_with(visitor) || value.visit_with(visitor),
-            Yield { ref value, ..} =>
-                value.visit_with(visitor),
-            Call { ref func, ref args, ref destination, .. } => {
+            SwitchInt {
+                ref discr,
+                switch_ty,
+                ..
+            } => discr.visit_with(visitor) || switch_ty.visit_with(visitor),
+            Drop { ref location, .. } => location.visit_with(visitor),
+            DropAndReplace {
+                ref location,
+                ref value,
+                ..
+            } => location.visit_with(visitor) || value.visit_with(visitor),
+            Yield { ref value, .. } => value.visit_with(visitor),
+            Call {
+                ref func,
+                ref args,
+                ref destination,
+                ..
+            } => {
                 let dest = if let Some((ref loc, _)) = *destination {
                     loc.visit_with(visitor)
-                } else { false };
+                } else {
+                    false
+                };
                 dest || func.visit_with(visitor) || args.visit_with(visitor)
-            },
-            Assert { ref cond, ref msg, .. } => {
+            }
+            Assert {
+                ref cond, ref msg, ..
+            } => {
                 if cond.visit_with(visitor) {
                     if let EvalErrorKind::BoundsCheck { ref len, ref index } = *msg {
                         len.visit_with(visitor) || index.visit_with(visitor)
@@ -2337,15 +2676,15 @@ fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
                 } else {
                     false
                 }
-            },
-            Goto { .. } |
-            Resume |
-            Abort |
-            Return |
-            GeneratorDrop |
-            Unreachable |
-            FalseEdges { .. } |
-            FalseUnwind { .. } => false
+            }
+            Goto { .. }
+            | Resume
+            | Abort
+            | Return
+            | GeneratorDrop
+            | Unreachable
+            | FalseEdges { .. }
+            | FalseUnwind { .. } => false,
         }
     }
 }
@@ -2354,7 +2693,7 @@ impl<'tcx> TypeFoldable<'tcx> for Place<'tcx> {
     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
         match self {
             &Place::Projection(ref p) => Place::Projection(p.fold_with(folder)),
-            _ => self.clone()
+            _ => self.clone(),
         }
     }
 
@@ -2373,14 +2712,17 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
         match *self {
             Use(ref op) => Use(op.fold_with(folder)),
             Repeat(ref op, len) => Repeat(op.fold_with(folder), len),
-            Ref(region, bk, ref place) =>
-                Ref(region.fold_with(folder), bk, place.fold_with(folder)),
+            Ref(region, bk, ref place) => {
+                Ref(region.fold_with(folder), bk, place.fold_with(folder))
+            }
             Len(ref place) => Len(place.fold_with(folder)),
             Cast(kind, ref op, ty) => Cast(kind, op.fold_with(folder), ty.fold_with(folder)),
-            BinaryOp(op, ref rhs, ref lhs) =>
-                BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
-            CheckedBinaryOp(op, ref rhs, ref lhs) =>
-                CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder)),
+            BinaryOp(op, ref rhs, ref lhs) => {
+                BinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
+            }
+            CheckedBinaryOp(op, ref rhs, ref lhs) => {
+                CheckedBinaryOp(op, rhs.fold_with(folder), lhs.fold_with(folder))
+            }
             UnaryOp(op, ref val) => UnaryOp(op, val.fold_with(folder)),
             Discriminant(ref place) => Discriminant(place.fold_with(folder)),
             NullaryOp(op, ty) => NullaryOp(op, ty.fold_with(folder)),
@@ -2388,12 +2730,15 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
                 let kind = box match **kind {
                     AggregateKind::Array(ty) => AggregateKind::Array(ty.fold_with(folder)),
                     AggregateKind::Tuple => AggregateKind::Tuple,
-                    AggregateKind::Adt(def, v, substs, n) =>
-                        AggregateKind::Adt(def, v, substs.fold_with(folder), n),
-                    AggregateKind::Closure(id, substs) =>
-                        AggregateKind::Closure(id, substs.fold_with(folder)),
-                    AggregateKind::Generator(id, substs, movablity) =>
-                        AggregateKind::Generator(id, substs.fold_with(folder), movablity),
+                    AggregateKind::Adt(def, v, substs, n) => {
+                        AggregateKind::Adt(def, v, substs.fold_with(folder), n)
+                    }
+                    AggregateKind::Closure(id, substs) => {
+                        AggregateKind::Closure(id, substs.fold_with(folder))
+                    }
+                    AggregateKind::Generator(id, substs, movablity) => {
+                        AggregateKind::Generator(id, substs.fold_with(folder), movablity)
+                    }
                 };
                 Aggregate(kind, fields.fold_with(folder))
             }
@@ -2408,9 +2753,9 @@ fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
             Ref(region, _, ref place) => region.visit_with(visitor) || place.visit_with(visitor),
             Len(ref place) => place.visit_with(visitor),
             Cast(_, ref op, ty) => op.visit_with(visitor) || ty.visit_with(visitor),
-            BinaryOp(_, ref rhs, ref lhs) |
-            CheckedBinaryOp(_, ref rhs, ref lhs) =>
-                rhs.visit_with(visitor) || lhs.visit_with(visitor),
+            BinaryOp(_, ref rhs, ref lhs) | CheckedBinaryOp(_, ref rhs, ref lhs) => {
+                rhs.visit_with(visitor) || lhs.visit_with(visitor)
+            }
             UnaryOp(_, ref val) => val.visit_with(visitor),
             Discriminant(ref place) => place.visit_with(visitor),
             NullaryOp(_, ty) => ty.visit_with(visitor),
@@ -2438,15 +2783,17 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
 
     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
         match *self {
-            Operand::Copy(ref place) |
-            Operand::Move(ref place) => place.visit_with(visitor),
-            Operand::Constant(ref c) => c.visit_with(visitor)
+            Operand::Copy(ref place) | Operand::Move(ref place) => place.visit_with(visitor),
+            Operand::Constant(ref c) => c.visit_with(visitor),
         }
     }
 }
 
 impl<'tcx, B, V, T> TypeFoldable<'tcx> for Projection<'tcx, B, V, T>
-    where B: TypeFoldable<'tcx>, V: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>
+where
+    B: TypeFoldable<'tcx>,
+    V: TypeFoldable<'tcx>,
+    T: TypeFoldable<'tcx>,
 {
     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
         use mir::ProjectionElem::*;
@@ -2456,24 +2803,20 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
             Deref => Deref,
             Field(f, ref ty) => Field(f, ty.fold_with(folder)),
             Index(ref v) => Index(v.fold_with(folder)),
-            ref elem => elem.clone()
+            ref elem => elem.clone(),
         };
 
-        Projection {
-            base,
-            elem,
-        }
+        Projection { base, elem }
     }
 
     fn super_visit_with<Vs: TypeVisitor<'tcx>>(&self, visitor: &mut Vs) -> bool {
         use mir::ProjectionElem::*;
 
-        self.base.visit_with(visitor) ||
-            match self.elem {
-                Field(_, ref ty) => ty.visit_with(visitor),
-                Index(ref v) => v.visit_with(visitor),
-                _ => false
-            }
+        self.base.visit_with(visitor) || match self.elem {
+            Field(_, ref ty) => ty.visit_with(visitor),
+            Index(ref v) => v.visit_with(visitor),
+            _ => false,
+        }
     }
 }
 
@@ -2491,7 +2834,7 @@ fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F)
         Constant {
             span: self.span.clone(),
             ty: self.ty.fold_with(folder),
-            literal: self.literal.fold_with(folder)
+            literal: self.literal.fold_with(folder),
         }
     }
     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
@@ -2503,15 +2846,15 @@ impl<'tcx> TypeFoldable<'tcx> for Literal<'tcx> {
     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
         match *self {
             Literal::Value { value } => Literal::Value {
-                value: value.fold_with(folder)
+                value: value.fold_with(folder),
             },
-            Literal::Promoted { index } => Literal::Promoted { index }
+            Literal::Promoted { index } => Literal::Promoted { index },
         }
     }
     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
         match *self {
             Literal::Value { value } => value.visit_with(visitor),
-            Literal::Promoted { .. } => false
+            Literal::Promoted { .. } => false,
         }
     }
 }
index 227cba40d146388a016431509201bd3a522f3c94..f48739799203fb9c41453c7a2f7592f42daf72a6 100644 (file)
@@ -224,11 +224,9 @@ pub fn find_auto_trait_generics<A>(
             let names_map: FxHashSet<String> = generics
                 .params
                 .iter()
-                .filter_map(|param| {
-                    match param.kind {
-                        ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
-                        _ => None
-                    }
+                .filter_map(|param| match param.kind {
+                    ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
+                    _ => None
                 })
                 .collect();
 
index 761de0014384265933c40d77a94430659c83d95b..354debf87dc0783bc85aae9830f93c7ec7c580af 100644 (file)
@@ -269,7 +269,9 @@ pub struct DerivedObligationCause<'tcx> {
 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
 
 /// The following types:
-/// * `WhereClauseAtom`
+/// * `WhereClause`
+/// * `WellFormed`
+/// * `FromEnv`
 /// * `DomainGoal`
 /// * `Goal`
 /// * `Clause`
@@ -277,21 +279,31 @@ pub struct DerivedObligationCause<'tcx> {
 /// logic programming clauses. They are part of the interface
 /// for the chalk SLG solver.
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
-pub enum WhereClauseAtom<'tcx> {
+pub enum WhereClause<'tcx> {
     Implemented(ty::TraitPredicate<'tcx>),
     ProjectionEq(ty::ProjectionPredicate<'tcx>),
+    RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
+    TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub enum WellFormed<'tcx> {
+    Trait(ty::TraitPredicate<'tcx>),
+    Ty(Ty<'tcx>),
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub enum FromEnv<'tcx> {
+    Trait(ty::TraitPredicate<'tcx>),
+    Ty(Ty<'tcx>),
 }
 
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
 pub enum DomainGoal<'tcx> {
-    Holds(WhereClauseAtom<'tcx>),
-    WellFormed(WhereClauseAtom<'tcx>),
-    FromEnv(WhereClauseAtom<'tcx>),
-    WellFormedTy(Ty<'tcx>),
+    Holds(WhereClause<'tcx>),
+    WellFormed(WellFormed<'tcx>),
+    FromEnv(FromEnv<'tcx>),
     Normalize(ty::ProjectionPredicate<'tcx>),
-    FromEnvTy(Ty<'tcx>),
-    RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
-    TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
 }
 
 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
@@ -314,27 +326,27 @@ pub enum Goal<'tcx> {
 
 pub type Goals<'tcx> = &'tcx Slice<Goal<'tcx>>;
 
+impl<'tcx> DomainGoal<'tcx> {
+    pub fn into_goal(self) -> Goal<'tcx> {
+        Goal::DomainGoal(self)
+    }
+}
+
 impl<'tcx> Goal<'tcx> {
     pub fn from_poly_domain_goal<'a>(
         domain_goal: PolyDomainGoal<'tcx>,
         tcx: TyCtxt<'a, 'tcx, 'tcx>,
     ) -> Goal<'tcx> {
         match domain_goal.no_late_bound_regions() {
-            Some(p) => p.into(),
+            Some(p) => p.into_goal(),
             None => Goal::Quantified(
                 QuantifierKind::Universal,
-                domain_goal.map_bound(|p| tcx.mk_goal(Goal::from(p)))
+                domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
             ),
         }
     }
 }
 
-impl<'tcx> From<DomainGoal<'tcx>> for Goal<'tcx> {
-    fn from(domain_goal: DomainGoal<'tcx>) -> Self {
-        Goal::DomainGoal(domain_goal)
-    }
-}
-
 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
 /// Harrop Formulas".
 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
index d1304a0a3f8871483a6f6c1546a9acd945010a5e..d24c84b2556f860653902fb8aace1aa896b6940c 100644 (file)
@@ -405,13 +405,37 @@ impl<'tcx, T> TypeFoldable<'tcx> for Normalized<'tcx, T> {
     } where T: TypeFoldable<'tcx>
 }
 
-impl<'tcx> fmt::Display for traits::WhereClauseAtom<'tcx> {
+impl<'tcx> fmt::Display for traits::WhereClause<'tcx> {
     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
-        use traits::WhereClauseAtom::*;
+        use traits::WhereClause::*;
 
         match self {
             Implemented(trait_ref) => write!(fmt, "Implemented({})", trait_ref),
             ProjectionEq(projection) => write!(fmt, "ProjectionEq({})", projection),
+            RegionOutlives(predicate) => write!(fmt, "RegionOutlives({})", predicate),
+            TypeOutlives(predicate) => write!(fmt, "TypeOutlives({})", predicate),
+        }
+    }
+}
+
+impl<'tcx> fmt::Display for traits::WellFormed<'tcx> {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        use traits::WellFormed::*;
+
+        match self {
+            Trait(trait_ref) => write!(fmt, "WellFormed({})", trait_ref),
+            Ty(ty) => write!(fmt, "WellFormed({})", ty),
+        }
+    }
+}
+
+impl<'tcx> fmt::Display for traits::FromEnv<'tcx> {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        use traits::FromEnv::*;
+
+        match self {
+            Trait(trait_ref) => write!(fmt, "FromEnv({})", trait_ref),
+            Ty(ty) => write!(fmt, "FromEnv({})", ty),
         }
     }
 }
@@ -419,19 +443,12 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
 impl<'tcx> fmt::Display for traits::DomainGoal<'tcx> {
     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
         use traits::DomainGoal::*;
-        use traits::WhereClauseAtom::*;
 
         match self {
             Holds(wc) => write!(fmt, "{}", wc),
-            WellFormed(Implemented(trait_ref)) => write!(fmt, "WellFormed({})", trait_ref),
-            WellFormed(ProjectionEq(projection)) => write!(fmt, "WellFormed({})", projection),
-            FromEnv(Implemented(trait_ref)) => write!(fmt, "FromEnv({})", trait_ref),
-            FromEnv(ProjectionEq(projection)) => write!(fmt, "FromEnv({})", projection),
-            WellFormedTy(ty) => write!(fmt, "WellFormed({})", ty),
+            WellFormed(wf) => write!(fmt, "{}", wf),
+            FromEnv(from_env) => write!(fmt, "{}", from_env),
             Normalize(projection) => write!(fmt, "Normalize({})", projection),
-            FromEnvTy(ty) => write!(fmt, "FromEnv({})", ty),
-            RegionOutlives(predicate) => write!(fmt, "RegionOutlives({})", predicate),
-            TypeOutlives(predicate) => write!(fmt, "TypeOutlives({})", predicate),
         }
     }
 }
@@ -506,30 +523,60 @@ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
 }
 
 EnumTypeFoldableImpl! {
-    impl<'tcx> TypeFoldable<'tcx> for traits::WhereClauseAtom<'tcx> {
-        (traits::WhereClauseAtom::Implemented)(trait_ref),
-        (traits::WhereClauseAtom::ProjectionEq)(projection),
+    impl<'tcx> TypeFoldable<'tcx> for traits::WhereClause<'tcx> {
+        (traits::WhereClause::Implemented)(trait_ref),
+        (traits::WhereClause::ProjectionEq)(projection),
+        (traits::WhereClause::TypeOutlives)(ty_outlives),
+        (traits::WhereClause::RegionOutlives)(region_outlives),
+    }
+}
+
+EnumLiftImpl! {
+    impl<'a, 'tcx> Lift<'tcx> for traits::WhereClause<'a> {
+        type Lifted = traits::WhereClause<'tcx>;
+        (traits::WhereClause::Implemented)(trait_ref),
+        (traits::WhereClause::ProjectionEq)(projection),
+        (traits::WhereClause::TypeOutlives)(ty_outlives),
+        (traits::WhereClause::RegionOutlives)(region_outlives),
+    }
+}
+
+EnumTypeFoldableImpl! {
+    impl<'tcx> TypeFoldable<'tcx> for traits::WellFormed<'tcx> {
+        (traits::WellFormed::Trait)(trait_ref),
+        (traits::WellFormed::Ty)(ty),
+    }
+}
+
+EnumLiftImpl! {
+    impl<'a, 'tcx> Lift<'tcx> for traits::WellFormed<'a> {
+        type Lifted = traits::WellFormed<'tcx>;
+        (traits::WellFormed::Trait)(trait_ref),
+        (traits::WellFormed::Ty)(ty),
+    }
+}
+
+EnumTypeFoldableImpl! {
+    impl<'tcx> TypeFoldable<'tcx> for traits::FromEnv<'tcx> {
+        (traits::FromEnv::Trait)(trait_ref),
+        (traits::FromEnv::Ty)(ty),
     }
 }
 
 EnumLiftImpl! {
-    impl<'a, 'tcx> Lift<'tcx> for traits::WhereClauseAtom<'a> {
-        type Lifted = traits::WhereClauseAtom<'tcx>;
-        (traits::WhereClauseAtom::Implemented)(trait_ref),
-        (traits::WhereClauseAtom::ProjectionEq)(projection),
+    impl<'a, 'tcx> Lift<'tcx> for traits::FromEnv<'a> {
+        type Lifted = traits::FromEnv<'tcx>;
+        (traits::FromEnv::Trait)(trait_ref),
+        (traits::FromEnv::Ty)(ty),
     }
 }
 
 EnumTypeFoldableImpl! {
     impl<'tcx> TypeFoldable<'tcx> for traits::DomainGoal<'tcx> {
         (traits::DomainGoal::Holds)(wc),
-        (traits::DomainGoal::WellFormed)(wc),
-        (traits::DomainGoal::FromEnv)(wc),
-        (traits::DomainGoal::WellFormedTy)(ty),
+        (traits::DomainGoal::WellFormed)(wf),
+        (traits::DomainGoal::FromEnv)(from_env),
         (traits::DomainGoal::Normalize)(projection),
-        (traits::DomainGoal::FromEnvTy)(ty),
-        (traits::DomainGoal::RegionOutlives)(predicate),
-        (traits::DomainGoal::TypeOutlives)(predicate),
     }
 }
 
@@ -537,13 +584,9 @@ impl<'tcx> TypeFoldable<'tcx> for traits::DomainGoal<'tcx> {
     impl<'a, 'tcx> Lift<'tcx> for traits::DomainGoal<'a> {
         type Lifted = traits::DomainGoal<'tcx>;
         (traits::DomainGoal::Holds)(wc),
-        (traits::DomainGoal::WellFormed)(wc),
-        (traits::DomainGoal::FromEnv)(wc),
-        (traits::DomainGoal::WellFormedTy)(ty),
+        (traits::DomainGoal::WellFormed)(wf),
+        (traits::DomainGoal::FromEnv)(from_env),
         (traits::DomainGoal::Normalize)(projection),
-        (traits::DomainGoal::FromEnvTy)(ty),
-        (traits::DomainGoal::RegionOutlives)(predicate),
-        (traits::DomainGoal::TypeOutlives)(predicate),
     }
 }
 
index 3db61b76cc55c57e3a7f8ce54672bbe7f75f05ec..971b3c3d14aebe3b88ed5ad042b34c5e4e92c23b 100644 (file)
@@ -18,6 +18,8 @@ pub enum BindingMode {
     BindByValue(Mutability),
 }
 
+CloneTypeFoldableAndLiftImpls! { BindingMode, }
+
 impl BindingMode {
     pub fn convert(ba: BindingAnnotation) -> BindingMode {
         match ba {
index d858ba7acf7863bf1da169566d194b99404db518..479fbe2673b97357a8d54aaa37dd41e06c6d0433 100644 (file)
@@ -215,7 +215,7 @@ pub fn push_item_path<T>(self, buffer: &mut T, def_id: DefId)
             data @ DefPathData::ValueNs(..) |
             data @ DefPathData::Module(..) |
             data @ DefPathData::TypeParam(..) |
-            data @ DefPathData::LifetimeDef(..) |
+            data @ DefPathData::LifetimeParam(..) |
             data @ DefPathData::EnumVariant(..) |
             data @ DefPathData::Field(..) |
             data @ DefPathData::AnonConst |
index 883882dfe6837f22be689cc3c2aa5499fd7ee386..3252a2cd6ab0f6bcbfe35c54ae3ba41cd6cb36e2 100644 (file)
@@ -287,7 +287,7 @@ fn parameterized<F: fmt::Write>(&mut self,
                     DefPathData::MacroDef(_) |
                     DefPathData::ClosureExpr |
                     DefPathData::TypeParam(_) |
-                    DefPathData::LifetimeDef(_) |
+                    DefPathData::LifetimeParam(_) |
                     DefPathData::Field(_) |
                     DefPathData::StructCtor |
                     DefPathData::AnonConst |
@@ -336,12 +336,10 @@ fn parameterized<F: fmt::Write>(&mut self,
 
             if !verbose {
                 let mut type_params =
-                    generics.params.iter().rev().filter_map(|param| {
-                        match param.kind {
-                            GenericParamDefKind::Type { has_default, .. } => {
-                                Some((param.def_id, has_default))
-                            }
-                            GenericParamDefKind::Lifetime => None,
+                    generics.params.iter().rev().filter_map(|param| match param.kind {
+                        GenericParamDefKind::Lifetime => None,
+                        GenericParamDefKind::Type { has_default, .. } => {
+                            Some((param.def_id, has_default))
                         }
                     }).peekable();
                 let has_default = {
index 7cf0a1c1becaa53c69ac26fa6f0c62826c755837..6ddae57e336ede3c2059cf1105b1a35ca1701d4c 100644 (file)
@@ -32,7 +32,7 @@ rustc_mir = { path = "../librustc_mir" }
 serialize = { path = "../libserialize" }
 syntax = { path = "../libsyntax" }
 syntax_pos = { path = "../libsyntax_pos" }
-tempdir = "0.3"
+tempfile = "3.0"
 
 # not actually used but needed to make sure we enable the same feature set as
 # winapi used in librustc
index a5d04c5c576b22e3c2d89e0c611ec58da7f88372..429acbbe0c2cb1cb428447c55e22845378bcfa14 100644 (file)
@@ -98,6 +98,11 @@ pub fn set_probestack(cx: &CodegenCx, llfn: ValueRef) {
         return;
     }
 
+    // probestack doesn't play nice either with gcov profiling.
+    if cx.sess().opts.debugging_opts.profile {
+        return;
+    }
+
     // Flag our internal `__rust_probestack` function as the stack probe symbol.
     // This is defined in the `compiler-builtins` crate for each architecture.
     llvm::AddFunctionAttrStringValue(
index 4e9910e58f391dcb79aca2626d2b1c57100cc53a..7e24e1114a0c2cf0118d6d2e5b49bb196b140d62 100644 (file)
@@ -28,7 +28,7 @@
 use rustc::util::common::time;
 use rustc::util::fs::fix_windows_verbatim_for_gcc;
 use rustc::hir::def_id::CrateNum;
-use tempdir::TempDir;
+use tempfile::{Builder as TempFileBuilder, TempDir};
 use rustc_target::spec::{PanicStrategy, RelroLevel, LinkerFlavor, TargetTriple};
 use rustc_data_structures::fx::FxHashSet;
 use context::get_reloc_model;
@@ -321,7 +321,10 @@ fn link_binary_output(sess: &Session,
         // final destination, with a `fs::rename` call. In order for the rename to
         // always succeed, the temporary file needs to be on the same filesystem,
         // which is why we create it inside the output directory specifically.
-        let metadata_tmpdir = match TempDir::new_in(out_filename.parent().unwrap(), "rmeta") {
+        let metadata_tmpdir = match TempFileBuilder::new()
+            .prefix("rmeta")
+            .tempdir_in(out_filename.parent().unwrap())
+        {
             Ok(tmpdir) => tmpdir,
             Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
         };
@@ -332,7 +335,7 @@ fn link_binary_output(sess: &Session,
         out_filenames.push(out_filename);
     }
 
-    let tmpdir = match TempDir::new("rustc") {
+    let tmpdir = match TempFileBuilder::new().prefix("rustc").tempdir() {
         Ok(tmpdir) => tmpdir,
         Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
     };
index 8732e115fd2fd967cc51ffc52a681de11f6db060..b11b0c7abe875b11b3a3bd184768ef00e330e17b 100644 (file)
@@ -56,7 +56,7 @@
 extern crate rustc_errors as errors;
 extern crate serialize;
 extern crate cc; // Used to locate MSVC
-extern crate tempdir;
+extern crate tempfile;
 
 use back::bytecode::RLIB_BYTECODE_EXTENSION;
 
index f1ad14237eec27dfeb7ee1ce1cf424a46db56895..67720e61e91af3eb16fbeb930a5ca2128f948cf8 100644 (file)
@@ -677,14 +677,20 @@ fn involves_impl_trait(ty: &ast::Ty) -> bool {
                     ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
                     ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
                     ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
-                        match seg.parameters.as_ref().map(|p| &**p) {
+                        match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
                             None => false,
-                            Some(&ast::PathParameters::AngleBracketed(ref data)) =>
-                                any_involves_impl_trait(data.types.iter()) ||
-                                any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty)),
-                            Some(&ast::PathParameters::Parenthesized(ref data)) =>
+                            Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
+                                let types = data.args.iter().filter_map(|arg| match arg {
+                                    ast::GenericArg::Type(ty) => Some(ty),
+                                    _ => None,
+                                });
+                                any_involves_impl_trait(types.into_iter()) ||
+                                any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty))
+                            },
+                            Some(&ast::GenericArgs::Parenthesized(ref data)) => {
                                 any_involves_impl_trait(data.inputs.iter()) ||
-                                any_involves_impl_trait(data.output.iter()),
+                                any_involves_impl_trait(data.output.iter())
+                            }
                         }
                     }),
                     _ => false,
index dbf756f80ca3853bb492549b8213171dd29139bb..8f8fe04fd8e019c9ab653ece9f90d1526297eae4 100644 (file)
@@ -18,7 +18,7 @@
 use syntax::attr;
 use syntax_pos::Span;
 
-use rustc::hir::{self, PatKind};
+use rustc::hir::{self, GenericParamKind, PatKind};
 use rustc::hir::intravisit::FnKind;
 
 #[derive(PartialEq)]
@@ -147,9 +147,12 @@ fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generic
     }
 
     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
-        if let hir::GenericParam::Type(ref gen) = *param {
-            if gen.synthetic.is_none() {
-                self.check_case(cx, "type parameter", gen.name, gen.span);
+        match param.kind {
+            GenericParamKind::Lifetime { .. } => {}
+            GenericParamKind::Type { synthetic, .. } => {
+                if synthetic.is_none() {
+                    self.check_case(cx, "type parameter", param.name.name(), param.span);
+                }
             }
         }
     }
@@ -253,13 +256,12 @@ fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
     }
 
     fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
-        if let hir::GenericParam::Lifetime(ref ld) = *param {
-            self.check_snake_case(
-                cx,
-                "lifetime",
-                &ld.lifetime.name.name().as_str(),
-                Some(ld.lifetime.span)
-            );
+        match param.kind {
+            GenericParamKind::Lifetime { .. } => {
+                let name = param.name.name().as_str();
+                self.check_snake_case(cx, "lifetime", &name, Some(param.span));
+            }
+            GenericParamKind::Type { .. } => {}
         }
     }
 
index 79796d788719a7be3a7cc78583f63cb3110a2ae7..941fabe26a6ed3ff3f789103372c6d4306dc2546 100644 (file)
@@ -49,7 +49,7 @@
 use syntax::symbol::keywords;
 use syntax::errors::{Applicability, DiagnosticBuilder};
 
-use rustc::hir::{self, PatKind};
+use rustc::hir::{self, GenericParamKind, PatKind};
 use rustc::hir::intravisit::FnKind;
 
 use bad_style::{MethodLateContext, method_context};
@@ -1196,15 +1196,21 @@ fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
                         }
                         err.emit();
                     }
-                    if generics.is_type_parameterized() {
-                        let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
-                                                          it.span,
-                                                          "functions generic over \
-                                                           types must be mangled");
-                        err.span_suggestion_short(no_mangle_attr.span,
-                                                  "remove this attribute",
-                                                  "".to_owned());
-                        err.emit();
+                    for param in &generics.params {
+                        match param.kind {
+                            GenericParamKind::Lifetime { .. } => {}
+                            GenericParamKind::Type { .. } => {
+                                let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
+                                                                  it.span,
+                                                                  "functions generic over \
+                                                                   types must be mangled");
+                                err.span_suggestion_short(no_mangle_attr.span,
+                                                          "remove this attribute",
+                                                          "".to_owned());
+                                err.emit();
+                                break;
+                            }
+                        }
                     }
                 }
             }
@@ -1531,10 +1537,7 @@ fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
         }
         // The parameters must not have bounds
         for param in type_alias_generics.params.iter() {
-            let spans : Vec<_> = match param {
-                &hir::GenericParam::Lifetime(ref l) => l.bounds.iter().map(|b| b.span).collect(),
-                &hir::GenericParam::Type(ref ty) => ty.bounds.iter().map(|b| b.span()).collect(),
-            };
+            let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
             if !spans.is_empty() {
                 let mut err = cx.struct_span_lint(
                     TYPE_ALIAS_BOUNDS,
index 2abe361233fd0f3fe77189a7f2fa6449f188d948..50492ae073720b62fef99564f6df441697fa2407 100644 (file)
@@ -810,52 +810,63 @@ fn get_lints(&self) -> LintArray {
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
-        if let hir::ItemEnum(ref enum_definition, ref gens) = it.node {
-            if gens.params.iter().all(|param| param.is_lifetime_param()) {
-                // sizes only make sense for non-generic types
-                let item_def_id = cx.tcx.hir.local_def_id(it.id);
-                let t = cx.tcx.type_of(item_def_id);
-                let ty = cx.tcx.erase_regions(&t);
-                let layout = cx.layout_of(ty).unwrap_or_else(|e| {
-                    bug!("failed to get layout for `{}`: {}", t, e)
-                });
-
-                if let layout::Variants::Tagged { ref variants, ref tag, .. } = layout.variants {
-                    let discr_size = tag.value.size(cx.tcx).bytes();
-
-                    debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
-                      t, layout.size.bytes(), layout);
-
-                    let (largest, slargest, largest_index) = enum_definition.variants
-                        .iter()
-                        .zip(variants)
-                        .map(|(variant, variant_layout)| {
-                            // Subtract the size of the enum discriminant
-                            let bytes = variant_layout.size.bytes()
-                                .saturating_sub(discr_size);
-
-                            debug!("- variant `{}` is {} bytes large", variant.node.name, bytes);
-                            bytes
-                        })
-                        .enumerate()
-                        .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
-                            (size, l, idx)
-                        } else if size > s {
-                            (l, size, li)
-                        } else {
-                            (l, s, li)
-                        });
-
-                    // we only warn if the largest variant is at least thrice as large as
-                    // the second-largest.
-                    if largest > slargest * 3 && slargest > 0 {
-                        cx.span_lint(VARIANT_SIZE_DIFFERENCES,
-                                     enum_definition.variants[largest_index].span,
-                                     &format!("enum variant is more than three times larger \
-                                               ({} bytes) than the next largest",
-                                              largest));
+        if let hir::ItemEnum(ref enum_definition, _) = it.node {
+            let item_def_id = cx.tcx.hir.local_def_id(it.id);
+            let generics = cx.tcx.generics_of(item_def_id);
+            for param in &generics.params {
+                match param.kind {
+                    ty::GenericParamDefKind::Lifetime { .. } => {},
+                    ty::GenericParamDefKind::Type { .. } => return,
+                }
+            }
+            // Sizes only make sense for non-generic types.
+            let t = cx.tcx.type_of(item_def_id);
+            let ty = cx.tcx.erase_regions(&t);
+            match cx.layout_of(ty) {
+                Ok(layout) => {
+                    let variants = &layout.variants;
+                    if let layout::Variants::Tagged { ref variants, ref tag, .. } = variants {
+                        let discr_size = tag.value.size(cx.tcx).bytes();
+
+                        debug!("enum `{}` is {} bytes large with layout:\n{:#?}",
+                               t, layout.size.bytes(), layout);
+
+                        let (largest, slargest, largest_index) = enum_definition.variants
+                            .iter()
+                            .zip(variants)
+                            .map(|(variant, variant_layout)| {
+                                // Subtract the size of the enum discriminant.
+                                let bytes = variant_layout.size.bytes().saturating_sub(discr_size);
+
+                                debug!("- variant `{}` is {} bytes large",
+                                       variant.node.name,
+                                       bytes);
+                                bytes
+                            })
+                            .enumerate()
+                            .fold((0, 0, 0), |(l, s, li), (idx, size)| if size > l {
+                                (size, l, idx)
+                            } else if size > s {
+                                (l, size, li)
+                            } else {
+                                (l, s, li)
+                            });
+
+                        // We only warn if the largest variant is at least thrice as large as
+                        // the second-largest.
+                        if largest > slargest * 3 && slargest > 0 {
+                            cx.span_lint(VARIANT_SIZE_DIFFERENCES,
+                                            enum_definition.variants[largest_index].span,
+                                            &format!("enum variant is more than three times \
+                                                      larger ({} bytes) than the next largest",
+                                                     largest));
+                        }
                     }
                 }
+                Err(ty::layout::LayoutError::Unknown(_)) => return,
+                Err(err @ ty::layout::LayoutError::SizeOverflow(_)) => {
+                    bug!("failed to get layout for `{}`: {}", t, err);
+                }
             }
         }
     }
index e41b3f5f53b252fee2d1829136d077bd8a0bcdd8..6c1991457433f6231b445ea18632501afff5bdc7 100644 (file)
@@ -986,8 +986,10 @@ fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
             },
             None => {
                 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
-                    self.sess.err("no #[default_lib_allocator] found but one is \
-                                   required; is libstd not linked?");
+                    self.sess.err("no global memory allocator found but one is \
+                                   required; link to std or \
+                                   add #[global_allocator] to a static item \
+                                   that implements the GlobalAlloc trait.");
                     return;
                 }
                 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
index 33d4df1c3a5dc2b37984615144fc81cd22ba15fa..cbe9615c69397c644e18b5c44652198aaaad30c5 100644 (file)
@@ -1235,10 +1235,14 @@ fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) ->
                     self.encode_optimized_mir(def_id)
                 }
                 hir::ItemConst(..) => self.encode_optimized_mir(def_id),
-                hir::ItemFn(_, _, constness, _, ref generics, _) => {
-                    let has_tps = generics.ty_params().next().is_some();
+                hir::ItemFn(_, _, constness, ..) => {
+                    let generics = tcx.generics_of(def_id);
+                    let has_types = generics.params.iter().any(|param| match param.kind {
+                        ty::GenericParamDefKind::Type { .. } => true,
+                        _ => false,
+                    });
                     let needs_inline =
-                        (has_tps || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
+                        (has_types || tcx.codegen_fn_attrs(def_id).requests_inline()) &&
                             !self.metadata_output_only();
                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
                     if needs_inline || constness == hir::Constness::Const || always_encode_mir {
@@ -1645,11 +1649,15 @@ fn encode_fields(&mut self, adt_def_id: DefId) {
     }
 
     fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
-        for ty_param in generics.ty_params() {
-            let def_id = self.tcx.hir.local_def_id(ty_param.id);
-            let has_default = Untracked(ty_param.default.is_some());
-            self.record(def_id, IsolatedEncoder::encode_info_for_ty_param, (def_id, has_default));
-        }
+        generics.params.iter().for_each(|param| match param.kind {
+            hir::GenericParamKind::Lifetime { .. } => {}
+            hir::GenericParamKind::Type { ref default, .. } => {
+                let def_id = self.tcx.hir.local_def_id(param.id);
+                let has_default = Untracked(default.is_some());
+                let encode_info = IsolatedEncoder::encode_info_for_ty_param;
+                self.record(def_id, encode_info, (def_id, has_default));
+            }
+        });
     }
 
     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
index 9061af1b68ca4717c9f4c562d22da3b79fb45013..30be87199ebe09f0968d84c293f0449017ce095f 100644 (file)
@@ -8,20 +8,21 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use syntax_pos::Span;
+use borrow_check::WriteKind;
 use rustc::middle::region::ScopeTree;
 use rustc::mir::{BorrowKind, Field, Local, LocalKind, Location, Operand};
 use rustc::mir::{Place, ProjectionElem, Rvalue, Statement, StatementKind};
 use rustc::ty::{self, RegionKind};
 use rustc_data_structures::indexed_vec::Idx;
 use rustc_data_structures::sync::Lrc;
+use syntax_pos::Span;
 
+use super::borrow_set::BorrowData;
 use super::{Context, MirBorrowckCtxt};
 use super::{InitializationRequiringAction, PrefixSet};
-use super::borrow_set::BorrowData;
 
-use dataflow::{FlowAtLocation, MovingOutStatements};
 use dataflow::move_paths::MovePathIndex;
+use dataflow::{FlowAtLocation, MovingOutStatements};
 use util::borrowck_errors::{BorrowckErrors, Origin};
 
 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
@@ -39,13 +40,9 @@ pub(super) fn report_use_of_moved_or_uninitialized(
             .collect::<Vec<_>>();
 
         if mois.is_empty() {
-            let root_place = self.prefixes(&place, PrefixSet::All)
-                .last()
-                .unwrap();
+            let root_place = self.prefixes(&place, PrefixSet::All).last().unwrap();
 
-            if self.moved_error_reported
-                .contains(&root_place.clone())
-            {
+            if self.moved_error_reported.contains(&root_place.clone()) {
                 debug!(
                     "report_use_of_moved_or_uninitialized place: error about {:?} suppressed",
                     root_place
@@ -53,8 +50,7 @@ pub(super) fn report_use_of_moved_or_uninitialized(
                 return;
             }
 
-            self.moved_error_reported
-                .insert(root_place.clone());
+            self.moved_error_reported.insert(root_place.clone());
 
             let item_msg = match self.describe_place(place) {
                 Some(name) => format!("`{}`", name),
@@ -162,7 +158,7 @@ pub(super) fn report_move_out_while_borrowed(
             format!("borrow of {} occurs here", borrow_msg),
         );
         err.span_label(span, format!("move out of {} occurs here", value_msg));
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
         err.emit();
     }
 
@@ -177,12 +173,13 @@ pub(super) fn report_use_while_mutably_borrowed(
             span,
             &self.describe_place(place).unwrap_or("_".to_owned()),
             self.retrieve_borrow_span(borrow),
-            &self.describe_place(&borrow.borrowed_place)
+            &self
+                .describe_place(&borrow.borrowed_place)
                 .unwrap_or("_".to_owned()),
             Origin::Mir,
         );
 
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
 
         err.emit();
     }
@@ -286,8 +283,8 @@ pub(super) fn report_conflicting_borrow(
             "mutable",
         ) {
             (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt)
-            | (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
-                tcx.cannot_reborrow_already_borrowed(
+            | (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => tcx
+                .cannot_reborrow_already_borrowed(
                     span,
                     &desc_place,
                     "",
@@ -298,11 +295,10 @@ pub(super) fn report_conflicting_borrow(
                     "",
                     None,
                     Origin::Mir,
-                )
-            }
+                ),
 
-            (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
-                tcx.cannot_mutably_borrow_multiply(
+            (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => tcx
+                .cannot_mutably_borrow_multiply(
                     span,
                     &desc_place,
                     "",
@@ -310,18 +306,16 @@ pub(super) fn report_conflicting_borrow(
                     "",
                     None,
                     Origin::Mir,
-                )
-            }
+                ),
 
-            (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
-                tcx.cannot_uniquely_borrow_by_two_closures(
+            (BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => tcx
+                .cannot_uniquely_borrow_by_two_closures(
                     span,
                     &desc_place,
                     issued_span,
                     None,
                     Origin::Mir,
-                )
-            }
+                ),
 
             (BorrowKind::Unique, _, _, _, _, _) => tcx.cannot_uniquely_borrow_by_one_closure(
                 span,
@@ -334,8 +328,8 @@ pub(super) fn report_conflicting_borrow(
                 Origin::Mir,
             ),
 
-            (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
-                tcx.cannot_reborrow_already_uniquely_borrowed(
+            (BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => tcx
+                .cannot_reborrow_already_uniquely_borrowed(
                     span,
                     &desc_place,
                     "",
@@ -344,11 +338,10 @@ pub(super) fn report_conflicting_borrow(
                     "",
                     None,
                     Origin::Mir,
-                )
-            }
+                ),
 
-            (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
-                tcx.cannot_reborrow_already_uniquely_borrowed(
+            (BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => tcx
+                .cannot_reborrow_already_uniquely_borrowed(
                     span,
                     &desc_place,
                     "",
@@ -357,13 +350,15 @@ pub(super) fn report_conflicting_borrow(
                     "",
                     None,
                     Origin::Mir,
-                )
-            }
+                ),
 
             (BorrowKind::Shared, _, _, BorrowKind::Shared, _, _) => unreachable!(),
         };
 
         if let Some((_, var_span)) = old_closure_span {
+            let place = &issued_borrow.borrowed_place;
+            let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
+
             err.span_label(
                 var_span,
                 format!(
@@ -380,7 +375,7 @@ pub(super) fn report_conflicting_borrow(
             );
         }
 
-        self.explain_why_borrow_contains_point(context, issued_borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, issued_borrow, None, &mut err);
 
         err.emit();
     }
@@ -389,10 +384,13 @@ pub(super) fn report_borrowed_value_does_not_live_long_enough(
         &mut self,
         context: Context,
         borrow: &BorrowData<'tcx>,
-        drop_span: Span,
+        place_span: (&Place<'tcx>, Span),
+        kind: Option<WriteKind>,
     ) {
+        let drop_span = place_span.1;
         let scope_tree = self.tcx.region_scope_tree(self.mir_def_id);
-        let root_place = self.prefixes(&borrow.borrowed_place, PrefixSet::All)
+        let root_place = self
+            .prefixes(&borrow.borrowed_place, PrefixSet::All)
             .last()
             .unwrap();
 
@@ -402,7 +400,8 @@ pub(super) fn report_borrowed_value_does_not_live_long_enough(
             _ => drop_span,
         };
 
-        if self.access_place_error_reported
+        if self
+            .access_place_error_reported
             .contains(&(root_place.clone(), borrow_span))
         {
             debug!(
@@ -450,6 +449,7 @@ pub(super) fn report_borrowed_value_does_not_live_long_enough(
                     drop_span,
                     borrow_span,
                     proper_span,
+                    kind.map(|k| (k, place_span.0)),
                 );
             }
             (RegionKind::ReEarlyBound(_), None)
@@ -471,8 +471,11 @@ pub(super) fn report_borrowed_value_does_not_live_long_enough(
             | (RegionKind::ReClosureBound(_), _)
             | (RegionKind::ReCanonical(_), _)
             | (RegionKind::ReErased, _) => {
-                span_bug!(drop_span, "region {:?} does not make sense in this context",
-                          borrow.region);
+                span_bug!(
+                    drop_span,
+                    "region {:?} does not make sense in this context",
+                    borrow.region
+                );
             }
         }
     }
@@ -495,7 +498,7 @@ fn report_scoped_local_value_does_not_live_long_enough(
             drop_span,
             format!("`{}` dropped here while still borrowed", name),
         );
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
         err.emit();
     }
 
@@ -517,7 +520,7 @@ fn report_scoped_temporary_value_does_not_live_long_enough(
             "temporary value dropped here while still borrowed",
         );
         err.note("consider using a `let` binding to increase its lifetime");
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
         err.emit();
     }
 
@@ -530,6 +533,7 @@ fn report_unscoped_local_value_does_not_live_long_enough(
         drop_span: Span,
         borrow_span: Span,
         _proper_span: Span,
+        kind_place: Option<(WriteKind, &Place<'tcx>)>,
     ) {
         debug!(
             "report_unscoped_local_value_does_not_live_long_enough(\
@@ -544,7 +548,7 @@ fn report_unscoped_local_value_does_not_live_long_enough(
         err.span_label(borrow_span, "borrowed value does not live long enough");
         err.span_label(drop_span, "borrowed value only lives until here");
 
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, kind_place, &mut err);
         err.emit();
     }
 
@@ -570,7 +574,7 @@ fn report_unscoped_temporary_value_does_not_live_long_enough(
         err.span_label(proper_span, "temporary value does not live long enough");
         err.span_label(drop_span, "temporary value only lives until here");
 
-        self.explain_why_borrow_contains_point(context, borrow, &mut err);
+        self.explain_why_borrow_contains_point(context, borrow, None, &mut err);
         err.emit();
     }
 
@@ -588,16 +592,23 @@ pub(super) fn report_illegal_mutation_of_borrowed(
             Origin::Mir,
         );
 
-        self.explain_why_borrow_contains_point(context, loan, &mut err);
+        self.explain_why_borrow_contains_point(context, loan, None, &mut err);
 
         err.emit();
     }
 
+    /// Reports an illegal reassignment; for example, an assignment to
+    /// (part of) a non-`mut` local that occurs potentially after that
+    /// local has already been initialized. `place` is the path being
+    /// assigned; `err_place` is a place providing a reason why
+    /// `place` is not mutable (e.g. the non-`mut` local `x` in an
+    /// assignment to `x.f`).
     pub(super) fn report_illegal_reassignment(
         &mut self,
         _context: Context,
         (place, span): (&Place<'tcx>, Span),
         assigned_span: Span,
+        err_place: &Place<'tcx>,
     ) {
         let is_arg = if let Place::Local(local) = place {
             if let LocalKind::Arg = self.mir.local_kind(*local) {
@@ -621,9 +632,7 @@ pub(super) fn report_illegal_reassignment(
             "cannot assign twice to immutable variable"
         };
         if span != assigned_span {
-            if is_arg {
-                err.span_label(assigned_span, "argument not declared as `mut`");
-            } else {
+            if !is_arg {
                 let value_msg = match self.describe_place(place) {
                     Some(name) => format!("`{}`", name),
                     None => "value".to_owned(),
@@ -631,6 +640,15 @@ pub(super) fn report_illegal_reassignment(
                 err.span_label(assigned_span, format!("first assignment to {}", value_msg));
             }
         }
+        if let Place::Local(local) = err_place {
+            let local_decl = &self.mir.local_decls[*local];
+            if let Some(name) = local_decl.name {
+                if local_decl.can_be_made_mutable() {
+                    err.span_label(local_decl.source_info.span,
+                                   format!("consider changing this to `mut {}`", name));
+                }
+            }
+        }
         err.span_label(span, msg);
         err.emit();
     }
@@ -745,9 +763,10 @@ fn describe_field(&self, base: &Place, field: Field) -> String {
             Place::Static(ref static_) => self.describe_field_from_ty(&static_.ty, field),
             Place::Projection(ref proj) => match proj.elem {
                 ProjectionElem::Deref => self.describe_field(&proj.base, field),
-                ProjectionElem::Downcast(def, variant_index) => {
-                    format!("{}", def.variants[variant_index].fields[field.index()].ident)
-                }
+                ProjectionElem::Downcast(def, variant_index) => format!(
+                    "{}",
+                    def.variants[variant_index].fields[field.index()].ident
+                ),
                 ProjectionElem::Field(_, field_type) => {
                     self.describe_field_from_ty(&field_type, field)
                 }
index c43ea0360ee1394101d923fbe5d9aab4b42eba44..115f36c149b64907ce33fa3974f5c9088803efbf 100644 (file)
@@ -18,7 +18,7 @@
 use rustc::ty::{self, ParamEnv, TyCtxt};
 use rustc::ty::query::Providers;
 use rustc::lint::builtin::UNUSED_MUT;
-use rustc::mir::{AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
+use rustc::mir::{self, AggregateKind, BasicBlock, BorrowCheckResult, BorrowKind};
 use rustc::mir::{ClearCrossCrate, Local, Location, Place, Mir, Mutability, Operand};
 use rustc::mir::{Projection, ProjectionElem, Rvalue, Field, Statement, StatementKind};
 use rustc::mir::{Terminator, TerminatorKind};
@@ -61,6 +61,7 @@
 crate mod place_ext;
 mod prefixes;
 mod path_utils;
+mod used_muts;
 
 pub(crate) mod nll;
 
@@ -278,23 +279,10 @@ fn do_mir_borrowck<'a, 'gcx, 'tcx>(
     // to the set.
     let temporary_used_locals: FxHashSet<Local> =
         mbcx.used_mut.iter()
-            .filter(|&local| !mbcx.mir.local_decls[*local].is_user_variable)
+            .filter(|&local| !mbcx.mir.local_decls[*local].is_user_variable.is_some())
             .cloned()
             .collect();
-
-    for local in temporary_used_locals {
-        for location in mbcx.mir.find_assignments(local) {
-            for moi in &mbcx.move_data.loc_map[location] {
-                let mpi = &mbcx.move_data.moves[*moi].path;
-                let path = &mbcx.move_data.move_paths[*mpi];
-                debug!("assignment of {:?} to {:?}, adding {:?} to used mutable set",
-                       path.place, local, path.place);
-                if let Place::Local(user_local) = path.place {
-                    mbcx.used_mut.insert(user_local);
-                }
-            }
-        }
-    }
+    mbcx.gather_used_muts(temporary_used_locals);
 
     debug!("mbcx.used_mut: {:?}", mbcx.used_mut);
 
@@ -1050,7 +1038,8 @@ fn check_access_for_conflict(
                             this.report_borrowed_value_does_not_live_long_enough(
                                 context,
                                 borrow,
-                                place_span.1,
+                                place_span,
+                                Some(kind),
                             );
                         }
                         WriteKind::Mutate => {
@@ -1328,7 +1317,8 @@ fn check_for_invalidation_at_exit(
             self.report_borrowed_value_does_not_live_long_enough(
                 context,
                 borrow,
-                span,
+                (place, span),
+                None,
             )
         }
     }
@@ -1398,9 +1388,10 @@ fn check_if_reassignment_to_immutable_state(
     ) {
         debug!("check_if_reassignment_to_immutable_state({:?})", place);
         // determine if this path has a non-mut owner (and thus needs checking).
-        if let Ok(..) = self.is_mutable(place, LocalMutationIsAllowed::No) {
-            return;
-        }
+        let err_place = match self.is_mutable(place, LocalMutationIsAllowed::No) {
+            Ok(..) => return,
+            Err(place) => place,
+        };
         debug!(
             "check_if_reassignment_to_immutable_state({:?}) - is an imm local",
             place
@@ -1410,7 +1401,7 @@ fn check_if_reassignment_to_immutable_state(
             let init = self.move_data.inits[i];
             let init_place = &self.move_data.move_paths[init.path].place;
             if places_conflict(self.tcx, self.mir, &init_place, place, Deep) {
-                self.report_illegal_reassignment(context, (place, span), init.span);
+                self.report_illegal_reassignment(context, (place, span), init.span, err_place);
                 break;
             }
         }
@@ -1658,36 +1649,6 @@ fn check_if_assigned_path_is_moved(
         }
     }
 
-    fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
-        if let Some(_name) = self.describe_place(place) {
-            Some(format!("data in a `&` reference"))
-        } else {
-            None
-        }
-    }
-
-    fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
-        match self.describe_place(place) {
-            Some(name) => format!("immutable item `{}`", name),
-            None => "immutable item".to_owned(),
-        }
-    }
-
-    fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
-        match self.specialized_description(place) {
-            Some(_) => format!("data in a `&` reference"),
-            None => self.get_default_err_msg(place)
-        }
-    }
-
-    fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
-        if let Some(name) = self.describe_place(place) {
-            format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
-        } else {
-            format!("cannot assign through `&`-reference")
-        }
-    }
-
     /// Check the permissions for the given place and read or write kind
     ///
     /// Returns true if an error is reported, false otherwise.
@@ -1702,7 +1663,15 @@ fn check_access_permissions(
             "check_access_permissions({:?}, {:?}, {:?})",
             place, kind, is_local_mutation_allowed
         );
-        let mut error_reported = false;
+
+        #[derive(Copy, Clone, Debug)]
+        enum AccessKind {
+            MutableBorrow,
+            Mutate,
+        }
+        let error_access;
+        let the_place_err;
+
         match kind {
             Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Unique))
             | Reservation(WriteKind::MutableBorrow(borrow_kind @ BorrowKind::Mut { .. }))
@@ -1715,91 +1684,29 @@ fn check_access_permissions(
                     BorrowKind::Shared => unreachable!(),
                 };
                 match self.is_mutable(place, is_local_mutation_allowed) {
-                    Ok(root_place) => self.add_used_mut(root_place, flow_state),
+                    Ok(root_place) => {
+                        self.add_used_mut(root_place, flow_state);
+                        return false;
+                    }
                     Err(place_err) => {
-                        error_reported = true;
-                        let item_msg = self.get_default_err_msg(place);
-                        let mut err = self.tcx
-                            .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
-                        err.span_label(span, "cannot borrow as mutable");
-
-                        if place != place_err {
-                            if let Some(name) = self.describe_place(place_err) {
-                                err.note(&format!("the value which is causing this path not to be \
-                                    mutable is...: `{}`", name));
-                            }
-                        }
-
-                        err.emit();
+                        error_access = AccessKind::MutableBorrow;
+                        the_place_err = place_err;
                     }
                 }
             }
             Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
                 match self.is_mutable(place, is_local_mutation_allowed) {
-                    Ok(root_place) => self.add_used_mut(root_place, flow_state),
+                    Ok(root_place) => {
+                        self.add_used_mut(root_place, flow_state);
+                        return false;
+                    }
                     Err(place_err) => {
-                        error_reported = true;
-
-                        let err_info = if let Place::Projection(
-                            box Projection {
-                                base: Place::Local(local),
-                                elem: ProjectionElem::Deref
-                            }
-                        ) = *place_err {
-                            let locations = self.mir.find_assignments(local);
-                            if locations.len() > 0 {
-                                let item_msg = if error_reported {
-                                    self.get_secondary_err_msg(&Place::Local(local))
-                                } else {
-                                    self.get_default_err_msg(place)
-                                };
-                                let sp = self.mir.source_info(locations[0]).span;
-                                let mut to_suggest_span = String::new();
-                                if let Ok(src) =
-                                    self.tcx.sess.codemap().span_to_snippet(sp) {
-                                        to_suggest_span = src[1..].to_string();
-                                };
-                                Some((sp,
-                                      "consider changing this to be a \
-                                      mutable reference",
-                                      to_suggest_span,
-                                      item_msg,
-                                      self.get_primary_err_msg(&Place::Local(local))))
-                            } else {
-                                None
-                            }
-                        } else {
-                            None
-                        };
-
-                        if let Some((err_help_span,
-                                     err_help_stmt,
-                                     to_suggest_span,
-                                     item_msg,
-                                     sec_span)) = err_info {
-                            let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
-                            err.span_suggestion(err_help_span,
-                                                err_help_stmt,
-                                                format!("&mut {}", to_suggest_span));
-                            if place != place_err {
-                                err.span_label(span, sec_span);
-                            }
-                            err.emit()
-                        } else {
-                            let item_msg = self.get_default_err_msg(place);
-                            let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
-                            err.span_label(span, "cannot mutate");
-                            if place != place_err {
-                                if let Some(name) = self.describe_place(place_err) {
-                                    err.note(&format!("the value which is causing this path not \
-                                                       to be mutable is...: `{}`", name));
-                                }
-                            }
-                            err.emit();
-                        }
+                        error_access = AccessKind::Mutate;
+                        the_place_err = place_err;
                     }
                 }
             }
+
             Reservation(WriteKind::Move)
             | Write(WriteKind::Move)
             | Reservation(WriteKind::StorageDeadOrDrop)
@@ -1815,15 +1722,174 @@ fn check_access_permissions(
                         ),
                     );
                 }
+                return false;
+            }
+            Activation(..) => {
+                // permission checks are done at Reservation point.
+                return false;
             }
-            Activation(..) => {} // permission checks are done at Reservation point.
             Read(ReadKind::Borrow(BorrowKind::Unique))
             | Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
             | Read(ReadKind::Borrow(BorrowKind::Shared))
-            | Read(ReadKind::Copy) => {} // Access authorized
+            | Read(ReadKind::Copy) => {
+                // Access authorized
+                return false;
+            }
         }
 
-        error_reported
+        // at this point, we have set up the error reporting state.
+
+        let mut err;
+        let item_msg = match self.describe_place(place) {
+            Some(name) => format!("immutable item `{}`", name),
+            None => "immutable item".to_owned(),
+        };
+
+        // `act` and `acted_on` are strings that let us abstract over
+        // the verbs used in some diagnostic messages.
+        let act; let acted_on;
+
+        match error_access {
+            AccessKind::Mutate => {
+                let item_msg = match the_place_err {
+                    Place::Projection(box Projection {
+                        base: _,
+                        elem: ProjectionElem::Deref }
+                    ) => match self.describe_place(place) {
+                        Some(description) =>
+                            format!("`{}` which is behind a `&` reference", description),
+                        None => format!("data in a `&` reference"),
+                    },
+                    _ => item_msg,
+                };
+                err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
+                act = "assign"; acted_on = "written";
+            }
+            AccessKind::MutableBorrow => {
+                err = self.tcx
+                    .cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
+                act = "borrow as mutable"; acted_on = "borrowed as mutable";
+            }
+        }
+
+        match the_place_err {
+            // We want to suggest users use `let mut` for local (user
+            // variable) mutations...
+            Place::Local(local) if self.mir.local_decls[*local].can_be_made_mutable() => {
+                // ... but it doesn't make sense to suggest it on
+                // variables that are `ref x`, `ref mut x`, `&self`,
+                // or `&mut self` (such variables are simply not
+                // mutable)..
+                let local_decl = &self.mir.local_decls[*local];
+                assert_eq!(local_decl.mutability, Mutability::Not);
+
+                err.span_label(span, format!("cannot {ACT}", ACT=act));
+                err.span_suggestion(local_decl.source_info.span,
+                                    "consider changing this to be mutable",
+                                    format!("mut {}", local_decl.name.unwrap()));
+            }
+
+            // complete hack to approximate old AST-borrowck
+            // diagnostic: if the span starts with a mutable borrow of
+            // a local variable, then just suggest the user remove it.
+            Place::Local(_) if {
+                if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
+                    snippet.starts_with("&mut ")
+                } else {
+                    false
+                }
+            } => {
+                err.span_label(span, format!("cannot {ACT}", ACT=act));
+                err.span_label(span, "try removing `&mut` here");
+            }
+
+            // We want to point out when a `&` can be readily replaced
+            // with an `&mut`.
+            //
+            // FIXME: can this case be generalized to work for an
+            // arbitrary base for the projection?
+            Place::Projection(box Projection { base: Place::Local(local),
+                                               elem: ProjectionElem::Deref })
+                if self.mir.local_decls[*local].is_nonref_binding() =>
+            {
+                let (err_help_span, suggested_code) =
+                    find_place_to_suggest_ampmut(self.tcx, self.mir, *local);
+                err.span_suggestion(err_help_span,
+                                    "consider changing this to be a mutable reference",
+                                    suggested_code);
+
+                let local_decl = &self.mir.local_decls[*local];
+                if let Some(name) = local_decl.name {
+                    err.span_label(
+                        span, format!("`{NAME}` is a `&` reference, \
+                                       so the data it refers to cannot be {ACTED_ON}",
+                                      NAME=name, ACTED_ON=acted_on));
+                } else {
+                    err.span_label(span, format!("cannot {ACT} through `&`-reference", ACT=act));
+                }
+            }
+
+            _ => {
+                err.span_label(span, format!("cannot {ACT}", ACT=act));
+            }
+        }
+
+        err.emit();
+        return true;
+
+        // Returns the span to highlight and the associated text to
+        // present when suggesting that the user use an `&mut`.
+        //
+        // When we want to suggest a user change a local variable to be a `&mut`, there
+        // are three potential "obvious" things to highlight:
+        //
+        // let ident [: Type] [= RightHandSideExresssion];
+        //     ^^^^^    ^^^^     ^^^^^^^^^^^^^^^^^^^^^^^
+        //     (1.)     (2.)              (3.)
+        //
+        // We can always fallback on highlighting the first. But chances are good that
+        // the user experience will be better if we highlight one of the others if possible;
+        // for example, if the RHS is present and the Type is not, then the type is going to
+        // be inferred *from* the RHS, which means we should highlight that (and suggest
+        // that they borrow the RHS mutably).
+        fn find_place_to_suggest_ampmut<'cx, 'gcx, 'tcx>(tcx: TyCtxt<'cx, 'gcx, 'tcx>,
+                                                         mir: &Mir<'tcx>,
+                                                         local: Local) -> (Span, String)
+        {
+            // This implementation attempts to emulate AST-borrowck prioritization
+            // by trying (3.), then (2.) and finally falling back on (1.).
+            let locations = mir.find_assignments(local);
+            if locations.len() > 0 {
+                let assignment_rhs_span = mir.source_info(locations[0]).span;
+                let snippet = tcx.sess.codemap().span_to_snippet(assignment_rhs_span);
+                if let Ok(src) = snippet {
+                    // pnkfelix inherited code; believes intention is
+                    // highlighted text will always be `&<expr>` and
+                    // thus can transform to `&mut` by slicing off
+                    // first ASCII character and prepending "&mut ".
+                    let borrowed_expr = src[1..].to_string();
+                    return (assignment_rhs_span, format!("&mut {}", borrowed_expr));
+                }
+            }
+
+            let local_decl = &mir.local_decls[local];
+            let highlight_span = match local_decl.is_user_variable {
+                // if this is a variable binding with an explicit type,
+                // try to highlight that for the suggestion.
+                Some(ClearCrossCrate::Set(mir::BindingForm::Var(mir::VarBindingForm {
+                    opt_ty_info: Some(ty_span), .. }))) => ty_span,
+
+                Some(ClearCrossCrate::Clear) => bug!("saw cleared local state"),
+
+                // otherwise, just highlight the span associated with
+                // the (MIR) LocalDecl.
+                _ => local_decl.source_info.span,
+            };
+
+            let ty_mut = local_decl.ty.builtin_deref(true).unwrap();
+            assert_eq!(ty_mut.mutbl, hir::MutImmutable);
+            return (highlight_span, format!("&mut {}", ty_mut.ty));
+        }
     }
 
     /// Adds the place into the used mutable variables set
index 2807a4e8857e0b91421dbf09506b2598f16fb48a..4f37b338e92b66e08323649868f901fb2b48b552 100644 (file)
@@ -8,11 +8,11 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use borrow_check::nll::region_infer::{Cause, RegionInferenceContext};
-use borrow_check::{Context, MirBorrowckCtxt};
 use borrow_check::borrow_set::BorrowData;
+use borrow_check::nll::region_infer::{Cause, RegionInferenceContext};
+use borrow_check::{Context, MirBorrowckCtxt, WriteKind};
 use rustc::mir::visit::{MirVisitable, PlaceContext, Visitor};
-use rustc::mir::{Local, Location, Mir};
+use rustc::mir::{Local, Location, Mir, Place};
 use rustc_data_structures::fx::FxHashSet;
 use rustc_errors::DiagnosticBuilder;
 use util::liveness::{self, DefUse, LivenessMode};
@@ -22,11 +22,21 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
     /// point from `context`. This is key for the "3-point errors"
     /// [described in the NLL RFC][d].
     ///
+    /// # Parameters
+    ///
+    /// - `borrow`: the borrow in question
+    /// - `context`: where the borrow occurs
+    /// - `kind_place`: if Some, this describes the statement that triggered the error.
+    ///   - first half is the kind of write, if any, being performed
+    ///   - second half is the place being accessed
+    /// - `err`: where the error annotations are going to be added
+    ///
     /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
     pub(in borrow_check) fn explain_why_borrow_contains_point(
         &mut self,
         context: Context,
         borrow: &BorrowData<'tcx>,
+        kind_place: Option<(WriteKind, &Place<'tcx>)>,
         err: &mut DiagnosticBuilder<'_>,
     ) {
         let regioncx = &&self.nonlexical_regioncx;
@@ -35,58 +45,68 @@ pub(in borrow_check) fn explain_why_borrow_contains_point(
         let borrow_region_vid = regioncx.to_region_vid(borrow.region);
         if let Some(cause) = regioncx.why_region_contains_point(borrow_region_vid, context.loc) {
             match cause {
-                Cause::LiveVar(local, location) => {
-                    match find_regular_use(mir, regioncx, borrow, location, local) {
-                        Some(p) => {
+                Cause::LiveVar(local, location) => match find_regular_use(
+                    mir, regioncx, borrow, location, local,
+                ) {
+                    Some(p) => {
+                        err.span_label(mir.source_info(p).span, format!("borrow later used here"));
+                    }
+
+                    None => {
+                        span_bug!(
+                            mir.source_info(context.loc).span,
+                            "Cause should end in a LiveVar"
+                        );
+                    }
+                },
+
+                Cause::DropVar(local, location) => match find_drop_use(
+                    mir, regioncx, borrow, location, local,
+                ) {
+                    Some(p) => match &mir.local_decls[local].name {
+                        Some(local_name) => {
                             err.span_label(
                                 mir.source_info(p).span,
-                                format!("borrow later used here"),
+                                format!("borrow later used here, when `{}` is dropped", local_name),
                             );
-                        }
 
+                            if let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place {
+                                if let Place::Local(borrowed_local) = place {
+                                    let dropped_local_scope =
+                                        mir.local_decls[local].visibility_scope;
+                                    let borrowed_local_scope =
+                                        mir.local_decls[*borrowed_local].visibility_scope;
+
+                                    if mir.is_sub_scope(borrowed_local_scope, dropped_local_scope) {
+                                        err.note(
+                                            "values in a scope are dropped \
+                                             in the opposite order they are defined",
+                                        );
+                                    }
+                                }
+                            }
+                        }
                         None => {
-                            span_bug!(
-                                mir.source_info(context.loc).span,
-                                "Cause should end in a LiveVar"
+                            err.span_label(
+                                mir.local_decls[local].source_info.span,
+                                "borrow may end up in a temporary, created here",
                             );
-                        }
-                    }
-                }
 
-                Cause::DropVar(local, location) => {
-                    match find_drop_use(mir, regioncx, borrow, location, local) {
-                        Some(p) => match &mir.local_decls[local].name {
-                            Some(local_name) => {
-                                err.span_label(
-                                    mir.source_info(p).span,
-                                    format!(
-                                        "borrow later used here, when `{}` is dropped",
-                                        local_name
-                                    ),
-                                );
-                            }
-                            None => {
-                                err.span_label(
-                                    mir.local_decls[local].source_info.span,
-                                    "borrow may end up in a temporary, created here",
-                                );
-
-                                err.span_label(
-                                    mir.source_info(p).span,
-                                    "temporary later dropped here, \
-                                     potentially using the reference",
-                                );
-                            }
-                        },
-
-                        None => {
-                            span_bug!(
-                                mir.source_info(context.loc).span,
-                                "Cause should end in a DropVar"
+                            err.span_label(
+                                mir.source_info(p).span,
+                                "temporary later dropped here, \
+                                 potentially using the reference",
                             );
                         }
+                    },
+
+                    None => {
+                        span_bug!(
+                            mir.source_info(context.loc).span,
+                            "Cause should end in a DropVar"
+                        );
                     }
-                }
+                },
 
                 Cause::UniversalRegion(region_vid) => {
                     if let Some(region) = regioncx.to_error_region(region_vid) {
@@ -185,15 +205,12 @@ fn find(&mut self) -> Option<Location> {
                         ..p
                     });
                 } else {
-                    stack.extend(
-                        block_data
-                            .terminator()
-                            .successors()
-                            .map(|&basic_block| Location {
-                                statement_index: 0,
-                                block: basic_block,
-                            }),
-                    );
+                    stack.extend(block_data.terminator().successors().map(|&basic_block| {
+                        Location {
+                            statement_index: 0,
+                            block: basic_block,
+                        }
+                    }));
                 }
             }
         }
index 4871d427d0767bc7bc6ebd2caddbb4ce8210f703..b692ffbb250c70b0586c017e3cc73bff5dced6c7 100644 (file)
@@ -21,6 +21,7 @@
 use rustc::mir::{Projection, ProjectionElem, BorrowKind};
 use rustc::ty::{self, TyCtxt};
 use rustc_data_structures::control_flow_graph::dominators::Dominators;
+use rustc_data_structures::small_vec::SmallVec;
 use std::iter;
 
 pub(super) fn allow_two_phase_borrow<'a, 'tcx, 'gcx: 'tcx>(
@@ -259,8 +260,8 @@ pub(super) fn places_conflict<'a, 'gcx: 'tcx, 'tcx>(
 
 /// Return all the prefixes of `place` in reverse order, including
 /// downcasts.
-fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> Vec<&'a Place<'tcx>> {
-    let mut result = vec![];
+fn place_elements<'a, 'tcx>(place: &'a Place<'tcx>) -> SmallVec<[&'a Place<'tcx>; 8]> {
+    let mut result = SmallVec::new();
     let mut place = place;
     loop {
         result.push(place);
diff --git a/src/librustc_mir/borrow_check/used_muts.rs b/src/librustc_mir/borrow_check/used_muts.rs
new file mode 100644 (file)
index 0000000..dbe19bc
--- /dev/null
@@ -0,0 +1,64 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use rustc::mir::visit::{PlaceContext, Visitor};
+use rustc::mir::{Local, Location, Place};
+
+use rustc_data_structures::fx::FxHashSet;
+
+use borrow_check::MirBorrowckCtxt;
+use util::collect_writes::is_place_assignment;
+
+impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
+    /// Walks the MIR looking for assignments to a set of locals, as part of the unused mutable
+    /// local variables lint, to update the context's `used_mut` in a single walk.
+    crate fn gather_used_muts(&mut self, locals: FxHashSet<Local>) {
+        let mut visitor = GatherUsedMutsVisitor {
+            needles: locals,
+            mbcx: self,
+        };
+        visitor.visit_mir(visitor.mbcx.mir);
+    }
+}
+
+/// MIR visitor gathering the assignments to a set of locals, in a single walk.
+/// 'visit = the duration of the MIR walk
+struct GatherUsedMutsVisitor<'visit, 'cx: 'visit, 'gcx: 'tcx, 'tcx: 'cx> {
+    needles: FxHashSet<Local>,
+    mbcx: &'visit mut MirBorrowckCtxt<'cx, 'gcx, 'tcx>,
+}
+
+impl<'visit, 'cx, 'gcx, 'tcx> Visitor<'tcx> for GatherUsedMutsVisitor<'visit, 'cx, 'gcx, 'tcx> {
+    fn visit_local(
+        &mut self,
+        local: &Local,
+        place_context: PlaceContext<'tcx>,
+        location: Location,
+    ) {
+        if !self.needles.contains(local) {
+            return;
+        }
+
+        if is_place_assignment(&place_context) {
+            // Propagate the Local assigned at this Location as a used mutable local variable
+            for moi in &self.mbcx.move_data.loc_map[location] {
+                let mpi = &self.mbcx.move_data.moves[*moi].path;
+                let path = &self.mbcx.move_data.move_paths[*mpi];
+                debug!(
+                    "assignment of {:?} to {:?}, adding {:?} to used mutable set",
+                    path.place, local, path.place
+                );
+                if let Place::Local(user_local) = path.place {
+                    self.mbcx.used_mut.insert(user_local);
+                }
+            }
+        }
+    }
+}
index 7096f91dc1ddb0751402e9f72f7588a08bf7fb3c..0fd55f752b84f38869e97b2e9da370ce62111226 100644 (file)
@@ -137,7 +137,7 @@ fn ast_block_stmts(&mut self,
                             }
                         }
 
-                        this.visit_bindings(&pattern, &mut |this, _, _, node, span, _| {
+                        this.visit_bindings(&pattern, &mut |this, _, _, _, node, span, _| {
                             this.storage_live_binding(block, node, span, OutsideGuard);
                             this.schedule_drop_for_binding(node, span, OutsideGuard);
                         })
index fbd771fbe500d7eb8fab1b18401ad1873a271d2a..94b387abe3c13e7d06ed13f103acc0ef1bda7c35 100644 (file)
@@ -249,7 +249,7 @@ pub fn into_expr(&mut self,
                         source_info,
                         visibility_scope: source_info.scope,
                         internal: true,
-                        is_user_variable: false
+                        is_user_variable: None,
                     });
                     let ptr_temp = Place::Local(ptr_temp);
                     let block = unpack!(this.into(&ptr_temp, block, ptr));
index 062a48a8c434d02e5029eedadb1cb1705ab884af..b6af0ed2a4a1c448ebdf65d964a2ecc9fd3b80a9 100644 (file)
@@ -307,7 +307,7 @@ pub fn declare_bindings(&mut self,
         assert!(!(visibility_scope.is_some() && lint_level.is_explicit()),
                 "can't have both a visibility and a lint scope at the same time");
         let mut scope = self.source_scope;
-        self.visit_bindings(pattern, &mut |this, mutability, name, var, span, ty| {
+        self.visit_bindings(pattern, &mut |this, mutability, name, mode, var, span, ty| {
             if visibility_scope.is_none() {
                 visibility_scope = Some(this.new_source_scope(scope_span,
                                                            LintLevel::Inherited,
@@ -325,7 +325,7 @@ pub fn declare_bindings(&mut self,
                 scope,
             };
             let visibility_scope = visibility_scope.unwrap();
-            this.declare_binding(source_info, visibility_scope, mutability, name, var,
+            this.declare_binding(source_info, visibility_scope, mutability, name, mode, var,
                                  ty, has_guard);
         });
         visibility_scope
@@ -359,11 +359,11 @@ pub fn schedule_drop_for_binding(&mut self,
     }
 
     pub fn visit_bindings<F>(&mut self, pattern: &Pattern<'tcx>, f: &mut F)
-        where F: FnMut(&mut Self, Mutability, Name, NodeId, Span, Ty<'tcx>)
+        where F: FnMut(&mut Self, Mutability, Name, BindingMode, NodeId, Span, Ty<'tcx>)
     {
         match *pattern.kind {
-            PatternKind::Binding { mutability, name, var, ty, ref subpattern, .. } => {
-                f(self, mutability, name, var, pattern.span, ty);
+            PatternKind::Binding { mutability, name, mode, var, ty, ref subpattern, .. } => {
+                f(self, mutability, name, mode, var, pattern.span, ty);
                 if let Some(subpattern) = subpattern.as_ref() {
                     self.visit_bindings(subpattern, f);
                 }
@@ -1118,15 +1118,20 @@ fn declare_binding(&mut self,
                        visibility_scope: SourceScope,
                        mutability: Mutability,
                        name: Name,
+                       mode: BindingMode,
                        var_id: NodeId,
                        var_ty: Ty<'tcx>,
                        has_guard: ArmHasGuard)
     {
-        debug!("declare_binding(var_id={:?}, name={:?}, var_ty={:?}, visibility_scope={:?}, \
-                source_info={:?})",
-               var_id, name, var_ty, visibility_scope, source_info);
+        debug!("declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
+                visibility_scope={:?}, source_info={:?})",
+               var_id, name, mode, var_ty, visibility_scope, source_info);
 
         let tcx = self.hir.tcx();
+        let binding_mode = match mode {
+            BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
+            BindingMode::ByRef { .. } => ty::BindingMode::BindByReference(mutability.into()),
+        };
         let local = LocalDecl::<'tcx> {
             mutability,
             ty: var_ty.clone(),
@@ -1134,7 +1139,14 @@ fn declare_binding(&mut self,
             source_info,
             visibility_scope,
             internal: false,
-            is_user_variable: true,
+            is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
+                binding_mode,
+                // hypothetically, `visit_bindings` could try to unzip
+                // an outermost hir::Ty as we descend, matching up
+                // idents in pat; but complex w/ unclear UI payoff.
+                // Instead, just abandon providing diagnostic info.
+                opt_ty_info: None,
+            }))),
         };
         let for_arm_body = self.local_decls.push(local.clone());
         let locals = if has_guard.0 && tcx.all_pat_vars_are_implicit_refs_within_guards() {
@@ -1145,8 +1157,9 @@ fn declare_binding(&mut self,
                 name: Some(name),
                 source_info,
                 visibility_scope,
+                // FIXME: should these secretly injected ref_for_guard's be marked as `internal`?
                 internal: false,
-                is_user_variable: true,
+                is_user_variable: None,
             });
             LocalsForNode::Three { val_for_guard, ref_for_guard, for_arm_body }
         } else {
index ca7a2daf39d2ecb9bef31b465c8710bc89aa3ec6..85671414618038781c9e4c2f81dcedf885e2112a 100644 (file)
@@ -70,11 +70,11 @@ pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'t
                     // HACK(eddyb) Avoid having RustCall on closures,
                     // as it adds unnecessary (and wrong) auto-tupling.
                     abi = Abi::Rust;
-                    Some((liberated_closure_env_ty(tcx, id, body_id), None))
+                    Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
                 }
                 ty::TyGenerator(..) => {
                     let gen_ty = tcx.body_tables(body_id).node_id_to_type(fn_hir_id);
-                    Some((gen_ty, None))
+                    Some(ArgInfo(gen_ty, None, None, None))
                 }
                 _ => None,
             };
@@ -91,7 +91,23 @@ pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'t
                     .iter()
                     .enumerate()
                     .map(|(index, arg)| {
-                        (fn_sig.inputs()[index], Some(&*arg.pat))
+                        let owner_id = tcx.hir.body_owner(body_id);
+                        let opt_ty_info;
+                        let self_arg;
+                        if let Some(ref fn_decl) = tcx.hir.fn_decl(owner_id) {
+                            let ty_hir_id = fn_decl.inputs[index].hir_id;
+                            let ty_span = tcx.hir.span(tcx.hir.hir_to_node_id(ty_hir_id));
+                            opt_ty_info = Some(ty_span);
+                            self_arg = if index == 0 && fn_decl.has_implicit_self {
+                                Some(ImplicitSelfBinding)
+                            } else {
+                                None
+                            };
+                        } else {
+                            opt_ty_info = None;
+                            self_arg = None;
+                        }
+                        ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
                     });
 
             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
@@ -433,6 +449,13 @@ fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
 ///////////////////////////////////////////////////////////////////////////
 /// the main entry point for building MIR for a function
 
+struct ImplicitSelfBinding;
+
+struct ArgInfo<'gcx>(Ty<'gcx>,
+                     Option<Span>,
+                     Option<&'gcx hir::Pat>,
+                     Option<ImplicitSelfBinding>);
+
 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
                                    fn_id: ast::NodeId,
                                    arguments: A,
@@ -442,7 +465,7 @@ fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
                                    yield_ty: Option<Ty<'gcx>>,
                                    body: &'gcx hir::Body)
                                    -> Mir<'tcx>
-    where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
+    where A: Iterator<Item=ArgInfo<'gcx>>
 {
     let arguments: Vec<_> = arguments.collect();
 
@@ -642,13 +665,13 @@ fn finish(self,
 
     fn args_and_body(&mut self,
                      mut block: BasicBlock,
-                     arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
+                     arguments: &[ArgInfo<'gcx>],
                      argument_scope: region::Scope,
                      ast_body: &'gcx hir::Expr)
                      -> BlockAnd<()>
     {
         // Allocate locals for the function arguments
-        for &(ty, pattern) in arguments.iter() {
+        for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
             // If this is a simple binding pattern, give the local a nice name for debuginfo.
             let mut name = None;
             if let Some(pat) = pattern {
@@ -668,16 +691,17 @@ fn args_and_body(&mut self,
                 visibility_scope: source_info.scope,
                 name,
                 internal: false,
-                is_user_variable: false,
+                is_user_variable: None,
             });
         }
 
         let mut scope = None;
         // Bind the argument patterns
-        for (index, &(ty, pattern)) in arguments.iter().enumerate() {
+        for (index, arg_info) in arguments.iter().enumerate() {
             // Function arguments always get the first Local indices after the return place
             let local = Local::new(index + 1);
             let place = Place::Local(local);
+            let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
 
             if let Some(pattern) = pattern {
                 let pattern = self.hir.pattern_from_hir(pattern);
@@ -686,6 +710,14 @@ fn args_and_body(&mut self,
                     // Don't introduce extra copies for simple bindings
                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
                         self.local_decls[local].mutability = mutability;
+                        self.local_decls[local].is_user_variable =
+                            if let Some(ImplicitSelfBinding) = self_binding {
+                                Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf))
+                            } else {
+                                let binding_mode = ty::BindingMode::BindByValue(mutability.into());
+                                Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
+                                    binding_mode, opt_ty_info })))
+                            };
                         self.var_indices.insert(var, LocalsForNode::One(local));
                     }
                     _ => {
index 0fbb54e8e0a089abb88178c82b1b9b3cf4b58343..a89d1afae8637bc25e89d876c03365f2b45dfccc 100644 (file)
@@ -204,10 +204,22 @@ impl<'tcx, T> FlowAtLocation<T>
     T: HasMoveData<'tcx> + BitDenotation<Idx = MovePathIndex>,
 {
     pub fn has_any_child_of(&self, mpi: T::Idx) -> Option<T::Idx> {
+        // We process `mpi` before the loop below, for two reasons:
+        // - it's a little different from the loop case (we don't traverse its
+        //   siblings);
+        // - ~99% of the time the loop isn't reached, and this code is hot, so
+        //   we don't want to allocate `todo` unnecessarily.
+        if self.contains(&mpi) {
+            return Some(mpi);
+        }
         let move_data = self.operator().move_data();
+        let move_path = &move_data.move_paths[mpi];
+        let mut todo = if let Some(child) = move_path.first_child {
+            vec![child]
+        } else {
+            return None;
+        };
 
-        let mut todo = vec![mpi];
-        let mut push_siblings = false; // don't look at siblings of original `mpi`.
         while let Some(mpi) = todo.pop() {
             if self.contains(&mpi) {
                 return Some(mpi);
@@ -216,15 +228,10 @@ pub fn has_any_child_of(&self, mpi: T::Idx) -> Option<T::Idx> {
             if let Some(child) = move_path.first_child {
                 todo.push(child);
             }
-            if push_siblings {
-                if let Some(sibling) = move_path.next_sibling {
-                    todo.push(sibling);
-                }
-            } else {
-                // after we've processed the original `mpi`, we should
-                // always traverse the siblings of any of its
-                // children.
-                push_siblings = true;
+            // After we've processed the original `mpi`, we should always
+            // traverse the siblings of any of its children.
+            if let Some(sibling) = move_path.next_sibling {
+                todo.push(sibling);
             }
         }
         return None;
index 7cef8a75aa6baf90d881b038c6a06ca43a55baba..2c58bd8e79b08ac7d4de1c7d4fb3c71577de9d83 100644 (file)
@@ -295,7 +295,7 @@ fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
             );
             let label_msg = match pat.node {
                 PatKind::Path(hir::QPath::Resolved(None, ref path))
-                        if path.segments.len() == 1 && path.segments[0].parameters.is_none() => {
+                        if path.segments.len() == 1 && path.segments[0].args.is_none() => {
                     format!("interpreted as a {} pattern, not new variable", path.def.kind_name())
                 }
                 _ => format!("pattern `{}` not covered", pattern_string),
index 96aeb969d89f96eb20f367b49609748498373db2..ef69cb574e07e6b70571899b23b92ba1f72dfc16 100644 (file)
@@ -1099,14 +1099,12 @@ fn create_mono_items_for_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                  item: &'tcx hir::Item,
                                                  output: &mut Vec<MonoItem<'tcx>>) {
     match item.node {
-        hir::ItemImpl(_,
-                      _,
-                      _,
-                      ref generics,
-                      ..,
-                      ref impl_item_refs) => {
-            if generics.is_type_parameterized() {
-                return
+        hir::ItemImpl(_, _, _, ref generics, .., ref impl_item_refs) => {
+            for param in &generics.params {
+                match param.kind {
+                    hir::GenericParamKind::Lifetime { .. } => {}
+                    hir::GenericParamKind::Type { .. } => return,
+                }
             }
 
             let impl_def_id = tcx.hir.local_def_id(item.id);
index f11d80201c28b4653351704eb6ee4216c4668e10..c703486560dcd204b3dd51000e853eedf4654365 100644 (file)
@@ -144,7 +144,7 @@ fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
         source_info,
         visibility_scope: source_info.scope,
         internal: false,
-        is_user_variable: false
+        is_user_variable: None,
     }
 }
 
index 7ac3b7beb06d5358dc797eda9763208e3bc5d11a..a6017fafcc8d4621cbe87204329c084cbc9b76e3 100644 (file)
@@ -303,7 +303,7 @@ fn replace_result_variable<'tcx>(ret_ty: Ty<'tcx>,
         source_info,
         visibility_scope: source_info.scope,
         internal: false,
-        is_user_variable: false,
+        is_user_variable: None,
     };
     let new_ret_local = Local::new(mir.local_decls.len());
     mir.local_decls.push(new_ret);
@@ -644,7 +644,7 @@ fn create_generator_drop_shim<'a, 'tcx>(
         source_info,
         visibility_scope: source_info.scope,
         internal: false,
-        is_user_variable: false,
+        is_user_variable: None,
     };
 
     make_generator_state_argument_indirect(tcx, def_id, &mut mir);
@@ -660,7 +660,7 @@ fn create_generator_drop_shim<'a, 'tcx>(
         source_info,
         visibility_scope: source_info.scope,
         internal: false,
-        is_user_variable: false,
+        is_user_variable: None,
     };
 
     no_landing_pads(tcx, &mut mir);
index f04f9233447c3d83761a34836fa913182de3aa0c..23f753f8569bb780170cb0118e6c61a453106f48 100644 (file)
@@ -43,25 +43,24 @@ fn visit_local(&mut self,
             return;
         }
 
-        match place_context {
-            PlaceContext::Store | PlaceContext::Call => {
-                self.locations.push(location);
-            }
-            PlaceContext::AsmOutput |
-            PlaceContext::Drop |
-            PlaceContext::Inspect |
-            PlaceContext::Borrow { .. } |
-            PlaceContext::Projection(..) |
-            PlaceContext::Copy |
-            PlaceContext::Move |
-            PlaceContext::StorageLive |
-            PlaceContext::StorageDead |
-            PlaceContext::Validate => {
-                // TO-DO
-                // self.super_local(local)
-            }
+        if is_place_assignment(&place_context) {
+            self.locations.push(location);
         }
     }
-    // TO-DO
-    // fn super_local()
+}
+
+/// Returns true if this place context represents an assignment statement
+crate fn is_place_assignment(place_context: &PlaceContext) -> bool {
+    match *place_context {
+        PlaceContext::Store | PlaceContext::Call | PlaceContext::AsmOutput => true,
+        PlaceContext::Drop
+        | PlaceContext::Inspect
+        | PlaceContext::Borrow { .. }
+        | PlaceContext::Projection(..)
+        | PlaceContext::Copy
+        | PlaceContext::Move
+        | PlaceContext::StorageLive
+        | PlaceContext::StorageDead
+        | PlaceContext::Validate => false,
+    }
 }
index 39e0a5392580b26349dea251d897dac2f6bf6220..fc54d323b0f9600726d930b4203415067ea23548 100644 (file)
@@ -99,9 +99,9 @@ fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
         }
     }
 
-    fn no_questions_in_bounds(&self, bounds: &TyParamBounds, where_: &str, is_trait: bool) {
+    fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
         for bound in bounds {
-            if let TraitTyParamBound(ref poly, TraitBoundModifier::Maybe) = *bound {
+            if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
                 let mut err = self.err_handler().struct_span_err(poly.span,
                                     &format!("`?Trait` is not permitted in {}", where_));
                 if is_trait {
@@ -139,29 +139,22 @@ fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
     }
 
     fn check_late_bound_lifetime_defs(&self, params: &Vec<GenericParam>) {
-        // Check: Only lifetime parameters
-        let non_lifetime_param_spans : Vec<_> = params.iter()
-            .filter_map(|param| match *param {
-                GenericParam::Lifetime(_) => None,
-                GenericParam::Type(ref t) => Some(t.ident.span),
-            }).collect();
-        if !non_lifetime_param_spans.is_empty() {
-            self.err_handler().span_err(non_lifetime_param_spans,
-                "only lifetime parameters can be used in this context");
-        }
-
-        // Check: No bounds on lifetime parameters
-        for param in params.iter() {
-            match *param {
-                GenericParam::Lifetime(ref l) => {
-                    if !l.bounds.is_empty() {
-                        let spans: Vec<_> = l.bounds.iter().map(|b| b.ident.span).collect();
-                        self.err_handler().span_err(spans,
-                            "lifetime bounds cannot be used in this context");
+        // Check only lifetime parameters are present and that the lifetime
+        // parameters that are present have no bounds.
+        let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
+                GenericParamKind::Lifetime { .. } => {
+                    if !param.bounds.is_empty() {
+                        let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
+                        self.err_handler()
+                            .span_err(spans, "lifetime bounds cannot be used in this context");
                     }
+                    None
                 }
-                GenericParam::Type(_) => {}
-            }
+                _ => Some(param.ident.span),
+            }).collect();
+        if !non_lt_param_spans.is_empty() {
+            self.err_handler().span_err(non_lt_param_spans,
+                "only lifetime parameters can be used in this context");
         }
     }
 }
@@ -197,7 +190,7 @@ fn visit_ty(&mut self, ty: &'a Ty) {
             TyKind::TraitObject(ref bounds, ..) => {
                 let mut any_lifetime_bounds = false;
                 for bound in bounds {
-                    if let RegionTyParamBound(ref lifetime) = *bound {
+                    if let GenericBound::Outlives(ref lifetime) = *bound {
                         if any_lifetime_bounds {
                             span_err!(self.session, lifetime.ident.span, E0226,
                                       "only a single explicit lifetime bound is permitted");
@@ -210,7 +203,7 @@ fn visit_ty(&mut self, ty: &'a Ty) {
             }
             TyKind::ImplTrait(ref bounds) => {
                 if !bounds.iter()
-                          .any(|b| if let TraitTyParamBound(..) = *b { true } else { false }) {
+                          .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
                 }
             }
@@ -230,9 +223,9 @@ fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
         // }
         // foo!(bar::baz<T>);
         use_tree.prefix.segments.iter().find(|segment| {
-            segment.parameters.is_some()
+            segment.args.is_some()
         }).map(|segment| {
-            self.err_handler().span_err(segment.parameters.as_ref().unwrap().span(),
+            self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
                                         "generic arguments in import path");
         });
 
@@ -300,7 +293,7 @@ fn visit_item(&mut self, item: &'a Item) {
             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
                 if is_auto == IsAuto::Yes {
                     // Auto traits cannot have generics, super traits nor contain items.
-                    if generics.is_parameterized() {
+                    if !generics.params.is_empty() {
                         struct_span_err!(self.session, item.span, E0567,
                                         "auto traits cannot have generic parameters").emit();
                     }
@@ -335,22 +328,19 @@ fn visit_item(&mut self, item: &'a Item) {
             }
             ItemKind::TraitAlias(Generics { ref params, .. }, ..) => {
                 for param in params {
-                    if let GenericParam::Type(TyParam {
-                        ident,
-                        ref bounds,
-                        ref default,
-                        ..
-                    }) = *param
-                    {
-                        if !bounds.is_empty() {
-                            self.err_handler().span_err(ident.span,
-                                                        "type parameters on the left side of a \
-                                                         trait alias cannot be bounded");
-                        }
-                        if !default.is_none() {
-                            self.err_handler().span_err(ident.span,
-                                                        "type parameters on the left side of a \
-                                                         trait alias cannot have defaults");
+                    match param.kind {
+                        GenericParamKind::Lifetime { .. } => {}
+                        GenericParamKind::Type { ref default, .. } => {
+                            if !param.bounds.is_empty() {
+                                self.err_handler()
+                                    .span_err(param.ident.span, "type parameters on the left \
+                                        side of a trait alias cannot be bounded");
+                            }
+                            if !default.is_none() {
+                                self.err_handler()
+                                    .span_err(param.ident.span, "type parameters on the left \
+                                        side of a trait alias cannot have defaults");
+                            }
                         }
                     }
                 }
@@ -398,8 +388,8 @@ fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
     fn visit_vis(&mut self, vis: &'a Visibility) {
         match vis.node {
             VisibilityKind::Restricted { ref path, .. } => {
-                path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| {
-                    self.err_handler().span_err(segment.parameters.as_ref().unwrap().span(),
+                path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
+                    self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
                                                 "generic arguments in visibility path");
                 });
             }
@@ -409,41 +399,40 @@ fn visit_vis(&mut self, vis: &'a Visibility) {
         visit::walk_vis(self, vis)
     }
 
-    fn visit_generics(&mut self, g: &'a Generics) {
+    fn visit_generics(&mut self, generics: &'a Generics) {
         let mut seen_non_lifetime_param = false;
         let mut seen_default = None;
-        for param in &g.params {
-            match (param, seen_non_lifetime_param) {
-                (&GenericParam::Lifetime(ref ld), true) => {
+        for param in &generics.params {
+            match (&param.kind, seen_non_lifetime_param) {
+                (GenericParamKind::Lifetime { .. }, true) => {
                     self.err_handler()
-                        .span_err(ld.lifetime.ident.span, "lifetime parameters must be leading");
+                        .span_err(param.ident.span, "lifetime parameters must be leading");
                 },
-                (&GenericParam::Lifetime(_), false) => {}
-                _ => {
+                (GenericParamKind::Lifetime { .. }, false) => {}
+                (GenericParamKind::Type { ref default, .. }, _) => {
                     seen_non_lifetime_param = true;
+                    if default.is_some() {
+                        seen_default = Some(param.ident.span);
+                    } else if let Some(span) = seen_default {
+                        self.err_handler()
+                            .span_err(span, "type parameters with a default must be trailing");
+                        break;
+                    }
                 }
             }
-
-            if let GenericParam::Type(ref ty_param @ TyParam { default: Some(_), .. }) = *param {
-                seen_default = Some(ty_param.ident.span);
-            } else if let Some(span) = seen_default {
-                self.err_handler()
-                    .span_err(span, "type parameters with a default must be trailing");
-                break
-            }
         }
-        for predicate in &g.where_clause.predicates {
+        for predicate in &generics.where_clause.predicates {
             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
                 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
                                                              supported in where clauses (#20041)");
             }
         }
-        visit::walk_generics(self, g)
+        visit::walk_generics(self, generics)
     }
 
     fn visit_generic_param(&mut self, param: &'a GenericParam) {
-        if let GenericParam::Lifetime(ref ld) = *param {
-            self.check_lifetime(ld.lifetime.ident);
+        if let GenericParamKind::Lifetime { .. } = param.kind {
+            self.check_lifetime(param.ident);
         }
         visit::walk_generic_param(self, param);
     }
@@ -521,23 +510,24 @@ fn visit_ty(&mut self, t: &'a Ty) {
             visit::walk_ty(self, t);
         }
     }
-    fn visit_path_parameters(&mut self, _: Span, path_parameters: &'a PathParameters) {
-        match *path_parameters {
-            PathParameters::AngleBracketed(ref params) => {
-                for type_ in &params.types {
-                    self.visit_ty(type_);
-                }
-                for type_binding in &params.bindings {
+    fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
+        match *generic_args {
+            GenericArgs::AngleBracketed(ref data) => {
+                data.args.iter().for_each(|arg| match arg {
+                    GenericArg::Type(ty) => self.visit_ty(ty),
+                    _ => {}
+                });
+                for type_binding in &data.bindings {
                     // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
                     // are allowed to contain nested `impl Trait`.
                     self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
                 }
             }
-            PathParameters::Parenthesized(ref params) => {
-                for type_ in &params.inputs {
+            GenericArgs::Parenthesized(ref data) => {
+                for type_ in &data.inputs {
                     self.visit_ty(type_);
                 }
-                if let Some(ref type_) = params.output {
+                if let Some(ref type_) = data.output {
                     // `-> Foo` syntax is essentially an associated type binding,
                     // so it is also allowed to contain nested `impl Trait`.
                     self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
@@ -590,7 +580,7 @@ fn visit_ty(&mut self, t: &'a Ty) {
                 //
                 // To implement this, we disallow `impl Trait` from `qself`
                 // (for cases like `<impl Trait>::Foo>`)
-                // but we allow `impl Trait` in `PathParameters`
+                // but we allow `impl Trait` in `GenericArgs`
                 // iff there are no more PathSegments.
                 if let Some(ref qself) = *qself {
                     // `impl Trait` in `qself` is always illegal
index ba0be974b2771997292c2df43b29614aeaac7ef0..e7b2869dfe61eaaea68c0f03df8350a07f7c9c5e 100644 (file)
@@ -203,9 +203,9 @@ fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
         hir_visit::walk_impl_item(self, ii)
     }
 
-    fn visit_ty_param_bound(&mut self, bounds: &'v hir::TyParamBound) {
-        self.record("TyParamBound", Id::None, bounds);
-        hir_visit::walk_ty_param_bound(self, bounds)
+    fn visit_param_bound(&mut self, bounds: &'v hir::GenericBound) {
+        self.record("GenericBound", Id::None, bounds);
+        hir_visit::walk_param_bound(self, bounds)
     }
 
     fn visit_struct_field(&mut self, s: &'v hir::StructField) {
@@ -322,9 +322,9 @@ fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
         ast_visit::walk_impl_item(self, ii)
     }
 
-    fn visit_ty_param_bound(&mut self, bounds: &'v ast::TyParamBound) {
-        self.record("TyParamBound", Id::None, bounds);
-        ast_visit::walk_ty_param_bound(self, bounds)
+    fn visit_param_bound(&mut self, bounds: &'v ast::GenericBound) {
+        self.record("GenericBound", Id::None, bounds);
+        ast_visit::walk_param_bound(self, bounds)
     }
 
     fn visit_struct_field(&mut self, s: &'v ast::StructField) {
index 291092015b57f06c208538d7d52b66c22985680b..de087049267b1f1ed82a4db643497692355a3061 100644 (file)
@@ -22,7 +22,7 @@
 extern crate syntax_pos;
 extern crate rustc_data_structures;
 
-use rustc::hir::{self, PatKind};
+use rustc::hir::{self, GenericParamKind, PatKind};
 use rustc::hir::def::Def;
 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId};
 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
@@ -1037,9 +1037,8 @@ fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
         self.access_levels.is_public(trait_id)
     }
 
-    fn check_ty_param_bound(&mut self,
-                            ty_param_bound: &hir::TyParamBound) {
-        if let hir::TraitTyParamBound(ref trait_ref, _) = *ty_param_bound {
+    fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
+        if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
             if self.path_is_private_type(&trait_ref.trait_ref.path) {
                 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
             }
@@ -1101,7 +1100,7 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
                 }
 
                 for bound in bounds.iter() {
-                    self.check_ty_param_bound(bound)
+                    self.check_generic_bound(bound)
                 }
             }
 
@@ -1268,16 +1267,19 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
     }
 
     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
-        for ty_param in generics.ty_params() {
-            for bound in ty_param.bounds.iter() {
-                self.check_ty_param_bound(bound)
+        generics.params.iter().for_each(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => {}
+            GenericParamKind::Type { .. } => {
+                for bound in &param.bounds {
+                    self.check_generic_bound(bound);
+                }
             }
-        }
+        });
         for predicate in &generics.where_clause.predicates {
             match predicate {
                 &hir::WherePredicate::BoundPredicate(ref bound_pred) => {
                     for bound in bound_pred.bounds.iter() {
-                        self.check_ty_param_bound(bound)
+                        self.check_generic_bound(bound)
                     }
                 }
                 &hir::WherePredicate::RegionPredicate(_) => {}
index a2b2096ccaa47aa01cf39bfa5587ea91556cfce3..e311701ac0589722ecc7a435d79e6ad39a49112e 100644 (file)
@@ -56,7 +56,7 @@
 use syntax::visit::{self, FnKind, Visitor};
 use syntax::attr;
 use syntax::ast::{Arm, BindingMode, Block, Crate, Expr, ExprKind};
-use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParam, Generics};
+use syntax::ast::{FnDecl, ForeignItem, ForeignItemKind, GenericParamKind, Generics};
 use syntax::ast::{Item, ItemKind, ImplItem, ImplItemKind};
 use syntax::ast::{Label, Local, Mutability, Pat, PatKind, Path};
 use syntax::ast::{QSelf, TraitItemKind, TraitRef, Ty, TyKind};
@@ -797,31 +797,41 @@ fn visit_generics(&mut self, generics: &'tcx Generics) {
         // put all the parameters on the ban list and then remove
         // them one by one as they are processed and become available.
         let mut default_ban_rib = Rib::new(ForwardTyParamBanRibKind);
+        let mut found_default = false;
         default_ban_rib.bindings.extend(generics.params.iter()
-            .filter_map(|p| if let GenericParam::Type(ref tp) = *p { Some(tp) } else { None })
-            .skip_while(|p| p.default.is_none())
-            .map(|p| (Ident::with_empty_ctxt(p.ident.name), Def::Err)));
+            .filter_map(|param| match param.kind {
+                GenericParamKind::Lifetime { .. } => None,
+                GenericParamKind::Type { ref default, .. } => {
+                    if found_default || default.is_some() {
+                        found_default = true;
+                        return Some((Ident::with_empty_ctxt(param.ident.name), Def::Err));
+                    }
+                    None
+                }
+            }));
 
         for param in &generics.params {
-            match *param {
-                GenericParam::Lifetime(_) => self.visit_generic_param(param),
-                GenericParam::Type(ref ty_param) => {
-                    for bound in &ty_param.bounds {
-                        self.visit_ty_param_bound(bound);
+            match param.kind {
+                GenericParamKind::Lifetime { .. } => self.visit_generic_param(param),
+                GenericParamKind::Type { ref default, .. } => {
+                    for bound in &param.bounds {
+                        self.visit_param_bound(bound);
                     }
 
-                    if let Some(ref ty) = ty_param.default {
+                    if let Some(ref ty) = default {
                         self.ribs[TypeNS].push(default_ban_rib);
                         self.visit_ty(ty);
                         default_ban_rib = self.ribs[TypeNS].pop().unwrap();
                     }
 
                     // Allow all following defaults to refer to this type parameter.
-                    default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(ty_param.ident.name));
+                    default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
                 }
             }
         }
-        for p in &generics.where_clause.predicates { self.visit_where_predicate(p); }
+        for p in &generics.where_clause.predicates {
+            self.visit_where_predicate(p);
+        }
     }
 }
 
@@ -2066,7 +2076,7 @@ fn resolve_item(&mut self, item: &Item) {
                     let local_def_id = this.definitions.local_def_id(item.id);
                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
                         this.visit_generics(generics);
-                        walk_list!(this, visit_ty_param_bound, bounds);
+                        walk_list!(this, visit_param_bound, bounds);
 
                         for trait_item in trait_items {
                             this.check_proc_macro_attrs(&trait_item.attrs);
@@ -2109,7 +2119,7 @@ fn resolve_item(&mut self, item: &Item) {
                     let local_def_id = this.definitions.local_def_id(item.id);
                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
                         this.visit_generics(generics);
-                        walk_list!(this, visit_ty_param_bound, bounds);
+                        walk_list!(this, visit_param_bound, bounds);
                     });
                 });
             }
@@ -2197,10 +2207,11 @@ fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<
             HasTypeParameters(generics, rib_kind) => {
                 let mut function_type_rib = Rib::new(rib_kind);
                 let mut seen_bindings = FxHashMap();
-                for param in &generics.params {
-                    if let GenericParam::Type(ref type_parameter) = *param {
-                        let ident = type_parameter.ident.modern();
-                        debug!("with_type_parameter_rib: {}", type_parameter.id);
+                generics.params.iter().for_each(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => {}
+                    GenericParamKind::Type { .. } => {
+                        let ident = param.ident.modern();
+                        debug!("with_type_parameter_rib: {}", param.id);
 
                         if seen_bindings.contains_key(&ident) {
                             let span = seen_bindings.get(&ident).unwrap();
@@ -2208,17 +2219,16 @@ fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<
                                 ident.name,
                                 span,
                             );
-                            resolve_error(self, type_parameter.ident.span, err);
+                            resolve_error(self, param.ident.span, err);
                         }
-                        seen_bindings.entry(ident).or_insert(type_parameter.ident.span);
+                        seen_bindings.entry(ident).or_insert(param.ident.span);
 
-                        // plain insert (no renaming)
-                        let def_id = self.definitions.local_def_id(type_parameter.id);
-                        let def = Def::TyParam(def_id);
+                    // Plain insert (no renaming).
+                    let def = Def::TyParam(self.definitions.local_def_id(param.id));
                         function_type_rib.bindings.insert(ident, def);
-                        self.record_def(type_parameter.id, PathResolution::new(def));
+                        self.record_def(param.id, PathResolution::new(def));
                     }
-                }
+                });
                 self.ribs[TypeNS].push(function_type_rib);
             }
 
index de7a3dc5ceeb273f061bab2c5338a777a300b024..649e8858b0971b4b45a25690ed4fa74be2216ce3 100644 (file)
@@ -437,8 +437,8 @@ fn resolve_macro_to_def(&mut self, scope: Mark, path: &ast::Path, kind: MacroKin
         let def = self.resolve_macro_to_def_inner(scope, path, kind, force);
         if def != Err(Determinacy::Undetermined) {
             // Do not report duplicated errors on every undetermined resolution.
-            path.segments.iter().find(|segment| segment.parameters.is_some()).map(|segment| {
-                self.session.span_err(segment.parameters.as_ref().unwrap().span(),
+            path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
+                self.session.span_err(segment.args.as_ref().unwrap().span(),
                                       "generic arguments in macro path");
             });
         }
index 279ee403cc6258d5b6e702a6fa55986bd32569b7..7da5b1668b3d824585af1c0ecdc2afd7b35291c4 100644 (file)
@@ -370,35 +370,38 @@ fn process_generic_params(
         id: NodeId,
     ) {
         for param in &generics.params {
-            if let ast::GenericParam::Type(ref ty_param) = *param {
-                let param_ss = ty_param.ident.span;
-                let name = escape(self.span.snippet(param_ss));
-                // Append $id to name to make sure each one is unique
-                let qualname = format!("{}::{}${}", prefix, name, id);
-                if !self.span.filter_generated(Some(param_ss), full_span) {
-                    let id = ::id_from_node_id(ty_param.id, &self.save_ctxt);
-                    let span = self.span_from_span(param_ss);
+            match param.kind {
+                ast::GenericParamKind::Lifetime { .. } => {}
+                ast::GenericParamKind::Type { .. } => {
+                    let param_ss = param.ident.span;
+                    let name = escape(self.span.snippet(param_ss));
+                    // Append $id to name to make sure each one is unique.
+                    let qualname = format!("{}::{}${}", prefix, name, id);
+                    if !self.span.filter_generated(Some(param_ss), full_span) {
+                        let id = ::id_from_node_id(param.id, &self.save_ctxt);
+                        let span = self.span_from_span(param_ss);
 
-                    self.dumper.dump_def(
-                        &Access {
-                            public: false,
-                            reachable: false,
-                        },
-                        Def {
-                            kind: DefKind::Type,
-                            id,
-                            span,
-                            name,
-                            qualname,
-                            value: String::new(),
-                            parent: None,
-                            children: vec![],
-                            decl_id: None,
-                            docs: String::new(),
-                            sig: None,
-                            attributes: vec![],
-                        },
-                    );
+                        self.dumper.dump_def(
+                            &Access {
+                                public: false,
+                                reachable: false,
+                            },
+                            Def {
+                                kind: DefKind::Type,
+                                id,
+                                span,
+                                name,
+                                qualname,
+                                value: String::new(),
+                                parent: None,
+                                children: vec![],
+                                decl_id: None,
+                                docs: String::new(),
+                                sig: None,
+                                attributes: vec![],
+                            },
+                        );
+                    }
                 }
             }
         }
@@ -715,7 +718,7 @@ fn process_trait(
         &mut self,
         item: &'l ast::Item,
         generics: &'l ast::Generics,
-        trait_refs: &'l ast::TyParamBounds,
+        trait_refs: &'l ast::GenericBounds,
         methods: &'l [ast::TraitItem],
     ) {
         let name = item.ident.to_string();
@@ -758,10 +761,8 @@ fn process_trait(
         // super-traits
         for super_bound in trait_refs.iter() {
             let trait_ref = match *super_bound {
-                ast::TraitTyParamBound(ref trait_ref, _) => trait_ref,
-                ast::RegionTyParamBound(..) => {
-                    continue;
-                }
+                ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
+                ast::GenericBound::Outlives(..) => continue,
             };
 
             let trait_ref = &trait_ref.trait_ref;
@@ -818,14 +819,17 @@ fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
         }
         self.dump_path_ref(id, path);
 
-        // Type parameters
+        // Type arguments
         for seg in &path.segments {
-            if let Some(ref params) = seg.parameters {
-                match **params {
-                    ast::PathParameters::AngleBracketed(ref data) => for t in &data.types {
-                        self.visit_ty(t);
-                    },
-                    ast::PathParameters::Parenthesized(ref data) => {
+            if let Some(ref generic_args) = seg.args {
+                match **generic_args {
+                    ast::GenericArgs::AngleBracketed(ref data) => {
+                        data.args.iter().for_each(|arg| match arg {
+                            ast::GenericArg::Type(ty) => self.visit_ty(ty),
+                            _ => {}
+                        });
+                    }
+                    ast::GenericArgs::Parenthesized(ref data) => {
                         for t in &data.inputs {
                             self.visit_ty(t);
                         }
@@ -905,11 +909,12 @@ fn process_method_call(
         }
 
         // Explicit types in the turbo-fish.
-        if let Some(ref params) = seg.parameters {
-            if let ast::PathParameters::AngleBracketed(ref data) = **params {
-                for t in &data.types {
-                    self.visit_ty(t);
-                }
+        if let Some(ref generic_args) = seg.args {
+            if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
+                data.args.iter().for_each(|arg| match arg {
+                    ast::GenericArg::Type(ty) => self.visit_ty(ty),
+                    _ => {}
+                });
             }
         }
 
@@ -1478,18 +1483,19 @@ fn visit_item(&mut self, item: &'l ast::Item) {
     }
 
     fn visit_generics(&mut self, generics: &'l ast::Generics) {
-        for param in &generics.params {
-            if let ast::GenericParam::Type(ref ty_param) = *param {
-                for bound in ty_param.bounds.iter() {
-                    if let ast::TraitTyParamBound(ref trait_ref, _) = *bound {
+        generics.params.iter().for_each(|param| match param.kind {
+            ast::GenericParamKind::Lifetime { .. } => {}
+            ast::GenericParamKind::Type { ref default, .. } => {
+                for bound in &param.bounds {
+                    if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
                         self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
                     }
                 }
-                if let Some(ref ty) = ty_param.default {
+                if let Some(ref ty) = default {
                     self.visit_ty(&ty);
                 }
             }
-        }
+        });
     }
 
     fn visit_ty(&mut self, t: &'l ast::Ty) {
index f9510970e43d44edb2a753b8dbfd6f785c56a586..453500d5ab7bd4d6a8cfd010d8130cdad8581d5d 100644 (file)
@@ -692,8 +692,8 @@ fn fn_type(path: &ast::Path) -> bool {
             if path.segments.len() != 1 {
                 return false;
             }
-            if let Some(ref params) = path.segments[0].parameters {
-                if let ast::PathParameters::Parenthesized(_) = **params {
+            if let Some(ref generic_args) = path.segments[0].args {
+                if let ast::GenericArgs::Parenthesized(_) = **generic_args {
                     return true;
                 }
             }
@@ -934,10 +934,7 @@ fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
         sig.push_str(&generics
             .params
             .iter()
-            .map(|param| match *param {
-                ast::GenericParam::Lifetime(ref l) => l.lifetime.ident.name.to_string(),
-                ast::GenericParam::Type(ref t) => t.ident.to_string(),
-            })
+            .map(|param| param.ident.to_string())
             .collect::<Vec<_>>()
             .join(", "));
         sig.push_str("> ");
index e3545e8f1a9b8e2a931c7d99ea5cfa08449f46dc..7f2f0b0c83716ea6767e24237ced1c4d8a8c517e 100644 (file)
@@ -104,7 +104,7 @@ pub fn assoc_const_signature(
 pub fn assoc_type_signature(
     id: NodeId,
     ident: ast::Ident,
-    bounds: Option<&ast::TyParamBounds>,
+    bounds: Option<&ast::GenericBounds>,
     default: Option<&ast::Ty>,
     scx: &SaveContext,
 ) -> Option<Signature> {
@@ -223,9 +223,9 @@ fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) ->
                     text.push_str("for<");
                     text.push_str(&f.generic_params
                         .iter()
-                        .filter_map(|p| match *p {
-                            ast::GenericParam::Lifetime(ref l) => {
-                                Some(l.lifetime.ident.to_string())
+                        .filter_map(|param| match param.kind {
+                            ast::GenericParamKind::Lifetime { .. } => {
+                                Some(param.ident.to_string())
                             }
                             _ => None,
                         })
@@ -617,45 +617,34 @@ fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) ->
 
         let mut defs = vec![];
         for param in &self.params {
-            match *param {
-                ast::GenericParam::Lifetime(ref l) => {
-                    let mut l_text = l.lifetime.ident.to_string();
-                    defs.push(SigElement {
-                        id: id_from_node_id(l.lifetime.id, scx),
-                        start: offset + text.len(),
-                        end: offset + text.len() + l_text.len(),
-                    });
-
-                    if !l.bounds.is_empty() {
-                        l_text.push_str(": ");
-                        let bounds = l.bounds
-                            .iter()
-                            .map(|l| l.ident.to_string())
+            let mut param_text = param.ident.to_string();
+            defs.push(SigElement {
+                id: id_from_node_id(param.id, scx),
+                start: offset + text.len(),
+                end: offset + text.len() + param_text.len(),
+            });
+            if !param.bounds.is_empty() {
+                param_text.push_str(": ");
+                match param.kind {
+                    ast::GenericParamKind::Lifetime { .. } => {
+                        let bounds = param.bounds.iter()
+                            .map(|bound| match bound {
+                                ast::GenericBound::Outlives(lt) => lt.ident.to_string(),
+                                _ => panic!(),
+                            })
                             .collect::<Vec<_>>()
                             .join(" + ");
-                        l_text.push_str(&bounds);
+                        param_text.push_str(&bounds);
                         // FIXME add lifetime bounds refs.
                     }
-                    text.push_str(&l_text);
-                    text.push(',');
-                }
-                ast::GenericParam::Type(ref t) => {
-                    let mut t_text = t.ident.to_string();
-                    defs.push(SigElement {
-                        id: id_from_node_id(t.id, scx),
-                        start: offset + text.len(),
-                        end: offset + text.len() + t_text.len(),
-                    });
-
-                    if !t.bounds.is_empty() {
-                        t_text.push_str(": ");
-                        t_text.push_str(&pprust::bounds_to_string(&t.bounds));
+                    ast::GenericParamKind::Type { .. } => {
+                        param_text.push_str(&pprust::bounds_to_string(&param.bounds));
                         // FIXME descend properly into bounds.
                     }
-                    text.push_str(&t_text);
-                    text.push(',');
                 }
             }
+            text.push_str(&param_text);
+            text.push(',');
         }
 
         text.push('>');
@@ -852,7 +841,7 @@ fn name_and_generics(
 fn make_assoc_type_signature(
     id: NodeId,
     ident: ast::Ident,
-    bounds: Option<&ast::TyParamBounds>,
+    bounds: Option<&ast::GenericBounds>,
     default: Option<&ast::Ty>,
     scx: &SaveContext,
 ) -> Result {
index bf26409c3ef5fa858cb932f967eb5e1b8a485347..a1242621cb18c5882197fd25c265bad632b7bac6 100644 (file)
     Canonical, CanonicalVarValues, Canonicalize, QueryRegionConstraint, QueryResult,
 };
 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
-use rustc::traits::{DomainGoal, ExClauseFold, ExClauseLift, Goal, ProgramClause, QuantifierKind};
+use rustc::traits::{
+    WellFormed,
+    FromEnv,
+    DomainGoal,
+    ExClauseFold,
+    ExClauseLift,
+    Goal,
+    ProgramClause,
+    QuantifierKind
+};
 use rustc::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
 use rustc::ty::subst::Kind;
 use rustc::ty::{self, TyCtxt};
@@ -314,11 +323,10 @@ fn program_clauses(
         _environment: &ty::ParamEnv<'tcx>,
         goal: &DomainGoal<'tcx>,
     ) -> Vec<ProgramClause<'tcx>> {
-        use rustc::traits::DomainGoal::*;
-        use rustc::traits::WhereClauseAtom::*;
+        use rustc::traits::WhereClause::*;
 
         match goal {
-            Holds(Implemented(_trait_predicate)) => {
+            DomainGoal::Holds(Implemented(_trait_predicate)) => {
                 // These come from:
                 //
                 // - Trait definitions (implied bounds)
@@ -326,31 +334,31 @@ fn program_clauses(
                 panic!()
             }
 
-            Holds(ProjectionEq(_projection_predicate)) => {
+            DomainGoal::Holds(ProjectionEq(_projection_predicate)) => {
                 // These come from:
                 panic!()
             }
 
-            WellFormed(Implemented(_trait_predicate)) => {
-                // These come from -- the trait decl.
+            DomainGoal::Holds(RegionOutlives(_region_outlives)) => {
                 panic!()
             }
 
-            WellFormed(ProjectionEq(_projection_predicate)) => panic!(),
-
-            FromEnv(Implemented(_trait_predicate)) => panic!(),
-
-            FromEnv(ProjectionEq(_projection_predicate)) => panic!(),
+            DomainGoal::Holds(TypeOutlives(_type_outlives)) => {
+                panic!()
+            }
 
-            WellFormedTy(_ty) => panic!(),
+            DomainGoal::WellFormed(WellFormed::Trait(_trait_predicate)) => {
+                // These come from -- the trait decl.
+                panic!()
+            }
 
-            FromEnvTy(_ty) => panic!(),
+            DomainGoal::WellFormed(WellFormed::Ty(_ty)) => panic!(),
 
-            RegionOutlives(_region_outlives) => panic!(),
+            DomainGoal::FromEnv(FromEnv::Trait(_trait_predicate)) => panic!(),
 
-            TypeOutlives(_type_outlives) => panic!(),
+            DomainGoal::FromEnv(FromEnv::Ty(_ty)) => panic!(),
 
-            Normalize(_) => panic!(),
+            DomainGoal::Normalize(_) => panic!(),
         }
     }
 
index 32f18a62abe596cd83289a169725b25b35516a11..0270e970976eaa59906bccbfda1f1783ee4e462c 100644 (file)
@@ -13,7 +13,7 @@
 use rustc::hir::map::definitions::DefPathData;
 use rustc::hir::{self, ImplPolarity};
 use rustc::traits::{Clause, Clauses, DomainGoal, Goal, PolyDomainGoal, ProgramClause,
-                    WhereClauseAtom};
+                    WhereClause, FromEnv, WellFormed};
 use rustc::ty::subst::Substs;
 use rustc::ty::{self, Slice, TyCtxt};
 use rustc_data_structures::fx::FxHashSet;
@@ -23,7 +23,7 @@
 use std::iter;
 
 crate trait Lower<T> {
-    /// Lower a rustc construction (e.g. `ty::TraitPredicate`) to a chalk-like type.
+    /// Lower a rustc construct (e.g. `ty::TraitPredicate`) to a chalk-like type.
     fn lower(&self) -> T;
 }
 
@@ -36,36 +36,36 @@ fn lower(&self) -> Vec<U> {
     }
 }
 
-impl<'tcx> Lower<WhereClauseAtom<'tcx>> for ty::TraitPredicate<'tcx> {
-    fn lower(&self) -> WhereClauseAtom<'tcx> {
-        WhereClauseAtom::Implemented(*self)
+impl<'tcx> Lower<WhereClause<'tcx>> for ty::TraitPredicate<'tcx> {
+    fn lower(&self) -> WhereClause<'tcx> {
+        WhereClause::Implemented(*self)
     }
 }
 
-impl<'tcx> Lower<WhereClauseAtom<'tcx>> for ty::ProjectionPredicate<'tcx> {
-    fn lower(&self) -> WhereClauseAtom<'tcx> {
-        WhereClauseAtom::ProjectionEq(*self)
+impl<'tcx> Lower<WhereClause<'tcx>> for ty::ProjectionPredicate<'tcx> {
+    fn lower(&self) -> WhereClause<'tcx> {
+        WhereClause::ProjectionEq(*self)
     }
 }
 
-impl<'tcx, T> Lower<DomainGoal<'tcx>> for T
-where
-    T: Lower<WhereClauseAtom<'tcx>>,
-{
-    fn lower(&self) -> DomainGoal<'tcx> {
-        DomainGoal::Holds(self.lower())
+impl<'tcx> Lower<WhereClause<'tcx>> for ty::RegionOutlivesPredicate<'tcx> {
+    fn lower(&self) -> WhereClause<'tcx> {
+        WhereClause::RegionOutlives(*self)
     }
 }
 
-impl<'tcx> Lower<DomainGoal<'tcx>> for ty::RegionOutlivesPredicate<'tcx> {
-    fn lower(&self) -> DomainGoal<'tcx> {
-        DomainGoal::RegionOutlives(*self)
+impl<'tcx> Lower<WhereClause<'tcx>> for ty::TypeOutlivesPredicate<'tcx> {
+    fn lower(&self) -> WhereClause<'tcx> {
+        WhereClause::TypeOutlives(*self)
     }
 }
 
-impl<'tcx> Lower<DomainGoal<'tcx>> for ty::TypeOutlivesPredicate<'tcx> {
+impl<'tcx, T> Lower<DomainGoal<'tcx>> for T
+where
+    T: Lower<WhereClause<'tcx>>,
+{
     fn lower(&self) -> DomainGoal<'tcx> {
-        DomainGoal::TypeOutlives(*self)
+        DomainGoal::Holds(self.lower())
     }
 }
 
@@ -86,15 +86,20 @@ fn lower(&self) -> PolyDomainGoal<'tcx> {
 
 impl<'tcx> Lower<PolyDomainGoal<'tcx>> for ty::Predicate<'tcx> {
     fn lower(&self) -> PolyDomainGoal<'tcx> {
-        use rustc::ty::Predicate::*;
+        use rustc::ty::Predicate;
 
         match self {
-            Trait(predicate) => predicate.lower(),
-            RegionOutlives(predicate) => predicate.lower(),
-            TypeOutlives(predicate) => predicate.lower(),
-            Projection(predicate) => predicate.lower(),
-            WellFormed(ty) => ty::Binder::dummy(DomainGoal::WellFormedTy(*ty)),
-            ObjectSafe(..) | ClosureKind(..) | Subtype(..) | ConstEvaluatable(..) => {
+            Predicate::Trait(predicate) => predicate.lower(),
+            Predicate::RegionOutlives(predicate) => predicate.lower(),
+            Predicate::TypeOutlives(predicate) => predicate.lower(),
+            Predicate::Projection(predicate) => predicate.lower(),
+            Predicate::WellFormed(ty) => ty::Binder::dummy(
+                DomainGoal::WellFormed(WellFormed::Ty(*ty))
+            ),
+            Predicate::ObjectSafe(..) |
+            Predicate::ClosureKind(..) |
+            Predicate::Subtype(..) |
+            Predicate::ConstEvaluatable(..) => {
                 unimplemented!()
             }
         }
@@ -110,11 +115,13 @@ trait IntoFromEnvGoal {
 
 impl<'tcx> IntoFromEnvGoal for DomainGoal<'tcx> {
     fn into_from_env_goal(self) -> DomainGoal<'tcx> {
-        use self::DomainGoal::*;
+        use self::WhereClause::*;
+
         match self {
-            Holds(wc_atom) => FromEnv(wc_atom),
-            WellFormed(..) | FromEnv(..) | WellFormedTy(..) | FromEnvTy(..) | Normalize(..)
-            | RegionOutlives(..) | TypeOutlives(..) => self,
+            DomainGoal::Holds(Implemented(trait_ref)) => DomainGoal::FromEnv(
+                FromEnv::Trait(trait_ref)
+            ),
+            other => other,
         }
     }
 }
@@ -127,6 +134,8 @@ fn into_from_env_goal(self) -> DomainGoal<'tcx> {
         DefPathData::Trait(_) => program_clauses_for_trait(tcx, def_id),
         DefPathData::Impl => program_clauses_for_impl(tcx, def_id),
         DefPathData::AssocTypeInImpl(..) => program_clauses_for_associated_type_value(tcx, def_id),
+        DefPathData::AssocTypeInTrait(..) => program_clauses_for_associated_type_def(tcx, def_id),
+        DefPathData::TypeNs(..) => program_clauses_for_type_def(tcx, def_id),
         _ => Slice::empty(),
     }
 }
@@ -212,16 +221,20 @@ fn program_clauses_for_trait<'a, 'tcx>(
             substs: Substs::identity_for_item(tcx, def_id),
         },
     };
-    // `FromEnv(Self: Trait<P1..Pn>)`
-    let from_env = Goal::from(DomainGoal::FromEnv(trait_pred.lower()));
+
     // `Implemented(Self: Trait<P1..Pn>)`
-    let impl_trait = DomainGoal::Holds(WhereClauseAtom::Implemented(trait_pred));
+    let impl_trait: DomainGoal = trait_pred.lower();
+
+     // `FromEnv(Self: Trait<P1..Pn>)`
+    let from_env_goal = impl_trait.into_from_env_goal().into_goal();
+    let hypotheses = tcx.intern_goals(&[from_env_goal]);
 
     // `Implemented(Self: Trait<P1..Pn>) :- FromEnv(Self: Trait<P1..Pn>)`
     let implemented_from_env = ProgramClause {
         goal: impl_trait,
-        hypotheses: tcx.intern_goals(&[from_env]),
+        hypotheses,
     };
+
     let clauses = iter::once(Clause::ForAll(ty::Binder::dummy(implemented_from_env)));
 
     // Rule Implied-Bound-From-Trait
@@ -239,25 +252,17 @@ fn program_clauses_for_trait<'a, 'tcx>(
     let where_clauses = &tcx.predicates_of(def_id).predicates;
     let implied_bound_clauses = where_clauses[1..]
         .into_iter()
-        .map(|wc| implied_bound_from_trait(tcx, trait_pred, wc));
+        .map(|wc| wc.lower())
 
-    tcx.mk_clauses(clauses.chain(implied_bound_clauses))
-}
+        // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`
+        .map(|wc| wc.map_bound(|goal| ProgramClause {
+            goal: goal.into_from_env_goal(),
+            hypotheses,
+        }))
 
-/// For a given `where_clause`, returns a clause `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`.
-fn implied_bound_from_trait<'a, 'tcx>(
-    tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    trait_pred: ty::TraitPredicate<'tcx>,
-    where_clause: &ty::Predicate<'tcx>,
-) -> Clause<'tcx> {
-    // `FromEnv(Self: Trait<P1..Pn>)`
-    let impl_trait = DomainGoal::FromEnv(WhereClauseAtom::Implemented(trait_pred));
-
-    // `FromEnv(WC) :- FromEnv(Self: Trait<P1..Pn>)`
-    Clause::ForAll(where_clause.lower().map_bound(|goal| ProgramClause {
-        goal: goal.into_from_env_goal(),
-        hypotheses: tcx.intern_goals(&[Goal::from(impl_trait)]),
-    }))
+        .map(Clause::ForAll);
+
+    tcx.mk_clauses(clauses.chain(implied_bound_clauses))
 }
 
 fn program_clauses_for_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Clauses<'tcx> {
@@ -275,9 +280,11 @@ fn program_clauses_for_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId
     // }
     // ```
 
-    let trait_ref = tcx.impl_trait_ref(def_id).unwrap();
+    let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl");
+
     // `Implemented(A0: Trait<A1..An>)`
     let trait_pred = ty::TraitPredicate { trait_ref }.lower();
+
     // `WC`
     let where_clauses = tcx.predicates_of(def_id).predicates.lower();
 
@@ -293,6 +300,72 @@ fn program_clauses_for_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId
     tcx.intern_clauses(&[Clause::ForAll(ty::Binder::dummy(clause))])
 }
 
+pub fn program_clauses_for_type_def<'a, 'tcx>(
+    tcx: TyCtxt<'a, 'tcx, 'tcx>,
+    def_id: DefId,
+) -> Clauses<'tcx> {
+
+    // Rule WellFormed-Type
+    //
+    // `struct Ty<P1..Pn> where WC1, ..., WCm`
+    //
+    // ```
+    // forall<P1..Pn> {
+    //   WellFormed(Ty<...>) :- WC1, ..., WCm`
+    // }
+    // ```
+
+    // `Ty<...>`
+    let ty = tcx.type_of(def_id);
+
+    // `WC`
+    let where_clauses = tcx.predicates_of(def_id).predicates.lower();
+
+    // `WellFormed(Ty<...>) :- WC1, ..., WCm`
+    let well_formed = ProgramClause {
+        goal: DomainGoal::WellFormed(WellFormed::Ty(ty)),
+        hypotheses: tcx.mk_goals(
+            where_clauses.iter().cloned().map(|wc| Goal::from_poly_domain_goal(wc, tcx))
+        ),
+    };
+
+    let well_formed_clause = iter::once(Clause::ForAll(ty::Binder::dummy(well_formed)));
+
+    // Rule FromEnv-Type
+    //
+    // For each where clause `WC`:
+    // ```
+    // forall<P1..Pn> {
+    //   FromEnv(WC) :- FromEnv(Ty<...>)
+    // }
+    // ```
+
+    // `FromEnv(Ty<...>)`
+    let from_env_goal = DomainGoal::FromEnv(FromEnv::Ty(ty)).into_goal();
+    let hypotheses = tcx.intern_goals(&[from_env_goal]);
+
+    // For each where clause `WC`:
+    let from_env_clauses = where_clauses
+        .into_iter()
+
+        // `FromEnv(WC) :- FromEnv(Ty<...>)`
+        .map(|wc| wc.map_bound(|goal| ProgramClause {
+            goal: goal.into_from_env_goal(),
+            hypotheses,
+        }))
+
+        .map(Clause::ForAll);
+
+    tcx.mk_clauses(well_formed_clause.chain(from_env_clauses))
+}
+
+pub fn program_clauses_for_associated_type_def<'a, 'tcx>(
+    _tcx: TyCtxt<'a, 'tcx, 'tcx>,
+    _item_id: DefId,
+) -> Clauses<'tcx> {
+    unimplemented!()
+}
+
 pub fn program_clauses_for_associated_type_value<'a, 'tcx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     item_id: DefId,
@@ -301,45 +374,50 @@ pub fn program_clauses_for_associated_type_value<'a, 'tcx>(
     //
     // ```impl<P0..Pn> Trait<A1..An> for A0
     // {
-    //     type AssocType<Pn+1..Pm> where WC = T;
+    //     type AssocType<Pn+1..Pm> = T;
     // }```
     //
+    // FIXME: For the moment, we don't account for where clauses written on the associated
+    // ty definition (i.e. in the trait def, as in `type AssocType<T> where T: Sized`).
     // ```
     // forall<P0..Pm> {
     //   forall<Pn+1..Pm> {
     //     Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T) :-
-    //       Implemented(A0: Trait<A1..An>) && WC
+    //       Implemented(A0: Trait<A1..An>)
     //   }
     // }
     // ```
 
     let item = tcx.associated_item(item_id);
     debug_assert_eq!(item.kind, ty::AssociatedKind::Type);
-    let impl_id = if let ty::AssociatedItemContainer::ImplContainer(impl_id) = item.container {
-        impl_id
-    } else {
-        bug!()
+    let impl_id = match item.container {
+        ty::AssociatedItemContainer::ImplContainer(impl_id) => impl_id,
+        _ => bug!("not an impl container"),
     };
+
     // `A0 as Trait<A1..An>`
     let trait_ref = tcx.impl_trait_ref(impl_id).unwrap();
+
     // `T`
     let ty = tcx.type_of(item_id);
+
     // `Implemented(A0: Trait<A1..An>)`
     let trait_implemented = ty::Binder::dummy(ty::TraitPredicate { trait_ref }.lower());
-    // `WC`
-    let item_where_clauses = tcx.predicates_of(item_id).predicates.lower();
-    // `Implemented(A0: Trait<A1..An>) && WC`
-    let mut where_clauses = vec![trait_implemented];
-    where_clauses.extend(item_where_clauses);
+
+    // `Implemented(A0: Trait<A1..An>)`
+    let hypotheses = vec![trait_implemented];
+
     // `<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm>`
     let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.name);
+
     // `Normalize(<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm> -> T)`
     let normalize_goal = DomainGoal::Normalize(ty::ProjectionPredicate { projection_ty, ty });
+
     // `Normalize(... -> T) :- ...`
     let clause = ProgramClause {
         goal: normalize_goal,
         hypotheses: tcx.mk_goals(
-            where_clauses
+            hypotheses
                 .into_iter()
                 .map(|wc| Goal::from_poly_domain_goal(wc, tcx)),
         ),
index 18911b47ed1d08434ac9ba141d56d92bacef8980..f3912c3042d7fceef539782e094ed0dcf2aa18d4 100644 (file)
@@ -13,7 +13,7 @@
 //! is parameterized by an instance of `AstConv`.
 
 use rustc_data_structures::accumulate_vec::AccumulateVec;
-use hir;
+use hir::{self, GenericArg};
 use hir::def::Def;
 use hir::def_id::DefId;
 use middle::resolve_lifetime as rl;
@@ -177,11 +177,11 @@ pub fn ast_path_substs_for_ty(&self,
     {
 
         let (substs, assoc_bindings) =
-            item_segment.with_parameters(|parameters| {
+            item_segment.with_generic_args(|generic_args| {
                 self.create_substs_for_ast_path(
                     span,
                     def_id,
-                    parameters,
+                    generic_args,
                     item_segment.infer_types,
                     None)
             });
@@ -199,7 +199,7 @@ pub fn ast_path_substs_for_ty(&self,
     fn create_substs_for_ast_path(&self,
         span: Span,
         def_id: DefId,
-        parameters: &hir::PathParameters,
+        generic_args: &hir::GenericArgs,
         infer_types: bool,
         self_ty: Option<Ty<'tcx>>)
         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
@@ -207,16 +207,26 @@ fn create_substs_for_ast_path(&self,
         let tcx = self.tcx();
 
         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
-               parameters={:?})",
-               def_id, self_ty, parameters);
+               generic_args={:?})",
+               def_id, self_ty, generic_args);
 
         // If the type is parameterized by this region, then replace this
         // region with the current anon region binding (in other words,
         // whatever & would get replaced with).
-        let decl_generics = tcx.generics_of(def_id);
-        let ty_provided = parameters.types.len();
-        let lt_provided = parameters.lifetimes.len();
 
+        // FIXME(varkor): Separating out the parameters is messy.
+        let lifetimes: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg {
+            GenericArg::Lifetime(lt) => Some(lt),
+            _ => None,
+        }).collect();
+        let types: Vec<_> = generic_args.args.iter().filter_map(|arg| match arg {
+            GenericArg::Type(ty) => Some(ty),
+            _ => None,
+        }).collect();
+        let lt_provided = lifetimes.len();
+        let ty_provided = types.len();
+
+        let decl_generics = tcx.generics_of(def_id);
         let mut lt_accepted = 0;
         let mut ty_params = ParamRange { required: 0, accepted: 0 };
         for param in &decl_generics.params {
@@ -269,8 +279,8 @@ fn create_substs_for_ast_path(&self,
             match param.kind {
                 GenericParamDefKind::Lifetime => {
                     let i = param.index as usize - own_self;
-                    if let Some(lifetime) = parameters.lifetimes.get(i) {
-                        self.ast_region_to_region(lifetime, Some(param)).into()
+                    if let Some(lt) = lifetimes.get(i) {
+                        self.ast_region_to_region(lt, Some(param)).into()
                     } else {
                         tcx.types.re_static.into()
                     }
@@ -286,7 +296,7 @@ fn create_substs_for_ast_path(&self,
                     let i = i - (lt_accepted + own_self);
                     if i < ty_provided {
                         // A provided type parameter.
-                        self.ast_ty_to_ty(&parameters.types[i]).into()
+                        self.ast_ty_to_ty(&types[i]).into()
                     } else if infer_types {
                         // No type parameters were provided, we can infer all.
                         if !default_needs_object_self(param) {
@@ -330,7 +340,7 @@ fn create_substs_for_ast_path(&self,
             }
         });
 
-        let assoc_bindings = parameters.bindings.iter().map(|binding| {
+        let assoc_bindings = generic_args.bindings.iter().map(|binding| {
             ConvertedBinding {
                 item_name: binding.name,
                 ty: self.ast_ty_to_ty(&binding.ty),
@@ -355,7 +365,7 @@ pub fn instantiate_mono_trait_ref(&self,
         self_ty: Ty<'tcx>)
         -> ty::TraitRef<'tcx>
     {
-        self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
+        self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
 
         let trait_def_id = self.trait_def_id(trait_ref);
         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
@@ -389,7 +399,7 @@ pub(super) fn instantiate_poly_trait_ref_inner(&self,
 
         debug!("ast_path_to_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
 
-        self.prohibit_type_params(trait_ref.path.segments.split_last().unwrap().1);
+        self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
 
         let (substs, assoc_bindings) =
             self.create_substs_for_ast_trait_ref(trait_ref.path.span,
@@ -451,7 +461,8 @@ fn create_substs_for_ast_trait_ref(&self,
         let trait_def = self.tcx().trait_def(trait_def_id);
 
         if !self.tcx().features().unboxed_closures &&
-           trait_segment.with_parameters(|p| p.parenthesized) != trait_def.paren_sugar {
+            trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
+            != trait_def.paren_sugar {
             // For now, require that parenthetical notation be used only with `Fn()` etc.
             let msg = if trait_def.paren_sugar {
                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
@@ -463,10 +474,10 @@ fn create_substs_for_ast_trait_ref(&self,
                              span, GateIssue::Language, msg);
         }
 
-        trait_segment.with_parameters(|parameters| {
+        trait_segment.with_generic_args(|generic_args| {
             self.create_substs_for_ast_path(span,
                                             trait_def_id,
-                                            parameters,
+                                            generic_args,
                                             trait_segment.infer_types,
                                             Some(self_ty))
         })
@@ -866,7 +877,7 @@ pub fn associated_path_def_to_ty(&self,
 
         debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
 
-        self.prohibit_type_params(slice::from_ref(item_segment));
+        self.prohibit_generics(slice::from_ref(item_segment));
 
         // Find the type of the associated item, and the trait where the associated
         // item is declared.
@@ -943,7 +954,7 @@ fn qpath_to_ty(&self,
         let tcx = self.tcx();
         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
 
-        self.prohibit_type_params(slice::from_ref(item_segment));
+        self.prohibit_generics(slice::from_ref(item_segment));
 
         let self_ty = if let Some(ty) = opt_self_ty {
             ty
@@ -968,25 +979,37 @@ fn qpath_to_ty(&self,
         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
     }
 
-    pub fn prohibit_type_params(&self, segments: &[hir::PathSegment]) {
+    pub fn prohibit_generics(&self, segments: &[hir::PathSegment]) {
         for segment in segments {
-            segment.with_parameters(|parameters| {
-                for typ in &parameters.types {
-                    struct_span_err!(self.tcx().sess, typ.span, E0109,
-                                     "type parameters are not allowed on this type")
-                        .span_label(typ.span, "type parameter not allowed")
-                        .emit();
-                    break;
-                }
-                for lifetime in &parameters.lifetimes {
-                    struct_span_err!(self.tcx().sess, lifetime.span, E0110,
-                                     "lifetime parameters are not allowed on this type")
-                        .span_label(lifetime.span,
-                                    "lifetime parameter not allowed on this type")
-                        .emit();
-                    break;
+            segment.with_generic_args(|generic_args| {
+                let (mut err_for_lt, mut err_for_ty) = (false, false);
+                for arg in &generic_args.args {
+                    let (mut span_err, span, kind) = match arg {
+                        hir::GenericArg::Lifetime(lt) => {
+                            if err_for_lt { continue }
+                            err_for_lt = true;
+                            (struct_span_err!(self.tcx().sess, lt.span, E0110,
+                                            "lifetime parameters are not allowed on \
+                                                this type"),
+                             lt.span,
+                             "lifetime")
+                        }
+                        hir::GenericArg::Type(ty) => {
+                            if err_for_ty { continue }
+                            err_for_ty = true;
+                            (struct_span_err!(self.tcx().sess, ty.span, E0109,
+                                            "type parameters are not allowed on this type"),
+                             ty.span,
+                             "type")
+                        }
+                    };
+                    span_err.span_label(span, format!("{} parameter not allowed", kind))
+                            .emit();
+                    if err_for_lt && err_for_ty {
+                        break;
+                    }
                 }
-                for binding in &parameters.bindings {
+                for binding in &generic_args.bindings {
                     self.prohibit_projection(binding.span);
                     break;
                 }
@@ -1016,21 +1039,21 @@ pub fn def_to_ty(&self,
             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
             Def::Union(did) | Def::TyForeign(did) => {
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(path.segments.split_last().unwrap().1);
+                self.prohibit_generics(path.segments.split_last().unwrap().1);
                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
             }
             Def::Variant(did) if permit_variants => {
                 // Convert "variant type" as if it were a real type.
                 // The resulting `Ty` is type of the variant's enum for now.
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(path.segments.split_last().unwrap().1);
+                self.prohibit_generics(path.segments.split_last().unwrap().1);
                 self.ast_path_to_ty(span,
                                     tcx.parent_def_id(did).unwrap(),
                                     path.segments.last().unwrap())
             }
             Def::TyParam(did) => {
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(&path.segments);
+                self.prohibit_generics(&path.segments);
 
                 let node_id = tcx.hir.as_local_node_id(did).unwrap();
                 let item_id = tcx.hir.get_parent_node(node_id);
@@ -1043,18 +1066,18 @@ pub fn def_to_ty(&self,
                 // Self in impl (we know the concrete type).
 
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(&path.segments);
+                self.prohibit_generics(&path.segments);
 
                 tcx.at(span).type_of(def_id)
             }
             Def::SelfTy(Some(_), None) => {
                 // Self in trait.
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(&path.segments);
+                self.prohibit_generics(&path.segments);
                 tcx.mk_self_type()
             }
             Def::AssociatedTy(def_id) => {
-                self.prohibit_type_params(&path.segments[..path.segments.len()-2]);
+                self.prohibit_generics(&path.segments[..path.segments.len()-2]);
                 self.qpath_to_ty(span,
                                  opt_self_ty,
                                  def_id,
@@ -1063,7 +1086,7 @@ pub fn def_to_ty(&self,
             }
             Def::PrimTy(prim_ty) => {
                 assert_eq!(opt_self_ty, None);
-                self.prohibit_type_params(&path.segments);
+                self.prohibit_generics(&path.segments);
                 match prim_ty {
                     hir::TyBool => tcx.types.bool,
                     hir::TyChar => tcx.types.char,
index 808c134e9944864f964cb85648ee0474fb0e67a0..5f8955612e10cb00614bf34c15aae479d6eab212 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use rustc::hir::{self, ImplItemKind, TraitItemKind};
+use rustc::hir::{self, GenericParamKind, ImplItemKind, TraitItemKind};
 use rustc::infer::{self, InferOk};
 use rustc::ty::{self, TyCtxt, GenericParamDefKind};
 use rustc::ty::util::ExplicitSelf;
@@ -728,11 +728,9 @@ fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     let mut error_found = false;
     let impl_m_generics = tcx.generics_of(impl_m.def_id);
     let trait_m_generics = tcx.generics_of(trait_m.def_id);
-    let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| {
-        match param.kind {
-            GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
-            GenericParamDefKind::Lifetime => None,
-        }
+    let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
+        GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
+        GenericParamDefKind::Lifetime => None,
     });
     let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| {
         match param.kind {
@@ -843,19 +841,19 @@ fn nested_visit_map<'this>(
                         }
                         let span = visitor.0?;
 
-                        let param = impl_m.generics.params.iter().filter_map(|param| {
-                            match param {
-                                hir::GenericParam::Type(param) => {
+                        let bounds = impl_m.generics.params.iter().find_map(|param| {
+                            match param.kind {
+                                GenericParamKind::Lifetime { .. } => None,
+                                GenericParamKind::Type { .. } => {
                                     if param.id == impl_node_id {
-                                        Some(param)
+                                        Some(&param.bounds)
                                     } else {
                                         None
                                     }
-                                },
-                                hir::GenericParam::Lifetime(..) => None,
+                                }
                             }
-                        }).next()?;
-                        let bounds = param.bounds.first()?.span().to(param.bounds.last()?.span());
+                        })?;
+                        let bounds = bounds.first()?.span().to(bounds.last()?.span());
                         let bounds = tcx
                             .sess
                             .codemap()
index f3a3c30fe5ad9ba09ac04903f3fd5ede60bb595f..36ce01bcd08b30cd266aa242a1c68fede31fae50 100644 (file)
@@ -12,6 +12,7 @@
 
 use astconv::AstConv;
 use check::{FnCtxt, PlaceOp, callee, Needs};
+use hir::GenericArg;
 use hir::def_id::DefId;
 use rustc::ty::subst::Substs;
 use rustc::traits;
@@ -59,7 +60,7 @@ pub fn confirm_method(
             "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})",
             unadjusted_self_ty,
             pick,
-            segment.parameters,
+            segment.args,
         );
 
         let mut confirm_cx = ConfirmContext::new(self, span, self_expr, call_expr);
@@ -316,36 +317,44 @@ fn instantiate_method_substs(
         let method_generics = self.tcx.generics_of(pick.item.def_id);
         let mut fn_segment = Some((segment, method_generics));
         let supress_mismatch = self.fcx.check_impl_trait(self.span, fn_segment);
-        self.fcx.check_path_parameter_count(self.span, &mut fn_segment, true, supress_mismatch);
+        self.fcx.check_generic_arg_count(self.span, &mut fn_segment, true, supress_mismatch);
 
         // Create subst for early-bound lifetime parameters, combining
         // parameters from the type and those from the method.
         assert_eq!(method_generics.parent_count, parent_substs.len());
-        let provided = &segment.parameters;
+        let provided = &segment.args;
         let own_counts = method_generics.own_counts();
         Substs::for_item(self.tcx, pick.item.def_id, |param, _| {
-            let i = param.index as usize;
+            let mut i = param.index as usize;
             if i < parent_substs.len() {
                 parent_substs[i]
             } else {
-                match param.kind {
-                    GenericParamDefKind::Lifetime => {
-                        if let Some(lifetime) = provided.as_ref().and_then(|p| {
-                            p.lifetimes.get(i - parent_substs.len())
-                        }) {
-                            return AstConv::ast_region_to_region(
-                                self.fcx, lifetime, Some(param)).into();
-                        }
-                    }
-                    GenericParamDefKind::Type {..} => {
-                        if let Some(ast_ty) = provided.as_ref().and_then(|p| {
-                            p.types.get(i - parent_substs.len() - own_counts.lifetimes)
-                        }) {
-                            return self.to_ty(ast_ty).into();
+                let (is_lt, is_ty) = match param.kind {
+                    GenericParamDefKind::Lifetime => (true, false),
+                    GenericParamDefKind::Type { .. } => (false, true),
+                };
+                provided.as_ref().and_then(|data| {
+                    for arg in &data.args {
+                        match arg {
+                            GenericArg::Lifetime(lt) if is_lt => {
+                                if i == parent_substs.len() {
+                                    return Some(AstConv::ast_region_to_region(
+                                        self.fcx, lt, Some(param)).into());
+                                }
+                                i -= 1;
+                            }
+                            GenericArg::Lifetime(_) => {}
+                            GenericArg::Type(ty) if is_ty => {
+                                if i == parent_substs.len() + own_counts.lifetimes {
+                                    return Some(self.to_ty(ty).into());
+                                }
+                                i -= 1;
+                            }
+                            GenericArg::Type(_) => {}
                         }
                     }
-                }
-                self.var_for_def(self.span, param)
+                    None
+                }).unwrap_or_else(|| self.var_for_def(self.span, param))
             }
         })
     }
index b70b61d191594f0baa9c8e2c6b4ee983a5b7de33..366420cfcabb15780a8f6e2e72c4a496b7f63d71 100644 (file)
@@ -85,6 +85,7 @@
 use self::TupleArgumentsFlag::*;
 
 use astconv::AstConv;
+use hir::GenericArg;
 use hir::def::Def;
 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
 use std::slice;
@@ -1260,10 +1261,11 @@ pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item
       hir::ItemUnion(..) => {
         check_union(tcx, it.id, it.span);
       }
-      hir::ItemTy(_, ref generics) => {
+      hir::ItemTy(..) => {
         let def_id = tcx.hir.local_def_id(it.id);
         let pty_ty = tcx.type_of(def_id);
-        check_bounds_are_used(tcx, generics, pty_ty);
+        let generics = tcx.generics_of(def_id);
+        check_bounds_are_used(tcx, &generics, pty_ty);
       }
       hir::ItemForeignMod(ref m) => {
         check_abi(tcx, it.span, m.abi);
@@ -4740,8 +4742,7 @@ pub fn instantiate_value_path(&self,
             Def::Fn(def_id) |
             Def::Const(def_id) |
             Def::Static(def_id, _) => {
-                fn_segment = Some((segments.last().unwrap(),
-                                   self.tcx.generics_of(def_id)));
+                fn_segment = Some((segments.last().unwrap(), self.tcx.generics_of(def_id)));
             }
 
             // Case 3. Reference to a method or associated const.
@@ -4781,7 +4782,7 @@ pub fn instantiate_value_path(&self,
         // errors if type parameters are provided in an inappropriate place.
         let poly_segments = type_segment.is_some() as usize +
                             fn_segment.is_some() as usize;
-        AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
+        AstConv::prohibit_generics(self, &segments[..segments.len() - poly_segments]);
 
         match def {
             Def::Local(nid) | Def::Upvar(nid, ..) => {
@@ -4800,8 +4801,8 @@ pub fn instantiate_value_path(&self,
         // to add defaults. If the user provided *too many* types, that's
         // a problem.
         let supress_mismatch = self.check_impl_trait(span, fn_segment);
-        self.check_path_parameter_count(span, &mut type_segment, false, supress_mismatch);
-        self.check_path_parameter_count(span, &mut fn_segment, false, supress_mismatch);
+        self.check_generic_arg_count(span, &mut type_segment, false, supress_mismatch);
+        self.check_generic_arg_count(span, &mut fn_segment, false, supress_mismatch);
 
         let (fn_start, has_self) = match (type_segment, fn_segment) {
             (_, Some((_, generics))) => {
@@ -4812,11 +4813,42 @@ pub fn instantiate_value_path(&self,
             }
             (None, None) => (0, false)
         };
+        // FIXME(varkor): Separating out the parameters is messy.
+        let mut lifetimes_type_seg = vec![];
+        let mut types_type_seg = vec![];
+        let mut infer_types_type_seg = true;
+        if let Some((seg, _)) = type_segment {
+            if let Some(ref data) = seg.args {
+                for arg in &data.args {
+                    match arg {
+                        GenericArg::Lifetime(lt) => lifetimes_type_seg.push(lt),
+                        GenericArg::Type(ty) => types_type_seg.push(ty),
+                    }
+                }
+            }
+            infer_types_type_seg = seg.infer_types;
+        }
+
+        let mut lifetimes_fn_seg = vec![];
+        let mut types_fn_seg = vec![];
+        let mut infer_types_fn_seg = true;
+        if let Some((seg, _)) = fn_segment {
+            if let Some(ref data) = seg.args {
+                for arg in &data.args {
+                    match arg {
+                        GenericArg::Lifetime(lt) => lifetimes_fn_seg.push(lt),
+                        GenericArg::Type(ty) => types_fn_seg.push(ty),
+                    }
+                }
+            }
+            infer_types_fn_seg = seg.infer_types;
+        }
+
         let substs = Substs::for_item(self.tcx, def.def_id(), |param, substs| {
             let mut i = param.index as usize;
 
-            let segment = if i < fn_start {
-                if let GenericParamDefKind::Type {..} = param.kind {
+            let (segment, lifetimes, types, infer_types) = if i < fn_start {
+                if let GenericParamDefKind::Type { .. } = param.kind {
                     // Handle Self first, so we can adjust the index to match the AST.
                     if has_self && i == 0 {
                         return opt_self_ty.map(|ty| ty.into()).unwrap_or_else(|| {
@@ -4825,29 +4857,21 @@ pub fn instantiate_value_path(&self,
                     }
                 }
                 i -= has_self as usize;
-                type_segment
+                (type_segment, &lifetimes_type_seg, &types_type_seg, infer_types_type_seg)
             } else {
                 i -= fn_start;
-                fn_segment
+                (fn_segment, &lifetimes_fn_seg, &types_fn_seg, infer_types_fn_seg)
             };
 
             match param.kind {
                 GenericParamDefKind::Lifetime => {
-                    let lifetimes = segment.map_or(&[][..], |(s, _)| {
-                        s.parameters.as_ref().map_or(&[][..], |p| &p.lifetimes[..])
-                    });
-
                     if let Some(lifetime) = lifetimes.get(i) {
                         AstConv::ast_region_to_region(self, lifetime, Some(param)).into()
                     } else {
                         self.re_infer(span, Some(param)).unwrap().into()
                     }
                 }
-                GenericParamDefKind::Type {..} => {
-                    let (types, infer_types) = segment.map_or((&[][..], true), |(s, _)| {
-                        (s.parameters.as_ref().map_or(&[][..], |p| &p.types[..]), s.infer_types)
-                    });
-
+                GenericParamDefKind::Type { .. } => {
                     // Skip over the lifetimes in the same segment.
                     if let Some((_, generics)) = segment {
                         i -= generics.own_counts().lifetimes;
@@ -4955,25 +4979,26 @@ fn check_rustc_args_require_const(&self,
     }
 
     /// Report errors if the provided parameters are too few or too many.
-    fn check_path_parameter_count(&self,
-                                  span: Span,
-                                  segment: &mut Option<(&hir::PathSegment, &ty::Generics)>,
-                                  is_method_call: bool,
-                                  supress_mismatch_error: bool) {
+    fn check_generic_arg_count(&self,
+                               span: Span,
+                               segment: &mut Option<(&hir::PathSegment, &ty::Generics)>,
+                               is_method_call: bool,
+                               supress_mismatch_error: bool) {
         let (lifetimes, types, infer_types, bindings) = segment.map_or(
-            (&[][..], &[][..], true, &[][..]),
-            |(s, _)| s.parameters.as_ref().map_or(
-                (&[][..], &[][..], s.infer_types, &[][..]),
-                |p| (&p.lifetimes[..], &p.types[..],
-                     s.infer_types, &p.bindings[..])));
-        let infer_lifetimes = lifetimes.len() == 0;
-
-        let count_lifetime_params = |n| {
-            format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
-        };
-        let count_type_params = |n| {
-            format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
-        };
+            (vec![], vec![], true, &[][..]),
+            |(s, _)| {
+                s.args.as_ref().map_or(
+                    (vec![], vec![], s.infer_types, &[][..]),
+                    |data| {
+                        let (mut lifetimes, mut types) = (vec![], vec![]);
+                        data.args.iter().for_each(|arg| match arg {
+                            GenericArg::Lifetime(lt) => lifetimes.push(lt),
+                            GenericArg::Type(ty) => types.push(ty),
+                        });
+                        (lifetimes, types, s.infer_types, &data.bindings[..])
+                    }
+                )
+            });
 
         // Check provided parameters.
         let ((ty_required, ty_accepted), lt_accepted) =
@@ -4987,9 +5012,7 @@ struct ParamRange {
                 let mut ty_params = ParamRange { required: 0, accepted: 0 };
                 for param in &generics.params {
                     match param.kind {
-                        GenericParamDefKind::Lifetime => {
-                            lt_accepted += 1;
-                        }
+                        GenericParamDefKind::Lifetime => lt_accepted += 1,
                         GenericParamDefKind::Type { has_default, .. } => {
                             ty_params.accepted += 1;
                             if !has_default {
@@ -5006,36 +5029,37 @@ struct ParamRange {
                 ((ty_params.required, ty_params.accepted), lt_accepted)
             });
 
-        if types.len() > ty_accepted {
-            let span = types[ty_accepted].span;
-            let expected_text = count_type_params(ty_accepted);
-            let actual_text = count_type_params(types.len());
-            struct_span_err!(self.tcx.sess, span, E0087,
-                             "too many type parameters provided: \
-                              expected at most {}, found {}",
-                             expected_text, actual_text)
-                .span_label(span, format!("expected {}", expected_text))
-                .emit();
-
+        let count_type_params = |n| {
+            format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
+        };
+        let expected_text = count_type_params(ty_accepted);
+        let actual_text = count_type_params(types.len());
+        if let Some((mut err, span)) = if types.len() > ty_accepted {
             // To prevent derived errors to accumulate due to extra
             // type parameters, we force instantiate_value_path to
             // use inference variables instead of the provided types.
             *segment = None;
+            let span = types[ty_accepted].span;
+            Some((struct_span_err!(self.tcx.sess, span, E0087,
+                                  "too many type parameters provided: \
+                                  expected at most {}, found {}",
+                                  expected_text, actual_text), span))
         } else if types.len() < ty_required && !infer_types && !supress_mismatch_error {
-            let expected_text = count_type_params(ty_required);
-            let actual_text = count_type_params(types.len());
-            struct_span_err!(self.tcx.sess, span, E0089,
-                             "too few type parameters provided: \
-                              expected {}, found {}",
-                             expected_text, actual_text)
-                .span_label(span, format!("expected {}", expected_text))
-                .emit();
+            Some((struct_span_err!(self.tcx.sess, span, E0089,
+                                  "too few type parameters provided: \
+                                  expected {}, found {}",
+                                  expected_text, actual_text), span))
+        } else {
+            None
+        } {
+            err.span_label(span, format!("expected {}", expected_text)).emit();
         }
 
         if !bindings.is_empty() {
             AstConv::prohibit_projection(self, bindings[0].span);
         }
 
+        let infer_lifetimes = lifetimes.len() == 0;
         // Prohibit explicit lifetime arguments if late bound lifetime parameters are present.
         let has_late_bound_lifetime_defs =
             segment.map_or(None, |(_, generics)| generics.has_late_bound_regions);
@@ -5059,25 +5083,26 @@ struct ParamRange {
             return;
         }
 
-        if lifetimes.len() > lt_accepted {
+        let count_lifetime_params = |n| {
+            format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
+        };
+        let expected_text = count_lifetime_params(lt_accepted);
+        let actual_text = count_lifetime_params(lifetimes.len());
+        if let Some((mut err, span)) = if lifetimes.len() > lt_accepted {
             let span = lifetimes[lt_accepted].span;
-            let expected_text = count_lifetime_params(lt_accepted);
-            let actual_text = count_lifetime_params(lifetimes.len());
-            struct_span_err!(self.tcx.sess, span, E0088,
-                             "too many lifetime parameters provided: \
-                              expected at most {}, found {}",
-                             expected_text, actual_text)
-                .span_label(span, format!("expected {}", expected_text))
-                .emit();
+            Some((struct_span_err!(self.tcx.sess, span, E0088,
+                                  "too many lifetime parameters provided: \
+                                  expected at most {}, found {}",
+                                  expected_text, actual_text), span))
         } else if lifetimes.len() < lt_accepted && !infer_lifetimes {
-            let expected_text = count_lifetime_params(lt_accepted);
-            let actual_text = count_lifetime_params(lifetimes.len());
-            struct_span_err!(self.tcx.sess, span, E0090,
-                             "too few lifetime parameters provided: \
-                              expected {}, found {}",
-                             expected_text, actual_text)
-                .span_label(span, format!("expected {}", expected_text))
-                .emit();
+            Some((struct_span_err!(self.tcx.sess, span, E0090,
+                                  "too few lifetime parameters provided: \
+                                  expected {}, found {}",
+                                  expected_text, actual_text), span))
+        } else {
+            None
+        } {
+            err.span_label(span, format!("expected {}", expected_text)).emit();
         }
     }
 
@@ -5088,13 +5113,11 @@ fn check_impl_trait(&self,
                         -> bool {
         let segment = segment.map(|(path_segment, generics)| {
             let explicit = !path_segment.infer_types;
-            let impl_trait = generics.params.iter().any(|param| {
-                match param.kind {
-                    ty::GenericParamDefKind::Type {
-                        synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
-                    } => true,
-                    _ => false,
-                }
+            let impl_trait = generics.params.iter().any(|param| match param.kind {
+                ty::GenericParamDefKind::Type {
+                    synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
+                } => true,
+                _ => false,
             });
 
             if explicit && impl_trait {
@@ -5155,34 +5178,39 @@ fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
 }
 
 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                       generics: &hir::Generics,
+                                       generics: &ty::Generics,
                                        ty: Ty<'tcx>) {
-    debug!("check_bounds_are_used(n_tps={}, ty={:?})",
-           generics.ty_params().count(),  ty);
-
-    // make a vector of booleans initially false, set to true when used
-    if generics.ty_params().next().is_none() { return; }
-    let mut tps_used = vec![false; generics.ty_params().count()];
+    let own_counts = generics.own_counts();
+    debug!("check_bounds_are_used(n_tps={}, ty={:?})", own_counts.types, ty);
 
-    let lifetime_count = generics.lifetimes().count();
+    if own_counts.types == 0 {
+        return;
+    }
+    // Make a vector of booleans initially false, set to true when used.
+    let mut types_used = vec![false; own_counts.types];
 
     for leaf_ty in ty.walk() {
-        if let ty::TyParam(ty::ParamTy {idx, ..}) = leaf_ty.sty {
+        if let ty::TyParam(ty::ParamTy { idx, .. }) = leaf_ty.sty {
             debug!("Found use of ty param num {}", idx);
-            tps_used[idx as usize - lifetime_count] = true;
+            types_used[idx as usize - own_counts.lifetimes] = true;
         } else if let ty::TyError = leaf_ty.sty {
-            // If there already another error, do not emit an error for not using a type Parameter
+            // If there is already another error, do not emit
+            // an error for not using a type Parameter.
             assert!(tcx.sess.err_count() > 0);
             return;
         }
     }
 
-    for (&used, param) in tps_used.iter().zip(generics.ty_params()) {
+    let types = generics.params.iter().filter(|param| match param.kind {
+        ty::GenericParamDefKind::Type { .. } => true,
+        _ => false,
+    });
+    for (&used, param) in types_used.iter().zip(types) {
         if !used {
-            struct_span_err!(tcx.sess, param.span, E0091,
-                "type parameter `{}` is unused",
-                param.name)
-                .span_label(param.span, "unused type parameter")
+            let id = tcx.hir.as_local_node_id(param.def_id).unwrap();
+            let span = tcx.hir.span(id);
+            struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name)
+                .span_label(span, "unused type parameter")
                 .emit();
         }
     }
index 7a2c38468e0448735811240adf0cbe4dc2ee2fe1..b61f09cbaea6d22b2789f476416768f0f039dd7a 100644 (file)
@@ -602,8 +602,8 @@ fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
 }
 
 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                    item: &hir::Item,
-                                    ast_generics: &hir::Generics)
+                                           item: &hir::Item,
+                                           hir_generics: &hir::Generics)
 {
     let item_def_id = tcx.hir.local_def_id(item.id);
     let ty = tcx.type_of(item_def_id);
@@ -631,11 +631,8 @@ fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             continue;
         }
 
-        let (span, name) = match ast_generics.params[index] {
-            hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
-            hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
-        };
-        report_bivariance(tcx, span, name);
+        let param = &hir_generics.params[index];
+        report_bivariance(tcx, param.span, param.name.name());
     }
 }
 
@@ -663,17 +660,12 @@ fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) {
     let generics = tcx.generics_of(def_id);
     let parent = tcx.generics_of(generics.parent.unwrap());
-    let impl_params: FxHashMap<_, _> =
-        parent.params.iter()
-                     .flat_map(|param| {
-                         match param.kind {
-                             GenericParamDefKind::Lifetime => None,
-                             GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
-                         }
-                     })
-                     .collect();
-
-    for method_param in generics.params.iter() {
+    let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
+        GenericParamDefKind::Lifetime => None,
+        GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
+    }).collect();
+
+    for method_param in &generics.params {
         match method_param.kind {
             // Shadowing is checked in resolve_lifetime.
             GenericParamDefKind::Lifetime => continue,
index 4aa876e85b69a5e2d0e1ee60e2c1f2cc43185fbb..5a442881a631582a539d625c0141ada151845590 100644 (file)
@@ -35,7 +35,9 @@ fn check_unsafety_coherence(&mut self,
 
             Some(trait_ref) => {
                 let trait_def = self.tcx.trait_def(trait_ref.def_id);
-                let unsafe_attr = impl_generics.and_then(|g| g.carries_unsafe_attr());
+                let unsafe_attr = impl_generics.and_then(|generics| {
+                    generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle")
+                });
                 match (trait_def.unsafety, unsafe_attr, unsafety, polarity) {
                     (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => {
                         span_err!(self.tcx.sess,
@@ -53,13 +55,14 @@ fn check_unsafety_coherence(&mut self,
                                   trait_ref);
                     }
 
-                    (Unsafety::Normal, Some(g), Unsafety::Normal, hir::ImplPolarity::Positive) =>
+                    (Unsafety::Normal, Some(attr_name), Unsafety::Normal,
+                        hir::ImplPolarity::Positive) =>
                     {
                         span_err!(self.tcx.sess,
                                   item.span,
                                   E0569,
                                   "requires an `unsafe impl` declaration due to `#[{}]` attribute",
-                                  g.attr_name());
+                                  attr_name);
                     }
 
                     (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative) => {
index 58e804fc13f2d8c9497f04672c4b528fa0fada04..4c849cad187abb30676b9e771d8cffad19652b17 100644 (file)
@@ -49,6 +49,7 @@
 use syntax_pos::{Span, DUMMY_SP};
 
 use rustc::hir::{self, map as hir_map, CodegenFnAttrs, CodegenFnAttrFlags, Unsafety};
+use rustc::hir::GenericParamKind;
 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
 use rustc::hir::def::{Def, CtorKind};
 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
@@ -113,10 +114,14 @@ fn visit_item(&mut self, item: &'tcx hir::Item) {
     }
 
     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
-        for param in generics.ty_params() {
-            if param.default.is_some() {
-                let def_id = self.tcx.hir.local_def_id(param.id);
-                self.tcx.type_of(def_id);
+        for param in &generics.params {
+            match param.kind {
+                hir::GenericParamKind::Lifetime { .. } => {}
+                hir::GenericParamKind::Type { default: Some(_), .. } => {
+                    let def_id = self.tcx.hir.local_def_id(param.id);
+                    self.tcx.type_of(def_id);
+                }
+                hir::GenericParamKind::Type { .. } => {}
             }
         }
         intravisit::walk_generics(self, generics);
@@ -308,9 +313,12 @@ fn type_parameter_bounds_in_generics(&self,
                                          -> Vec<ty::Predicate<'tcx>>
     {
         let from_ty_params =
-            ast_generics.ty_params()
-                .filter(|p| p.id == param_id)
-                .flat_map(|p| p.bounds.iter())
+            ast_generics.params.iter()
+                .filter_map(|param| match param.kind {
+                    GenericParamKind::Type { .. } if param.id == param_id => Some(&param.bounds),
+                    _ => None
+                })
+                .flat_map(|bounds| bounds.iter())
                 .flat_map(|b| predicates_from_bound(self, ty, b));
 
         let from_where_clauses =
@@ -739,10 +747,15 @@ fn has_late_bound_regions<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             outer_index: ty::INNERMOST,
             has_late_bound_regions: None,
         };
-        for lifetime in generics.lifetimes() {
-            let hir_id = tcx.hir.node_to_hir_id(lifetime.lifetime.id);
-            if tcx.is_late_bound(hir_id) {
-                return Some(lifetime.lifetime.span);
+        for param in &generics.params {
+            match param.kind {
+                GenericParamKind::Lifetime { .. } => {
+                    let hir_id = tcx.hir.node_to_hir_id(param.id);
+                    if tcx.is_late_bound(hir_id) {
+                        return Some(param.span);
+                    }
+                }
+                _ => {},
             }
         }
         visitor.visit_fn_decl(decl);
@@ -883,12 +896,12 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     let mut params: Vec<_> = opt_self.into_iter().collect();
 
     let early_lifetimes = early_bound_lifetimes_from_generics(tcx, ast_generics);
-    params.extend(early_lifetimes.enumerate().map(|(i, l)| {
+    params.extend(early_lifetimes.enumerate().map(|(i, param)| {
         ty::GenericParamDef {
-            name: l.lifetime.name.name().as_interned_str(),
+            name: param.name.name().as_interned_str(),
             index: own_start + i as u32,
-            def_id: tcx.hir.local_def_id(l.lifetime.id),
-            pure_wrt_drop: l.pure_wrt_drop,
+            def_id: tcx.hir.local_def_id(param.id),
+            pure_wrt_drop: param.pure_wrt_drop,
             kind: ty::GenericParamDefKind::Lifetime,
         }
     }));
@@ -898,34 +911,40 @@ fn generics_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 
     // Now create the real type parameters.
     let type_start = own_start - has_self as u32 + params.len() as u32;
-    params.extend(ast_generics.ty_params().enumerate().map(|(i, p)| {
-        if p.name == keywords::SelfType.name() {
-            span_bug!(p.span, "`Self` should not be the name of a regular parameter");
-        }
-
-        if !allow_defaults && p.default.is_some() {
-            if !tcx.features().default_type_parameter_fallback {
-                tcx.lint_node(
-                    lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
-                    p.id,
-                    p.span,
-                    &format!("defaults for type parameters are only allowed in `struct`, \
-                              `enum`, `type`, or `trait` definitions."));
+    let mut i = 0;
+    params.extend(ast_generics.params.iter().filter_map(|param| match param.kind {
+        GenericParamKind::Type { ref default, synthetic, .. } => {
+            if param.name.name() == keywords::SelfType.name() {
+                span_bug!(param.span,  "`Self` should not be the name of a regular parameter");
             }
-        }
 
-        ty::GenericParamDef {
-            index: type_start + i as u32,
-            name: p.name.as_interned_str(),
-            def_id: tcx.hir.local_def_id(p.id),
-            pure_wrt_drop: p.pure_wrt_drop,
-            kind: ty::GenericParamDefKind::Type {
-                has_default: p.default.is_some(),
-                object_lifetime_default:
-                    object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
-                synthetic: p.synthetic,
-            },
+            if !allow_defaults && default.is_some() {
+                if !tcx.features().default_type_parameter_fallback {
+                    tcx.lint_node(
+                        lint::builtin::INVALID_TYPE_PARAM_DEFAULT,
+                        param.id,
+                        param.span,
+                        &format!("defaults for type parameters are only allowed in \
+                                    `struct`, `enum`, `type`, or `trait` definitions."));
+                }
+            }
+
+            let ty_param = ty::GenericParamDef {
+                index: type_start + i as u32,
+                name: param.name.name().as_interned_str(),
+                def_id: tcx.hir.local_def_id(param.id),
+                pure_wrt_drop: param.pure_wrt_drop,
+                kind: ty::GenericParamDefKind::Type {
+                    has_default: default.is_some(),
+                    object_lifetime_default:
+                        object_lifetime_defaults.as_ref().map_or(rl::Set1::Empty, |o| o[i]),
+                    synthetic,
+                },
+            };
+            i += 1;
+            Some(ty_param)
         }
+        _ => None,
     }));
 
     // provide junk type parameter defs - the only place that
@@ -1047,7 +1066,24 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                 ItemExistential(hir::ExistTy { impl_trait_fn: None, .. }) => unimplemented!(),
                 // existential types desugared from impl Trait
                 ItemExistential(hir::ExistTy { impl_trait_fn: Some(owner), .. }) => {
-                    tcx.typeck_tables_of(owner).concrete_existential_types[&def_id]
+                    tcx.typeck_tables_of(owner).concrete_existential_types
+                        .get(&def_id)
+                        .cloned()
+                        .unwrap_or_else(|| {
+                            // This can occur if some error in the
+                            // owner fn prevented us from populating
+                            // the `concrete_existential_types` table.
+                            tcx.sess.delay_span_bug(
+                                DUMMY_SP,
+                                &format!(
+                                    "owner {:?} has no existential type for {:?} in its tables",
+                                    owner,
+                                    def_id,
+                                ),
+                            );
+
+                            tcx.types.err
+                        })
                 },
                 ItemTrait(..) | ItemTraitAlias(..) |
                 ItemMod(..) |
@@ -1119,8 +1155,13 @@ fn type_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             }
         },
 
-        NodeTyParam(&hir::TyParam { default: Some(ref ty), .. }) => {
-            icx.to_ty(ty)
+        NodeGenericParam(param) => {
+            match param.kind {
+                hir::GenericParamKind::Type { default: Some(ref ty), .. } => {
+                    icx.to_ty(ty)
+                }
+                _ => bug!("unexpected non-type NodeGenericParam"),
+            }
         }
 
         x => {
@@ -1225,7 +1266,7 @@ fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 
 // Is it marked with ?Sized
 fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
-                                ast_bounds: &[hir::TyParamBound],
+                                ast_bounds: &[hir::GenericBound],
                                 span: Span) -> bool
 {
     let tcx = astconv.tcx();
@@ -1233,7 +1274,7 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
     // Try to find an unbound in bounds.
     let mut unbound = None;
     for ab in ast_bounds {
-        if let &hir::TraitTyParamBound(ref ptr, hir::TraitBoundModifier::Maybe) = ab  {
+        if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab  {
             if unbound.is_none() {
                 unbound = Some(ptr.trait_ref.clone());
             } else {
@@ -1274,15 +1315,16 @@ fn is_unsized<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
 /// `resolve_lifetime::early_bound_lifetimes`.
 fn early_bound_lifetimes_from_generics<'a, 'tcx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    ast_generics: &'a hir::Generics)
-    -> impl Iterator<Item=&'a hir::LifetimeDef> + Captures<'tcx>
+    generics: &'a hir::Generics)
+    -> impl Iterator<Item=&'a hir::GenericParam> + Captures<'tcx>
 {
-    ast_generics
-        .lifetimes()
-        .filter(move |l| {
-            let hir_id = tcx.hir.node_to_hir_id(l.lifetime.id);
+    generics.params.iter().filter(move |param| match param.kind {
+        GenericParamKind::Lifetime { .. } => {
+            let hir_id = tcx.hir.node_to_hir_id(param.id);
             !tcx.is_late_bound(hir_id)
-        })
+        }
+        _ => false,
+    })
 }
 
 fn predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
@@ -1410,31 +1452,42 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
     let mut index = parent_count + has_own_self as u32;
     for param in early_bound_lifetimes_from_generics(tcx, ast_generics) {
         let region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
-            def_id: tcx.hir.local_def_id(param.lifetime.id),
+            def_id: tcx.hir.local_def_id(param.id),
             index,
-            name: param.lifetime.name.name().as_interned_str(),
+            name: param.name.name().as_interned_str(),
         }));
         index += 1;
 
-        for bound in &param.bounds {
-            let bound_region = AstConv::ast_region_to_region(&icx, bound, None);
-            let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound_region));
-            predicates.push(outlives.to_predicate());
+        match param.kind {
+            GenericParamKind::Lifetime { .. } => {
+                param.bounds.iter().for_each(|bound| match bound {
+                    hir::GenericBound::Outlives(lt) => {
+                        let bound = AstConv::ast_region_to_region(&icx, &lt, None);
+                        let outlives = ty::Binder::bind(ty::OutlivesPredicate(region, bound));
+                        predicates.push(outlives.to_predicate());
+                    }
+                    _ => bug!(),
+                });
+            },
+            _ => bug!(),
         }
     }
 
     // Collect the predicates that were written inline by the user on each
     // type parameter (e.g., `<T:Foo>`).
-    for param in ast_generics.ty_params() {
-        let param_ty = ty::ParamTy::new(index, param.name.as_interned_str()).to_ty(tcx);
-        index += 1;
-
-        let bounds = compute_bounds(&icx,
-                                    param_ty,
-                                    &param.bounds,
-                                    SizedByDefault::Yes,
-                                    param.span);
-        predicates.extend(bounds.predicates(tcx, param_ty));
+    for param in &ast_generics.params {
+        match param.kind {
+            GenericParamKind::Type { .. } => {
+                let name = param.name.name().as_interned_str();
+                let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
+                index += 1;
+
+                let sized = SizedByDefault::Yes;
+                let bounds = compute_bounds(&icx, param_ty, &param.bounds, sized, param.span);
+                predicates.extend(bounds.predicates(tcx, param_ty));
+            }
+            _ => {}
+        }
     }
 
     // Add in the bounds that appear in the where-clause
@@ -1446,7 +1499,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
 
                 for bound in bound_pred.bounds.iter() {
                     match bound {
-                        &hir::TyParamBound::TraitTyParamBound(ref poly_trait_ref, _) => {
+                        &hir::GenericBound::Trait(ref poly_trait_ref, _) => {
                             let mut projections = Vec::new();
 
                             let trait_ref =
@@ -1462,7 +1515,7 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                             }
                         }
 
-                        &hir::TyParamBound::RegionTyParamBound(ref lifetime) => {
+                        &hir::GenericBound::Outlives(ref lifetime) => {
                             let region = AstConv::ast_region_to_region(&icx,
                                                                        lifetime,
                                                                        None);
@@ -1476,7 +1529,12 @@ pub fn explicit_predicates_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
             &hir::WherePredicate::RegionPredicate(ref region_pred) => {
                 let r1 = AstConv::ast_region_to_region(&icx, &region_pred.lifetime, None);
                 for bound in &region_pred.bounds {
-                    let r2 = AstConv::ast_region_to_region(&icx, bound, None);
+                    let r2 = match bound {
+                        hir::GenericBound::Outlives(lt) => {
+                            AstConv::ast_region_to_region(&icx, lt, None)
+                        }
+                        _ => bug!(),
+                    };
                     let pred = ty::Binder::bind(ty::OutlivesPredicate(r1, r2));
                     predicates.push(ty::Predicate::RegionOutlives(pred))
                 }
@@ -1541,7 +1599,7 @@ pub enum SizedByDefault { Yes, No, }
 /// built-in trait (formerly known as kind): Send.
 pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
                                         param_ty: Ty<'tcx>,
-                                        ast_bounds: &[hir::TyParamBound],
+                                        ast_bounds: &[hir::GenericBound],
                                         sized_by_default: SizedByDefault,
                                         span: Span)
                                         -> Bounds<'tcx>
@@ -1550,22 +1608,16 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
     let mut trait_bounds = vec![];
     for ast_bound in ast_bounds {
         match *ast_bound {
-            hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
-                trait_bounds.push(b);
-            }
-            hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
-            hir::RegionTyParamBound(ref l) => {
-                region_bounds.push(l);
-            }
+            hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => trait_bounds.push(b),
+            hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
+            hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
         }
     }
 
     let mut projection_bounds = vec![];
 
     let mut trait_bounds: Vec<_> = trait_bounds.iter().map(|&bound| {
-        astconv.instantiate_poly_trait_ref(bound,
-                                           param_ty,
-                                           &mut projection_bounds)
+        astconv.instantiate_poly_trait_ref(bound, param_ty, &mut projection_bounds)
     }).collect();
 
     let region_bounds = region_bounds.into_iter().map(|r| {
@@ -1588,18 +1640,18 @@ pub fn compute_bounds<'gcx: 'tcx, 'tcx>(astconv: &AstConv<'gcx, 'tcx>,
     }
 }
 
-/// Converts a specific TyParamBound from the AST into a set of
+/// Converts a specific GenericBound from the AST into a set of
 /// predicates that apply to the self-type. A vector is returned
 /// because this can be anywhere from 0 predicates (`T:?Sized` adds no
 /// predicates) to 1 (`T:Foo`) to many (`T:Bar<X=i32>` adds `T:Bar`
 /// and `<T as Bar>::X == i32`).
 fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>,
                                param_ty: Ty<'tcx>,
-                               bound: &hir::TyParamBound)
+                               bound: &hir::GenericBound)
                                -> Vec<ty::Predicate<'tcx>>
 {
     match *bound {
-        hir::TraitTyParamBound(ref tr, hir::TraitBoundModifier::None) => {
+        hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => {
             let mut projections = Vec::new();
             let pred = astconv.instantiate_poly_trait_ref(tr,
                                                           param_ty,
@@ -1609,14 +1661,12 @@ fn predicates_from_bound<'tcx>(astconv: &AstConv<'tcx, 'tcx>,
                        .chain(Some(pred.to_predicate()))
                        .collect()
         }
-        hir::RegionTyParamBound(ref lifetime) => {
+        hir::GenericBound::Outlives(ref lifetime) => {
             let region = astconv.ast_region_to_region(lifetime, None);
             let pred = ty::Binder::bind(ty::OutlivesPredicate(param_ty, region));
             vec![ty::Predicate::TypeOutlives(pred)]
         }
-        hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {
-            Vec::new()
-        }
+        hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => vec![],
     }
 }
 
index da54eeabdb97be3727f73dc4df57c24731b5c5b8..3f7e3529e9648f713430dd29216aec29ab623802 100644 (file)
@@ -1501,12 +1501,12 @@ struct Foo {
 "##,
 
 E0131: r##"
-It is not possible to define `main` with type parameters, or even with function
-parameters. When `main` is present, it must take no arguments and return `()`.
+It is not possible to define `main` with generic parameters.
+When `main` is present, it must take no arguments and return `()`.
 Erroneous code example:
 
 ```compile_fail,E0131
-fn main<T>() { // error: main function is not allowed to have type parameters
+fn main<T>() { // error: main function is not allowed to have generic parameters
 }
 ```
 "##,
index 80f57adf580bfc6b5743025a4a812c2c14effd55..dcc5fa53d2f420f9c0e75c6cc0464d00b1f37781 100644 (file)
@@ -76,6 +76,7 @@
 #![feature(crate_visibility_modifier)]
 #![feature(from_ref)]
 #![feature(exhaustive_patterns)]
+#![feature(iterator_find_map)]
 #![feature(quote)]
 #![feature(refcell_replace_swap)]
 #![feature(rustc_diagnostic_macros)]
@@ -190,16 +191,9 @@ fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                         hir::ItemFn(.., ref generics, _) => {
                             let mut error = false;
                             if !generics.params.is_empty() {
-                                let param_type = if generics.is_lt_parameterized() {
-                                    "lifetime"
-                                } else {
-                                    "type"
-                                };
-                                let msg =
-                                    format!("`main` function is not allowed to have {} parameters",
-                                            param_type);
-                                let label =
-                                    format!("`main` cannot have {} parameters", param_type);
+                                let msg = format!("`main` function is not allowed to have generic \
+                                                   parameters");
+                                let label = format!("`main` cannot have generic parameters");
                                 struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg)
                                     .span_label(generics.span, label)
                                     .emit();
index 96a2194eeeefda76809b53d0d986462a17ca6e71..126fa7fb320348b78a3958d9a31867b86bc0729e 100644 (file)
@@ -9,5 +9,5 @@ path = "lib.rs"
 
 [dependencies]
 pulldown-cmark = { version = "0.1.2", default-features = false }
-tempdir = "0.3"
 minifier = "0.0.11"
+tempfile = "3"
index da749fca2a953524f619a2ea94286a97acd2f0c9..5c09da90491d064f6001723f0080d4e1171640e4 100644 (file)
@@ -244,34 +244,32 @@ fn get_auto_trait_impl_for<F>(
         None
     }
 
-    fn generics_to_path_params(&self, generics: ty::Generics) -> hir::PathParameters {
-        let mut lifetimes = vec![];
-        let mut types = vec![];
+    fn generics_to_path_params(&self, generics: ty::Generics) -> hir::GenericArgs {
+        let mut args = vec![];
 
         for param in generics.params.iter() {
             match param.kind {
                 ty::GenericParamDefKind::Lifetime => {
                     let name = if param.name == "" {
-                        hir::LifetimeName::Static
+                        hir::ParamName::Plain(keywords::StaticLifetime.name())
                     } else {
-                        hir::LifetimeName::Name(param.name.as_symbol())
+                        hir::ParamName::Plain(param.name.as_symbol())
                     };
 
-                    lifetimes.push(hir::Lifetime {
+                    args.push(hir::GenericArg::Lifetime(hir::Lifetime {
                         id: ast::DUMMY_NODE_ID,
                         span: DUMMY_SP,
-                        name,
-                    });
+                        name: hir::LifetimeName::Param(name),
+                    }));
                 }
                 ty::GenericParamDefKind::Type {..} => {
-                    types.push(P(self.ty_param_to_ty(param.clone())));
+                    args.push(hir::GenericArg::Type(P(self.ty_param_to_ty(param.clone()))));
                 }
             }
         }
 
-        hir::PathParameters {
-            lifetimes: HirVec::from_vec(lifetimes),
-            types: HirVec::from_vec(types),
+        hir::GenericArgs {
+            args: HirVec::from_vec(args),
             bindings: HirVec::new(),
             parenthesized: false,
         }
@@ -488,11 +486,8 @@ fn handle_lifetimes<'cx>(
             .iter()
             .flat_map(|(name, lifetime)| {
                 let empty = Vec::new();
-                let bounds: FxHashSet<Lifetime> = finished
-                    .get(name)
-                    .unwrap_or(&empty)
-                    .iter()
-                    .map(|region| self.get_lifetime(region, names_map))
+                let bounds: FxHashSet<GenericBound> = finished.get(name).unwrap_or(&empty).iter()
+                    .map(|region| GenericBound::Outlives(self.get_lifetime(region, names_map)))
                     .collect();
 
                 if bounds.is_empty() {
@@ -523,7 +518,10 @@ fn extract_for_generics<'b, 'c, 'd>(
                         // We only care about late bound regions, as we need to add them
                         // to the 'for<>' section
                         &ty::ReLateBound(_, ty::BoundRegion::BrNamed(_, name)) => {
-                            Some(GenericParamDef::Lifetime(Lifetime(name.to_string())))
+                            Some(GenericParamDef {
+                                name: name.to_string(),
+                                kind: GenericParamDefKind::Lifetime,
+                            })
                         }
                         &ty::ReVar(_) | &ty::ReEarlyBound(_) => None,
                         _ => panic!("Unexpected region type {:?}", r),
@@ -535,9 +533,9 @@ fn extract_for_generics<'b, 'c, 'd>(
 
     fn make_final_bounds<'b, 'c, 'cx>(
         &self,
-        ty_to_bounds: FxHashMap<Type, FxHashSet<TyParamBound>>,
+        ty_to_bounds: FxHashMap<Type, FxHashSet<GenericBound>>,
         ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)>,
-        lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<Lifetime>>,
+        lifetime_to_bounds: FxHashMap<Lifetime, FxHashSet<GenericBound>>,
     ) -> Vec<WherePredicate> {
         ty_to_bounds
             .into_iter()
@@ -555,9 +553,9 @@ fn make_final_bounds<'b, 'c, 'cx>(
                             let mut new_path = path.clone();
                             let last_segment = new_path.segments.pop().unwrap();
 
-                            let (old_input, old_output) = match last_segment.params {
-                                PathParameters::AngleBracketed { types, .. } => (types, None),
-                                PathParameters::Parenthesized { inputs, output, .. } => {
+                            let (old_input, old_output) = match last_segment.args {
+                                GenericArgs::AngleBracketed { types, .. } => (types, None),
+                                GenericArgs::Parenthesized { inputs, output, .. } => {
                                     (inputs, output)
                                 }
                             };
@@ -569,14 +567,14 @@ fn make_final_bounds<'b, 'c, 'cx>(
                                 );
                             }
 
-                            let new_params = PathParameters::Parenthesized {
+                            let new_params = GenericArgs::Parenthesized {
                                 inputs: old_input,
                                 output,
                             };
 
                             new_path.segments.push(PathSegment {
                                 name: last_segment.name,
-                                params: new_params,
+                                args: new_params,
                             });
 
                             Type::ResolvedPath {
@@ -588,7 +586,7 @@ fn make_final_bounds<'b, 'c, 'cx>(
                         }
                         _ => panic!("Unexpected data: {:?}, {:?}", ty, data),
                     };
-                    bounds.insert(TyParamBound::TraitBound(
+                    bounds.insert(GenericBound::TraitBound(
                         PolyTrait {
                             trait_: new_ty,
                             generic_params: poly_trait.generic_params,
@@ -614,7 +612,7 @@ fn make_final_bounds<'b, 'c, 'cx>(
                     .filter(|&(_, ref bounds)| !bounds.is_empty())
                     .map(|(lifetime, bounds)| {
                         let mut bounds_vec = bounds.into_iter().collect();
-                        self.sort_where_lifetimes(&mut bounds_vec);
+                        self.sort_where_bounds(&mut bounds_vec);
                         WherePredicate::RegionPredicate {
                             lifetime,
                             bounds: bounds_vec,
@@ -731,7 +729,7 @@ fn param_env_to_generics<'b, 'c, 'cx>(
                         // later
 
                         let is_fn = match &mut b {
-                            &mut TyParamBound::TraitBound(ref mut p, _) => {
+                            &mut GenericBound::TraitBound(ref mut p, _) => {
                                 // Insert regions into the for_generics hash map first, to ensure
                                 // that we don't end up with duplicate bounds (e.g. for<'b, 'b>)
                                 for_generics.extend(p.generic_params.clone());
@@ -793,13 +791,13 @@ fn param_env_to_generics<'b, 'c, 'cx>(
 
                                     // FIXME: Remove this scope when NLL lands
                                     {
-                                        let params =
-                                            &mut new_trait_path.segments.last_mut().unwrap().params;
+                                        let args =
+                                            &mut new_trait_path.segments.last_mut().unwrap().args;
 
-                                        match params {
+                                        match args {
                                             // Convert somethiung like '<T as Iterator::Item> = u8'
                                             // to 'T: Iterator<Item=u8>'
-                                            &mut PathParameters::AngleBracketed {
+                                            &mut GenericArgs::AngleBracketed {
                                                 ref mut bindings,
                                                 ..
                                             } => {
@@ -808,7 +806,7 @@ fn param_env_to_generics<'b, 'c, 'cx>(
                                                     ty: rhs,
                                                 });
                                             }
-                                            &mut PathParameters::Parenthesized { .. } => {
+                                            &mut GenericArgs::Parenthesized { .. } => {
                                                 existing_predicates.push(
                                                     WherePredicate::EqPredicate {
                                                         lhs: lhs.clone(),
@@ -825,7 +823,7 @@ fn param_env_to_generics<'b, 'c, 'cx>(
                                         .entry(*ty.clone())
                                         .or_insert_with(|| FxHashSet());
 
-                                    bounds.insert(TyParamBound::TraitBound(
+                                    bounds.insert(GenericBound::TraitBound(
                                         PolyTrait {
                                             trait_: Type::ResolvedPath {
                                                 path: new_trait_path,
@@ -842,7 +840,7 @@ fn param_env_to_generics<'b, 'c, 'cx>(
                                     // that we don't see a
                                     // duplicate bound like `T: Iterator + Iterator<Item=u8>`
                                     // on the docs page.
-                                    bounds.remove(&TyParamBound::TraitBound(
+                                    bounds.remove(&GenericBound::TraitBound(
                                         PolyTrait {
                                             trait_: *trait_.clone(),
                                             generic_params: Vec::new(),
@@ -869,19 +867,17 @@ fn param_env_to_generics<'b, 'c, 'cx>(
 
         existing_predicates.extend(final_bounds);
 
-        for p in generic_params.iter_mut() {
-            match p {
-                &mut GenericParamDef::Type(ref mut ty) => {
-                    // We never want something like 'impl<T=Foo>'
-                    ty.default.take();
-
-                    let generic_ty = Type::Generic(ty.name.clone());
-
+        for param in generic_params.iter_mut() {
+            match param.kind {
+                GenericParamDefKind::Type { ref mut default, ref mut bounds, .. } => {
+                    // We never want something like `impl<T=Foo>`.
+                    default.take();
+                    let generic_ty = Type::Generic(param.name.clone());
                     if !has_sized.contains(&generic_ty) {
-                        ty.bounds.insert(0, TyParamBound::maybe_sized(self.cx));
+                        bounds.insert(0, GenericBound::maybe_sized(self.cx));
                     }
                 }
-                GenericParamDef::Lifetime(_) => {}
+                GenericParamDefKind::Lifetime => {}
             }
         }
 
@@ -912,15 +908,7 @@ fn sort_where_predicates(&self, mut predicates: &mut Vec<WherePredicate>) {
     // both for visual consistency between 'rustdoc' runs, and to
     // make writing tests much easier
     #[inline]
-    fn sort_where_bounds(&self, mut bounds: &mut Vec<TyParamBound>) {
-        // We should never have identical bounds - and if we do,
-        // they're visually identical as well. Therefore, using
-        // an unstable sort is fine.
-        self.unstable_debug_sort(&mut bounds);
-    }
-
-    #[inline]
-    fn sort_where_lifetimes(&self, mut bounds: &mut Vec<Lifetime>) {
+    fn sort_where_bounds(&self, mut bounds: &mut Vec<GenericBound>) {
         // We should never have identical bounds - and if we do,
         // they're visually identical as well. Therefore, using
         // an unstable sort is fine.
@@ -940,7 +928,7 @@ fn sort_where_lifetimes(&self, mut bounds: &mut Vec<Lifetime>) {
     // to end users, it makes writing tests much more difficult, as predicates
     // can appear in any order in the final result.
     //
-    // To solve this problem, we sort WherePredicates and TyParamBounds
+    // To solve this problem, we sort WherePredicates and GenericBounds
     // by their Debug string. The thing to keep in mind is that we don't really
     // care what the final order is - we're synthesizing an impl or bound
     // ourselves, so any order can be considered equally valid. By sorting the
@@ -950,7 +938,7 @@ fn sort_where_lifetimes(&self, mut bounds: &mut Vec<Lifetime>) {
     // Using the Debug impementation for sorting prevents us from needing to
     // write quite a bit of almost entirely useless code (e.g. how should two
     // Types be sorted relative to each other). It also allows us to solve the
-    // problem for both WherePredicates and TyParamBounds at the same time. This
+    // problem for both WherePredicates and GenericBounds at the same time. This
     // approach is probably somewhat slower, but the small number of items
     // involved (impls rarely have more than a few bounds) means that it
     // shouldn't matter in practice.
index 80eb2d1e214fbd9146574d9ec49240a4ae8c295b..114cb0e455d9aa057a7e950cce502b0a658123db 100644 (file)
@@ -374,8 +374,8 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
     let polarity = tcx.impl_polarity(did);
     let trait_ = associated_trait.clean(cx).map(|bound| {
         match bound {
-            clean::TraitBound(polyt, _) => polyt.trait_,
-            clean::RegionBound(..) => unreachable!(),
+            clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
+            clean::GenericBound::Outlives(..) => unreachable!(),
         }
     });
     if trait_.def_id() == tcx.lang_items().deref_trait() {
@@ -387,9 +387,9 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
 
     let provided = trait_.def_id().map(|did| {
         tcx.provided_trait_methods(did)
-            .into_iter()
-            .map(|meth| meth.name.to_string())
-            .collect()
+           .into_iter()
+           .map(|meth| meth.name.to_string())
+           .collect()
     }).unwrap_or(FxHashSet());
 
     ret.push(clean::Item {
@@ -474,7 +474,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean:
             } if *s == "Self" => {
                 bounds.retain(|bound| {
                     match *bound {
-                        clean::TyParamBound::TraitBound(clean::PolyTrait {
+                        clean::GenericBound::TraitBound(clean::PolyTrait {
                             trait_: clean::ResolvedPath { did, .. },
                             ..
                         }, _) => did != trait_did,
@@ -505,7 +505,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean:
 /// the metadata for a crate, so we want to separate those out and create a new
 /// list of explicit supertrait bounds to render nicely.
 fn separate_supertrait_bounds(mut g: clean::Generics)
-                              -> (clean::Generics, Vec<clean::TyParamBound>) {
+                              -> (clean::Generics, Vec<clean::GenericBound>) {
     let mut ty_bounds = Vec::new();
     g.where_predicates.retain(|pred| {
         match *pred {
index 852a4479199df6f5f75741b421e6037aaaad771b..0979c3d85587d2ed2852f7a8b804ef8b550b78f8 100644 (file)
@@ -14,7 +14,6 @@
 pub use self::Type::*;
 pub use self::Mutability::*;
 pub use self::ItemEnum::*;
-pub use self::TyParamBound::*;
 pub use self::SelfTy::*;
 pub use self::FunctionRetTy::*;
 pub use self::Visibility::{Public, Inherited};
 use rustc::ty::fold::TypeFolder;
 use rustc::middle::lang_items;
 use rustc::mir::interpret::GlobalId;
-use rustc::hir::{self, HirVec};
+use rustc::hir::{self, GenericArg, HirVec};
 use rustc::hir::def::{self, Def, CtorKind};
 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
 use rustc::hir::def_id::DefIndexAddressSpace;
 use rustc::ty::subst::Substs;
-use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind, GenericParamCount};
+use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind};
 use rustc::middle::stability;
 use rustc::util::nodemap::{FxHashMap, FxHashSet};
 use rustc_typeck::hir_ty_to_ty;
@@ -532,7 +531,7 @@ pub enum ItemEnum {
     MacroItem(Macro),
     PrimitiveItem(PrimitiveType),
     AssociatedConstItem(Type, Option<String>),
-    AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
+    AssociatedTypeItem(Vec<GenericBound>, Option<Type>),
     /// An item that has been stripped by a rustdoc pass
     StrippedItem(Box<ItemEnum>),
     KeywordItem(String),
@@ -1458,61 +1457,19 @@ fn clean(&self, cx: &DocContext) -> Attributes {
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
-pub struct TyParam {
-    pub name: String,
-    pub did: DefId,
-    pub bounds: Vec<TyParamBound>,
-    pub default: Option<Type>,
-    pub synthetic: Option<hir::SyntheticTyParamKind>,
-}
-
-impl Clean<TyParam> for hir::TyParam {
-    fn clean(&self, cx: &DocContext) -> TyParam {
-        TyParam {
-            name: self.name.clean(cx),
-            did: cx.tcx.hir.local_def_id(self.id),
-            bounds: self.bounds.clean(cx),
-            default: self.default.clean(cx),
-            synthetic: self.synthetic,
-        }
-    }
+pub enum GenericBound {
+    TraitBound(PolyTrait, hir::TraitBoundModifier),
+    Outlives(Lifetime),
 }
 
-impl<'tcx> Clean<TyParam> for ty::GenericParamDef {
-    fn clean(&self, cx: &DocContext) -> TyParam {
-        cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
-        let has_default = match self.kind {
-            ty::GenericParamDefKind::Type { has_default, .. } => has_default,
-            _ => panic!("tried to convert a non-type GenericParamDef as a type")
-        };
-        TyParam {
-            name: self.name.clean(cx),
-            did: self.def_id,
-            bounds: vec![], // these are filled in from the where-clauses
-            default: if has_default {
-                Some(cx.tcx.type_of(self.def_id).clean(cx))
-            } else {
-                None
-            },
-            synthetic: None,
-        }
-    }
-}
-
-#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
-pub enum TyParamBound {
-    RegionBound(Lifetime),
-    TraitBound(PolyTrait, hir::TraitBoundModifier)
-}
-
-impl TyParamBound {
-    fn maybe_sized(cx: &DocContext) -> TyParamBound {
+impl GenericBound {
+    fn maybe_sized(cx: &DocContext) -> GenericBound {
         let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
         let empty = cx.tcx.intern_substs(&[]);
         let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
             Some(did), false, vec![], empty);
         inline::record_extern_fqn(cx, did, TypeKind::Trait);
-        TraitBound(PolyTrait {
+        GenericBound::TraitBound(PolyTrait {
             trait_: ResolvedPath {
                 path,
                 typarams: None,
@@ -1525,7 +1482,7 @@ fn maybe_sized(cx: &DocContext) -> TyParamBound {
 
     fn is_sized_bound(&self, cx: &DocContext) -> bool {
         use rustc::hir::TraitBoundModifier as TBM;
-        if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
+        if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
             if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
                 return true;
             }
@@ -1534,7 +1491,7 @@ fn is_sized_bound(&self, cx: &DocContext) -> bool {
     }
 
     fn get_poly_trait(&self) -> Option<PolyTrait> {
-        if let TyParamBound::TraitBound(ref p, _) = *self {
+        if let GenericBound::TraitBound(ref p, _) = *self {
             return Some(p.clone())
         }
         None
@@ -1542,24 +1499,26 @@ fn get_poly_trait(&self) -> Option<PolyTrait> {
 
     fn get_trait_type(&self) -> Option<Type> {
 
-        if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
+        if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
             return Some(trait_.clone());
         }
         None
     }
 }
 
-impl Clean<TyParamBound> for hir::TyParamBound {
-    fn clean(&self, cx: &DocContext) -> TyParamBound {
+impl Clean<GenericBound> for hir::GenericBound {
+    fn clean(&self, cx: &DocContext) -> GenericBound {
         match *self {
-            hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
-            hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
+            hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
+            hir::GenericBound::Trait(ref t, modifier) => {
+                GenericBound::TraitBound(t.clean(cx), modifier)
+            }
         }
     }
 }
 
-fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
-                        bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
+fn external_generic_args(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
+                        bindings: Vec<TypeBinding>, substs: &Substs) -> GenericArgs {
     let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
     let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
 
@@ -1570,7 +1529,7 @@ fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: boo
             let inputs = match types[0].sty {
                 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
                 _ => {
-                    return PathParameters::AngleBracketed {
+                    return GenericArgs::AngleBracketed {
                         lifetimes,
                         types: types.clean(cx),
                         bindings,
@@ -1583,13 +1542,13 @@ fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: boo
             //     ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
             //     _ => Some(types[1].clean(cx))
             // };
-            PathParameters::Parenthesized {
+            GenericArgs::Parenthesized {
                 inputs,
                 output,
             }
         },
         _ => {
-            PathParameters::AngleBracketed {
+            GenericArgs::AngleBracketed {
                 lifetimes,
                 types: types.clean(cx),
                 bindings,
@@ -1607,13 +1566,13 @@ fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self
         def: Def::Err,
         segments: vec![PathSegment {
             name: name.to_string(),
-            params: external_path_params(cx, trait_did, has_self, bindings, substs)
+            args: external_generic_args(cx, trait_did, has_self, bindings, substs)
         }],
     }
 }
 
-impl<'a, 'tcx> Clean<TyParamBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
-    fn clean(&self, cx: &DocContext) -> TyParamBound {
+impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
+    fn clean(&self, cx: &DocContext) -> GenericBound {
         let (trait_ref, ref bounds) = *self;
         inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
         let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(),
@@ -1629,8 +1588,11 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
                     if let ty::TyRef(ref reg, _, _) = ty_s.sty {
                         if let &ty::RegionKind::ReLateBound(..) = *reg {
                             debug!("  hit an ReLateBound {:?}", reg);
-                            if let Some(lt) = reg.clean(cx) {
-                                late_bounds.push(GenericParamDef::Lifetime(lt));
+                            if let Some(Lifetime(name)) = reg.clean(cx) {
+                                late_bounds.push(GenericParamDef {
+                                    name,
+                                    kind: GenericParamDefKind::Lifetime,
+                                });
                             }
                         }
                     }
@@ -1638,7 +1600,7 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
             }
         }
 
-        TraitBound(
+        GenericBound::TraitBound(
             PolyTrait {
                 trait_: ResolvedPath {
                     path,
@@ -1653,18 +1615,17 @@ fn clean(&self, cx: &DocContext) -> TyParamBound {
     }
 }
 
-impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
-    fn clean(&self, cx: &DocContext) -> TyParamBound {
+impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
+    fn clean(&self, cx: &DocContext) -> GenericBound {
         (self, vec![]).clean(cx)
     }
 }
 
-impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
-    fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
+impl<'tcx> Clean<Option<Vec<GenericBound>>> for Substs<'tcx> {
+    fn clean(&self, cx: &DocContext) -> Option<Vec<GenericBound>> {
         let mut v = Vec::new();
-        v.extend(self.regions().filter_map(|r| r.clean(cx))
-                     .map(RegionBound));
-        v.extend(self.types().map(|t| TraitBound(PolyTrait {
+        v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
+        v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
             trait_: t.clean(cx),
             generic_params: Vec::new(),
         }, hir::TraitBoundModifier::None)));
@@ -1707,18 +1668,26 @@ fn clean(&self, cx: &DocContext) -> Lifetime {
     }
 }
 
-impl Clean<Lifetime> for hir::LifetimeDef {
+impl Clean<Lifetime> for hir::GenericParam {
     fn clean(&self, _: &DocContext) -> Lifetime {
-        if self.bounds.len() > 0 {
-            let mut s = format!("{}: {}",
-                                self.lifetime.name.name(),
-                                self.bounds[0].name.name());
-            for bound in self.bounds.iter().skip(1) {
-                s.push_str(&format!(" + {}", bound.name.name()));
+        match self.kind {
+            hir::GenericParamKind::Lifetime { .. } => {
+                if self.bounds.len() > 0 {
+                    let mut bounds = self.bounds.iter().map(|bound| match bound {
+                        hir::GenericBound::Outlives(lt) => lt,
+                        _ => panic!(),
+                    });
+                    let name = bounds.next().unwrap().name.name();
+                    let mut s = format!("{}: {}", self.name.name(), name);
+                    for bound in bounds {
+                        s.push_str(&format!(" + {}", bound.name.name()));
+                    }
+                    Lifetime(s)
+                } else {
+                    Lifetime(self.name.name().to_string())
+                }
             }
-            Lifetime(s)
-        } else {
-            Lifetime(self.lifetime.name.name().to_string())
+            _ => panic!(),
         }
     }
 }
@@ -1751,8 +1720,8 @@ fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
 pub enum WherePredicate {
-    BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
-    RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
+    BoundPredicate { ty: Type, bounds: Vec<GenericBound> },
+    RegionPredicate { lifetime: Lifetime, bounds: Vec<GenericBound> },
     EqPredicate { lhs: Type, rhs: Type },
 }
 
@@ -1822,7 +1791,7 @@ fn clean(&self, cx: &DocContext) -> WherePredicate {
         let ty::OutlivesPredicate(ref a, ref b) = *self;
         WherePredicate::RegionPredicate {
             lifetime: a.clean(cx).unwrap(),
-            bounds: vec![b.clean(cx).unwrap()]
+            bounds: vec![GenericBound::Outlives(b.clean(cx).unwrap())]
         }
     }
 }
@@ -1833,7 +1802,7 @@ fn clean(&self, cx: &DocContext) -> WherePredicate {
 
         WherePredicate::BoundPredicate {
             ty: ty.clean(cx),
-            bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
+            bounds: vec![GenericBound::Outlives(lt.clean(cx).unwrap())]
         }
     }
 }
@@ -1850,10 +1819,8 @@ fn clean(&self, cx: &DocContext) -> WherePredicate {
 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
     fn clean(&self, cx: &DocContext) -> Type {
         let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
-            TyParamBound::TraitBound(t, _) => t.trait_,
-            TyParamBound::RegionBound(_) => {
-                panic!("cleaning a trait got a region")
-            }
+            GenericBound::TraitBound(t, _) => t.trait_,
+            GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
         };
         Type::QPath {
             name: cx.tcx.associated_item(self.item_def_id).name.clean(cx),
@@ -1864,25 +1831,95 @@ fn clean(&self, cx: &DocContext) -> Type {
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
-pub enum GenericParamDef {
-    Lifetime(Lifetime),
-    Type(TyParam),
+pub enum GenericParamDefKind {
+    Lifetime,
+    Type {
+        did: DefId,
+        bounds: Vec<GenericBound>,
+        default: Option<Type>,
+        synthetic: Option<hir::SyntheticTyParamKind>,
+    },
+}
+
+#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
+pub struct GenericParamDef {
+    pub name: String,
+
+    pub kind: GenericParamDefKind,
 }
 
 impl GenericParamDef {
     pub fn is_synthetic_type_param(&self) -> bool {
-        match self {
-            GenericParamDef::Type(ty) => ty.synthetic.is_some(),
-            GenericParamDef::Lifetime(_) => false,
+        match self.kind {
+            GenericParamDefKind::Lifetime => false,
+            GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(),
+        }
+    }
+}
+
+impl<'tcx> Clean<GenericParamDef> for ty::GenericParamDef {
+    fn clean(&self, cx: &DocContext) -> GenericParamDef {
+        let (name, kind) = match self.kind {
+            ty::GenericParamDefKind::Lifetime => {
+                (self.name.to_string(), GenericParamDefKind::Lifetime)
+            }
+            ty::GenericParamDefKind::Type { has_default, .. } => {
+                cx.renderinfo.borrow_mut().external_typarams
+                             .insert(self.def_id, self.name.clean(cx));
+                let default = if has_default {
+                    Some(cx.tcx.type_of(self.def_id).clean(cx))
+                } else {
+                    None
+                };
+                (self.name.clean(cx), GenericParamDefKind::Type {
+                    did: self.def_id,
+                    bounds: vec![], // These are filled in from the where-clauses.
+                    default,
+                    synthetic: None,
+                })
+            }
+        };
+
+        GenericParamDef {
+            name,
+            kind,
         }
     }
 }
 
 impl Clean<GenericParamDef> for hir::GenericParam {
     fn clean(&self, cx: &DocContext) -> GenericParamDef {
-        match *self {
-            hir::GenericParam::Lifetime(ref l) => GenericParamDef::Lifetime(l.clean(cx)),
-            hir::GenericParam::Type(ref t) => GenericParamDef::Type(t.clean(cx)),
+        let (name, kind) = match self.kind {
+            hir::GenericParamKind::Lifetime { .. } => {
+                let name = if self.bounds.len() > 0 {
+                    let mut bounds = self.bounds.iter().map(|bound| match bound {
+                        hir::GenericBound::Outlives(lt) => lt,
+                        _ => panic!(),
+                    });
+                    let name = bounds.next().unwrap().name.name();
+                    let mut s = format!("{}: {}", self.name.name(), name);
+                    for bound in bounds {
+                        s.push_str(&format!(" + {}", bound.name.name()));
+                    }
+                    s
+                } else {
+                    self.name.name().to_string()
+                };
+                (name, GenericParamDefKind::Lifetime)
+            }
+            hir::GenericParamKind::Type { ref default, synthetic, .. } => {
+                (self.name.name().clean(cx), GenericParamDefKind::Type {
+                    did: cx.tcx.hir.local_def_id(self.id),
+                    bounds: self.bounds.clean(cx),
+                    default: default.clean(cx),
+                    synthetic: synthetic,
+                })
+            }
+        };
+
+        GenericParamDef {
+            name,
+            kind,
         }
     }
 }
@@ -1900,25 +1937,25 @@ fn clean(&self, cx: &DocContext) -> Generics {
         // In order for normal parameters to be able to refer to synthetic ones,
         // scans them first.
         fn is_impl_trait(param: &hir::GenericParam) -> bool {
-            if let hir::GenericParam::Type(ref tp) = param {
-                tp.synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
-            } else {
-                false
+            match param.kind {
+                hir::GenericParamKind::Type { synthetic, .. } => {
+                    synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
+                }
+                _ => false,
             }
         }
         let impl_trait_params = self.params
             .iter()
-            .filter(|p| is_impl_trait(p))
-            .map(|p| {
-                let p = p.clean(cx);
-                if let GenericParamDef::Type(ref tp) = p {
-                    cx.impl_trait_bounds
-                        .borrow_mut()
-                        .insert(tp.did, tp.bounds.clone());
-                } else {
-                    unreachable!()
+            .filter(|param| is_impl_trait(param))
+            .map(|param| {
+                let param: GenericParamDef = param.clean(cx);
+                match param.kind {
+                    GenericParamDefKind::Lifetime => unreachable!(),
+                    GenericParamDefKind::Type { did, ref bounds, .. } => {
+                        cx.impl_trait_bounds.borrow_mut().insert(did, bounds.clone());
+                    }
                 }
-                p
+                param
             })
             .collect::<Vec<_>>();
 
@@ -1929,23 +1966,26 @@ fn is_impl_trait(param: &hir::GenericParam) -> bool {
         }
         params.extend(impl_trait_params);
 
-        let mut g = Generics {
+        let mut generics = Generics {
             params,
-            where_predicates: self.where_clause.predicates.clean(cx)
+            where_predicates: self.where_clause.predicates.clean(cx),
         };
 
         // Some duplicates are generated for ?Sized bounds between type params and where
         // predicates. The point in here is to move the bounds definitions from type params
         // to where predicates when such cases occur.
-        for where_pred in &mut g.where_predicates {
+        for where_pred in &mut generics.where_predicates {
             match *where_pred {
                 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
                     if bounds.is_empty() {
-                        for param in &mut g.params {
-                            if let GenericParamDef::Type(ref mut type_param) = *param {
-                                if &type_param.name == name {
-                                    mem::swap(bounds, &mut type_param.bounds);
-                                    break
+                        for param in &mut generics.params {
+                            match param.kind {
+                                GenericParamDefKind::Lifetime => {}
+                                GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
+                                    if &param.name == name {
+                                        mem::swap(bounds, ty_bounds);
+                                        break
+                                    }
                                 }
                             }
                         }
@@ -1954,7 +1994,7 @@ fn is_impl_trait(param: &hir::GenericParam) -> bool {
                 _ => continue,
             }
         }
-        g
+        generics
     }
 }
 
@@ -1968,18 +2008,16 @@ fn clean(&self, cx: &DocContext) -> Generics {
         // Bounds in the type_params and lifetimes fields are repeated in the
         // predicates field (see rustc_typeck::collect::ty_generics), so remove
         // them.
-        let stripped_typarams = gens.params.iter().filter_map(|param| {
-            if let ty::GenericParamDefKind::Type {..} = param.kind {
+        let stripped_typarams = gens.params.iter().filter_map(|param| match param.kind {
+            ty::GenericParamDefKind::Lifetime => None,
+            ty::GenericParamDefKind::Type { .. } => {
                 if param.name == keywords::SelfType.name().as_str() {
                     assert_eq!(param.index, 0);
-                    None
-                } else {
-                    Some(param.clean(cx))
+                    return None;
                 }
-            } else {
-                None
+                Some(param.clean(cx))
             }
-        }).collect::<Vec<TyParam>>();
+        }).collect::<Vec<GenericParamDef>>();
 
         let mut where_predicates = preds.predicates.to_vec().clean(cx);
 
@@ -2011,7 +2049,7 @@ fn clean(&self, cx: &DocContext) -> Generics {
             if !sized_params.contains(&tp.name) {
                 where_predicates.push(WP::BoundPredicate {
                     ty: Type::Generic(tp.name.clone()),
-                    bounds: vec![TyParamBound::maybe_sized(cx)],
+                    bounds: vec![GenericBound::maybe_sized(cx)],
                 })
             }
         }
@@ -2023,17 +2061,10 @@ fn clean(&self, cx: &DocContext) -> Generics {
         Generics {
             params: gens.params
                         .iter()
-                        .flat_map(|param| {
-                            if let ty::GenericParamDefKind::Lifetime = param.kind {
-                                Some(GenericParamDef::Lifetime(param.clean(cx)))
-                            } else {
-                                None
-                            }
-                        }).chain(
-                            simplify::ty_params(stripped_typarams)
-                                .into_iter()
-                                .map(|tp| GenericParamDef::Type(tp))
-                        )
+                        .flat_map(|param| match param.kind {
+                            ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
+                            ty::GenericParamDefKind::Type { .. } => None,
+                        }).chain(simplify::ty_params(stripped_typarams).into_iter())
                         .collect(),
             where_predicates: simplify::where_clauses(cx, where_predicates),
         }
@@ -2259,7 +2290,7 @@ pub struct Trait {
     pub unsafety: hir::Unsafety,
     pub items: Vec<Item>,
     pub generics: Generics,
-    pub bounds: Vec<TyParamBound>,
+    pub bounds: Vec<GenericBound>,
     pub is_spotlight: bool,
     pub is_auto: bool,
 }
@@ -2481,7 +2512,7 @@ fn clean(&self, cx: &DocContext) -> Item {
                     // at the end.
                     match bounds.iter().position(|b| b.is_sized_bound(cx)) {
                         Some(i) => { bounds.remove(i); }
-                        None => bounds.push(TyParamBound::maybe_sized(cx)),
+                        None => bounds.push(GenericBound::maybe_sized(cx)),
                     }
 
                     let ty = if self.defaultness.has_value() {
@@ -2536,7 +2567,7 @@ pub enum Type {
     /// structs/enums/traits (most that'd be an hir::TyPath)
     ResolvedPath {
         path: Path,
-        typarams: Option<Vec<TyParamBound>>,
+        typarams: Option<Vec<GenericBound>>,
         did: DefId,
         /// true if is a `T::Name` path for associated types
         is_generic: bool,
@@ -2572,7 +2603,7 @@ pub enum Type {
     Infer,
 
     // impl TraitA+TraitB
-    ImplTrait(Vec<TyParamBound>),
+    ImplTrait(Vec<GenericBound>),
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
@@ -2656,7 +2687,7 @@ pub fn generics(&self) -> Option<&[Type]> {
         match *self {
             ResolvedPath { ref path, .. } => {
                 path.segments.last().and_then(|seg| {
-                    if let PathParameters::AngleBracketed { ref types, .. } = seg.params {
+                    if let GenericArgs::AngleBracketed { ref types, .. } = seg.args {
                         Some(&**types)
                     } else {
                         None
@@ -2851,31 +2882,55 @@ fn clean(&self, cx: &DocContext) -> Type {
                     let provided_params = &path.segments.last().unwrap();
                     let mut ty_substs = FxHashMap();
                     let mut lt_substs = FxHashMap();
-                    provided_params.with_parameters(|provided_params| {
-                        let mut indices = GenericParamCount {
+                    provided_params.with_generic_args(|generic_args| {
+                        let mut indices = ty::GenericParamCount {
                             lifetimes: 0,
                             types: 0
                         };
                         for param in generics.params.iter() {
-                            match param {
-                                hir::GenericParam::Lifetime(lt_param) => {
-                                    if let Some(lt) = provided_params.lifetimes
-                                        .get(indices.lifetimes).cloned() {
+                            match param.kind {
+                                hir::GenericParamKind::Lifetime { .. } => {
+                                    let mut j = 0;
+                                    let lifetime = generic_args.args.iter().find_map(|arg| {
+                                        match arg {
+                                            GenericArg::Lifetime(lt) => {
+                                                if indices.lifetimes == j {
+                                                    return Some(lt);
+                                                }
+                                                j += 1;
+                                                None
+                                            }
+                                            _ => None,
+                                        }
+                                    });
+                                    if let Some(lt) = lifetime.cloned() {
                                         if !lt.is_elided() {
                                             let lt_def_id =
-                                                cx.tcx.hir.local_def_id(lt_param.lifetime.id);
+                                                cx.tcx.hir.local_def_id(param.id);
                                             lt_substs.insert(lt_def_id, lt.clean(cx));
                                         }
                                     }
                                     indices.lifetimes += 1;
                                 }
-                                hir::GenericParam::Type(ty_param) => {
+                                hir::GenericParamKind::Type { ref default, .. } => {
                                     let ty_param_def =
-                                        Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id));
-                                    if let Some(ty) = provided_params.types
-                                        .get(indices.types).cloned() {
+                                        Def::TyParam(cx.tcx.hir.local_def_id(param.id));
+                                    let mut j = 0;
+                                    let type_ = generic_args.args.iter().find_map(|arg| {
+                                        match arg {
+                                            GenericArg::Type(ty) => {
+                                                if indices.types == j {
+                                                    return Some(ty);
+                                                }
+                                                j += 1;
+                                                None
+                                            }
+                                            _ => None,
+                                        }
+                                    });
+                                    if let Some(ty) = type_.cloned() {
                                         ty_substs.insert(ty_param_def, ty.into_inner().clean(cx));
-                                    } else if let Some(default) = ty_param.default.clone() {
+                                    } else if let Some(default) = default.clone() {
                                         ty_substs.insert(ty_param_def,
                                                          default.into_inner().clean(cx));
                                     }
@@ -2922,18 +2977,14 @@ fn clean(&self, cx: &DocContext) -> Type {
             TyTraitObject(ref bounds, ref lifetime) => {
                 match bounds[0].clean(cx).trait_ {
                     ResolvedPath { path, typarams: None, did, is_generic } => {
-                        let mut bounds: Vec<_> = bounds[1..].iter().map(|bound| {
-                            TraitBound(bound.clean(cx), hir::TraitBoundModifier::None)
+                        let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
+                            self::GenericBound::TraitBound(bound.clean(cx),
+                                                           hir::TraitBoundModifier::None)
                         }).collect();
                         if !lifetime.is_elided() {
-                            bounds.push(RegionBound(lifetime.clean(cx)));
-                        }
-                        ResolvedPath {
-                            path,
-                            typarams: Some(bounds),
-                            did,
-                            is_generic,
+                            bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
                         }
+                        ResolvedPath { path, typarams: Some(bounds), did, is_generic, }
                     }
                     _ => Infer // shouldn't happen
                 }
@@ -3030,13 +3081,13 @@ fn clean(&self, cx: &DocContext) -> Type {
                     inline::record_extern_fqn(cx, did, TypeKind::Trait);
 
                     let mut typarams = vec![];
-                    reg.clean(cx).map(|b| typarams.push(RegionBound(b)));
+                    reg.clean(cx).map(|b| typarams.push(GenericBound::Outlives(b)));
                     for did in obj.auto_traits() {
                         let empty = cx.tcx.intern_substs(&[]);
                         let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
                             Some(did), false, vec![], empty);
                         inline::record_extern_fqn(cx, did, TypeKind::Trait);
-                        let bound = TraitBound(PolyTrait {
+                        let bound = GenericBound::TraitBound(PolyTrait {
                             trait_: ResolvedPath {
                                 path,
                                 typarams: None,
@@ -3087,7 +3138,9 @@ fn clean(&self, cx: &DocContext) -> Type {
                         tr
                     } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
                         // these should turn up at the end
-                        pred.skip_binder().1.clean(cx).map(|r| regions.push(RegionBound(r)));
+                        pred.skip_binder().1.clean(cx).map(|r| {
+                            regions.push(GenericBound::Outlives(r))
+                        });
                         return None;
                     } else {
                         return None;
@@ -3100,7 +3153,6 @@ fn clean(&self, cx: &DocContext) -> Type {
                         }
                     }
 
-
                     let bounds = bounds.predicates.iter().filter_map(|pred|
                         if let ty::Predicate::Projection(proj) = *pred {
                             let proj = proj.skip_binder();
@@ -3122,7 +3174,7 @@ fn clean(&self, cx: &DocContext) -> Type {
                 }).collect::<Vec<_>>();
                 bounds.extend(regions);
                 if !has_sized && !bounds.is_empty() {
-                    bounds.insert(0, TyParamBound::maybe_sized(cx));
+                    bounds.insert(0, GenericBound::maybe_sized(cx));
                 }
                 ImplTrait(bounds)
             }
@@ -3447,7 +3499,7 @@ pub fn singleton(name: String) -> Path {
             def: Def::Err,
             segments: vec![PathSegment {
                 name,
-                params: PathParameters::AngleBracketed {
+                args: GenericArgs::AngleBracketed {
                     lifetimes: Vec::new(),
                     types: Vec::new(),
                     bindings: Vec::new(),
@@ -3472,7 +3524,7 @@ fn clean(&self, cx: &DocContext) -> Path {
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
-pub enum PathParameters {
+pub enum GenericArgs {
     AngleBracketed {
         lifetimes: Vec<Lifetime>,
         types: Vec<Type>,
@@ -3484,22 +3536,33 @@ pub enum PathParameters {
     }
 }
 
-impl Clean<PathParameters> for hir::PathParameters {
-    fn clean(&self, cx: &DocContext) -> PathParameters {
+impl Clean<GenericArgs> for hir::GenericArgs {
+    fn clean(&self, cx: &DocContext) -> GenericArgs {
         if self.parenthesized {
             let output = self.bindings[0].ty.clean(cx);
-            PathParameters::Parenthesized {
+            GenericArgs::Parenthesized {
                 inputs: self.inputs().clean(cx),
                 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
             }
         } else {
-            PathParameters::AngleBracketed {
-                lifetimes: if self.lifetimes.iter().all(|lt| lt.is_elided()) {
-                    vec![]
-                } else {
-                    self.lifetimes.clean(cx)
-                },
-                types: self.types.clean(cx),
+            let (mut lifetimes, mut types) = (vec![], vec![]);
+            let mut elided_lifetimes = true;
+            for arg in &self.args {
+                match arg {
+                    GenericArg::Lifetime(lt) => {
+                        if !lt.is_elided() {
+                            elided_lifetimes = false;
+                        }
+                        lifetimes.push(lt.clean(cx));
+                    }
+                    GenericArg::Type(ty) => {
+                        types.push(ty.clean(cx));
+                    }
+                }
+            }
+            GenericArgs::AngleBracketed {
+                lifetimes: if elided_lifetimes { vec![] } else { lifetimes },
+                types,
                 bindings: self.bindings.clean(cx),
             }
         }
@@ -3509,14 +3572,14 @@ fn clean(&self, cx: &DocContext) -> PathParameters {
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
 pub struct PathSegment {
     pub name: String,
-    pub params: PathParameters,
+    pub args: GenericArgs,
 }
 
 impl Clean<PathSegment> for hir::PathSegment {
     fn clean(&self, cx: &DocContext) -> PathSegment {
         PathSegment {
             name: self.name.clean(cx),
-            params: self.with_parameters(|parameters| parameters.clean(cx))
+            args: self.with_generic_args(|generic_args| generic_args.clean(cx))
         }
     }
 }
@@ -3550,7 +3613,7 @@ fn strip_path(path: &Path) -> Path {
     let segments = path.segments.iter().map(|s| {
         PathSegment {
             name: s.name.clone(),
-            params: PathParameters::AngleBracketed {
+            args: GenericArgs::AngleBracketed {
                 lifetimes: Vec::new(),
                 types: Vec::new(),
                 bindings: Vec::new(),
@@ -4365,7 +4428,7 @@ fn push(&mut self, text: &str) {
         def: def_ctor(def_id),
         segments: hir::HirVec::from_vec(apb.names.iter().map(|s| hir::PathSegment {
             name: ast::Name::intern(&s),
-            parameters: None,
+            args: None,
             infer_types: false,
         }).collect())
     }
@@ -4388,8 +4451,8 @@ struct RegionDeps<'tcx> {
 
 #[derive(Eq, PartialEq, Hash, Debug)]
 enum SimpleBound {
-    RegionBound(Lifetime),
-    TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier)
+    TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
+    Outlives(Lifetime),
 }
 
 enum AutoTraitResult {
@@ -4407,11 +4470,11 @@ fn is_auto(&self) -> bool {
     }
 }
 
-impl From<TyParamBound> for SimpleBound {
-    fn from(bound: TyParamBound) -> Self {
+impl From<GenericBound> for SimpleBound {
+    fn from(bound: GenericBound) -> Self {
         match bound.clone() {
-            TyParamBound::RegionBound(l) => SimpleBound::RegionBound(l),
-            TyParamBound::TraitBound(t, mod_) => match t.trait_ {
+            GenericBound::Outlives(l) => SimpleBound::Outlives(l),
+            GenericBound::TraitBound(t, mod_) => match t.trait_ {
                 Type::ResolvedPath { path, typarams, .. } => {
                     SimpleBound::TraitBound(path.segments,
                                             typarams
index b7767606a6aa48861602c9b81f7e2c10d19088db..30a55bf0d18092f112df492ec5356e51f01bf1bb 100644 (file)
@@ -27,7 +27,7 @@
 use rustc::hir::def_id::DefId;
 use rustc::ty;
 
-use clean::PathParameters as PP;
+use clean::GenericArgs as PP;
 use clean::WherePredicate as WP;
 use clean;
 use core::DocContext;
@@ -83,8 +83,8 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
         };
         !bounds.iter_mut().any(|b| {
             let trait_ref = match *b {
-                clean::TraitBound(ref mut tr, _) => tr,
-                clean::RegionBound(..) => return false,
+                clean::GenericBound::TraitBound(ref mut tr, _) => tr,
+                clean::GenericBound::Outlives(..) => return false,
             };
             let (did, path) = match trait_ref.trait_ {
                 clean::ResolvedPath { did, ref mut path, ..} => (did, path),
@@ -97,7 +97,7 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
                 return false
             }
             let last = path.segments.last_mut().unwrap();
-            match last.params {
+            match last.args {
                 PP::AngleBracketed { ref mut bindings, .. } => {
                     bindings.push(clean::TypeBinding {
                         name: name.clone(),
@@ -135,14 +135,19 @@ pub fn where_clauses(cx: &DocContext, clauses: Vec<WP>) -> Vec<WP> {
     clauses
 }
 
-pub fn ty_params(mut params: Vec<clean::TyParam>) -> Vec<clean::TyParam> {
+pub fn ty_params(mut params: Vec<clean::GenericParamDef>) -> Vec<clean::GenericParamDef> {
     for param in &mut params {
-        param.bounds = ty_bounds(mem::replace(&mut param.bounds, Vec::new()));
+        match param.kind {
+            clean::GenericParamDefKind::Type { ref mut bounds, .. } => {
+                *bounds = ty_bounds(mem::replace(bounds, Vec::new()));
+            }
+            _ => panic!("expected only type parameters"),
+        }
     }
     params
 }
 
-fn ty_bounds(bounds: Vec<clean::TyParamBound>) -> Vec<clean::TyParamBound> {
+fn ty_bounds(bounds: Vec<clean::GenericBound>) -> Vec<clean::GenericBound> {
     bounds
 }
 
index e858f10860b411df97397910571caabe6efe7832..53ebb3a12f527e637bfe3b84938f2e6c816d9d79 100644 (file)
@@ -77,7 +77,7 @@ pub struct DocContext<'a, 'tcx: 'a, 'rcx: 'a> {
     /// Table node id of lifetime parameter definition -> substituted lifetime
     pub lt_substs: RefCell<FxHashMap<DefId, clean::Lifetime>>,
     /// Table DefId of `impl Trait` in argument position -> bounds
-    pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::TyParamBound>>>,
+    pub impl_trait_bounds: RefCell<FxHashMap<DefId, Vec<clean::GenericBound>>>,
     pub send_trait: Option<DefId>,
     pub fake_def_ids: RefCell<FxHashMap<CrateNum, DefId>>,
     pub all_fake_def_ids: RefCell<FxHashSet<DefId>>,
index f85a70a6d401f24c5bcb09f4923426df1b74b1cd..16d14bc56d6950257b21eda784f2fe559b548101 100644 (file)
@@ -201,7 +201,7 @@ pub struct Trait {
     pub name: Name,
     pub items: hir::HirVec<hir::TraitItem>,
     pub generics: hir::Generics,
-    pub bounds: hir::HirVec<hir::TyParamBound>,
+    pub bounds: hir::HirVec<hir::GenericBound>,
     pub attrs: hir::HirVec<ast::Attribute>,
     pub id: ast::NodeId,
     pub whence: Span,
index 40dcd6e891fe8cfba1161c4335c4fd7c33c2b580..3d360f2f344b614c369eb1649ff73cb90d245788 100644 (file)
@@ -46,7 +46,7 @@
 #[derive(Copy, Clone)]
 pub struct RawMutableSpace(pub clean::Mutability);
 /// Wrapper struct for emitting type parameter bounds.
-pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
+pub struct GenericBounds<'a>(pub &'a [clean::GenericBound]);
 /// Wrapper struct for emitting a comma-separated list of items
 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
 pub struct AbiSpace(pub Abi);
@@ -104,9 +104,9 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-impl<'a> fmt::Display for TyParamBounds<'a> {
+impl<'a> fmt::Display for GenericBounds<'a> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        let &TyParamBounds(bounds) = self;
+        let &GenericBounds(bounds) = self;
         for (i, bound) in bounds.iter().enumerate() {
             if i > 0 {
                 f.write_str(" + ")?;
@@ -119,20 +119,20 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 impl fmt::Display for clean::GenericParamDef {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        match *self {
-            clean::GenericParamDef::Lifetime(ref lp) => write!(f, "{}", lp),
-            clean::GenericParamDef::Type(ref tp) => {
-                f.write_str(&tp.name)?;
+        match self.kind {
+            clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
+            clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
+                f.write_str(&self.name)?;
 
-                if !tp.bounds.is_empty() {
+                if !bounds.is_empty() {
                     if f.alternate() {
-                        write!(f, ": {:#}", TyParamBounds(&tp.bounds))?;
+                        write!(f, ": {:#}", GenericBounds(bounds))?;
                     } else {
-                        write!(f, ":&nbsp;{}", TyParamBounds(&tp.bounds))?;
+                        write!(f, ":&nbsp;{}", GenericBounds(bounds))?;
                     }
                 }
 
-                if let Some(ref ty) = tp.default {
+                if let Some(ref ty) = default {
                     if f.alternate() {
                         write!(f, " = {:#}", ty)?;
                     } else {
@@ -190,9 +190,9 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
                     let bounds = bounds;
                     if f.alternate() {
-                        clause.push_str(&format!("{:#}: {:#}", ty, TyParamBounds(bounds)));
+                        clause.push_str(&format!("{:#}: {:#}", ty, GenericBounds(bounds)));
                     } else {
-                        clause.push_str(&format!("{}: {}", ty, TyParamBounds(bounds)));
+                        clause.push_str(&format!("{}: {}", ty, GenericBounds(bounds)));
                     }
                 }
                 &clean::WherePredicate::RegionPredicate { ref lifetime,
@@ -267,13 +267,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-impl fmt::Display for clean::TyParamBound {
+impl fmt::Display for clean::GenericBound {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match *self {
-            clean::RegionBound(ref lt) => {
+            clean::GenericBound::Outlives(ref lt) => {
                 write!(f, "{}", *lt)
             }
-            clean::TraitBound(ref ty, modifier) => {
+            clean::GenericBound::TraitBound(ref ty, modifier) => {
                 let modifier_str = match modifier {
                     hir::TraitBoundModifier::None => "",
                     hir::TraitBoundModifier::Maybe => "?",
@@ -288,10 +288,10 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-impl fmt::Display for clean::PathParameters {
+impl fmt::Display for clean::GenericArgs {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match *self {
-            clean::PathParameters::AngleBracketed {
+            clean::GenericArgs::AngleBracketed {
                 ref lifetimes, ref types, ref bindings
             } => {
                 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
@@ -337,7 +337,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                     }
                 }
             }
-            clean::PathParameters::Parenthesized { ref inputs, ref output } => {
+            clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
                 f.write_str("(")?;
                 let mut comma = false;
                 for ty in inputs {
@@ -369,9 +369,9 @@ impl fmt::Display for clean::PathSegment {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         f.write_str(&self.name)?;
         if f.alternate() {
-            write!(f, "{:#}", self.params)
+            write!(f, "{:#}", self.args)
         } else {
-            write!(f, "{}", self.params)
+            write!(f, "{}", self.args)
         }
     }
 }
@@ -447,7 +447,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
         }
     }
     if w.alternate() {
-        write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?;
+        write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.args)?;
     } else {
         let path = if use_absolute {
             match href(did) {
@@ -461,7 +461,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
         } else {
             format!("{}", HRef::new(did, &last.name))
         };
-        write!(w, "{}{}", path, last.params)?;
+        write!(w, "{}{}", path, last.args)?;
     }
     Ok(())
 }
@@ -512,7 +512,7 @@ fn primitive_link(f: &mut fmt::Formatter,
 
 /// Helper to render type parameters
 fn tybounds(w: &mut fmt::Formatter,
-            typarams: &Option<Vec<clean::TyParamBound>>) -> fmt::Result {
+            typarams: &Option<Vec<clean::GenericBound>>) -> fmt::Result {
     match *typarams {
         Some(ref params) => {
             for param in params {
@@ -667,7 +667,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt:
             }
         }
         clean::ImplTrait(ref bounds) => {
-            write!(f, "impl {}", TyParamBounds(bounds))
+            write!(f, "impl {}", GenericBounds(bounds))
         }
         clean::QPath { ref name, ref self_type, ref trait_ } => {
             let should_show_cast = match *trait_ {
@@ -757,7 +757,7 @@ fn fmt_impl(i: &clean::Impl,
                 clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => {
                     let last = path.segments.last().unwrap();
                     fmt::Display::fmt(&last.name, f)?;
-                    fmt::Display::fmt(&last.params, f)?;
+                    fmt::Display::fmt(&last.args, f)?;
                 }
                 _ => unreachable!(),
             }
index 5c2ec2058ee9d703d0723b6cda9c8dc3a6592ee6..180591b35326073f3fc3c825be08563a7d2d0d39 100644 (file)
@@ -69,7 +69,7 @@
 use fold::DocFolder;
 use html::escape::Escape;
 use html::format::{ConstnessSpace};
-use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
+use html::format::{GenericBounds, WhereClause, href, AbiSpace};
 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
 use html::format::fmt_impl_for_trait_page;
 use html::item_type::ItemType;
@@ -1453,11 +1453,11 @@ fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
 impl<'a> Cache {
     fn generics(&mut self, generics: &clean::Generics) {
         for param in &generics.params {
-            match *param {
-                clean::GenericParamDef::Type(ref typ) => {
-                    self.typarams.insert(typ.did, typ.name.clone());
+            match param.kind {
+                clean::GenericParamDefKind::Lifetime => {}
+                clean::GenericParamDefKind::Type { did, .. } => {
+                    self.typarams.insert(did, param.name.clone());
                 }
-                clean::GenericParamDef::Lifetime(_) => {}
             }
         }
     }
@@ -2960,14 +2960,14 @@ fn assoc_const(w: &mut fmt::Formatter,
 }
 
 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
-                             bounds: &Vec<clean::TyParamBound>,
+                             bounds: &Vec<clean::GenericBound>,
                              default: Option<&clean::Type>,
                              link: AssocItemLink) -> fmt::Result {
     write!(w, "type <a href='{}' class=\"type\">{}</a>",
            naive_assoc_href(it, link),
            it.name.as_ref().unwrap())?;
     if !bounds.is_empty() {
-        write!(w, ": {}", TyParamBounds(bounds))?
+        write!(w, ": {}", GenericBounds(bounds))?
     }
     if let Some(default) = default {
         write!(w, " = {}", default)?;
index 97c84d8348f7c0ce6f142dcf29a9a6493beac68a..566e2f1ed498c47fd8e7fbc1fc442b32b7e161b3 100644 (file)
@@ -18,6 +18,7 @@
 #![feature(box_patterns)]
 #![feature(box_syntax)]
 #![feature(fs_read_write)]
+#![feature(iterator_find_map)]
 #![feature(set_stdio)]
 #![feature(slice_sort_by_cached_key)]
 #![feature(test)]
@@ -46,7 +47,7 @@
 #[macro_use] extern crate log;
 extern crate rustc_errors as errors;
 extern crate pulldown_cmark;
-extern crate tempdir;
+extern crate tempfile;
 extern crate minifier;
 
 extern crate serialize as rustc_serialize; // used by deriving
index 6086c5a47c78c62dd058235a68a066fa69911d1c..fe992169ca934552f49e08970fa94034a70e8ca6 100644 (file)
@@ -27,7 +27,7 @@
 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
 use rustc::session::search_paths::{SearchPaths, PathKind};
 use rustc_metadata::dynamic_lib::DynamicLibrary;
-use tempdir::TempDir;
+use tempfile::Builder as TempFileBuilder;
 use rustc_driver::{self, driver, target_features, Compilation};
 use rustc_driver::driver::phase_2_configure_and_expand;
 use rustc_metadata::cstore::CStore;
@@ -277,7 +277,9 @@ fn drop(&mut self) {
         let cstore = CStore::new(codegen_backend.metadata_loader());
         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
 
-        let outdir = Mutex::new(TempDir::new("rustdoctest").ok().expect("rustdoc needs a tempdir"));
+        let outdir = Mutex::new(
+            TempFileBuilder::new().prefix("rustdoctest").tempdir().expect("rustdoc needs a tempdir")
+        );
         let libdir = sess.target_filesearch(PathKind::All).get_lib_path();
         let mut control = driver::CompileController::basic();
 
index ae74a71dd06815de686c74a615245261056f4af9..f28e91e19b73c834dd999c6b93177923295f8248 100644 (file)
 
 static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
 
-/// Registers a custom OOM hook, replacing any that was previously registered.
+/// Registers a custom allocation error hook, replacing any that was previously registered.
 ///
-/// The OOM hook is invoked when an infallible memory allocation fails, before
+/// The allocation error hook is invoked when an infallible memory allocation fails, before
 /// the runtime aborts. The default hook prints a message to standard error,
-/// but this behavior can be customized with the [`set_oom_hook`] and
-/// [`take_oom_hook`] functions.
+/// but this behavior can be customized with the [`set_alloc_error_hook`] and
+/// [`take_alloc_error_hook`] functions.
 ///
 /// The hook is provided with a `Layout` struct which contains information
 /// about the allocation that failed.
 ///
-/// The OOM hook is a global resource.
-#[unstable(feature = "oom_hook", issue = "51245")]
-pub fn set_oom_hook(hook: fn(Layout)) {
+/// The allocation error hook is a global resource.
+#[unstable(feature = "alloc_error_hook", issue = "51245")]
+pub fn set_alloc_error_hook(hook: fn(Layout)) {
     HOOK.store(hook as *mut (), Ordering::SeqCst);
 }
 
-/// Unregisters the current OOM hook, returning it.
+/// Unregisters the current allocation error hook, returning it.
 ///
-/// *See also the function [`set_oom_hook`].*
+/// *See also the function [`set_alloc_error_hook`].*
 ///
 /// If no custom hook is registered, the default hook will be returned.
-#[unstable(feature = "oom_hook", issue = "51245")]
-pub fn take_oom_hook() -> fn(Layout) {
+#[unstable(feature = "alloc_error_hook", issue = "51245")]
+pub fn take_alloc_error_hook() -> fn(Layout) {
     let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
     if hook.is_null() {
-        default_oom_hook
+        default_alloc_error_hook
     } else {
         unsafe { mem::transmute(hook) }
     }
 }
 
-fn default_oom_hook(layout: Layout) {
+fn default_alloc_error_hook(layout: Layout) {
     dumb_print(format_args!("memory allocation of {} bytes failed", layout.size()));
 }
 
@@ -130,7 +130,7 @@ fn default_oom_hook(layout: Layout) {
 pub extern fn rust_oom(layout: Layout) -> ! {
     let hook = HOOK.load(Ordering::SeqCst);
     let hook: fn(Layout) = if hook.is_null() {
-        default_oom_hook
+        default_alloc_error_hook
     } else {
         unsafe { mem::transmute(hook) }
     };
index 55f9f4f7cfeb75d7b8a615d06d2acc0f070d00ac..d14b754ddb6614831466307656733a8ae5110b0a 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use alloc::{Global, Alloc, Layout, LayoutErr, CollectionAllocErr, oom};
+use alloc::{Global, Alloc, Layout, LayoutErr, CollectionAllocErr, handle_alloc_error};
 use hash::{BuildHasher, Hash, Hasher};
 use marker;
 use mem::{size_of, needs_drop};
@@ -699,7 +699,7 @@ unsafe fn new_uninitialized_internal(
         // point into it.
         let (layout, _) = calculate_layout::<K, V>(capacity)?;
         let buffer = Global.alloc(layout).map_err(|e| match fallibility {
-            Infallible => oom(layout),
+            Infallible => handle_alloc_error(layout),
             Fallible => e,
         })?;
 
index eba4e9fe70368f6de4e853316ede9a6110e43ab1..2b4644bd013f2aa6d9a8911a7296041965999eff 100644 (file)
 //! ```
 //!
 //! Note that you cannot use the [`?` operator] in functions that do not return
-//! a [`Result<T, E>`][`Result`] (e.g. `main`). Instead, you can call [`.unwrap()`]
+//! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
 //! or `match` on the return value to catch any possible errors:
 //!
 //! ```no_run
index 4b5a063ea73aa2a5b823be0667a874022da31ef6..2c11c262488b2d04f396ea37e74d9e785971b4f0 100644 (file)
 ///
 /// [`AssertUnwindSafe`]: ./struct.AssertUnwindSafe.html
 #[stable(feature = "catch_unwind", since = "1.9.0")]
-#[rustc_on_unimplemented = "the type {Self} may not be safely transferred \
-                            across an unwind boundary"]
+#[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",
+)]
 pub auto trait UnwindSafe {}
 
 /// A marker trait representing types where a shared reference is considered
 /// [`UnsafeCell`]: ../cell/struct.UnsafeCell.html
 /// [`UnwindSafe`]: ./trait.UnwindSafe.html
 #[stable(feature = "catch_unwind", since = "1.9.0")]
-#[rustc_on_unimplemented = "the type {Self} may contain interior mutability \
-                            and a reference may not be safely transferrable \
-                            across a catch_unwind boundary"]
+#[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",
+)]
 pub auto trait RefUnwindSafe {}
 
 /// A simple wrapper around a type to assert that it is unwind safe.
index caa189457655230e1a47094fe73b054a308cdf2f..3f7f06714908428ee990b89fe15c483fe890d8ec 100644 (file)
@@ -183,15 +183,14 @@ pub fn fill_bytes(v: &mut [u8]) {
 mod imp {
     #[link(name = "zircon")]
     extern {
-        fn zx_cprng_draw(buffer: *mut u8, len: usize, actual: *mut usize) -> i32;
+        fn zx_cprng_draw_new(buffer: *mut u8, len: usize) -> i32;
     }
 
     fn getrandom(buf: &mut [u8]) -> Result<usize, i32> {
         unsafe {
-            let mut actual = 0;
-            let status = zx_cprng_draw(buf.as_mut_ptr(), buf.len(), &mut actual);
+            let status = zx_cprng_draw_new(buf.as_mut_ptr(), buf.len());
             if status == 0 {
-                Ok(actual)
+                Ok(buf.len())
             } else {
                 Err(status)
             }
index 76fa463a63134a494b49b05e191a487d2b5361c8..c6de2c4da39cfb59238af3da3e5cd89069f0c09a 100644 (file)
@@ -10,9 +10,8 @@
 
 // The Rust abstract syntax tree.
 
-pub use self::TyParamBound::*;
 pub use self::UnsafeSource::*;
-pub use self::PathParameters::*;
+pub use self::GenericArgs::*;
 pub use symbol::{Ident, Symbol as Name};
 pub use util::ThinVec;
 pub use util::parser::ExprPrecedence;
@@ -58,14 +57,6 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-/// A lifetime definition, e.g. `'a: 'b+'c+'d`
-#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct LifetimeDef {
-    pub attrs: ThinVec<Attribute>,
-    pub lifetime: Lifetime,
-    pub bounds: Vec<Lifetime>
-}
-
 /// A "Path" is essentially Rust's notion of a name.
 ///
 /// It's represented as a sequence of identifiers,
@@ -135,30 +126,30 @@ pub struct PathSegment {
     /// `Some` means that parameter list is supplied (`Path<X, Y>`)
     /// but it can be empty (`Path<>`).
     /// `P` is used as a size optimization for the common case with no parameters.
-    pub parameters: Option<P<PathParameters>>,
+    pub args: Option<P<GenericArgs>>,
 }
 
 impl PathSegment {
     pub fn from_ident(ident: Ident) -> Self {
-        PathSegment { ident, parameters: None }
+        PathSegment { ident, args: None }
     }
     pub fn crate_root(span: Span) -> Self {
         PathSegment::from_ident(Ident::new(keywords::CrateRoot.name(), span))
     }
 }
 
-/// Parameters of a path segment.
+/// Arguments of a path segment.
 ///
 /// E.g. `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum PathParameters {
+pub enum GenericArgs {
     /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>`
-    AngleBracketed(AngleBracketedParameterData),
+    AngleBracketed(AngleBracketedArgs),
     /// The `(A,B)` and `C` in `Foo(A,B) -> C`
-    Parenthesized(ParenthesizedParameterData),
+    Parenthesized(ParenthesisedArgs),
 }
 
-impl PathParameters {
+impl GenericArgs {
     pub fn span(&self) -> Span {
         match *self {
             AngleBracketed(ref data) => data.span,
@@ -167,36 +158,40 @@ pub fn span(&self) -> Span {
     }
 }
 
+#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
+pub enum GenericArg {
+    Lifetime(Lifetime),
+    Type(P<Ty>),
+}
+
 /// A path like `Foo<'a, T>`
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Default)]
-pub struct AngleBracketedParameterData {
+pub struct AngleBracketedArgs {
     /// Overall span
     pub span: Span,
-    /// The lifetime parameters for this path segment.
-    pub lifetimes: Vec<Lifetime>,
-    /// The type parameters for this path segment, if present.
-    pub types: Vec<P<Ty>>,
+    /// The arguments for this path segment.
+    pub args: Vec<GenericArg>,
     /// Bindings (equality constraints) on associated types, if present.
     ///
     /// E.g., `Foo<A=Bar>`.
     pub bindings: Vec<TypeBinding>,
 }
 
-impl Into<Option<P<PathParameters>>> for AngleBracketedParameterData {
-    fn into(self) -> Option<P<PathParameters>> {
-        Some(P(PathParameters::AngleBracketed(self)))
+impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
+    fn into(self) -> Option<P<GenericArgs>> {
+        Some(P(GenericArgs::AngleBracketed(self)))
     }
 }
 
-impl Into<Option<P<PathParameters>>> for ParenthesizedParameterData {
-    fn into(self) -> Option<P<PathParameters>> {
-        Some(P(PathParameters::Parenthesized(self)))
+impl Into<Option<P<GenericArgs>>> for ParenthesisedArgs {
+    fn into(self) -> Option<P<GenericArgs>> {
+        Some(P(GenericArgs::Parenthesized(self)))
     }
 }
 
 /// A path like `Foo(A,B) -> C`
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct ParenthesizedParameterData {
+pub struct ParenthesisedArgs {
     /// Overall span
     pub span: Span,
 
@@ -273,64 +268,52 @@ fn index(self) -> usize {
 /// small, positive ids.
 pub const DUMMY_NODE_ID: NodeId = NodeId(!0);
 
+/// A modifier on a bound, currently this is only used for `?Sized`, where the
+/// modifier is `Maybe`. Negative bounds should also be handled here.
+#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
+pub enum TraitBoundModifier {
+    None,
+    Maybe,
+}
+
 /// The AST represents all type param bounds as types.
 /// typeck::collect::compute_bounds matches these against
 /// the "special" built-in traits (see middle::lang_items) and
 /// detects Copy, Send and Sync.
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum TyParamBound {
-    TraitTyParamBound(PolyTraitRef, TraitBoundModifier),
-    RegionTyParamBound(Lifetime)
+pub enum GenericBound {
+    Trait(PolyTraitRef, TraitBoundModifier),
+    Outlives(Lifetime)
 }
 
-impl TyParamBound {
+impl GenericBound {
     pub fn span(&self) -> Span {
         match self {
-            &TraitTyParamBound(ref t, ..) => t.span,
-            &RegionTyParamBound(ref l) => l.ident.span,
+            &GenericBound::Trait(ref t, ..) => t.span,
+            &GenericBound::Outlives(ref l) => l.ident.span,
         }
     }
 }
 
-/// A modifier on a bound, currently this is only used for `?Sized`, where the
-/// modifier is `Maybe`. Negative bounds should also be handled here.
-#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum TraitBoundModifier {
-    None,
-    Maybe,
-}
-
-pub type TyParamBounds = Vec<TyParamBound>;
+pub type GenericBounds = Vec<GenericBound>;
 
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub struct TyParam {
-    pub attrs: ThinVec<Attribute>,
-    pub ident: Ident,
-    pub id: NodeId,
-    pub bounds: TyParamBounds,
-    pub default: Option<P<Ty>>,
+pub enum GenericParamKind {
+    /// A lifetime definition, e.g. `'a: 'b+'c+'d`.
+    Lifetime,
+    Type {
+        default: Option<P<Ty>>,
+    }
 }
 
 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
-pub enum GenericParam {
-    Lifetime(LifetimeDef),
-    Type(TyParam),
-}
-
-impl GenericParam {
-    pub fn is_lifetime_param(&self) -> bool {
-        match *self {
-            GenericParam::Lifetime(_) => true,
-            _ => false,
-        }
-    }
+pub struct GenericParam {
+    pub id: NodeId,
+    pub ident: Ident,
+    pub attrs: ThinVec<Attribute>,
+    pub bounds: GenericBounds,
 
-    pub fn is_type_param(&self) -> bool {
-        match *self {
-            GenericParam::Type(_) => true,
-            _ => false,
-        }
-    }
+    pub kind: GenericParamKind,
 }
 
 /// Represents lifetime, type and const parameters attached to a declaration of
@@ -342,31 +325,6 @@ pub struct Generics {
     pub span: Span,
 }
 
-impl Generics {
-    pub fn is_lt_parameterized(&self) -> bool {
-        self.params.iter().any(|param| param.is_lifetime_param())
-    }
-
-    pub fn is_type_parameterized(&self) -> bool {
-        self.params.iter().any(|param| param.is_type_param())
-    }
-
-    pub fn is_parameterized(&self) -> bool {
-        !self.params.is_empty()
-    }
-
-    pub fn span_for_name(&self, name: &str) -> Option<Span> {
-        for param in &self.params {
-            if let GenericParam::Type(ref t) = *param {
-                if t.ident.name == name {
-                    return Some(t.ident.span);
-                }
-            }
-        }
-        None
-    }
-}
-
 impl Default for Generics {
     /// Creates an instance of `Generics`.
     fn default() ->  Generics {
@@ -422,7 +380,7 @@ pub struct WhereBoundPredicate {
     /// The type being bounded
     pub bounded_ty: P<Ty>,
     /// Trait and lifetime bounds (`Clone+Send+'static`)
-    pub bounds: TyParamBounds,
+    pub bounds: GenericBounds,
 }
 
 /// A lifetime predicate.
@@ -432,7 +390,7 @@ pub struct WhereBoundPredicate {
 pub struct WhereRegionPredicate {
     pub span: Span,
     pub lifetime: Lifetime,
-    pub bounds: Vec<Lifetime>,
+    pub bounds: GenericBounds,
 }
 
 /// An equality predicate (unsupported).
@@ -968,11 +926,11 @@ pub fn returns(&self) -> bool {
         }
     }
 
-    fn to_bound(&self) -> Option<TyParamBound> {
+    fn to_bound(&self) -> Option<GenericBound> {
         match &self.node {
             ExprKind::Path(None, path) =>
-                Some(TraitTyParamBound(PolyTraitRef::new(Vec::new(), path.clone(), self.span),
-                                       TraitBoundModifier::None)),
+                Some(GenericBound::Trait(PolyTraitRef::new(Vec::new(), path.clone(), self.span),
+                                         TraitBoundModifier::None)),
             _ => None,
         }
     }
@@ -1393,7 +1351,7 @@ pub struct TraitItem {
 pub enum TraitItemKind {
     Const(P<Ty>, Option<P<Expr>>),
     Method(MethodSig, Option<P<Block>>),
-    Type(TyParamBounds, Option<P<Ty>>),
+    Type(GenericBounds, Option<P<Ty>>),
     Macro(Mac),
 }
 
@@ -1578,10 +1536,10 @@ pub enum TyKind {
     Path(Option<QSelf>, Path),
     /// A trait object type `Bound1 + Bound2 + Bound3`
     /// where `Bound` is a trait or a lifetime.
-    TraitObject(TyParamBounds, TraitObjectSyntax),
+    TraitObject(GenericBounds, TraitObjectSyntax),
     /// An `impl Bound1 + Bound2 + Bound3` type
     /// where `Bound` is a trait or a lifetime.
-    ImplTrait(TyParamBounds),
+    ImplTrait(GenericBounds),
     /// No-op; kept solely so that we can pretty-print faithfully
     Paren(P<Ty>),
     /// Unused for now
@@ -2102,11 +2060,11 @@ pub enum ItemKind {
     /// A Trait declaration (`trait` or `pub trait`).
     ///
     /// E.g. `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`
-    Trait(IsAuto, Unsafety, Generics, TyParamBounds, Vec<TraitItem>),
+    Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
     /// Trait alias
     ///
     /// E.g. `trait Foo = Bar + Quux;`
-    TraitAlias(Generics, TyParamBounds),
+    TraitAlias(Generics, GenericBounds),
     /// An implementation.
     ///
     /// E.g. `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`
index 2389ed799cfcc268301e70275aac9b3c190f029f..ded493fe3958c4f57a8e32db2e11a74646e08f4a 100644 (file)
@@ -1446,17 +1446,12 @@ fn map_attrs<F: FnOnce(Vec<ast::Attribute>) -> Vec<ast::Attribute>>(self, f: F)
 
 impl HasAttrs for GenericParam {
     fn attrs(&self) -> &[ast::Attribute] {
-        match self {
-            GenericParam::Lifetime(lifetime) => lifetime.attrs(),
-            GenericParam::Type(ty) => ty.attrs(),
-        }
+        &self.attrs
     }
 
-    fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
-        match self {
-            GenericParam::Lifetime(lifetime) => GenericParam::Lifetime(lifetime.map_attrs(f)),
-            GenericParam::Type(ty) => GenericParam::Type(ty.map_attrs(f)),
-        }
+    fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(mut self, f: F) -> Self {
+        self.attrs = self.attrs.map_attrs(f);
+        self
     }
 }
 
@@ -1479,5 +1474,5 @@ fn map_attrs<F>(mut self, f: F) -> Self
 
 derive_has_attrs! {
     Item, Expr, Local, ast::ForeignItem, ast::StructField, ast::ImplItem, ast::TraitItem, ast::Arm,
-    ast::Field, ast::FieldPat, ast::Variant_, ast::LifetimeDef, ast::TyParam
+    ast::Field, ast::FieldPat, ast::Variant_
 }
index ab8317bfa027ea5b9b22fd04300985c8b92c47a2..8534969c623bc5c906c0c40625b6a7435b33d7c2 100644 (file)
@@ -397,4 +397,6 @@ fn main() {}
     E0630, // rustc_const_unstable attribute must be paired with stable/unstable attribute
     E0693, // incorrect `repr(align)` attribute format
     E0694, // an unknown tool name found in scoped attributes
+    E0703, // invalid ABI
+    E0704, // incorrect visibility restriction
 }
index 4a6f06dcc17ba712e79543f7f3a419d508b59bf2..9044cab05d667f08d70b186d8aae85e569ec349a 100644 (file)
@@ -30,10 +30,9 @@ pub trait AstBuilder {
     fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path;
     fn path_all(&self, sp: Span,
                 global: bool,
-                idents: Vec<ast::Ident> ,
-                lifetimes: Vec<ast::Lifetime>,
-                types: Vec<P<ast::Ty>>,
-                bindings: Vec<ast::TypeBinding> )
+                idents: Vec<ast::Ident>,
+                args: Vec<ast::GenericArg>,
+                bindings: Vec<ast::TypeBinding>)
         -> ast::Path;
 
     fn qpath(&self, self_type: P<ast::Ty>,
@@ -43,8 +42,7 @@ fn qpath(&self, self_type: P<ast::Ty>,
     fn qpath_all(&self, self_type: P<ast::Ty>,
                 trait_path: ast::Path,
                 ident: ast::Ident,
-                lifetimes: Vec<ast::Lifetime>,
-                types: Vec<P<ast::Ty>>,
+                args: Vec<ast::GenericArg>,
                 bindings: Vec<ast::TypeBinding>)
                 -> (ast::QSelf, ast::Path);
 
@@ -70,19 +68,19 @@ fn typaram(&self,
                span: Span,
                id: ast::Ident,
                attrs: Vec<ast::Attribute>,
-               bounds: ast::TyParamBounds,
-               default: Option<P<ast::Ty>>) -> ast::TyParam;
+               bounds: ast::GenericBounds,
+               default: Option<P<ast::Ty>>) -> ast::GenericParam;
 
     fn trait_ref(&self, path: ast::Path) -> ast::TraitRef;
     fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef;
-    fn typarambound(&self, path: ast::Path) -> ast::TyParamBound;
+    fn trait_bound(&self, path: ast::Path) -> ast::GenericBound;
     fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime;
     fn lifetime_def(&self,
                     span: Span,
                     ident: ast::Ident,
                     attrs: Vec<ast::Attribute>,
-                    bounds: Vec<ast::Lifetime>)
-                    -> ast::LifetimeDef;
+                    bounds: ast::GenericBounds)
+                    -> ast::GenericParam;
 
     // statements
     fn stmt_expr(&self, expr: P<ast::Expr>) -> ast::Stmt;
@@ -304,34 +302,33 @@ fn item_use_glob(&self, sp: Span,
 
 impl<'a> AstBuilder for ExtCtxt<'a> {
     fn path(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path {
-        self.path_all(span, false, strs, Vec::new(), Vec::new(), Vec::new())
+        self.path_all(span, false, strs, vec![], vec![])
     }
     fn path_ident(&self, span: Span, id: ast::Ident) -> ast::Path {
         self.path(span, vec![id])
     }
     fn path_global(&self, span: Span, strs: Vec<ast::Ident> ) -> ast::Path {
-        self.path_all(span, true, strs, Vec::new(), Vec::new(), Vec::new())
+        self.path_all(span, true, strs, vec![], vec![])
     }
     fn path_all(&self,
                 span: Span,
                 global: bool,
                 mut idents: Vec<ast::Ident> ,
-                lifetimes: Vec<ast::Lifetime>,
-                types: Vec<P<ast::Ty>>,
+                args: Vec<ast::GenericArg>,
                 bindings: Vec<ast::TypeBinding> )
                 -> ast::Path {
         let last_ident = idents.pop().unwrap();
-        let mut segments: Vec<ast::PathSegment> = Vec::new();
+        let mut segments: Vec<ast::PathSegment> = vec![];
 
         segments.extend(idents.into_iter().map(|ident| {
             ast::PathSegment::from_ident(ident.with_span_pos(span))
         }));
-        let parameters = if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
-            ast::AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
+        let args = if !args.is_empty() || !bindings.is_empty() {
+            ast::AngleBracketedArgs { args, bindings, span }.into()
         } else {
             None
         };
-        segments.push(ast::PathSegment { ident: last_ident.with_span_pos(span), parameters });
+        segments.push(ast::PathSegment { ident: last_ident.with_span_pos(span), args });
         let mut path = ast::Path { span, segments };
         if global {
             if let Some(seg) = path.make_root() {
@@ -349,7 +346,7 @@ fn qpath(&self,
              trait_path: ast::Path,
              ident: ast::Ident)
              -> (ast::QSelf, ast::Path) {
-        self.qpath_all(self_type, trait_path, ident, vec![], vec![], vec![])
+        self.qpath_all(self_type, trait_path, ident, vec![], vec![])
     }
 
     /// Constructs a qualified path.
@@ -359,17 +356,16 @@ fn qpath_all(&self,
                  self_type: P<ast::Ty>,
                  trait_path: ast::Path,
                  ident: ast::Ident,
-                 lifetimes: Vec<ast::Lifetime>,
-                 types: Vec<P<ast::Ty>>,
+                 args: Vec<ast::GenericArg>,
                  bindings: Vec<ast::TypeBinding>)
                  -> (ast::QSelf, ast::Path) {
         let mut path = trait_path;
-        let parameters = if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
-            ast::AngleBracketedParameterData { lifetimes, types, bindings, span: ident.span }.into()
+        let args = if !args.is_empty() || !bindings.is_empty() {
+            ast::AngleBracketedArgs { args, bindings, span: ident.span }.into()
         } else {
             None
         };
-        path.segments.push(ast::PathSegment { ident, parameters });
+        path.segments.push(ast::PathSegment { ident, args });
 
         (ast::QSelf {
             ty: self_type,
@@ -428,8 +424,7 @@ fn ty_option(&self, ty: P<ast::Ty>) -> P<ast::Ty> {
             self.path_all(DUMMY_SP,
                           true,
                           self.std_path(&["option", "Option"]),
-                          Vec::new(),
-                          vec![ ty ],
+                          vec![ast::GenericArg::Type(ty)],
                           Vec::new()))
     }
 
@@ -441,14 +436,16 @@ fn typaram(&self,
                span: Span,
                ident: ast::Ident,
                attrs: Vec<ast::Attribute>,
-               bounds: ast::TyParamBounds,
-               default: Option<P<ast::Ty>>) -> ast::TyParam {
-        ast::TyParam {
+               bounds: ast::GenericBounds,
+               default: Option<P<ast::Ty>>) -> ast::GenericParam {
+        ast::GenericParam {
             ident: ident.with_span_pos(span),
             id: ast::DUMMY_NODE_ID,
             attrs: attrs.into(),
             bounds,
-            default,
+            kind: ast::GenericParamKind::Type {
+                default,
+            }
         }
     }
 
@@ -467,8 +464,9 @@ fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {
         }
     }
 
-    fn typarambound(&self, path: ast::Path) -> ast::TyParamBound {
-        ast::TraitTyParamBound(self.poly_trait_ref(path.span, path), ast::TraitBoundModifier::None)
+    fn trait_bound(&self, path: ast::Path) -> ast::GenericBound {
+        ast::GenericBound::Trait(self.poly_trait_ref(path.span, path),
+                                 ast::TraitBoundModifier::None)
     }
 
     fn lifetime(&self, span: Span, ident: ast::Ident) -> ast::Lifetime {
@@ -479,12 +477,15 @@ fn lifetime_def(&self,
                     span: Span,
                     ident: ast::Ident,
                     attrs: Vec<ast::Attribute>,
-                    bounds: Vec<ast::Lifetime>)
-                    -> ast::LifetimeDef {
-        ast::LifetimeDef {
+                    bounds: ast::GenericBounds)
+                    -> ast::GenericParam {
+        let lifetime = self.lifetime(span, ident);
+        ast::GenericParam {
+            ident: lifetime.ident,
+            id: lifetime.id,
             attrs: attrs.into(),
-            lifetime: self.lifetime(span, ident),
             bounds,
+            kind: ast::GenericParamKind::Lifetime,
         }
     }
 
index a2ea6a214841e71ca1d883b252a8114ec1f852d8..be4cf197be4eb2c569abe0511cf99e6ee1bdd207 100644 (file)
@@ -1797,7 +1797,7 @@ fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
                     gate_feature_post!(&self, associated_type_defaults, ti.span,
                                        "associated type defaults are unstable");
                 }
-                if ti.generics.is_parameterized() {
+                if !ti.generics.params.is_empty() {
                     gate_feature_post!(&self, generic_associated_types, ti.span,
                                        "generic associated types are unstable");
                 }
@@ -1824,7 +1824,7 @@ fn visit_impl_item(&mut self, ii: &'a ast::ImplItem) {
                     gate_feature_post!(&self, const_fn, ii.span, "const fn is unstable");
                 }
             }
-            ast::ImplItemKind::Type(_) if ii.generics.is_parameterized() => {
+            ast::ImplItemKind::Type(_) if !ii.generics.params.is_empty() => {
                 gate_feature_post!(&self, generic_associated_types, ii.span,
                                    "generic associated types are unstable");
             }
index 8544ef330dc33bb21ba046390c2a761561d842c0..93248fe3bfab0a0ac8971755f3fa73314f0c7c5b 100644 (file)
@@ -132,10 +132,21 @@ fn fold_exprs(&mut self, es: Vec<P<Expr>>) -> Vec<P<Expr>> {
         noop_fold_exprs(es, self)
     }
 
+    fn fold_generic_arg(&mut self, arg: GenericArg) -> GenericArg {
+        match arg {
+            GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.fold_lifetime(lt)),
+            GenericArg::Type(ty) => GenericArg::Type(self.fold_ty(ty)),
+        }
+    }
+
     fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
         noop_fold_ty(t, self)
     }
 
+    fn fold_lifetime(&mut self, l: Lifetime) -> Lifetime {
+        noop_fold_lifetime(l, self)
+    }
+
     fn fold_ty_binding(&mut self, t: TypeBinding) -> TypeBinding {
         noop_fold_ty_binding(t, self)
     }
@@ -172,18 +183,18 @@ fn fold_qpath(&mut self, qs: Option<QSelf>, p: Path) -> (Option<QSelf>, Path) {
         noop_fold_qpath(qs, p, self)
     }
 
-    fn fold_path_parameters(&mut self, p: PathParameters) -> PathParameters {
-        noop_fold_path_parameters(p, self)
+    fn fold_generic_args(&mut self, p: GenericArgs) -> GenericArgs {
+        noop_fold_generic_args(p, self)
     }
 
-    fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedParameterData)
-                                           -> AngleBracketedParameterData
+    fn fold_angle_bracketed_parameter_data(&mut self, p: AngleBracketedArgs)
+                                           -> AngleBracketedArgs
     {
         noop_fold_angle_bracketed_parameter_data(p, self)
     }
 
-    fn fold_parenthesized_parameter_data(&mut self, p: ParenthesizedParameterData)
-                                         -> ParenthesizedParameterData
+    fn fold_parenthesized_parameter_data(&mut self, p: ParenthesisedArgs)
+                                         -> ParenthesisedArgs
     {
         noop_fold_parenthesized_parameter_data(p, self)
     }
@@ -233,10 +244,6 @@ fn fold_variant_data(&mut self, vdata: VariantData) -> VariantData {
         noop_fold_variant_data(vdata, self)
     }
 
-    fn fold_ty_param(&mut self, tp: TyParam) -> TyParam {
-        noop_fold_ty_param(tp, self)
-    }
-
     fn fold_generic_param(&mut self, param: GenericParam) -> GenericParam {
         noop_fold_generic_param(param, self)
     }
@@ -261,18 +268,16 @@ fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
         noop_fold_interpolated(nt, self)
     }
 
-    fn fold_opt_bounds(&mut self, b: Option<TyParamBounds>)
-                       -> Option<TyParamBounds> {
+    fn fold_opt_bounds(&mut self, b: Option<GenericBounds>) -> Option<GenericBounds> {
         noop_fold_opt_bounds(b, self)
     }
 
-    fn fold_bounds(&mut self, b: TyParamBounds)
-                       -> TyParamBounds {
+    fn fold_bounds(&mut self, b: GenericBounds) -> GenericBounds {
         noop_fold_bounds(b, self)
     }
 
-    fn fold_ty_param_bound(&mut self, tpb: TyParamBound) -> TyParamBound {
-        noop_fold_ty_param_bound(tpb, self)
+    fn fold_param_bound(&mut self, tpb: GenericBound) -> GenericBound {
+        noop_fold_param_bound(tpb, self)
     }
 
     fn fold_mt(&mut self, mt: MutTy) -> MutTy {
@@ -385,10 +390,10 @@ pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
                 TyKind::Typeof(fld.fold_anon_const(expr))
             }
             TyKind::TraitObject(bounds, syntax) => {
-                TyKind::TraitObject(bounds.move_map(|b| fld.fold_ty_param_bound(b)), syntax)
+                TyKind::TraitObject(bounds.move_map(|b| fld.fold_param_bound(b)), syntax)
             }
             TyKind::ImplTrait(bounds) => {
-                TyKind::ImplTrait(bounds.move_map(|b| fld.fold_ty_param_bound(b)))
+                TyKind::ImplTrait(bounds.move_map(|b| fld.fold_param_bound(b)))
             }
             TyKind::Mac(mac) => {
                 TyKind::Mac(fld.fold_mac(mac))
@@ -433,9 +438,9 @@ pub fn noop_fold_usize<T: Folder>(i: usize, _: &mut T) -> usize {
 
 pub fn noop_fold_path<T: Folder>(Path { segments, span }: Path, fld: &mut T) -> Path {
     Path {
-        segments: segments.move_map(|PathSegment {ident, parameters}| PathSegment {
+        segments: segments.move_map(|PathSegment { ident, args }| PathSegment {
             ident: fld.fold_ident(ident),
-            parameters: parameters.map(|ps| ps.map(|ps| fld.fold_path_parameters(ps))),
+            args: args.map(|args| args.map(|args| fld.fold_generic_args(args))),
         }),
         span: fld.new_span(span)
     }
@@ -454,36 +459,40 @@ pub fn noop_fold_qpath<T: Folder>(qself: Option<QSelf>,
     (qself, fld.fold_path(path))
 }
 
-pub fn noop_fold_path_parameters<T: Folder>(path_parameters: PathParameters, fld: &mut T)
-                                            -> PathParameters
+pub fn noop_fold_generic_args<T: Folder>(generic_args: GenericArgs, fld: &mut T) -> GenericArgs
 {
-    match path_parameters {
-        PathParameters::AngleBracketed(data) =>
-            PathParameters::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data)),
-        PathParameters::Parenthesized(data) =>
-            PathParameters::Parenthesized(fld.fold_parenthesized_parameter_data(data)),
+    match generic_args {
+        GenericArgs::AngleBracketed(data) => {
+            GenericArgs::AngleBracketed(fld.fold_angle_bracketed_parameter_data(data))
+        }
+        GenericArgs::Parenthesized(data) => {
+            GenericArgs::Parenthesized(fld.fold_parenthesized_parameter_data(data))
+        }
     }
 }
 
-pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedParameterData,
+pub fn noop_fold_angle_bracketed_parameter_data<T: Folder>(data: AngleBracketedArgs,
                                                            fld: &mut T)
-                                                           -> AngleBracketedParameterData
+                                                           -> AngleBracketedArgs
 {
-    let AngleBracketedParameterData { lifetimes, types, bindings, span } = data;
-    AngleBracketedParameterData { lifetimes: lifetimes.move_map(|l| noop_fold_lifetime(l, fld)),
-                                  types: types.move_map(|ty| fld.fold_ty(ty)),
-                                  bindings: bindings.move_map(|b| fld.fold_ty_binding(b)),
-                                  span: fld.new_span(span) }
+    let AngleBracketedArgs { args, bindings, span } = data;
+    AngleBracketedArgs {
+        args: args.move_map(|arg| fld.fold_generic_arg(arg)),
+        bindings: bindings.move_map(|b| fld.fold_ty_binding(b)),
+        span: fld.new_span(span)
+    }
 }
 
-pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesizedParameterData,
+pub fn noop_fold_parenthesized_parameter_data<T: Folder>(data: ParenthesisedArgs,
                                                          fld: &mut T)
-                                                         -> ParenthesizedParameterData
+                                                         -> ParenthesisedArgs
 {
-    let ParenthesizedParameterData { inputs, output, span } = data;
-    ParenthesizedParameterData { inputs: inputs.move_map(|ty| fld.fold_ty(ty)),
-                                 output: output.map(|ty| fld.fold_ty(ty)),
-                                 span: fld.new_span(span) }
+    let ParenthesisedArgs { inputs, output, span } = data;
+    ParenthesisedArgs {
+        inputs: inputs.move_map(|ty| fld.fold_ty(ty)),
+        output: output.map(|ty| fld.fold_ty(ty)),
+        span: fld.new_span(span)
+    }
 }
 
 pub fn noop_fold_local<T: Folder>(l: P<Local>, fld: &mut T) -> P<Local> {
@@ -667,47 +676,33 @@ pub fn noop_fold_fn_decl<T: Folder>(decl: P<FnDecl>, fld: &mut T) -> P<FnDecl> {
     })
 }
 
-pub fn noop_fold_ty_param_bound<T>(tpb: TyParamBound, fld: &mut T)
-                                   -> TyParamBound
-                                   where T: Folder {
-    match tpb {
-        TraitTyParamBound(ty, modifier) => TraitTyParamBound(fld.fold_poly_trait_ref(ty), modifier),
-        RegionTyParamBound(lifetime) => RegionTyParamBound(noop_fold_lifetime(lifetime, fld)),
-    }
-}
-
-pub fn noop_fold_ty_param<T: Folder>(tp: TyParam, fld: &mut T) -> TyParam {
-    let TyParam {attrs, id, ident, bounds, default} = tp;
-    let attrs: Vec<_> = attrs.into();
-    TyParam {
-        attrs: attrs.into_iter()
-            .flat_map(|x| fld.fold_attribute(x).into_iter())
-            .collect::<Vec<_>>()
-            .into(),
-        id: fld.new_id(id),
-        ident: fld.fold_ident(ident),
-        bounds: fld.fold_bounds(bounds),
-        default: default.map(|x| fld.fold_ty(x)),
+pub fn noop_fold_param_bound<T>(pb: GenericBound, fld: &mut T) -> GenericBound where T: Folder {
+    match pb {
+        GenericBound::Trait(ty, modifier) => {
+            GenericBound::Trait(fld.fold_poly_trait_ref(ty), modifier)
+        }
+        GenericBound::Outlives(lifetime) => {
+            GenericBound::Outlives(noop_fold_lifetime(lifetime, fld))
+        }
     }
 }
 
 pub fn noop_fold_generic_param<T: Folder>(param: GenericParam, fld: &mut T) -> GenericParam {
-    match param {
-        GenericParam::Lifetime(l) => {
-            let attrs: Vec<_> = l.attrs.into();
-            GenericParam::Lifetime(LifetimeDef {
-                attrs: attrs.into_iter()
+    let attrs: Vec<_> = param.attrs.into();
+    GenericParam {
+        ident: fld.fold_ident(param.ident),
+        id: fld.new_id(param.id),
+        attrs: attrs.into_iter()
                     .flat_map(|x| fld.fold_attribute(x).into_iter())
                     .collect::<Vec<_>>()
                     .into(),
-                lifetime: Lifetime {
-                    id: fld.new_id(l.lifetime.id),
-                    ident: fld.fold_ident(l.lifetime.ident),
-                },
-                bounds: l.bounds.move_map(|l| noop_fold_lifetime(l, fld)),
-            })
+        bounds: param.bounds.move_map(|l| noop_fold_param_bound(l, fld)),
+        kind: match param.kind {
+            GenericParamKind::Lifetime => GenericParamKind::Lifetime,
+            GenericParamKind::Type { default } => GenericParamKind::Type {
+                default: default.map(|ty| fld.fold_ty(ty))
+            }
         }
-        GenericParam::Type(t) => GenericParam::Type(fld.fold_ty_param(t)),
     }
 }
 
@@ -765,7 +760,7 @@ pub fn noop_fold_where_predicate<T: Folder>(
             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
                 bound_generic_params: fld.fold_generic_params(bound_generic_params),
                 bounded_ty: fld.fold_ty(bounded_ty),
-                bounds: bounds.move_map(|x| fld.fold_ty_param_bound(x)),
+                bounds: bounds.move_map(|x| fld.fold_param_bound(x)),
                 span: fld.new_span(span)
             })
         }
@@ -775,7 +770,7 @@ pub fn noop_fold_where_predicate<T: Folder>(
             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
                 span: fld.new_span(span),
                 lifetime: noop_fold_lifetime(lifetime, fld),
-                bounds: bounds.move_map(|bound| noop_fold_lifetime(bound, fld))
+                bounds: bounds.move_map(|bound| noop_fold_param_bound(bound, fld))
             })
         }
         ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{id,
@@ -854,14 +849,14 @@ pub fn noop_fold_mt<T: Folder>(MutTy {ty, mutbl}: MutTy, folder: &mut T) -> MutT
     }
 }
 
-pub fn noop_fold_opt_bounds<T: Folder>(b: Option<TyParamBounds>, folder: &mut T)
-                                       -> Option<TyParamBounds> {
+pub fn noop_fold_opt_bounds<T: Folder>(b: Option<GenericBounds>, folder: &mut T)
+                                       -> Option<GenericBounds> {
     b.map(|bounds| folder.fold_bounds(bounds))
 }
 
-fn noop_fold_bounds<T: Folder>(bounds: TyParamBounds, folder: &mut T)
-                          -> TyParamBounds {
-    bounds.move_map(|bound| folder.fold_ty_param_bound(bound))
+fn noop_fold_bounds<T: Folder>(bounds: GenericBounds, folder: &mut T)
+                          -> GenericBounds {
+    bounds.move_map(|bound| folder.fold_param_bound(bound))
 }
 
 pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
@@ -1184,8 +1179,8 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
                 ExprKind::MethodCall(
                     PathSegment {
                         ident: folder.fold_ident(seg.ident),
-                        parameters: seg.parameters.map(|ps| {
-                            ps.map(|ps| folder.fold_path_parameters(ps))
+                        args: seg.args.map(|args| {
+                            args.map(|args| folder.fold_generic_args(args))
                         }),
                     },
                     folder.fold_exprs(args))
index 1735951da2f34638008e06bd45f482dc2c1ad6c0..9e527fc8aad057288d74a1c2c31a0931e90f32d4 100644 (file)
@@ -9,8 +9,8 @@
 // except according to those terms.
 
 use rustc_target::spec::abi::{self, Abi};
-use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
-use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
+use ast::{AngleBracketedArgs, ParenthesisedArgs, AttrStyle, BareFnTy};
+use ast::{GenericBound, TraitBoundModifier};
 use ast::Unsafety;
 use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
 use ast::Block;
 use ast::{Expr, ExprKind, RangeLimits};
 use ast::{Field, FnDecl};
 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
-use ast::GenericParam;
+use ast::{GenericParam, GenericParamKind};
+use ast::GenericArg;
 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
-use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind};
+use ast::{Label, Lifetime, Lit, LitKind};
 use ast::Local;
 use ast::MacStmtStyle;
 use ast::{Mac, Mac_, MacDelimiter};
@@ -35,7 +36,7 @@
 use ast::StrStyle;
 use ast::SelfKind;
 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
-use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
+use ast::{Ty, TyKind, TypeBinding, GenericBounds};
 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
 use ast::{UseTree, UseTreeKind};
 use ast::{BinOpKind, UnOp};
@@ -637,7 +638,26 @@ pub fn expect(&mut self, t: &token::Token) -> PResult<'a,  ()> {
                 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
                                                   token_str,
                                                   this_token_str));
-                err.span_label(self.span, format!("expected `{}`", token_str));
+
+                let sp = if self.token == token::Token::Eof {
+                    // EOF, don't want to point at the following char, but rather the last token
+                    self.prev_span
+                } else {
+                    self.sess.codemap().next_point(self.prev_span)
+                };
+                let label_exp = format!("expected `{}`", token_str);
+                let cm = self.sess.codemap();
+                match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
+                    (Ok(ref a), Ok(ref b)) if a.line == b.line => {
+                        // When the spans are in the same line, it means that the only content
+                        // between them is whitespace, point only at the found token.
+                        err.span_label(self.span, label_exp);
+                    }
+                    _ => {
+                        err.span_label(sp, label_exp);
+                        err.span_label(self.span, "unexpected token");
+                    }
+                }
                 Err(err)
             }
         } else {
@@ -756,6 +776,9 @@ fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
             err.span_label(self.span, format!("expected identifier, found {}", token_descr));
         } else {
             err.span_label(self.span, "expected identifier");
+            if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
+                err.span_suggestion(self.span, "remove this comma", "".into());
+            }
         }
         err
     }
@@ -1037,7 +1060,7 @@ pub fn parse_seq_to_end<T, F>(&mut self,
     /// Parse a sequence, not including the closing delimiter. The function
     /// f must consume tokens until reaching the next separator or
     /// closing bracket.
-    fn parse_seq_to_before_end<T, F>(&mut self,
+    pub fn parse_seq_to_before_end<T, F>(&mut self,
                                          ket: &token::Token,
                                          sep: SeqSep,
                                          f: F)
@@ -1204,14 +1227,6 @@ pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilde
     fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
         err.span_err(sp, self.diagnostic())
     }
-    fn span_fatal_help<S: Into<MultiSpan>>(&self,
-                                            sp: S,
-                                            m: &str,
-                                            help: &str) -> DiagnosticBuilder<'a> {
-        let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
-        err.help(help);
-        err
-    }
     fn bug(&self, m: &str) -> ! {
         self.sess.span_diagnostic.span_bug(self.span, m)
     }
@@ -1245,8 +1260,7 @@ fn token_is_bare_fn_keyword(&mut self) -> bool {
     }
 
     /// parse a TyKind::BareFn type:
-    fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
-                            -> PResult<'a, TyKind> {
+    fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
         /*
 
         [unsafe] [extern "ABI"] fn (S) -> T
@@ -1311,9 +1325,7 @@ fn parse_trait_item_(&mut self,
         let lo = self.span;
 
         let (name, node, generics) = if self.eat_keyword(keywords::Type) {
-            let (generics, TyParam {ident, bounds, default, ..}) =
-                self.parse_trait_item_assoc_ty(vec![])?;
-            (ident, TraitItemKind::Type(bounds, default), generics)
+            self.parse_trait_item_assoc_ty()?
         } else if self.is_const_item() {
             self.expect_keyword(keywords::Const)?;
             let ident = self.parse_ident()?;
@@ -1446,7 +1458,7 @@ fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
                     TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
                             if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
                         let path = match bounds[0] {
-                            TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
+                            GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
                             _ => self.bug("unexpected lifetime bound"),
                         };
                         self.parse_remaining_bounds(Vec::new(), path, lo, true)?
@@ -1511,7 +1523,7 @@ fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
             }
         } else if self.eat_keyword(keywords::Impl) {
             // Always parse bounds greedily for better error recovery.
-            let bounds = self.parse_ty_param_bounds()?;
+            let bounds = self.parse_generic_bounds()?;
             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
             TyKind::ImplTrait(bounds)
         } else if self.check_keyword(keywords::Dyn) &&
@@ -1519,13 +1531,13 @@ fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
                                          !can_continue_type_after_non_fn_ident(t)) {
             self.bump(); // `dyn`
             // Always parse bounds greedily for better error recovery.
-            let bounds = self.parse_ty_param_bounds()?;
+            let bounds = self.parse_generic_bounds()?;
             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
             TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
         } else if self.check(&token::Question) ||
                   self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
             // Bound list (trait object type)
-            TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
+            TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
                                 TraitObjectSyntax::None)
         } else if self.eat_lt() {
             // Qualified path
@@ -1568,10 +1580,10 @@ fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
     fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
                               lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
-        let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
+        let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
         if parse_plus {
             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
-            bounds.append(&mut self.parse_ty_param_bounds()?);
+            bounds.append(&mut self.parse_generic_bounds()?);
         }
         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
     }
@@ -1596,7 +1608,7 @@ fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PRe
         }
 
         self.bump(); // `+`
-        let bounds = self.parse_ty_param_bounds()?;
+        let bounds = self.parse_generic_bounds()?;
         let sum_span = ty.span.to(self.prev_span);
 
         let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
@@ -1612,7 +1624,7 @@ fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PRe
                     s.print_mutability(mut_ty.mutbl)?;
                     s.popen()?;
                     s.print_type(&mut_ty.ty)?;
-                    s.print_bounds(" +", &bounds)?;
+                    s.print_type_bounds(" +", &bounds)?;
                     s.pclose()
                 });
                 err.span_suggestion_with_applicability(
@@ -1894,7 +1906,7 @@ pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
                              -> PResult<'a, ast::Path> {
         maybe_whole!(self, NtPath, |path| {
             if style == PathStyle::Mod &&
-               path.segments.iter().any(|segment| segment.parameters.is_some()) {
+               path.segments.iter().any(|segment| segment.args.is_some()) {
                 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
             }
             path
@@ -1969,12 +1981,12 @@ fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
                                  .span_label(self.prev_span, "try removing `::`").emit();
             }
 
-            let parameters = if self.eat_lt() {
+            let args = if self.eat_lt() {
                 // `<'a, T, A = U>`
-                let (lifetimes, types, bindings) = self.parse_generic_args()?;
+                let (args, bindings) = self.parse_generic_args()?;
                 self.expect_gt()?;
                 let span = lo.to(self.prev_span);
-                AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
+                AngleBracketedArgs { args, bindings, span }.into()
             } else {
                 // `(T, U) -> R`
                 self.bump(); // `(`
@@ -1990,10 +2002,10 @@ fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
                     None
                 };
                 let span = lo.to(self.prev_span);
-                ParenthesizedParameterData { inputs, output, span }.into()
+                ParenthesisedArgs { inputs, output, span }.into()
             };
 
-            PathSegment { ident, parameters }
+            PathSegment { ident, args }
         } else {
             // Generic arguments are not found.
             PathSegment::from_ident(ident)
@@ -2108,7 +2120,7 @@ fn mk_assign_op(&mut self, binop: ast::BinOp,
         ExprKind::AssignOp(binop, lhs, rhs)
     }
 
-    fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
+    pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
         P(Expr {
             id: ast::DUMMY_NODE_ID,
             node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
@@ -2437,8 +2449,14 @@ fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Att
                 Err(mut e) => {
                     e.span_label(struct_sp, "while parsing this struct");
                     e.emit();
-                    self.recover_stmt();
-                    break;
+
+                    // If the next token is a comma, then try to parse
+                    // what comes next as additional fields, rather than
+                    // bailing out until next `}`.
+                    if self.token != token::Comma {
+                        self.recover_stmt();
+                        break;
+                    }
                 }
             }
 
@@ -2543,8 +2561,8 @@ fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Exp
             }
             _ => {
                 // Field access `expr.f`
-                if let Some(parameters) = segment.parameters {
-                    self.span_err(parameters.span(),
+                if let Some(args) = segment.args {
+                    self.span_err(args.span(),
                                   "field expressions may not have generic arguments");
                 }
 
@@ -4700,7 +4718,7 @@ fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Blo
                 if macro_legacy_warnings && self.token != token::Semi {
                     self.warn_missing_semicolon();
                 } else {
-                    self.expect_one_of(&[token::Semi], &[])?;
+                    self.expect_one_of(&[], &[token::Semi])?;
                 }
             }
             _ => {}
@@ -4737,7 +4755,7 @@ fn err_dotdotdot_syntax(&self, span: Span) {
     // LT_BOUND = LIFETIME (e.g. `'a`)
     // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
     // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
-    fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
+    fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
         let mut bounds = Vec::new();
         loop {
             // This needs to be syncronized with `Token::can_begin_bound`.
@@ -4754,7 +4772,7 @@ fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyPa
                         self.span_err(question_span,
                                       "`?` may only modify trait bounds, not lifetime bounds");
                     }
-                    bounds.push(RegionTyParamBound(self.expect_lifetime()));
+                    bounds.push(GenericBound::Outlives(self.expect_lifetime()));
                     if has_parens {
                         self.expect(&token::CloseDelim(token::Paren))?;
                         self.span_err(self.prev_span,
@@ -4772,7 +4790,7 @@ fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyPa
                     } else {
                         TraitBoundModifier::None
                     };
-                    bounds.push(TraitTyParamBound(poly_trait, modifier));
+                    bounds.push(GenericBound::Trait(poly_trait, modifier));
                 }
             } else {
                 break
@@ -4786,16 +4804,16 @@ fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyPa
         return Ok(bounds);
     }
 
-    fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
-        self.parse_ty_param_bounds_common(true)
+    fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
+        self.parse_generic_bounds_common(true)
     }
 
     // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
     // BOUND = LT_BOUND (e.g. `'a`)
-    fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
+    fn parse_lt_param_bounds(&mut self) -> GenericBounds {
         let mut lifetimes = Vec::new();
         while self.check_lifetime() {
-            lifetimes.push(self.expect_lifetime());
+            lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
 
             if !self.eat_plus() {
                 break
@@ -4805,12 +4823,14 @@ fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
     }
 
     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
-    fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
+    fn parse_ty_param(&mut self,
+                      preceding_attrs: Vec<Attribute>)
+                      -> PResult<'a, GenericParam> {
         let ident = self.parse_ident()?;
 
         // Parse optional colon and param bounds.
         let bounds = if self.eat(&token::Colon) {
-            self.parse_ty_param_bounds()?
+            self.parse_generic_bounds()?
         } else {
             Vec::new()
         };
@@ -4821,25 +4841,27 @@ fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyP
             None
         };
 
-        Ok(TyParam {
-            attrs: preceding_attrs.into(),
+        Ok(GenericParam {
             ident,
             id: ast::DUMMY_NODE_ID,
+            attrs: preceding_attrs.into(),
             bounds,
-            default,
+            kind: GenericParamKind::Type {
+                default,
+            }
         })
     }
 
     /// Parses the following grammar:
-    ///     TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
-    fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
-        -> PResult<'a, (ast::Generics, TyParam)> {
+    ///     TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
+    fn parse_trait_item_assoc_ty(&mut self)
+        -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
         let ident = self.parse_ident()?;
         let mut generics = self.parse_generics()?;
 
         // Parse optional colon and param bounds.
         let bounds = if self.eat(&token::Colon) {
-            self.parse_ty_param_bounds()?
+            self.parse_generic_bounds()?
         } else {
             Vec::new()
         };
@@ -4852,13 +4874,7 @@ fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
         };
         self.expect(&token::Semi)?;
 
-        Ok((generics, TyParam {
-            attrs: preceding_attrs.into(),
-            ident,
-            id: ast::DUMMY_NODE_ID,
-            bounds,
-            default,
-        }))
+        Ok((ident, TraitItemKind::Type(bounds, default), generics))
     }
 
     /// Parses (possibly empty) list of lifetime and type parameters, possibly including
@@ -4876,18 +4892,20 @@ fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
                 } else {
                     Vec::new()
                 };
-                params.push(ast::GenericParam::Lifetime(LifetimeDef {
+                params.push(ast::GenericParam {
+                    ident: lifetime.ident,
+                    id: lifetime.id,
                     attrs: attrs.into(),
-                    lifetime,
                     bounds,
-                }));
+                    kind: ast::GenericParamKind::Lifetime,
+                });
                 if seen_ty_param {
                     self.span_err(self.prev_span,
                         "lifetime parameters must be declared prior to type parameters");
                 }
             } else if self.check_ident() {
                 // Parse type parameter.
-                params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
+                params.push(self.parse_ty_param(attrs)?);
                 seen_ty_param = true;
             } else {
                 // Check for trailing attributes and stop parsing.
@@ -4936,16 +4954,16 @@ fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
 
     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
     /// possibly including trailing comma.
-    fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
-        let mut lifetimes = Vec::new();
-        let mut types = Vec::new();
+    fn parse_generic_args(&mut self)
+                          -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
+        let mut args = Vec::new();
         let mut bindings = Vec::new();
         let mut seen_type = false;
         let mut seen_binding = false;
         loop {
             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
                 // Parse lifetime argument.
-                lifetimes.push(self.expect_lifetime());
+                args.push(GenericArg::Lifetime(self.expect_lifetime()));
                 if seen_type || seen_binding {
                     self.span_err(self.prev_span,
                         "lifetime parameters must be declared prior to type parameters");
@@ -4965,11 +4983,12 @@ fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<
                 seen_binding = true;
             } else if self.check_type() {
                 // Parse type argument.
-                types.push(self.parse_ty()?);
+                let ty_param = self.parse_ty()?;
                 if seen_binding {
-                    self.span_err(types[types.len() - 1].span,
+                    self.span_err(ty_param.span,
                         "type parameters must be declared prior to associated type bindings");
                 }
+                args.push(GenericArg::Type(ty_param));
                 seen_type = true;
             } else {
                 break
@@ -4979,7 +4998,7 @@ fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<
                 break
             }
         }
-        Ok((lifetimes, types, bindings))
+        Ok((args, bindings))
     }
 
     /// Parses an optional `where` clause and places it in `generics`.
@@ -5037,7 +5056,7 @@ fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
                 // or with mandatory equality sign and the second type.
                 let ty = self.parse_ty()?;
                 if self.eat(&token::Colon) {
-                    let bounds = self.parse_ty_param_bounds()?;
+                    let bounds = self.parse_generic_bounds()?;
                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
                         ast::WhereBoundPredicate {
                             span: lo.to(self.prev_span),
@@ -5537,14 +5556,14 @@ fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'
 
         // Parse optional colon and supertrait bounds.
         let bounds = if self.eat(&token::Colon) {
-            self.parse_ty_param_bounds()?
+            self.parse_generic_bounds()?
         } else {
             Vec::new()
         };
 
         if self.eat(&token::Eq) {
             // it's a trait alias
-            let bounds = self.parse_ty_param_bounds()?;
+            let bounds = self.parse_generic_bounds()?;
             tps.where_clause = self.parse_where_clause()?;
             self.expect(&token::Semi)?;
             if unsafety != Unsafety::Normal {
@@ -5986,12 +6005,13 @@ pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibili
 `pub(super)`: visible only in the current module's parent
 `pub(in path::to::module)`: visible only on the specified path"##;
                 let path = self.parse_path(PathStyle::Mod)?;
-                let path_span = self.prev_span;
+                let sp = self.prev_span;
                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
-                let mut err = self.span_fatal_help(path_span, msg, suggestion);
+                let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
+                err.help(suggestion);
                 err.span_suggestion_with_applicability(
-                    path_span, &help_msg, format!("in {}", path), Applicability::MachineApplicable
+                    sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
                 );
                 err.emit();  // emit diagnostic, but continue with public visibility
             }
@@ -6535,12 +6555,15 @@ fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
                     Some(abi) => Ok(Some(abi)),
                     None => {
                         let prev_span = self.prev_span;
-                        self.span_err(
+                        let mut err = struct_span_err!(
+                            self.sess.span_diagnostic,
                             prev_span,
-                            &format!("invalid ABI: expected one of [{}], \
-                                     found `{}`",
-                                    abi::all_names().join(", "),
-                                    s));
+                            E0703,
+                            "invalid ABI: found `{}`",
+                            s);
+                        err.span_label(prev_span, "invalid ABI");
+                        err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
+                        err.emit();
                         Ok(None)
                     }
                 }
@@ -7212,7 +7235,7 @@ pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
         })
     }
 
-    fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
+    pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
         let ret = match self.token {
             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
index 87edfd69e2bd6fda7480f904b6ac68826f337cba..7a55919f422b88c70adc2b49f3e1bc2e2eb1f92a 100644 (file)
@@ -12,8 +12,8 @@
 
 use rustc_target::spec::abi::{self, Abi};
 use ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
-use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
-use ast::{Attribute, MacDelimiter};
+use ast::{SelfKind, GenericBound, TraitBoundModifier};
+use ast::{Attribute, MacDelimiter, GenericArg};
 use util::parser::{self, AssocOp, Fixity};
 use attr;
 use codemap::{self, CodeMap};
@@ -292,8 +292,8 @@ pub fn ty_to_string(ty: &ast::Ty) -> String {
     to_string(|s| s.print_type(ty))
 }
 
-pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
-    to_string(|s| s.print_bounds("", bounds))
+pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
+    to_string(|s| s.print_type_bounds("", bounds))
 }
 
 pub fn pat_to_string(pat: &ast::Pat) -> String {
@@ -308,8 +308,8 @@ pub fn expr_to_string(e: &ast::Expr) -> String {
     to_string(|s| s.print_expr(e))
 }
 
-pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
-    to_string(|s| s.print_lifetime(e))
+pub fn lifetime_to_string(lt: &ast::Lifetime) -> String {
+    to_string(|s| s.print_lifetime(*lt))
 }
 
 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
@@ -1008,15 +1008,21 @@ pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
         Ok(())
     }
 
-    pub fn print_opt_lifetime(&mut self,
-                              lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
-        if let Some(l) = *lifetime {
-            self.print_lifetime(&l)?;
+    pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
+        if let Some(lt) = *lifetime {
+            self.print_lifetime(lt)?;
             self.nbsp()?;
         }
         Ok(())
     }
 
+    pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) -> io::Result<()> {
+        match generic_arg {
+            GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
+            GenericArg::Type(ty) => self.print_type(ty),
+        }
+    }
+
     pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
         self.maybe_print_comment(ty.span.lo())?;
         self.ibox(0)?;
@@ -1071,10 +1077,10 @@ pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
             }
             ast::TyKind::TraitObject(ref bounds, syntax) => {
                 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
-                self.print_bounds(prefix, &bounds[..])?;
+                self.print_type_bounds(prefix, &bounds[..])?;
             }
             ast::TyKind::ImplTrait(ref bounds) => {
-                self.print_bounds("impl", &bounds[..])?;
+                self.print_type_bounds("impl", &bounds[..])?;
             }
             ast::TyKind::Array(ref ty, ref length) => {
                 self.s.word("[")?;
@@ -1171,13 +1177,13 @@ fn print_associated_const(&mut self,
 
     fn print_associated_type(&mut self,
                              ident: ast::Ident,
-                             bounds: Option<&ast::TyParamBounds>,
+                             bounds: Option<&ast::GenericBounds>,
                              ty: Option<&ast::Ty>)
                              -> io::Result<()> {
         self.word_space("type")?;
         self.print_ident(ident)?;
         if let Some(bounds) = bounds {
-            self.print_bounds(":", bounds)?;
+            self.print_type_bounds(":", bounds)?;
         }
         if let Some(ty) = ty {
             self.s.space()?;
@@ -1322,7 +1328,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
                 self.print_unsafety(unsafety)?;
                 self.word_nbsp("impl")?;
 
-                if generics.is_parameterized() {
+                if !generics.params.is_empty() {
                     self.print_generic_params(&generics.params)?;
                     self.s.space()?;
                 }
@@ -1358,7 +1364,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
                 self.print_generic_params(&generics.params)?;
                 let mut real_bounds = Vec::with_capacity(bounds.len());
                 for b in bounds.iter() {
-                    if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
+                    if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
                         self.s.space()?;
                         self.word_space("for ?")?;
                         self.print_trait_ref(&ptr.trait_ref)?;
@@ -1366,7 +1372,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
                         real_bounds.push(b.clone());
                     }
                 }
-                self.print_bounds(":", &real_bounds[..])?;
+                self.print_type_bounds(":", &real_bounds[..])?;
                 self.print_where_clause(&generics.where_clause)?;
                 self.s.word(" ")?;
                 self.bopen()?;
@@ -1384,7 +1390,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
                 let mut real_bounds = Vec::with_capacity(bounds.len());
                 // FIXME(durka) this seems to be some quite outdated syntax
                 for b in bounds.iter() {
-                    if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
+                    if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
                         self.s.space()?;
                         self.word_space("for ?")?;
                         self.print_trait_ref(&ptr.trait_ref)?;
@@ -1393,7 +1399,7 @@ pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
                     }
                 }
                 self.nbsp()?;
-                self.print_bounds("=", &real_bounds[..])?;
+                self.print_type_bounds("=", &real_bounds[..])?;
                 self.print_where_clause(&generics.where_clause)?;
                 self.s.word(";")?;
             }
@@ -1984,8 +1990,8 @@ fn print_expr_method_call(&mut self,
         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX)?;
         self.s.word(".")?;
         self.print_ident(segment.ident)?;
-        if let Some(ref parameters) = segment.parameters {
-            self.print_path_parameters(parameters, true)?;
+        if let Some(ref args) = segment.args {
+            self.print_generic_args(args, true)?;
         }
         self.print_call_post(base_args)
     }
@@ -2428,8 +2434,8 @@ fn print_path_segment(&mut self,
         if segment.ident.name != keywords::CrateRoot.name() &&
            segment.ident.name != keywords::DollarCrate.name() {
             self.print_ident(segment.ident)?;
-            if let Some(ref parameters) = segment.parameters {
-                self.print_path_parameters(parameters, colons_before_params)?;
+            if let Some(ref args) = segment.args {
+                self.print_generic_args(args, colons_before_params)?;
             }
         } else if segment.ident.name == keywords::DollarCrate.name() {
             self.print_dollar_crate(segment.ident.span.ctxt())?;
@@ -2455,44 +2461,30 @@ fn print_qpath(&mut self,
         self.s.word("::")?;
         let item_segment = path.segments.last().unwrap();
         self.print_ident(item_segment.ident)?;
-        match item_segment.parameters {
-            Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
+        match item_segment.args {
+            Some(ref args) => self.print_generic_args(args, colons_before_params),
             None => Ok(()),
         }
     }
 
-    fn print_path_parameters(&mut self,
-                             parameters: &ast::PathParameters,
-                             colons_before_params: bool)
-                             -> io::Result<()>
+    fn print_generic_args(&mut self,
+                          args: &ast::GenericArgs,
+                          colons_before_params: bool)
+                          -> io::Result<()>
     {
         if colons_before_params {
             self.s.word("::")?
         }
 
-        match *parameters {
-            ast::PathParameters::AngleBracketed(ref data) => {
+        match *args {
+            ast::GenericArgs::AngleBracketed(ref data) => {
                 self.s.word("<")?;
 
-                let mut comma = false;
-                for lifetime in &data.lifetimes {
-                    if comma {
-                        self.word_space(",")?
-                    }
-                    self.print_lifetime(lifetime)?;
-                    comma = true;
-                }
+                self.commasep(Inconsistent, &data.args, |s, generic_arg| {
+                    s.print_generic_arg(generic_arg)
+                })?;
 
-                if !data.types.is_empty() {
-                    if comma {
-                        self.word_space(",")?
-                    }
-                    self.commasep(
-                        Inconsistent,
-                        &data.types,
-                        |s, ty| s.print_type(ty))?;
-                        comma = true;
-                }
+                let mut comma = data.args.len() != 0;
 
                 for binding in data.bindings.iter() {
                     if comma {
@@ -2508,7 +2500,7 @@ fn print_path_parameters(&mut self,
                 self.s.word(">")?
             }
 
-            ast::PathParameters::Parenthesized(ref data) => {
+            ast::GenericArgs::Parenthesized(ref data) => {
                 self.s.word("(")?;
                 self.commasep(
                     Inconsistent,
@@ -2816,9 +2808,9 @@ pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
         }
     }
 
-    pub fn print_bounds(&mut self,
+    pub fn print_type_bounds(&mut self,
                         prefix: &str,
-                        bounds: &[ast::TyParamBound])
+                        bounds: &[ast::GenericBound])
                         -> io::Result<()> {
         if !bounds.is_empty() {
             self.s.word(prefix)?;
@@ -2834,32 +2826,25 @@ pub fn print_bounds(&mut self,
                 }
 
                 match bound {
-                    TraitTyParamBound(tref, modifier) => {
+                    GenericBound::Trait(tref, modifier) => {
                         if modifier == &TraitBoundModifier::Maybe {
                             self.s.word("?")?;
                         }
                         self.print_poly_trait_ref(tref)?;
                     }
-                    RegionTyParamBound(lt) => {
-                        self.print_lifetime(lt)?;
-                    }
+                    GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
                 }
             }
         }
         Ok(())
     }
 
-    pub fn print_lifetime(&mut self,
-                          lifetime: &ast::Lifetime)
-                          -> io::Result<()>
-    {
+    pub fn print_lifetime(&mut self, lifetime: ast::Lifetime) -> io::Result<()> {
         self.print_name(lifetime.ident.name)
     }
 
-    pub fn print_lifetime_bounds(&mut self,
-                                 lifetime: &ast::Lifetime,
-                                 bounds: &[ast::Lifetime])
-                                 -> io::Result<()>
+    pub fn print_lifetime_bounds(&mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds)
+        -> io::Result<()>
     {
         self.print_lifetime(lifetime)?;
         if !bounds.is_empty() {
@@ -2868,7 +2853,10 @@ pub fn print_lifetime_bounds(&mut self,
                 if i != 0 {
                     self.s.word(" + ")?;
                 }
-                self.print_lifetime(bound)?;
+                match bound {
+                    ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
+                    _ => panic!(),
+                }
             }
         }
         Ok(())
@@ -2885,12 +2873,25 @@ pub fn print_generic_params(
         self.s.word("<")?;
 
         self.commasep(Inconsistent, &generic_params, |s, param| {
-            match *param {
-                ast::GenericParam::Lifetime(ref lifetime_def) => {
-                    s.print_outer_attributes_inline(&lifetime_def.attrs)?;
-                    s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
+            match param.kind {
+                ast::GenericParamKind::Lifetime => {
+                    s.print_outer_attributes_inline(&param.attrs)?;
+                    let lt = ast::Lifetime { id: param.id, ident: param.ident };
+                    s.print_lifetime_bounds(lt, &param.bounds)
                 },
-                ast::GenericParam::Type(ref ty_param) => s.print_ty_param(ty_param),
+                ast::GenericParamKind::Type { ref default } => {
+                    s.print_outer_attributes_inline(&param.attrs)?;
+                    s.print_ident(param.ident)?;
+                    s.print_type_bounds(":", &param.bounds)?;
+                    match default {
+                        Some(ref default) => {
+                            s.s.space()?;
+                            s.word_space("=")?;
+                            s.print_type(default)
+                        }
+                        _ => Ok(())
+                    }
+                }
             }
         })?;
 
@@ -2898,20 +2899,6 @@ pub fn print_generic_params(
         Ok(())
     }
 
-    pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
-        self.print_outer_attributes_inline(&param.attrs)?;
-        self.print_ident(param.ident)?;
-        self.print_bounds(":", &param.bounds)?;
-        match param.default {
-            Some(ref default) => {
-                self.s.space()?;
-                self.word_space("=")?;
-                self.print_type(default)
-            }
-            _ => Ok(())
-        }
-    }
-
     pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
                               -> io::Result<()> {
         if where_clause.predicates.is_empty() {
@@ -2935,12 +2922,12 @@ pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
                 }) => {
                     self.print_formal_generic_params(bound_generic_params)?;
                     self.print_type(bounded_ty)?;
-                    self.print_bounds(":", bounds)?;
+                    self.print_type_bounds(":", bounds)?;
                 }
                 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
                                                                                ref bounds,
                                                                                ..}) => {
-                    self.print_lifetime_bounds(lifetime, bounds)?;
+                    self.print_lifetime_bounds(*lifetime, bounds)?;
                 }
                 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
                                                                        ref rhs_ty,
index da7deb3c4cfe7856df02dbb981c61d663dc79b2a..f896fa351b0af4210fb525113be4dec96388248d 100644 (file)
@@ -353,7 +353,7 @@ fn has_test_signature(_cx: &TestCtxt, i: &ast::Item) -> HasTestSignature {
 
                 match (has_output, has_should_panic_attr) {
                     (true, true) => No(BadTestSignature::ShouldPanicOnlyWithNoArgs),
-                    (true, false) => if generics.is_parameterized() {
+                    (true, false) => if !generics.params.is_empty() {
                         No(BadTestSignature::WrongTypeSignature)
                     } else {
                         Yes
index d4c6b4b158b25dc2590063e1e04d6e0cced892c7..ebb3081c1fde5586665e08271e5cdd35ef972e75 100644 (file)
@@ -95,9 +95,9 @@ fn visit_trait_ref(&mut self, t: &TraitRef) {
         self.count += 1;
         walk_trait_ref(self, t)
     }
-    fn visit_ty_param_bound(&mut self, bounds: &TyParamBound) {
+    fn visit_param_bound(&mut self, bounds: &GenericBound) {
         self.count += 1;
-        walk_ty_param_bound(self, bounds)
+        walk_param_bound(self, bounds)
     }
     fn visit_poly_trait_ref(&mut self, t: &PolyTraitRef, m: &TraitBoundModifier) {
         self.count += 1;
@@ -137,9 +137,9 @@ fn visit_use_tree(&mut self, use_tree: &UseTree, id: NodeId, _nested: bool) {
         self.count += 1;
         walk_use_tree(self, use_tree, id)
     }
-    fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &PathParameters) {
+    fn visit_generic_args(&mut self, path_span: Span, generic_args: &GenericArgs) {
         self.count += 1;
-        walk_path_parameters(self, path_span, path_parameters)
+        walk_generic_args(self, path_span, generic_args)
     }
     fn visit_assoc_type_binding(&mut self, type_binding: &TypeBinding) {
         self.count += 1;
index adda39c62ed0e2b4c3b9c6be026c84c9bd7ff7ce..613f1a4f113bdf5377ba79b9ffb150edf43a6f11 100644 (file)
@@ -73,7 +73,9 @@ fn visit_anon_const(&mut self, c: &'ast AnonConst) { walk_anon_const(self, c) }
     fn visit_expr(&mut self, ex: &'ast Expr) { walk_expr(self, ex) }
     fn visit_expr_post(&mut self, _ex: &'ast Expr) { }
     fn visit_ty(&mut self, t: &'ast Ty) { walk_ty(self, t) }
-    fn visit_generic_param(&mut self, param: &'ast GenericParam) { walk_generic_param(self, param) }
+    fn visit_generic_param(&mut self, param: &'ast GenericParam) {
+        walk_generic_param(self, param)
+    }
     fn visit_generics(&mut self, g: &'ast Generics) { walk_generics(self, g) }
     fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
         walk_where_predicate(self, p)
@@ -84,8 +86,8 @@ fn visit_fn(&mut self, fk: FnKind<'ast>, fd: &'ast FnDecl, s: Span, _: NodeId) {
     fn visit_trait_item(&mut self, ti: &'ast TraitItem) { walk_trait_item(self, ti) }
     fn visit_impl_item(&mut self, ii: &'ast ImplItem) { walk_impl_item(self, ii) }
     fn visit_trait_ref(&mut self, t: &'ast TraitRef) { walk_trait_ref(self, t) }
-    fn visit_ty_param_bound(&mut self, bounds: &'ast TyParamBound) {
-        walk_ty_param_bound(self, bounds)
+    fn visit_param_bound(&mut self, bounds: &'ast GenericBound) {
+        walk_param_bound(self, bounds)
     }
     fn visit_poly_trait_ref(&mut self, t: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) {
         walk_poly_trait_ref(self, t, m)
@@ -128,8 +130,14 @@ fn visit_use_tree(&mut self, use_tree: &'ast UseTree, id: NodeId, _nested: bool)
     fn visit_path_segment(&mut self, path_span: Span, path_segment: &'ast PathSegment) {
         walk_path_segment(self, path_span, path_segment)
     }
-    fn visit_path_parameters(&mut self, path_span: Span, path_parameters: &'ast PathParameters) {
-        walk_path_parameters(self, path_span, path_parameters)
+    fn visit_generic_args(&mut self, path_span: Span, generic_args: &'ast GenericArgs) {
+        walk_generic_args(self, path_span, generic_args)
+    }
+    fn visit_generic_arg(&mut self, generic_arg: &'ast GenericArg) {
+        match generic_arg {
+            GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
+            GenericArg::Type(ty) => self.visit_ty(ty),
+        }
     }
     fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) {
         walk_assoc_type_binding(self, type_binding)
@@ -268,12 +276,12 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) {
         }
         ItemKind::Trait(.., ref generics, ref bounds, ref methods) => {
             visitor.visit_generics(generics);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_trait_item, methods);
         }
         ItemKind::TraitAlias(ref generics, ref bounds) => {
             visitor.visit_generics(generics);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
         }
         ItemKind::Mac(ref mac) => visitor.visit_mac(mac),
         ItemKind::MacroDef(ref ts) => visitor.visit_mac_def(ts, item.id),
@@ -333,7 +341,7 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) {
         }
         TyKind::TraitObject(ref bounds, ..) |
         TyKind::ImplTrait(ref bounds) => {
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
         }
         TyKind::Typeof(ref expression) => {
             visitor.visit_anon_const(expression)
@@ -375,23 +383,22 @@ pub fn walk_path_segment<'a, V: Visitor<'a>>(visitor: &mut V,
                                              path_span: Span,
                                              segment: &'a PathSegment) {
     visitor.visit_ident(segment.ident);
-    if let Some(ref parameters) = segment.parameters {
-        visitor.visit_path_parameters(path_span, parameters);
+    if let Some(ref args) = segment.args {
+        visitor.visit_generic_args(path_span, args);
     }
 }
 
-pub fn walk_path_parameters<'a, V>(visitor: &mut V,
-                                   _path_span: Span,
-                                   path_parameters: &'a PathParameters)
+pub fn walk_generic_args<'a, V>(visitor: &mut V,
+                                _path_span: Span,
+                                generic_args: &'a GenericArgs)
     where V: Visitor<'a>,
 {
-    match *path_parameters {
-        PathParameters::AngleBracketed(ref data) => {
-            walk_list!(visitor, visit_ty, &data.types);
-            walk_list!(visitor, visit_lifetime, &data.lifetimes);
+    match *generic_args {
+        GenericArgs::AngleBracketed(ref data) => {
+            walk_list!(visitor, visit_generic_arg, &data.args);
             walk_list!(visitor, visit_assoc_type_binding, &data.bindings);
         }
-        PathParameters::Parenthesized(ref data) => {
+        GenericArgs::Parenthesized(ref data) => {
             walk_list!(visitor, visit_ty, &data.inputs);
             walk_list!(visitor, visit_ty, &data.output);
         }
@@ -472,30 +479,20 @@ pub fn walk_global_asm<'a, V: Visitor<'a>>(_: &mut V, _: &'a GlobalAsm) {
     // Empty!
 }
 
-pub fn walk_ty_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a TyParamBound) {
+pub fn walk_param_bound<'a, V: Visitor<'a>>(visitor: &mut V, bound: &'a GenericBound) {
     match *bound {
-        TraitTyParamBound(ref typ, ref modifier) => {
-            visitor.visit_poly_trait_ref(typ, modifier);
-        }
-        RegionTyParamBound(ref lifetime) => {
-            visitor.visit_lifetime(lifetime);
-        }
+        GenericBound::Trait(ref typ, ref modifier) => visitor.visit_poly_trait_ref(typ, modifier),
+        GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime),
     }
 }
 
 pub fn walk_generic_param<'a, V: Visitor<'a>>(visitor: &mut V, param: &'a GenericParam) {
-    match *param {
-        GenericParam::Lifetime(ref l) => {
-            visitor.visit_ident(l.lifetime.ident);
-            walk_list!(visitor, visit_lifetime, &l.bounds);
-            walk_list!(visitor, visit_attribute, &*l.attrs);
-        }
-        GenericParam::Type(ref t) => {
-            visitor.visit_ident(t.ident);
-            walk_list!(visitor, visit_ty_param_bound, &t.bounds);
-            walk_list!(visitor, visit_ty, &t.default);
-            walk_list!(visitor, visit_attribute, &*t.attrs);
-        }
+    visitor.visit_ident(param.ident);
+    walk_list!(visitor, visit_attribute, param.attrs.iter());
+    walk_list!(visitor, visit_param_bound, &param.bounds);
+    match param.kind {
+        GenericParamKind::Lifetime => {}
+        GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default),
     }
 }
 
@@ -511,14 +508,14 @@ pub fn walk_where_predicate<'a, V: Visitor<'a>>(visitor: &mut V, predicate: &'a
                                                            ref bound_generic_params,
                                                            ..}) => {
             visitor.visit_ty(bounded_ty);
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_generic_param, bound_generic_params);
         }
         WherePredicate::RegionPredicate(WhereRegionPredicate{ref lifetime,
                                                              ref bounds,
                                                              ..}) => {
             visitor.visit_lifetime(lifetime);
-            walk_list!(visitor, visit_lifetime, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
         }
         WherePredicate::EqPredicate(WhereEqPredicate{ref lhs_ty,
                                                      ref rhs_ty,
@@ -579,7 +576,7 @@ pub fn walk_trait_item<'a, V: Visitor<'a>>(visitor: &mut V, trait_item: &'a Trai
                              &sig.decl, trait_item.span, trait_item.id);
         }
         TraitItemKind::Type(ref bounds, ref default) => {
-            walk_list!(visitor, visit_ty_param_bound, bounds);
+            walk_list!(visitor, visit_param_bound, bounds);
             walk_list!(visitor, visit_ty, default);
         }
         TraitItemKind::Macro(ref mac) => {
index dec24d13c9b493fd766013b773c612a14f966f0a..9aeac5b1ddb2ae9937cb952897cde1b90e4cda49 100644 (file)
@@ -13,6 +13,7 @@
 use deriving::generic::ty::*;
 
 use syntax::ast::{self, Expr, Generics, ItemKind, MetaItem, VariantData};
+use syntax::ast::GenericArg;
 use syntax::attr;
 use syntax::ext::base::{Annotatable, ExtCtxt};
 use syntax::ext::build::AstBuilder;
@@ -48,7 +49,10 @@ pub fn expand_deriving_clone(cx: &mut ExtCtxt,
                 ItemKind::Struct(_, Generics { ref params, .. }) |
                 ItemKind::Enum(_, Generics { ref params, .. }) => {
                     if attr::contains_name(&annitem.attrs, "rustc_copy_clone_marker") &&
-                        !params.iter().any(|param| param.is_type_param())
+                        !params.iter().any(|param| match param.kind {
+                            ast::GenericParamKind::Type { .. } => true,
+                            _ => false,
+                        })
                     {
                         bounds = vec![];
                         is_shallow = true;
@@ -123,7 +127,7 @@ fn assert_ty_bounds(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>,
         let span = span.with_ctxt(cx.backtrace());
         let assert_path = cx.path_all(span, true,
                                         cx.std_path(&["clone", helper_name]),
-                                        vec![], vec![ty], vec![]);
+                                        vec![GenericArg::Type(ty)], vec![]);
         stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path)));
     }
     fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>, variant: &VariantData) {
index 237c8654edf6ea127ca5873be4afba2b6ba6243d..00ab39032acbd2489dbdc6273ca1812d1a8f9259 100644 (file)
@@ -12,7 +12,7 @@
 use deriving::generic::*;
 use deriving::generic::ty::*;
 
-use syntax::ast::{self, Expr, MetaItem};
+use syntax::ast::{self, Expr, MetaItem, GenericArg};
 use syntax::ext::base::{Annotatable, ExtCtxt};
 use syntax::ext::build::AstBuilder;
 use syntax::ptr::P;
@@ -62,7 +62,7 @@ fn assert_ty_bounds(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>,
         let span = span.with_ctxt(cx.backtrace());
         let assert_path = cx.path_all(span, true,
                                         cx.std_path(&["cmp", helper_name]),
-                                        vec![], vec![ty], vec![]);
+                                        vec![GenericArg::Type(ty)], vec![]);
         stmts.push(cx.stmt_let_type_only(span, cx.ty_path(assert_path)));
     }
     fn process_variant(cx: &mut ExtCtxt, stmts: &mut Vec<ast::Stmt>, variant: &ast::VariantData) {
index 80f65957c39a2e3935c41ef99b961c2c083e50bd..672726d1475793e80340bda13a7e6bb66e3cc243 100644 (file)
 use std::vec;
 
 use rustc_target::spec::abi::Abi;
-use syntax::ast::{
-    self, BinOpKind, EnumDef, Expr, GenericParam, Generics, Ident, PatKind, VariantData
-};
-
+use syntax::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind};
+use syntax::ast::{VariantData, GenericParamKind, GenericArg};
 use syntax::attr;
 use syntax::ext::base::{Annotatable, ExtCtxt};
 use syntax::ext::build::AstBuilder;
@@ -424,7 +422,10 @@ pub fn expand_ext(self,
                     ast::ItemKind::Struct(_, ref generics) |
                     ast::ItemKind::Enum(_, ref generics) |
                     ast::ItemKind::Union(_, ref generics) => {
-                        !generics.params.iter().any(|p| p.is_type_param())
+                        !generics.params.iter().any(|param| match param.kind {
+                            ast::GenericParamKind::Type { .. } => true,
+                            _ => false,
+                        })
                     }
                     _ => {
                         // Non-ADT derive is an error, but it should have been
@@ -548,30 +549,27 @@ fn create_derived_impl(&self,
             .to_generics(cx, self.span, type_ident, generics);
 
         // Create the generic parameters
-        params.extend(generics.params.iter().map(|param| {
-            match *param {
-                ref l @ GenericParam::Lifetime(_) => l.clone(),
-                GenericParam::Type(ref ty_param) => {
-                    // I don't think this can be moved out of the loop, since
-                    // a TyParamBound requires an ast id
-                    let mut bounds: Vec<_> =
-                        // extra restrictions on the generics parameters to the
-                        // type being derived upon
-                        self.additional_bounds.iter().map(|p| {
-                            cx.typarambound(p.to_path(cx, self.span,
-                                                        type_ident, generics))
-                        }).collect();
-
-                    // require the current trait
-                    bounds.push(cx.typarambound(trait_path.clone()));
-
-                    // also add in any bounds from the declaration
-                    for declared_bound in ty_param.bounds.iter() {
-                        bounds.push((*declared_bound).clone());
-                    }
-
-                    GenericParam::Type(cx.typaram(self.span, ty_param.ident, vec![], bounds, None))
+        params.extend(generics.params.iter().map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => param.clone(),
+            GenericParamKind::Type { .. } => {
+                // I don't think this can be moved out of the loop, since
+                // a GenericBound requires an ast id
+                let mut bounds: Vec<_> =
+                    // extra restrictions on the generics parameters to the
+                    // type being derived upon
+                    self.additional_bounds.iter().map(|p| {
+                        cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))
+                    }).collect();
+
+                // require the current trait
+                bounds.push(cx.trait_bound(trait_path.clone()));
+
+                // also add in any bounds from the declaration
+                for declared_bound in &param.bounds {
+                    bounds.push((*declared_bound).clone());
                 }
+
+                cx.typaram(self.span, param.ident, vec![], bounds, None)
             }
         }));
 
@@ -608,8 +606,8 @@ fn create_derived_impl(&self,
             // Extra scope required here so ty_params goes out of scope before params is moved
 
             let mut ty_params = params.iter()
-                .filter_map(|param| match *param {
-                    ast::GenericParam::Type(ref t) => Some(t),
+                .filter_map(|param| match param.kind {
+                    ast::GenericParamKind::Type { .. } => Some(param),
                     _ => None,
                 })
                 .peekable();
@@ -636,12 +634,12 @@ fn create_derived_impl(&self,
                         let mut bounds: Vec<_> = self.additional_bounds
                             .iter()
                             .map(|p| {
-                                cx.typarambound(p.to_path(cx, self.span, type_ident, generics))
+                                cx.trait_bound(p.to_path(cx, self.span, type_ident, generics))
                             })
                             .collect();
 
                         // require the current trait
-                        bounds.push(cx.typarambound(trait_path.clone()));
+                        bounds.push(cx.trait_bound(trait_path.clone()));
 
                         let predicate = ast::WhereBoundPredicate {
                             span: self.span,
@@ -666,31 +664,18 @@ fn create_derived_impl(&self,
         // Create the reference to the trait.
         let trait_ref = cx.trait_ref(trait_path);
 
-        // Create the type parameters on the `self` path.
-        let self_ty_params = generics.params
-            .iter()
-            .filter_map(|param| match *param {
-                GenericParam::Type(ref ty_param)
-                    => Some(cx.ty_ident(self.span, ty_param.ident)),
-                _ => None,
-            })
-            .collect();
-
-        let self_lifetimes: Vec<ast::Lifetime> = generics.params
-            .iter()
-            .filter_map(|param| match *param {
-                GenericParam::Lifetime(ref ld) => Some(ld.lifetime),
-                _ => None,
-            })
-            .collect();
+        let self_params: Vec<_> = generics.params.iter().map(|param| match param.kind {
+            GenericParamKind::Lifetime { .. } => {
+                GenericArg::Lifetime(cx.lifetime(self.span, param.ident))
+            }
+            GenericParamKind::Type { .. } => {
+                GenericArg::Type(cx.ty_ident(self.span, param.ident))
+            }
+        }).collect();
 
         // Create the type of `self`.
-        let self_type = cx.ty_path(cx.path_all(self.span,
-                                               false,
-                                               vec![type_ident],
-                                               self_lifetimes,
-                                               self_ty_params,
-                                               Vec::new()));
+        let path = cx.path_all(self.span, false, vec![type_ident], self_params, vec![]);
+        let self_type = cx.ty_path(path);
 
         let attr = cx.attribute(self.span,
                                 cx.meta_word(self.span,
index 25a2969448835dca4ba648e9be841b01dd61ee0f..0b809ab585cdcb9cd2e927e74640049e8bf4f94a 100644 (file)
@@ -15,7 +15,7 @@
 pub use self::Ty::*;
 
 use syntax::ast;
-use syntax::ast::{Expr, GenericParam, Generics, Ident, SelfKind};
+use syntax::ast::{Expr, GenericParamKind, Generics, Ident, SelfKind, GenericArg};
 use syntax::ext::base::ExtCtxt;
 use syntax::ext::build::AstBuilder;
 use syntax::codemap::{respan, DUMMY_SP};
@@ -86,15 +86,20 @@ pub fn to_path(&self,
                    -> ast::Path {
         let mut idents = self.path.iter().map(|s| cx.ident_of(*s)).collect();
         let lt = mk_lifetimes(cx, span, &self.lifetime);
-        let tys = self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect();
+        let tys: Vec<P<ast::Ty>> =
+            self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect();
+        let params = lt.into_iter()
+                       .map(|lt| GenericArg::Lifetime(lt))
+                       .chain(tys.into_iter().map(|ty| GenericArg::Type(ty)))
+                       .collect();
 
         match self.kind {
-            PathKind::Global => cx.path_all(span, true, idents, lt, tys, Vec::new()),
-            PathKind::Local => cx.path_all(span, false, idents, lt, tys, Vec::new()),
+            PathKind::Global => cx.path_all(span, true, idents, params, Vec::new()),
+            PathKind::Local => cx.path_all(span, false, idents, params, Vec::new()),
             PathKind::Std => {
                 let def_site = DUMMY_SP.apply_mark(cx.current_expansion.mark);
                 idents.insert(0, Ident::new(keywords::DollarCrate.name(), def_site));
-                cx.path_all(span, false, idents, lt, tys, Vec::new())
+                cx.path_all(span, false, idents, params, Vec::new())
             }
         }
 
@@ -180,34 +185,22 @@ pub fn to_path(&self,
                    cx: &ExtCtxt,
                    span: Span,
                    self_ty: Ident,
-                   self_generics: &Generics)
+                   generics: &Generics)
                    -> ast::Path {
         match *self {
             Self_ => {
-                let self_params = self_generics.params
-                    .iter()
-                    .filter_map(|param| match *param {
-                        GenericParam::Type(ref ty_param) => Some(cx.ty_ident(span, ty_param.ident)),
-                        _ => None,
-                    })
-                    .collect();
-
-                let lifetimes: Vec<ast::Lifetime> = self_generics.params
-                    .iter()
-                    .filter_map(|param| match *param {
-                        GenericParam::Lifetime(ref ld) => Some(ld.lifetime),
-                        _ => None,
-                    })
-                    .collect();
+                let params: Vec<_> = generics.params.iter().map(|param| match param.kind {
+                    GenericParamKind::Lifetime { .. } => {
+                        GenericArg::Lifetime(ast::Lifetime { id: param.id, ident: param.ident })
+                    }
+                    GenericParamKind::Type { .. } => {
+                        GenericArg::Type(cx.ty_ident(span, param.ident))
+                    }
+                }).collect();
 
-                cx.path_all(span,
-                            false,
-                            vec![self_ty],
-                            lifetimes,
-                            self_params,
-                            Vec::new())
+                cx.path_all(span, false, vec![self_ty], params, vec![])
             }
-            Literal(ref p) => p.to_path(cx, span, self_ty, self_generics),
+            Literal(ref p) => p.to_path(cx, span, self_ty, generics),
             Ptr(..) => cx.span_bug(span, "pointer in a path in generic `derive`"),
             Tuple(..) => cx.span_bug(span, "tuple in a path in generic `derive`"),
         }
@@ -222,17 +215,17 @@ fn mk_ty_param(cx: &ExtCtxt,
                bounds: &[Path],
                self_ident: Ident,
                self_generics: &Generics)
-               -> ast::TyParam {
+               -> ast::GenericParam {
     let bounds = bounds.iter()
         .map(|b| {
             let path = b.to_path(cx, span, self_ident, self_generics);
-            cx.typarambound(path)
+            cx.trait_bound(path)
         })
         .collect();
     cx.typaram(span, cx.ident_of(name), attrs.to_owned(), bounds, None)
 }
 
-fn mk_generics(params: Vec<GenericParam>, span: Span) -> Generics {
+fn mk_generics(params: Vec<ast::GenericParam>, span: Span) -> Generics {
     Generics {
         params,
         where_clause: ast::WhereClause {
@@ -268,17 +261,14 @@ pub fn to_generics(&self,
             .iter()
             .map(|&(lt, ref bounds)| {
                 let bounds = bounds.iter()
-                    .map(|b| cx.lifetime(span, Ident::from_str(b)))
-                    .collect();
-                GenericParam::Lifetime(cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds))
+                    .map(|b| ast::GenericBound::Outlives(cx.lifetime(span, Ident::from_str(b))));
+                cx.lifetime_def(span, Ident::from_str(lt), vec![], bounds.collect())
             })
             .chain(self.bounds
                 .iter()
                 .map(|t| {
                     let (name, ref bounds) = *t;
-                    GenericParam::Type(mk_ty_param(
-                        cx, span, name, &[], &bounds, self_ty, self_generics
-                    ))
+                    mk_ty_param(cx, span, name, &[], &bounds, self_ty, self_generics)
                 })
             )
             .collect();
index a5b348a661a78a5ed78e2f7f24022a945d79753a..6ff385b18e8bf41187de2b5511db7c3d973b6c90 100644 (file)
@@ -134,9 +134,12 @@ fn hygienic_type_parameter(item: &Annotatable, base: &str) -> String {
         match item.node {
             ast::ItemKind::Struct(_, ast::Generics { ref params, .. }) |
             ast::ItemKind::Enum(_, ast::Generics { ref params, .. }) => {
-                for param in params.iter() {
-                    if let ast::GenericParam::Type(ref ty) = *param{
-                        typaram.push_str(&ty.ident.as_str());
+                for param in params {
+                    match param.kind {
+                        ast::GenericParamKind::Type { .. } => {
+                            typaram.push_str(&param.ident.as_str());
+                        }
+                        _ => {}
                     }
                 }
             }
index 4e1af108ab4fa038765d01da23b0977a3d5922ce..bbc5b03d6885eaa3f1a69cf2119b7d12f3550827 100644 (file)
@@ -13,7 +13,7 @@
 // interface.
 //
 
-use syntax::ast::{self, Ident};
+use syntax::ast::{self, Ident, GenericArg};
 use syntax::ext::base::*;
 use syntax::ext::base;
 use syntax::ext::build::AstBuilder;
@@ -39,12 +39,11 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt,
             cx.expr_path(cx.path_all(sp,
                                      true,
                                      cx.std_path(&["option", "Option", "None"]),
-                                     Vec::new(),
-                                     vec![cx.ty_rptr(sp,
+                                     vec![GenericArg::Type(cx.ty_rptr(sp,
                                                      cx.ty_ident(sp, Ident::from_str("str")),
                                                      Some(lt),
-                                                     ast::Mutability::Immutable)],
-                                     Vec::new()))
+                                                     ast::Mutability::Immutable))],
+                                     vec![]))
         }
         Ok(s) => {
             cx.expr_call_global(sp,
index d5e412c3745e0e50030b289ed799126ea52d0040..ee9dafdd49eb86c897d6ed4672ff8dd0d54e5248 100644 (file)
@@ -13,6 +13,7 @@
 
 fn test() {
     let v: isize;
+    //[mir]~^ NOTE consider changing this to `mut v`
     v = 1; //[ast]~ NOTE first assignment
            //[mir]~^ NOTE first assignment
     println!("v={}", v);
index f1827022964169293e55e73260846c06158fca5e..3bb0382ef037be8299c335d675a14253ca13d9b1 100644 (file)
@@ -14,7 +14,7 @@ trait Get {
 }
 
 fn foo<T:Get>(t: T) {
-    let x = t.get(); //~ ERROR `<T as Get>::Value: std::marker::Sized` is not
+    let x = t.get(); //~ ERROR the size for value values of type
 }
 
 fn main() {
index 5be90f05018331389eddcbee6a33e2a9dbfa9061..7cef3f13dfc2cef2c574a2916f839748471d0aa0 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 fn foo<T:'static>() {
-    1.bar::<T>(); //~ ERROR `T: std::marker::Send` is not satisfied
+    1.bar::<T>(); //~ ERROR `T` cannot be sent between threads safely
 }
 
 trait bar {
index df3da5096bf538d9d57639d729b92b178b0bbcb3..9b87ec4d446cd155bf5ce4f2a8b18317973b20fb 100644 (file)
@@ -13,6 +13,6 @@ trait Trait {}
 pub fn main() {
     let x: Vec<Trait + Sized> = Vec::new();
     //~^ ERROR only auto traits can be used as additional traits in a trait object
-    //~| ERROR the trait bound `Trait: std::marker::Sized` is not satisfied
-    //~| ERROR the trait bound `Trait: std::marker::Sized` is not satisfied
+    //~| ERROR the size for value values of type
+    //~| ERROR the size for value values of type
 }
index fbdd013024db56d5663960ffada8f7ca5e4d50e7..3c5f932af47cec42ed4ab5780b5ccb4ba5ab2051 100644 (file)
@@ -27,7 +27,7 @@ fn indirect_write_to_imm_box() {
     let y: Box<_> = box &mut x;
     let p = &y;
     ***p = 2; //[ast]~ ERROR cannot assign to data in a `&` reference
-              //[mir]~^ ERROR cannot assign to data in a `&` reference
+              //[mir]~^ ERROR cannot assign to `***p`
     drop(p);
 }
 
index 109fe3d1128e1990b186e36158e679b864db127d..f4f40e0407fded4e6443df9cf009877b248c0730 100644 (file)
@@ -70,6 +70,6 @@ fn main() {
     };
     s[2] = 20;
     //[ast]~^ ERROR cannot assign to immutable indexed content
-    //[mir]~^^ ERROR cannot assign to immutable item
+    //[mir]~^^ ERROR cannot assign to data in a `&` reference
     drop(rs);
 }
index 261881d880bf9fcd8074f34c6d371cfa86046114..3f7f2adabdfb114d5dae43c5502319c942028642 100644 (file)
@@ -14,7 +14,7 @@
 trait Foo : Send+Sync { }
 
 impl <T: Sync+'static> Foo for (T,) { }
-//~^ ERROR the trait bound `T: std::marker::Send` is not satisfied in `(T,)` [E0277]
+//~^ ERROR `T` cannot be sent between threads safely [E0277]
 
 impl <T: Send> Foo for (T,T) { }
 //~^ ERROR `T` cannot be shared between threads safely [E0277]
index de2084c4e8187baa3d52ae9dc0323d8c128ba662..88b5a3fbb55b63337fbcd6cb14cacf4f8580f12d 100644 (file)
@@ -22,6 +22,6 @@
 impl <T:Sync> RequiresShare for X<T> { }
 
 impl <T:Sync+'static> RequiresRequiresShareAndSend for X<T> { }
-//~^ ERROR `T: std::marker::Send` is not satisfied
+//~^ ERROR `T` cannot be sent between threads safely [E0277]
 
 fn main() { }
index 6dc5f39cb30dfa05a8cc741781deed0fd0bffefe..22dc9598d29ca1d373d409a63d9a5c261434a53e 100644 (file)
@@ -14,6 +14,6 @@
 trait Foo : Send { }
 
 impl Foo for std::rc::Rc<i8> { }
-//~^ ERROR `std::rc::Rc<i8>: std::marker::Send` is not satisfied
+//~^ ERROR `std::rc::Rc<i8>` cannot be sent between threads safely
 
 fn main() { }
index d4bb8de13d056fc84ff13e5eb52853f66520524b..e0b2043c1107c80e6fdc81f7565cbdaa94455dac 100644 (file)
@@ -12,6 +12,7 @@
 
 trait Foo : Send { }
 
-impl <T: Sync+'static> Foo for T { } //~ ERROR `T: std::marker::Send` is not satisfied
+impl <T: Sync+'static> Foo for T { }
+//~^ ERROR `T` cannot be sent between threads safely
 
 fn main() { }
index b9224e7be7f12eddf404f034462e1ccabf2f7305..12e9fb30902b5a5dafc6a488393984ebee701f57 100644 (file)
@@ -13,7 +13,7 @@ struct X<F> where F: FnOnce() + 'static + Send {
 }
 
 fn foo<F>(blk: F) -> X<F> where F: FnOnce() + 'static {
-    //~^ ERROR `F: std::marker::Send` is not satisfied
+    //~^ ERROR `F` cannot be sent between threads safely
     return X { field: blk };
 }
 
index 10c8f1eed00b0dfe89e26e241c48f738d69db49d..1dbdd42ca36e267e8e32f9bdcefe0cc9f54b9431 100644 (file)
@@ -43,5 +43,6 @@ pub fn main() {
     let f5: &mut Fat<ToBar> = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} };
     let z: Box<ToBar> = Box::new(Bar1 {f: 36});
     f5.ptr = *z;
-    //~^ ERROR `ToBar: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
+
 }
index ceaa371623223647c6eed876b18004a785f465a1..5bc6c6cda263afe3ca4762d48c83bd742198d714 100644 (file)
@@ -45,5 +45,5 @@ pub fn main() {
     //~| expected type `ToBar`
     //~| found type `Bar1`
     //~| expected trait ToBar, found struct `Bar1`
-    //~| ERROR `ToBar: std::marker::Sized` is not satisfied
+    //~| ERROR the size for value values of type
 }
index 4f7d07600ad154e68712ea96b736c627d8161d0c..37b6056d1a762328eea2d61e52f245bdbd109547 100644 (file)
@@ -47,5 +47,5 @@ pub fn main() {
     //~| expected type `ToBar`
     //~| found type `Bar1`
     //~| expected trait ToBar, found struct `Bar1`
-    //~| ERROR `ToBar: std::marker::Sized` is not satisfied
+    //~| ERROR the size for value values of type
 }
index 0c812b1d815ab000da92254d3c9cf6d4affb9a6e..82d81913cd3a3dbd6a290bc52ccb72c742d61459 100644 (file)
@@ -19,5 +19,5 @@ pub fn main() {
     let f: ([isize; 3],) = ([5, 6, 7],);
     let g: &([isize],) = &f;
     let h: &(([isize],),) = &(*g,);
-    //~^ ERROR `[isize]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index f508364d75115fa74f7a10baab0c7f6f6a658a55..b8ca22185bc3c9dd33e4ca8f7c5833e2bb997eb1 100644 (file)
@@ -21,5 +21,5 @@ pub fn main() {
     let f: Fat<[isize; 3]> = Fat { ptr: [5, 6, 7] };
     let g: &Fat<[isize]> = &f;
     let h: &Fat<Fat<[isize]>> = &Fat { ptr: *g };
-    //~^ ERROR `[isize]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 8fafd78d407969ec26ee9b2cdf998a2554789a3f..4a892753595a72cb4f3c7a76550878aa8848cd05 100644 (file)
@@ -16,22 +16,22 @@ impl Foo for [u8] {}
 
 fn test1<T: ?Sized + Foo>(t: &T) {
     let u: &Foo = t;
-    //~^ ERROR `T: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn test2<T: ?Sized + Foo>(t: &T) {
     let v: &Foo = t as &Foo;
-    //~^ ERROR `T: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn test3() {
     let _: &[&Foo] = &["hi"];
-    //~^ ERROR `str: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn test4(x: &[u8]) {
     let _: &Foo = x as &Foo;
-    //~^ ERROR `[u8]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index bd5fd3ee3b71eff738117678b3e34f4cf2da068c..0679556743228c28af4c363ed92fb6b08e72ddc1 100644 (file)
@@ -15,9 +15,9 @@
 trait Foo<T> : Sized { fn take(self, x: &T) { } } // Note: T is sized
 
 impl Foo<[isize]> for usize { }
-//~^ ERROR `[isize]: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 impl Foo<isize> for [usize] { }
-//~^ ERROR `[usize]: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 pub fn main() { }
index 6a7a515ba5fbba41d5f773408bbef7d4f8300b92..10abb80a2f71b9072c0422bc60926ef4a29fec1b 100644 (file)
@@ -24,5 +24,5 @@ fn main() {
     //~^ ERROR `A` cannot be shared between threads safely [E0277]
 
     assert_send::<A>();
-    //~^ ERROR the trait bound `A: std::marker::Send` is not satisfied
+    //~^ ERROR `A` cannot be sent between threads safely [E0277]
 }
index faa27894806f8d81c7f049d90086403069e6dd97..135b466161d77a0cbe88c62d9314bf9da04eebcd 100644 (file)
@@ -30,14 +30,14 @@ fn assert_sized<T>() { }
 
 fn main() {
     assert_sized::<A>();
-    //~^ ERROR the trait bound `A: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     assert_sized::<Foo>();
-    //~^ ERROR the trait bound `A: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     assert_sized::<Bar<A>>();
-    //~^ ERROR the trait bound `A: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     assert_sized::<Bar<Bar<A>>>();
-    //~^ ERROR the trait bound `A: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 84452accc9a4ac4abec7e0134f6a81c628cbaf24..5212cbb004efadffd955977b1e68fd8367cf749e 100644 (file)
@@ -10,5 +10,5 @@
 
 fn main() {
     let _x = "test" as &::std::any::Any;
-//~^ ERROR `str: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 41349d7d7443b056bcaeb16498090e66b22ca71e..4756099ab95689c954112855ecfba28136c177e0 100644 (file)
@@ -15,7 +15,7 @@ fn dft_iter<'a, T>(arg1: Chunks<'a,T>, arg2: ChunksMut<'a,T>)
 {
     for
     &mut something
-//~^ ERROR `[T]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
     in arg2
     {
     }
index 4996da057dd8ebc7be04358282479c5810b8a486..e7019ff7c0d21193caaa0a91119a31596622cdc1 100644 (file)
@@ -13,5 +13,5 @@
 
 fn main() {
     (|| Box::new(*(&[0][..])))();
-    //~^ ERROR `[{integer}]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 33d68c121bf2674a9d11e854690129b1b5a284fe..9239ceb341fc6da523732dbd941e7ccf80195488 100644 (file)
@@ -12,7 +12,7 @@ pub trait AbstractRenderer {}
 
 fn _create_render(_: &()) ->
     AbstractRenderer
-//~^ ERROR: `AbstractRenderer + 'static: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 {
     match 0 {
         _ => unimplemented!()
index 3e21360721b6d87a9076a72e7efdea81fe9d0405..0b717ec641375d8a27af24804aef5a8ebf91263b 100644 (file)
@@ -11,7 +11,7 @@
 type FuncType<'f> = Fn(&isize) -> isize + 'f;
 
 fn ho_func(f: Option<FuncType>) {
-    //~^ ERROR: `for<'r> std::ops::Fn(&'r isize) -> isize: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {}
index c7564a9355bc5d19e3a15d85e4dbf7f3cca5896b..ccdd9db25c40a0b2e8d10b6de52ad49fda78bd1f 100644 (file)
@@ -8,5 +8,5 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// error-pattern: `main` function is not allowed to have type parameters
+// error-pattern: `main` function is not allowed to have generic parameters
 fn main<T>() { }
index b02757fb5a3133acdf5f81f1fdda9a98f644d0bd..426657ac92e2c868a902d9edec48f5701ce410e4 100644 (file)
@@ -15,7 +15,7 @@ trait From<Src> {
 }
 
 trait To {
-    fn to<Dst>(  //~ ERROR `Self: std::marker::Sized` is not satisfied
+    fn to<Dst>(  //~ ERROR the size for value values of type
         self
     ) -> <Dst as From<Self>>::Result where Dst: From<Self> {
         From::from(self)
index d1a139e698e12e78e876973aad18e49a00524495..8b7f2d5a4588e3334ce464e0959643bf2cc52a19 100644 (file)
@@ -14,5 +14,5 @@ fn main() {}
 
 impl The {
     fn iceman(c: Vec<[i32]>) {}
-    //~^ ERROR the trait bound `[i32]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 5eb0e4360fc93beeb208a294674ca837dded48d3..2d8d9c6565532c84ed65e24bb2b07a9e41c627f9 100644 (file)
@@ -10,7 +10,7 @@
 
 fn changer<'a>(mut things: Box<Iterator<Item=&'a mut u8>>) {
     for item in *things { *item = 0 }
-//~^ ERROR the trait bound `std::iter::Iterator<Item=&mut u8>: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 }
 
 fn main() {}
index cb0baee0a8787d538d5f484dc4bd15f34014cf55..b4f952c87d4aae25a705d07395a95812b67fcf1e 100644 (file)
@@ -17,5 +17,5 @@ fn foo<T: Send>() {}
 
 fn main() {
     foo::<HashMap<Rc<()>, Rc<()>>>();
-    //~^ ERROR: `std::rc::Rc<()>: std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<()>` cannot be sent between threads safely
 }
index 0df84a436c0a936f0409dd159ac6f8934e09d428..cb199580b10dd182137a89de62dd8404dea87a63 100644 (file)
@@ -10,7 +10,7 @@
 
 struct Table {
     rows: [[String]],
-    //~^ ERROR the trait bound `[std::string::String]: std::marker::Sized` is not satisfied [E0277]
+    //~^ ERROR the size for value values of type
 }
 
 fn f(table: &Table) -> &[String] {
index 5feeb36b1e4d4f86a833270e19edbbedcbf2fbb8..d6b5c32982554a3055ff4e911552bc4cd994fc6b 100644 (file)
@@ -14,7 +14,7 @@
 
 impl Struct {
     pub fn function(funs: Vec<Fn() -> ()>) {}
-    //~^ ERROR the trait bound `std::ops::Fn() + 'static: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {}
index acd50bcf9e112fa0d608ba26e8f97f1c61b8f49b..74c68c50ae35aee6b8a773654d14a81c254f35d9 100644 (file)
@@ -10,8 +10,8 @@
 
 fn main() {
     static foo: Fn() -> u32 = || -> u32 {
-        //~^ ERROR: mismatched types
-        //~| ERROR: `std::ops::Fn() -> u32 + 'static: std::marker::Sized` is not satisfied
+        //~^ ERROR mismatched types
+        //~| ERROR the size for value values of type
         0
     };
 }
index 28180b05c8de8dcca986f5a6e34915d90f3df295..bc5567e1686d3ac16b35849c5d07f26cf8860c06 100644 (file)
@@ -10,7 +10,7 @@
 
 #[repr(packed)]
 pub struct Bad<T: ?Sized> {
-    data: T, //~ ERROR `T: std::marker::Sized` is not satisfied
+    data: T, //~ ERROR the size for value values of type
 }
 
 fn main() {}
index f34bef6224900620123f4fba8659e892f0efb9e6..6efc1f1024317ff8853c46faf4939921b845fb1f 100644 (file)
@@ -13,7 +13,7 @@
 trait Foo {
     const BAR: i32;
     fn foo(self) -> &'static i32 {
-        //~^ ERROR the trait bound `Self: std::marker::Sized` is not satisfied
+        //~^ ERROR the size for value values of type
         &<Self>::BAR
     }
 }
index c2e6a88a57bff7fedbc12259fc8e5c7229e9f88b..805b1a48a038012a67f2be38acb4ec080bcce1c3 100644 (file)
@@ -10,7 +10,7 @@
 
 enum E {
     V([Box<E>]),
-    //~^ ERROR the trait bound `[std::boxed::Box<E>]: std::marker::Sized` is not satisfied [E0277]
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {}
index 896728b6da0f1df15d6b1a26f692556cd869f3cc..1b64d17bbeffe4b1de41f6c66aacbf2c465f68c1 100644 (file)
@@ -9,6 +9,6 @@
 // except according to those terms.
 
 fn _test(ref _p: str) {}
-//~^ ERROR the trait bound `str: std::marker::Sized` is not satisfied [E0277]
+//~^ ERROR the size for value values of type
 
 fn main() { }
index 31bc21c23ba5f08e1f2306a097717b9f4d041986..6207e669d0092ad790c994b743d3714bbe805a34 100644 (file)
@@ -9,8 +9,6 @@
 // except according to those terms.
 
 pub fn example(ref s: str) {}
-//~^ ERROR the trait bound `str: std::marker::Sized` is not satisfied
-//~| `str` does not have a constant size known at compile-time
-//~| the trait `std::marker::Sized` is not implemented for `str`
+//~^ ERROR the size for value values of type
 
 fn main() {}
index 06573b42b592db5c0dd61dc9ce62f311e39af538..2ab44433ede82151cd1e97320ad70b2127a26807 100644 (file)
 
 pub trait Foo {
     fn baz(_: Self::Target) where Self: Deref {}
-    //~^ ERROR `<Self as std::ops::Deref>::Target: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 pub fn f(_: ToString) {}
-//~^ ERROR the trait bound `std::string::ToString + 'static: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 fn main() { }
index ecddb4c101fdf7f89d26008f9ff4768dc2e513fd..61e19ffc0d293b7db19a27131db79728eddaecb5 100644 (file)
@@ -13,6 +13,7 @@
 
 fn test_drop_replace() {
     let b: Box<isize>;
+    //[mir]~^ NOTE consider changing this to `mut b`
     b = Box::new(1);    //[ast]~ NOTE first assignment
                         //[mir]~^ NOTE first assignment
     b = Box::new(2);    //[ast]~ ERROR cannot assign twice to immutable variable
@@ -24,6 +25,7 @@ fn test_drop_replace() {
 fn test_call() {
     let b = Box::new(1);    //[ast]~ NOTE first assignment
                             //[mir]~^ NOTE first assignment
+                            //[mir]~| NOTE consider changing this to `mut b`
     b = Box::new(2);        //[ast]~ ERROR cannot assign twice to immutable variable
                             //[mir]~^ ERROR cannot assign twice to immutable variable `b`
                             //[ast]~| NOTE cannot assign twice to immutable
@@ -31,7 +33,7 @@ fn test_call() {
 }
 
 fn test_args(b: Box<i32>) {  //[ast]~ NOTE first assignment
-                                //[mir]~^ NOTE argument not declared as `mut`
+                                //[mir]~^ NOTE consider changing this to `mut b`
     b = Box::new(2);            //[ast]~ ERROR cannot assign twice to immutable variable
                                 //[mir]~^ ERROR cannot assign to immutable argument `b`
                                 //[ast]~| NOTE cannot assign twice to immutable
index e14d9f3a35c84ff0fda9e7f8eeca93feb2eb796a..82d4666ce549ca1a68de9c2fb58ba98a40e995b4 100644 (file)
@@ -15,8 +15,8 @@ struct Struct {
 }
 
 fn new_struct(r: A+'static)
-    -> Struct { //~^  ERROR `A + 'static: std::marker::Sized` is not satisfied
-    //~^ ERROR `A + 'static: std::marker::Sized` is not satisfied
+    -> Struct { //~^ ERROR the size for value values of type
+    //~^ ERROR the size for value values of type
     Struct { r: r }
 }
 
index 95bbd4eccf4ff08cebdb83bcad077d0847a4ebbf..0c19780bcb4cab442589df9fd9f661689308f137 100644 (file)
@@ -34,5 +34,5 @@ struct A {
 
 fn main() {
     let a = A {v: box B{v: None} as Box<Foo+Send>};
-    //~^ ERROR `std::rc::Rc<std::cell::RefCell<A>>: std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<std::cell::RefCell<A>>` cannot be sent between threads safely
 }
index 2a86cdef9812fb88da2b80c8950634921f6648a9..3a0e66f58e0765e0fd48d7a6726ae4451eb1f2bc 100644 (file)
@@ -26,15 +26,15 @@ impl<T: Send + Copy + 'static> Gettable<T> for S<T> {}
 fn f<T>(val: T) {
     let t: S<T> = S(marker::PhantomData);
     let a = &t as &Gettable<T>;
-    //~^ ERROR : std::marker::Send` is not satisfied
-    //~^^ ERROR : std::marker::Copy` is not satisfied
+    //~^ ERROR `T` cannot be sent between threads safely
+    //~| ERROR : std::marker::Copy` is not satisfied
 }
 
 fn g<T>(val: T) {
     let t: S<T> = S(marker::PhantomData);
     let a: &Gettable<T> = &t;
-    //~^ ERROR : std::marker::Send` is not satisfied
-    //~^^ ERROR : std::marker::Copy` is not satisfied
+    //~^ ERROR `T` cannot be sent between threads safely
+    //~| ERROR : std::marker::Copy` is not satisfied
 }
 
 fn foo<'a>() {
index dd77c2c138f4622df9b7a129959b05fb95e37d46..43c212b2af58278d8e7efe365edd2254d322e9e4 100644 (file)
@@ -18,5 +18,5 @@ fn bar<F:FnOnce() + Send>(_: F) { }
 fn main() {
     let x = Rc::new(3);
     bar(move|| foo(x));
-    //~^ ERROR : std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<usize>` cannot be sent between threads safely
 }
index a84eae0bfdae86c23b76bc403a58953f8ade4b48..a3eb47be3eed8a4212e2a9a7e233b5c0b25f6dee 100644 (file)
@@ -24,7 +24,8 @@ fn object_ref_with_static_bound_not_ok() {
 }
 
 fn box_object_with_no_bound_not_ok<'a>() {
-    assert_send::<Box<Dummy>>(); //~ ERROR : std::marker::Send` is not satisfied
+    assert_send::<Box<Dummy>>();
+    //~^ ERROR `Dummy` cannot be sent between threads safely
 }
 
 fn object_with_send_bound_ok() {
index 66865bbcc7ee12f162c7529f53bacd385e79b40f..673a6abc5f03df178b0abbf78bf8efc120e75c5b 100644 (file)
@@ -37,7 +37,7 @@ fn test61() {
 // them not ok
 fn test_71<'a>() {
     assert_send::<Box<Dummy+'a>>();
-    //~^ ERROR : std::marker::Send` is not satisfied
+    //~^ ERROR `Dummy + 'a` cannot be sent between threads safely
 }
 
 fn main() { }
index 51bc587d74ff83e5d84d179886a35fec57fcca2b..3a935af200054a0e3d6f20460fb88038cbe15090 100644 (file)
@@ -19,7 +19,8 @@ fn test50() {
 }
 
 fn test53() {
-    assert_send::<Box<Dummy>>(); //~ ERROR : std::marker::Send` is not satisfied
+    assert_send::<Box<Dummy>>();
+    //~^ ERROR `Dummy` cannot be sent between threads safely
 }
 
 // ...unless they are properly bounded
index 583381a1c28f5b23fc9753f8e2ef25f9b1dde529..e48460a87537f2d5aa62d2d41c6fb0e8d375696e 100644 (file)
@@ -19,7 +19,8 @@ fn assert_send<T:Send>() { }
 
 // but not if they own a bad thing
 fn test40() {
-    assert_send::<Box<*mut u8>>(); //~ ERROR : std::marker::Send` is not satisfied
+    assert_send::<Box<*mut u8>>();
+    //~^ ERROR `*mut u8` cannot be sent between threads safely
 }
 
 fn main() { }
index c717d1a72e05d31c536274cee20a703deb0062b2..99b995b0906b4edd66f0a2ee9a1770fd4a4c1389 100644 (file)
@@ -14,7 +14,7 @@ fn assert_send<T:Send>() { }
 
 fn test71<'a>() {
     assert_send::<*mut &'a isize>();
-    //~^ ERROR `*mut &'a isize: std::marker::Send` is not satisfied
+    //~^ ERROR `*mut &'a isize` cannot be sent between threads safely
 }
 
 fn main() {
index f28906ddb955fccd02f1d4e21a1cf9be1a1ffe4c..7bc3680ca772343b51bafa75f343847445487c0d 100644 (file)
@@ -13,6 +13,7 @@
 
 fn test() {
     let v: isize;
+    //[mir]~^ NOTE consider changing this to `mut v`
     loop {
         v = 1; //[ast]~ ERROR cannot assign twice to immutable variable
                //[mir]~^ ERROR cannot assign twice to immutable variable `v`
index 594cc0761214aa2fbd2892af7ae34d0c100fe1e8..7812cdd8684f6c773599909581afcb7db2c2498e 100644 (file)
@@ -13,6 +13,7 @@
 
 fn test() {
     let v: isize;
+    //[mir]~^ NOTE consider changing this to `mut v`
     v = 2;  //[ast]~ NOTE first assignment
             //[mir]~^ NOTE first assignment
     v += 1; //[ast]~ ERROR cannot assign twice to immutable variable
index b4fb33ca15e2660d77c0ef5a937e2ebed5311806..bb61a9037d906c9b80939e26350de5ca426c5b64 100644 (file)
@@ -14,6 +14,7 @@
 fn test() {
     let b = Box::new(1); //[ast]~ NOTE first assignment
                          //[mir]~^ NOTE first assignment
+                         //[mir]~| NOTE consider changing this to `mut b`
     drop(b);
     b = Box::new(2); //[ast]~ ERROR cannot assign twice to immutable variable
                      //[mir]~^ ERROR cannot assign twice to immutable variable `b`
index 7204b5d5f2e169e742f1c5d33c499418a71eed47..672e9fab83743b8bf7b668fa17029850878ace20 100644 (file)
@@ -14,6 +14,7 @@
 fn test() {
     let v: isize = 1; //[ast]~ NOTE first assignment
                       //[mir]~^ NOTE first assignment
+                      //[mir]~| NOTE consider changing this to `mut v`
     v.clone();
     v = 2; //[ast]~ ERROR cannot assign twice to immutable variable
            //[mir]~^ ERROR cannot assign twice to immutable variable `v`
index 334952cefa6e02f9612f3e761db590f966a07159..6825963c486470f69e41692e8e1a8f7058ef1fd0 100644 (file)
@@ -33,7 +33,7 @@ fn foo(x: Port<()>) -> foo {
     let x = foo(Port(Rc::new(())));
 
     thread::spawn(move|| {
-        //~^ ERROR `std::rc::Rc<()>: std::marker::Send` is not satisfied
+        //~^ ERROR `std::rc::Rc<()>` cannot be sent between threads safely
         let y = x;
         println!("{:?}", y);
     });
index 902710e96e274fbc0ffc8a83d61e739741ff1ded..83f19ed19efc22a5c0f3c4eb00388e6ea0ad45a9 100644 (file)
@@ -24,5 +24,5 @@ fn bar<T: Send>(_: T) {}
 fn main() {
     let x = Foo::A(NoSend);
     bar(x);
-    //~^ ERROR `NoSend: std::marker::Send` is not satisfied
+    //~^ ERROR `NoSend` cannot be sent between threads safely
 }
index f31d3787334916bffb1565d63bd1eaf5df7067a8..d3616d144229c648e8731f9034c7f2ce92946227 100644 (file)
@@ -15,5 +15,5 @@ fn bar<T: Send>(_: T) {}
 fn main() {
     let x = Rc::new(5);
     bar(x);
-    //~^ ERROR `std::rc::Rc<{integer}>: std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<{integer}>` cannot be sent between threads safely
 }
index b2ca4f9f5db16bb76a749cf8478733ded2a68b5e..d38d993e7e8e6f2af7b56da73b498f88b12b981b 100644 (file)
@@ -23,5 +23,5 @@ fn bar<T: Send>(_: T) {}
 fn main() {
     let x = Foo { a: 5 };
     bar(x);
-    //~^ ERROR `Foo: std::marker::Send` is not satisfied
+    //~^ ERROR `Foo` cannot be sent between threads safely
 }
index 7107211fc914b47479b2569515fee614191cca08..d750851b719e4e691a7691c24255a2480503c6df 100644 (file)
@@ -18,6 +18,6 @@ fn assert<T: UnwindSafe + ?Sized>() {}
 
 fn main() {
     assert::<Rc<RefCell<i32>>>();
-    //~^ ERROR `std::cell::UnsafeCell<i32>: std::panic::RefUnwindSafe` is not satisfied
-    //~^^ ERROR `std::cell::UnsafeCell<usize>: std::panic::RefUnwindSafe` is not satisfied
+    //~^ ERROR the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a
+    //~| ERROR the type `std::cell::UnsafeCell<usize>` may contain interior mutability and a
 }
index 76c34e4dc0b448613ddaef1d2041ad8bc15f18dd..cd27b274258ea3d49619ef0622576c6cf22a003e 100644 (file)
@@ -18,6 +18,6 @@ fn assert<T: UnwindSafe + ?Sized>() {}
 
 fn main() {
     assert::<Arc<RefCell<i32>>>();
-    //~^ ERROR `std::cell::UnsafeCell<i32>: std::panic::RefUnwindSafe` is not satisfied
-    //~^^ ERROR `std::cell::UnsafeCell<usize>: std::panic::RefUnwindSafe` is not satisfied
+    //~^ ERROR the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a
+    //~| ERROR the type `std::cell::UnsafeCell<usize>` may contain interior mutability and a
 }
index 177a43e2a7f71650a74955496b37f75cfc1b508f..956eca432c5f06f1602ca0e1a86723c62cce462c 100644 (file)
@@ -17,6 +17,6 @@ fn assert<T: UnwindSafe + ?Sized>() {}
 
 fn main() {
     assert::<&RefCell<i32>>();
-    //~^ ERROR `std::cell::UnsafeCell<i32>: std::panic::RefUnwindSafe` is not satisfied
-    //~^^ ERROR `std::cell::UnsafeCell<usize>: std::panic::RefUnwindSafe` is not satisfied
+    //~^ ERROR the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a
+    //~| ERROR the type `std::cell::UnsafeCell<usize>` may contain interior mutability and a
 }
index f03e1d545a8083786f324118f27ebc25eb9f9a94..d0ca1db52120480d29447df6491d6f3190516b26 100644 (file)
@@ -17,6 +17,6 @@ fn assert<T: UnwindSafe + ?Sized>() {}
 
 fn main() {
     assert::<*mut RefCell<i32>>();
-    //~^ ERROR `std::cell::UnsafeCell<i32>: std::panic::RefUnwindSafe` is not satisfied
-    //~^^ ERROR `std::cell::UnsafeCell<usize>: std::panic::RefUnwindSafe` is not satisfied
+    //~^ ERROR the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a
+    //~| ERROR the type `std::cell::UnsafeCell<usize>` may contain interior mutability and a
 }
index ece8fa7dc47bb12da8a4ffdbdad81c48a9a513e7..0ebf3d3fed7b5dcfb97c3764e3319c68148b15d1 100644 (file)
@@ -16,5 +16,6 @@
 fn assert<T: UnwindSafe + ?Sized>() {}
 
 fn main() {
-    assert::<&mut i32>(); //~ ERROR: UnwindSafe` is not satisfied
+    assert::<&mut i32>();
+    //~^ ERROR the type `&mut i32` may not be safely transferred across an unwind boundary
 }
index 58794e3b35d531c897a3eee98be7e5ca5e33961b..ed26204bbe10920d39a5896ae8c9d0e9a949ed03 100644 (file)
@@ -22,5 +22,5 @@ pub fn main() {
     // Unsized type.
     let arr: &[_] = &[1, 2, 3];
     let range = *arr..;
-    //~^ ERROR `[{integer}]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
index 32f9b83b6e2c77f556439d8e5cbf4851f1ecca11..78d3702b449caa7613cb167d13d30c4005a2f825 100644 (file)
 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
 struct AllTheRanges {
     a: Range<usize>,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
     b: RangeTo<usize>,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
     c: RangeFrom<usize>,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
     d: RangeFull,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
     e: RangeInclusive<usize>,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
     f: RangeToInclusive<usize>,
-    //~^ ERROR PartialOrd
-    //~^^ ERROR Ord
+    //~^ ERROR can't compare
+    //~| ERROR Ord
 }
 
 fn main() {}
index 2b2c23a3ce4e92c88fee61c0c242775e1a65cc7d..b5f1ffb977ed630e85a2bebd1c8c09a67a7fb943 100644 (file)
@@ -10,5 +10,5 @@
 
 pub fn main() {
     let s: &str = "hello";
-    let c: u8 = s[4]; //~ ERROR `str: std::ops::Index<{integer}>` is not satisfied
+    let c: u8 = s[4]; //~ ERROR the type `str` cannot be indexed by `{integer}`
 }
index 219fcdfd7026531d935abbe1354da050de769ef0..cc5fd7e3f24d82fd64dcd99b7ec1a35810b90463 100644 (file)
@@ -12,10 +12,10 @@ fn bot<T>() -> T { loop {} }
 
 fn mutate(s: &mut str) {
     s[1..2] = bot();
-    //~^ ERROR `str: std::marker::Sized` is not satisfied
-    //~| ERROR `str: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
+    //~| ERROR the size for value values of type
     s[1usize] = bot();
-    //~^ ERROR `str: std::ops::IndexMut<usize>` is not satisfied
+    //~^ ERROR the type `str` cannot be mutably indexed by `usize`
 }
 
 pub fn main() {}
index c857790e342d0270921b9028c0b0329c2a5b22ae..b8557cb79e38743d5008faa28819f2cc39ac122c 100644 (file)
@@ -56,6 +56,6 @@ fn foo<'z>() where &'z (): Sized {
     //[normal]~| found type `fn() {foo::<'static>}`
 
     <str as Foo<u8>>::bar;
-    //[verbose]~^ ERROR `str: std::marker::Sized` is not satisfied
-    //[normal]~^^ ERROR `str: std::marker::Sized` is not satisfied
+    //[verbose]~^ ERROR the size for value values of type
+    //[normal]~^^ ERROR the size for value values of type
 }
index 983c66ec1c40fba449e4ba1490512cd00521d9b3..89fddf1f65f0240ea7f391358ea8d43ffc98d866 100644 (file)
@@ -15,7 +15,7 @@ fn dummy(&self) { }
 // This should emit the less confusing error, not the more confusing one.
 
 fn foo(_x: Foo + Send) {
-    //~^ ERROR the trait bound `Foo + std::marker::Send + 'static: std::marker::Sized` is not
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index 8014f92e1734438b5765e21caaaeb77f01395927..a272686c535738ab38071e163c12b2c14cc47d73 100644 (file)
@@ -31,8 +31,8 @@ fn dummy() {
     impl !Send for TestType {}
 
     Outer(TestType);
-    //~^ ERROR `dummy::TestType: std::marker::Send` is not satisfied
-    //~| ERROR `dummy::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `dummy::TestType` cannot be sent between threads safely
+    //~| ERROR `dummy::TestType` cannot be sent between threads safely
 }
 
 fn dummy1b() {
@@ -40,7 +40,7 @@ fn dummy1b() {
     impl !Send for TestType {}
 
     is_send(TestType);
-    //~^ ERROR `dummy1b::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `dummy1b::TestType` cannot be sent between threads safely
 }
 
 fn dummy1c() {
@@ -48,7 +48,7 @@ fn dummy1c() {
     impl !Send for TestType {}
 
     is_send((8, TestType));
-    //~^ ERROR `dummy1c::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `dummy1c::TestType` cannot be sent between threads safely
 }
 
 fn dummy2() {
@@ -56,7 +56,7 @@ fn dummy2() {
     impl !Send for TestType {}
 
     is_send(Box::new(TestType));
-    //~^ ERROR `dummy2::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `dummy2::TestType` cannot be sent between threads safely
 }
 
 fn dummy3() {
@@ -64,7 +64,7 @@ fn dummy3() {
     impl !Send for TestType {}
 
     is_send(Box::new(Outer2(TestType)));
-    //~^ ERROR `dummy3::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `dummy3::TestType` cannot be sent between threads safely
 }
 
 fn main() {
@@ -74,5 +74,5 @@ impl !Send for TestType {}
     // This will complain about a missing Send impl because `Sync` is implement *just*
     // for T that are `Send`. Look at #20366 and #19950
     is_sync(Outer2(TestType));
-    //~^ ERROR `main::TestType: std::marker::Send` is not satisfied
+    //~^ ERROR `main::TestType` cannot be sent between threads safely
 }
index 853718f1e77d08ddcc68ca765eaa4173550cc76e..65438e5df8e08e73a2256c0f961038b76ff19227 100644 (file)
@@ -27,5 +27,5 @@ fn is_send<T: Send>() {}
 fn main() {
     is_send::<MySendable>();
     is_send::<MyNotSendable>();
-    //~^ ERROR `MyNotSendable: std::marker::Send` is not satisfied
+    //~^ ERROR `MyNotSendable` cannot be sent between threads safely
 }
index 0dbd61413e053d9ebd23976eddff7f2665c55857..f20719ec7fab7193a0699445284a9366132b3a39 100644 (file)
@@ -23,6 +23,6 @@ fn main() {
     call(|| {
         counter += 1;
         //[ast]~^ ERROR cannot assign to data in a captured outer variable in an `Fn` closure
-        //[mir]~^^ ERROR cannot assign to immutable item `counter`
+        //[mir]~^^ ERROR cannot assign to `counter`
     });
 }
index a238eaf052508460677a4c59f893754a2abf70f3..a9a2a3c4c92a11064698d939d08873d183f41f8b 100644 (file)
 #![feature(untagged_unions)]
 
 union U {
-    a: str, //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+    a: str,
+    //~^ ERROR the size for value values of type
+
     b: u8,
 }
 
 union W {
     a: u8,
-    b: str, //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+    b: str,
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {}
index 3dcc7d248d72db316eb7848174d9f19ae48c38de..736794ac5384e0c768404c791b9ce6b2dcfaf34c 100644 (file)
@@ -9,5 +9,6 @@
 // except according to those terms.
 
 fn bar<T: Sized>() { }
-fn foo<T: ?Sized>() { bar::<T>() } //~ ERROR `T: std::marker::Sized` is not satisfied
+fn foo<T: ?Sized>() { bar::<T>() }
+//~^ ERROR the size for value values of type
 fn main() { }
index 5d791215f36c60108c3819e98d69d498b252a7b5..f9702e29f1dc36ea44cc03fda326ca6859c58523 100644 (file)
@@ -15,7 +15,7 @@ fn not_sized<T: ?Sized>() { }
 enum Foo<U> { FooSome(U), FooNone }
 fn foo1<T>() { not_sized::<Foo<T>>() } // Hunky dory.
 fn foo2<T: ?Sized>() { not_sized::<Foo<T>>() }
-//~^ ERROR `T: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 //
 // Not OK: `T` is not sized.
 
index 4d0774f2ce44157743fbdc6135a37874b7808eb7..03d3d98b59f012d62b54c16c73817128db8da673 100644 (file)
@@ -14,7 +14,8 @@
 
 struct S5<Y>(Y);
 
-impl<X: ?Sized> S5<X> { //~ ERROR E0277
+impl<X: ?Sized> S5<X> {
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index bbefb2fcecd80f7ba78fcd03abedf8d7fa702e7e..8cb1f760664de469aec6c0572f6ab7086c1d619e 100644 (file)
@@ -15,14 +15,14 @@ fn not_sized<T: ?Sized>() { }
 struct Foo<T> { data: T }
 fn foo1<T>() { not_sized::<Foo<T>>() } // Hunky dory.
 fn foo2<T: ?Sized>() { not_sized::<Foo<T>>() }
-//~^ ERROR `T: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 //
 // Not OK: `T` is not sized.
 
 struct Bar<T: ?Sized> { data: T }
 fn bar1<T: ?Sized>() { not_sized::<Bar<T>>() }
 fn bar2<T: ?Sized>() { is_sized::<Bar<T>>() }
-//~^ ERROR `T: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 //
 // Not OK: `Bar<T>` is not sized, but it should be.
 
index c919bdf924f6566bb8b707451d7b860e3e397e31..b3610a4c9b9b64b8f0ddd5921e3e181fa9649ec7 100644 (file)
@@ -17,7 +17,8 @@ trait T3<Z: ?Sized> {
 
 struct S5<Y>(Y);
 
-impl<X: ?Sized> T3<X> for S5<X> { //~ ERROR E0277
+impl<X: ?Sized> T3<X> for S5<X> {
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index ad5e4c2daef9ea010cc8eb8f086f7a2721195e53..50a058a4338d8d56f9813d32dbedddce449a2cb9 100644 (file)
@@ -16,7 +16,7 @@ trait T2<Z> {
 }
 struct S4<Y: ?Sized>(Box<Y>);
 impl<X: ?Sized> T2<X> for S4<X> {
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index e96e0ea3aec3623ec0d57b2a3e4aae3927c2adaf..945f20b28779ed9963fd552ca7c47a28683f830f 100644 (file)
@@ -15,7 +15,7 @@
 // Unbounded.
 fn f1<X: ?Sized>(x: &X) {
     f2::<X>(x);
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 fn f2<X>(x: &X) {
 }
@@ -26,7 +26,7 @@ fn foo(&self) { }
 }
 fn f3<X: ?Sized + T>(x: &X) {
     f4::<X>(x);
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 fn f4<X: T>(x: &X) {
 }
@@ -41,20 +41,20 @@ struct S<X: ?Sized> {
 
 fn f8<X: ?Sized>(x1: &S<X>, x2: &S<X>) {
     f5(x1);
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
     f6(x2); // ok
 }
 
 // Test some tuples.
 fn f9<X: ?Sized>(x1: Box<S<X>>) {
     f5(&(*x1, 34));
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn f10<X: ?Sized>(x1: Box<S<X>>) {
     f5(&(32, *x1));
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
-    //~| ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
+    //~| ERROR the size for value values of type
 }
 
 pub fn main() {
index 3e6c9cc4061e1cb8ff7a02bf94e5048404f4d410..e04aa3599e9b5805e47af228ffcdf65d3287d1c5 100644 (file)
 // Test `?Sized` types not allowed in fields (except the last one).
 
 struct S1<X: ?Sized> {
-    f1: X, //~ ERROR `X: std::marker::Sized` is not satisfied
+    f1: X,
+    //~^ ERROR the size for value values of type
     f2: isize,
 }
 struct S2<X: ?Sized> {
     f: isize,
-    g: X, //~ ERROR `X: std::marker::Sized` is not satisfied
+    g: X,
+    //~^ ERROR the size for value values of type
     h: isize,
 }
 struct S3 {
-    f: str, //~ ERROR `str: std::marker::Sized` is not satisfied
+    f: str,
+    //~^ ERROR the size for value values of type
     g: [usize]
 }
 struct S4 {
-    f: [u8], //~ ERROR `[u8]: std::marker::Sized` is not satisfied
+    f: [u8],
+    //~^ ERROR the size for value values of type
     g: usize
 }
 enum E<X: ?Sized> {
-    V1(X, isize), //~ERROR `X: std::marker::Sized` is not satisfied
+    V1(X, isize),
+    //~^ ERROR the size for value values of type
 }
 enum F<X: ?Sized> {
-    V2{f1: X, f: isize}, //~ERROR `X: std::marker::Sized` is not satisfied
+    V2{f1: X, f: isize},
+    //~^ ERROR the size for value values of type
 }
 
 pub fn main() {
index dec8699f46e3b3542b67f6f22377d0292b08f691..8ac9fe4c58787b1a54cd78cb0bd4acafd4dbf2e7 100644 (file)
@@ -14,28 +14,41 @@ trait T {}
 
 fn f1<W: ?Sized, X: ?Sized, Y: ?Sized, Z: ?Sized>(x: &X) {
     let _: W; // <-- this is OK, no bindings created, no initializer.
-    let _: (isize, (X, isize)); //~ERROR `X: std::marker::Sized` is not satisfie
-    let y: Y; //~ERROR `Y: std::marker::Sized` is not satisfied
-    let y: (isize, (Z, usize)); //~ERROR `Z: std::marker::Sized` is not satisfied
+    let _: (isize, (X, isize));
+    //~^ ERROR the size for value values of type
+    let y: Y;
+    //~^ ERROR the size for value values of type
+    let y: (isize, (Z, usize));
+    //~^ ERROR the size for value values of type
 }
 fn f2<X: ?Sized, Y: ?Sized>(x: &X) {
-    let y: X; //~ERROR `X: std::marker::Sized` is not satisfied
-    let y: (isize, (Y, isize)); //~ERROR `Y: std::marker::Sized` is not satisfied
+    let y: X;
+    //~^ ERROR the size for value values of type
+    let y: (isize, (Y, isize));
+    //~^ ERROR the size for value values of type
 }
 
 fn f3<X: ?Sized>(x1: Box<X>, x2: Box<X>, x3: Box<X>) {
-    let y: X = *x1; //~ERROR `X: std::marker::Sized` is not satisfied
-    let y = *x2; //~ERROR `X: std::marker::Sized` is not satisfied
-    let (y, z) = (*x3, 4); //~ERROR `X: std::marker::Sized` is not satisfied
+    let y: X = *x1;
+    //~^ ERROR the size for value values of type
+    let y = *x2;
+    //~^ ERROR the size for value values of type
+    let (y, z) = (*x3, 4);
+    //~^ ERROR the size for value values of type
 }
 fn f4<X: ?Sized + T>(x1: Box<X>, x2: Box<X>, x3: Box<X>) {
-    let y: X = *x1;         //~ERROR `X: std::marker::Sized` is not satisfied
-    let y = *x2;            //~ERROR `X: std::marker::Sized` is not satisfied
-    let (y, z) = (*x3, 4); //~ERROR `X: std::marker::Sized` is not satisfied
+    let y: X = *x1;
+    //~^ ERROR the size for value values of type
+    let y = *x2;
+    //~^ ERROR the size for value values of type
+    let (y, z) = (*x3, 4);
+    //~^ ERROR the size for value values of type
 }
 
-fn g1<X: ?Sized>(x: X) {} //~ERROR `X: std::marker::Sized` is not satisfied
-fn g2<X: ?Sized + T>(x: X) {} //~ERROR `X: std::marker::Sized` is not satisfied
+fn g1<X: ?Sized>(x: X) {}
+//~^ ERROR the size for value values of type
+fn g2<X: ?Sized + T>(x: X) {}
+//~^ ERROR the size for value values of type
 
 pub fn main() {
 }
index 25868c594feb675326960008eff1724b43b84763..44d7df35680ce3bee8d5a6c7ea416d38514ce537 100644 (file)
@@ -20,7 +20,7 @@ trait T1<Z: T> {
 
 struct S3<Y: ?Sized>(Box<Y>);
 impl<X: ?Sized + T> T1<X> for S3<X> {
-    //~^ ERROR `X: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() { }
index f1fdbfc702ddf6dfcb40f4c642dd579488472ba5..f15b013c07ba497a02278a7fa3c1d55788841732 100644 (file)
 
 #![feature(allocator_api, nonnull)]
 
-use std::alloc::{Alloc, Global, Layout, oom};
+use std::alloc::{Alloc, Global, Layout, handle_alloc_error};
 
 fn main() {
     unsafe {
-        let ptr = Global.alloc_one::<i32>().unwrap_or_else(|_| oom(Layout::new::<i32>()));
+        let ptr = Global.alloc_one::<i32>().unwrap_or_else(|_| {
+            handle_alloc_error(Layout::new::<i32>())
+        });
         *ptr.as_ptr() = 4;
         assert_eq!(*ptr.as_ptr(), 4);
         Global.dealloc_one(ptr);
index 2dc4d775a9c45f17777f7cd00108af398068703f..4df46c0e2e1e7377cc514d93e22a8c11f5f14996 100644 (file)
@@ -32,8 +32,8 @@ pub fn noop_fold_impl_item() -> SmallVector<ImplItem> {
 struct S05_PolyTraitRef(S06_TraitRef);
 struct S06_TraitRef(S07_Path);
 struct S07_Path(Vec<S08_PathSegment>);
-struct S08_PathSegment(S09_PathParameters);
-struct S09_PathParameters(P<S10_ParenthesizedParameterData>);
+struct S08_PathSegment(S09_GenericArgs);
+struct S09_GenericArgs(P<S10_ParenthesizedParameterData>);
 struct S10_ParenthesizedParameterData(Option<P<S11_Ty>>);
 struct S11_Ty(P<S12_Expr>);
 struct S12_Expr(P<S13_Block>);
index 7152e721eac9e63642ef45ffae13e4571b79506f..3b4b458bb0477508081a4d36cb0f1e157812ef81 100644 (file)
@@ -15,7 +15,7 @@
 
 #![feature(heap_api, allocator_api)]
 
-use std::alloc::{Global, Alloc, Layout, oom};
+use std::alloc::{Global, Alloc, Layout, handle_alloc_error};
 use std::ptr::{self, NonNull};
 
 fn main() {
@@ -50,7 +50,7 @@ unsafe fn allocate(layout: Layout) -> *mut u8 {
             println!("allocate({:?})", layout);
         }
 
-        let ret = Global.alloc(layout).unwrap_or_else(|_| oom(layout));
+        let ret = Global.alloc(layout).unwrap_or_else(|_| handle_alloc_error(layout));
 
         if PRINT {
             println!("allocate({:?}) = {:?}", layout, ret);
@@ -73,7 +73,9 @@ unsafe fn reallocate(ptr: *mut u8, old: Layout, new: Layout) -> *mut u8 {
         }
 
         let ret = Global.realloc(NonNull::new_unchecked(ptr), old, new.size())
-            .unwrap_or_else(|_| oom(Layout::from_size_align_unchecked(new.size(), old.align())));
+            .unwrap_or_else(|_| handle_alloc_error(
+                Layout::from_size_align_unchecked(new.size(), old.align())
+            ));
 
         if PRINT {
             println!("reallocate({:?}, old={:?}, new={:?}) = {:?}",
index 745a19dec4d785fc11c7839f23b0950d660b289a..b58e837f3bdcf27359f8d21a336b0cde0119cafd 100644 (file)
@@ -12,7 +12,7 @@
 
 #![feature(allocator_api)]
 
-use std::alloc::{Alloc, Global, Layout, oom};
+use std::alloc::{Alloc, Global, Layout, handle_alloc_error};
 use std::ptr::NonNull;
 
 struct arena(());
@@ -33,7 +33,7 @@ struct Ccx {
 fn alloc<'a>(_bcx : &'a arena) -> &'a Bcx<'a> {
     unsafe {
         let layout = Layout::new::<Bcx>();
-        let ptr = Global.alloc(layout).unwrap_or_else(|_| oom(layout));
+        let ptr = Global.alloc(layout).unwrap_or_else(|_| handle_alloc_error(layout));
         &*(ptr.as_ptr() as *const _)
     }
 }
diff --git a/src/test/ui/asm-out-assign-imm.nll.stderr b/src/test/ui/asm-out-assign-imm.nll.stderr
new file mode 100644 (file)
index 0000000..fbd58cd
--- /dev/null
@@ -0,0 +1,14 @@
+error[E0384]: cannot assign twice to immutable variable `x`
+  --> $DIR/asm-out-assign-imm.rs:33:9
+   |
+LL |     let x: isize;
+   |         - consider changing this to `mut x`
+LL |     x = 1;
+   |     ----- first assignment to `x`
+...
+LL |         asm!("mov $1, $0" : "=r"(x) : "r"(5));
+   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0384`.
index deb2e7ed4a33dfaeee88d3d1ed071128ce3fb7cc..592f666eff8f3955b2f8af28f90bac2df13117f4 100644 (file)
@@ -17,6 +17,9 @@ LL | |     x;  //~ value moved here
 error[E0596]: cannot borrow immutable item `y` as mutable
   --> $DIR/augmented-assignments.rs:30:5
    |
+LL |     let y = Int(2);
+   |         - help: consider changing this to be mutable: `mut y`
+LL |     //~^ consider changing this to `mut y`
 LL |     y   //~ error: cannot borrow immutable local variable `y` as mutable
    |     ^ cannot borrow as mutable
 
index b7506849b817d52dead7277f0e3be46211118ac4..1cf68795bf07f5e3dc4101d9162eebdb259068ed 100644 (file)
@@ -10,7 +10,7 @@ error[E0384]: cannot assign to immutable argument `_x` (Mir)
   --> $DIR/immutable-arg.rs:14:5
    |
 LL | fn foo(_x: u32) {
-   |        -- argument not declared as `mut`
+   |        -- consider changing this to `mut _x`
 LL |     _x = 4;
    |     ^^^^^^ cannot assign to immutable argument
 
index 1aec71fee347b397665b502ffb44f1d9d6238eb6..a008a408d97112116774c66e4b3234f24c7896d1 100644 (file)
@@ -14,13 +14,13 @@ error[E0594]: cannot assign to immutable item `x`
   --> $DIR/issue-45983.rs:17:18
    |
 LL |     give_any(|y| x = Some(y));
-   |                  ^^^^^^^^^^^ cannot mutate
-   |
-   = note: the value which is causing this path not to be mutable is...: `x`
+   |                  ^^^^^^^^^^^ cannot assign
 
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/issue-45983.rs:17:14
    |
+LL |     let x = None;
+   |         - help: consider changing this to be mutable: `mut x`
 LL |     give_any(|y| x = Some(y));
    |              ^^^^^^^^^^^^^^^ cannot borrow as mutable
 
diff --git a/src/test/ui/borrowck/issue-51415.nll.stderr b/src/test/ui/borrowck/issue-51415.nll.stderr
new file mode 100644 (file)
index 0000000..79454b6
--- /dev/null
@@ -0,0 +1,9 @@
+error[E0507]: cannot move out of borrowed content
+  --> $DIR/issue-51415.rs:16:47
+   |
+LL |     let opt = a.iter().enumerate().find(|(_, &s)| {
+   |                                               ^ cannot move out of borrowed content
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0507`.
diff --git a/src/test/ui/borrowck/issue-51415.rs b/src/test/ui/borrowck/issue-51415.rs
new file mode 100644 (file)
index 0000000..9067a50
--- /dev/null
@@ -0,0 +1,21 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Regression test for #51415: match default bindings were failing to
+// see the "move out" implied by `&s` below.
+
+fn main() {
+    let a = vec![String::from("a")];
+    let opt = a.iter().enumerate().find(|(_, &s)| {
+        //~^ ERROR cannot move out
+        *s == String::from("d")
+    }).map(|(i, _)| i);
+    println!("{:?}", opt);
+}
diff --git a/src/test/ui/borrowck/issue-51415.stderr b/src/test/ui/borrowck/issue-51415.stderr
new file mode 100644 (file)
index 0000000..b4b0bc7
--- /dev/null
@@ -0,0 +1,12 @@
+error[E0507]: cannot move out of borrowed content
+  --> $DIR/issue-51415.rs:16:46
+   |
+LL |     let opt = a.iter().enumerate().find(|(_, &s)| {
+   |                                              ^-
+   |                                              ||
+   |                                              |hint: to prevent move, use `ref s` or `ref mut s`
+   |                                              cannot move out of borrowed content
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0507`.
index f8b84bce04ecfdb11df2fc069aa0cef7b0f195af..0674c8230165aa20713708cf551c43ebb2d5068f 100644 (file)
@@ -1,6 +1,8 @@
 error[E0596]: cannot borrow immutable item `b` as mutable
   --> $DIR/mut-borrow-of-mut-ref.rs:18:7
    |
+LL | fn f(b: &mut i32) {
+   |      - help: consider changing this to be mutable: `mut b`
 LL |     g(&mut b) //~ ERROR cannot borrow
    |       ^^^^^^ cannot borrow as mutable
 
diff --git a/src/test/ui/chalkify/lower_struct.rs b/src/test/ui/chalkify/lower_struct.rs
new file mode 100644 (file)
index 0000000..9287555
--- /dev/null
@@ -0,0 +1,18 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(rustc_attrs)]
+
+#[rustc_dump_program_clauses] //~ ERROR program clause dump
+struct Foo<T> where Box<T>: Clone {
+    _x: std::marker::PhantomData<T>,
+}
+
+fn main() { }
diff --git a/src/test/ui/chalkify/lower_struct.stderr b/src/test/ui/chalkify/lower_struct.stderr
new file mode 100644 (file)
index 0000000..d6cc9c8
--- /dev/null
@@ -0,0 +1,12 @@
+error: program clause dump
+  --> $DIR/lower_struct.rs:13:1
+   |
+LL | #[rustc_dump_program_clauses] //~ ERROR program clause dump
+   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+   = note: FromEnv(T: std::marker::Sized) :- FromEnv(Foo<T>).
+   = note: FromEnv(std::boxed::Box<T>: std::clone::Clone) :- FromEnv(Foo<T>).
+   = note: WellFormed(Foo<T>) :- Implemented(T: std::marker::Sized), Implemented(std::boxed::Box<T>: std::clone::Clone).
+
+error: aborting due to previous error
+
index 7f6f503c6ff7235fbae3a441abbae71d45f8c6fb..ea275d647fa7c143fb66a355d8853c1355906656 100644 (file)
@@ -4,10 +4,10 @@ error: program clause dump
 LL | #[rustc_dump_program_clauses] //~ ERROR program clause dump
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
-   = note: FromEnv(<F as std::ops::FnOnce<(&'a (u8, u16),)>>::Output == &'a u8) :- FromEnv(Self: Foo<F>).
    = note: FromEnv(F: std::marker::Sized) :- FromEnv(Self: Foo<F>).
    = note: FromEnv(F: std::ops::Fn<(&'a (u8, u16),)>) :- FromEnv(Self: Foo<F>).
    = note: Implemented(Self: Foo<F>) :- FromEnv(Self: Foo<F>).
+   = note: ProjectionEq(<F as std::ops::FnOnce<(&'a (u8, u16),)>>::Output == &'a u8) :- FromEnv(Self: Foo<F>).
 
 error: aborting due to previous error
 
index 4526616e48899dce909577308d39b7bcc4edd443..da0b201f5d4e160b6b6d191a8c0dce5adc6ab7d2 100644 (file)
@@ -1,6 +1,9 @@
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/huge_multispan_highlight.rs:100:13
    |
+LL |     let x = "foo";
+   |         - help: consider changing this to be mutable: `mut x`
+...
 LL |     let y = &mut x; //~ ERROR cannot borrow
    |             ^^^^^^ cannot borrow as mutable
 
index b9b03c9b9ec6224219220fbbfeab29cab562bf68..4271382ed5b22e06e40ee85af03714854b148513 100644 (file)
@@ -1,8 +1,11 @@
-error: invalid ABI: expected one of [cdecl, stdcall, fastcall, vectorcall, thiscall, aapcs, win64, sysv64, ptx-kernel, msp430-interrupt, x86-interrupt, Rust, C, system, rust-intrinsic, rust-call, platform-intrinsic, unadjusted], found `路濫狼á́́`
+error[E0703]: invalid ABI: found `路濫狼á́́`
   --> $DIR/unicode.rs:11:8
    |
 LL | extern "路濫狼á́́" fn foo() {} //~ ERROR invalid ABI
-   |        ^^^^^^^^^
+   |        ^^^^^^^^^ invalid ABI
+   |
+   = help: valid ABIs: cdecl, stdcall, fastcall, vectorcall, thiscall, aapcs, win64, sysv64, ptx-kernel, msp430-interrupt, x86-interrupt, Rust, C, system, rust-intrinsic, rust-call, platform-intrinsic, unadjusted
 
 error: aborting due to previous error
 
+For more information about this error, try `rustc --explain E0703`.
index 2d5a31f0586b192e65ab99ab2a4fdd4766279f42..10dcf7d0e657a38d177b763486190b1d1da6f925 100644 (file)
@@ -2,7 +2,9 @@ error[E0384]: cannot assign twice to immutable variable `x`
   --> $DIR/command-line-diagnostics.rs:16:5
    |
 LL |     let x = 42;
-   |             -- first assignment to `x`
+   |         -   -- first assignment to `x`
+   |         |
+   |         consider changing this to `mut x`
 LL |     x = 43;
    |     ^^^^^^ cannot assign twice to immutable variable
 
index c6ce34b60ca770d11733b2fd88914429ab352b87..c0a367604c374be88f353433d4c2b54b5b47420d 100644 (file)
 use std::fmt::Debug;
 
 const CONST_0: Debug+Sync = *(&0 as &(Debug+Sync));
-//~^ ERROR `std::fmt::Debug + std::marker::Sync + 'static: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 const CONST_FOO: str = *"foo";
-//~^ ERROR `str: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 static STATIC_1: Debug+Sync = *(&1 as &(Debug+Sync));
-//~^ ERROR `std::fmt::Debug + std::marker::Sync + 'static: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 static STATIC_BAR: str = *"bar";
-//~^ ERROR `str: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
 
 fn main() {
     println!("{:?} {:?} {:?} {:?}", &CONST_0, &CONST_FOO, &STATIC_1, &STATIC_BAR);
index 0bbb5debbba69c02be8cf109c2e2c26242e4d3f0..2cde4aec2b5d47b84e1fb8cc67a1264fbe88394f 100644 (file)
@@ -1,37 +1,41 @@
-error[E0277]: the trait bound `std::fmt::Debug + std::marker::Sync + 'static: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `std::fmt::Debug + std::marker::Sync + 'static` cannot be known at compilation time
   --> $DIR/const-unsized.rs:13:29
    |
 LL | const CONST_0: Debug+Sync = *(&0 as &(Debug+Sync));
-   |                             ^^^^^^^^^^^^^^^^^^^^^^ `std::fmt::Debug + std::marker::Sync + 'static` does not have a constant size known at compile-time
+   |                             ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `std::fmt::Debug + std::marker::Sync + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: constant expressions must have a statically known size
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/const-unsized.rs:16:24
    |
 LL | const CONST_FOO: str = *"foo";
-   |                        ^^^^^^ `str` does not have a constant size known at compile-time
+   |                        ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: constant expressions must have a statically known size
 
-error[E0277]: the trait bound `std::fmt::Debug + std::marker::Sync + 'static: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `std::fmt::Debug + std::marker::Sync + 'static` cannot be known at compilation time
   --> $DIR/const-unsized.rs:19:31
    |
 LL | static STATIC_1: Debug+Sync = *(&1 as &(Debug+Sync));
-   |                               ^^^^^^^^^^^^^^^^^^^^^^ `std::fmt::Debug + std::marker::Sync + 'static` does not have a constant size known at compile-time
+   |                               ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `std::fmt::Debug + std::marker::Sync + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: constant expressions must have a statically known size
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/const-unsized.rs:22:26
    |
 LL | static STATIC_BAR: str = *"bar";
-   |                          ^^^^^^ `str` does not have a constant size known at compile-time
+   |                          ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: constant expressions must have a statically known size
 
 error: aborting due to 4 previous errors
index 6b63f64c699e283905e10dece0fe3f6a5fdb309e..21c5e3608c00b5dd73fbffac57fa5f504731c930 100644 (file)
@@ -7,6 +7,8 @@ LL |         (&mut self).bar(); //~ ERROR cannot borrow
 error[E0596]: cannot borrow immutable item `self` as mutable
   --> $DIR/issue-31424.rs:23:9
    |
+LL |     fn bar(self: &mut Self) {
+   |            ---- help: consider changing this to be mutable: `mut self`
 LL |         (&mut self).bar(); //~ ERROR cannot borrow
    |         ^^^^^^^^^^^ cannot borrow as mutable
 
index 81f858f6bfcb007096c57418768bc0445c02971f..8dedb6ec4db80a1eed930a3e5168805c7546cef8 100644 (file)
@@ -2,7 +2,10 @@ error[E0596]: cannot borrow immutable item `self` as mutable
   --> $DIR/issue-34126.rs:16:18
    |
 LL |         self.run(&mut self); //~ ERROR cannot borrow
-   |                  ^^^^^^^^^ cannot borrow as mutable
+   |                  ^^^^^^^^^
+   |                  |
+   |                  cannot borrow as mutable
+   |                  try removing `&mut` here
 
 error[E0502]: cannot borrow `self` as mutable because it is also borrowed as immutable
   --> $DIR/issue-34126.rs:16:18
index 258e1bb1ad7da4dd18e44d06b5dcbb993f86e885..d2271e8e7de76b5ee9cf526f745edb54d1e56aeb 100644 (file)
@@ -2,7 +2,10 @@ error[E0596]: cannot borrow immutable item `key` as mutable
   --> $DIR/issue-34337.rs:16:9
    |
 LL |     get(&mut key); //~ ERROR cannot borrow
-   |         ^^^^^^^^ cannot borrow as mutable
+   |         ^^^^^^^^
+   |         |
+   |         cannot borrow as mutable
+   |         try removing `&mut` here
 
 error: aborting due to previous error
 
index 40b640b63cf32deee09ec1d4e3e8ac8b6f899fd9..0c1dcb29d4d2c2067f795325946bc69e76d45ed7 100644 (file)
@@ -1,16 +1,18 @@
 error[E0596]: cannot borrow immutable item `f.v` as mutable
   --> $DIR/issue-35937.rs:17:5
    |
+LL |     let f = Foo { v: Vec::new() };
+   |         - help: consider changing this to be mutable: `mut f`
 LL |     f.v.push("cat".to_string()); //~ ERROR cannot borrow
    |     ^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `f`
 
 error[E0384]: cannot assign twice to immutable variable `s.x`
   --> $DIR/issue-35937.rs:26:5
    |
 LL |     let s = S { x: 42 };
-   |             ----------- first assignment to `s.x`
+   |         -   ----------- first assignment to `s.x`
+   |         |
+   |         consider changing this to `mut s`
 LL |     s.x += 1; //~ ERROR cannot assign
    |     ^^^^^^^^ cannot assign twice to immutable variable
 
@@ -18,7 +20,10 @@ error[E0384]: cannot assign twice to immutable variable `s.x`
   --> $DIR/issue-35937.rs:30:5
    |
 LL | fn bar(s: S) {
-   |        - first assignment to `s.x`
+   |        -
+   |        |
+   |        first assignment to `s.x`
+   |        consider changing this to `mut s`
 LL |     s.x += 1; //~ ERROR cannot assign
    |     ^^^^^^^^ cannot assign twice to immutable variable
 
index 29c7192a98bc6513915628179e5aa106e5ccb34b..e51a1baad25f26685fdfc7a43477e936986a67de 100644 (file)
@@ -2,7 +2,10 @@ error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/issue-37139.rs:22:18
    |
 LL |             test(&mut x); //~ ERROR cannot borrow immutable
-   |                  ^^^^^^ cannot borrow as mutable
+   |                  ^^^^^^
+   |                  |
+   |                  cannot borrow as mutable
+   |                  try removing `&mut` here
 
 error: aborting due to previous error
 
index 8e4426779517c74782bc6e05eb38901e3138f18b..76b8c8ebf602940058e6828efbb1b1a2836de961 100644 (file)
@@ -1,10 +1,10 @@
 error[E0596]: cannot borrow immutable item `*self.s` as mutable
   --> $DIR/issue-38147-1.rs:27:9
    |
+LL |     fn f(&self) {
+   |          ----- help: consider changing this to be a mutable reference: `&mut Foo<'_>`
 LL |         self.s.push('x'); //~ ERROR cannot borrow data mutably
-   |         ^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*self`
+   |         ^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to previous error
 
index 6808222cc3241356a46583ebf4b159b772cd84d7..c875957623b62841a675fbd11ce9e9340380c49f 100644 (file)
@@ -1,10 +1,10 @@
 error[E0596]: cannot borrow immutable item `*f.s` as mutable
   --> $DIR/issue-38147-4.rs:16:5
    |
+LL | fn f(x: usize, f: &Foo) {
+   |                   ---- help: consider changing this to be a mutable reference: `&mut Foo<'_>`
 LL |     f.s.push('x'); //~ ERROR cannot borrow data mutably
-   |     ^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*f`
+   |     ^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to previous error
 
index f5f5b675e7727b53d90096a75084975ed066da0b..02c1debca69b24fa515978b7e4c757612eba2fc1 100644 (file)
 error[E0596]: cannot borrow immutable item `z.x` as mutable
   --> $DIR/issue-39544.rs:21:13
    |
+LL |     let z = Z { x: X::Y };
+   |         - help: consider changing this to be mutable: `mut z`
 LL |     let _ = &mut z.x; //~ ERROR cannot borrow
    |             ^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `z`
 
 error[E0596]: cannot borrow immutable item `self.x` as mutable
   --> $DIR/issue-39544.rs:26:17
    |
+LL |     fn foo<'z>(&'z self) {
+   |                -------- help: consider changing this to be a mutable reference: `&mut Z`
 LL |         let _ = &mut self.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*self`
+   |                 ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `self.x` as mutable
   --> $DIR/issue-39544.rs:30:17
    |
+LL |     fn foo1(&self, other: &Z) {
+   |             ----- help: consider changing this to be a mutable reference: `&mut Z`
 LL |         let _ = &mut self.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*self`
+   |                 ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `other.x` as mutable
   --> $DIR/issue-39544.rs:31:17
    |
+LL |     fn foo1(&self, other: &Z) {
+   |                           -- help: consider changing this to be a mutable reference: `&mut Z`
+LL |         let _ = &mut self.x; //~ ERROR cannot borrow
 LL |         let _ = &mut other.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*other`
+   |                 ^^^^^^^^^^^^ `other` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `self.x` as mutable
   --> $DIR/issue-39544.rs:35:17
    |
+LL |     fn foo2<'a>(&'a self, other: &Z) {
+   |                 -------- help: consider changing this to be a mutable reference: `&mut Z`
 LL |         let _ = &mut self.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*self`
+   |                 ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `other.x` as mutable
   --> $DIR/issue-39544.rs:36:17
    |
+LL |     fn foo2<'a>(&'a self, other: &Z) {
+   |                                  -- help: consider changing this to be a mutable reference: `&mut Z`
+LL |         let _ = &mut self.x; //~ ERROR cannot borrow
 LL |         let _ = &mut other.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*other`
+   |                 ^^^^^^^^^^^^ `other` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `self.x` as mutable
   --> $DIR/issue-39544.rs:40:17
    |
+LL |     fn foo3<'a>(self: &'a Self, other: &Z) {
+   |                       -------- help: consider changing this to be a mutable reference: `&mut Z`
 LL |         let _ = &mut self.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*self`
+   |                 ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `other.x` as mutable
   --> $DIR/issue-39544.rs:41:17
    |
+LL |     fn foo3<'a>(self: &'a Self, other: &Z) {
+   |                                        -- help: consider changing this to be a mutable reference: `&mut Z`
+LL |         let _ = &mut self.x; //~ ERROR cannot borrow
 LL |         let _ = &mut other.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*other`
+   |                 ^^^^^^^^^^^^ `other` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `other.x` as mutable
   --> $DIR/issue-39544.rs:45:17
    |
+LL |     fn foo4(other: &Z) {
+   |                    -- help: consider changing this to be a mutable reference: `&mut Z`
 LL |         let _ = &mut other.x; //~ ERROR cannot borrow
-   |                 ^^^^^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*other`
+   |                 ^^^^^^^^^^^^ `other` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `z.x` as mutable
   --> $DIR/issue-39544.rs:51:13
    |
+LL | pub fn with_arg(z: Z, w: &Z) {
+   |                 - help: consider changing this to be mutable: `mut z`
 LL |     let _ = &mut z.x; //~ ERROR cannot borrow
    |             ^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `z`
 
 error[E0596]: cannot borrow immutable item `w.x` as mutable
   --> $DIR/issue-39544.rs:52:13
    |
+LL | pub fn with_arg(z: Z, w: &Z) {
+   |                          -- help: consider changing this to be a mutable reference: `&mut Z`
+LL |     let _ = &mut z.x; //~ ERROR cannot borrow
 LL |     let _ = &mut w.x; //~ ERROR cannot borrow
-   |             ^^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*w`
+   |             ^^^^^^^^ `w` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
-error[E0594]: cannot assign to immutable item `*x.0`
+error[E0594]: cannot assign to `*x.0` which is behind a `&` reference
   --> $DIR/issue-39544.rs:58:5
    |
 LL |     *x.0 = 1;
-   |     ^^^^^^^^ cannot mutate
+   |     ^^^^^^^^ cannot assign
 
 error: aborting due to 12 previous errors
 
index 489e1c39c46b9504f9bf00fe4d8a69662af1f81d..1fd75de81284fd363b62fa149f616dd7894aeb96 100644 (file)
@@ -1,8 +1,10 @@
 error[E0596]: cannot borrow immutable item `*buf` as mutable
   --> $DIR/issue-40823.rs:13:5
    |
+LL |     let mut buf = &[1, 2, 3, 4];
+   |                   ------------- help: consider changing this to be a mutable reference: `&mut [1, 2, 3, 4]`
 LL |     buf.iter_mut(); //~ ERROR cannot borrow immutable borrowed content
-   |     ^^^ cannot borrow as mutable
+   |     ^^^ `buf` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to previous error
 
index 008ecfeabcb1461432d84b2e8af4fba7a92fec4f..730ace7858bd19c572b902e4ad4ee259c1de57e7 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `dt` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 233ff198af48bef8926b7880005f8d50f3a1bd8c..f0df7109ba4b6bce70d48a4c5cd1958c6974a371 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `dt` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 7b27ff01f924a3a6f35d5e597da82eb4a2c05f41..2072bc6a756c9f32f0045e5464172fa3e0a5a218 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `dt` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 10e06ee6d025a4f5169d6b3e9b0b5342ba7ed25e..7f5b78684fbc18a9011b7cd6585532a47594279b 100644 (file)
@@ -2,7 +2,7 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/E0110.rs:11:14
    |
 LL | type X = u32<'static>; //~ ERROR E0110
-   |              ^^^^^^^ lifetime parameter not allowed on this type
+   |              ^^^^^^^ lifetime parameter not allowed
 
 error: aborting due to previous error
 
index ba9355763f67aca3816b635992ddfffd4f0309e2..46bc872746cc32492d16ccd787bf2afdd5ae6f91 100644 (file)
@@ -1,8 +1,8 @@
-error[E0131]: `main` function is not allowed to have type parameters
+error[E0131]: `main` function is not allowed to have generic parameters
   --> $DIR/E0131.rs:11:8
    |
 LL | fn main<T>() {
-   |        ^^^ `main` cannot have type parameters
+   |        ^^^ `main` cannot have generic parameters
 
 error: aborting due to previous error
 
index 4d1c50002a39c1f6e6b53dbdcd10d1a03fb00329..313aa1f706e9320b186743ce46dcd6d7d5db648d 100644 (file)
@@ -24,5 +24,5 @@ fn is_send<T: Send>() { }
 
 fn main() {
     is_send::<Foo>();
-    //~^ ERROR the trait bound `*const u8: std::marker::Send` is not satisfied in `Foo`
+    //~^ ERROR `*const u8` cannot be sent between threads safely
 }
index bbe04cfc6e16d9ceb708e684a32915ddd719f400..32776f028b4cec69fc7657c3c899c625b3fbb807 100644 (file)
@@ -1,4 +1,4 @@
-error[E0277]: the trait bound `*const u8: std::marker::Send` is not satisfied in `Foo`
+error[E0277]: `*const u8` cannot be sent between threads safely
   --> $DIR/E0277-2.rs:26:5
    |
 LL |     is_send::<Foo>();
index b29e435701507c931552e16e8145f3094e6bbcc4..95f10e7206f92ec7816fbe2d564f9f4d88bd7333 100644 (file)
@@ -21,7 +21,7 @@ fn some_func<T: Foo>(foo: T) {
 }
 
 fn f(p: Path) { }
-//~^ ERROR the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path`
+//~^ ERROR the size for value values of type
 
 fn main() {
     some_func(5i32);
index 477128d7d9f08c0ef47c864acf86a6a57e47aa7e..ca5b0d2b987d6ac2c06c43c844ba070acd334c71 100644 (file)
@@ -1,10 +1,11 @@
-error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path`
+error[E0277]: the size for value values of type `[u8]` cannot be known at compilation time
   --> $DIR/E0277.rs:23:6
    |
 LL | fn f(p: Path) { }
-   |      ^ `[u8]` does not have a constant size known at compile-time
+   |      ^ doesn't have a size known at compile-time
    |
    = help: within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `std::path::Path`
    = note: all local variables must have a statically known size
 
index 0525e16239d2cb606f8fa29442cb7dc30895bcd1..66e46dfe29d70d7cfc6b2f4dafdca49243e370dd 100644 (file)
@@ -1,4 +1,4 @@
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `fancy_ref.num` which is behind a `&` reference
   --> $DIR/E0389.rs:18:5
    |
 LL |     let fancy_ref = &(&mut fancy);
index 459de1bc00b0f8b5b937bd88e40ac20a2bb52e6a..172db9ced82f9ef706d3d147f374c0574f4f0cf8 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `x` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index c23aa40ee3790d54a055fb2e5177f454bcd5eac6..05a4b8b3544f5dc1932017abf18d767305525af7 100644 (file)
@@ -19,7 +19,7 @@ fn free_fn_capture_hrtb_in_impl_trait()
     -> Box<for<'a> Id<impl Lt<'a>>>
         //~^ ERROR `impl Trait` can only capture lifetimes bound at the fn or impl level [E0657]
 {
-    ()
+    () //~ ERROR mismatched types
 }
 
 struct Foo;
@@ -28,7 +28,7 @@ fn impl_fn_capture_hrtb_in_impl_trait()
         -> Box<for<'a> Id<impl Lt<'a>>>
             //~^ ERROR `impl Trait` can only capture lifetimes bound at the fn or impl level
     {
-        ()
+        () //~ ERROR mismatched types
     }
 }
 
index 737ae3a163ac20c219e2ed3db3929f9a4f184aae..23b9666de3cd9f0ea1e059125172bbb43825d062 100644 (file)
@@ -10,6 +10,25 @@ error[E0657]: `impl Trait` can only capture lifetimes bound at the fn or impl le
 LL |         -> Box<for<'a> Id<impl Lt<'a>>>
    |                                   ^^
 
-error: aborting due to 2 previous errors
+error[E0308]: mismatched types
+  --> $DIR/E0657.rs:22:5
+   |
+LL |     () //~ ERROR mismatched types
+   |     ^^ expected struct `std::boxed::Box`, found ()
+   |
+   = note: expected type `std::boxed::Box<Id<_> + 'static>`
+              found type `()`
+
+error[E0308]: mismatched types
+  --> $DIR/E0657.rs:31:9
+   |
+LL |         () //~ ERROR mismatched types
+   |         ^^ expected struct `std::boxed::Box`, found ()
+   |
+   = note: expected type `std::boxed::Box<Id<_> + 'static>`
+              found type `()`
+
+error: aborting due to 4 previous errors
 
-For more information about this error, try `rustc --explain E0657`.
+Some errors occurred: E0308, E0657.
+For more information about an error, try `rustc --explain E0308`.
index 9c2c80600b8c8f0f80204850a963298e5a62e7fd..db280f2d1f763540068c4d73fd5712b36ba610e8 100644 (file)
@@ -87,38 +87,41 @@ LL | | }
    = help: see issue #48214
    = help: add #![feature(trivial_bounds)] to the crate attributes to enable
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/feature-gate-trivial_bounds.rs:62:1
    |
 LL | struct TwoStrs(str, str) where str: Sized; //~ ERROR
-   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `str` does not have a constant size known at compile-time
+   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: see issue #48214
    = help: add #![feature(trivial_bounds)] to the crate attributes to enable
 
-error[E0277]: the trait bound `A + 'static: std::marker::Sized` is not satisfied in `Dst<A + 'static>`
+error[E0277]: the size for value values of type `A + 'static` cannot be known at compilation time
   --> $DIR/feature-gate-trivial_bounds.rs:65:1
    |
 LL | / fn unsized_local() where Dst<A>: Sized { //~ ERROR
 LL | |     let x: Dst<A> = *(Box::new(Dst { x: 1 }) as Box<Dst<A>>);
 LL | | }
-   | |_^ `A + 'static` does not have a constant size known at compile-time
+   | |_^ doesn't have a size known at compile-time
    |
    = help: within `Dst<A + 'static>`, the trait `std::marker::Sized` is not implemented for `A + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `Dst<A + 'static>`
    = help: see issue #48214
    = help: add #![feature(trivial_bounds)] to the crate attributes to enable
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/feature-gate-trivial_bounds.rs:69:1
    |
 LL | / fn return_str() -> str where str: Sized { //~ ERROR
 LL | |     *"Sized".to_string().into_boxed_str()
 LL | | }
-   | |_^ `str` does not have a constant size known at compile-time
+   | |_^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: see issue #48214
    = help: add #![feature(trivial_bounds)] to the crate attributes to enable
 
index 7b68c167d4acb0cdd2c339da2106e6207747ad26..01a53cdd6dd4a21f9f6c696a38bc27addb0e4adc 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `gen` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `ref_` does not live long enough
   --> $DIR/dropck.rs:22:11
@@ -26,6 +28,8 @@ LL |   }
    |   |
    |   borrowed value only lives until here
    |   borrow later used here, when `gen` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 2 previous errors
 
index a1c8ca77e41e8bf34ff228ae6c5470f98be8167a..efaee4095c1487a925c9437c992776004632c9a4 100644 (file)
 
 fn main() {
    let s = String::from("foo");
-   let mut gen = move || { //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+   let mut gen = move || {
+   //~^ ERROR the size for value values of type
        yield s[..];
    };
-   unsafe { gen.resume(); } //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+   unsafe { gen.resume(); }
+   //~^ ERROR the size for value values of type
 }
index 957fac172c2588dd071245ec89e53b1bd7b5e1cd..2938268a804ae1dfeb598a8dfbc6fa506920ed3e 100644 (file)
@@ -1,22 +1,25 @@
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/sized-yield.rs:17:26
    |
-LL |      let mut gen = move || { //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+LL |      let mut gen = move || {
    |  __________________________^
+LL | |    //~^ ERROR the size for value values of type
 LL | |        yield s[..];
 LL | |    };
-   | |____^ `str` does not have a constant size known at compile-time
+   | |____^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: the yield type of a generator must have a statically known size
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
-  --> $DIR/sized-yield.rs:20:17
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
+  --> $DIR/sized-yield.rs:21:17
    |
-LL |    unsafe { gen.resume(); } //~ ERROR the trait bound `str: std::marker::Sized` is not satisfied
-   |                 ^^^^^^ `str` does not have a constant size known at compile-time
+LL |    unsafe { gen.resume(); }
+   |                 ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
 
 error: aborting due to 2 previous errors
 
index abb3682a4987a3533b8b70b8d75c53e381f6b54b..f6b64b394fc12580dfceb696ee1799170aea1713 100644 (file)
@@ -25,7 +25,7 @@ fn cycle1() -> impl Clone {
     //~^ ERROR cycle detected
     //~| ERROR cycle detected
     send(cycle2().clone());
-    //~^ ERROR Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<std::string::String>` cannot be sent between threads safely
 
     Rc::new(Cell::new(5))
 }
index 4537c96c4ab3b8319984f8f5d09d1c97604c38a5..b34facd2d39ce471e76832022c5f3ca92d66377f 100644 (file)
@@ -47,7 +47,7 @@ LL | fn cycle2() -> impl Clone {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^
    = note: ...which again requires processing `cycle1::{{exist-impl-Trait}}`, completing the cycle
 
-error[E0277]: the trait bound `std::rc::Rc<std::string::String>: std::marker::Send` is not satisfied in `impl std::clone::Clone`
+error[E0277]: `std::rc::Rc<std::string::String>` cannot be sent between threads safely
   --> $DIR/auto-trait-leak.rs:27:5
    |
 LL |     send(cycle2().clone());
index 16310e67f1bb9c26f1f68d89302fb666886f0925..3c61543a711bd8f3762378c6a025d10ebd253e41 100644 (file)
@@ -23,10 +23,10 @@ fn send<T: Send>(_: T) {}
 
 fn main() {
     send(before());
-    //~^ ERROR the trait bound `std::rc::Rc<std::cell::Cell<i32>>: std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<std::cell::Cell<i32>>` cannot be sent between threads safely
 
     send(after());
-    //~^ ERROR the trait bound `std::rc::Rc<std::cell::Cell<i32>>: std::marker::Send` is not satisfied
+    //~^ ERROR `std::rc::Rc<std::cell::Cell<i32>>` cannot be sent between threads safely
 }
 
 // Deferred path, main has to wait until typeck finishes,
index 59623aed3d2b73fdb5b7c7854cc2f6c1d5653aaf..fb00c41f79c8f4c4e0fcbd357602c31bb8023ae7 100644 (file)
@@ -1,4 +1,4 @@
-error[E0277]: the trait bound `std::rc::Rc<std::cell::Cell<i32>>: std::marker::Send` is not satisfied in `impl std::ops::Fn<(i32,)>`
+error[E0277]: `std::rc::Rc<std::cell::Cell<i32>>` cannot be sent between threads safely
   --> $DIR/auto-trait-leak2.rs:25:5
    |
 LL |     send(before());
@@ -13,7 +13,7 @@ note: required by `send`
 LL | fn send<T: Send>(_: T) {}
    | ^^^^^^^^^^^^^^^^^^^^^^
 
-error[E0277]: the trait bound `std::rc::Rc<std::cell::Cell<i32>>: std::marker::Send` is not satisfied in `impl std::ops::Fn<(i32,)>`
+error[E0277]: `std::rc::Rc<std::cell::Cell<i32>>` cannot be sent between threads safely
   --> $DIR/auto-trait-leak2.rs:28:5
    |
 LL |     send(after());
index 57a0040600a255d506e893c997c8b983494b9479..b64caccd98abef8311b646deb96affdb375a3aeb 100644 (file)
@@ -34,8 +34,9 @@ fn projection_with_named_trait_is_disallowed(x: impl Iterator)
 fn projection_with_named_trait_inside_path_is_disallowed()
     -> <::std::ops::Range<impl Debug> as Iterator>::Item
 //~^ ERROR `impl Trait` is not allowed in path parameters
-{
-    (1i32..100).next().unwrap()
+//~| ERROR trait bound `impl std::fmt::Debug: std::iter::Step` is not satisfied
+{ //~ ERROR trait bound `impl std::fmt::Debug: std::iter::Step` is not satisfied
+    (1i32..100).next().unwrap() //~ ERROR mismatched types
 }
 
 fn projection_from_impl_trait_inside_dyn_trait_is_disallowed()
index f6d58984ecef747ae3994640d005c6380d7ae928..b495d4b4b010b82890183f7631cea963eedc3ab4 100644 (file)
@@ -17,7 +17,7 @@ LL |     -> <::std::ops::Range<impl Debug> as Iterator>::Item
    |                           ^^^^^^^^^^
 
 error[E0667]: `impl Trait` is not allowed in path parameters
-  --> $DIR/impl_trait_projections.rs:42:29
+  --> $DIR/impl_trait_projections.rs:43:29
    |
 LL |     -> <dyn Iterator<Item = impl Debug> as Iterator>::Item
    |                             ^^^^^^^^^^
@@ -30,7 +30,34 @@ LL | fn projection_is_disallowed(x: impl Iterator) -> <impl Iterator>::Item {
    |
    = note: specify the type using the syntax `<impl std::iter::Iterator as Trait>::Item`
 
-error: aborting due to 5 previous errors
+error[E0277]: the trait bound `impl std::fmt::Debug: std::iter::Step` is not satisfied
+  --> $DIR/impl_trait_projections.rs:38:1
+   |
+LL | / { //~ ERROR trait bound `impl std::fmt::Debug: std::iter::Step` is not satisfied
+LL | |     (1i32..100).next().unwrap() //~ ERROR mismatched types
+LL | | }
+   | |_^ the trait `std::iter::Step` is not implemented for `impl std::fmt::Debug`
+   |
+   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::Range<impl std::fmt::Debug>`
+
+error[E0308]: mismatched types
+  --> $DIR/impl_trait_projections.rs:39:5
+   |
+LL |     (1i32..100).next().unwrap() //~ ERROR mismatched types
+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected anonymized type, found i32
+   |
+   = note: expected type `impl std::fmt::Debug`
+              found type `i32`
+
+error[E0277]: the trait bound `impl std::fmt::Debug: std::iter::Step` is not satisfied
+  --> $DIR/impl_trait_projections.rs:35:8
+   |
+LL |     -> <::std::ops::Range<impl Debug> as Iterator>::Item
+   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `impl std::fmt::Debug`
+   |
+   = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::Range<impl std::fmt::Debug>`
+
+error: aborting due to 8 previous errors
 
-Some errors occurred: E0223, E0667.
+Some errors occurred: E0223, E0277, E0308, E0667.
 For more information about an error, try `rustc --explain E0223`.
index a772d1f90cc0b5050ad4f4bab5c6bb2cad20695f..b0288463e9157432aa11bacb1c07e9d1d40b3e3c 100644 (file)
@@ -12,5 +12,6 @@
 use std::panic::catch_unwind;
 fn main() {
     let mut x = Cell::new(22);
-    catch_unwind(|| { x.set(23); }); //~ ERROR the trait bound
+    catch_unwind(|| { x.set(23); });
+    //~^ ERROR the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a
 }
index 4c489c5964ba7b0b4fae3c8e03908f0f0cf7d2a9..f2aecc55ccb41ad3daf01e42fcbc3c998408b72d 100644 (file)
@@ -1,8 +1,8 @@
-error[E0277]: the trait bound `std::cell::UnsafeCell<i32>: std::panic::RefUnwindSafe` is not satisfied in `std::cell::Cell<i32>`
+error[E0277]: the type `std::cell::UnsafeCell<i32>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary
   --> $DIR/interior-mutability.rs:15:5
    |
-LL |     catch_unwind(|| { x.set(23); }); //~ ERROR the trait bound
-   |     ^^^^^^^^^^^^ the type std::cell::UnsafeCell<i32> may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary
+LL |     catch_unwind(|| { x.set(23); });
+   |     ^^^^^^^^^^^^ `std::cell::UnsafeCell<i32>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary
    |
    = help: within `std::cell::Cell<i32>`, the trait `std::panic::RefUnwindSafe` is not implemented for `std::cell::UnsafeCell<i32>`
    = note: required because it appears within the type `std::cell::Cell<i32>`
index 8045993747934a09c8bad37c719df935f877fa3b..be10b1d517bdc6c16af40bb31bef21b15a9cc0f8 100644 (file)
@@ -1,10 +1,10 @@
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/issue-36400.rs:15:7
    |
+LL |     let x = Box::new(3);
+   |         - help: consider changing this to be mutable: `mut x`
 LL |     f(&mut *x); //~ ERROR cannot borrow immutable
    |       ^^^^^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `x`
 
 error: aborting due to previous error
 
index f9486fa57b136eccf30f45a685a3cbf897f030fd..831c3e5fda084c560f01c0676303e1ea99a85ad4 100644 (file)
@@ -9,4 +9,4 @@
 // except according to those terms.
 
 fn main<'a>() { }
-    //~^ ERROR `main` function is not allowed to have lifetime parameters [E0131]
+    //~^ ERROR `main` function is not allowed to have generic parameters [E0131]
index 3b691bbb0330f587f82f381477a1e64e6233a6f9..1daa8dfbba689ec3b55edc3daf15dbf6da8f8932 100644 (file)
@@ -1,8 +1,8 @@
-error[E0131]: `main` function is not allowed to have lifetime parameters
+error[E0131]: `main` function is not allowed to have generic parameters
   --> $DIR/issue-51022.rs:11:8
    |
 LL | fn main<'a>() { }
-   |        ^^^^ `main` cannot have lifetime parameters
+   |        ^^^^ `main` cannot have generic parameters
 
 error: aborting due to previous error
 
index 9d6d68f518d72997542dbcb959647cb68c1cabf8..93f2837c0fc11ce2b838da0757d829d87805cd54 100644 (file)
@@ -18,7 +18,7 @@ error[E0384]: cannot assign to immutable argument `y`
   --> $DIR/ex3-both-anon-regions-one-is-struct-2.rs:14:5
    |
 LL | fn foo(mut x: Ref, y: &u32) {
-   |                    - argument not declared as `mut`
+   |                    - consider changing this to `mut y`
 LL |     y = x.b; //~ ERROR lifetime mismatch
    |     ^^^^^^^ cannot assign to immutable argument
 
index f58f33c9a9adbced2b9eca788f152104b8153b91..01e26980323949cac18c34806e96e9453f4cc79a 100644 (file)
@@ -15,6 +15,8 @@ LL |   y.push(z); //~ ERROR lifetime mismatch
 error[E0596]: cannot borrow immutable item `y` as mutable
   --> $DIR/ex3-both-anon-regions-using-fn-items.rs:11:3
    |
+LL | fn foo(x:fn(&u8, &u8), y: Vec<&u8>, z: &u8) {
+   |                        - help: consider changing this to be mutable: `mut y`
 LL |   y.push(z); //~ ERROR lifetime mismatch
    |   ^ cannot borrow as mutable
 
index 4bfb4ac2833c8c77c36b7b516530198bc8a80c68..a61d49fc953dbd9eb2ba896d5eddccca5c8179b4 100644 (file)
@@ -15,6 +15,8 @@ LL |   y.push(z); //~ ERROR lifetime mismatch
 error[E0596]: cannot borrow immutable item `y` as mutable
   --> $DIR/ex3-both-anon-regions-using-trait-objects.rs:11:3
    |
+LL | fn foo(x:Box<Fn(&u8, &u8)> , y: Vec<&u8>, z: &u8) {
+   |                              - help: consider changing this to be mutable: `mut y`
 LL |   y.push(z); //~ ERROR lifetime mismatch
    |   ^ cannot borrow as mutable
 
index 43743118966596dde663f6af9dac9e9ae1a63ef5..0620235371a3928126d3037102188b5002ed61b6 100644 (file)
@@ -32,6 +32,9 @@ LL |             x = 2;      //~ ERROR (Ast) [E0384]
 error[E0384]: cannot assign twice to immutable variable `x` (Mir)
   --> $DIR/liveness-assign-imm-local-notes.rs:23:9
    |
+LL |     let x;
+   |         - consider changing this to `mut x`
+...
 LL |         x = 2;
    |         ----- first assignment to `x`
 LL |         x = 3;      //~ ERROR (Ast) [E0384]
@@ -40,6 +43,9 @@ LL |         x = 3;      //~ ERROR (Ast) [E0384]
 error[E0384]: cannot assign twice to immutable variable `x` (Mir)
   --> $DIR/liveness-assign-imm-local-notes.rs:35:13
    |
+LL |         let x;
+   |             - consider changing this to `mut x`
+...
 LL |             x = 2;
    |             ----- first assignment to `x`
 LL |             x = 3;      //~ ERROR (Ast) [E0384]
@@ -48,12 +54,18 @@ LL |             x = 3;      //~ ERROR (Ast) [E0384]
 error[E0384]: cannot assign twice to immutable variable `x` (Mir)
   --> $DIR/liveness-assign-imm-local-notes.rs:45:13
    |
+LL |     let x;
+   |         - consider changing this to `mut x`
+...
 LL |             x = 1;      //~ ERROR (Ast) [E0384]
    |             ^^^^^ cannot assign twice to immutable variable
 
 error[E0384]: cannot assign twice to immutable variable `x` (Mir)
   --> $DIR/liveness-assign-imm-local-notes.rs:48:13
    |
+LL |     let x;
+   |         - consider changing this to `mut x`
+...
 LL |             x = 1;      //~ ERROR (Ast) [E0384]
    |             ----- first assignment to `x`
 ...
index a12baab415907892419e271e5a1f9f3a6ac652cc..213eddee720d3e081949e761f6762e0d9955b00a 100644 (file)
@@ -1,6 +1,8 @@
 error[E0596]: cannot borrow immutable item `foo` as mutable
   --> $DIR/span-covering-argument-1.rs:15:14
    |
+LL |             let $s = 0;
+   |                 -- help: consider changing this to be mutable: `mut foo`
 LL |             *&mut $s = 0;
    |              ^^^^^^^ cannot borrow as mutable
 ...
index 3f2cb59b11dee4f189eb36f543fe151c9fec17b2..86785f24f3637fbc9a9a059ece035cdd9c5dff5d 100644 (file)
@@ -13,6 +13,6 @@ fn main() {
     2 as usize - Some(1); //~ ERROR cannot subtract `std::option::Option<{integer}>` from `usize`
     3 * (); //~ ERROR cannot multiply `()` to `{integer}`
     4 / ""; //~ ERROR cannot divide `{integer}` by `&str`
-    5 < String::new(); //~ ERROR is not satisfied
-    6 == Ok(1); //~ ERROR is not satisfied
+    5 < String::new(); //~ ERROR can't compare `{integer}` with `std::string::String`
+    6 == Ok(1); //~ ERROR can't compare `{integer}` with `std::result::Result<{integer}, _>`
 }
index 9d23b256fd333bee352c51ff796d2c21630ae910..4c6d95efadb1557fa071bb0c560f8e00f6bcb4cd 100644 (file)
@@ -30,19 +30,19 @@ LL |     4 / ""; //~ ERROR cannot divide `{integer}` by `&str`
    |
    = help: the trait `std::ops::Div<&str>` is not implemented for `{integer}`
 
-error[E0277]: the trait bound `{integer}: std::cmp::PartialOrd<std::string::String>` is not satisfied
+error[E0277]: can't compare `{integer}` with `std::string::String`
   --> $DIR/binops.rs:16:7
    |
-LL |     5 < String::new(); //~ ERROR is not satisfied
-   |       ^ can't compare `{integer}` with `std::string::String`
+LL |     5 < String::new(); //~ ERROR can't compare `{integer}` with `std::string::String`
+   |       ^ no implementation for `{integer} < std::string::String` and `{integer} > std::string::String`
    |
    = help: the trait `std::cmp::PartialOrd<std::string::String>` is not implemented for `{integer}`
 
-error[E0277]: the trait bound `{integer}: std::cmp::PartialEq<std::result::Result<{integer}, _>>` is not satisfied
+error[E0277]: can't compare `{integer}` with `std::result::Result<{integer}, _>`
   --> $DIR/binops.rs:17:7
    |
-LL |     6 == Ok(1); //~ ERROR is not satisfied
-   |       ^^ can't compare `{integer}` with `std::result::Result<{integer}, _>`
+LL |     6 == Ok(1); //~ ERROR can't compare `{integer}` with `std::result::Result<{integer}, _>`
+   |       ^^ no implementation for `{integer} == std::result::Result<{integer}, _>`
    |
    = help: the trait `std::cmp::PartialEq<std::result::Result<{integer}, _>>` is not implemented for `{integer}`
 
index 15388b3a7647f9625e894f76069a61ce6ca8deb0..d76c4a015a2c2f5236ee0b5598f54d28d4110dba 100644 (file)
@@ -60,7 +60,7 @@ fn main()
 
     let _ = 42usize as *const [u8]; //~ ERROR is invalid
     let _ = v as *const [u8]; //~ ERROR cannot cast
-    let _ = fat_v as *const Foo; //~ ERROR is not satisfied
+    let _ = fat_v as *const Foo; //~ ERROR the size for value values of type
     let _ = foo as *const str; //~ ERROR is invalid
     let _ = foo as *mut str; //~ ERROR is invalid
     let _ = main as *mut str; //~ ERROR is invalid
@@ -69,7 +69,7 @@ fn main()
     let _ = fat_sv as usize; //~ ERROR is invalid
 
     let a : *const str = "hello";
-    let _ = a as *const Foo; //~ ERROR is not satisfied
+    let _ = a as *const Foo; //~ ERROR the size for value values of type
 
     // check no error cascade
     let _ = main.f as *const u32; //~ ERROR no field
index 7931e7ff07f4ce55d4e5d573d3f49daa077f8278..feaf492837f7f83b795717934763cd8890f760e8 100644 (file)
@@ -216,22 +216,24 @@ LL |     let _ = cf as *const Bar; //~ ERROR is invalid
    |
    = note: vtable kinds may not match
 
-error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `[u8]` cannot be known at compilation time
   --> $DIR/cast-rfc0401.rs:63:13
    |
-LL |     let _ = fat_v as *const Foo; //~ ERROR is not satisfied
-   |             ^^^^^ `[u8]` does not have a constant size known at compile-time
+LL |     let _ = fat_v as *const Foo; //~ ERROR the size for value values of type
+   |             ^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u8]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required for the cast to the object type `Foo`
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/cast-rfc0401.rs:72:13
    |
-LL |     let _ = a as *const Foo; //~ ERROR is not satisfied
-   |             ^ `str` does not have a constant size known at compile-time
+LL |     let _ = a as *const Foo; //~ ERROR the size for value values of type
+   |             ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required for the cast to the object type `Foo`
 
 error[E0606]: casting `&{float}` as `f32` is invalid
diff --git a/src/test/ui/missing-allocator.rs b/src/test/ui/missing-allocator.rs
new file mode 100644 (file)
index 0000000..2428263
--- /dev/null
@@ -0,0 +1,26 @@
+// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: -C panic=abort
+// no-prefer-dynamic
+
+#![no_std]
+#![crate_type = "staticlib"]
+#![feature(panic_implementation, lang_items, alloc)]
+
+#[panic_implementation]
+fn panic(_: &core::panic::PanicInfo) -> ! {
+    loop {}
+}
+
+#[lang = "oom"]
+fn oom() {}
+
+extern crate alloc;
diff --git a/src/test/ui/missing-allocator.stderr b/src/test/ui/missing-allocator.stderr
new file mode 100644 (file)
index 0000000..11e0085
--- /dev/null
@@ -0,0 +1,4 @@
+error: no global memory allocator found but one is required; link to std or add #[global_allocator] to a static item that implements the GlobalAlloc trait.
+
+error: aborting due to previous error
+
index f3952c49a2a36fecd13ff84996782ed83cff5d39..96e9f1554144788a6ecbaf1ccf0a15a6f85fea83 100644 (file)
@@ -1,4 +1,4 @@
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `fancy_ref.num` which is behind a `&` reference
   --> $DIR/issue-47388.rs:18:5
    |
 LL |     let fancy_ref = &(&mut fancy);
diff --git a/src/test/ui/nll/issue-51268.rs b/src/test/ui/nll/issue-51268.rs
new file mode 100644 (file)
index 0000000..6edd4a3
--- /dev/null
@@ -0,0 +1,35 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-tidy-linelength
+
+#![feature(nll)]
+
+struct Bar;
+
+impl Bar {
+    fn bar(&mut self, _: impl Fn()) {}
+}
+
+struct Foo {
+    thing: Bar,
+    number: usize,
+}
+
+impl Foo {
+    fn foo(&mut self) {
+        self.thing.bar(|| {
+        //~^ ERROR cannot borrow `self.thing` as mutable because it is also borrowed as immutable [E0502]
+            &self.number;
+        });
+    }
+}
+
+fn main() {}
diff --git a/src/test/ui/nll/issue-51268.stderr b/src/test/ui/nll/issue-51268.stderr
new file mode 100644 (file)
index 0000000..269bc36
--- /dev/null
@@ -0,0 +1,20 @@
+error[E0502]: cannot borrow `self.thing` as mutable because it is also borrowed as immutable
+  --> $DIR/issue-51268.rs:28:9
+   |
+LL |            self.thing.bar(|| {
+   |            ^              -- immutable borrow occurs here
+   |   _________|
+   |  |_________|
+   | ||
+LL | ||         //~^ ERROR cannot borrow `self.thing` as mutable because it is also borrowed as immutable [E0502]
+LL | ||             &self.number;
+   | ||              ---- previous borrow occurs due to use of `self` in closure
+LL | ||         });
+   | ||          ^
+   | ||__________|
+   | |___________mutable borrow occurs here
+   |             borrow later used here
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0502`.
diff --git a/src/test/ui/parser/expected-comma-found-token.rs b/src/test/ui/parser/expected-comma-found-token.rs
new file mode 100644 (file)
index 0000000..3c53c3a
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Tests that two closures cannot simultaneously have mutable
+// access to the variable, whether that mutable access be used
+// for direct assignment or for taking mutable ref. Issue #6801.
+
+#![feature(on_unimplemented)]
+
+#[rustc_on_unimplemented(
+    message="the message"
+    label="the label"
+)]
+trait T {}
+//~^^^ ERROR expected one of `)` or `,`, found `label`
diff --git a/src/test/ui/parser/expected-comma-found-token.stderr b/src/test/ui/parser/expected-comma-found-token.stderr
new file mode 100644 (file)
index 0000000..9a564bb
--- /dev/null
@@ -0,0 +1,10 @@
+error: expected one of `)` or `,`, found `label`
+  --> $DIR/expected-comma-found-token.rs:19:5
+   |
+LL |     message="the message"
+   |                          - expected one of `)` or `,` here
+LL |     label="the label"
+   |     ^^^^^ unexpected token
+
+error: aborting due to previous error
+
index c813b64d40b58ddde391f8f185b286898dba871d..43f13d45684e8c7ee46cdf5d1ce08fc74422e91d 100644 (file)
@@ -1,8 +1,8 @@
-error[E0277]: the trait bound `&T: std::cmp::PartialEq<T>` is not satisfied
+error[E0277]: can't compare `&T` with `T`
   --> $DIR/partialeq_help.rs:12:7
    |
 LL |     a == b; //~ ERROR E0277
-   |       ^^ can't compare `&T` with `T`
+   |       ^^ no implementation for `&T == T`
    |
    = help: the trait `std::cmp::PartialEq<T>` is not implemented for `&T`
    = help: consider adding a `where &T: std::cmp::PartialEq<T>` bound
index 7005088965df13f78e0b53e8922e873fdfeea3b6..de755dd6a4602e2a6ec4a0da0f86091bdd1c6614 100644 (file)
@@ -1,4 +1,4 @@
-error: incorrect visibility restriction
+error[E0704]: incorrect visibility restriction
   --> $DIR/pub-restricted.rs:15:6
    |
 LL | pub (a) fn afn() {} //~ incorrect visibility restriction
@@ -9,7 +9,7 @@ LL | pub (a) fn afn() {} //~ incorrect visibility restriction
            `pub(super)`: visible only in the current module's parent
            `pub(in path::to::module)`: visible only on the specified path
 
-error: incorrect visibility restriction
+error[E0704]: incorrect visibility restriction
   --> $DIR/pub-restricted.rs:16:6
    |
 LL | pub (b) fn bfn() {} //~ incorrect visibility restriction
@@ -20,7 +20,7 @@ LL | pub (b) fn bfn() {} //~ incorrect visibility restriction
            `pub(super)`: visible only in the current module's parent
            `pub(in path::to::module)`: visible only on the specified path
 
-error: incorrect visibility restriction
+error[E0704]: incorrect visibility restriction
   --> $DIR/pub-restricted.rs:32:14
    |
 LL |         pub (a) invalid: usize, //~ incorrect visibility restriction
@@ -31,7 +31,7 @@ LL |         pub (a) invalid: usize, //~ incorrect visibility restriction
            `pub(super)`: visible only in the current module's parent
            `pub(in path::to::module)`: visible only on the specified path
 
-error: incorrect visibility restriction
+error[E0704]: incorrect visibility restriction
   --> $DIR/pub-restricted.rs:41:6
    |
 LL | pub (xyz) fn xyz() {} //~ incorrect visibility restriction
@@ -50,3 +50,4 @@ LL |         pub (in x) non_parent_invalid: usize, //~ ERROR visibilities can on
 
 error: aborting due to 5 previous errors
 
+For more information about this error, try `rustc --explain E0704`.
diff --git a/src/test/ui/reassign-ref-mut.rs b/src/test/ui/reassign-ref-mut.rs
new file mode 100644 (file)
index 0000000..c045720
--- /dev/null
@@ -0,0 +1,26 @@
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// Tests how we behave when the user attempts to mutate an immutable
+// binding that was introduced by either `ref` or `ref mut`
+// patterns.
+//
+// Such bindings cannot be made mutable via the mere addition of the
+// `mut` keyword, and thus we want to check that the compiler does not
+// suggest doing so.
+
+fn main() {
+    let (mut one_two, mut three_four) = ((1, 2), (3, 4));
+    let &mut (ref a, ref mut b) = &mut one_two;
+    a = &three_four.0;
+    //~^ ERROR cannot assign twice to immutable variable `a` [E0384]
+    b = &mut three_four.1;
+    //~^ ERROR cannot assign twice to immutable variable `b` [E0384]
+}
diff --git a/src/test/ui/reassign-ref-mut.stderr b/src/test/ui/reassign-ref-mut.stderr
new file mode 100644 (file)
index 0000000..bf627dd
--- /dev/null
@@ -0,0 +1,20 @@
+error[E0384]: cannot assign twice to immutable variable `a`
+  --> $DIR/reassign-ref-mut.rs:22:5
+   |
+LL |     let &mut (ref a, ref mut b) = &mut one_two;
+   |               ----- first assignment to `a`
+LL |     a = &three_four.0;
+   |     ^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
+
+error[E0384]: cannot assign twice to immutable variable `b`
+  --> $DIR/reassign-ref-mut.rs:24:5
+   |
+LL |     let &mut (ref a, ref mut b) = &mut one_two;
+   |                      --------- first assignment to `b`
+...
+LL |     b = &mut three_four.1;
+   |     ^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0384`.
index 83ff95cc2ea48f59c0086e69e970eb4a3aa1752f..ca854f9f70122c2b4750bac48c658447f6fa7a13 100644 (file)
@@ -11,6 +11,7 @@
 trait I {}
 type K = I+'static;
 
-fn foo(_x: K) {} //~ ERROR: `I + 'static: std::marker::Sized` is not satisfied
+fn foo(_x: K) {}
+//~^ ERROR the size for value values of type
 
 fn main() {}
index 92309274e844279f3b18846115cf1816f20a5c23..efcd0b3624811c76d4db90ee6c2329df367588ef 100644 (file)
@@ -1,10 +1,11 @@
-error[E0277]: the trait bound `I + 'static: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `I + 'static` cannot be known at compilation time
   --> $DIR/issue-5035-2.rs:14:8
    |
-LL | fn foo(_x: K) {} //~ ERROR: `I + 'static: std::marker::Sized` is not satisfied
-   |        ^^ `I + 'static` does not have a constant size known at compile-time
+LL | fn foo(_x: K) {}
+   |        ^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `I + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: all local variables must have a statically known size
 
 error: aborting due to previous error
index b97bdeea409c6310e431d7139356b1cf6f07d246..8aa7e8a417c2bea3aeb5d778768278e29720e664 100644 (file)
@@ -1,26 +1,20 @@
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*x` which is behind a `&` reference
   --> $DIR/enum.rs:19:5
    |
-LL |     let Wrap(x) = &Wrap(3);
-   |              - help: consider changing this to be a mutable reference: `&mut`
 LL |     *x += 1; //~ ERROR cannot assign to immutable
-   |     ^^^^^^^
+   |     ^^^^^^^ cannot assign
 
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*x` which is behind a `&` reference
   --> $DIR/enum.rs:23:9
    |
-LL |     if let Some(x) = &Some(3) {
-   |                 - help: consider changing this to be a mutable reference: `&mut`
 LL |         *x += 1; //~ ERROR cannot assign to immutable
-   |         ^^^^^^^
+   |         ^^^^^^^ cannot assign
 
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*x` which is behind a `&` reference
   --> $DIR/enum.rs:29:9
    |
-LL |     while let Some(x) = &Some(3) {
-   |                    - help: consider changing this to be a mutable reference: `&mut`
 LL |         *x += 1; //~ ERROR cannot assign to immutable
-   |         ^^^^^^^
+   |         ^^^^^^^ cannot assign
 
 error: aborting due to 3 previous errors
 
index 3ee4dc07bb8bbb05bb993fcdfe2ec3bcd1341aa4..4e00dec761621ac58d317944e99a1275c270ea28 100644 (file)
@@ -1,26 +1,20 @@
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*n` which is behind a `&` reference
   --> $DIR/explicit-mut.rs:17:13
    |
-LL |         Some(n) => {
-   |              - help: consider changing this to be a mutable reference: `&mut`
 LL |             *n += 1; //~ ERROR cannot assign to immutable
-   |             ^^^^^^^
+   |             ^^^^^^^ cannot assign
 
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*n` which is behind a `&` reference
   --> $DIR/explicit-mut.rs:25:13
    |
-LL |         Some(n) => {
-   |              - help: consider changing this to be a mutable reference: `&mut`
 LL |             *n += 1; //~ ERROR cannot assign to immutable
-   |             ^^^^^^^
+   |             ^^^^^^^ cannot assign
 
-error[E0594]: cannot assign to data in a `&` reference
+error[E0594]: cannot assign to `*n` which is behind a `&` reference
   --> $DIR/explicit-mut.rs:33:13
    |
-LL |         Some(n) => {
-   |              - help: consider changing this to be a mutable reference: `&mut`
 LL |             *n += 1; //~ ERROR cannot assign to immutable
-   |             ^^^^^^^
+   |             ^^^^^^^ cannot assign
 
 error: aborting due to 3 previous errors
 
index ed96570583f4ffb4bbda6230eaa2a5438f686b9d..8c31ab2ca88e4d71a88dda2c6d1b759b1c3444d0 100644 (file)
@@ -20,13 +20,13 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/collections.rs:33:50
    |
 LL |     fn iterate<'iter>(&'iter self) -> Self::Iter<'iter>;
-   |                                                  ^^^^^ lifetime parameter not allowed on this type
+   |                                                  ^^^^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/collections.rs:59:50
    |
 LL |     fn iterate<'iter>(&'iter self) -> Self::Iter<'iter> {
-   |                                                  ^^^^^ lifetime parameter not allowed on this type
+   |                                                  ^^^^^ lifetime parameter not allowed
 
 error: aborting due to 5 previous errors
 
index 764a0db2478a8478d7d86dd03758905bf9db48f4..1746122eb49f41d68b726acf25b086e6cda7e555 100644 (file)
@@ -2,19 +2,19 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/construct_with_other_type.rs:26:46
    |
 LL |     type Baa<'a>: Deref<Target = <Self::Quux<'a> as Foo>::Bar<'a, 'static>>;
-   |                                              ^^ lifetime parameter not allowed on this type
+   |                                              ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/construct_with_other_type.rs:26:63
    |
 LL |     type Baa<'a>: Deref<Target = <Self::Quux<'a> as Foo>::Bar<'a, 'static>>;
-   |                                                               ^^ lifetime parameter not allowed on this type
+   |                                                               ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/construct_with_other_type.rs:34:40
    |
 LL |     type Baa<'a> = &'a <T as Foo>::Bar<'a, 'static>;
-   |                                        ^^ lifetime parameter not allowed on this type
+   |                                        ^^ lifetime parameter not allowed
 
 error: aborting due to 3 previous errors
 
index 64e82c0d1097ffc1de33bf470488046bb9d4f9a5..d48c21477b310668bfa620ace9f6314c561a08e0 100644 (file)
@@ -14,19 +14,19 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/generic_associated_type_undeclared_lifetimes.rs:20:47
    |
 LL |     type Iter<'a>: Iterator<Item = Self::Item<'a>>
-   |                                               ^^ lifetime parameter not allowed on this type
+   |                                               ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/generic_associated_type_undeclared_lifetimes.rs:22:37
    |
 LL |         + Deref<Target = Self::Item<'b>>;
-   |                                     ^^ lifetime parameter not allowed on this type
+   |                                     ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/generic_associated_type_undeclared_lifetimes.rs:26:41
    |
 LL |     fn iter<'a>(&'a self) -> Self::Iter<'undeclared>;
-   |                                         ^^^^^^^^^^^ lifetime parameter not allowed on this type
+   |                                         ^^^^^^^^^^^ lifetime parameter not allowed
 
 error: aborting due to 5 previous errors
 
index 0e251300e451f8bb49eae67a15577a72ead73977..737a29ec2c8be46ced3f82ad9674b416b6ca9b73 100644 (file)
@@ -2,37 +2,37 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:20:47
    |
 LL |     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
-   |                                               ^^ lifetime parameter not allowed on this type
+   |                                               ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:49:53
    |
 LL | fn make_iter<'a, I: Iterable>(it: &'a I) -> I::Iter<'a> {
-   |                                                     ^^ lifetime parameter not allowed on this type
+   |                                                     ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:54:60
    |
 LL | fn get_first<'a, I: Iterable>(it: &'a I) -> Option<I::Item<'a>> {
-   |                                                            ^^ lifetime parameter not allowed on this type
+   |                                                            ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:23:41
    |
 LL |     fn iter<'a>(&'a self) -> Self::Iter<'a>;
-   |                                         ^^ lifetime parameter not allowed on this type
+   |                                         ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:32:41
    |
 LL |     fn iter<'a>(&'a self) -> Self::Iter<'a> {
-   |                                         ^^ lifetime parameter not allowed on this type
+   |                                         ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/iterable.rs:43:41
    |
 LL |     fn iter<'a>(&'a self) -> Self::Iter<'a> {
-   |                                         ^^ lifetime parameter not allowed on this type
+   |                                         ^^ lifetime parameter not allowed
 
 error: aborting due to 6 previous errors
 
index df83fdaad5bfa66f13ce9210569fe1a31e288faf..c8d37a51fa96bd5cd73e1c6161a89c453bca1b62 100644 (file)
@@ -1,3 +1,9 @@
+error[E0110]: lifetime parameters are not allowed on this type
+  --> $DIR/parameter_number_and_kind.rs:26:27
+   |
+LL |     type FOk<T> = Self::E<'static, T>;
+   |                           ^^^^^^^ lifetime parameter not allowed
+
 error[E0109]: type parameters are not allowed on this type
   --> $DIR/parameter_number_and_kind.rs:26:36
    |
@@ -5,16 +11,16 @@ LL |     type FOk<T> = Self::E<'static, T>;
    |                                    ^ type parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
-  --> $DIR/parameter_number_and_kind.rs:26:27
+  --> $DIR/parameter_number_and_kind.rs:29:26
    |
-LL |     type FOk<T> = Self::E<'static, T>;
-   |                           ^^^^^^^ lifetime parameter not allowed on this type
+LL |     type FErr1 = Self::E<'static, 'static>; // Error
+   |                          ^^^^^^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
-  --> $DIR/parameter_number_and_kind.rs:29:26
+  --> $DIR/parameter_number_and_kind.rs:31:29
    |
-LL |     type FErr1 = Self::E<'static, 'static>; // Error
-   |                          ^^^^^^^ lifetime parameter not allowed on this type
+LL |     type FErr2<T> = Self::E<'static, T, u32>; // Error
+   |                             ^^^^^^^ lifetime parameter not allowed
 
 error[E0109]: type parameters are not allowed on this type
   --> $DIR/parameter_number_and_kind.rs:31:38
@@ -22,12 +28,6 @@ error[E0109]: type parameters are not allowed on this type
 LL |     type FErr2<T> = Self::E<'static, T, u32>; // Error
    |                                      ^ type parameter not allowed
 
-error[E0110]: lifetime parameters are not allowed on this type
-  --> $DIR/parameter_number_and_kind.rs:31:29
-   |
-LL |     type FErr2<T> = Self::E<'static, T, u32>; // Error
-   |                             ^^^^^^^ lifetime parameter not allowed on this type
-
 error: aborting due to 5 previous errors
 
 Some errors occurred: E0109, E0110.
index 607a4b8d57996e1cb0343783c379a9e4669093c8..12e206cbd476af56a70098be716d39a69b699fc8 100644 (file)
@@ -2,31 +2,31 @@ error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/streaming_iterator.rs:27:41
    |
 LL |     bar: <T as StreamingIterator>::Item<'static>,
-   |                                         ^^^^^^^ lifetime parameter not allowed on this type
+   |                                         ^^^^^^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/streaming_iterator.rs:35:64
    |
 LL | fn foo<T>(iter: T) where T: StreamingIterator, for<'a> T::Item<'a>: Display { /* ... */ }
-   |                                                                ^^ lifetime parameter not allowed on this type
+   |                                                                ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/streaming_iterator.rs:21:48
    |
 LL |     fn next<'a>(&'a self) -> Option<Self::Item<'a>>;
-   |                                                ^^ lifetime parameter not allowed on this type
+   |                                                ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/streaming_iterator.rs:47:37
    |
 LL |     type Item<'a> = (usize, I::Item<'a>);
-   |                                     ^^ lifetime parameter not allowed on this type
+   |                                     ^^ lifetime parameter not allowed
 
 error[E0110]: lifetime parameters are not allowed on this type
   --> $DIR/streaming_iterator.rs:49:48
    |
 LL |     fn next<'a>(&'a self) -> Option<Self::Item<'a>> {
-   |                                                ^^ lifetime parameter not allowed on this type
+   |                                                ^^ lifetime parameter not allowed
 
 error: aborting due to 5 previous errors
 
index 172828b9a40f9f1bd1a2e06bbc0e56cbda21a49b..3282fbba6c5cfea76aca5fd6733a04fc25e9b21f 100644 (file)
@@ -1,50 +1,66 @@
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:63:24
    |
+LL | fn deref_mut_field1(x: Own<Point>) {
+   |                     - help: consider changing this to be mutable: `mut x`
 LL |     let __isize = &mut x.y; //~ ERROR cannot borrow
    |                        ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:75:10
    |
+LL | fn deref_extend_mut_field1(x: &Own<Point>) -> &mut isize {
+   |                               ----------- help: consider changing this to be a mutable reference: `&mut Own<Point>`
 LL |     &mut x.y //~ ERROR cannot borrow
-   |          ^ cannot borrow as mutable
+   |          ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:98:5
    |
+LL | fn assign_field1<'a>(x: Own<Point>) {
+   |                      - help: consider changing this to be mutable: `mut x`
 LL |     x.y = 3; //~ ERROR cannot borrow
    |     ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:102:5
    |
+LL | fn assign_field2<'a>(x: &'a Own<Point>) {
+   |                         -------------- help: consider changing this to be a mutable reference: `&mut Own<Point>`
 LL |     x.y = 3; //~ ERROR cannot borrow
-   |     ^ cannot borrow as mutable
+   |     ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:119:5
    |
+LL | fn deref_mut_method1(x: Own<Point>) {
+   |                      - help: consider changing this to be mutable: `mut x`
 LL |     x.set(0, 0); //~ ERROR cannot borrow
    |     ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:131:5
    |
+LL | fn deref_extend_mut_method1(x: &Own<Point>) -> &mut isize {
+   |                                ----------- help: consider changing this to be a mutable reference: `&mut Own<Point>`
 LL |     x.y_mut() //~ ERROR cannot borrow
-   |     ^ cannot borrow as mutable
+   |     ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:139:6
    |
+LL | fn assign_method1<'a>(x: Own<Point>) {
+   |                       - help: consider changing this to be mutable: `mut x`
 LL |     *x.y_mut() = 3; //~ ERROR cannot borrow
    |      ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:143:6
    |
+LL | fn assign_method2<'a>(x: &'a Own<Point>) {
+   |                          -------------- help: consider changing this to be a mutable reference: `&mut Own<Point>`
 LL |     *x.y_mut() = 3; //~ ERROR cannot borrow
-   |      ^ cannot borrow as mutable
+   |      ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to 8 previous errors
 
index 24abe85de76f728d604adaa91c6b2d6c6207cff4..0b1bfd8cee6730821670893decd6197ff80cf59b 100644 (file)
@@ -1,26 +1,34 @@
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-deref-mut.rs:39:25
    |
+LL | fn deref_mut1(x: Own<isize>) {
+   |               - help: consider changing this to be mutable: `mut x`
 LL |     let __isize = &mut *x; //~ ERROR cannot borrow
    |                         ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-deref-mut.rs:51:11
    |
+LL | fn deref_extend_mut1<'a>(x: &'a Own<isize>) -> &'a mut isize {
+   |                             -------------- help: consider changing this to be a mutable reference: `&mut Own<isize>`
 LL |     &mut **x //~ ERROR cannot borrow
-   |           ^^ cannot borrow as mutable
+   |           ^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `x` as mutable
   --> $DIR/borrowck-borrow-overloaded-deref-mut.rs:59:6
    |
+LL | fn assign1<'a>(x: Own<isize>) {
+   |                - help: consider changing this to be mutable: `mut x`
 LL |     *x = 3; //~ ERROR cannot borrow
    |      ^ cannot borrow as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-borrow-overloaded-deref-mut.rs:63:6
    |
+LL | fn assign2<'a>(x: &'a Own<isize>) {
+   |                   -------------- help: consider changing this to be a mutable reference: `&mut Own<isize>`
 LL |     **x = 3; //~ ERROR cannot borrow
-   |      ^^ cannot borrow as mutable
+   |      ^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to 4 previous errors
 
index 26e9ea4dc0bc86b286cf22f096acaa46dc4bd4cc..c4bdef21de4bacdf5698a5c6ee99b7877ae1f993 100644 (file)
@@ -15,16 +15,18 @@ LL | |     }));
 error[E0596]: cannot borrow immutable item `*f` as mutable
   --> $DIR/borrowck-call-is-borrow-issue-12224.rs:35:5
    |
+LL | fn test2<F>(f: &F) where F: FnMut() {
+   |                -- help: consider changing this to be a mutable reference: `&mut F`
 LL |     (*f)();
-   |     ^^^^ cannot borrow as mutable
+   |     ^^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `*f.f` as mutable
   --> $DIR/borrowck-call-is-borrow-issue-12224.rs:44:5
    |
+LL | fn test4(f: &Test) {
+   |             ----- help: consider changing this to be a mutable reference: `&mut Test<'_>`
 LL |     f.f.call_mut(())
-   |     ^^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*f`
+   |     ^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0507]: cannot move out of borrowed content
   --> $DIR/borrowck-call-is-borrow-issue-12224.rs:66:13
index 43934bf4aeec15fff36516d960922370aa5bdc62..0bc614589e3d2ef1d0361fa8db4ae37bd736b6ab 100644 (file)
@@ -1,8 +1,11 @@
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-call-method-from-mut-aliasable.rs:27:5
    |
+LL | fn b(x: &Foo) {
+   |         ---- help: consider changing this to be a mutable reference: `&mut Foo`
+LL |     x.f();
 LL |     x.h(); //~ ERROR cannot borrow
-   |     ^ cannot borrow as mutable
+   |     ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to previous error
 
index d3c6fd66599478c6de092761e2e67e959796748a..1cb2c92833c1634ab689cadce02bf38b98765fb1 100644 (file)
@@ -1,8 +1,10 @@
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-fn-in-const-b.rs:17:9
    |
+LL |     fn broken(x: &Vec<String>) {
+   |                  ------------ help: consider changing this to be a mutable reference: `&mut std::vec::Vec<std::string::String>`
 LL |         x.push(format!("this is broken"));
-   |         ^ cannot borrow as mutable
+   |         ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to previous error
 
index 9b5e084bd375134372d1863b936b27a527bcc498..cf615eed55691d3fc1db747ee184707042d3c7b8 100644 (file)
@@ -1,16 +1,20 @@
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-object-mutability.rs:19:5
    |
+LL | fn borrowed_receiver(x: &Foo) {
+   |                         ---- help: consider changing this to be a mutable reference: `&mut Foo`
+LL |     x.borrowed();
 LL |     x.borrowed_mut(); //~ ERROR cannot borrow
-   |     ^ cannot borrow as mutable
+   |     ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `*x` as mutable
   --> $DIR/borrowck-object-mutability.rs:29:5
    |
+LL | fn owned_receiver(x: Box<Foo>) {
+   |                   - help: consider changing this to be mutable: `mut x`
+LL |     x.borrowed();
 LL |     x.borrowed_mut(); //~ ERROR cannot borrow
    |     ^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `x`
 
 error: aborting due to 2 previous errors
 
index 64a76399da3454ef1bff452c08b7b0331c1e2cfd..b268f6e3ab014ea0c6b368b5384e4465d822b56b 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `m` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 2a8ef24307d2476ff68bf8a519b21c9757277e92..86a4f0e13b512b07312eb58c389e10b8d4ce59ee 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `d1` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `d2` does not live long enough
   --> $DIR/dropck_direct_cycle_with_drop.rs:46:19
@@ -21,6 +23,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `d1` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 2 previous errors
 
index 0eeec8e51beaac36f63dae5510e3ae563bf6f4f2..0eb84e4a7d0b23394a4106bfcf2760787abc0b86 100644 (file)
@@ -8,6 +8,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_w` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `v` does not live long enough
   --> $DIR/dropck_misc_variants.rs:41:27
@@ -20,6 +22,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_w` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 2 previous errors
 
index 3f18f4d025a09d12ce4e770ce79589f0a999facf..ec1df8aeca15a312d1b6c4f9f6c90d7e014dd29a 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_d` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 79e607bb392c89d56d54463b33a1ae5c89fbb468..288c196b27b2df2413bf402aaa644ceacc0722f8 100644 (file)
@@ -8,6 +8,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_d` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `d1` does not live long enough
   --> $DIR/issue-24805-dropck-trait-has-items.rs:53:33
@@ -19,6 +21,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_d` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `d1` does not live long enough
   --> $DIR/issue-24805-dropck-trait-has-items.rs:59:20
@@ -30,6 +34,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `_d` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 3 previous errors
 
index 550f9d8b60de0684ab0686884182d847bea0a226..c89e68bcd0ae06f0ef10d18f705dbcb17b898133 100644 (file)
@@ -8,6 +8,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `d2` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 64bb83fc782191201927c45280609bb36fd34183..bea6dc6b3f6a06d4a46af3c71b755bb1eab14301 100644 (file)
@@ -8,6 +8,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `zook` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index c5e7a93c76349676accb54a978c1ce7ced7301ec..3ed13f2653ccd769a884f130c206acfe0de6fb32 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `foo` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 25708219bd1be88ddd1f213636c34c523fd74d32..ce9e75b44831874efa2cb710545b4d6490ffc134 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `foo1` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 661570963948dcd81cc0a143814c0b6bbe4fcbf8..fcdc1c3f9452de27eb491f269f1328bde8f90180 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `foo1` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index bb9d67983de7a60d3adfad8c0132990c9c695ad3..6300bb3eacd643821b1c92e8c773964651ac3bdc 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `foo1` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to previous error
 
index 8e1cb9720e2369ac971bc8bdb30f062e1d38a169..cd19059fdae32d5121e3621de64dc28c952d7ef9 100644 (file)
@@ -1,20 +1,26 @@
 error[E0596]: cannot borrow immutable item `*a` as mutable
   --> $DIR/mut-arg-hint.rs:13:9
    |
+LL |     fn foo(mut a: &String) {
+   |                   ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
 LL |         a.push_str("bar"); //~ ERROR cannot borrow immutable borrowed content
-   |         ^ cannot borrow as mutable
+   |         ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `*a` as mutable
   --> $DIR/mut-arg-hint.rs:18:5
    |
+LL | pub fn foo<'a>(mut a: &'a String) {
+   |                       ---------- help: consider changing this to be a mutable reference: `&mut std::string::String`
 LL |     a.push_str("foo"); //~ ERROR cannot borrow immutable borrowed content
-   |     ^ cannot borrow as mutable
+   |     ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `*a` as mutable
   --> $DIR/mut-arg-hint.rs:25:9
    |
+LL |     pub fn foo(mut a: &String) {
+   |                       ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
 LL |         a.push_str("foo"); //~ ERROR cannot borrow immutable borrowed content
-   |         ^ cannot borrow as mutable
+   |         ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to 3 previous errors
 
index d411f0d26f4fbd7afafb40c6c1b27b7a2cbab152..6ebbf3e1ec4d22017d985637808dbe699648179d 100644 (file)
@@ -63,6 +63,8 @@ LL |     }
 ...
 LL | }
    | - borrow later used here, when `tx` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 6 previous errors
 
index 6074199b89a1575cd95a062cc9f3f2abe37f0bcc..9d89fac08ffe2eb0a8c7c5596065e27897c34470 100644 (file)
@@ -9,6 +9,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `v` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error[E0597]: `x` does not live long enough
   --> $DIR/vec_refs_data_with_early_death.rs:27:12
@@ -21,6 +23,8 @@ LL | }
    | |
    | borrowed value only lives until here
    | borrow later used here, when `v` is dropped
+   |
+   = note: values in a scope are dropped in the opposite order they are defined
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/struct-duplicate-comma.rs b/src/test/ui/struct-duplicate-comma.rs
new file mode 100644 (file)
index 0000000..d7ee2f2
--- /dev/null
@@ -0,0 +1,27 @@
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: -Z parse-only
+
+// Issue #50974
+
+struct Foo {
+    a: u8,
+    b: u8
+}
+
+fn main() {
+    let bar = Foo {
+        a: 0,,
+          //~^ ERROR expected identifier
+        b: 42
+    };
+}
+
diff --git a/src/test/ui/struct-duplicate-comma.stderr b/src/test/ui/struct-duplicate-comma.stderr
new file mode 100644 (file)
index 0000000..06e3b95
--- /dev/null
@@ -0,0 +1,13 @@
+error: expected identifier, found `,`
+  --> $DIR/struct-duplicate-comma.rs:22:14
+   |
+LL |     let bar = Foo {
+   |               --- while parsing this struct
+LL |         a: 0,,
+   |              ^
+   |              |
+   |              expected identifier
+   |              help: remove this comma
+
+error: aborting due to previous error
+
index bc655114c2b471a764e8ce670620cacf369ffed3..335ccefe8a0b12096d3655d1343adf11f9232635 100644 (file)
@@ -2,7 +2,7 @@ error[E0594]: cannot assign to immutable item `y`
   --> $DIR/closure-immutable-outer-variable.rs:21:26
    |
 LL |     foo(Box::new(move || y = false) as Box<_>); //~ ERROR cannot assign to captured outer variable
-   |                          ^^^^^^^^^ cannot mutate
+   |                          ^^^^^^^^^ cannot assign
 
 error: aborting due to previous error
 
index ed691843f9b26b500d44e2f1c2242318e9db4074..7ef21d3720d8833ed9180789d0907889206f7f99 100644 (file)
@@ -1,8 +1,8 @@
-error[E0594]: cannot assign to immutable item `x`
+error[E0594]: cannot assign to `x` which is behind a `&` reference
   --> $DIR/fn-closure-mutable-capture.rs:15:17
    |
 LL |     bar(move || x = 1);
-   |                 ^^^^^ cannot mutate
+   |                 ^^^^^ cannot assign
 
 error: aborting due to previous error
 
index b70028bd926c6ea78c2fe27eb4f55c2cddd98c4f..8fbab4022327171feb87ce682c25b0f7d3154273 100644 (file)
@@ -15,7 +15,7 @@ fn main() {
   let u: &str = if true { s[..2] } else { s };
   //~^ ERROR mismatched types
   let v = s[..2];
-  //~^ ERROR the trait bound `str: std::marker::Sized` is not satisfied
+  //~^ ERROR the size for value values of type
   let w: &str = s[..2];
   //~^ ERROR mismatched types
 }
index 76db882742a01a331e9a0cfe01ab3294ff44d344..12699d8b25f81750393da26779a59a5d70d020e1 100644 (file)
@@ -19,15 +19,16 @@ LL |   let u: &str = if true { s[..2] } else { s };
    = note: expected type `&str`
               found type `str`
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/str-array-assignment.rs:17:7
    |
 LL |   let v = s[..2];
    |       ^   ------ help: consider borrowing here: `&s[..2]`
    |       |
-   |       `str` does not have a constant size known at compile-time
+   |       doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: all local variables must have a statically known size
 
 error[E0308]: mismatched types
index 5dcb4c8a220baf865e59ff4d6f70585d43d94e18..dd74f4f4797272400bc36dd0bd7f6dd9ccee42d0 100644 (file)
 fn check<T: Iterator, U: ?Sized>() {
     // suggest a where-clause, if needed
     mem::size_of::<U>();
-    //~^ ERROR `U: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     mem::size_of::<Misc<U>>();
-    //~^ ERROR `U: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     // ... even if T occurs as a type parameter
 
@@ -36,10 +36,10 @@ fn check<T: Iterator, U: ?Sized>() {
     // ... and also not if the error is not related to the type
 
     mem::size_of::<[T]>();
-    //~^ ERROR `[T]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 
     mem::size_of::<[&U]>();
-    //~^ ERROR `[&U]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {
index abd9f5a8b73f77a758d3539f481355bccaf1c83f..feb31ae22d8ca9b01fc81c982287d6b0c01ed4a9 100644 (file)
@@ -1,20 +1,22 @@
-error[E0277]: the trait bound `U: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `U` cannot be known at compilation time
   --> $DIR/trait-suggest-where-clause.rs:17:5
    |
 LL |     mem::size_of::<U>();
-   |     ^^^^^^^^^^^^^^^^^ `U` does not have a constant size known at compile-time
+   |     ^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `U`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where U: std::marker::Sized` bound
    = note: required by `std::mem::size_of`
 
-error[E0277]: the trait bound `U: std::marker::Sized` is not satisfied in `Misc<U>`
+error[E0277]: the size for value values of type `U` cannot be known at compilation time
   --> $DIR/trait-suggest-where-clause.rs:20:5
    |
 LL |     mem::size_of::<Misc<U>>();
-   |     ^^^^^^^^^^^^^^^^^^^^^^^ `U` does not have a constant size known at compile-time
+   |     ^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Misc<U>`, the trait `std::marker::Sized` is not implemented for `U`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where U: std::marker::Sized` bound
    = note: required because it appears within the type `Misc<U>`
    = note: required by `std::mem::size_of`
@@ -45,22 +47,24 @@ LL |     <Misc<_> as From<T>>::from;
    |
    = note: required by `std::convert::From::from`
 
-error[E0277]: the trait bound `[T]: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `[T]` cannot be known at compilation time
   --> $DIR/trait-suggest-where-clause.rs:38:5
    |
 LL |     mem::size_of::<[T]>();
-   |     ^^^^^^^^^^^^^^^^^^^ `[T]` does not have a constant size known at compile-time
+   |     ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[T]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required by `std::mem::size_of`
 
-error[E0277]: the trait bound `[&U]: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `[&U]` cannot be known at compilation time
   --> $DIR/trait-suggest-where-clause.rs:41:5
    |
 LL |     mem::size_of::<[&U]>();
-   |     ^^^^^^^^^^^^^^^^^^^^ `[&U]` does not have a constant size known at compile-time
+   |     ^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[&U]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required by `std::mem::size_of`
 
 error: aborting due to 7 previous errors
index 66547863db2fd2c8eecc7815c7e916872ef82996..1a36b0c4839b6b79a59d317c8518df502f9abe31 100644 (file)
@@ -1,18 +1,18 @@
 error[E0596]: cannot borrow immutable item `**t` as mutable
   --> $DIR/trivial-bounds-inconsistent-copy-reborrow.rs:16:5
    |
+LL | fn reborrow_mut<'a>(t: &'a &'a mut i32) -> &'a mut i32 where &'a mut i32: Copy {
+   |                        --------------- help: consider changing this to be a mutable reference: `&mut &mut i32`
 LL |     *t //~ ERROR
-   |     ^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*t`
+   |     ^^ `t` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error[E0596]: cannot borrow immutable item `**t` as mutable
   --> $DIR/trivial-bounds-inconsistent-copy-reborrow.rs:20:6
    |
+LL | fn copy_reborrow_mut<'a>(t: &'a &'a mut i32) -> &'a mut i32 where &'a mut i32: Copy {
+   |                             --------------- help: consider changing this to be a mutable reference: `&mut &mut i32`
 LL |     {*t} //~ ERROR
-   |      ^^ cannot borrow as mutable
-   |
-   = note: the value which is causing this path not to be mutable is...: `*t`
+   |      ^^ `t` is a `&` reference, so the data it refers to cannot be borrowed as mutable
 
 error: aborting due to 2 previous errors
 
index df91ba0dd2ac5b2b6513be46ab98f5a5b9909f3d..d08574c3d878967d533fd7c36f6a4b5f8e1547fb 100644 (file)
@@ -1,10 +1,11 @@
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
   --> $DIR/trivial-bounds-leak.rs:22:25
    |
 LL | fn cant_return_str() -> str { //~ ERROR
-   |                         ^^^ `str` does not have a constant size known at compile-time
+   |                         ^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: the return type of a function must have a statically known size
 
 error[E0599]: no method named `test` found for type `i32` in the current scope
index f916df5d32d0462826035a9e87aca7351c6ee88e..92a45db0689680e81b63a003e3200ae583f79eb5 100644 (file)
 
 struct Foo<T, U: FromIterator<T>>(T, U);
 struct WellFormed<Z = Foo<i32, i32>>(Z);
-//~^ error: the trait bound `i32: std::iter::FromIterator<i32>` is not satisfied [E0277]
+//~^ ERROR a collection of type `i32` cannot be built from an iterator over elements of type `i32`
 struct WellFormedNoBounds<Z:?Sized = Foo<i32, i32>>(Z);
-//~^ error: the trait bound `i32: std::iter::FromIterator<i32>` is not satisfied [E0277]
+//~^ ERROR a collection of type `i32` cannot be built from an iterator over elements of type `i32`
 
 struct Bounds<T:Copy=String>(T);
-//~^ error: the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
+//~^ ERROR the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
 
 struct WhereClause<T=String>(T) where T: Copy;
-//~^ error: the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
+//~^ ERROR the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
 
 trait TraitBound<T:Copy=String> {}
-//~^ error: the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
+//~^ ERROR the trait bound `std::string::String: std::marker::Copy` is not satisfied [E0277]
 
 trait Super<T: Copy> { }
 trait Base<T = String>: Super<T> { }
-//~^ error: the trait bound `T: std::marker::Copy` is not satisfied [E0277]
+//~^ ERROR the trait bound `T: std::marker::Copy` is not satisfied [E0277]
 
 trait ProjectionPred<T:Iterator = IntoIter<i32>> where T::Item : Add<u8> {}
-//~^ error:  cannot add `u8` to `i32` [E0277]
+//~^ ERROR cannot add `u8` to `i32` [E0277]
 
 fn main() { }
index a2d6e53df050236ac5be1dd64bb75f0486bef485..aa124110243a52cc6cdb67cedb742d45237a8843 100644 (file)
@@ -1,8 +1,8 @@
-error[E0277]: the trait bound `i32: std::iter::FromIterator<i32>` is not satisfied
+error[E0277]: a collection of type `i32` cannot be built from an iterator over elements of type `i32`
   --> $DIR/type-check-defaults.rs:16:19
    |
 LL | struct WellFormed<Z = Foo<i32, i32>>(Z);
-   |                   ^ a collection of type `i32` cannot be built from an iterator over elements of type `i32`
+   |                   ^ a collection of type `i32` cannot be built from `std::iter::Iterator<Item=i32>`
    |
    = help: the trait `std::iter::FromIterator<i32>` is not implemented for `i32`
 note: required by `Foo`
@@ -11,11 +11,11 @@ note: required by `Foo`
 LL | struct Foo<T, U: FromIterator<T>>(T, U);
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-error[E0277]: the trait bound `i32: std::iter::FromIterator<i32>` is not satisfied
+error[E0277]: a collection of type `i32` cannot be built from an iterator over elements of type `i32`
   --> $DIR/type-check-defaults.rs:18:27
    |
 LL | struct WellFormedNoBounds<Z:?Sized = Foo<i32, i32>>(Z);
-   |                           ^ a collection of type `i32` cannot be built from an iterator over elements of type `i32`
+   |                           ^ a collection of type `i32` cannot be built from `std::iter::Iterator<Item=i32>`
    |
    = help: the trait `std::iter::FromIterator<i32>` is not implemented for `i32`
 note: required by `Foo`
index 8999f1e0930bed3898474fda10a779ebf4704321..15822ae42998c5769acd0670067bdaba22396ed1 100644 (file)
 #![feature(untagged_unions)]
 
 union Foo<T: ?Sized> {
-    value: T, //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
+    value: T,
+    //~^ ERROR the size for value values of type
 }
 
 struct Foo2<T: ?Sized> {
-    value: T, //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
+    value: T,
+    //~^ ERROR the size for value values of type
     t: u32,
 }
 
 enum Foo3<T: ?Sized> {
-    Value(T), //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
+    Value(T),
+    //~^ ERROR the size for value values of type
 }
 
 fn main() {}
index ba80af6c7e037b7739310d06d14d04b020092b8d..c6b7cf4e078233c5bc6cdb86696ddc5856d01e97 100644 (file)
@@ -1,30 +1,33 @@
-error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `T` cannot be known at compilation time
   --> $DIR/union-sized-field.rs:14:5
    |
-LL |     value: T, //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
-   |     ^^^^^^^^ `T` does not have a constant size known at compile-time
+LL |     value: T,
+   |     ^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where T: std::marker::Sized` bound
    = note: no field of a union may have a dynamically sized type
 
-error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
-  --> $DIR/union-sized-field.rs:18:5
+error[E0277]: the size for value values of type `T` cannot be known at compilation time
+  --> $DIR/union-sized-field.rs:19:5
    |
-LL |     value: T, //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
-   |     ^^^^^^^^ `T` does not have a constant size known at compile-time
+LL |     value: T,
+   |     ^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where T: std::marker::Sized` bound
    = note: only the last field of a struct may have a dynamically sized type
 
-error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
-  --> $DIR/union-sized-field.rs:23:11
+error[E0277]: the size for value values of type `T` cannot be known at compilation time
+  --> $DIR/union-sized-field.rs:25:11
    |
-LL |     Value(T), //~ ERROR the trait bound `T: std::marker::Sized` is not satisfied
-   |           ^ `T` does not have a constant size known at compile-time
+LL |     Value(T),
+   |           ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `T`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where T: std::marker::Sized` bound
    = note: no field of an enum variant may have a dynamically sized type
 
index 95fc3243fbed34629eb516bc9f6799b4c32cef1b..9082ea4abddbdd669ad4a3c86539e84c83ee33fd 100644 (file)
@@ -30,37 +30,54 @@ trait PathHelper4 {}
 
 enum E<W: ?Sized, X: ?Sized, Y: ?Sized, Z: ?Sized> {
     // parameter
-    VA(W), //~ ERROR `W: std::marker::Sized` is not satisfied
-    VB{x: X}, //~ ERROR `X: std::marker::Sized` is not satisfied
-    VC(isize, Y), //~ ERROR `Y: std::marker::Sized` is not satisfied
-    VD{u: isize, x: Z}, //~ ERROR `Z: std::marker::Sized` is not satisfied
+    VA(W),
+    //~^ ERROR the size for value values of type
+    VB{x: X},
+    //~^ ERROR the size for value values of type
+    VC(isize, Y),
+    //~^ ERROR the size for value values of type
+    VD{u: isize, x: Z},
+    //~^ ERROR the size for value values of type
 
     // slice / str
-    VE([u8]), //~ ERROR `[u8]: std::marker::Sized` is not satisfied
-    VF{x: str}, //~ ERROR `str: std::marker::Sized` is not satisfied
-    VG(isize, [f32]), //~ ERROR `[f32]: std::marker::Sized` is not satisfied
-    VH{u: isize, x: [u32]}, //~ ERROR `[u32]: std::marker::Sized` is not satisfied
+    VE([u8]),
+    //~^ ERROR the size for value values of type
+    VF{x: str},
+    //~^ ERROR the size for value values of type
+    VG(isize, [f32]),
+    //~^ ERROR the size for value values of type
+    VH{u: isize, x: [u32]},
+    //~^ ERROR the size for value values of type
 
     // unsized struct
-    VI(Path1), //~ ERROR `PathHelper1 + 'static: std::marker::Sized` is not satisfied
-    VJ{x: Path2}, //~ ERROR `PathHelper2 + 'static: std::marker::Sized` is not satisfied
-    VK(isize, Path3), //~ ERROR `PathHelper3 + 'static: std::marker::Sized` is not satisfied
-    VL{u: isize, x: Path4}, //~ ERROR `PathHelper4 + 'static: std::marker::Sized` is not satisfied
+    VI(Path1),
+    //~^ ERROR the size for value values of type
+    VJ{x: Path2},
+    //~^ ERROR the size for value values of type
+    VK(isize, Path3),
+    //~^ ERROR the size for value values of type
+    VL{u: isize, x: Path4},
+    //~^ ERROR the size for value values of type
 
     // plain trait
-    VM(Foo),  //~ ERROR `Foo + 'static: std::marker::Sized` is not satisfied
-    VN{x: Bar}, //~ ERROR `Bar + 'static: std::marker::Sized` is not satisfied
-    VO(isize, FooBar), //~ ERROR `FooBar + 'static: std::marker::Sized` is not satisfied
-    VP{u: isize, x: BarFoo}, //~ ERROR `BarFoo + 'static: std::marker::Sized` is not satisfied
+    VM(Foo),
+    //~^ ERROR the size for value values of type
+    VN{x: Bar},
+    //~^ ERROR the size for value values of type
+    VO(isize, FooBar),
+    //~^ ERROR the size for value values of type
+    VP{u: isize, x: BarFoo},
+    //~^ ERROR the size for value values of type
 
     // projected
-    VQ(<&'static [i8] as Deref>::Target), //~ ERROR `[i8]: std::marker::Sized` is not satisfied
+    VQ(<&'static [i8] as Deref>::Target),
+    //~^ ERROR the size for value values of type
     VR{x: <&'static [char] as Deref>::Target},
-    //~^ ERROR `[char]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
     VS(isize, <&'static [f64] as Deref>::Target),
-    //~^ ERROR `[f64]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
     VT{u: isize, x: <&'static [i32] as Deref>::Target},
-    //~^ ERROR `[i32]: std::marker::Sized` is not satisfied
+    //~^ ERROR the size for value values of type
 }
 
 
index 0e18efbf9da3eda5b87c4e8d72e1e123bca283e8..ff2aa1d1ef91778321049ab8101d545a0732b494 100644 (file)
-error[E0277]: the trait bound `W: std::marker::Sized` is not satisfied
+error[E0277]: the size for value values of type `W` cannot be known at compilation time
   --> $DIR/unsized-enum2.rs:33:8
    |
-LL |     VA(W), //~ ERROR `W: std::marker::Sized` is not satisfied
-   |        ^ `W` does not have a constant size known at compile-time
+LL |     VA(W),
+   |        ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `W`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where W: std::marker::Sized` bound
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `X: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:34:8
+error[E0277]: the size for value values of type `X` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:35:8
    |
-LL |     VB{x: X}, //~ ERROR `X: std::marker::Sized` is not satisfied
-   |        ^^^^ `X` does not have a constant size known at compile-time
+LL |     VB{x: X},
+   |        ^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `X`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where X: std::marker::Sized` bound
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `Y: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:35:15
+error[E0277]: the size for value values of type `Y` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:37:15
    |
-LL |     VC(isize, Y), //~ ERROR `Y: std::marker::Sized` is not satisfied
-   |               ^ `Y` does not have a constant size known at compile-time
+LL |     VC(isize, Y),
+   |               ^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `Y`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where Y: std::marker::Sized` bound
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `Z: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:36:18
+error[E0277]: the size for value values of type `Z` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:39:18
    |
-LL |     VD{u: isize, x: Z}, //~ ERROR `Z: std::marker::Sized` is not satisfied
-   |                  ^^^^ `Z` does not have a constant size known at compile-time
+LL |     VD{u: isize, x: Z},
+   |                  ^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `Z`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = help: consider adding a `where Z: std::marker::Sized` bound
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:39:8
+error[E0277]: the size for value values of type `[u8]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:43:8
    |
-LL |     VE([u8]), //~ ERROR `[u8]: std::marker::Sized` is not satisfied
-   |        ^^^^ `[u8]` does not have a constant size known at compile-time
+LL |     VE([u8]),
+   |        ^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u8]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:40:8
+error[E0277]: the size for value values of type `str` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:45:8
    |
-LL |     VF{x: str}, //~ ERROR `str: std::marker::Sized` is not satisfied
-   |        ^^^^^^ `str` does not have a constant size known at compile-time
+LL |     VF{x: str},
+   |        ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `str`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[f32]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:41:15
+error[E0277]: the size for value values of type `[f32]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:47:15
    |
-LL |     VG(isize, [f32]), //~ ERROR `[f32]: std::marker::Sized` is not satisfied
-   |               ^^^^^ `[f32]` does not have a constant size known at compile-time
+LL |     VG(isize, [f32]),
+   |               ^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[f32]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[u32]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:42:18
+error[E0277]: the size for value values of type `[u32]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:49:18
    |
-LL |     VH{u: isize, x: [u32]}, //~ ERROR `[u32]: std::marker::Sized` is not satisfied
-   |                  ^^^^^^^^ `[u32]` does not have a constant size known at compile-time
+LL |     VH{u: isize, x: [u32]},
+   |                  ^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[u32]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `Foo + 'static: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:51:8
+error[E0277]: the size for value values of type `Foo + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:63:8
    |
-LL |     VM(Foo),  //~ ERROR `Foo + 'static: std::marker::Sized` is not satisfied
-   |        ^^^ `Foo + 'static` does not have a constant size known at compile-time
+LL |     VM(Foo),
+   |        ^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `Foo + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `Bar + 'static: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:52:8
+error[E0277]: the size for value values of type `Bar + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:65:8
    |
-LL |     VN{x: Bar}, //~ ERROR `Bar + 'static: std::marker::Sized` is not satisfied
-   |        ^^^^^^ `Bar + 'static` does not have a constant size known at compile-time
+LL |     VN{x: Bar},
+   |        ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `Bar + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `FooBar + 'static: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:53:15
+error[E0277]: the size for value values of type `FooBar + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:67:15
    |
-LL |     VO(isize, FooBar), //~ ERROR `FooBar + 'static: std::marker::Sized` is not satisfied
-   |               ^^^^^^ `FooBar + 'static` does not have a constant size known at compile-time
+LL |     VO(isize, FooBar),
+   |               ^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `FooBar + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `BarFoo + 'static: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:54:18
+error[E0277]: the size for value values of type `BarFoo + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:69:18
    |
-LL |     VP{u: isize, x: BarFoo}, //~ ERROR `BarFoo + 'static: std::marker::Sized` is not satisfied
-   |                  ^^^^^^^^^ `BarFoo + 'static` does not have a constant size known at compile-time
+LL |     VP{u: isize, x: BarFoo},
+   |                  ^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `BarFoo + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[i8]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:57:8
+error[E0277]: the size for value values of type `[i8]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:73:8
    |
-LL |     VQ(<&'static [i8] as Deref>::Target), //~ ERROR `[i8]: std::marker::Sized` is not satisfied
-   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `[i8]` does not have a constant size known at compile-time
+LL |     VQ(<&'static [i8] as Deref>::Target),
+   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[i8]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[char]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:58:8
+error[E0277]: the size for value values of type `[char]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:75:8
    |
 LL |     VR{x: <&'static [char] as Deref>::Target},
-   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `[char]` does not have a constant size known at compile-time
+   |        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[char]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[f64]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:60:15
+error[E0277]: the size for value values of type `[f64]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:77:15
    |
 LL |     VS(isize, <&'static [f64] as Deref>::Target),
-   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `[f64]` does not have a constant size known at compile-time
+   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[f64]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `[i32]: std::marker::Sized` is not satisfied
-  --> $DIR/unsized-enum2.rs:62:18
+error[E0277]: the size for value values of type `[i32]` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:79:18
    |
 LL |     VT{u: isize, x: <&'static [i32] as Deref>::Target},
-   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `[i32]` does not have a constant size known at compile-time
+   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: the trait `std::marker::Sized` is not implemented for `[i32]`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `PathHelper1 + 'static: std::marker::Sized` is not satisfied in `Path1`
-  --> $DIR/unsized-enum2.rs:45:8
+error[E0277]: the size for value values of type `PathHelper1 + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:53:8
    |
-LL |     VI(Path1), //~ ERROR `PathHelper1 + 'static: std::marker::Sized` is not satisfied
-   |        ^^^^^ `PathHelper1 + 'static` does not have a constant size known at compile-time
+LL |     VI(Path1),
+   |        ^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Path1`, the trait `std::marker::Sized` is not implemented for `PathHelper1 + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `Path1`
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `PathHelper2 + 'static: std::marker::Sized` is not satisfied in `Path2`
-  --> $DIR/unsized-enum2.rs:46:8
+error[E0277]: the size for value values of type `PathHelper2 + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:55:8
    |
-LL |     VJ{x: Path2}, //~ ERROR `PathHelper2 + 'static: std::marker::Sized` is not satisfied
-   |        ^^^^^^^^ `PathHelper2 + 'static` does not have a constant size known at compile-time
+LL |     VJ{x: Path2},
+   |        ^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Path2`, the trait `std::marker::Sized` is not implemented for `PathHelper2 + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `Path2`
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `PathHelper3 + 'static: std::marker::Sized` is not satisfied in `Path3`
-  --> $DIR/unsized-enum2.rs:47:15
+error[E0277]: the size for value values of type `PathHelper3 + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:57:15
    |
-LL |     VK(isize, Path3), //~ ERROR `PathHelper3 + 'static: std::marker::Sized` is not satisfied
-   |               ^^^^^ `PathHelper3 + 'static` does not have a constant size known at compile-time
+LL |     VK(isize, Path3),
+   |               ^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Path3`, the trait `std::marker::Sized` is not implemented for `PathHelper3 + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `Path3`
    = note: no field of an enum variant may have a dynamically sized type
 
-error[E0277]: the trait bound `PathHelper4 + 'static: std::marker::Sized` is not satisfied in `Path4`
-  --> $DIR/unsized-enum2.rs:48:18
+error[E0277]: the size for value values of type `PathHelper4 + 'static` cannot be known at compilation time
+  --> $DIR/unsized-enum2.rs:59:18
    |
-LL |     VL{u: isize, x: Path4}, //~ ERROR `PathHelper4 + 'static: std::marker::Sized` is not satisfied
-   |                  ^^^^^^^^ `PathHelper4 + 'static` does not have a constant size known at compile-time
+LL |     VL{u: isize, x: Path4},
+   |                  ^^^^^^^^ doesn't have a size known at compile-time
    |
    = help: within `Path4`, the trait `std::marker::Sized` is not implemented for `PathHelper4 + 'static`
+   = note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types--sized>
    = note: required because it appears within the type `Path4`
    = note: no field of an enum variant may have a dynamically sized type
 
index 91a44fdd424fb12ff34b2298ce7a8b1e12828293..db30e649a7e6b5b4f0ee8b6e73ea946549ba765b 100644 (file)
@@ -212,6 +212,7 @@ fn main() {
     let cargo_release = args.next().unwrap();
     let rls_release = args.next().unwrap();
     let rustfmt_release = args.next().unwrap();
+    let _llvm_tools_vers = args.next().unwrap(); // FIXME do something with it?
     let s3_address = args.next().unwrap();
     let mut passphrase = String::new();
     t!(io::stdin().read_to_string(&mut passphrase));
index cef548b0d94da6db7df5b568f2c87a7da262cf4f..6f03d09268b91ce0c8cc284c60b7f35901062064 100644 (file)
     Crate("scopeguard"),
     Crate("smallvec"),
     Crate("stable_deref_trait"),
-    Crate("tempdir"),
+    Crate("tempfile"),
     Crate("termcolor"),
     Crate("terminon"),
     Crate("termion"),