try:
float(value)
return True
- except:
+ except ValueError:
return False
# Here we walk through the constructed configuration we have from the parsed
sample usage: src/etc/generate-deriving-span-tests.py
"""
-import sys, os, datetime, stat, re
+import os, datetime, stat, re
TEST_DIR = os.path.abspath(
- os.path.join(os.path.dirname(__file__), '../test/compile-fail'))
+ os.path.join(os.path.dirname(__file__), '../test/ui/derives/'))
YEAR = datetime.datetime.now().year
const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
const MINIMUM_CAPACITY: usize = 1; // 2 - 1
+#[cfg(target_pointer_width = "16")]
+const MAXIMUM_ZST_CAPACITY: usize = 1 << (16 - 1); // Largest possible power of two
#[cfg(target_pointer_width = "32")]
const MAXIMUM_ZST_CAPACITY: usize = 1 << (32 - 1); // Largest possible power of two
#[cfg(target_pointer_width = "64")]
/// sentinel value. Types that lazily allocate must track initialization by
/// some other means.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub fn dangling() -> Self {
unsafe {
let ptr = mem::align_of::<T>() as *mut T;
///
/// `ptr` must be non-null.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
NonNull { pointer: NonZero(ptr as _) }
}
/// Creates a new `NonNull` if `ptr` is non-null.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub fn new(ptr: *mut T) -> Option<Self> {
if !ptr.is_null() {
Some(NonNull { pointer: NonZero(ptr as _) })
/// Acquires the underlying `*mut` pointer.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub fn as_ptr(self) -> *mut T {
self.pointer.0 as *mut T
}
/// it were actually an instance of T that is getting borrowed. If a longer
/// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub unsafe fn as_ref(&self) -> &T {
&*self.as_ptr()
}
/// it were actually an instance of T that is getting borrowed. If a longer
/// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`.
#[stable(feature = "nonnull", since = "1.25.0")]
+ #[inline]
pub unsafe fn as_mut(&mut self) -> &mut T {
&mut *self.as_ptr()
}
/// Cast to a pointer of another type
#[stable(feature = "nonnull_cast", since = "1.27.0")]
+ #[inline]
pub fn cast<U>(self) -> NonNull<U> {
unsafe {
NonNull::new_unchecked(self.as_ptr() as *mut U)
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> PartialEq for NonNull<T> {
+ #[inline]
fn eq(&self, other: &Self) -> bool {
self.as_ptr() == other.as_ptr()
}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> Ord for NonNull<T> {
+ #[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.as_ptr().cmp(&other.as_ptr())
}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> PartialOrd for NonNull<T> {
+ #[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.as_ptr().partial_cmp(&other.as_ptr())
}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> hash::Hash for NonNull<T> {
+ #[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.as_ptr().hash(state)
}
#[unstable(feature = "ptr_internals", issue = "0")]
impl<T: ?Sized> From<Unique<T>> for NonNull<T> {
+ #[inline]
fn from(unique: Unique<T>) -> Self {
NonNull { pointer: unique.pointer }
}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<'a, T: ?Sized> From<&'a mut T> for NonNull<T> {
+ #[inline]
fn from(reference: &'a mut T) -> Self {
NonNull { pointer: NonZero(reference as _) }
}
#[stable(feature = "nonnull", since = "1.25.0")]
impl<'a, T: ?Sized> From<&'a T> for NonNull<T> {
+ #[inline]
fn from(reference: &'a T) -> Self {
NonNull { pointer: NonZero(reference as _) }
}
+++ /dev/null
-// Copyright 2016 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_data_structures::sync::Lrc;
-use syntax::source_map::SourceMap;
-use syntax_pos::{BytePos, SourceFile};
-
-#[derive(Clone)]
-struct CacheEntry {
- time_stamp: usize,
- line_number: usize,
- line_start: BytePos,
- line_end: BytePos,
- file: Lrc<SourceFile>,
- file_index: usize,
-}
-
-#[derive(Clone)]
-pub struct CachingSourceMapView<'cm> {
- source_map: &'cm SourceMap,
- line_cache: [CacheEntry; 3],
- time_stamp: usize,
-}
-
-impl<'cm> CachingSourceMapView<'cm> {
- pub fn new(source_map: &'cm SourceMap) -> CachingSourceMapView<'cm> {
- let files = source_map.files();
- let first_file = files[0].clone();
- let entry = CacheEntry {
- time_stamp: 0,
- line_number: 0,
- line_start: BytePos(0),
- line_end: BytePos(0),
- file: first_file,
- file_index: 0,
- };
-
- CachingSourceMapView {
- source_map,
- line_cache: [entry.clone(), entry.clone(), entry],
- time_stamp: 0,
- }
- }
-
- pub fn byte_pos_to_line_and_col(&mut self,
- pos: BytePos)
- -> Option<(Lrc<SourceFile>, usize, BytePos)> {
- self.time_stamp += 1;
-
- // Check if the position is in one of the cached lines
- for cache_entry in self.line_cache.iter_mut() {
- if pos >= cache_entry.line_start && pos < cache_entry.line_end {
- cache_entry.time_stamp = self.time_stamp;
-
- return Some((cache_entry.file.clone(),
- cache_entry.line_number,
- pos - cache_entry.line_start));
- }
- }
-
- // No cache hit ...
- let mut oldest = 0;
- for index in 1 .. self.line_cache.len() {
- if self.line_cache[index].time_stamp < self.line_cache[oldest].time_stamp {
- oldest = index;
- }
- }
-
- let cache_entry = &mut self.line_cache[oldest];
-
- // If the entry doesn't point to the correct file, fix it up
- if pos < cache_entry.file.start_pos || pos >= cache_entry.file.end_pos {
- let file_valid;
- if self.source_map.files().len() > 0 {
- let file_index = self.source_map.lookup_source_file_idx(pos);
- let file = self.source_map.files()[file_index].clone();
-
- if pos >= file.start_pos && pos < file.end_pos {
- cache_entry.file = file;
- cache_entry.file_index = file_index;
- file_valid = true;
- } else {
- file_valid = false;
- }
- } else {
- file_valid = false;
- }
-
- if !file_valid {
- return None;
- }
- }
-
- let line_index = cache_entry.file.lookup_line(pos).unwrap();
- let line_bounds = cache_entry.file.line_bounds(line_index);
-
- cache_entry.line_number = line_index + 1;
- cache_entry.line_start = line_bounds.0;
- cache_entry.line_end = line_bounds.1;
- cache_entry.time_stamp = self.time_stamp;
-
- return Some((cache_entry.file.clone(),
- cache_entry.line_number,
- pos - cache_entry.line_start));
- }
-}
--- /dev/null
+// Copyright 2016 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_data_structures::sync::Lrc;
+use syntax::source_map::SourceMap;
+use syntax_pos::{BytePos, SourceFile};
+
+#[derive(Clone)]
+struct CacheEntry {
+ time_stamp: usize,
+ line_number: usize,
+ line_start: BytePos,
+ line_end: BytePos,
+ file: Lrc<SourceFile>,
+ file_index: usize,
+}
+
+#[derive(Clone)]
+pub struct CachingSourceMapView<'cm> {
+ source_map: &'cm SourceMap,
+ line_cache: [CacheEntry; 3],
+ time_stamp: usize,
+}
+
+impl<'cm> CachingSourceMapView<'cm> {
+ pub fn new(source_map: &'cm SourceMap) -> CachingSourceMapView<'cm> {
+ let files = source_map.files();
+ let first_file = files[0].clone();
+ let entry = CacheEntry {
+ time_stamp: 0,
+ line_number: 0,
+ line_start: BytePos(0),
+ line_end: BytePos(0),
+ file: first_file,
+ file_index: 0,
+ };
+
+ CachingSourceMapView {
+ source_map,
+ line_cache: [entry.clone(), entry.clone(), entry],
+ time_stamp: 0,
+ }
+ }
+
+ pub fn byte_pos_to_line_and_col(&mut self,
+ pos: BytePos)
+ -> Option<(Lrc<SourceFile>, usize, BytePos)> {
+ self.time_stamp += 1;
+
+ // Check if the position is in one of the cached lines
+ for cache_entry in self.line_cache.iter_mut() {
+ if pos >= cache_entry.line_start && pos < cache_entry.line_end {
+ cache_entry.time_stamp = self.time_stamp;
+
+ return Some((cache_entry.file.clone(),
+ cache_entry.line_number,
+ pos - cache_entry.line_start));
+ }
+ }
+
+ // No cache hit ...
+ let mut oldest = 0;
+ for index in 1 .. self.line_cache.len() {
+ if self.line_cache[index].time_stamp < self.line_cache[oldest].time_stamp {
+ oldest = index;
+ }
+ }
+
+ let cache_entry = &mut self.line_cache[oldest];
+
+ // If the entry doesn't point to the correct file, fix it up
+ if pos < cache_entry.file.start_pos || pos >= cache_entry.file.end_pos {
+ let file_valid;
+ if self.source_map.files().len() > 0 {
+ let file_index = self.source_map.lookup_source_file_idx(pos);
+ let file = self.source_map.files()[file_index].clone();
+
+ if pos >= file.start_pos && pos < file.end_pos {
+ cache_entry.file = file;
+ cache_entry.file_index = file_index;
+ file_valid = true;
+ } else {
+ file_valid = false;
+ }
+ } else {
+ file_valid = false;
+ }
+
+ if !file_valid {
+ return None;
+ }
+ }
+
+ let line_index = cache_entry.file.lookup_line(pos).unwrap();
+ let line_bounds = cache_entry.file.line_bounds(line_index);
+
+ cache_entry.line_number = line_index + 1;
+ cache_entry.line_start = line_bounds.0;
+ cache_entry.line_end = line_bounds.1;
+ cache_entry.time_stamp = self.time_stamp;
+
+ return Some((cache_entry.file.clone(),
+ cache_entry.line_number,
+ pos - cache_entry.line_start));
+ }
+}
//! ICH - Incremental Compilation Hash
crate use rustc_data_structures::fingerprint::Fingerprint;
-pub use self::caching_codemap_view::CachingSourceMapView;
+pub use self::caching_source_map_view::CachingSourceMapView;
pub use self::hcx::{StableHashingContextProvider, StableHashingContext, NodeIdHashingMode,
hash_stable_trait_impls};
-mod caching_codemap_view;
+mod caching_source_map_view;
mod hcx;
mod impls_cstore;
err.span_label(arm_span, msg);
}
}
- hir::MatchSource::TryDesugar => {
- // Issue #51632
- if let Ok(try_snippet) = self.tcx.sess.source_map().span_to_snippet(arm_span) {
- err.span_suggestion_with_applicability(
- arm_span,
- "try wrapping with a success variant",
- format!("Ok({})", try_snippet),
- Applicability::MachineApplicable,
- );
- }
- }
+ hir::MatchSource::TryDesugar => {}
_ => {
let msg = "match arm with an incompatible type";
if self.tcx.sess.source_map().is_multiline(arm_span) {
type Node = Node;
type Edge = Edge<'tcx>;
fn nodes(&self) -> dot::Nodes<'_, Node> {
- let mut set = FxHashSet::default();
- for node in self.node_ids.keys() {
- set.insert(*node);
- }
+ let set = self.node_ids.keys().cloned().collect::<FxHashSet<_>>();
debug!("constraint graph has {} nodes", set.len());
set.into_iter().collect()
}
pub fn calculate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let sess = &tcx.sess;
- let mut fmts = FxHashMap::default();
- for &ty in sess.crate_types.borrow().iter() {
+ let fmts = sess.crate_types.borrow().iter().map(|&ty| {
let linkage = calculate_type(tcx, ty);
verify_ok(tcx, &linkage);
- fmts.insert(ty, linkage);
- }
+ (ty, linkage)
+ }).collect::<FxHashMap<_, _>>();
sess.abort_if_errors();
sess.dependency_formats.set(fmts);
}
use session::{CrateDisambiguator, Session};
use std::mem;
use syntax::ast::NodeId;
-use syntax::source_map::{SourceMap, StableFilemapId};
+use syntax::source_map::{SourceMap, StableSourceFileId};
use syntax_pos::{BytePos, Span, DUMMY_SP, SourceFile};
use syntax_pos::hygiene::{Mark, SyntaxContext, ExpnInfo};
use ty;
cnum_map: Once<IndexVec<CrateNum, Option<CrateNum>>>,
source_map: &'sess SourceMap,
- file_index_to_stable_id: FxHashMap<SourceFileIndex, StableFilemapId>,
+ file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
// These two fields caches that are populated lazily during decoding.
file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
// This type is used only for (de-)serialization.
#[derive(RustcEncodable, RustcDecodable)]
struct Footer {
- file_index_to_stable_id: FxHashMap<SourceFileIndex, StableFilemapId>,
+ file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
query_result_index: EncodedQueryResultIndex,
diagnostics_index: EncodedQueryResultIndex,
tcx.dep_graph.with_ignore(|| {
// Allocate SourceFileIndices
let (file_to_file_index, file_index_to_stable_id) = {
- let mut file_to_file_index = FxHashMap::default();
- let mut file_index_to_stable_id = FxHashMap::default();
+ let files = tcx.sess.source_map().files();
+ let mut file_to_file_index = FxHashMap::with_capacity_and_hasher(
+ files.len(), Default::default());
+ let mut file_index_to_stable_id = FxHashMap::with_capacity_and_hasher(
+ files.len(), Default::default());
- for (index, file) in tcx.sess.source_map().files().iter().enumerate() {
+ for (index, file) in files.iter().enumerate() {
let index = SourceFileIndex(index as u32);
let file_ptr: *const SourceFile = &**file as *const _;
file_to_file_index.insert(file_ptr, index);
- file_index_to_stable_id.insert(index, StableFilemapId::new(&file));
+ file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
}
(file_to_file_index, file_index_to_stable_id)
cnum_map: &'x IndexVec<CrateNum, Option<CrateNum>>,
synthetic_expansion_infos: &'x Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
file_index_to_file: &'x Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
- file_index_to_stable_id: &'x FxHashMap<SourceFileIndex, StableFilemapId>,
+ file_index_to_stable_id: &'x FxHashMap<SourceFileIndex, StableSourceFileId>,
alloc_decoding_session: AllocDecodingSession<'x>,
}
pub struct EmitterWriter {
dst: Destination,
- cm: Option<Lrc<SourceMapperDyn>>,
+ sm: Option<Lrc<SourceMapperDyn>>,
short_message: bool,
teach: bool,
ui_testing: bool,
impl EmitterWriter {
pub fn stderr(color_config: ColorConfig,
- code_map: Option<Lrc<SourceMapperDyn>>,
+ source_map: Option<Lrc<SourceMapperDyn>>,
short_message: bool,
teach: bool)
-> EmitterWriter {
let dst = Destination::from_stderr(color_config);
EmitterWriter {
dst,
- cm: code_map,
+ sm: source_map,
short_message,
teach,
ui_testing: false,
}
pub fn new(dst: Box<dyn Write + Send>,
- code_map: Option<Lrc<SourceMapperDyn>>,
+ source_map: Option<Lrc<SourceMapperDyn>>,
short_message: bool,
teach: bool)
-> EmitterWriter {
EmitterWriter {
dst: Raw(dst),
- cm: code_map,
+ sm: source_map,
short_message,
teach,
ui_testing: false,
let mut output = vec![];
let mut multiline_annotations = vec![];
- if let Some(ref cm) = self.cm {
+ if let Some(ref sm) = self.sm {
for span_label in msp.span_labels() {
if span_label.span.is_dummy() {
continue;
}
- let lo = cm.lookup_char_pos(span_label.span.lo());
- let mut hi = cm.lookup_char_pos(span_label.span.hi());
+ let lo = sm.lookup_char_pos(span_label.span.lo());
+ let mut hi = sm.lookup_char_pos(span_label.span.hi());
// Watch out for "empty spans". If we get a span like 6..6, we
// want to just display a `^` at 6, so convert that to
fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
let mut max = 0;
- if let Some(ref cm) = self.cm {
+ if let Some(ref sm) = self.sm {
for primary_span in msp.primary_spans() {
if !primary_span.is_dummy() {
- let hi = cm.lookup_char_pos(primary_span.hi());
+ let hi = sm.lookup_char_pos(primary_span.hi());
if hi.line > max {
max = hi.line;
}
if !self.short_message {
for span_label in msp.span_labels() {
if !span_label.span.is_dummy() {
- let hi = cm.lookup_char_pos(span_label.span.hi());
+ let hi = sm.lookup_char_pos(span_label.span.hi());
if hi.line > max {
max = hi.line;
}
always_backtrace: bool) -> bool {
let mut spans_updated = false;
- if let Some(ref cm) = self.cm {
+ if let Some(ref sm) = self.sm {
let mut before_after: Vec<(Span, Span)> = vec![];
let mut new_labels: Vec<(Span, String)> = vec![];
if sp.is_dummy() {
continue;
}
- let call_sp = cm.call_span_if_macro(*sp);
+ let call_sp = sm.call_span_if_macro(*sp);
if call_sp != *sp && !always_backtrace {
before_after.push((*sp, call_sp));
}
})));
}
// Check to make sure we're not in any <*macros>
- if !cm.span_to_filename(def_site).is_macros() &&
+ if !sm.span_to_filename(def_site).is_macros() &&
!trace.macro_decl_name.starts_with("desugaring of ") &&
!trace.macro_decl_name.starts_with("#[") ||
always_backtrace {
if sp_label.span.is_dummy() {
continue;
}
- if cm.span_to_filename(sp_label.span.clone()).is_macros() &&
+ if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
!always_backtrace
{
let v = sp_label.span.macro_backtrace();
let mut annotated_files = self.preprocess_annotations(msp);
// Make sure our primary file comes first
- let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
- (self.cm.as_ref(), msp.primary_span().as_ref()) {
+ let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
+ (self.sm.as_ref(), msp.primary_span().as_ref()) {
if !primary_span.is_dummy() {
- (cm.lookup_char_pos(primary_span.lo()), cm)
+ (sm.lookup_char_pos(primary_span.lo()), sm)
} else {
emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
return Ok(());
// Print out the annotate source lines that correspond with the error
for annotated_file in annotated_files {
// we can't annotate anything if the source is unavailable.
- if !cm.ensure_source_file_source_present(annotated_file.file.clone()) {
+ if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
continue;
}
buffer.append(buffer_msg_line_offset,
&format!("{}:{}:{}",
loc.file.name,
- cm.doctest_offset_line(loc.line),
+ sm.doctest_offset_line(loc.line),
loc.col.0 + 1),
Style::LineAndColumn);
for _ in 0..max_line_num_len {
buffer.prepend(0,
&format!("{}:{}:{}: ",
loc.file.name,
- cm.doctest_offset_line(loc.line),
+ sm.doctest_offset_line(loc.line),
loc.col.0 + 1),
Style::LineAndColumn);
}
};
format!("{}:{}{}",
annotated_file.file.name,
- cm.doctest_offset_line(first_line.line_index),
+ sm.doctest_offset_line(first_line.line_index),
col)
} else {
annotated_file.file.name.to_string()
level: &Level,
max_line_num_len: usize)
-> io::Result<()> {
- if let Some(ref cm) = self.cm {
+ if let Some(ref sm) = self.sm {
let mut buffer = StyledBuffer::new();
// Render the suggestion message
Some(Style::HeaderMsg));
// Render the replacements for each suggestion
- let suggestions = suggestion.splice_lines(&**cm);
+ let suggestions = suggestion.splice_lines(&**sm);
let mut row_num = 2;
for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
&& parts[0].snippet.trim() == complete.trim())
&& complete.lines().count() == 1;
- let lines = cm.span_to_lines(parts[0].span).unwrap();
+ let lines = sm.span_to_lines(parts[0].span).unwrap();
assert!(!lines.lines.is_empty());
- let line_start = cm.lookup_char_pos(parts[0].span.lo()).line;
+ let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
let mut line_pos = 0;
let mut lines = complete.lines();
if show_underline {
draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
for part in parts {
- let span_start_pos = cm.lookup_char_pos(part.span.lo()).col_display;
- let span_end_pos = cm.lookup_char_pos(part.span.hi()).col_display;
+ let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
+ let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
// Do not underline the leading...
let start = part.snippet.len()
fn span_to_filename(&self, sp: Span) -> FileName;
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
fn call_span_if_macro(&self, sp: Span) -> Span;
- fn ensure_source_file_source_present(&self, file_map: Lrc<SourceFile>) -> bool;
+ fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
fn doctest_offset_line(&self, line: usize) -> usize;
}
msg: &str,
followed_by_block: bool) {
if let ast::ExprKind::Paren(ref inner) = value.node {
- let necessary = followed_by_block && if let ast::ExprKind::Ret(_) = inner.node {
- true
- } else {
- parser::contains_exterior_struct_lit(&inner)
+ let necessary = followed_by_block && match inner.node {
+ ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true,
+ _ => parser::contains_exterior_struct_lit(&inner),
};
if !necessary {
let expr_text = if let Ok(snippet) = cx.sess().source_map()
| Write(wk @ WriteKind::StorageDeadOrDrop)
| Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shared))
| Write(wk @ WriteKind::MutableBorrow(BorrowKind::Shallow)) => {
- if let Err(_place_err) = self.is_mutable(place, is_local_mutation_allowed) {
+ if let (Err(_place_err), true) = (
+ self.is_mutable(place, is_local_mutation_allowed),
+ self.errors_buffer.is_empty()
+ ) {
if self.infcx.tcx.migrate_borrowck() {
// rust-lang/rust#46908: In pure NLL mode this
// code path should be unreachable (and thus
location,
);
} else {
- self.infcx.tcx.sess.delay_span_bug(
+ span_bug!(
span,
- &format!(
- "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
- place, kind
- ),
+ "Accessing `{:?}` with the kind `{:?}` shouldn't be possible",
+ place,
+ kind,
);
}
}
AccessKind::Move => {
err = self.infcx.tcx
.cannot_move_out_of(span, &(item_msg + &reason), Origin::Mir);
- act = "move";
- acted_on = "moved";
- span
+ err.span_label(span, "cannot move");
+ err.buffer(&mut self.errors_buffer);
+ return;
}
AccessKind::Mutate => {
err = self.infcx.tcx
use rustc::hir::def::Def;
use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
use rustc::mir;
-use rustc::ty::{self, Ty, TyCtxt, Instance, query::TyCtxtAt};
-use rustc::ty::layout::{self, Size, LayoutOf, TyLayout};
+use rustc::ty::{self, TyCtxt, Instance, query::TyCtxtAt};
+use rustc::ty::layout::{self, LayoutOf, TyLayout};
use rustc::ty::subst::Subst;
use rustc::traits::Reveal;
use rustc_data_structures::indexed_vec::IndexVec;
use syntax::source_map::{Span, DUMMY_SP};
use interpret::{self,
- PlaceTy, MemPlace, OpTy, Operand, Value, Pointer, Scalar, ConstValue,
+ PlaceTy, MemPlace, OpTy, Operand, Value, Scalar, ConstValue, Pointer,
EvalResult, EvalError, EvalErrorKind, GlobalId, EvalContext, StackPopCleanup,
Allocation, AllocId, MemoryKind,
snapshot, RefTracking,
}
#[inline(always)]
- fn static_with_default_tag(
+ fn adjust_static_allocation(
alloc: &'_ Allocation
) -> Cow<'_, Allocation<Self::PointerTag>> {
// We do not use a tag so we can just cheaply forward the reference
}
#[inline(always)]
- fn tag_reference(
+ fn tag_new_allocation(
_ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
- _ptr: Pointer<Self::PointerTag>,
- _pointee_ty: Ty<'tcx>,
- _pointee_size: Size,
- _borrow_kind: Option<mir::BorrowKind>,
- ) -> EvalResult<'tcx, Self::PointerTag> {
- Ok(())
- }
-
- #[inline(always)]
- fn tag_dereference(
- _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
- _ptr: Pointer<Self::PointerTag>,
- _ptr_ty: Ty<'tcx>,
- ) -> EvalResult<'tcx, Self::PointerTag> {
- Ok(())
+ ptr: Pointer,
+ _kind: MemoryKind<Self::MemoryKinds>,
+ ) -> EvalResult<'tcx, Pointer> {
+ Ok(ptr)
}
}
def_id,
substs,
).ok_or_else(|| EvalErrorKind::TooGeneric.into());
- let fn_ptr = self.memory.create_fn_alloc(instance?);
+ let fn_ptr = self.memory.create_fn_alloc(instance?).with_default_tag();
self.write_scalar(Scalar::Ptr(fn_ptr.into()), dest)?;
}
ref other => bug!("reify fn pointer on {:?}", other),
substs,
ty::ClosureKind::FnOnce,
);
- let fn_ptr = self.memory.create_fn_alloc(instance);
+ let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let val = Value::Scalar(Scalar::Ptr(fn_ptr.into()).into());
self.write_value(val, dest)?;
}
pub(crate) param_env: ty::ParamEnv<'tcx>,
/// The virtual memory system.
- pub memory: Memory<'a, 'mir, 'tcx, M>,
+ pub(crate) memory: Memory<'a, 'mir, 'tcx, M>,
/// The virtual call stack.
pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag>>,
}
pub fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value<M::PointerTag>> {
- let ptr = self.memory.allocate_static_bytes(s.as_bytes());
+ let ptr = self.memory.allocate_static_bytes(s.as_bytes()).with_default_tag();
Ok(Value::new_slice(Scalar::Ptr(ptr), s.len() as u64, self.tcx.tcx))
}
use std::borrow::{Borrow, Cow};
use std::hash::Hash;
-use rustc::hir::def_id::DefId;
+use rustc::hir::{self, def_id::DefId};
use rustc::mir;
use rustc::ty::{self, Ty, layout::{Size, TyLayout}, query::TyCtxtAt};
use super::{
Allocation, AllocId, EvalResult, Scalar,
- EvalContext, PlaceTy, OpTy, Pointer, MemoryKind,
+ EvalContext, PlaceTy, OpTy, Pointer, MemPlace, MemoryKind,
};
/// Classifying memory accesses
/// Tag tracked alongside every pointer. This is used to implement "Stacked Borrows"
/// <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>.
+ /// The `default()` is used for pointers to consts, statics, vtables and functions.
type PointerTag: ::std::fmt::Debug + Default + Copy + Eq + Hash + 'static;
/// Extra data stored in every allocation.
) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag, Self::AllocExtra>>>;
/// Called to turn an allocation obtained from the `tcx` into one that has
- /// the appropriate tags on each pointer.
+ /// the right type for this machine.
///
/// This should avoid copying if no work has to be done! If this returns an owned
- /// allocation (because a copy had to be done to add the tags), machine memory will
+ /// allocation (because a copy had to be done to add tags or metadata), machine memory will
/// cache the result. (This relies on `AllocMap::get_or` being able to add the
/// owned allocation to the map even when the map is shared.)
- fn static_with_default_tag(
+ fn adjust_static_allocation(
alloc: &'_ Allocation
) -> Cow<'_, Allocation<Self::PointerTag, Self::AllocExtra>>;
Ok(())
}
+ /// Add the tag for a newly allocated pointer.
+ fn tag_new_allocation(
+ ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
+ ptr: Pointer,
+ kind: MemoryKind<Self::MemoryKinds>,
+ ) -> EvalResult<'tcx, Pointer<Self::PointerTag>>;
+
/// Executed when evaluating the `&` operator: Creating a new reference.
- /// This has the chance to adjust the tag.
- /// `borrow_kind` can be `None` in case a raw ptr is being created.
+ /// This has the chance to adjust the tag. It should not change anything else!
+ /// `mutability` can be `None` in case a raw ptr is being created.
+ #[inline]
fn tag_reference(
- ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
- ptr: Pointer<Self::PointerTag>,
- pointee_ty: Ty<'tcx>,
- pointee_size: Size,
- borrow_kind: Option<mir::BorrowKind>,
- ) -> EvalResult<'tcx, Self::PointerTag>;
+ _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
+ place: MemPlace<Self::PointerTag>,
+ _ty: Ty<'tcx>,
+ _size: Size,
+ _mutability: Option<hir::Mutability>,
+ ) -> EvalResult<'tcx, MemPlace<Self::PointerTag>> {
+ Ok(place)
+ }
/// Executed when evaluating the `*` operator: Following a reference.
- /// This has the change to adjust the tag.
+ /// This has the change to adjust the tag. It should not change anything else!
+ /// `mutability` can be `None` in case a raw ptr is being dereferenced.
+ #[inline]
fn tag_dereference(
- ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
- ptr: Pointer<Self::PointerTag>,
- ptr_ty: Ty<'tcx>,
- ) -> EvalResult<'tcx, Self::PointerTag>;
+ _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
+ place: MemPlace<Self::PointerTag>,
+ _ty: Ty<'tcx>,
+ _size: Size,
+ _mutability: Option<hir::Mutability>,
+ ) -> EvalResult<'tcx, MemPlace<Self::PointerTag>> {
+ Ok(place)
+ }
/// Execute a validation operation
#[inline]
}
}
- pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer<M::PointerTag> {
- Pointer::from(self.tcx.alloc_map.lock().create_fn_alloc(instance)).with_default_tag()
+ pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer {
+ Pointer::from(self.tcx.alloc_map.lock().create_fn_alloc(instance))
}
- pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer<M::PointerTag> {
- Pointer::from(self.tcx.allocate_bytes(bytes)).with_default_tag()
+ pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer {
+ Pointer::from(self.tcx.allocate_bytes(bytes))
}
pub fn allocate_with(
size: Size,
align: Align,
kind: MemoryKind<M::MemoryKinds>,
- ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
- let ptr = Pointer::from(self.allocate_with(Allocation::undef(size, align), kind)?);
- Ok(ptr.with_default_tag())
+ ) -> EvalResult<'tcx, Pointer> {
+ Ok(Pointer::from(self.allocate_with(Allocation::undef(size, align), kind)?))
}
pub fn reallocate(
new_size: Size,
new_align: Align,
kind: MemoryKind<M::MemoryKinds>,
- ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
+ ) -> EvalResult<'tcx, Pointer> {
if ptr.offset.bytes() != 0 {
return err!(ReallocateNonBasePtr);
}
- // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc"
+ // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
+ // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
let new_ptr = self.allocate(new_size, new_align, kind)?;
self.copy(
ptr.into(),
old_align,
- new_ptr.into(),
+ new_ptr.with_default_tag().into(),
new_align,
old_size.min(new_size),
/*nonoverlapping*/ true,
Some(AllocType::Memory(mem)) => {
// We got tcx memory. Let the machine figure out whether and how to
// turn that into memory with the right pointer tag.
- return Ok(M::static_with_default_tag(mem))
+ return Ok(M::adjust_static_allocation(mem))
}
Some(AllocType::Function(..)) => {
return err!(DerefFunctionPointer)
if let ConstValue::ByRef(_, allocation, _) = const_val.val {
// We got tcx memory. Let the machine figure out whether and how to
// turn that into memory with the right pointer tag.
- M::static_with_default_tag(allocation)
+ M::adjust_static_allocation(allocation)
} else {
bug!("Matching on non-ByRef static")
}
Value::ScalarPair(ptr, _) => ptr.not_undef(),
}
}
+
+ /// Convert the value into its metadata.
+ /// Throws away the first half of a ScalarPair!
+ #[inline]
+ pub fn to_meta(self) -> EvalResult<'tcx, Option<Scalar<Tag>>> {
+ Ok(match self {
+ Value::Scalar(_) => None,
+ Value::ScalarPair(_, meta) => Some(meta.not_undef()?),
+ })
+ }
}
// ScalarPair needs a type to interpret, so we often have a value and a type together
use std::convert::TryFrom;
use std::hash::Hash;
+use rustc::hir;
use rustc::mir;
use rustc::ty::{self, Ty};
use rustc::ty::layout::{self, Size, Align, LayoutOf, TyLayout, HasDataLayout};
&self,
val: ValTy<'tcx, M::PointerTag>,
) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
- let ptr = match val.to_scalar_ptr()? {
- Scalar::Ptr(ptr) if M::ENABLE_PTR_TRACKING_HOOKS => {
- // Machine might want to track the `*` operator
- let tag = M::tag_dereference(self, ptr, val.layout.ty)?;
- Scalar::Ptr(Pointer::new_with_tag(ptr.alloc_id, ptr.offset, tag))
- }
- other => other,
- };
-
let pointee_type = val.layout.ty.builtin_deref(true).unwrap().ty;
let layout = self.layout_of(pointee_type)?;
- let align = layout.align;
- let mplace = match *val {
- Value::Scalar(_) =>
- MemPlace { ptr, align, meta: None },
- Value::ScalarPair(_, meta) =>
- MemPlace { ptr, align, meta: Some(meta.not_undef()?) },
+ let align = layout.align;
+ let meta = val.to_meta()?;
+ let ptr = val.to_scalar_ptr()?;
+ let mplace = MemPlace { ptr, align, meta };
+ // Pointer tag tracking might want to adjust the tag.
+ let mplace = if M::ENABLE_PTR_TRACKING_HOOKS {
+ let (size, _) = self.size_and_align_of(meta, layout)?
+ // for extern types, just cover what we can
+ .unwrap_or_else(|| layout.size_and_align());
+ let mutbl = match val.layout.ty.sty {
+ // `builtin_deref` considers boxes immutable, that's useless for our purposes
+ ty::Ref(_, _, mutbl) => Some(mutbl),
+ ty::Adt(def, _) if def.is_box() => Some(hir::MutMutable),
+ ty::RawPtr(_) => None,
+ _ => bug!("Unexpected pointer type {}", val.layout.ty.sty),
+ };
+ M::tag_dereference(self, mplace, pointee_type, size, mutbl)?
+ } else {
+ mplace
};
Ok(MPlaceTy { mplace, layout })
}
place: MPlaceTy<'tcx, M::PointerTag>,
borrow_kind: Option<mir::BorrowKind>,
) -> EvalResult<'tcx, Value<M::PointerTag>> {
- let ptr = match place.ptr {
- Scalar::Ptr(ptr) if M::ENABLE_PTR_TRACKING_HOOKS => {
- // Machine might want to track the `&` operator
- let (size, _) = self.size_and_align_of_mplace(place)?
- .expect("create_ref cannot determine size");
- let tag = M::tag_reference(self, ptr, place.layout.ty, size, borrow_kind)?;
- Scalar::Ptr(Pointer::new_with_tag(ptr.alloc_id, ptr.offset, tag))
- },
- other => other,
+ // Pointer tag tracking might want to adjust the tag
+ let place = if M::ENABLE_PTR_TRACKING_HOOKS {
+ let (size, _) = self.size_and_align_of_mplace(place)?
+ // for extern types, just cover what we can
+ .unwrap_or_else(|| place.layout.size_and_align());
+ let mutbl = match borrow_kind {
+ Some(mir::BorrowKind::Mut { .. }) |
+ Some(mir::BorrowKind::Unique) =>
+ Some(hir::MutMutable),
+ Some(_) => Some(hir::MutImmutable),
+ None => None,
+ };
+ M::tag_reference(self, *place, place.layout.ty, size, mutbl)?
+ } else {
+ *place
};
Ok(match place.meta {
- None => Value::Scalar(ptr.into()),
- Some(meta) => Value::ScalarPair(ptr.into(), meta.into()),
+ None => Value::Scalar(place.ptr.into()),
+ Some(meta) => Value::ScalarPair(place.ptr.into(), meta.into()),
})
}
}
/// Make sure that a place is in memory, and return where it is.
+ /// If the place currently refers to a local that doesn't yet have a matching allocation,
+ /// create such an allocation.
/// This is essentially `force_to_memplace`.
pub fn force_allocation(
&mut self,
) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
if layout.is_unsized() {
assert!(self.tcx.features().unsized_locals, "cannot alloc memory for unsized type");
- // FIXME: What should we do here?
+ // FIXME: What should we do here? We should definitely also tag!
Ok(MPlaceTy::dangling(layout, &self))
} else {
let ptr = self.memory.allocate(layout.size, layout.align, kind)?;
+ let ptr = M::tag_new_allocation(self, ptr, kind)?;
Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
}
}
ptr_size * (3 + methods.len() as u64),
ptr_align,
MemoryKind::Vtable,
- )?;
+ )?.with_default_tag();
let drop = ::monomorphize::resolve_drop_in_place(*self.tcx, ty);
- let drop = self.memory.create_fn_alloc(drop);
+ let drop = self.memory.create_fn_alloc(drop).with_default_tag();
self.memory.write_ptr_sized(vtable, ptr_align, Scalar::Ptr(drop).into())?;
let size_ptr = vtable.offset(ptr_size, &self)?;
for (i, method) in methods.iter().enumerate() {
if let Some((def_id, substs)) = *method {
let instance = self.resolve(def_id, substs)?;
- let fn_ptr = self.memory.create_fn_alloc(instance);
+ let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), &self)?;
self.memory.write_ptr_sized(method_ptr, ptr_align, Scalar::Ptr(fn_ptr).into())?;
}
use std::hash::Hash;
use syntax_pos::symbol::Symbol;
-use rustc::ty::layout::{self, Size, Align, TyLayout};
+use rustc::ty::layout::{self, Size, Align, TyLayout, LayoutOf};
use rustc::ty;
use rustc_data_structures::fx::FxHashSet;
use rustc::mir::interpret::{
// undef. We should fix that, but let's start low.
}
}
- _ if ty.is_box() || ty.is_region_ptr() || ty.is_unsafe_ptr() => {
- // Handle fat pointers. We also check fat raw pointers,
- // their metadata must be valid!
- // This also checks that the ptr itself is initialized, which
- // seems reasonable even for raw pointers.
- let place = try_validation!(self.ref_to_mplace(value),
- "undefined data in pointer", path);
+ ty::RawPtr(..) => {
+ // No undef allowed here. Eventually this should be consistent with
+ // the integer types.
+ let _ptr = try_validation!(value.to_scalar_ptr(),
+ "undefined address in pointer", path);
+ let _meta = try_validation!(value.to_meta(),
+ "uninitialized data in fat pointer metadata", path);
+ }
+ _ if ty.is_box() || ty.is_region_ptr() => {
+ // Handle fat pointers.
// Check metadata early, for better diagnostics
- if place.layout.is_unsized() {
- let tail = self.tcx.struct_tail(place.layout.ty);
+ let ptr = try_validation!(value.to_scalar_ptr(),
+ "undefined address in pointer", path);
+ let meta = try_validation!(value.to_meta(),
+ "uninitialized data in fat pointer metadata", path);
+ let layout = self.layout_of(value.layout.ty.builtin_deref(true).unwrap().ty)?;
+ if layout.is_unsized() {
+ let tail = self.tcx.struct_tail(layout.ty);
match tail.sty {
ty::Dynamic(..) => {
- let vtable = try_validation!(place.meta.unwrap().to_ptr(),
+ let vtable = try_validation!(meta.unwrap().to_ptr(),
"non-pointer vtable in fat pointer", path);
try_validation!(self.read_drop_type_from_vtable(vtable),
"invalid drop fn in vtable", path);
// FIXME: More checks for the vtable.
}
ty::Slice(..) | ty::Str => {
- try_validation!(place.meta.unwrap().to_usize(self),
+ try_validation!(meta.unwrap().to_usize(self),
"non-integer slice length in fat pointer", path);
}
ty::Foreign(..) => {
bug!("Unexpected unsized type tail: {:?}", tail),
}
}
- // for safe ptrs, also check the ptr values itself
- if !ty.is_unsafe_ptr() {
- // Make sure this is non-NULL and aligned
- let (size, align) = self.size_and_align_of(place.meta, place.layout)?
- // for the purpose of validity, consider foreign types to have
- // alignment and size determined by the layout (size will be 0,
- // alignment should take attributes into account).
- .unwrap_or_else(|| place.layout.size_and_align());
- match self.memory.check_align(place.ptr, align) {
- Ok(_) => {},
- Err(err) => match err.kind {
+ // Make sure this is non-NULL and aligned
+ let (size, align) = self.size_and_align_of(meta, layout)?
+ // for the purpose of validity, consider foreign types to have
+ // alignment and size determined by the layout (size will be 0,
+ // alignment should take attributes into account).
+ .unwrap_or_else(|| layout.size_and_align());
+ match self.memory.check_align(ptr, align) {
+ Ok(_) => {},
+ Err(err) => {
+ error!("{:?} is not aligned to {:?}", ptr, align);
+ match err.kind {
EvalErrorKind::InvalidNullPointerUsage =>
return validation_failure!("NULL reference", path),
EvalErrorKind::AlignmentCheckFailed { .. } =>
_ =>
return validation_failure!(
"dangling (out-of-bounds) reference (might be NULL at \
- run-time)",
+ run-time)",
path
),
}
}
- // non-ZST also have to be dereferenceable
+ }
+ // Turn ptr into place.
+ // `ref_to_mplace` also calls the machine hook for (re)activating the tag,
+ // which in turn will (in full miri) check if the pointer is dereferencable.
+ let place = self.ref_to_mplace(value)?;
+ // Recursive checking
+ if let Some(ref_tracking) = ref_tracking {
+ assert!(const_mode, "We should only do recursie checking in const mode");
if size != Size::ZERO {
+ // Non-ZST also have to be dereferencable
let ptr = try_validation!(place.ptr.to_ptr(),
"integer pointer in non-ZST reference", path);
- if const_mode {
- // Skip validation entirely for some external statics
- let alloc_kind = self.tcx.alloc_map.lock().get(ptr.alloc_id);
- if let Some(AllocType::Static(did)) = alloc_kind {
- // `extern static` cannot be validated as they have no body.
- // FIXME: Statics from other crates are also skipped.
- // They might be checked at a different type, but for now we
- // want to avoid recursing too deeply. This is not sound!
- if !did.is_local() || self.tcx.is_foreign_item(did) {
- return Ok(());
- }
+ // Skip validation entirely for some external statics
+ let alloc_kind = self.tcx.alloc_map.lock().get(ptr.alloc_id);
+ if let Some(AllocType::Static(did)) = alloc_kind {
+ // `extern static` cannot be validated as they have no body.
+ // FIXME: Statics from other crates are also skipped.
+ // They might be checked at a different type, but for now we
+ // want to avoid recursing too deeply. This is not sound!
+ if !did.is_local() || self.tcx.is_foreign_item(did) {
+ return Ok(());
}
}
+ // Maintain the invariant that the place we are checking is
+ // already verified to be in-bounds.
try_validation!(self.memory.check_bounds(ptr, size, false),
"dangling (not entirely in bounds) reference", path);
}
- if let Some(ref_tracking) = ref_tracking {
- // Check if we have encountered this pointer+layout combination
- // before. Proceed recursively even for integer pointers, no
- // reason to skip them! They are (recursively) valid for some ZST,
- // but not for others (e.g. `!` is a ZST).
- let op = place.into();
- if ref_tracking.seen.insert(op) {
- trace!("Recursing below ptr {:#?}", *op);
- ref_tracking.todo.push((op, path_clone_and_deref(path)));
- }
+ // Check if we have encountered this pointer+layout combination
+ // before. Proceed recursively even for integer pointers, no
+ // reason to skip them! They are (recursively) valid for some ZST,
+ // but not for others (e.g. `!` is a ZST).
+ let op = place.into();
+ if ref_tracking.seen.insert(op) {
+ trace!("Recursing below ptr {:#?}", *op);
+ ref_tracking.todo.push((op, path_clone_and_deref(path)));
}
}
}
no_integrated_as: true,
// There are no atomic CAS instructions available in the MSP430
- // instruction set
- max_atomic_width: Some(16),
+ // instruction set, and the LLVM backend doesn't currently support
+ // compiler fences so the Atomic* API is missing on this target.
+ // When the LLVM backend gains support for compile fences uncomment
+ // the `singlethread: true` line and set `max_atomic_width` to
+ // `Some(16)`.
+ max_atomic_width: Some(0),
atomic_cas: false,
+ // singlethread: true,
// Because these devices have very little resources having an
// unwinder is too onerous so we default to "abort" because the
_ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
};
- let mut remaining_fields = FxHashMap::default();
- for (i, field) in variant.fields.iter().enumerate() {
- remaining_fields.insert(field.ident.modern(), (i, field));
- }
+ let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
+ (field.ident.modern(), (i, field))
+ ).collect::<FxHashMap<_, _>>();
let mut seen_fields = FxHashMap::default();
// provided (if any) into their appropriate spaces. We'll also report
// errors if type parameters are provided in an inappropriate place.
- let mut generic_segs = FxHashSet::default();
- for PathSeg(_, index) in &path_segs {
- generic_segs.insert(index);
- }
+ let generic_segs = path_segs.iter().map(|PathSeg(_, index)| index)
+ .collect::<FxHashSet<_>>();
AstConv::prohibit_generics(self, segments.iter().enumerate().filter_map(|(index, seg)| {
if !generic_segs.contains(&index) {
Some(seg)
var end = start + className.length;
return !(end < elemClass.length && elemClass[end] !== ' ');
}
- if (start > 0 && elemClass[start - 1] !== ' ') {
- return false;
- }
- var end = start + className.length;
- return !(end < elemClass.length && elemClass[end] !== ' ');
}
return false;
}
pub struct JsonEmitter {
dst: Box<dyn Write + Send>,
registry: Option<Registry>,
- cm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
+ sm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
pretty: bool,
ui_testing: bool,
}
impl JsonEmitter {
pub fn stderr(registry: Option<Registry>,
- code_map: Lrc<SourceMap>,
+ source_map: Lrc<SourceMap>,
pretty: bool) -> JsonEmitter {
JsonEmitter {
dst: Box::new(io::stderr()),
registry,
- cm: code_map,
+ sm: source_map,
pretty,
ui_testing: false,
}
pub fn new(dst: Box<dyn Write + Send>,
registry: Option<Registry>,
- code_map: Lrc<SourceMap>,
+ source_map: Lrc<SourceMap>,
pretty: bool) -> JsonEmitter {
JsonEmitter {
dst,
registry,
- cm: code_map,
+ sm: source_map,
pretty,
ui_testing: false,
}
}
let buf = BufWriter::default();
let output = buf.clone();
- EmitterWriter::new(Box::new(buf), Some(je.cm.clone()), false, false)
+ EmitterWriter::new(Box::new(buf), Some(je.sm.clone()), false, false)
.ui_testing(je.ui_testing).emit(db);
let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
let output = String::from_utf8(output).unwrap();
mut backtrace: vec::IntoIter<MacroBacktrace>,
je: &JsonEmitter)
-> DiagnosticSpan {
- let start = je.cm.lookup_char_pos(span.lo());
- let end = je.cm.lookup_char_pos(span.hi());
+ let start = je.sm.lookup_char_pos(span.lo());
+ let end = je.sm.lookup_char_pos(span.hi());
let backtrace_step = backtrace.next().map(|bt| {
let call_site =
Self::from_span_full(bt.call_site,
/// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
/// `span` within the line.
fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
- je.cm.span_to_lines(span)
+ je.sm.span_to_lines(span)
.map(|lines| {
let fm = &*lines.file;
lines.lines
let end = sess.source_map().lookup_byte_offset(span.hi());
// Make the range zero-length if the span is invalid.
- if span.lo() > span.hi() || begin.fm.start_pos != end.fm.start_pos {
+ if span.lo() > span.hi() || begin.sf.start_pos != end.sf.start_pos {
span = span.shrink_to_lo();
}
- let mut sr = StringReader::new_raw_internal(sess, begin.fm, None);
+ let mut sr = StringReader::new_raw_internal(sess, begin.sf, None);
// Seek the lexer to the right byte range.
sr.next_pos = span.lo();
// I guess this is the only way to figure out if
// we're at the beginning of the file...
- let cmap = SourceMap::new(FilePathMapping::empty());
- cmap.files.borrow_mut().file_maps.push(self.source_file.clone());
- let loc = cmap.lookup_char_pos_adj(self.pos);
+ let smap = SourceMap::new(FilePathMapping::empty());
+ smap.files.borrow_mut().source_files.push(self.source_file.clone());
+ let loc = smap.lookup_char_pos_adj(self.pos);
debug!("Skipping a shebang");
if loc.line == 1 && loc.col == CharPos(0) {
// FIXME: Add shebang "token", return it
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lock;
use with_globals;
- fn mk_sess(cm: Lrc<SourceMap>) -> ParseSess {
+ fn mk_sess(sm: Lrc<SourceMap>) -> ParseSess {
let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()),
- Some(cm.clone()),
+ Some(sm.clone()),
false,
false);
ParseSess {
unstable_features: UnstableFeatures::from_environment(),
config: CrateConfig::default(),
included_mod_stack: Lock::new(Vec::new()),
- code_map: cm,
+ source_map: sm,
missing_fragment_specifiers: Lock::new(FxHashSet::default()),
raw_identifier_spans: Lock::new(Vec::new()),
registered_diagnostics: Lock::new(ErrorMap::new()),
}
// open a string reader for the given string
- fn setup<'a>(cm: &SourceMap,
+ fn setup<'a>(sm: &SourceMap,
sess: &'a ParseSess,
teststr: String)
-> StringReader<'a> {
- let fm = cm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
- StringReader::new(sess, fm, None)
+ let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
+ StringReader::new(sess, sf, None)
}
#[test]
fn t1() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- let mut string_reader = setup(&cm,
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ let mut string_reader = setup(&sm,
&sh,
"/* my source file */ fn main() { println!(\"zebra\"); }\n"
.to_string());
#[test]
fn doublecolonparsing() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- check_tokenization(setup(&cm, &sh, "a b".to_string()),
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ check_tokenization(setup(&sm, &sh, "a b".to_string()),
vec![mk_ident("a"), token::Whitespace, mk_ident("b")]);
})
}
#[test]
fn dcparsing_2() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- check_tokenization(setup(&cm, &sh, "a::b".to_string()),
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ check_tokenization(setup(&sm, &sh, "a::b".to_string()),
vec![mk_ident("a"), token::ModSep, mk_ident("b")]);
})
}
#[test]
fn dcparsing_3() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- check_tokenization(setup(&cm, &sh, "a ::b".to_string()),
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ check_tokenization(setup(&sm, &sh, "a ::b".to_string()),
vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]);
})
}
#[test]
fn dcparsing_4() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- check_tokenization(setup(&cm, &sh, "a:: b".to_string()),
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ check_tokenization(setup(&sm, &sh, "a:: b".to_string()),
vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]);
})
}
#[test]
fn character_a() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok,
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ assert_eq!(setup(&sm, &sh, "'a'".to_string()).next_token().tok,
token::Literal(token::Char(Symbol::intern("a")), None));
})
}
#[test]
fn character_space() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok,
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ assert_eq!(setup(&sm, &sh, "' '".to_string()).next_token().tok,
token::Literal(token::Char(Symbol::intern(" ")), None));
})
}
#[test]
fn character_escaped() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok,
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ assert_eq!(setup(&sm, &sh, "'\\n'".to_string()).next_token().tok,
token::Literal(token::Char(Symbol::intern("\\n")), None));
})
}
#[test]
fn lifetime_name() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok,
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ assert_eq!(setup(&sm, &sh, "'abc".to_string()).next_token().tok,
token::Lifetime(Ident::from_str("'abc")));
})
}
#[test]
fn raw_string() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ assert_eq!(setup(&sm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string())
.next_token()
.tok,
token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None));
#[test]
fn literal_suffixes() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
macro_rules! test {
($input: expr, $tok_type: ident, $tok_contents: expr) => {{
- assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok,
+ assert_eq!(setup(&sm, &sh, format!("{}suffix", $input)).next_token().tok,
token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
Some(Symbol::intern("suffix"))));
// with a whitespace separator:
- assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok,
+ assert_eq!(setup(&sm, &sh, format!("{} suffix", $input)).next_token().tok,
token::Literal(token::$tok_type(Symbol::intern($tok_contents)),
None));
}}
test!("1.0", Float, "1.0");
test!("1.0e10", Float, "1.0e10");
- assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok,
+ assert_eq!(setup(&sm, &sh, "2us".to_string()).next_token().tok,
token::Literal(token::Integer(Symbol::intern("2")),
Some(Symbol::intern("us"))));
- assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
+ assert_eq!(setup(&sm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok,
token::Literal(token::StrRaw(Symbol::intern("raw"), 3),
Some(Symbol::intern("suffix"))));
- assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
+ assert_eq!(setup(&sm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok,
token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3),
Some(Symbol::intern("suffix"))));
})
#[test]
fn nested_block_comments() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string());
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ let mut lexer = setup(&sm, &sh, "/* /* */ */'a'".to_string());
match lexer.next_token().tok {
token::Comment => {}
_ => panic!("expected a comment!"),
#[test]
fn crlf_comments() {
with_globals(|| {
- let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- let sh = mk_sess(cm.clone());
- let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string());
+ let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ let sh = mk_sess(sm.clone());
+ let mut lexer = setup(&sm, &sh, "// test\r\n/// test\r\n".to_string());
let comment = lexer.next_token();
assert_eq!(comment.tok, token::Comment);
assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7)));
pub non_modrs_mods: Lock<Vec<(ast::Ident, Span)>>,
/// Used to determine and report recursive mod inclusions
included_mod_stack: Lock<Vec<PathBuf>>,
- code_map: Lrc<SourceMap>,
+ source_map: Lrc<SourceMap>,
pub buffered_lints: Lock<Vec<BufferedEarlyLint>>,
}
ParseSess::with_span_handler(handler, cm)
}
- pub fn with_span_handler(handler: Handler, code_map: Lrc<SourceMap>) -> ParseSess {
+ pub fn with_span_handler(handler: Handler, source_map: Lrc<SourceMap>) -> ParseSess {
ParseSess {
span_diagnostic: handler,
unstable_features: UnstableFeatures::from_environment(),
raw_identifier_spans: Lock::new(Vec::new()),
registered_diagnostics: Lock::new(ErrorMap::new()),
included_mod_stack: Lock::new(vec![]),
- code_map,
+ source_map,
non_modrs_mods: Lock::new(vec![]),
buffered_lints: Lock::new(vec![]),
}
}
pub fn source_map(&self) -> &SourceMap {
- &self.code_map
+ &self.source_map
}
pub fn buffer_lint<S: Into<MultiSpan>>(&self,
-> Option<ast::LitKind> {
debug!("float_lit: {:?}, {:?}", s, suffix);
// FIXME #2252: bounds checking float literals is deferred until trans
- let s = s.chars().filter(|&c| c != '_').collect::<String>();
- filtered_float_lit(Symbol::intern(&s), suffix, diag)
+
+ // Strip underscores without allocating a new String unless necessary.
+ let s2;
+ let s = if s.chars().any(|c| c == '_') {
+ s2 = s.chars().filter(|&c| c != '_').collect::<String>();
+ &s2
+ } else {
+ s
+ };
+
+ filtered_float_lit(Symbol::intern(s), suffix, diag)
}
/// Parse a string representing a byte literal into its final form. Similar to `char_lit`
-> Option<ast::LitKind> {
// s can only be ascii, byte indexing is fine
- let s2 = s.chars().filter(|&c| c != '_').collect::<String>();
- let mut s = &s2[..];
+ // Strip underscores without allocating a new String unless necessary.
+ let s2;
+ let mut s = if s.chars().any(|c| c == '_') {
+ s2 = s.chars().filter(|&c| c != '_').collect::<String>();
+ &s2
+ } else {
+ s
+ };
debug!("integer_lit: {}, {:?}", s, suffix);
// subsequent compilation sessions (which is something we need to do during
// incremental compilation).
#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
-pub struct StableFilemapId(u128);
+pub struct StableSourceFileId(u128);
-impl StableFilemapId {
- pub fn new(source_file: &SourceFile) -> StableFilemapId {
+impl StableSourceFileId {
+ pub fn new(source_file: &SourceFile) -> StableSourceFileId {
let mut hasher = StableHasher::new();
source_file.name.hash(&mut hasher);
source_file.name_was_remapped.hash(&mut hasher);
source_file.unmapped_path.hash(&mut hasher);
- StableFilemapId(hasher.finish())
+ StableSourceFileId(hasher.finish())
}
}
#[derive(Default)]
pub(super) struct SourceMapFiles {
- pub(super) file_maps: Vec<Lrc<SourceFile>>,
- stable_id_to_source_file: FxHashMap<StableFilemapId, Lrc<SourceFile>>
+ pub(super) source_files: Vec<Lrc<SourceFile>>,
+ stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
}
pub struct SourceMap {
}
pub fn files(&self) -> MappedLockGuard<Vec<Lrc<SourceFile>>> {
- LockGuard::map(self.files.borrow(), |files| &mut files.file_maps)
+ LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
}
- pub fn source_file_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Lrc<SourceFile>> {
- self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|fm| fm.clone())
+ pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
+ Option<Lrc<SourceFile>> {
+ self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
}
fn next_start_pos(&self) -> usize {
- match self.files.borrow().file_maps.last() {
+ match self.files.borrow().source_files.last() {
None => 0,
// Add one so there is some space between files. This lets us distinguish
// positions in the source_map, even in the presence of zero-length files.
let mut files = self.files.borrow_mut();
- files.file_maps.push(source_file.clone());
- files.stable_id_to_source_file.insert(StableFilemapId::new(&source_file),
+ files.source_files.push(source_file.clone());
+ files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
source_file.clone());
source_file
let mut files = self.files.borrow_mut();
- files.file_maps.push(source_file.clone());
- files.stable_id_to_source_file.insert(StableFilemapId::new(&source_file),
+ files.source_files.push(source_file.clone());
+ files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
source_file.clone());
source_file
pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
let chpos = self.bytepos_to_file_charpos(pos);
match self.lookup_line(pos) {
- Ok(SourceFileAndLine { fm: f, line: a }) => {
+ Ok(SourceFileAndLine { sf: f, line: a }) => {
let line = a + 1; // Line numbers start at 1
let linebpos = f.lines[a];
let linechpos = self.bytepos_to_file_charpos(linebpos);
pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
let idx = self.lookup_source_file_idx(pos);
- let f = (*self.files.borrow().file_maps)[idx].clone();
+ let f = (*self.files.borrow().source_files)[idx].clone();
match f.lookup_line(pos) {
- Some(line) => Ok(SourceFileAndLine { fm: f, line: line }),
+ Some(line) => Ok(SourceFileAndLine { sf: f, line: line }),
None => Err(f)
}
}
}
pub fn span_to_string(&self, sp: Span) -> String {
- if self.files.borrow().file_maps.is_empty() && sp.is_dummy() {
+ if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
return "no-location".to_string();
}
let local_begin = self.lookup_byte_offset(sp.lo());
let local_end = self.lookup_byte_offset(sp.hi());
- if local_begin.fm.start_pos != local_end.fm.start_pos {
+ if local_begin.sf.start_pos != local_end.sf.start_pos {
return Err(SpanSnippetError::DistinctSources(DistinctSources {
- begin: (local_begin.fm.name.clone(),
- local_begin.fm.start_pos),
- end: (local_end.fm.name.clone(),
- local_end.fm.start_pos)
+ begin: (local_begin.sf.name.clone(),
+ local_begin.sf.start_pos),
+ end: (local_end.sf.name.clone(),
+ local_end.sf.start_pos)
}));
} else {
- self.ensure_source_file_source_present(local_begin.fm.clone());
+ self.ensure_source_file_source_present(local_begin.sf.clone());
let start_index = local_begin.pos.to_usize();
let end_index = local_end.pos.to_usize();
- let source_len = (local_begin.fm.end_pos -
- local_begin.fm.start_pos).to_usize();
+ let source_len = (local_begin.sf.end_pos -
+ local_begin.sf.start_pos).to_usize();
if start_index > end_index || end_index > source_len {
- return Err(SpanSnippetError::MalformedForCodemap(
- MalformedCodemapPositions {
- name: local_begin.fm.name.clone(),
+ return Err(SpanSnippetError::MalformedForSourcemap(
+ MalformedSourceMapPositions {
+ name: local_begin.sf.name.clone(),
source_len,
begin_pos: local_begin.pos,
end_pos: local_end.pos,
}));
}
- if let Some(ref src) = local_begin.fm.src {
+ if let Some(ref src) = local_begin.sf.src {
return Ok(extract_source(src, start_index, end_index));
- } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
+ } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
return Ok(extract_source(src, start_index, end_index));
} else {
return Err(SpanSnippetError::SourceNotAvailable {
- filename: local_begin.fm.name.clone()
+ filename: local_begin.sf.name.clone()
});
}
}
return 1;
}
- let source_len = (local_begin.fm.end_pos - local_begin.fm.start_pos).to_usize();
+ let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
// Ensure indexes are also not malformed.
if start_index > end_index || end_index > source_len {
return 1;
}
- let src = local_begin.fm.external_src.borrow();
+ let src = local_begin.sf.external_src.borrow();
// We need to extend the snippet to the end of the src rather than to end_index so when
// searching forwards for boundaries we've got somewhere to search.
- let snippet = if let Some(ref src) = local_begin.fm.src {
+ let snippet = if let Some(ref src) = local_begin.sf.src {
let len = src.len();
(&src[start_index..len])
} else if let Some(src) = src.get_source() {
}
pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
- for fm in self.files.borrow().file_maps.iter() {
- if *filename == fm.name {
- return Some(fm.clone());
+ for sf in self.files.borrow().source_files.iter() {
+ if *filename == sf.name {
+ return Some(sf.clone());
}
}
None
/// For a global BytePos compute the local offset within the containing SourceFile
pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
let idx = self.lookup_source_file_idx(bpos);
- let fm = (*self.files.borrow().file_maps)[idx].clone();
- let offset = bpos - fm.start_pos;
- SourceFileAndBytePos {fm: fm, pos: offset}
+ let sf = (*self.files.borrow().source_files)[idx].clone();
+ let offset = bpos - sf.start_pos;
+ SourceFileAndBytePos {sf: sf, pos: offset}
}
/// Converts an absolute BytePos to a CharPos relative to the source_file.
pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
let idx = self.lookup_source_file_idx(bpos);
- let map = &(*self.files.borrow().file_maps)[idx];
+ let map = &(*self.files.borrow().source_files)[idx];
// The number of extra bytes due to multibyte chars in the SourceFile
let mut total_extra_bytes = 0;
// Return the index of the source_file (in self.files) which contains pos.
pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
let files = self.files.borrow();
- let files = &files.file_maps;
+ let files = &files.source_files;
let count = files.len();
// Binary search for the source_file.
}
sp
}
- fn ensure_source_file_source_present(&self, file_map: Lrc<SourceFile>) -> bool {
- file_map.add_external_src(
- || match file_map.name {
+ fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
+ source_file.add_external_src(
+ || match source_file.name {
FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
_ => None,
}
use super::*;
use rustc_data_structures::sync::Lrc;
- fn init_code_map() -> SourceMap {
- let cm = SourceMap::new(FilePathMapping::empty());
- cm.new_source_file(PathBuf::from("blork.rs").into(),
+ fn init_source_map() -> SourceMap {
+ let sm = SourceMap::new(FilePathMapping::empty());
+ sm.new_source_file(PathBuf::from("blork.rs").into(),
"first line.\nsecond line".to_string());
- cm.new_source_file(PathBuf::from("empty.rs").into(),
+ sm.new_source_file(PathBuf::from("empty.rs").into(),
String::new());
- cm.new_source_file(PathBuf::from("blork2.rs").into(),
+ sm.new_source_file(PathBuf::from("blork2.rs").into(),
"first line.\nsecond line".to_string());
- cm
+ sm
}
#[test]
fn t3() {
// Test lookup_byte_offset
- let cm = init_code_map();
+ let sm = init_source_map();
- let fmabp1 = cm.lookup_byte_offset(BytePos(23));
- assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
- assert_eq!(fmabp1.pos, BytePos(23));
+ let srcfbp1 = sm.lookup_byte_offset(BytePos(23));
+ assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into());
+ assert_eq!(srcfbp1.pos, BytePos(23));
- let fmabp1 = cm.lookup_byte_offset(BytePos(24));
- assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
- assert_eq!(fmabp1.pos, BytePos(0));
+ let srcfbp1 = sm.lookup_byte_offset(BytePos(24));
+ assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into());
+ assert_eq!(srcfbp1.pos, BytePos(0));
- let fmabp2 = cm.lookup_byte_offset(BytePos(25));
- assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
- assert_eq!(fmabp2.pos, BytePos(0));
+ let srcfbp2 = sm.lookup_byte_offset(BytePos(25));
+ assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into());
+ assert_eq!(srcfbp2.pos, BytePos(0));
}
#[test]
fn t4() {
// Test bytepos_to_file_charpos
- let cm = init_code_map();
+ let sm = init_source_map();
- let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
+ let cp1 = sm.bytepos_to_file_charpos(BytePos(22));
assert_eq!(cp1, CharPos(22));
- let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
+ let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
assert_eq!(cp2, CharPos(0));
}
#[test]
fn t5() {
// Test zero-length source_files.
- let cm = init_code_map();
+ let sm = init_source_map();
- let loc1 = cm.lookup_char_pos(BytePos(22));
+ let loc1 = sm.lookup_char_pos(BytePos(22));
assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
assert_eq!(loc1.line, 2);
assert_eq!(loc1.col, CharPos(10));
- let loc2 = cm.lookup_char_pos(BytePos(25));
+ let loc2 = sm.lookup_char_pos(BytePos(25));
assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
assert_eq!(loc2.line, 1);
assert_eq!(loc2.col, CharPos(0));
}
- fn init_code_map_mbc() -> SourceMap {
- let cm = SourceMap::new(FilePathMapping::empty());
+ fn init_source_map_mbc() -> SourceMap {
+ let sm = SourceMap::new(FilePathMapping::empty());
// € is a three byte utf8 char.
- cm.new_source_file(PathBuf::from("blork.rs").into(),
+ sm.new_source_file(PathBuf::from("blork.rs").into(),
"fir€st €€€€ line.\nsecond line".to_string());
- cm.new_source_file(PathBuf::from("blork2.rs").into(),
+ sm.new_source_file(PathBuf::from("blork2.rs").into(),
"first line€€.\n€ second line".to_string());
- cm
+ sm
}
#[test]
fn t6() {
// Test bytepos_to_file_charpos in the presence of multi-byte chars
- let cm = init_code_map_mbc();
+ let sm = init_source_map_mbc();
- let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
+ let cp1 = sm.bytepos_to_file_charpos(BytePos(3));
assert_eq!(cp1, CharPos(3));
- let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
+ let cp2 = sm.bytepos_to_file_charpos(BytePos(6));
assert_eq!(cp2, CharPos(4));
- let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
+ let cp3 = sm.bytepos_to_file_charpos(BytePos(56));
assert_eq!(cp3, CharPos(12));
- let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
+ let cp4 = sm.bytepos_to_file_charpos(BytePos(61));
assert_eq!(cp4, CharPos(15));
}
#[test]
fn t7() {
// Test span_to_lines for a span ending at the end of source_file
- let cm = init_code_map();
+ let sm = init_source_map();
let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
- let file_lines = cm.span_to_lines(span).unwrap();
+ let file_lines = sm.span_to_lines(span).unwrap();
assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
assert_eq!(file_lines.lines.len(), 1);
/// lines in the middle of a file.
#[test]
fn span_to_snippet_and_lines_spanning_multiple_lines() {
- let cm = SourceMap::new(FilePathMapping::empty());
+ let sm = SourceMap::new(FilePathMapping::empty());
let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
let selection = " \n ~~\n~~~\n~~~~~ \n \n";
- cm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
+ sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
let span = span_from_selection(inputtext, selection);
// check that we are extracting the text we thought we were extracting
- assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
+ assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
// check that span_to_lines gives us the complete result with the lines/cols we expected
- let lines = cm.span_to_lines(span).unwrap();
+ let lines = sm.span_to_lines(span).unwrap();
let expected = vec![
LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
#[test]
fn t8() {
// Test span_to_snippet for a span ending at the end of source_file
- let cm = init_code_map();
+ let sm = init_source_map();
let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
- let snippet = cm.span_to_snippet(span);
+ let snippet = sm.span_to_snippet(span);
assert_eq!(snippet, Ok("second line".to_string()));
}
#[test]
fn t9() {
// Test span_to_str for a span ending at the end of source_file
- let cm = init_code_map();
+ let sm = init_source_map();
let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
- let sstr = cm.span_to_string(span);
+ let sstr = sm.span_to_string(span);
assert_eq!(sstr, "blork.rs:2:1: 2:12");
}
/// Test failing to merge two spans on different lines
#[test]
fn span_merging_fail() {
- let cm = SourceMap::new(FilePathMapping::empty());
+ let sm = SourceMap::new(FilePathMapping::empty());
let inputtext = "bbbb BB\ncc CCC\n";
let selection1 = " ~~\n \n";
let selection2 = " \n ~~~\n";
- cm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
+ sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
let span1 = span_from_selection(inputtext, selection1);
let span2 = span_from_selection(inputtext, selection2);
- assert!(cm.merge_spans(span1, span2).is_none());
+ assert!(sm.merge_spans(span1, span2).is_none());
}
/// Returns the span corresponding to the `n`th occurrence of
with_globals(|| {
let output = Arc::new(Mutex::new(Vec::new()));
- let code_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
- code_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned());
+ let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
+ source_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned());
let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end);
let mut msp = MultiSpan::from_span(primary_span);
let span = make_span(&file_text, &span_label.start, &span_label.end);
msp.push_span_label(span, span_label.label.to_string());
println!("span: {:?} label: {:?}", span, span_label.label);
- println!("text: {:?}", code_map.span_to_snippet(span));
+ println!("text: {:?}", source_map.span_to_snippet(span));
}
let emitter = EmitterWriter::new(Box::new(Shared { data: output.clone() }),
- Some(code_map.clone()),
+ Some(source_map.clone()),
false,
false);
let handler = Handler::with_emitter(true, false, Box::new(emitter));
// it encounters. If that point is already outside the source_file, remove
// it again.
if let Some(&last_line_start) = lines.last() {
- let file_map_end = source_file_start_pos + BytePos::from_usize(src.len());
- assert!(file_map_end >= last_line_start);
- if last_line_start == file_map_end {
+ let source_file_end = source_file_start_pos + BytePos::from_usize(src.len());
+ assert!(source_file_end >= last_line_start);
+ if last_line_start == source_file_end {
lines.pop();
}
}
// used to be structural records. Better names, anyone?
#[derive(Debug)]
-pub struct SourceFileAndLine { pub fm: Lrc<SourceFile>, pub line: usize }
+pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
#[derive(Debug)]
-pub struct SourceFileAndBytePos { pub fm: Lrc<SourceFile>, pub pos: BytePos }
+pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct LineInfo {
}
// _____________________________________________________________________________
-// SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
+// SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
//
pub type FileLinesResult = Result<FileLines, SpanLinesError>;
pub enum SpanSnippetError {
IllFormedSpan(Span),
DistinctSources(DistinctSources),
- MalformedForCodemap(MalformedCodemapPositions),
+ MalformedForSourcemap(MalformedSourceMapPositions),
SourceNotAvailable { filename: FileName }
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
-pub struct MalformedCodemapPositions {
+pub struct MalformedSourceMapPositions {
pub name: FileName,
pub source_len: usize,
pub begin_pos: BytePos,
// The AST node for the (1 + y) expression generated by the macro will then
// take it's `lo` span bound from the `1` literal in the macro-defining file
// and it's `hi` bound from `y` in this file, which should be lower than the
- // `lo` and even lower than the lower bound of the FileMap it is supposedly
- // contained in because the FileMap for this file was allocated earlier than
- // the FileMap of the macro-defining file.
+ // `lo` and even lower than the lower bound of the SourceFile it is supposedly
+ // contained in because the SourceFile for this file was allocated earlier than
+ // the SourceFile of the macro-defining file.
return (x, add1!(y));
}
LL | match *s { sty(v) => v } //~ ERROR cannot move out
| ^
-error[E0507]: cannot move out of `s.0` which is behind a `&` reference
- --> $DIR/access-mode-in-closures.rs:19:24
- |
-LL | let _foo = unpack(|s| {
- | - help: consider changing this to be a mutable reference: `&mut sty`
-LL | // Test that `s` is moved here.
-LL | match *s { sty(v) => v } //~ ERROR cannot move out
- | ^
- | |
- | cannot move out of `s.0` which is behind a `&` reference
- | `s` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | *n; //~ ERROR: cannot move out of borrowed content
| ^^ cannot move out of borrowed content
-error[E0507]: cannot move out of `*n` which is behind a `&` reference
- --> $DIR/binop-move-semantics.rs:42:5
- |
-LL | let n = &y;
- | -- help: consider changing this to be a mutable reference: `&mut y`
-...
-LL | *n; //~ ERROR: cannot move out of borrowed content
- | ^^
- | |
- | cannot move out of `*n` which is behind a `&` reference
- | `n` is a `&` reference, so the data it refers to cannot be moved
-
error[E0502]: cannot borrow `f` as immutable because it is also borrowed as mutable
--> $DIR/binop-move-semantics.rs:64:5
|
| | immutable borrow later used here
| mutable borrow occurs here
-error: aborting due to 7 previous errors
+error: aborting due to 6 previous errors
Some errors occurred: E0382, E0502, E0507.
For more information about an error, try `rustc --explain E0382`.
+++ /dev/null
-error[E0507]: cannot move out of borrowed content
- --> $DIR/borrowck-fn-in-const-a.rs:19:16
- |
-LL | return *x //[ast]~ ERROR cannot move out of borrowed content [E0507]
- | ^^ cannot move out of borrowed content
-
-error[E0507]: cannot move out of `*x` which is behind a `&` reference
- --> $DIR/borrowck-fn-in-const-a.rs:19:16
- |
-LL | fn broken(x: &String) -> String {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | return *x //[ast]~ ERROR cannot move out of borrowed content [E0507]
- | ^^
- | |
- | cannot move out of `*x` which is behind a `&` reference
- | `x` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
-error[E0507]: cannot move out of `*__next` which is behind a `&` reference
- --> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:22:10
- |
-LL | for &a in x.iter() { //~ ERROR cannot move out
- | -^
- | ||
- | |cannot move out of `*__next` which is behind a `&` reference
- | |`__next` is a `&` reference, so the data it refers to cannot be moved
- | help: consider changing this to be a mutable reference: `&mut a`
-
error[E0507]: cannot move out of borrowed content
--> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:22:15
|
LL | for &a in x.iter() { //~ ERROR cannot move out
| ^
-error[E0507]: cannot move out of `*__next` which is behind a `&` reference
- --> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:28:10
- |
-LL | for &a in &f.a { //~ ERROR cannot move out
- | -^
- | ||
- | |cannot move out of `*__next` which is behind a `&` reference
- | |`__next` is a `&` reference, so the data it refers to cannot be moved
- | help: consider changing this to be a mutable reference: `&mut a`
-
error[E0507]: cannot move out of borrowed content
--> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:28:15
|
LL | for &a in &f.a { //~ ERROR cannot move out
| ^
-error[E0507]: cannot move out of `*__next` which is behind a `&` reference
- --> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:32:10
- |
-LL | for &a in x.iter() { //~ ERROR cannot move out
- | -^
- | ||
- | |cannot move out of `*__next` which is behind a `&` reference
- | |`__next` is a `&` reference, so the data it refers to cannot be moved
- | help: consider changing this to be a mutable reference: `&mut a`
-
error[E0507]: cannot move out of borrowed content
--> $DIR/borrowck-for-loop-correct-cmt-for-pattern.rs:32:15
|
LL | for &a in x.iter() { //~ ERROR cannot move out
| ^
-error: aborting due to 6 previous errors
+error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0507`.
LL | Box::new(|| x) //~ ERROR cannot move out of captured outer variable
| ^ cannot move out of captured variable in an `Fn` closure
-error[E0507]: cannot move out of `x`, as it is a captured variable in a `Fn` closure
- --> $DIR/borrowck-in-static.rs:15:17
- |
-LL | Box::new(|| x) //~ ERROR cannot move out of captured outer variable
- | ^
- | |
- | cannot move out of `x`, as it is a captured variable in a `Fn` closure
- | cannot move
- |
-help: consider changing this to accept closures that implement `FnMut`
- --> $DIR/borrowck-in-static.rs:15:14
- |
-LL | Box::new(|| x) //~ ERROR cannot move out of captured outer variable
- | ^^^^
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
| cannot move out of borrowed content
| help: consider removing the `*`: `y`
-error[E0507]: cannot move out of `*y` which is behind a `&` reference
- --> $DIR/borrowck-issue-2657-2.rs:17:18
- |
-LL | Some(ref y) => {
- | ----- help: consider changing this to be a mutable reference: `ref mut y`
-LL | let _b = *y; //~ ERROR cannot move out
- | ^^
- | |
- | cannot move out of `*y` which is behind a `&` reference
- | `y` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
It represents potential unsoundness in your code.
This warning will become a hard error in the future.
-warning[E0507]: cannot move out of `foo`, as it is immutable for the pattern guard
- --> $DIR/borrowck-migrate-to-nll.rs:35:17
- |
-LL | (|| { let bar = foo; bar.take() })();
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | cannot move out of `foo`, as it is immutable for the pattern guard
- | cannot move
- |
- = note: variables bound in patterns are immutable until the end of the pattern guard
- = warning: This error has been downgraded to a warning for backwards compatibility with previous releases.
- It represents potential unsoundness in your code.
- This warning will become a hard error in the future.
-
It represents potential unsoundness in your code.
This warning will become a hard error in the future.
-warning[E0507]: cannot move out of `foo`, as it is immutable for the pattern guard
- --> $DIR/borrowck-migrate-to-nll.rs:35:17
- |
-LL | (|| { let bar = foo; bar.take() })();
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | cannot move out of `foo`, as it is immutable for the pattern guard
- | cannot move
- |
- = note: variables bound in patterns are immutable until the end of the pattern guard
- = warning: This error has been downgraded to a warning for backwards compatibility with previous releases.
- It represents potential unsoundness in your code.
- This warning will become a hard error in the future.
-
LL | Foo::Foo2(num) => (),
| ^^^
-error[E0507]: cannot move out of `f.0` which is behind a `&` reference
- --> $DIR/borrowck-move-error-with-note.rs:23:19
- |
-LL | let f = &Foo::Foo1(box 1, box 2);
- | ------------------------ help: consider changing this to be a mutable reference: `&mut Foo::Foo1(box 1, box 2)`
-...
-LL | Foo::Foo1(num1,
- | ^^^^
- | |
- | cannot move out of `f.0` which is behind a `&` reference
- | `f` is a `&` reference, so the data it refers to cannot be moved
-
-error[E0507]: cannot move out of `f.1` which is behind a `&` reference
- --> $DIR/borrowck-move-error-with-note.rs:24:19
- |
-LL | let f = &Foo::Foo1(box 1, box 2);
- | ------------------------ help: consider changing this to be a mutable reference: `&mut Foo::Foo1(box 1, box 2)`
-...
-LL | num2) => (),
- | ^^^^
- | |
- | cannot move out of `f.1` which is behind a `&` reference
- | `f` is a `&` reference, so the data it refers to cannot be moved
-
-error[E0507]: cannot move out of `f.0` which is behind a `&` reference
- --> $DIR/borrowck-move-error-with-note.rs:25:19
- |
-LL | let f = &Foo::Foo1(box 1, box 2);
- | ------------------------ help: consider changing this to be a mutable reference: `&mut Foo::Foo1(box 1, box 2)`
-...
-LL | Foo::Foo2(num) => (),
- | ^^^
- | |
- | cannot move out of `f.0` which is behind a `&` reference
- | `f` is a `&` reference, so the data it refers to cannot be moved
-
error[E0509]: cannot move out of type `S`, which implements the `Drop` trait
--> $DIR/borrowck-move-error-with-note.rs:39:11
|
LL | n => {
| ^
-error[E0507]: cannot move out of `a.a` which is behind a `&` reference
- --> $DIR/borrowck-move-error-with-note.rs:59:9
- |
-LL | let a = &A { a: box 1 };
- | --------------- help: consider changing this to be a mutable reference: `&mut A { a: box 1 }`
-...
-LL | n => {
- | ^
- | |
- | cannot move out of `a.a` which is behind a `&` reference
- | `a` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 7 previous errors
+error: aborting due to 3 previous errors
Some errors occurred: E0507, E0509.
For more information about an error, try `rustc --explain E0507`.
| cannot move out of dereference of raw pointer
| help: consider removing the `*`: `x`
-error[E0507]: cannot move out of `*x` which is behind a `*const` pointer
- --> $DIR/borrowck-move-from-unsafe-ptr.rs:13:13
- |
-LL | unsafe fn foo(x: *const Box<isize>) -> Box<isize> {
- | ----------------- help: consider changing this to be a mutable pointer: `*mut std::boxed::Box<isize>`
-LL | let y = *x; //~ ERROR cannot move out of dereference of raw pointer
- | ^^
- | |
- | cannot move out of `*x` which is behind a `*const` pointer
- | `x` is a `*const` pointer, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | fn arg_item(&_x: &String) {}
| ^^
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-move-in-irrefut-pat.rs:16:14
- |
-LL | fn arg_item(&_x: &String) {}
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/borrowck-move-in-irrefut-pat.rs:21:11
|
LL | with(|&_x| ())
| ^^
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-move-in-irrefut-pat.rs:21:12
- |
-LL | with(|&_x| ())
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-move-in-irrefut-pat.rs:27:10
- |
-LL | let &_x = &"hi".to_string();
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/borrowck-move-in-irrefut-pat.rs:27:15
|
LL | let &_x = &"hi".to_string();
| ^^
-error: aborting due to 6 previous errors
+error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0507`.
LL | let _x = Rc::new(vec![1, 2]).into_iter();
| ^^^^^^^^^^^^^^^^^^^ cannot move out of an `Rc`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-move-out-of-overloaded-auto-deref.rs:17:14
- |
-LL | let _x = Rc::new(vec![1, 2]).into_iter();
- | ^^^^^^^^^^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
| cannot move out of an `Rc`
| help: consider removing the `*`: `Rc::new("hi".to_string())`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-move-out-of-overloaded-deref.rs:14:14
- |
-LL | let _x = *Rc::new("hi".to_string());
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
+++ /dev/null
-error[E0507]: cannot move out of static item
- --> $DIR/borrowck-move-out-of-static-item.rs:28:10
- |
-LL | test(BAR); //[ast]~ ERROR cannot move out of static item [E0507]
- | ^^^ cannot move out of static item
-
-error[E0507]: cannot move out of immutable static item `BAR`
- --> $DIR/borrowck-move-out-of-static-item.rs:28:10
- |
-LL | test(BAR); //[ast]~ ERROR cannot move out of static item [E0507]
- | ^^^
- | |
- | cannot move out of immutable static item `BAR`
- | cannot move
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
LL | Foo { string: b }] => {
|
-error[E0507]: cannot move out of `tail[..].string` which is behind a `&` reference
- --> $DIR/borrowck-move-out-of-vec-tail.rs:30:33
- |
-LL | [_, ref tail..] => {
- | -------- help: consider changing this to be a mutable reference: `ref mut tail`
-LL | match tail {
-LL | &[Foo { string: a },
- | ^
- | |
- | cannot move out of `tail[..].string` which is behind a `&` reference
- | `tail` is a `&` reference, so the data it refers to cannot be moved
-
-error[E0507]: cannot move out of `tail[..].string` which is behind a `&` reference
- --> $DIR/borrowck-move-out-of-vec-tail.rs:34:33
- |
-LL | [_, ref tail..] => {
- | -------- help: consider changing this to be a mutable reference: `ref mut tail`
-...
-LL | Foo { string: b }] => {
- | ^
- | |
- | cannot move out of `tail[..].string` which is behind a `&` reference
- | `tail` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 3 previous errors
+error: aborting due to previous error
-Some errors occurred: E0507, E0508.
-For more information about an error, try `rustc --explain E0507`.
+For more information about this error, try `rustc --explain E0508`.
| cannot move out of borrowed content
| help: consider borrowing here: `&v[0]`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/borrowck-overloaded-index-move-from-vec.rs:30:15
- |
-LL | let bad = v[0];
- | ^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | let opt = a.iter().enumerate().find(|(_, &s)| {
| ^
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-51415.rs:16:47
- |
-LL | let opt = a.iter().enumerate().find(|(_, &s)| {
- | ^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
+++ /dev/null
-error[E0507]: cannot move out of borrowed content
- --> $DIR/move-in-static-initializer-issue-38520.rs:25:23
- |
-LL | static Y: usize = get(*&X); //[ast]~ ERROR E0507
- | ^^^ cannot move out of borrowed content
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/move-in-static-initializer-issue-38520.rs:25:23
- |
-LL | static Y: usize = get(*&X); //[ast]~ ERROR E0507
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of borrowed content
- --> $DIR/move-in-static-initializer-issue-38520.rs:27:22
- |
-LL | const Z: usize = get(*&X); //[ast]~ ERROR E0507
- | ^^^ cannot move out of borrowed content
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/move-in-static-initializer-issue-38520.rs:27:22
- |
-LL | const Z: usize = get(*&X); //[ast]~ ERROR E0507
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 4 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
LL | y.into_iter();
| ^ cannot move out of captured variable in an `Fn` closure
-error[E0507]: cannot move out of `y`, as it is a captured variable in a `Fn` closure
- --> $DIR/unboxed-closures-move-upvar-from-non-once-ref-closure.rs:21:9
- |
-LL | y.into_iter();
- | ^
- | |
- | cannot move out of `y`, as it is a captured variable in a `Fn` closure
- | cannot move
- |
-help: consider changing this to accept closures that implement `FnMut`
- --> $DIR/unboxed-closures-move-upvar-from-non-once-ref-closure.rs:20:10
- |
-LL | call(|| {
- | __________^
-LL | | y.into_iter();
-LL | | //~^ ERROR cannot move out of captured outer variable in an `Fn` closure
-LL | | });
- | |_____^
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | &E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
| ^^^^^^^^^^
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/by-move-pattern-binding.rs:26:17
- |
-LL | &E::Bar(identifier) => f(identifier.clone()) //~ ERROR cannot move
- | ^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
| cannot move out of static item
| help: consider borrowing here: `&x`
-error[E0507]: cannot move out of immutable static item `x`
- --> $DIR/check-static-values-constraints.rs:120:45
- |
-LL | let y = { static x: Box<isize> = box 3; x };
- | ^
- | |
- | cannot move out of immutable static item `x`
- | cannot move
-
error[E0010]: allocations are not allowed in statics
--> $DIR/check-static-values-constraints.rs:120:38
|
LL | let y = { static x: Box<isize> = box 3; x };
| ^^^^^ allocation not allowed in statics
-error: aborting due to 11 previous errors
+error: aborting due to 10 previous errors
Some errors occurred: E0010, E0015, E0493, E0507.
For more information about an error, try `rustc --explain E0010`.
LL | S[0];
| ^^^^ cannot move out of borrowed content
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/dst-index.rs:41:5
- |
-LL | S[0];
- | ^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/dst-index.rs:44:5
|
LL | T[0];
| ^^^^ cannot move out of borrowed content
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/dst-index.rs:44:5
- |
-LL | T[0];
- | ^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 6 previous errors
+error: aborting due to 4 previous errors
Some errors occurred: E0161, E0507.
For more information about an error, try `rustc --explain E0161`.
LL | let _x: Box<str> = box *"hello world";
| ^^^^^^^^^^^^^^ cannot move out of borrowed content
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/dst-rvalue.rs:16:28
- |
-LL | let _x: Box<str> = box *"hello world";
- | ^^^^^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0508]: cannot move out of type `[isize]`, a non-copy slice
--> $DIR/dst-rvalue.rs:21:32
|
LL | let _x: Box<[isize]> = box *array;
| ^^^^^^ cannot move out of here
-error[E0507]: cannot move out of `*array` which is behind a `&` reference
- --> $DIR/dst-rvalue.rs:21:32
- |
-LL | let array: &[isize] = &[1, 2, 3];
- | ---------- help: consider changing this to be a mutable reference: `&mut [1, 2, 3]`
-LL | let _x: Box<[isize]> = box *array;
- | ^^^^^^
- | |
- | cannot move out of `*array` which is behind a `&` reference
- | `array` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 6 previous errors
+error: aborting due to 4 previous errors
Some errors occurred: E0161, E0507, E0508.
For more information about an error, try `rustc --explain E0161`.
+++ /dev/null
-error[E0507]: cannot move out of borrowed content
- --> $DIR/E0507.rs:22:5
- |
-LL | x.borrow().nothing_is_true(); //~ ERROR E0507
- | ^^^^^^^^^^ cannot move out of borrowed content
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/E0507.rs:22:5
- |
-LL | x.borrow().nothing_is_true(); //~ ERROR E0507
- | ^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
LL | (&[hd1, ..], &[hd2, ..])
| ^^^
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-12567.rs:16:17
- |
-LL | (&[], &[hd, ..]) | (&[hd, ..], &[])
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-12567.rs:16:31
- |
-LL | (&[], &[hd, ..]) | (&[hd, ..], &[])
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-12567.rs:20:12
- |
-LL | (&[hd1, ..], &[hd2, ..])
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-12567.rs:20:24
- |
-LL | (&[hd1, ..], &[hd2, ..])
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 6 previous errors
+error: aborting due to 2 previous errors
-Some errors occurred: E0507, E0508.
-For more information about an error, try `rustc --explain E0507`.
+For more information about this error, try `rustc --explain E0508`.
| cannot move out of static item
| help: consider borrowing here: `&FOO`
-error[E0507]: cannot move out of immutable static item `FOO`
- --> $DIR/issue-17718-static-move.rs:16:14
- |
-LL | let _a = FOO; //~ ERROR: cannot move out of static item
- | ^^^
- | |
- | cannot move out of immutable static item `FOO`
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
| cannot move out of borrowed content
| help: consider removing the `*`: `imm_ref()`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-20801.rs:39:22
- |
-LL | let b = unsafe { *imm_ref() };
- | ^^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of dereference of raw pointer
--> $DIR/issue-20801.rs:42:22
|
| cannot move out of dereference of raw pointer
| help: consider removing the `*`: `const_ptr()`
-error[E0507]: cannot move out of data in a `*const` pointer
- --> $DIR/issue-20801.rs:45:22
- |
-LL | let d = unsafe { *const_ptr() };
- | ^^^^^^^^^^^^
- | |
- | cannot move out of data in a `*const` pointer
- | cannot move
-
-error: aborting due to 6 previous errors
+error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0507`.
LL | self.tokens //~ ERROR cannot move out of borrowed content
| ^^^^^^^^^^^ cannot move out of borrowed content
-error[E0507]: cannot move out of `self.tokens` which is behind a `&` reference
- --> $DIR/issue-2590.rs:22:9
- |
-LL | fn parse(&self) -> Vec<isize> {
- | ----- help: consider changing this to be a mutable reference: `&mut self`
-LL | self.tokens //~ ERROR cannot move out of borrowed content
- | ^^^^^^^^^^^
- | |
- | cannot move out of `self.tokens` which is behind a `&` reference
- | `self` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | &X(*Y)
| ^^ cannot move out of here
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-30355.rs:15:8
- |
-LL | &X(*Y)
- | ^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 4 previous errors
+error: aborting due to 3 previous errors
-Some errors occurred: E0161, E0507, E0508.
+Some errors occurred: E0161, E0508.
For more information about an error, try `rustc --explain E0161`.
| cannot move out of borrowed content
| help: consider borrowing here: `&f.v[0]`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-40402-1.rs:19:13
- |
-LL | let e = f.v[0]; //~ ERROR cannot move out of indexed content
- | ^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-40402-2.rs:15:10
- |
-LL | let (a, b) = x[0]; //~ ERROR cannot move out of indexed content
- | ^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/issue-40402-2.rs:15:13
- |
-LL | let (a, b) = x[0]; //~ ERROR cannot move out of indexed content
- | ^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/issue-40402-2.rs:15:18
|
LL | let (a, b) = x[0]; //~ ERROR cannot move out of indexed content
| ^ ^
-error: aborting due to 3 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | id(Box::new(|| *v))
| ^^ cannot move out of captured variable in an `FnMut` closure
-error[E0507]: cannot move out of `*v` which is behind a `&` reference
- --> $DIR/issue-4335.rs:16:20
- |
-LL | id(Box::new(|| *v))
- | ^^
- | |
- | cannot move out of `*v` which is behind a `&` reference
- | cannot move
-
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--> $DIR/issue-4335.rs:16:17
|
LL | id(Box::new(move || *v))
| ^^^^^^^
-error: aborting due to 3 previous errors
+error: aborting due to 2 previous errors
Some errors occurred: E0373, E0507.
For more information about an error, try `rustc --explain E0373`.
+++ /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.
-
-// run-rustfix
-
-#![allow(dead_code)]
-
-fn missing_discourses() -> Result<isize, ()> {
- Ok(1)
-}
-
-fn forbidden_narratives() -> Result<isize, ()> {
- Ok(missing_discourses()?)
- //~^ ERROR try expression alternatives have incompatible types
- //~| HELP try wrapping with a success variant
-}
-
-fn main() {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// run-rustfix
-
#![allow(dead_code)]
fn missing_discourses() -> Result<isize, ()> {
fn forbidden_narratives() -> Result<isize, ()> {
missing_discourses()?
//~^ ERROR try expression alternatives have incompatible types
- //~| HELP try wrapping with a success variant
}
fn main() {}
error[E0308]: try expression alternatives have incompatible types
- --> $DIR/issue-51632-try-desugar-incompatible-types.rs:20:5
+ --> $DIR/issue-51632-try-desugar-incompatible-types.rs:18:5
|
LL | missing_discourses()?
- | ^^^^^^^^^^^^^^^^^^^^^
- | |
- | expected enum `std::result::Result`, found isize
- | help: try wrapping with a success variant: `Ok(missing_discourses()?)`
+ | ^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found isize
|
= note: expected type `std::result::Result<isize, ()>`
found type `isize`
// We want to suggest the properly-balanced expression `1 / (2 + 3)`, not
// the malformed `1 / (2 + 3`
let _a = (1 / (2 + 3));
+ f();
+}
+
+fn f() -> bool {
+ loop {
+ if (break { return true }) {
+ }
+ }
+ false
}
LL | box E::Bar(x) => println!("{}", x.to_string()),
| ^
-error[E0507]: cannot move out of `hellothere.x.0` which is behind a `&` reference
- --> $DIR/moves-based-on-type-block-bad.rs:37:28
- |
-LL | f(&s, |hellothere| {
- | ---------- help: consider changing this to be a mutable reference: `&mut S`
-...
-LL | box E::Bar(x) => println!("{}", x.to_string()),
- | ^
- | |
- | cannot move out of `hellothere.x.0` which is behind a `&` reference
- | `hellothere` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
LL | let _f = to_fn(|| test(i)); //~ ERROR cannot move out
| ^ cannot move out of captured variable in an `Fn` closure
-error[E0507]: cannot move out of `i`, as it is a captured variable in a `Fn` closure
- --> $DIR/moves-based-on-type-move-out-of-closure-env-issue-1965.rs:21:28
- |
-LL | let _f = to_fn(|| test(i)); //~ ERROR cannot move out
- | ^
- | |
- | cannot move out of `i`, as it is a captured variable in a `Fn` closure
- | cannot move
- |
-help: consider changing this to accept closures that implement `FnMut`
- --> $DIR/moves-based-on-type-move-out-of-closure-env-issue-1965.rs:21:20
- |
-LL | let _f = to_fn(|| test(i)); //~ ERROR cannot move out
- | ^^^^^^^^^^
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:15:15
- |
-LL | pub fn deref(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | let x = { *r }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
error[E0507]: cannot move out of borrowed content
--> $DIR/cannot-move-block-spans.rs:16:22
|
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:16:22
- |
-LL | pub fn deref(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | let x = { *r }; //~ ERROR
-LL | let y = unsafe { *r }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
error[E0507]: cannot move out of borrowed content
--> $DIR/cannot-move-block-spans.rs:17:26
|
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:17:26
- |
-LL | pub fn deref(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-...
-LL | let z = loop { break *r; }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
error[E0508]: cannot move out of type `[std::string::String; 2]`, a non-copy array
--> $DIR/cannot-move-block-spans.rs:21:15
|
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:27:38
- |
-LL | pub fn additional_statement_cases(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | let x = { let mut u = 0; u += 1; *r }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
error[E0507]: cannot move out of borrowed content
--> $DIR/cannot-move-block-spans.rs:28:45
|
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:28:45
- |
-LL | pub fn additional_statement_cases(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | let x = { let mut u = 0; u += 1; *r }; //~ ERROR
-LL | let y = unsafe { let mut u = 0; u += 1; *r }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
error[E0507]: cannot move out of borrowed content
--> $DIR/cannot-move-block-spans.rs:29:49
|
| cannot move out of borrowed content
| help: consider removing the `*`: `r`
-error[E0507]: cannot move out of `*r` which is behind a `&` reference
- --> $DIR/cannot-move-block-spans.rs:29:49
- |
-LL | pub fn additional_statement_cases(r: &String) {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-...
-LL | let z = loop { let mut u = 0; u += 1; break *r; u += 2; }; //~ ERROR
- | ^^
- | |
- | cannot move out of `*r` which is behind a `&` reference
- | `r` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 15 previous errors
+error: aborting due to 9 previous errors
Some errors occurred: E0507, E0508.
For more information about an error, try `rustc --explain E0507`.
It represents potential unsoundness in your code.
This warning will become a hard error in the future.
-warning[E0507]: cannot move out of `foo`, as it is immutable for the pattern guard
- --> $DIR/match-guards-always-borrow.rs:23:13
- |
-LL | (|| { let bar = foo; bar.take() })();
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | cannot move out of `foo`, as it is immutable for the pattern guard
- | cannot move
- |
- = note: variables bound in patterns are immutable until the end of the pattern guard
- = warning: This error has been downgraded to a warning for backwards compatibility with previous releases.
- It represents potential unsoundness in your code.
- This warning will become a hard error in the future.
-
error: compilation successful
--> $DIR/match-guards-always-borrow.rs:57:1
|
+++ /dev/null
-error[E0507]: cannot move out of static item
- --> $DIR/static-items-cant-move.rs:28:10
- |
-LL | test(BAR); //~ ERROR cannot move out of static item
- | ^^^ cannot move out of static item
-
-error[E0507]: cannot move out of immutable static item `BAR`
- --> $DIR/static-items-cant-move.rs:28:10
- |
-LL | test(BAR); //~ ERROR cannot move out of static item
- | ^^^
- | |
- | cannot move out of immutable static item `BAR`
- | cannot move
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
| cannot move out of borrowed content
| help: consider removing the `*`: `&x`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/std-uncopyable-atomics.rs:19:13
- |
-LL | let x = *&x; //~ ERROR: cannot move out of borrowed content
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/std-uncopyable-atomics.rs:21:13
|
| cannot move out of borrowed content
| help: consider removing the `*`: `&x`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/std-uncopyable-atomics.rs:21:13
- |
-LL | let x = *&x; //~ ERROR: cannot move out of borrowed content
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/std-uncopyable-atomics.rs:23:13
|
| cannot move out of borrowed content
| help: consider removing the `*`: `&x`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/std-uncopyable-atomics.rs:23:13
- |
-LL | let x = *&x; //~ ERROR: cannot move out of borrowed content
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
error[E0507]: cannot move out of borrowed content
--> $DIR/std-uncopyable-atomics.rs:25:13
|
| cannot move out of borrowed content
| help: consider removing the `*`: `&x`
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/std-uncopyable-atomics.rs:25:13
- |
-LL | let x = *&x; //~ ERROR: cannot move out of borrowed content
- | ^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 8 previous errors
+error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0507`.
+++ /dev/null
-error[E0507]: cannot move out of borrowed content
- --> $DIR/trivial-bounds-leak-copy.rs:19:5
- |
-LL | *t //~ ERROR
- | ^^ cannot move out of borrowed content
-
-error[E0507]: cannot move out of `*t` which is behind a `&` reference
- --> $DIR/trivial-bounds-leak-copy.rs:19:5
- |
-LL | fn move_out_string(t: &String) -> String {
- | ------- help: consider changing this to be a mutable reference: `&mut std::string::String`
-LL | *t //~ ERROR
- | ^^
- | |
- | cannot move out of `*t` which is behind a `&` reference
- | `t` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0507`.
LL | let f = to_fn(|| drop(x)); //~ ERROR cannot move
| ^ cannot move out of captured variable in an `Fn` closure
-error[E0507]: cannot move out of `x`, as it is a captured variable in a `Fn` closure
- --> $DIR/unboxed-closure-illegal-move.rs:25:31
- |
-LL | let f = to_fn(|| drop(x)); //~ ERROR cannot move
- | ^
- | |
- | cannot move out of `x`, as it is a captured variable in a `Fn` closure
- | cannot move
- |
-help: consider changing this to accept closures that implement `FnMut`
- --> $DIR/unboxed-closure-illegal-move.rs:25:23
- |
-LL | let f = to_fn(|| drop(x)); //~ ERROR cannot move
- | ^^^^^^^^^^
-
error[E0507]: cannot move out of captured variable in an `FnMut` closure
--> $DIR/unboxed-closure-illegal-move.rs:29:35
|
LL | let f = to_fn(move || drop(x)); //~ ERROR cannot move
| ^ cannot move out of captured variable in an `Fn` closure
-error[E0507]: cannot move out of `x`, as it is a captured variable in a `Fn` closure
- --> $DIR/unboxed-closure-illegal-move.rs:38:36
- |
-LL | let f = to_fn(move || drop(x)); //~ ERROR cannot move
- | ^
- | |
- | cannot move out of `x`, as it is a captured variable in a `Fn` closure
- | cannot move
- |
-help: consider changing this to accept closures that implement `FnMut`
- --> $DIR/unboxed-closure-illegal-move.rs:38:23
- |
-LL | let f = to_fn(move || drop(x)); //~ ERROR cannot move
- | ^^^^^^^^^^^^^^^
-
error[E0507]: cannot move out of captured variable in an `FnMut` closure
--> $DIR/unboxed-closure-illegal-move.rs:42:40
|
LL | let f = to_fn_mut(move || drop(x)); //~ ERROR cannot move
| ^ cannot move out of captured variable in an `FnMut` closure
-error: aborting due to 6 previous errors
+error: aborting due to 4 previous errors
For more information about this error, try `rustc --explain E0507`.
LL | !*n; //~ ERROR: cannot move out of borrowed content
| ^^ cannot move out of borrowed content
-error[E0507]: cannot move out of `*n` which is behind a `&` reference
- --> $DIR/unop-move-semantics.rs:36:6
- |
-LL | let n = &y;
- | -- help: consider changing this to be a mutable reference: `&mut y`
-...
-LL | !*n; //~ ERROR: cannot move out of borrowed content
- | ^^
- | |
- | cannot move out of `*n` which is behind a `&` reference
- | `n` is a `&` reference, so the data it refers to cannot be moved
-
-error: aborting due to 4 previous errors
+error: aborting due to 3 previous errors
Some errors occurred: E0382, E0507.
For more information about an error, try `rustc --explain E0382`.
LL | udrop::<[u8]>(foo()[..]);
| ^^^^^^^^^ cannot move out of here
-error[E0507]: cannot move out of data in a `&` reference
- --> $DIR/unsized-exprs2.rs:22:19
- |
-LL | udrop::<[u8]>(foo()[..]);
- | ^^^^^^^^^
- | |
- | cannot move out of data in a `&` reference
- | cannot move
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
-Some errors occurred: E0507, E0508.
-For more information about an error, try `rustc --explain E0507`.
+For more information about this error, try `rustc --explain E0508`.