[`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
# 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
"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]]
"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]]
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]]
"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"
"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"
dist::Cargo,
dist::Rls,
dist::Rustfmt,
+ dist::LlvmTools,
dist::Extended,
dist::HashSign
),
pub llvm_link_jobs: Option<u32>,
pub lld_enabled: bool,
+ pub llvm_tools_enabled: bool,
// rust codegen options
pub rust_optimize: bool,
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>,
}
}
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);
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
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};
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())
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);
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));
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)))
+ }
+}
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
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.
///
// 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") {
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.
if !ptr.is_null() {
ptr
} else {
- oom(layout)
+ handle_alloc_error(layout)
}
}
}
///
/// 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"]
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);
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;
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>;
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;
};
match result {
Ok(ptr) => ptr.cast(),
- Err(_) => oom(layout),
+ Err(_) => handle_alloc_error(layout),
}
};
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 => {
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()),
}
}
};
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;
};
match (&res, fallibility) {
- (Err(AllocErr), Infallible) => oom(new_layout),
+ (Err(AllocErr), Infallible) => handle_alloc_error(new_layout),
_ => {}
}
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;
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>;
}
#[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]>,
}
#[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]>,
/// 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;
/// 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();
/// 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());
/// 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`.
/// 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,
/// 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);
/// 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))
/// 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,
/// 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.
/// 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.
/// 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
{
/// 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
{
/// 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,
#[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 `==`.
#[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.
///
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;
#[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]
}
}
+// 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 {}
/// 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.
///
/// [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.
}
/// [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.
/// 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 = "[")]
/// 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 = "]")]
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));
# 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"
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)
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)
}
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)
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 => {}
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))
}
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);
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,
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, ¶m.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, ¶m.bounds);
}
pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) {
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,
}
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);
}
}
//! 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;
use std::iter;
use std::mem;
use syntax::attr;
+use syntax::ast;
use syntax::ast::*;
use syntax::errors;
use syntax::ext::hygiene::{Mark, SyntaxContext};
// 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`
// (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
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);
}
});
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);
+ }
+ });
}
}
// 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)
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;
}
/// 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);
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);
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| {
}
}
+ fn lower_generic_arg(&mut self,
+ arg: &ast::GenericArg,
+ itctx: ImplTraitContext)
+ -> hir::GenericArg {
+ match arg {
+ ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)),
+ 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,
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,
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));
}
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(
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(
&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.
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);
}
}
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);
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 {
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,
- }));
+ }
+ });
}
}
}
};
for bound in bounds {
- hir::intravisit::walk_ty_param_bound(&mut lifetime_collector, &bound);
+ hir::intravisit::walk_param_bound(&mut lifetime_collector, &bound);
}
(
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(
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)
}
},
}
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
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,
})
}
- 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) {
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 => {
},
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))
}
}
}
}
}
- 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(¶m.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(¶m.attrs, "may_dangle"),
+ attrs: self.lower_attrs(¶m.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(¶m.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(¶m.attrs, "may_dangle"),
+ attrs: self.lower_attrs(¶m.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,
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;
+ }
}
+ _ => {}
}
}
}
}
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,
}
}
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(
.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,
)),
}) => 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,
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),
);
}
}
- 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> {
);
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()
)
}
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))
}
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"),
}
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)),
hir::Lifetime {
id: self.next_id().node_id,
span,
- name: fresh_name,
+ name: hir::LifetimeName::Param(fresh_name),
}
}
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),
}
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);
}
}
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);
}
/// A type parameter (generic parameter)
TypeParam(InternedString),
/// A lifetime definition
- LifetimeDef(InternedString),
+ LifetimeParam(InternedString),
/// A variant of a enum
EnumVariant(InternedString),
/// A struct field
Module(name) |
MacroDef(name) |
TypeParam(name) |
- LifetimeDef(name) |
+ LifetimeParam(name) |
EnumVariant(name) |
Field(name) |
GlobalMetaData(name) => Some(name),
Module(name) |
MacroDef(name) |
TypeParam(name) |
- LifetimeDef(name) |
+ LifetimeParam(name) |
EnumVariant(name) |
Field(name) |
GlobalMetaData(name) => {
NodeStructCtor(&'hir VariantData),
NodeLifetime(&'hir Lifetime),
- NodeTyParam(&'hir TyParam),
+ NodeGenericParam(&'hir GenericParam),
NodeVisibility(&'hir Visibility),
}
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),
EntryBlock(id, _, _) => id,
EntryStructCtor(id, _, _) => id,
EntryLifetime(id, _, _) => id,
- EntryTyParam(id, _, _) => id,
+ EntryGenericParam(id, _, _) => id,
EntryVisibility(id, _, _) => id,
EntryLocal(id, _, _) => id,
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),
})
}
+ 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) => {
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, _) |
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)),
+ })
}
}
}
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`.
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))
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)),
}
}
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))
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(¶m.attrs[..]),
// unit/tuple structs take the attributes straight from
// the struct definition.
Some(NodeStructCtor(_)) => {
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,
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 }
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"),
}
}
}
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)
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};
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
}
#[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:
/// 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 {
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 {
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.
/// 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
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 {
- ¶ms
+ let dummy = GenericArgs::none();
+ f(if let Some(ref args) = self.args {
+ &args
} else {
&dummy
})
}
#[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
}
}
- 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
}
}
/// 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`
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
- pub bounds: HirVec<Lifetime>,
+ pub bounds: GenericBounds,
}
/// An equality predicate (unsupported), e.g. `T=int`
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
#[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>,
}
/// 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,
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};
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")?;
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)?;
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)?;
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)?;
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(¶meters, 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)
}
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)
})?;
}
}
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)
})?;
}
}
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) => {
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(¶meters.bindings[0].ty)?;
+ self.print_type(&generic_args.bindings[0].ty)?;
} else {
let start = if colons_before_params { "::<" } else { "<" };
let empty = Cell::new(true);
}
};
- if !parameters.lifetimes.iter().all(|lt| lt.is_elided()) {
- for lifetime in ¶meters.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, ¶meters.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.:
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()?;
}
}
- 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;
}
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)?;
}
}
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(">")?;
Ok(())
}
- pub fn print_ty_param(&mut self, param: &hir::TyParam) -> io::Result<()> {
- self.print_name(param.name)?;
- self.print_bounds(":", ¶m.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 ¶m.bounds {
+ match bound {
+ GenericBound::Outlives(lt) => {
+ self.s.word(sep)?;
+ self.print_lifetime(lt)?;
+ sep = "+";
+ }
+ _ => bug!(),
+ }
+ }
+ Ok(())
+ }
+ GenericParamKind::Type { ref default, .. } => {
+ self.print_bounds(":", ¶m.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(());
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(":")?;
}
}
+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 {
name
});
-impl_stable_hash_for!(struct hir::LifetimeDef {
- lifetime,
- bounds,
- pure_wrt_drop,
- in_band
-});
-
impl_stable_hash_for!(struct hir::Path {
span,
def,
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 {
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,
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),
}
}
}
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),
}
}
}
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();
// 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()
} else {
sp
};
- (sp, has_lifetimes)
+ (sp, has_bounds)
})
} else {
None
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)));
/// 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
};
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)?;
};
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));
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)?;
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,
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")
}
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,
}
}
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 {
// 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
}
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);
}
}
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.
///
}
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"),
}
}
}
}
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 {
}
}
- 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)
}
/// 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?
} 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,
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,
// 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);
}
// 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);
"`impl Trait` can only capture lifetimes \
bound at the fn or impl level"
);
+ self.uninsert_lifetime_on_error(lifetime, def.unwrap());
}
}
}
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, <_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, ¶m);
+ 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 {
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);
}
});
});
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);
}
});
}
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,
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);
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,
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() {
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);
}
}
}
}
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, ¶m.bounds);
+ if let Some(ref ty) = default {
+ self.visit_ty(&ty);
+ }
+ }
}
}
for predicate in &generics.where_clause.predicates {
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,
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 {
..
}) => {
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,
|| 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!(
}
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,
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,
}
}
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();
}
}
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(¶m_name) {
let node_id = tcx.hir.as_local_node_id(def.id().unwrap()).unwrap();
signal_shadowing_problem(
.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(),
})
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, ¶m.bounds);
}
}
- 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> {
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) => {
}
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();
}
}
}
}
}
- 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(¶m.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,
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;
}
}
- 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(¶ms.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(¶ms.lifetimes, true);
- } else {
- for l in ¶ms.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,
}).collect()
})
};
- unsubst
- .iter()
- .map(|set| match *set {
- Set1::Empty => if in_body {
- None
- } else {
- Some(Region::Static)
- },
- Set1::One(r) => r.subst(¶ms.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(<) = 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(<) = 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 ¶ms.bindings {
+ for b in &generic_args.bindings {
self.visit_assoc_type_binding(b);
}
}
}
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;
}
}
- 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;
}
}
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(¶m),
);
return;
}
Scope::Binder {
ref lifetimes, s, ..
} => {
- if let Some(&def) = lifetimes.get(&lifetime.name) {
+ if let Some(&def) = lifetimes.get(¶m.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(¶m),
);
return;
}
}
}
}
+
+ /// 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));
+ }
}
///////////////////////////////////////////////////////////////////////////
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 { .. } => {}
}
}
// - 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(<_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(<_name)
+ && appears_in_output.regions.contains(<_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;
//! [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>>;
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,
upvar_decls,
spread_arg: None,
span,
- cache: cache::Cache::new()
+ cache: cache::Cache::new(),
}
}
}
#[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>,
) {
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 {
} 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
}
/// 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)
/// 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
/// 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 {
/// 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
}
}
+ /// 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
/// 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> {
}
}
-#[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> {}
/// The source scope, keeping track of which bindings can be
/// seen by debuginfo, active lint levels, `unsafe {...}`, etc.
- pub scope: SourceScope
+ pub scope: SourceScope,
}
///////////////////////////////////////////////////////////////////////////
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.
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,
}
}
}
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
/// 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
///
}
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 {
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,
}
}
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,
}
}
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,
}
}
}
#[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`
Drop {
location: Place<'tcx>,
target: BasicBlock,
- unwind: Option<BasicBlock>
+ unwind: Option<BasicBlock>,
},
/// Drop the Place and assign the new value over it. This ensures
/// 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,
expected: bool,
msg: AssertMessage<'tcx>,
target: BasicBlock,
- cleanup: Option<BasicBlock>
+ cleanup: Option<BasicBlock>,
},
/// A suspend point
}
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,
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),
}
}
}
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();
}
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![];
// 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 {
}
write!(fmt, "]")
}
-
}
}
}
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"),
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)?;
}
}
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"),
}
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()],
}
}
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),
}
}
}
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),
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
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"),
}
}
}
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 }))
}
}
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)
+ }
+ },
}
}
}
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()),
}
}
}
use self::BinOp::*;
match self {
Add | Sub | Mul | Shl | Shr => true,
- _ => false
+ _ => false,
}
}
}
// 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
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];
}
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]);
}
});
newtype_index!(Promoted { DEBUG_FORMAT = "promoted[{}]" });
-
#[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum Literal<'tcx> {
Value {
},
Promoted {
// Index into the `promoted` vector of `Mir`.
- index: Promoted
+ index: Promoted,
},
}
write!(fmt, "const ")?;
fmt_const_val(fmt, value)
}
- Promoted { index } => {
- write!(fmt, "{:?}", index)
- }
+ Promoted { index } => write!(fmt, "{:?}", index),
}
}
}
} else {
write!(fmt, "{:?}:{}", val, const_val.ty)
}
- },
+ }
}
}
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),
}
}
}
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()
}
}
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>>;
}
/// 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 {
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),
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),
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,
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)
} else {
false
}
- },
- Goto { .. } |
- Resume |
- Abort |
- Return |
- GeneratorDrop |
- Unreachable |
- FalseEdges { .. } |
- FalseUnwind { .. } => false
+ }
+ Goto { .. }
+ | Resume
+ | Abort
+ | Return
+ | GeneratorDrop
+ | Unreachable
+ | FalseEdges { .. }
+ | FalseUnwind { .. } => false,
}
}
}
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(),
}
}
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)),
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))
}
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),
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::*;
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,
+ }
}
}
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 {
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,
}
}
}
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();
pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
/// The following types:
-/// * `WhereClauseAtom`
+/// * `WhereClause`
+/// * `WellFormed`
+/// * `FromEnv`
/// * `DomainGoal`
/// * `Goal`
/// * `Clause`
/// 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>>;
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)]
} 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),
}
}
}
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),
}
}
}
}
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),
}
}
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),
}
}
BindByValue(Mutability),
}
+CloneTypeFoldableAndLiftImpls! { BindingMode, }
+
impl BindingMode {
pub fn convert(ba: BindingAnnotation) -> BindingMode {
match ba {
data @ DefPathData::ValueNs(..) |
data @ DefPathData::Module(..) |
data @ DefPathData::TypeParam(..) |
- data @ DefPathData::LifetimeDef(..) |
+ data @ DefPathData::LifetimeParam(..) |
data @ DefPathData::EnumVariant(..) |
data @ DefPathData::Field(..) |
data @ DefPathData::AnonConst |
DefPathData::MacroDef(_) |
DefPathData::ClosureExpr |
DefPathData::TypeParam(_) |
- DefPathData::LifetimeDef(_) |
+ DefPathData::LifetimeParam(_) |
DefPathData::Field(_) |
DefPathData::StructCtor |
DefPathData::AnonConst |
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 = {
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
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(
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;
// 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)),
};
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)),
};
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;
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,
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)]
}
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);
+ }
}
}
}
}
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 { .. } => {}
}
}
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};
}
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;
+ }
+ }
}
}
}
}
// 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,
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);
+ }
}
}
}
},
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));
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 {
}
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) {
// 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> {
.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
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),
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();
}
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();
}
"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,
"",
"",
None,
Origin::Mir,
- )
- }
+ ),
- (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
- tcx.cannot_mutably_borrow_multiply(
+ (BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => tcx
+ .cannot_mutably_borrow_multiply(
span,
&desc_place,
"",
"",
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,
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,
"",
"",
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,
"",
"",
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!(
);
}
- 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();
}
&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();
_ => drop_span,
};
- if self.access_place_error_reported
+ if self
+ .access_place_error_reported
.contains(&(root_place.clone(), borrow_span))
{
debug!(
drop_span,
borrow_span,
proper_span,
+ kind.map(|k| (k, place_span.0)),
);
}
(RegionKind::ReEarlyBound(_), None)
| (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
+ );
}
}
}
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();
}
"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();
}
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(\
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();
}
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();
}
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) {
"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(),
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();
}
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)
}
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};
crate mod place_ext;
mod prefixes;
mod path_utils;
+mod used_muts;
pub(crate) mod nll;
// 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);
this.report_borrowed_value_does_not_live_long_enough(
context,
borrow,
- place_span.1,
+ place_span,
+ Some(kind),
);
}
WriteKind::Mutate => {
self.report_borrowed_value_does_not_live_long_enough(
context,
borrow,
- span,
+ (place, span),
+ None,
)
}
}
) {
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
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;
}
}
}
}
- 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.
"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 { .. }))
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)
),
);
}
+ 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
// 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};
/// 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;
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) {
..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,
+ }
+ }));
}
}
}
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>(
/// 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);
--- /dev/null
+// 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);
+ }
+ }
+ }
+ }
+}
}
}
- 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);
})
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));
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,
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
}
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);
}
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(),
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() {
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 {
// 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,
};
.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);
///////////////////////////////////////////////////////////////////////////
/// 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,
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();
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 {
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);
// 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));
}
_ => {
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);
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;
);
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),
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);
source_info,
visibility_scope: source_info.scope,
internal: false,
- is_user_variable: false
+ is_user_variable: None,
}
}
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);
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);
source_info,
visibility_scope: source_info.scope,
internal: false,
- is_user_variable: false,
+ is_user_variable: None,
};
no_landing_pads(tcx, &mut mir);
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,
+ }
}
}
}
- 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 {
}
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");
}
}
}
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");
}
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");
}
}
// }
// 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");
});
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();
}
}
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");
+ }
}
}
}
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");
});
}
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 (¶m.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);
}
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 ¶ms.types {
- self.visit_ty(type_);
- }
- for type_binding in ¶ms.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 ¶ms.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_));
//
// 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
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) {
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) {
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};
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);
}
}
for bound in bounds.iter() {
- self.check_ty_param_bound(bound)
+ self.check_generic_bound(bound)
}
}
}
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 ¶m.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(_) => {}
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};
// 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 ¶m.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);
+ }
}
}
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);
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);
});
});
}
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();
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);
}
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");
});
}
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![],
+ },
+ );
+ }
}
}
}
&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();
// 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;
}
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);
}
}
// 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),
+ _ => {}
+ });
}
}
}
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 ¶m.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) {
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;
}
}
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("> ");
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> {
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,
})
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(¶m.bounds));
// FIXME descend properly into bounds.
}
- text.push_str(&t_text);
- text.push(',');
}
}
+ text.push_str(¶m_text);
+ text.push(',');
}
text.push('>');
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 {
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};
_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)
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!(),
}
}
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;
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;
}
}
}
-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())
}
}
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!()
}
}
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,
}
}
}
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(),
}
}
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
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> {
// }
// ```
- 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();
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,
//
// ```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)),
),
//! 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;
{
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)
});
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>>)
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 {
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()
}
let i = i - (lt_accepted + own_self);
if i < ty_provided {
// A provided type parameter.
- self.ast_ty_to_ty(¶meters.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) {
}
});
- 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),
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,
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,
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. \
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))
})
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.
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
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 ¶meters.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 ¶meters.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 ¶meters.bindings {
+ for binding in &generic_args.bindings {
self.prohibit_projection(binding.span);
break;
}
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);
// 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,
}
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,
// 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;
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 {
}
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(¶m.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()
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;
"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);
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))
}
})
}
use self::TupleArgumentsFlag::*;
use astconv::AstConv;
+use hir::GenericArg;
use hir::def::Def;
use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use std::slice;
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);
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.
// 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, ..) => {
// 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))) => {
}
(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(|| {
}
}
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;
}
/// 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) =
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 {
((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);
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();
}
}
-> 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 {
}
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();
}
}
}
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);
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());
}
}
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,
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,
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) => {
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};
}
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);
-> 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(¶m.bounds),
+ _ => None
+ })
+ .flat_map(|bounds| bounds.iter())
.flat_map(|b| predicates_from_bound(self, ty, b));
let from_where_clauses =
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);
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,
}
}));
// 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
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(..) |
}
},
- 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 => {
// 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();
// 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 {
/// `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>,
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 ¶m.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, <, 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,
- ¶m.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, ¶m.bounds, sized, param.span);
+ predicates.extend(bounds.predicates(tcx, param_ty));
+ }
+ _ => {}
+ }
}
// Add in the bounds that appear in the where-clause
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 =
}
}
- &hir::TyParamBound::RegionTyParamBound(ref lifetime) => {
+ &hir::GenericBound::Outlives(ref lifetime) => {
let region = AstConv::ast_region_to_region(&icx,
lifetime,
None);
&hir::WherePredicate::RegionPredicate(ref region_pred) => {
let r1 = AstConv::ast_region_to_region(&icx, ®ion_pred.lifetime, None);
for bound in ®ion_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))
}
/// 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>
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| {
}
}
-/// 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,
.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![],
}
}
"##,
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
}
```
"##,
#![feature(crate_visibility_modifier)]
#![feature(from_ref)]
#![feature(exhaustive_patterns)]
+#![feature(iterator_find_map)]
#![feature(quote)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
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();
[dependencies]
pulldown-cmark = { version = "0.1.2", default-features = false }
-tempdir = "0.3"
minifier = "0.0.11"
+tempfile = "3"
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,
}
.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() {
// 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),
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()
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)
}
};
);
}
- 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 {
}
_ => panic!("Unexpected data: {:?}, {:?}", ty, data),
};
- bounds.insert(TyParamBound::TraitBound(
+ bounds.insert(GenericBound::TraitBound(
PolyTrait {
trait_: new_ty,
generic_params: poly_trait.generic_params,
.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,
// 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());
// 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,
..
} => {
ty: rhs,
});
}
- &mut PathParameters::Parenthesized { .. } => {
+ &mut GenericArgs::Parenthesized { .. } => {
existing_predicates.push(
WherePredicate::EqPredicate {
lhs: lhs.clone(),
.entry(*ty.clone())
.or_insert_with(|| FxHashSet());
- bounds.insert(TyParamBound::TraitBound(
+ bounds.insert(GenericBound::TraitBound(
PolyTrait {
trait_: Type::ResolvedPath {
path: new_trait_path,
// 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(),
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 => {}
}
}
// 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.
// 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
// 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.
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() {
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 {
} 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,
/// 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 {
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;
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),
}
#[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,
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;
}
}
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
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<_>>();
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,
// 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,
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(),
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,
+ });
}
}
}
}
}
- TraitBound(
+ GenericBound::TraitBound(
PolyTrait {
trait_: ResolvedPath {
path,
}
}
-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)));
}
}
-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!(),
}
}
}
#[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 },
}
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())]
}
}
}
WherePredicate::BoundPredicate {
ty: ty.clean(cx),
- bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
+ bounds: vec![GenericBound::Outlives(lt.clean(cx).unwrap())]
}
}
}
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),
}
#[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,
}
}
}
// 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<_>>();
}
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 ¶m.name == name {
+ mem::swap(bounds, ty_bounds);
+ break
+ }
}
}
}
_ => continue,
}
}
- g
+ 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);
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)],
})
}
}
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),
}
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,
}
// 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() {
/// 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,
Infer,
// impl TraitA+TraitB
- ImplTrait(Vec<TyParamBound>),
+ ImplTrait(Vec<GenericBound>),
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
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
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));
}
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
}
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,
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;
}
}
-
let bounds = bounds.predicates.iter().filter_map(|pred|
if let ty::Predicate::Projection(proj) = *pred {
let proj = proj.skip_binder();
}).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)
}
def: Def::Err,
segments: vec![PathSegment {
name,
- params: PathParameters::AngleBracketed {
+ args: GenericArgs::AngleBracketed {
lifetimes: Vec::new(),
types: Vec::new(),
bindings: Vec::new(),
}
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
-pub enum PathParameters {
+pub enum GenericArgs {
AngleBracketed {
lifetimes: Vec<Lifetime>,
types: Vec<Type>,
}
}
-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),
}
}
#[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))
}
}
}
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(),
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())
}
#[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 {
}
}
-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
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;
};
!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),
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(),
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
}
/// 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>>,
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,
#[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);
}
}
-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(" + ")?;
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, ": {}", TyParamBounds(&tp.bounds))?;
+ write!(f, ": {}", GenericBounds(bounds))?;
}
}
- if let Some(ref ty) = tp.default {
+ if let Some(ref ty) = default {
if f.alternate() {
write!(f, " = {:#}", ty)?;
} else {
&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,
}
}
-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 => "?",
}
}
-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() {
}
}
}
- 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 {
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)
}
}
}
}
}
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) {
} else {
format!("{}", HRef::new(did, &last.name))
};
- write!(w, "{}{}", path, last.params)?;
+ write!(w, "{}{}", path, last.args)?;
}
Ok(())
}
/// 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 {
}
}
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_ {
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!(),
}
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;
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(_) => {}
}
}
}
}
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)?;
#![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)]
#[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
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;
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();
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()));
}
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) }
};
// 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};
// 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,
})?;
//! ```
//!
//! 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
///
/// [`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.
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)
}
// 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;
}
}
-/// 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,
/// `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,
}
}
+#[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,
/// 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
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 {
/// 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.
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
- pub bounds: Vec<Lifetime>,
+ pub bounds: GenericBounds,
}
/// An equality predicate (unsupported).
}
}
- 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,
}
}
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),
}
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
/// 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> { .. }`
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
}
}
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_
}
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
}
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>,
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);
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;
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() {
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.
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,
self.path_all(DUMMY_SP,
true,
self.std_path(&["option", "Option"]),
- Vec::new(),
- vec![ ty ],
+ vec![ast::GenericArg::Type(ty)],
Vec::new()))
}
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,
+ }
}
}
}
}
- 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 {
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,
}
}
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");
}
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");
}
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)
}
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)
}
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)
}
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 {
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))
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)
}
(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> {
})
}
-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)),
}
}
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)
})
}
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,
}
}
-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> {
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))
// 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};
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};
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 {
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
}
/// 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)
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)
}
}
/// 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
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()?;
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)?
}
} 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) &&
!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
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))
}
}
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,
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(
-> 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
.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(); // `(`
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)
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}),
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;
+ }
}
}
}
_ => {
// 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");
}
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])?;
}
}
_ => {}
// 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`.
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,
} else {
TraitBoundModifier::None
};
- bounds.push(TraitTyParamBound(poly_trait, modifier));
+ bounds.push(GenericBound::Trait(poly_trait, modifier));
}
} else {
break
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
}
/// 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()
};
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()
};
};
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
} 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.
/// 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");
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
break
}
}
- Ok((lifetimes, types, bindings))
+ Ok((args, bindings))
}
/// Parses an optional `where` clause and places it in `generics`.
// 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),
// 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 {
`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
}
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)
}
}
})
}
- 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),
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};
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 {
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 {
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)?;
}
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("[")?;
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()?;
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()?;
}
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)?;
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()?;
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)?;
}
}
self.nbsp()?;
- self.print_bounds("=", &real_bounds[..])?;
+ self.print_type_bounds("=", &real_bounds[..])?;
self.print_where_clause(&generics.where_clause)?;
self.s.word(";")?;
}
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)
}
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())?;
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 {
self.s.word(">")?
}
- ast::PathParameters::Parenthesized(ref data) => {
+ ast::GenericArgs::Parenthesized(ref data) => {
self.s.word("(")?;
self.commasep(
Inconsistent,
}
}
- 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)?;
}
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() {
if i != 0 {
self.s.word(" + ")?;
}
- self.print_lifetime(bound)?;
+ match bound {
+ ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt)?,
+ _ => panic!(),
+ }
}
}
Ok(())
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(¶m.attrs)?;
+ let lt = ast::Lifetime { id: param.id, ident: param.ident };
+ s.print_lifetime_bounds(lt, ¶m.bounds)
},
- ast::GenericParam::Type(ref ty_param) => s.print_ty_param(ty_param),
+ ast::GenericParamKind::Type { ref default } => {
+ s.print_outer_attributes_inline(¶m.attrs)?;
+ s.print_ident(param.ident)?;
+ s.print_type_bounds(":", ¶m.bounds)?;
+ match default {
+ Some(ref default) => {
+ s.s.space()?;
+ s.word_space("=")?;
+ s.print_type(default)
+ }
+ _ => Ok(())
+ }
+ }
}
})?;
Ok(())
}
- pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
- self.print_outer_attributes_inline(¶m.attrs)?;
- self.print_ident(param.ident)?;
- self.print_bounds(":", ¶m.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() {
}) => {
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,
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
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;
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;
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)
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)
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)
}
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),
}
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)
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);
}
// 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, ¶m.bounds);
+ match param.kind {
+ GenericParamKind::Lifetime => {}
+ GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default),
}
}
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,
&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) => {
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;
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;
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) {
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;
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) {
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;
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
.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 ¶m.bounds {
+ bounds.push((*declared_bound).clone());
}
+
+ cx.typaram(self.span, param.ident, vec![], bounds, None)
}
}));
// 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();
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,
// 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,
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};
-> 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())
}
}
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`"),
}
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 {
.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();
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(¶m.ident.as_str());
+ }
+ _ => {}
}
}
}
// 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;
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,
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);
}
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() {
// 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 {
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
}
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);
}
};
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);
}
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]
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() { }
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() { }
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() { }
}
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 };
}
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
+
}
//~| 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
}
//~| 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
}
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
}
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
}
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() { }
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() { }
//~^ 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]
}
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
}
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
}
{
for
&mut something
-//~^ ERROR `[T]: std::marker::Sized` is not satisfied
+ //~^ ERROR the size for value values of type
in arg2
{
}
fn main() {
(|| Box::new(*(&[0][..])))();
- //~^ ERROR `[{integer}]: std::marker::Sized` is not satisfied
+ //~^ ERROR the size for value values of type
}
fn _create_render(_: &()) ->
AbstractRenderer
-//~^ ERROR: `AbstractRenderer + 'static: std::marker::Sized` is not satisfied
+//~^ ERROR the size for value values of type
{
match 0 {
_ => unimplemented!()
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() {}
// 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>() { }
}
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)
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
}
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() {}
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
}
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] {
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() {}
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
};
}
#[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() {}
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
}
}
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() {}
// 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() { }
// 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() {}
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() { }
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
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
}
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
}
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 }
}
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
}
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>() {
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
}
}
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() {
// 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() { }
}
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
// 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() { }
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() {
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`
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
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`
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`
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);
});
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
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}
// 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
}
#[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() {}
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}`
}
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() {}
//[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
}
// 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() { }
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() {
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() {
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() {
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() {
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() {
// 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
}
fn main() {
is_send::<MySendable>();
is_send::<MyNotSendable>();
- //~^ ERROR `MyNotSendable: std::marker::Send` is not satisfied
+ //~^ ERROR `MyNotSendable` cannot be sent between threads safely
}
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`
});
}
#![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() {}
// 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() { }
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.
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() { }
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.
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() { }
}
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() { }
// 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) {
}
}
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) {
}
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() {
// 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() {
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() {
}
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() { }
#![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);
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>);
#![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() {
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);
}
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={:?}) = {:?}",
#![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(());
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 _)
}
}
--- /dev/null
+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`.
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
--> $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
--> $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
--- /dev/null
+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`.
--- /dev/null
+// 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);
+}
--- /dev/null
+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`.
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
--- /dev/null
+// 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() { }
--- /dev/null
+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
+
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
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
-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`.
--> $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
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);
-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
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
--> $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
--> $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
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
--> $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
--> $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
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
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
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
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
| |
| 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
| |
| 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
| |
| 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
--> $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
-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
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
}
-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>();
}
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);
-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
-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);
| |
| 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
-> 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;
-> Box<for<'a> Id<impl Lt<'a>>>
//~^ ERROR `impl Trait` can only capture lifetimes bound at the fn or impl level
{
- ()
+ () //~ ERROR mismatched types
}
}
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`.
= 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
| |
| 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
| |
| 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
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
}
-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
//~^ 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))
}
| ^^^^^^^^^^^^^^^^^^^^^^^^^
= 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());
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,
-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());
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());
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()
| ^^^^^^^^^^
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
| ^^^^^^^^^^
|
= 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`.
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
}
-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>`
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
// 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]
-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
--> $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
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
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
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]
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]
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`
...
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
...
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}, _>`
}
|
= 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}`
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
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
|
= 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
--- /dev/null
+// 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;
--- /dev/null
+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
+
-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);
--- /dev/null
+// 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() {}
--- /dev/null
+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`.
--- /dev/null
+// 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`
--- /dev/null
+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
+
-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
-error: incorrect visibility restriction
+error[E0704]: incorrect visibility restriction
--> $DIR/pub-restricted.rs:15:6
|
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
`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
`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
error: aborting due to 5 previous errors
+For more information about this error, try `rustc --explain E0704`.
--- /dev/null
+// 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]
+}
--- /dev/null
+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`.
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() {}
-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
-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
-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
--> $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
--> $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
--> $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
--> $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
+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
|
| ^ 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
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.
--> $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
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
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
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
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
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
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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
| |
| 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
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
...
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
| |
| 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
| |
| 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
--- /dev/null
+// 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
+ };
+}
+
--- /dev/null
+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
+
--> $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
-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
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
}
= 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
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
// ... 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() {
-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`
|
= 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
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
-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
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() { }
-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`
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`
#![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() {}
-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
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
}
-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
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));
Crate("scopeguard"),
Crate("smallvec"),
Crate("stable_deref_trait"),
- Crate("tempdir"),
+ Crate("tempfile"),
Crate("termcolor"),
Crate("terminon"),
Crate("termion"),