Small nits to make couple of tests pass on mips targets.
# rustc to execute.
#lld = false
+# Whether to deny warnings in crates
+#deny-warnings = true
+
# =============================================================================
# Options for specific targets
#
cmd.arg("--color=always");
}
+ if env::var_os("RUSTC_DENY_WARNINGS").is_some() {
+ cmd.arg("-Dwarnings");
+ }
+
if verbose > 1 {
eprintln!("rustc command: {:?}", cmd);
eprintln!("sysroot: {:?}", sysroot);
cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
+ // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
+ if self.config.deny_warnings && !(mode == Mode::Libstd && stage == 0) {
+ cargo.env("RUSTC_DENY_WARNINGS", "1");
+ }
+
// Throughout the build Cargo can execute a number of build scripts
// compiling C/C++ code and we need to pass compilers, archivers, flags, etc
// obtained previously to those build scripts.
pub incremental: bool,
pub dry_run: bool,
+ pub deny_warnings: bool,
+
// llvm codegen options
pub llvm_enabled: bool,
pub llvm_assertions: bool,
codegen_backends_dir: Option<String>,
wasm_syscall: Option<bool>,
lld: Option<bool>,
+ deny_warnings: Option<bool>,
}
/// TOML representation of how each build target is configured.
config.test_miri = false;
config.rust_codegen_backends = vec![INTERNER.intern_str("llvm")];
config.rust_codegen_backends_dir = "codegen-backends".to_owned();
+ config.deny_warnings = true;
// set by bootstrap.py
config.src = env::var_os("SRC").map(PathBuf::from).expect("'SRC' to be set");
config.incremental = flags.incremental;
config.dry_run = flags.dry_run;
config.keep_stage = flags.keep_stage;
+ if let Some(value) = flags.warnings {
+ config.deny_warnings = value;
+ }
if config.dry_run {
let dir = config.out.join("tmp-dry-run");
config.rustc_default_linker = rust.default_linker.clone();
config.musl_root = rust.musl_root.clone().map(PathBuf::from);
config.save_toolstates = rust.save_toolstates.clone().map(PathBuf::from);
+ set(&mut config.deny_warnings, rust.deny_warnings.or(flags.warnings));
if let Some(ref backends) = rust.codegen_backends {
config.rust_codegen_backends = backends.iter()
pub exclude: Vec<PathBuf>,
pub rustc_error_format: Option<String>,
pub dry_run: bool,
+
+ // true => deny
+ pub warnings: Option<bool>,
}
pub enum Subcommand {
opts.optopt("", "src", "path to the root of the rust checkout", "DIR");
opts.optopt("j", "jobs", "number of jobs to run in parallel", "JOBS");
opts.optflag("h", "help", "print this help message");
+ opts.optopt("", "warnings", "if value is deny, will deny warnings, otherwise use default",
+ "VALUE");
opts.optopt("", "error-format", "rustc error format", "FORMAT");
// fn usage()
incremental: matches.opt_present("incremental"),
exclude: split(matches.opt_strs("exclude"))
.into_iter().map(|p| p.into()).collect::<Vec<_>>(),
+ warnings: matches.opt_str("warnings").map(|v| v == "deny"),
}
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
use std::fs::File;
use std::path::{Path, PathBuf};
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(rand)]
#![feature(repr_simd)]
#![feature(slice_sort_by_cached_key)]
test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![no_std]
#![needs_allocator]
-#![deny(warnings)]
#![deny(missing_debug_implementations)]
#![cfg_attr(test, allow(deprecated))] // rand
let sz_usize = mem::size_of::<(K, usize)>();
let len = self.len();
+ if len < 2 { return }
if sz_u8 < sz_u16 && len <= ( u8::MAX as usize) { return sort_by_key!( u8, self, f) }
if sz_u16 < sz_u32 && len <= (u16::MAX as usize) { return sort_by_key!(u16, self, f) }
if sz_u32 < sz_usize && len <= (u32::MAX as usize) { return sort_by_key!(u32, self, f) }
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(allocator_api)]
#![feature(alloc_system)]
#![feature(attr_literals)]
reason = "this library is unlikely to be stabilized in its current \
form or name",
issue = "27783")]
-#![deny(warnings)]
#![feature(alloc_system)]
#![feature(libc)]
#![feature(linkage)]
#![no_std]
#![allow(unused_attributes)]
-#![deny(warnings)]
#![unstable(feature = "alloc_system",
reason = "this library is unlikely to be stabilized in its current \
form or name",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
test(no_crate_inject, attr(deny(warnings))))]
-#![deny(warnings)]
#![feature(alloc)]
#![feature(core_intrinsics)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(flt2dec)]
#![feature(test)]
#![no_core]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
-#![deny(warnings)]
#![feature(allow_internal_unstable)]
#![feature(asm)]
/// # Examples
///
/// ```rust
- /// #![feature(option_filter)]
- ///
/// fn is_even(n: &i32) -> bool {
/// n % 2 == 0
/// }
/// assert_eq!(Some(4).filter(is_even), Some(4));
/// ```
#[inline]
- #[unstable(feature = "option_filter", issue = "45860")]
+ #[stable(feature = "option_filter", since = "1.27.0")]
pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
if let Some(x) = self {
if predicate(&x) {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(ascii_ctype)]
#![feature(box_syntax)]
#![feature(core_float)]
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/",
test(attr(deny(warnings))))]
-#![deny(warnings)]
pub use self::Piece::*;
pub use self::Position::*;
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
test(attr(allow(unused_variables), deny(warnings))))]
-#![deny(warnings)]
#![feature(str_escape)]
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
-#![deny(warnings)]
#![panic_runtime]
#![allow(unused_features)]
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
-#![deny(warnings)]
#![feature(alloc)]
#![feature(core_intrinsics)]
//! See [the book](../book/first-edition/procedural-macros.html) for more.
#![stable(feature = "proc_macro_lib", since = "1.15.0")]
-#![deny(warnings)]
#![deny(missing_docs)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(test)]
extern crate test;
use util::nodemap::{DefIdMap, FxHashMap};
use arena::TypedArena;
-use std::cell::RefCell;
use std::io;
use ty::TyCtxt;
+use rustc_data_structures::sync::Lock;
+
pub mod blocks;
mod collector;
mod def_collector;
definitions: &'hir Definitions,
/// Bodies inlined from other crates are cached here.
- inlined_bodies: RefCell<DefIdMap<&'hir Body>>,
+ inlined_bodies: Lock<DefIdMap<&'hir Body>>,
/// The reverse mapping of `node_to_hir_id`.
hir_to_node_id: FxHashMap<HirId, NodeId>,
}
pub fn intern_inlined_body(&self, def_id: DefId, body: Body) -> &'hir Body {
+ let mut inlined_bodies = self.inlined_bodies.borrow_mut();
+ if let Some(&b) = inlined_bodies.get(&def_id) {
+ debug_assert_eq!(&body, b);
+ return b;
+ }
let body = self.forest.inlined_bodies.alloc(body);
- self.inlined_bodies.borrow_mut().insert(def_id, body);
+ inlined_bodies.insert(def_id, body);
body
}
map,
hir_to_node_id,
definitions,
- inlined_bodies: RefCell::new(DefIdMap()),
+ inlined_bodies: Lock::new(DefIdMap()),
};
hir_id_validator::check_crate(&map);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use syntax::ast;
+use syntax::symbol::InternedString;
use syntax_pos::Span;
use ty::{self, Ty};
MiscVariable(Span),
NormalizeProjectionType(Span),
TypeInference(Span),
- TypeParameterDefinition(Span, ast::Name),
+ TypeParameterDefinition(Span, InternedString),
/// one of the upvars or closure kind parameters in a `ClosureSubsts`
/// (before it has been determined)
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]
+#![feature(slice_sort_by_cached_key)]
#![feature(specialization)]
#![feature(unboxed_closures)]
#![feature(trace_macros)]
pub use self::Level::*;
pub use self::LintSource::*;
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{self, Lrc};
use errors::{DiagnosticBuilder, DiagnosticId};
use hir::def_id::{CrateNum, LOCAL_CRATE};
}
/// A lint pass boxed up as a trait object.
-pub type EarlyLintPassObject = Box<dyn EarlyLintPass + 'static>;
-pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + 'static>;
+pub type EarlyLintPassObject = Box<dyn EarlyLintPass + sync::Send + sync::Sync + 'static>;
+pub type LateLintPassObject = Box<dyn for<'a, 'tcx> LateLintPass<'a, 'tcx> + sync::Send
+ + sync::Sync + 'static>;
/// Identifies a lint known to the compiler.
#[derive(Clone, Copy, Debug)]
.collect::<Vec<_>>();
let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
Lrc::make_mut(&mut ordering).reverse();
- libs.sort_by_key(|&(a, _)| {
+ libs.sort_by_cached_key(|&(a, _)| {
ordering.iter().position(|x| *x == a)
});
libs
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::cell::{Ref, RefCell};
use rustc_data_structures::indexed_vec::IndexVec;
+use rustc_data_structures::sync::{RwLock, ReadGuard};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
StableHasherResult};
use ich::StableHashingContext;
#[derive(Clone, Debug)]
pub struct Cache {
- predecessors: RefCell<Option<IndexVec<BasicBlock, Vec<BasicBlock>>>>
+ predecessors: RwLock<Option<IndexVec<BasicBlock, Vec<BasicBlock>>>>
}
impl Cache {
pub fn new() -> Self {
Cache {
- predecessors: RefCell::new(None)
+ predecessors: RwLock::new(None)
}
}
*self.predecessors.borrow_mut() = None;
}
- pub fn predecessors(&self, mir: &Mir) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
+ pub fn predecessors(&self, mir: &Mir) -> ReadGuard<IndexVec<BasicBlock, Vec<BasicBlock>>> {
if self.predecessors.borrow().is_none() {
*self.predecessors.borrow_mut() = Some(calculate_predecessors(mir));
}
- Ref::map(self.predecessors.borrow(), |p| p.as_ref().unwrap())
+ ReadGuard::map(self.predecessors.borrow(), |p| p.as_ref().unwrap())
}
}
use std::slice;
use hir::{self, InlineAsm};
use std::borrow::{Cow};
-use std::cell::Ref;
+use rustc_data_structures::sync::ReadGuard;
use std::fmt::{self, Debug, Formatter, Write};
use std::{iter, mem, u32};
use std::ops::{Index, IndexMut};
}
#[inline]
- pub fn predecessors(&self) -> Ref<IndexVec<BasicBlock, Vec<BasicBlock>>> {
+ pub fn predecessors(&self) -> ReadGuard<IndexVec<BasicBlock, Vec<BasicBlock>>> {
self.cache.predecessors(self)
}
#[inline]
- pub fn predecessors_for(&self, bb: BasicBlock) -> Ref<Vec<BasicBlock>> {
- Ref::map(self.predecessors(), |p| &p[bb])
+ pub fn predecessors_for(&self, bb: BasicBlock) -> ReadGuard<Vec<BasicBlock>> {
+ ReadGuard::map(self.predecessors(), |p| &p[bb])
}
#[inline]
}
for param in generics.types.iter() {
- let name = param.name.as_str().to_string();
+ let name = param.name.to_string();
let ty = trait_ref.substs.type_for_def(param);
let ty_str = ty.to_string();
flags.push((name.clone(),
let trait_str = tcx.item_path_str(trait_ref.def_id);
let generics = tcx.generics_of(trait_ref.def_id);
let generic_map = generics.types.iter().map(|param| {
- (param.name.as_str().to_string(),
+ (param.name.to_string(),
trait_ref.substs.type_for_def(param).to_string())
}).collect::<FxHashMap<String, String>>();
StableVec};
use arena::{TypedArena, DroplessArena};
use rustc_data_structures::indexed_vec::IndexVec;
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{Lrc, Lock};
use std::any::Any;
use std::borrow::Borrow;
use std::cell::{Cell, RefCell};
use std::sync::mpsc;
use std::sync::Arc;
use syntax::abi;
-use syntax::ast::{self, Name, NodeId};
+use syntax::ast::{self, NodeId};
use syntax::attr;
use syntax::codemap::MultiSpan;
use syntax::feature_gate;
-use syntax::symbol::{Symbol, keywords};
+use syntax::symbol::{Symbol, keywords, InternedString};
use syntax_pos::Span;
use hir;
/// Specifically use a speedy hash algorithm for these hash sets,
/// they're accessed quite often.
- type_: RefCell<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
- type_list: RefCell<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
- substs: RefCell<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
- canonical_var_infos: RefCell<FxHashSet<Interned<'tcx, Slice<CanonicalVarInfo>>>>,
- region: RefCell<FxHashSet<Interned<'tcx, RegionKind>>>,
- existential_predicates: RefCell<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
- predicates: RefCell<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
- const_: RefCell<FxHashSet<Interned<'tcx, Const<'tcx>>>>,
+ type_: Lock<FxHashSet<Interned<'tcx, TyS<'tcx>>>>,
+ type_list: Lock<FxHashSet<Interned<'tcx, Slice<Ty<'tcx>>>>>,
+ substs: Lock<FxHashSet<Interned<'tcx, Substs<'tcx>>>>,
+ canonical_var_infos: Lock<FxHashSet<Interned<'tcx, Slice<CanonicalVarInfo>>>>,
+ region: Lock<FxHashSet<Interned<'tcx, RegionKind>>>,
+ existential_predicates: Lock<FxHashSet<Interned<'tcx, Slice<ExistentialPredicate<'tcx>>>>>,
+ predicates: Lock<FxHashSet<Interned<'tcx, Slice<Predicate<'tcx>>>>>,
+ const_: Lock<FxHashSet<Interned<'tcx, Const<'tcx>>>>,
}
impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> {
CtxtInterners {
- arena,
- type_: RefCell::new(FxHashSet()),
- type_list: RefCell::new(FxHashSet()),
- substs: RefCell::new(FxHashSet()),
- region: RefCell::new(FxHashSet()),
- existential_predicates: RefCell::new(FxHashSet()),
- canonical_var_infos: RefCell::new(FxHashSet()),
- predicates: RefCell::new(FxHashSet()),
- const_: RefCell::new(FxHashSet()),
+ arena: arena,
+ type_: Lock::new(FxHashSet()),
+ type_list: Lock::new(FxHashSet()),
+ substs: Lock::new(FxHashSet()),
+ canonical_var_infos: Lock::new(FxHashSet()),
+ region: Lock::new(FxHashSet()),
+ existential_predicates: Lock::new(FxHashSet()),
+ predicates: Lock::new(FxHashSet()),
+ const_: Lock::new(FxHashSet()),
}
}
/// by `proc-macro` crates.
pub derive_macros: RefCell<NodeMap<Symbol>>,
- stability_interner: RefCell<FxHashSet<&'tcx attr::Stability>>,
+ stability_interner: Lock<FxHashSet<&'tcx attr::Stability>>,
pub interpret_interner: InterpretInterner<'tcx>,
- layout_interner: RefCell<FxHashSet<&'tcx LayoutDetails>>,
+ layout_interner: Lock<FxHashSet<&'tcx LayoutDetails>>,
/// A vector of every trait accessible in the whole crate
/// (i.e. including those from subcrates). This is used only for
/// This is intended to only get used during the trans phase of the compiler
/// when satisfying the query for a particular codegen unit. Internally in
/// the query it'll send data along this channel to get processed later.
- pub tx_to_llvm_workers: mpsc::Sender<Box<dyn Any + Send>>,
+ pub tx_to_llvm_workers: Lock<mpsc::Sender<Box<dyn Any + Send>>>,
output_filenames: Arc<OutputFilenames>,
}
/// Everything needed to efficiently work with interned allocations
#[derive(Debug, Default)]
pub struct InterpretInterner<'tcx> {
- inner: RefCell<InterpretInternerInner<'tcx>>,
+ inner: Lock<InterpretInternerInner<'tcx>>,
}
#[derive(Debug, Default)]
evaluation_cache: traits::EvaluationCache::new(),
crate_name: Symbol::intern(crate_name),
data_layout,
- layout_interner: RefCell::new(FxHashSet()),
+ layout_interner: Lock::new(FxHashSet()),
layout_depth: Cell::new(0),
derive_macros: RefCell::new(NodeMap()),
- stability_interner: RefCell::new(FxHashSet()),
+ stability_interner: Lock::new(FxHashSet()),
interpret_interner: Default::default(),
all_traits: RefCell::new(None),
- tx_to_llvm_workers: tx,
+ tx_to_llvm_workers: Lock::new(tx),
output_filenames: Arc::new(output_filenames.clone()),
};
pub fn mk_param(self,
index: u32,
- name: Name) -> Ty<'tcx> {
+ name: InternedString) -> Ty<'tcx> {
self.mk_ty(TyParam(ParamTy { idx: index, name: name }))
}
pub fn mk_self_type(self) -> Ty<'tcx> {
- self.mk_param(0, keywords::SelfType.name())
+ self.mk_param(0, keywords::SelfType.name().as_str())
}
pub fn mk_param_from_def(self, def: &ty::TypeParameterDef) -> Ty<'tcx> {
map: LockGuard<'_, QueryMap<$tcx, Self>>,
dep_node: DepNode)
-> Result<($V, DepNodeIndex), CycleError<$tcx>> {
- debug_assert!(!tcx.dep_graph.dep_node_exists(&dep_node));
+ // If the following assertion triggers, it can have two reasons:
+ // 1. Something is wrong with DepNode creation, either here or
+ // in DepGraph::try_mark_green()
+ // 2. Two distinct query keys get mapped to the same DepNode
+ // (see for example #48923)
+ assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
+ "Forcing query with already existing DepNode.\n\
+ - query-key: {:?}\n\
+ - dep-node: {:?}",
+ key, dep_node);
profq_msg!(tcx, ProfileQueriesMsg::ProviderBegin);
let res = Self::start_job(tcx,
#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
pub struct TypeParameterDef {
- pub name: Name,
+ pub name: InternedString,
pub def_id: DefId,
pub index: u32,
pub has_default: bool,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use std::cell::{Ref, RefCell};
+use rustc_data_structures::sync::{RwLock, ReadGuard};
use std::mem;
/// The `Steal` struct is intended to used as the value for a query.
///
/// FIXME(#41710) -- what is the best way to model linear queries?
pub struct Steal<T> {
- value: RefCell<Option<T>>
+ value: RwLock<Option<T>>
}
impl<T> Steal<T> {
pub fn new(value: T) -> Self {
Steal {
- value: RefCell::new(Some(value))
+ value: RwLock::new(Some(value))
}
}
- pub fn borrow(&self) -> Ref<T> {
- Ref::map(self.value.borrow(), |opt| match *opt {
+ pub fn borrow(&self) -> ReadGuard<T> {
+ ReadGuard::map(self.value.borrow(), |opt| match *opt {
None => bug!("attempted to read from stolen value"),
Some(ref v) => v
})
}
pub fn steal(&self) -> T {
- let value_ref = &mut *self.value.borrow_mut();
+ let value_ref = &mut *self.value.try_write().expect("stealing value which is locked");
let value = mem::replace(value_ref, None);
value.expect("attempt to read from stolen value")
}
use std::cmp::Ordering;
use syntax::abi;
use syntax::ast::{self, Name};
-use syntax::symbol::keywords;
+use syntax::symbol::{keywords, InternedString};
use serialize;
#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct ParamTy {
pub idx: u32,
- pub name: Name,
+ pub name: InternedString,
}
impl<'a, 'gcx, 'tcx> ParamTy {
- pub fn new(index: u32, name: Name) -> ParamTy {
+ pub fn new(index: u32, name: InternedString) -> ParamTy {
ParamTy { idx: index, name: name }
}
pub fn for_self() -> ParamTy {
- ParamTy::new(0, keywords::SelfType.name())
+ ParamTy::new(0, keywords::SelfType.name().as_str())
}
pub fn for_def(def: &ty::TypeParameterDef) -> ParamTy {
}
pub fn is_self(&self) -> bool {
- if self.name == keywords::SelfType.name() {
+ if self.name == keywords::SelfType.name().as_str() {
assert_eq!(self.idx, 0);
true
} else {
}
TyParam(p) => {
self.hash(p.idx);
- self.hash(p.name.as_str());
+ self.hash(p.name);
}
TyProjection(ref data) => {
self.def_id(data.item_def_id);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
-
#![feature(rustc_private)]
extern crate rustc;
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![forbid(unsafe_code)]
// See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_syntax)]
#![feature(const_fn)]
// Note that `mir_validated` is a "stealable" result; the
// thief, `optimized_mir()`, forces borrowck, so we know that
// is not yet stolen.
- tcx.mir_validated(owner_def_id).borrow();
+ ty::maps::queries::mir_validated::ensure(tcx, owner_def_id);
// option dance because you can't capture an uninitialized variable
// by mut-ref.
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![allow(non_camel_case_types)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
extern crate rustc_apfloat;
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(collections_range)]
#![feature(nonzero)]
f(&*self.read())
}
+ #[cfg(not(parallel_queries))]
+ #[inline(always)]
+ pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
+ self.0.try_borrow_mut().map_err(|_| ())
+ }
+
+ #[cfg(parallel_queries)]
+ #[inline(always)]
+ pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
+ self.0.try_write().ok_or(())
+ }
+
#[cfg(not(parallel_queries))]
#[inline(always)]
pub fn write(&self) -> WriteGuard<T> {
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_syntax)]
#![cfg_attr(unix, feature(libc))]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
+#![feature(slice_sort_by_cached_key)]
#![feature(set_stdio)]
#![feature(rustc_stack_internals)]
use serialize::json::ToJson;
use std::any::Any;
-use std::cmp::Ordering::Equal;
use std::cmp::max;
use std::default::Default;
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
- lints.sort_by(|x: &&Lint, y: &&Lint| {
- match x.default_level(sess).cmp(&y.default_level(sess)) {
- // The sort doesn't case-fold but it's doubtful we care.
- Equal => x.name.cmp(y.name),
- r => r,
- }
- });
+ // The sort doesn't case-fold but it's doubtful we care.
+ lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
lints
}
pub fn t_param(&self, index: u32) -> Ty<'tcx> {
let name = format!("T{}", index);
- self.infcx.tcx.mk_param(index, Symbol::intern(&name))
+ self.infcx.tcx.mk_param(index, Symbol::intern(&name).as_str())
}
pub fn re_early_bound(&self, index: u32, name: &'static str) -> ty::Region<'tcx> {
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(custom_attribute)]
#![allow(unused_attributes)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(fs_read_write)]
#![feature(specialization)]
}
if let PatKind::Binding(_, _, name, None) = fieldpat.node.pat.node {
if name.node == fieldpat.node.name {
+ if let Some(_) = fieldpat.span.ctxt().outer().expn_info() {
+ // Don't lint if this is a macro expansion: macro authors
+ // shouldn't have to worry about this kind of style issue
+ // (Issue #49588)
+ return;
+ }
let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
fieldpat.span,
&format!("the `{}:` in this pattern is redundant",
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![cfg_attr(test, feature(test))]
#![feature(box_patterns)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_syntax)]
#![feature(concat_idents)]
fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
impl_parent => { cdata.get_parent_impl(def_id.index) }
trait_of_item => { cdata.get_trait_of_item(def_id.index) }
- item_body_nested_bodies => { cdata.item_body_nested_bodies(def_id.index) }
+ item_body_nested_bodies => { cdata.item_body_nested_bodies(tcx, def_id.index) }
const_is_rvalue_promotable_to_static => {
cdata.const_is_rvalue_promotable_to_static(def_id.index)
}
tcx.alloc_tables(ast.tables.decode((self, tcx)))
}
- pub fn item_body_nested_bodies(&self, id: DefIndex) -> ExternBodyNestedBodies {
+ pub fn item_body_nested_bodies(&self,
+ tcx: TyCtxt<'a, 'tcx, 'tcx>,
+ id: DefIndex)
+ -> ExternBodyNestedBodies {
if let Some(ref ast) = self.entry(id).ast {
- let ast = ast.decode(self);
+ let mut ast = ast.decode(self);
let nested_bodies: BTreeMap<_, _> = ast.nested_bodies
- .decode(self)
+ .decode((self, tcx.sess))
.map(|body| (body.id(), body))
.collect();
ExternBodyNestedBodies {
let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
// Bring everything into deterministic order for hashing
- all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
+ all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
tcx.def_path_hash(trait_def_id)
});
.into_iter()
.map(|(trait_def_id, mut impls)| {
// Bring everything into deterministic order for hashing
- impls.sort_unstable_by_key(|&def_index| {
+ impls.sort_by_cached_key(|&def_index| {
tcx.hir.definitions().def_path_hash(def_index)
});
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_patterns)]
#![feature(fs_read_write)]
#![feature(macro_lifetime_matcher)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
+#![feature(slice_sort_by_cached_key)]
#![feature(specialization)]
#![feature(rustc_private)]
use dataflow::move_paths::{IllegalMoveOriginKind, MoveError};
use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex};
use util::borrowck_errors::{BorrowckErrors, Origin};
+use util::collect_writes::FindAssignments;
use std::iter;
}
}
+ fn specialized_description(&self, place:&Place<'tcx>) -> Option<String>{
+ if let Some(_name) = self.describe_place(place) {
+ Some(format!("data in a `&` reference"))
+ } else {
+ None
+ }
+ }
+
+ fn get_default_err_msg(&self, place:&Place<'tcx>) -> String{
+ match self.describe_place(place) {
+ Some(name) => format!("immutable item `{}`", name),
+ None => "immutable item".to_owned(),
+ }
+ }
+
+ fn get_secondary_err_msg(&self, place:&Place<'tcx>) -> String{
+ match self.specialized_description(place) {
+ Some(_) => format!("data in a `&` reference"),
+ None => self.get_default_err_msg(place)
+ }
+ }
+
+ fn get_primary_err_msg(&self, place:&Place<'tcx>) -> String{
+ if let Some(name) = self.describe_place(place) {
+ format!("`{}` is a `&` reference, so the data it refers to cannot be written", name)
+ } else {
+ format!("cannot assign through `&`-reference")
+ }
+ }
+
/// Check the permissions for the given place and read or write kind
///
/// Returns true if an error is reported, false otherwise.
self.is_mutable(place, is_local_mutation_allowed)
{
error_reported = true;
-
- let item_msg = match self.describe_place(place) {
- Some(name) => format!("immutable item `{}`", name),
- None => "immutable item".to_owned(),
- };
-
+ let item_msg = self.get_default_err_msg(place);
let mut err = self.tcx
.cannot_borrow_path_as_mutable(span, &item_msg, Origin::Mir);
err.span_label(span, "cannot borrow as mutable");
if place != place_err {
if let Some(name) = self.describe_place(place_err) {
- err.note(&format!("Value not mutable causing this error: `{}`", name));
+ err.note(&format!("the value which is causing this path not to be mutable \
+ is...: `{}`", name));
}
}
err.emit();
},
Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
+
if let Err(place_err) = self.is_mutable(place, is_local_mutation_allowed) {
error_reported = true;
+ let mut err_info = None;
+ match *place_err {
+
+ Place::Projection(box Projection {
+ ref base, elem:ProjectionElem::Deref}) => {
+ match *base {
+ Place::Local(local) => {
+ let locations = self.mir.find_assignments(local);
+ if locations.len() > 0 {
+ let item_msg = if error_reported {
+ self.get_secondary_err_msg(base)
+ } else {
+ self.get_default_err_msg(place)
+ };
+ err_info = Some((
+ self.mir.source_info(locations[0]).span,
+ "consider changing this to be a \
+ mutable reference: `&mut`", item_msg,
+ self.get_primary_err_msg(base)));
+ }
+ },
+ _ => {},
+ }
+ },
+ _ => {},
+ }
- let item_msg = match self.describe_place(place) {
- Some(name) => format!("immutable item `{}`", name),
- None => "immutable item".to_owned(),
- };
-
- let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
- err.span_label(span, "cannot mutate");
-
- if place != place_err {
- if let Some(name) = self.describe_place(place_err) {
- err.note(&format!("Value not mutable causing this error: `{}`", name));
+ if let Some((err_help_span, err_help_stmt, item_msg, sec_span)) = err_info {
+ let mut err = self.tcx.cannot_assign(span, &item_msg, Origin::Mir);
+ err.span_suggestion(err_help_span, err_help_stmt, format!(""));
+ if place != place_err {
+ err.span_label(span, sec_span);
}
+ err.emit()
+ } else {
+ let item_msg_ = self.get_default_err_msg(place);
+ let mut err = self.tcx.cannot_assign(span, &item_msg_, Origin::Mir);
+ err.span_label(span, "cannot mutate");
+ if place != place_err {
+ if let Some(name) = self.describe_place(place_err) {
+ err.note(&format!("the value which is causing this path not to be \
+ mutable is...: `{}`", name));
+ }
+ }
+ err.emit();
}
-
- err.emit();
}
}
Reservation(WriteKind::Move)
);
}
}
-
Activation(..) => {} // permission checks are done at Reservation point.
-
Read(ReadKind::Borrow(BorrowKind::Unique))
| Read(ReadKind::Borrow(BorrowKind::Mut { .. }))
| Read(ReadKind::Borrow(BorrowKind::Shared))
}
}
}
+
*/
-#![deny(warnings)]
-
#![feature(slice_patterns)]
+#![feature(slice_sort_by_cached_key)]
#![feature(from_ref)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(rustc_diagnostic_macros)]
#![feature(nonzero)]
#![feature(inclusive_range_fields)]
+#![feature(crate_visibility_modifier)]
extern crate arena;
#[macro_use]
use rustc::ty::item_path::characteristic_def_id_of_type;
use rustc::util::nodemap::{FxHashMap, FxHashSet};
use std::collections::hash_map::Entry;
+use std::cmp;
use syntax::ast::NodeId;
use syntax::symbol::{Symbol, InternedString};
use rustc::mir::mono::MonoItem;
use monomorphize::item::{MonoItemExt, InstantiationMode};
-use core::usize;
pub use rustc::mir::mono::CodegenUnit;
}, item.symbol_name(tcx))
}
- let items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
- let mut items : Vec<_> = items.iter()
- .map(|il| (il, item_sort_key(tcx, il.0))).collect();
- items.sort_by(|&(_, ref key1), &(_, ref key2)| key1.cmp(key2));
- items.into_iter().map(|(&item_linkage, _)| item_linkage).collect()
+ let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
+ items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
+ items
}
}
// Merge the two smallest codegen units until the target size is reached.
while codegen_units.len() > target_cgu_count {
// Sort small cgus to the back
- codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
+ codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
let mut smallest = codegen_units.pop().unwrap();
let second_smallest = codegen_units.last_mut().unwrap();
self.cancel_if_wrong_origin(err, o)
}
- fn cannot_assign(self, span: Span, desc: &str, o: Origin) -> DiagnosticBuilder<'cx>
+ fn cannot_assign(self, span: Span, desc: &str, o: Origin)
+ -> DiagnosticBuilder<'cx>
{
let err = struct_span_err!(self, span, E0594,
"cannot assign to {}{OGN}",
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use rustc::mir::{Local, Location};
+use rustc::mir::Mir;
+use rustc::mir::visit::PlaceContext;
+use rustc::mir::visit::Visitor;
+
+crate trait FindAssignments {
+ // Finds all statements that assign directly to local (i.e., X = ...)
+ // and returns their locations.
+ fn find_assignments(&self, local: Local) -> Vec<Location>;
+}
+
+impl<'tcx> FindAssignments for Mir<'tcx>{
+ fn find_assignments(&self, local: Local) -> Vec<Location>{
+ let mut visitor = FindLocalAssignmentVisitor{ needle: local, locations: vec![]};
+ visitor.visit_mir(self);
+ visitor.locations
+ }
+}
+
+// The Visitor walks the MIR to return the assignment statements corresponding
+// to a Local.
+struct FindLocalAssignmentVisitor {
+ needle: Local,
+ locations: Vec<Location>,
+}
+
+impl<'tcx> Visitor<'tcx> for FindLocalAssignmentVisitor {
+ fn visit_local(&mut self,
+ local: &Local,
+ place_context: PlaceContext<'tcx>,
+ location: Location) {
+ if self.needle != *local {
+ return;
+ }
+
+ match place_context {
+ PlaceContext::Store | PlaceContext::Call => {
+ self.locations.push(location);
+ }
+ PlaceContext::AsmOutput |
+ PlaceContext::Drop |
+ PlaceContext::Inspect |
+ PlaceContext::Borrow { .. } |
+ PlaceContext::Projection(..) |
+ PlaceContext::Copy |
+ PlaceContext::Move |
+ PlaceContext::StorageLive |
+ PlaceContext::StorageDead |
+ PlaceContext::Validate => {
+ // TO-DO
+ // self.super_local(local)
+ }
+ }
+ }
+ // TO-DO
+ // fn super_local()
+}
mod graphviz;
pub(crate) mod pretty;
pub mod liveness;
+pub mod collect_writes;
pub use self::alignment::is_disaligned;
pub use self::pretty::{dump_enabled, dump_mir, write_mir_pretty, PassWhere};
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(rustc_diagnostic_macros)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-#![deny(warnings)]
#![allow(bad_style)]
pub struct Intrinsic {
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(rustc_diagnostic_macros)]
#![feature(staged_api)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(rustc_diagnostic_macros)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(rustc_diagnostic_macros)]
+#![feature(slice_sort_by_cached_key)]
#[macro_use]
extern crate log;
fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
let resolutions = self.resolutions.borrow();
- let mut resolutions = resolutions.iter().map(|(&(ident, ns), &resolution)| {
- // Pre-compute keys for sorting
- (ident.name.as_str(), ns, ident, resolution)
- })
- .collect::<Vec<_>>();
- resolutions.sort_unstable_by_key(|&(str, ns, ..)| (str, ns));
- for &(_, ns, ident, resolution) in resolutions.iter() {
+ let mut resolutions = resolutions.iter().collect::<Vec<_>>();
+ resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.name.as_str(), ns));
+ for &(&(ident, ns), &resolution) in resolutions.iter() {
resolution.borrow().binding.map(|binding| f(ident, ns, binding));
}
}
let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
let mut candidates =
self.lookup_import_candidates(name, TypeNS, is_mod);
- candidates.sort_by_key(|c| (c.path.segments.len(), c.path.to_string()));
+ candidates.sort_by_cached_key(|c| {
+ (c.path.segments.len(), c.path.to_string())
+ });
if let Some(candidate) = candidates.get(0) {
format!("Did you mean `{}`?", candidate.path)
} else {
let name = path[path.len() - 1].name;
// Make sure error reporting is deterministic.
- names.sort_by_key(|name| name.as_str());
+ names.sort_by_cached_key(|name| name.as_str());
match find_best_match_for_name(names.iter(), &name.as_str(), None) {
Some(found) if found != name => Some(found),
_ => None,
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(custom_attribute)]
#![feature(macro_lifetime_matcher)]
#![allow(unused_attributes)]
//! New recursive solver modeled on Chalk's recursive solver. Most of
//! the guts are broken up into modules; see the comments in those modules.
-#![deny(warnings)]
-
#![feature(crate_visibility_modifier)]
#[macro_use]
crate_info,
time_graph,
- coordinator_send: tcx.tx_to_llvm_workers.clone(),
+ coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
trans_worker_receive,
shared_emitter_main,
future: coordinator_thread,
metadata_config: Arc<ModuleConfig>,
allocator_config: Arc<ModuleConfig>)
-> thread::JoinHandle<Result<CompiledModules, ()>> {
- let coordinator_send = tcx.tx_to_llvm_workers.clone();
+ let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
let sess = tcx.sess;
// Compute the set of symbols we need to retain when doing LTO (if we need to)
mtrans: ModuleTranslation,
cost: u64) {
let llvm_work_item = WorkItem::Optimize(mtrans);
- drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone {
+ drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::TranslationDone {
llvm_work_item,
cost,
})));
use std::str;
use std::sync::Arc;
use std::time::{Instant, Duration};
-use std::{i32, usize};
+use std::i32;
+use std::cmp;
use std::sync::mpsc;
use syntax_pos::Span;
use syntax_pos::symbol::InternedString;
// a bit more efficiently.
let codegen_units = {
let mut codegen_units = codegen_units;
- codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
+ codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
codegen_units
};
use syntax_pos::{self, Span, Pos};
use syntax::ast;
-use syntax::symbol::Symbol;
+use syntax::symbol::{Symbol, InternedString};
use rustc::ty::layout::{self, LayoutOf};
pub mod gdb;
substs.types().zip(names).map(|(ty, name)| {
let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
let actual_type_metadata = type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
- let name = CString::new(name.as_str().as_bytes()).unwrap();
+ let name = CString::new(name.as_bytes()).unwrap();
unsafe {
llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
DIB(cx),
return create_DIArray(DIB(cx), &template_params[..]);
}
- fn get_type_parameter_names(cx: &CodegenCx, generics: &ty::Generics) -> Vec<ast::Name> {
+ fn get_type_parameter_names(cx: &CodegenCx, generics: &ty::Generics) -> Vec<InternedString> {
let mut names = generics.parent.map_or(vec![], |def_id| {
get_type_parameter_names(cx, cx.tcx.generics_of(def_id))
});
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
+#![feature(slice_sort_by_cached_key)]
#![feature(optin_builtin_traits)]
#![feature(inclusive_range_fields)]
#![feature(underscore_lifetimes)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(box_patterns)]
#![feature(box_syntax)]
let item_def_id = tcx.hir.local_def_id(item_id);
let generics = tcx.generics_of(item_def_id);
let index = generics.type_param_to_index[&tcx.hir.local_def_id(node_id)];
- tcx.mk_param(index, tcx.hir.name(node_id))
+ tcx.mk_param(index, tcx.hir.name(node_id).as_str())
}
Def::SelfTy(_, Some(def_id)) => {
// Self in impl (we know the concrete type).
/// and in libcore/intrinsics.rs
pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
it: &hir::ForeignItem) {
- let param = |n| tcx.mk_param(n, Symbol::intern(&format!("P{}", n)));
+ let param = |n| tcx.mk_param(n, Symbol::intern(&format!("P{}", n)).as_str());
let name = it.name.as_str();
let (n_tps, inputs, output) = if name.starts_with("atomic_") {
let split : Vec<&str> = name.split('_').collect();
pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
it: &hir::ForeignItem) {
let param = |n| {
- let name = Symbol::intern(&format!("P{}", n));
+ let name = Symbol::intern(&format!("P{}", n)).as_str();
tcx.mk_param(n, name)
};
.collect();
// sort them by the name so we have a stable result
- names.sort_by_key(|n| n.as_str());
+ names.sort_by_cached_key(|n| n.as_str());
names
}
// local so it should be okay to just unwrap everything.
let trait_def_id = impl_params[&method_param.name];
let trait_decl_span = tcx.def_span(trait_def_id);
- error_194(tcx, type_span, trait_decl_span, method_param.name);
+ error_194(tcx, type_span, trait_decl_span, &method_param.name[..]);
}
}
}
err
}
-fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
+fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
struct_span_err!(tcx.sess, span, E0194,
"type parameter `{}` shadows another type parameter of the same name",
name)
let param_owner_def_id = tcx.hir.local_def_id(param_owner);
let generics = tcx.generics_of(param_owner_def_id);
let index = generics.type_param_to_index[&def_id];
- let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id));
+ let ty = tcx.mk_param(index, tcx.hir.ty_param_name(param_id).as_str());
// Don't look for bounds where the type parameter isn't in scope.
let parent = if item_def_id == param_owner_def_id {
opt_self = Some(ty::TypeParameterDef {
index: 0,
- name: keywords::SelfType.name(),
+ name: keywords::SelfType.name().as_str(),
def_id: tcx.hir.local_def_id(param_id),
has_default: false,
object_lifetime_default: rl::Set1::Empty,
ty::TypeParameterDef {
index: type_start + i as u32,
- name: p.name,
+ name: p.name.as_str(),
def_id: tcx.hir.local_def_id(p.id),
has_default: p.default.is_some(),
object_lifetime_default:
// add a dummy parameter for the closure kind
types.push(ty::TypeParameterDef {
index: type_start,
- name: Symbol::intern("<closure_kind>"),
+ name: Symbol::intern("<closure_kind>").as_str(),
def_id,
has_default: false,
object_lifetime_default: rl::Set1::Empty,
// add a dummy parameter for the closure signature
types.push(ty::TypeParameterDef {
index: type_start + 1,
- name: Symbol::intern("<closure_signature>"),
+ name: Symbol::intern("<closure_signature>").as_str(),
def_id,
has_default: false,
object_lifetime_default: rl::Set1::Empty,
tcx.with_freevars(node_id, |fv| {
types.extend(fv.iter().zip(2..).map(|(_, i)| ty::TypeParameterDef {
index: type_start + i,
- name: Symbol::intern("<upvar>"),
+ name: Symbol::intern("<upvar>").as_str(),
def_id,
has_default: false,
object_lifetime_default: rl::Set1::Empty,
// Collect the predicates that were written inline by the user on each
// type parameter (e.g., `<T:Foo>`).
for param in ast_generics.ty_params() {
- let param_ty = ty::ParamTy::new(index, param.name).to_ty(tcx);
+ let param_ty = ty::ParamTy::new(index, param.name.as_str()).to_ty(tcx);
index += 1;
let bounds = compute_bounds(&icx,
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![allow(non_camel_case_types)]
#![feature(crate_visibility_modifier)]
#![feature(from_ref)]
#![feature(exhaustive_patterns)]
-#![feature(option_filter)]
#![feature(quote)]
#![feature(refcell_replace_swap)]
#![feature(rustc_diagnostic_macros)]
#![feature(slice_patterns)]
+#![feature(slice_sort_by_cached_key)]
#![feature(dyn_trait)]
#[macro_use] extern crate log;
P(hir::Path {
span: DUMMY_SP,
def: Def::TyParam(param.def_id),
- segments: HirVec::from_vec(vec![hir::PathSegment::from_name(param.name)]),
+ segments: HirVec::from_vec(vec![
+ hir::PathSegment::from_name(Symbol::intern(¶m.name))
+ ]),
}),
)),
span: DUMMY_SP,
// involved (impls rarely have more than a few bounds) means that it
// shouldn't matter in practice.
fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
- vec.sort_unstable_by(|first, second| {
- format!("{:?}", first).cmp(&format!("{:?}", second))
- });
+ vec.sort_by_cached_key(|x| format!("{:?}", x))
}
fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {
use syntax::feature_gate::UnstableFeatures;
use syntax::ptr::P;
use syntax::symbol::keywords;
-use syntax::symbol::Symbol;
+use syntax::symbol::{Symbol, InternedString};
use syntax_pos::{self, DUMMY_SP, Pos, FileName};
use rustc::middle::const_val::ConstVal;
// predicates field (see rustc_typeck::collect::ty_generics), so remove
// them.
let stripped_typarams = gens.types.iter().filter_map(|tp| {
- if tp.name == keywords::SelfType.name() {
+ if tp.name == keywords::SelfType.name().as_str() {
assert_eq!(tp.index, 0);
None
} else {
}
}
+impl Clean<String> for InternedString {
+ fn clean(&self, _: &DocContext) -> String {
+ self.to_string()
+ }
+}
+
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Typedef {
pub type_: Type,
href.push_str(component);
href.push('/');
});
- let mut fname = p.file_name().expect("source has no filename")
+ let mut fname = p.file_name()
+ .expect("source has no filename")
.to_os_string();
fname.push(".html");
cur.push(&fname);
}
}
+#[derive(Debug, Eq, PartialEq, Hash)]
+struct ItemEntry {
+ url: String,
+ name: String,
+}
+
+impl ItemEntry {
+ fn new(mut url: String, name: String) -> ItemEntry {
+ while url.starts_with('/') {
+ url.remove(0);
+ }
+ ItemEntry {
+ url,
+ name,
+ }
+ }
+}
+
+impl fmt::Display for ItemEntry {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
+ }
+}
+
+impl PartialOrd for ItemEntry {
+ fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for ItemEntry {
+ fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
+ self.name.cmp(&other.name)
+ }
+}
+
+#[derive(Debug)]
+struct AllTypes {
+ structs: HashSet<ItemEntry>,
+ enums: HashSet<ItemEntry>,
+ unions: HashSet<ItemEntry>,
+ primitives: HashSet<ItemEntry>,
+ traits: HashSet<ItemEntry>,
+ macros: HashSet<ItemEntry>,
+ functions: HashSet<ItemEntry>,
+ typedefs: HashSet<ItemEntry>,
+ statics: HashSet<ItemEntry>,
+ constants: HashSet<ItemEntry>,
+}
+
+impl AllTypes {
+ fn new() -> AllTypes {
+ AllTypes {
+ structs: HashSet::with_capacity(100),
+ enums: HashSet::with_capacity(100),
+ unions: HashSet::with_capacity(100),
+ primitives: HashSet::with_capacity(26),
+ traits: HashSet::with_capacity(100),
+ macros: HashSet::with_capacity(100),
+ functions: HashSet::with_capacity(100),
+ typedefs: HashSet::with_capacity(100),
+ statics: HashSet::with_capacity(100),
+ constants: HashSet::with_capacity(100),
+ }
+ }
+
+ fn append(&mut self, item_name: String, item_type: &ItemType) {
+ let mut url: Vec<_> = item_name.split("::").skip(1).collect();
+ if let Some(name) = url.pop() {
+ let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
+ url.push(name);
+ let name = url.join("::");
+ match *item_type {
+ ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
+ ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
+ ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
+ ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
+ ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
+ ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
+ ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
+ ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
+ ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
+ ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
+ _ => true,
+ };
+ }
+ }
+}
+
+fn print_entries(f: &mut fmt::Formatter, e: &HashSet<ItemEntry>, title: &str,
+ class: &str) -> fmt::Result {
+ if !e.is_empty() {
+ let mut e: Vec<&ItemEntry> = e.iter().collect();
+ e.sort();
+ write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
+ title,
+ Escape(title),
+ class,
+ e.iter().map(|s| format!("<li>{}</li>", s)).collect::<String>())?;
+ }
+ Ok(())
+}
+
+impl fmt::Display for AllTypes {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f,
+"<h1 class='fqn'>\
+ <span class='in-band'>List of all items</span>\
+ <span class='out-of-band'>\
+ <span id='render-detail'>\
+ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
+ [<span class='inner'>−</span>]\
+ </a>\
+ </span>
+ </span>
+</h1>")?;
+ print_entries(f, &self.structs, "Structs", "structs")?;
+ print_entries(f, &self.enums, "Enums", "enums")?;
+ print_entries(f, &self.unions, "Unions", "unions")?;
+ print_entries(f, &self.primitives, "Primitives", "primitives")?;
+ print_entries(f, &self.traits, "Traits", "traits")?;
+ print_entries(f, &self.macros, "Macros", "macros")?;
+ print_entries(f, &self.functions, "Functions", "functions")?;
+ print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
+ print_entries(f, &self.statics, "Statics", "statics")?;
+ print_entries(f, &self.constants, "Constants", "constants")
+ }
+}
+
impl Context {
/// String representation of how to get back to the root path of the 'doc/'
/// folder in terms of a relative URL.
Some(i) => i,
None => return Ok(()),
};
+ let final_file = self.dst.join(&krate.name)
+ .join("all.html");
+ let crate_name = krate.name.clone();
item.name = Some(krate.name);
- // Render the crate documentation
- let mut work = vec![(self, item)];
+ let mut all = AllTypes::new();
- while let Some((mut cx, item)) = work.pop() {
- cx.item(item, |cx, item| {
- work.push((cx.clone(), item))
- })?
+ {
+ // Render the crate documentation
+ let mut work = vec![(self.clone(), item)];
+
+ while let Some((mut cx, item)) = work.pop() {
+ cx.item(item, &mut all, |cx, item| {
+ work.push((cx.clone(), item))
+ })?
+ }
}
+
+ let mut w = BufWriter::new(try_err!(File::create(&final_file), &final_file));
+ let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
+ if !root_path.ends_with('/') {
+ root_path.push('/');
+ }
+ let page = layout::Page {
+ title: "List of all items in this crate",
+ css_class: "mod",
+ root_path: "../",
+ description: "List of all items in this crate",
+ keywords: BASIC_KEYWORDS,
+ resource_suffix: &self.shared.resource_suffix,
+ };
+ let sidebar = if let Some(ref version) = cache().crate_version {
+ format!("<p class='location'>Crate {}</p>\
+ <div class='block version'>\
+ <p>Version {}</p>\
+ </div>\
+ <a id='all-types' href='index.html'><p>Back to index</p></a>",
+ crate_name, version)
+ } else {
+ String::new()
+ };
+ try_err!(layout::render(&mut w, &self.shared.layout,
+ &page, &sidebar, &all,
+ self.shared.css_file_extension.is_some(),
+ &self.shared.themes),
+ &final_file);
Ok(())
}
/// all sub-items which need to be rendered.
///
/// The rendering driver uses this closure to queue up more work.
- fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
- F: FnMut(&mut Context, clean::Item),
+ fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
+ where F: FnMut(&mut Context, clean::Item),
{
// Stripped modules survive the rustdoc passes (i.e. `strip-private`)
// if they contain impls for public types. These modules can also
}
for item in m.items {
- f(this,item);
+ f(this, item);
}
Ok(())
let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
try_err!(dst.write_all(&buf), &joint_dst);
+ all.append(full_path(self, &item), &item_type);
// Redirect from a sane URL using the namespace to Rustdoc's
// URL for the page.
let redir_name = format!("{}.{}.html", name, item_type.name_space());
let redir_dst = self.dst.join(redir_name);
if let Ok(redirect_out) = OpenOptions::new().create_new(true)
- .write(true)
- .open(&redir_dst) {
+ .write(true)
+ .open(&redir_dst) {
let mut redirect_out = BufWriter::new(redirect_out);
try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
}
version)?;
}
write!(fmt,
- r##"<span id='render-detail'>
- <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
- [<span class='inner'>−</span>]
- </a>
- </span>"##)?;
+ "<span id='render-detail'>\
+ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
+ title=\"collapse all docs\">\
+ [<span class='inner'>−</span>]\
+ </a>\
+ </span>")?;
// Write `src` tag
//
if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
|| it.is_enum() || it.is_mod() || it.is_typedef() {
- write!(fmt, "<p class='location'>")?;
- match it.inner {
- clean::StructItem(..) => write!(fmt, "Struct ")?,
- clean::TraitItem(..) => write!(fmt, "Trait ")?,
- clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
- clean::UnionItem(..) => write!(fmt, "Union ")?,
- clean::EnumItem(..) => write!(fmt, "Enum ")?,
- clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
- clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
- clean::ModuleItem(..) => if it.is_crate() {
- write!(fmt, "Crate ")?;
- } else {
- write!(fmt, "Module ")?;
+ write!(fmt, "<p class='location'>{}{}</p>",
+ match it.inner {
+ clean::StructItem(..) => "Struct ",
+ clean::TraitItem(..) => "Trait ",
+ clean::PrimitiveItem(..) => "Primitive Type ",
+ clean::UnionItem(..) => "Union ",
+ clean::EnumItem(..) => "Enum ",
+ clean::TypedefItem(..) => "Type Definition ",
+ clean::ForeignTypeItem => "Foreign Type ",
+ clean::ModuleItem(..) => if it.is_crate() {
+ "Crate "
+ } else {
+ "Module "
+ },
+ _ => "",
},
- _ => (),
- }
- write!(fmt, "{}", it.name.as_ref().unwrap())?;
- write!(fmt, "</p>")?;
+ it.name.as_ref().unwrap())?;
}
if it.is_crate() {
write!(fmt,
"<div class='block version'>\
<p>Version {}</p>\
- </div>",
- version)?;
+ </div>
+ <a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
+ version,
+ it.name.as_ref().unwrap())?;
}
}
font-size: 19px;
display: block;
}
+
+#main > ul {
+ padding-left: 10px;
+}
+#main > ul > li {
+ list-style: none;
+}
+#all-types {
+ text-align: center;
+ border: 1px solid;
+ margin: 0 10px;
+ margin-bottom: 10px;
+ display: block;
+ border-radius: 7px;
+}
+#all-types > p {
+ margin: 5px 0;
+}
\ No newline at end of file
background: #f0f0f0;
}
}
+
+#all-types {
+ background-color: #505050;
+}
+#all-types:hover {
+ background-color: #606060;
+}
background: #fff;
}
}
+
+#all-types {
+ background-color: #fff;
+}
+#all-types:hover {
+ background-color: #f9f9f9;
+}
\ No newline at end of file
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/")]
-#![deny(warnings)]
#![feature(ascii_ctype)]
#![feature(rustc_private)]
#![feature(box_syntax)]
#![feature(fs_read_write)]
#![feature(set_stdio)]
+#![feature(slice_sort_by_cached_key)]
#![feature(test)]
#![feature(unicode)]
#![feature(vec_remove_item)]
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/",
test(attr(allow(unused_variables), deny(warnings))))]
-#![deny(warnings)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
/// # Examples
///
/// ```no_run
- /// #![feature(take_set_limit)]
/// use std::io;
/// use std::io::prelude::*;
/// use std::fs::File;
/// Ok(())
/// }
/// ```
- #[unstable(feature = "take_set_limit", issue = "42781")]
+ #[stable(feature = "take_set_limit", since = "1.27.0")]
pub fn set_limit(&mut self, limit: u64) {
self.limit = limit;
}
// Tell the compiler to link to either panic_abort or panic_unwind
#![needs_panic_runtime]
-// Turn warnings into errors, but only after stage0, where it can be useful for
-// code to emit warnings during language transitions
-#![cfg_attr(not(stage0), deny(warnings))]
-
// std may use features in a platform-specific way
#![allow(unused_features)]
html_playground_url = "https://play.rust-lang.org/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
-#![deny(warnings)]
#![deny(missing_debug_implementations)]
#![no_std]
use std::iter;
use std::path::PathBuf;
use std::rc::Rc;
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{self, Lrc};
use std::default::Default;
use tokenstream::{self, TokenStream};
/// `#[derive(...)]` is a `MultiItemDecorator`.
///
/// Prefer ProcMacro or MultiModifier since they are more flexible.
- MultiDecorator(Box<MultiItemDecorator>),
+ MultiDecorator(Box<MultiItemDecorator + sync::Sync + sync::Send>),
/// A syntax extension that is attached to an item and modifies it
/// in-place. Also allows decoration, i.e., creating new items.
- MultiModifier(Box<MultiItemModifier>),
+ MultiModifier(Box<MultiItemModifier + sync::Sync + sync::Send>),
/// A function-like procedural macro. TokenStream -> TokenStream.
- ProcMacro(Box<ProcMacro>),
+ ProcMacro(Box<ProcMacro + sync::Sync + sync::Send>),
/// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
/// The first TokenSteam is the attribute, the second is the annotated item.
/// Allows modification of the input items and adding new items, similar to
/// MultiModifier, but uses TokenStreams, rather than AST nodes.
- AttrProcMacro(Box<AttrProcMacro>),
+ AttrProcMacro(Box<AttrProcMacro + sync::Sync + sync::Send>),
/// A normal, function-like syntax extension.
///
/// `bytes!` is a `NormalTT`.
NormalTT {
- expander: Box<TTMacroExpander>,
+ expander: Box<TTMacroExpander + sync::Sync + sync::Send>,
def_info: Option<(ast::NodeId, Span)>,
/// Whether the contents of the macro can
/// directly use `#[unstable]` things (true == yes).
/// A function-like syntax extension that has an extra ident before
/// the block.
///
- IdentTT(Box<IdentMacroExpander>, Option<Span>, bool),
+ IdentTT(Box<IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
/// An attribute-like procedural macro. TokenStream -> TokenStream.
/// The input is the annotated item.
/// Allows generating code to implement a Trait for a given struct
/// or enum item.
- ProcMacroDerive(Box<MultiItemModifier>, Vec<Symbol> /* inert attribute names */),
+ ProcMacroDerive(Box<MultiItemModifier +
+ sync::Sync +
+ sync::Send>, Vec<Symbol> /* inert attribute names */),
/// An attribute-like procedural macro that derives a builtin trait.
BuiltinDerive(BuiltinDeriveFn),
/// A declarative macro, e.g. `macro m() {}`.
///
/// The second element is the definition site span.
- DeclMacro(Box<TTMacroExpander>, Option<(ast::NodeId, Span)>),
+ DeclMacro(Box<TTMacroExpander + sync::Sync + sync::Send>, Option<(ast::NodeId, Span)>),
}
impl SyntaxExtension {
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
test(attr(deny(warnings))))]
-#![deny(warnings)]
#![feature(unicode)]
#![feature(rustc_diagnostic_macros)]
+#![feature(slice_sort_by_cached_key)]
#![feature(non_exhaustive)]
#![feature(const_atomic_usize_new)]
#![feature(rustc_attrs)]
+#![recursion_limit="256"]
+
// See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
#[allow(unused_extern_crates)]
extern crate rustc_cratesio_shim;
use errors;
use feature_gate::UnstableFeatures;
use parse::token;
- use std::cell::RefCell;
use std::collections::HashSet;
use std::io;
use std::path::PathBuf;
span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)),
unstable_features: UnstableFeatures::from_environment(),
config: CrateConfig::new(),
- included_mod_stack: RefCell::new(Vec::new()),
+ included_mod_stack: Lock::new(Vec::new()),
code_map: cm,
- missing_fragment_specifiers: RefCell::new(HashSet::new()),
- raw_identifier_spans: RefCell::new(Vec::new()),
+ missing_fragment_specifiers: Lock::new(HashSet::new()),
+ raw_identifier_spans: Lock::new(Vec::new()),
registered_diagnostics: Lock::new(ErrorMap::new()),
- non_modrs_mods: RefCell::new(vec![]),
+ non_modrs_mods: Lock::new(vec![]),
}
}
use tokenstream::{TokenStream, TokenTree};
use diagnostics::plugin::ErrorMap;
-use std::cell::RefCell;
use std::collections::HashSet;
use std::iter;
use std::path::{Path, PathBuf};
pub span_diagnostic: Handler,
pub unstable_features: UnstableFeatures,
pub config: CrateConfig,
- pub missing_fragment_specifiers: RefCell<HashSet<Span>>,
+ pub missing_fragment_specifiers: Lock<HashSet<Span>>,
/// Places where raw identifiers were used. This is used for feature gating
/// raw identifiers
- pub raw_identifier_spans: RefCell<Vec<Span>>,
+ pub raw_identifier_spans: Lock<Vec<Span>>,
/// The registered diagnostics codes
pub registered_diagnostics: Lock<ErrorMap>,
// Spans where a `mod foo;` statement was included in a non-mod.rs file.
// These are used to issue errors if the non_modrs_mods feature is not enabled.
- pub non_modrs_mods: RefCell<Vec<(ast::Ident, Span)>>,
+ pub non_modrs_mods: Lock<Vec<(ast::Ident, Span)>>,
/// Used to determine and report recursive mod inclusions
- included_mod_stack: RefCell<Vec<PathBuf>>,
+ included_mod_stack: Lock<Vec<PathBuf>>,
code_map: Lrc<CodeMap>,
}
span_diagnostic: handler,
unstable_features: UnstableFeatures::from_environment(),
config: HashSet::new(),
- missing_fragment_specifiers: RefCell::new(HashSet::new()),
- raw_identifier_spans: RefCell::new(Vec::new()),
+ missing_fragment_specifiers: Lock::new(HashSet::new()),
+ raw_identifier_spans: Lock::new(Vec::new()),
registered_diagnostics: Lock::new(ErrorMap::new()),
- included_mod_stack: RefCell::new(vec![]),
+ included_mod_stack: Lock::new(vec![]),
code_map,
- non_modrs_mods: RefCell::new(vec![]),
+ non_modrs_mods: Lock::new(vec![]),
}
}
.chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
.chain(self.expected_tokens.iter().cloned())
.collect::<Vec<_>>();
- expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
+ expected.sort_by_cached_key(|x| x.to_string());
expected.dedup();
let expect = tokens_to_string(&expected[..]);
let actual = self.this_token_to_string();
use tokenstream::{TokenStream, TokenTree};
use tokenstream;
-use std::cell::Cell;
use std::{cmp, fmt};
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{Lrc, Lock};
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum BinOpToken {
}
}
-pub struct LazyTokenStream(Cell<Option<TokenStream>>);
-
-impl Clone for LazyTokenStream {
- fn clone(&self) -> Self {
- let opt_stream = self.0.take();
- self.0.set(opt_stream.clone());
- LazyTokenStream(Cell::new(opt_stream))
- }
-}
+#[derive(Clone)]
+pub struct LazyTokenStream(Lock<Option<TokenStream>>);
impl cmp::Eq for LazyTokenStream {}
impl PartialEq for LazyTokenStream {
impl LazyTokenStream {
pub fn new() -> Self {
- LazyTokenStream(Cell::new(None))
+ LazyTokenStream(Lock::new(None))
}
pub fn force<F: FnOnce() -> TokenStream>(&self, f: F) -> TokenStream {
- let mut opt_stream = self.0.take();
+ let mut opt_stream = self.0.lock();
if opt_stream.is_none() {
- opt_stream = Some(f());
+ *opt_stream = Some(f());
}
- self.0.set(opt_stream.clone());
opt_stream.clone().unwrap()
}
}
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(proc_macro_internals)]
#![feature(decl_macro)]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
-#![deny(warnings)]
#![feature(const_fn)]
#![feature(custom_attribute)]
html_playground_url = "https://play.rust-lang.org/",
test(attr(deny(warnings))))]
#![deny(missing_docs)]
-#![deny(warnings)]
#![cfg_attr(windows, feature(libc))]
// Handle rustfmt skips
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/", test(attr(deny(warnings))))]
-#![deny(warnings)]
#![feature(asm)]
#![feature(fnbox)]
#![cfg_attr(any(unix, target_os = "cloudabi"), feature(libc))]
#![no_std]
#![unstable(feature = "panic_unwind", issue = "32837")]
-#![deny(warnings)]
#![feature(cfg_target_vendor)]
#![feature(link_cfg)]
// Set the stack size at link time on Windows. See rustc_driver::in_rustc_thread
// for the rationale.
+#[allow(unused_attributes)]
#[cfg_attr(all(windows, target_env = "msvc"), link_args = "/STACK:16777216")]
// We only build for msvc and gnu now, but we use a exhaustive condition here
// so we can expect either the stack size to be set or the build fails.
let y: Box<_> = box &mut x;
let p = &y;
***p = 2; //[ast]~ ERROR cannot assign to data in a `&` reference
- //[mir]~^ ERROR cannot assign to immutable item `***p`
+ //[mir]~^ ERROR cannot assign to data in a `&` reference
drop(p);
}
--- /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.
+
+#![deny(non_shorthand_field_patterns)]
+
+pub struct Value<A> { pub value: A }
+
+#[macro_export]
+macro_rules! pat {
+ ($a:pat) => {
+ Value { value: $a }
+ };
+}
+
+fn main() {
+ let pat!(value) = Value { value: () };
+}
--- /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.
+
+#![crate_name = "foo"]
+
+// @has foo/all.html '//a[@href="struct.Struct.html"]' 'Struct'
+// @has foo/all.html '//a[@href="enum.Enum.html"]' 'Enum'
+// @has foo/all.html '//a[@href="union.Union.html"]' 'Union'
+// @has foo/all.html '//a[@href="constant.CONST.html"]' 'CONST'
+// @has foo/all.html '//a[@href="static.STATIC.html"]' 'STATIC'
+// @has foo/all.html '//a[@href="fn.function.html"]' 'function'
+
+pub struct Struct;
+pub enum Enum {
+ X,
+ Y,
+}
+pub union Union {
+ x: u32,
+}
+pub const CONST: u32 = 0;
+pub static STATIC: &str = "baguette";
+pub fn function() {}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+#![feature(nll)]
+struct FancyNum {
+ num: u8,
+}
+
+fn main() {
+ let mut fancy = FancyNum{ num: 5 };
+ let fancy_ref = &(&mut fancy);
+ fancy_ref.num = 6; //~ ERROR E0594
+ println!("{}", fancy_ref.num);
+}
--- /dev/null
+error[E0594]: cannot assign to data in a `&` reference
+ --> $DIR/issue-47388.rs:18:5
+ |
+LL | let fancy_ref = &(&mut fancy);
+ | ------------- help: consider changing this to be a mutable reference: `&mut`
+LL | fancy_ref.num = 6; //~ ERROR E0594
+ | ^^^^^^^^^^^^^^^^^ `fancy_ref` is a `&` reference, so the data it refers to cannot be written
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0594`.
// except according to those terms.
#![feature(link_args)]
+
+#[allow(unused_attributes)]
// Set the stack size at link time on Windows. See rustc_driver::in_rustc_thread
// for the rationale.
#[cfg_attr(all(windows, target_env = "msvc"), link_args = "/STACK:16777216")]
//! This library contains the tidy lints and exposes it
//! to be used by tools.
-#![deny(warnings)]
-
extern crate serde;
extern crate serde_json;
#[macro_use]