From 7ca1b2f504a77fd6d82c981242c577dae05f0b9e Mon Sep 17 00:00:00 2001 From: 12101111 Date: Tue, 3 Mar 2020 16:17:15 +0800 Subject: [PATCH 01/31] Don't use static crt by default when build proc-macro. --- src/librustc_codegen_ssa/back/link.rs | 10 +++--- src/librustc_codegen_utils/link.rs | 2 +- src/librustc_interface/util.rs | 2 +- src/librustc_metadata/dependency_format.rs | 4 +-- src/librustc_session/session.rs | 41 +++++++++++++++++----- src/test/ui/proc-macro/musl-proc-macro.rs | 15 ++++++++ 6 files changed, 57 insertions(+), 17 deletions(-) create mode 100644 src/test/ui/proc-macro/musl-proc-macro.rs diff --git a/src/librustc_codegen_ssa/back/link.rs b/src/librustc_codegen_ssa/back/link.rs index 90601521b19f1..387312addfac2 100644 --- a/src/librustc_codegen_ssa/back/link.rs +++ b/src/librustc_codegen_ssa/back/link.rs @@ -497,7 +497,7 @@ fn link_natively<'a, B: ArchiveBuilder<'a>>( cmd.args(args); } if let Some(args) = sess.target.target.options.pre_link_args_crt.get(&flavor) { - if sess.crt_static() { + if sess.crt_static(Some(crate_type)) { cmd.args(args); } } @@ -523,7 +523,7 @@ fn link_natively<'a, B: ArchiveBuilder<'a>>( cmd.arg(get_file_path(sess, obj)); } - if crate_type == config::CrateType::Executable && sess.crt_static() { + if crate_type == config::CrateType::Executable && sess.crt_static(Some(crate_type)) { for obj in &sess.target.target.options.pre_link_objects_exe_crt { cmd.arg(get_file_path(sess, obj)); } @@ -558,7 +558,7 @@ fn link_natively<'a, B: ArchiveBuilder<'a>>( for obj in &sess.target.target.options.post_link_objects { cmd.arg(get_file_path(sess, obj)); } - if sess.crt_static() { + if sess.crt_static(Some(crate_type)) { for obj in &sess.target.target.options.post_link_objects_crt { cmd.arg(get_file_path(sess, obj)); } @@ -1288,7 +1288,7 @@ fn link_args<'a, B: ArchiveBuilder<'a>>( let more_args = &sess.opts.cg.link_arg; let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter()); - if is_pic(sess) && !sess.crt_static() && !args.any(|x| *x == "-static") { + if is_pic(sess) && !sess.crt_static(Some(crate_type)) && !args.any(|x| *x == "-static") { position_independent_executable = true; } } @@ -1373,7 +1373,7 @@ fn link_args<'a, B: ArchiveBuilder<'a>>( if crate_type != config::CrateType::Executable { cmd.build_dylib(out_filename); } - if crate_type == config::CrateType::Executable && sess.crt_static() { + if crate_type == config::CrateType::Executable && sess.crt_static(Some(crate_type)) { cmd.build_static_executable(); } diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs index 524fb0a59c2f1..f80c19a79e2bc 100644 --- a/src/librustc_codegen_utils/link.rs +++ b/src/librustc_codegen_utils/link.rs @@ -167,7 +167,7 @@ pub fn invalid_output_for_target(sess: &Session, crate_type: config::CrateType) if !sess.target.target.options.dynamic_linking { return true; } - if sess.crt_static() && !sess.target.target.options.crt_static_allows_dylibs { + if sess.crt_static(Some(crate_type)) && !sess.target.target.options.crt_static_allows_dylibs { return true; } } diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs index 10a8c0a63f188..ce0665a00ec5f 100644 --- a/src/librustc_interface/util.rs +++ b/src/librustc_interface/util.rs @@ -49,7 +49,7 @@ pub fn add_configuration( cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat)))); - if sess.crt_static_feature() { + if sess.crt_static_feature(None) { cfg.insert((tf, Some(Symbol::intern("crt-static")))); } } diff --git a/src/librustc_metadata/dependency_format.rs b/src/librustc_metadata/dependency_format.rs index 9e71839dbfde6..13cda397f24a9 100644 --- a/src/librustc_metadata/dependency_format.rs +++ b/src/librustc_metadata/dependency_format.rs @@ -97,7 +97,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList { // If the global prefer_dynamic switch is turned off, or the final // executable will be statically linked, prefer static crate linkage. - config::CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static() => { + config::CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => { Linkage::Static } config::CrateType::Executable => Linkage::Dynamic, @@ -129,7 +129,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList { // If any are not found, generate some nice pretty errors. if ty == config::CrateType::Staticlib || (ty == config::CrateType::Executable - && sess.crt_static() + && sess.crt_static(Some(ty)) && !sess.target.target.options.crt_static_allows_dylibs) { for &cnum in tcx.crates().iter() { diff --git a/src/librustc_session/session.rs b/src/librustc_session/session.rs index 2fb7977dce9ee..dcd9ae44e88c1 100644 --- a/src/librustc_session/session.rs +++ b/src/librustc_session/session.rs @@ -540,25 +540,50 @@ impl Session { .unwrap_or(self.opts.debug_assertions) } - pub fn crt_static(&self) -> bool { + /// Check whether this compile session and crate type use static crt. + pub fn crt_static(&self, crate_type: Option) -> bool { // If the target does not opt in to crt-static support, use its default. if self.target.target.options.crt_static_respected { - self.crt_static_feature() + self.crt_static_feature(crate_type) } else { self.target.target.options.crt_static_default } } - pub fn crt_static_feature(&self) -> bool { + /// Check whether this compile session and crate type use `crt-static` feature. + pub fn crt_static_feature(&self, crate_type: Option) -> bool { let requested_features = self.opts.cg.target_feature.split(','); let found_negative = requested_features.clone().any(|r| r == "-crt-static"); let found_positive = requested_features.clone().any(|r| r == "+crt-static"); - // If the target we're compiling for requests a static crt by default, - // then see if the `-crt-static` feature was passed to disable that. - // Otherwise if we don't have a static crt by default then see if the - // `+crt-static` feature was passed. - if self.target.target.options.crt_static_default { !found_negative } else { found_positive } + if self.target.target.options.crt_static_default { + // `proc-macro` always required to be compiled to dylibs. + // We don't use a static crt unless the `+crt-static` feature was passed. + if !self.target.target.options.crt_static_allows_dylibs { + match crate_type { + Some(config::CrateType::ProcMacro) => found_positive, + Some(_) => !found_negative, + None => { + // FIXME: When crate_type is not available, + // we use compiler options to determine the crate_type. + // We can't check `#![crate_type = "proc-macro"]` here. + if self.opts.crate_types.contains(&config::CrateType::ProcMacro) { + found_positive + } else { + !found_negative + } + } + } + } else { + // If the target we're compiling for requests a static crt by default, + // then see if the `-crt-static` feature was passed to disable that. + !found_negative + } + } else { + // If the target we're compiling for don't have a static crt by default then see if the + // `+crt-static` feature was passed. + found_positive + } } pub fn must_not_eliminate_frame_pointers(&self) -> bool { diff --git a/src/test/ui/proc-macro/musl-proc-macro.rs b/src/test/ui/proc-macro/musl-proc-macro.rs new file mode 100644 index 0000000000000..44abfcf129b10 --- /dev/null +++ b/src/test/ui/proc-macro/musl-proc-macro.rs @@ -0,0 +1,15 @@ +// Test proc-macro crate can be built without addtional RUSTFLAGS +// on musl target + +// run-pass +// compile-flags: --target=x86_64-unknown-linux-musl +#![crate_type = "proc-macro"] + +extern crate proc_macro; + +use proc_macro::TokenStream; + +#[proc_macro_derive(Foo)] +pub fn derive_foo(input: TokenStream) -> TokenStream { + input +} From 7996df992fba0b7e09215843fcfabc0c53828c57 Mon Sep 17 00:00:00 2001 From: 12101111 Date: Tue, 3 Mar 2020 16:29:44 +0800 Subject: [PATCH 02/31] Run format. --- src/librustc_codegen_ssa/back/link.rs | 3 ++- src/librustc_codegen_utils/link.rs | 4 +++- src/librustc_metadata/dependency_format.rs | 4 +++- src/librustc_session/session.rs | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/librustc_codegen_ssa/back/link.rs b/src/librustc_codegen_ssa/back/link.rs index 387312addfac2..b6cf3a30211b9 100644 --- a/src/librustc_codegen_ssa/back/link.rs +++ b/src/librustc_codegen_ssa/back/link.rs @@ -1288,7 +1288,8 @@ fn link_args<'a, B: ArchiveBuilder<'a>>( let more_args = &sess.opts.cg.link_arg; let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter()); - if is_pic(sess) && !sess.crt_static(Some(crate_type)) && !args.any(|x| *x == "-static") { + if is_pic(sess) && !sess.crt_static(Some(crate_type)) && !args.any(|x| *x == "-static") + { position_independent_executable = true; } } diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs index f80c19a79e2bc..2850a29148ed0 100644 --- a/src/librustc_codegen_utils/link.rs +++ b/src/librustc_codegen_utils/link.rs @@ -167,7 +167,9 @@ pub fn invalid_output_for_target(sess: &Session, crate_type: config::CrateType) if !sess.target.target.options.dynamic_linking { return true; } - if sess.crt_static(Some(crate_type)) && !sess.target.target.options.crt_static_allows_dylibs { + if sess.crt_static(Some(crate_type)) + && !sess.target.target.options.crt_static_allows_dylibs + { return true; } } diff --git a/src/librustc_metadata/dependency_format.rs b/src/librustc_metadata/dependency_format.rs index 13cda397f24a9..4a9a9ddc4bd0f 100644 --- a/src/librustc_metadata/dependency_format.rs +++ b/src/librustc_metadata/dependency_format.rs @@ -97,7 +97,9 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList { // If the global prefer_dynamic switch is turned off, or the final // executable will be statically linked, prefer static crate linkage. - config::CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => { + config::CrateType::Executable + if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => + { Linkage::Static } config::CrateType::Executable => Linkage::Dynamic, diff --git a/src/librustc_session/session.rs b/src/librustc_session/session.rs index dcd9ae44e88c1..619fbdcf7f8a9 100644 --- a/src/librustc_session/session.rs +++ b/src/librustc_session/session.rs @@ -564,7 +564,7 @@ impl Session { Some(config::CrateType::ProcMacro) => found_positive, Some(_) => !found_negative, None => { - // FIXME: When crate_type is not available, + // FIXME: When crate_type is not available, // we use compiler options to determine the crate_type. // We can't check `#![crate_type = "proc-macro"]` here. if self.opts.crate_types.contains(&config::CrateType::ProcMacro) { From 89aebbdd7b6cea56284d53ab5aff5e62f1e67b67 Mon Sep 17 00:00:00 2001 From: 12101111 Date: Tue, 3 Mar 2020 19:17:24 +0800 Subject: [PATCH 03/31] Only run this test on musl --- src/test/ui/proc-macro/musl-proc-macro.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/ui/proc-macro/musl-proc-macro.rs b/src/test/ui/proc-macro/musl-proc-macro.rs index 44abfcf129b10..f025a92c43e46 100644 --- a/src/test/ui/proc-macro/musl-proc-macro.rs +++ b/src/test/ui/proc-macro/musl-proc-macro.rs @@ -1,8 +1,8 @@ // Test proc-macro crate can be built without addtional RUSTFLAGS // on musl target -// run-pass -// compile-flags: --target=x86_64-unknown-linux-musl +// build-pass +// only-musl #![crate_type = "proc-macro"] extern crate proc_macro; From 84349cc56492d70b37ec288f6f3e887858635fa4 Mon Sep 17 00:00:00 2001 From: 12101111 Date: Tue, 3 Mar 2020 19:42:27 +0800 Subject: [PATCH 04/31] Remove trailing whitespace. --- src/test/ui/proc-macro/musl-proc-macro.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/ui/proc-macro/musl-proc-macro.rs b/src/test/ui/proc-macro/musl-proc-macro.rs index f025a92c43e46..223f00eb043c5 100644 --- a/src/test/ui/proc-macro/musl-proc-macro.rs +++ b/src/test/ui/proc-macro/musl-proc-macro.rs @@ -2,7 +2,7 @@ // on musl target // build-pass -// only-musl +// only-musl #![crate_type = "proc-macro"] extern crate proc_macro; From a755d8d3328af84894e8e49cb56ea5abc26f9bb3 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 23 Feb 2020 02:38:33 +0100 Subject: [PATCH 05/31] Support type search for arguments and returned types --- src/librustdoc/clean/mod.rs | 20 ++++ src/librustdoc/clean/types.rs | 14 +-- src/librustdoc/clean/utils.rs | 40 +++++-- src/librustdoc/html/render.rs | 69 +++++++++-- src/librustdoc/html/render/cache.rs | 47 +++++--- src/librustdoc/html/static/main.js | 128 +++++++++++---------- src/test/rustdoc-js-std/return-specific.js | 7 ++ 7 files changed, 222 insertions(+), 103 deletions(-) create mode 100644 src/test/rustdoc-js-std/return-specific.js diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7c845a9b66bbd..16a73ad8d36ad 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1078,6 +1078,26 @@ impl Clean for hir::PolyTraitRef<'_> { } } +impl Clean for hir::def::DefKind { + fn clean(&self, _: &DocContext<'_>) -> TypeKind { + match *self { + hir::def::DefKind::Mod => TypeKind::Module, + hir::def::DefKind::Struct => TypeKind::Struct, + hir::def::DefKind::Union => TypeKind::Union, + hir::def::DefKind::Enum => TypeKind::Enum, + hir::def::DefKind::Trait => TypeKind::Trait, + hir::def::DefKind::TyAlias => TypeKind::Typedef, + hir::def::DefKind::ForeignTy => TypeKind::Foreign, + hir::def::DefKind::TraitAlias => TypeKind::TraitAlias, + hir::def::DefKind::Fn => TypeKind::Function, + hir::def::DefKind::Const => TypeKind::Const, + hir::def::DefKind::Static => TypeKind::Static, + hir::def::DefKind::Macro(_) => TypeKind::Macro, + _ => TypeKind::Foreign, + } + } +} + impl Clean for hir::TraitItem<'_> { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.kind { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 9c3bedfe37c7a..6ee6a52c46757 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -836,8 +836,8 @@ pub struct Method { pub decl: FnDecl, pub header: hir::FnHeader, pub defaultness: Option, - pub all_types: Vec, - pub ret_types: Vec, + pub all_types: Vec<(Type, TypeKind)>, + pub ret_types: Vec<(Type, TypeKind)>, } #[derive(Clone, Debug)] @@ -845,8 +845,8 @@ pub struct TyMethod { pub header: hir::FnHeader, pub decl: FnDecl, pub generics: Generics, - pub all_types: Vec, - pub ret_types: Vec, + pub all_types: Vec<(Type, TypeKind)>, + pub ret_types: Vec<(Type, TypeKind)>, } #[derive(Clone, Debug)] @@ -854,8 +854,8 @@ pub struct Function { pub decl: FnDecl, pub generics: Generics, pub header: hir::FnHeader, - pub all_types: Vec, - pub ret_types: Vec, + pub all_types: Vec<(Type, TypeKind)>, + pub ret_types: Vec<(Type, TypeKind)>, } #[derive(Clone, PartialEq, Eq, Debug, Hash)] @@ -1043,7 +1043,7 @@ pub enum PrimitiveType { Never, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, PartialEq, Eq, Hash, Copy, Debug)] pub enum TypeKind { Enum, Function, diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 99e3d731d0d6f..e4808a9090967 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -186,7 +186,7 @@ pub fn get_real_types( arg: &Type, cx: &DocContext<'_>, recurse: i32, -) -> FxHashSet { +) -> FxHashSet<(Type, TypeKind)> { let arg_s = arg.print().to_string(); let mut res = FxHashSet::default(); if recurse >= 10 { @@ -211,7 +211,11 @@ pub fn get_real_types( if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { - res.insert(ty); + if let Some(did) = ty.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + res.insert((ty, kind)); + } + } } } } @@ -227,13 +231,21 @@ pub fn get_real_types( if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { - res.insert(ty.clone()); + if let Some(did) = ty.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + res.insert((ty.clone(), kind)); + } + } } } } } } else { - res.insert(arg.clone()); + if let Some(did) = arg.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + res.insert((arg.clone(), kind)); + } + } if let Some(gens) = arg.generics() { for gen in gens.iter() { if gen.is_full_generic() { @@ -241,8 +253,10 @@ pub fn get_real_types( if !adds.is_empty() { res.extend(adds); } - } else { - res.insert(gen.clone()); + } else if let Some(did) = gen.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + res.insert((gen.clone(), kind)); + } } } } @@ -258,7 +272,7 @@ pub fn get_all_types( generics: &Generics, decl: &FnDecl, cx: &DocContext<'_>, -) -> (Vec, Vec) { +) -> (Vec<(Type, TypeKind)>, Vec<(Type, TypeKind)>) { let mut all_types = FxHashSet::default(); for arg in decl.inputs.values.iter() { if arg.type_.is_self_type() { @@ -268,7 +282,11 @@ pub fn get_all_types( if !args.is_empty() { all_types.extend(args); } else { - all_types.insert(arg.type_.clone()); + if let Some(did) = arg.type_.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + all_types.insert((arg.type_.clone(), kind)); + } + } } } @@ -276,7 +294,11 @@ pub fn get_all_types( FnRetTy::Return(ref return_type) => { let mut ret = get_real_types(generics, &return_type, cx, 0); if ret.is_empty() { - ret.insert(return_type.clone()); + if let Some(did) = return_type.def_id() { + if let Some(kind) = cx.tcx.def_kind(did).clean(cx) { + ret.insert((return_type.clone(), kind)); + } + } } ret.into_iter().collect() } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 4dd2a6562a4cd..79c2adc4c213f 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -59,7 +59,7 @@ use rustc_span::symbol::{sym, Symbol}; use serde::ser::SerializeSeq; use serde::{Serialize, Serializer}; -use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy}; +use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, TypeKind}; use crate::config::RenderOptions; use crate::docfs::{DocFS, ErrorStorage, PathError}; use crate::doctree; @@ -303,8 +303,10 @@ impl Serialize for IndexItem { /// A type used for the search index. #[derive(Debug)] struct Type { + ty: Option, + idx: Option, name: Option, - generics: Option>, + generics: Option>, } impl Serialize for Type { @@ -314,7 +316,11 @@ impl Serialize for Type { { if let Some(name) = &self.name { let mut seq = serializer.serialize_seq(None)?; - seq.serialize_element(&name)?; + if let Some(id) = self.idx { + seq.serialize_element(&id)?; + } else { + seq.serialize_element(&name)?; + } if let Some(generics) = &self.generics { seq.serialize_element(&generics)?; } @@ -325,11 +331,32 @@ impl Serialize for Type { } } +/// A type used for the search index. +#[derive(Debug)] +struct Generic { + name: String, + defid: Option, + idx: Option, +} + +impl Serialize for Generic { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + if let Some(id) = self.idx { + serializer.serialize_some(&id) + } else { + serializer.serialize_some(&self.name) + } + } +} + /// Full type of functions/methods in the search index. #[derive(Debug)] struct IndexItemFunctionType { - inputs: Vec, - output: Option>, + inputs: Vec, + output: Option>, } impl Serialize for IndexItemFunctionType { @@ -340,8 +367,8 @@ impl Serialize for IndexItemFunctionType { // If we couldn't figure out a type, just write `null`. let mut iter = self.inputs.iter(); if match self.output { - Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()), - None => iter.any(|ref i| i.name.is_none()), + Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()), + None => iter.any(|ref i| i.ty.name.is_none()), } { serializer.serialize_none() } else { @@ -359,6 +386,34 @@ impl Serialize for IndexItemFunctionType { } } +#[derive(Debug)] +pub struct TypeWithKind { + ty: Type, + kind: TypeKind, +} + +impl From<(Type, TypeKind)> for TypeWithKind { + fn from(x: (Type, TypeKind)) -> TypeWithKind { + TypeWithKind { + ty: x.0, + kind: x.1, + } + } +} + +impl Serialize for TypeWithKind { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(None)?; + seq.serialize_element(&self.ty.name)?; + let x: ItemType = self.kind.into(); + seq.serialize_element(&x)?; + seq.end() + } +} + thread_local!(static CACHE_KEY: RefCell> = Default::default()); thread_local!(pub static CURRENT_DEPTH: Cell = Cell::new(0)); diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index a0a35e4ce4b85..9dae5c1b05495 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use serde::Serialize; use super::{plain_summary_line, shorten, Impl, IndexItem, IndexItemFunctionType, ItemType}; -use super::{RenderInfo, Type}; +use super::{Generic, RenderInfo, Type, TypeWithKind}; /// Indicates where an external crate can be found. pub enum ExternalLocation { @@ -587,19 +587,22 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String { let mut lastpathid = 0usize; for item in search_index { - item.parent_idx = item.parent.map(|defid| { - if defid_to_pathid.contains_key(&defid) { - *defid_to_pathid.get(&defid).expect("no pathid") - } else { - let pathid = lastpathid; - defid_to_pathid.insert(defid, pathid); - lastpathid += 1; + item.parent_idx = item.parent.and_then(|defid| { + if defid_to_pathid.contains_key(&defid) { + defid_to_pathid.get(&defid).map(|x| *x) + } else { + let pathid = lastpathid; + defid_to_pathid.insert(defid, pathid); + lastpathid += 1; - let &(ref fqp, short) = paths.get(&defid).unwrap(); + if let Some(&(ref fqp, short)) = paths.get(&defid) { crate_paths.push((short, fqp.last().unwrap().clone())); - pathid + Some(pathid) + } else { + None } - }); + } + }); // Omit the parent path if it is same to that of the prior item. if lastpath == item.path { @@ -646,12 +649,15 @@ fn get_index_search_type(item: &clean::Item) -> Option { _ => return None, }; - let inputs = - all_types.iter().map(|arg| get_index_type(&arg)).filter(|a| a.name.is_some()).collect(); + let inputs = all_types + .iter() + .map(|(ty, kind)| TypeWithKind::from((get_index_type(&ty), *kind))) + .filter(|a| a.ty.name.is_some()) + .collect(); let output = ret_types .iter() - .map(|arg| get_index_type(&arg)) - .filter(|a| a.name.is_some()) + .map(|(ty, kind)| TypeWithKind::from((get_index_type(&ty), *kind))) + .filter(|a| a.ty.name.is_some()) .collect::>(); let output = if output.is_empty() { None } else { Some(output) }; @@ -660,6 +666,8 @@ fn get_index_search_type(item: &clean::Item) -> Option { fn get_index_type(clean_type: &clean::Type) -> Type { let t = Type { + ty: clean_type.def_id(), + idx: None, name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()), generics: get_generics(clean_type), }; @@ -684,12 +692,15 @@ fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option } } -fn get_generics(clean_type: &clean::Type) -> Option> { +fn get_generics(clean_type: &clean::Type) -> Option> { clean_type.generics().and_then(|types| { let r = types .iter() - .filter_map(|t| get_index_type_name(t, false)) - .map(|s| s.to_ascii_lowercase()) + .filter_map(|t| if let Some(name) = get_index_type_name(t, false) { + Some(Generic { name: name.to_ascii_lowercase(), defid: t.def_id(), idx: None }) + } else { + None + }) .collect::>(); if r.is_empty() { None } else { Some(r) } }) diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 2870c6e0a6147..735044af5afc0 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -526,13 +526,14 @@ function getSearchElement() { } function initSearch(rawSearchIndex) { - var currentResults, index, searchIndex; var MAX_LEV_DISTANCE = 3; var MAX_RESULTS = 200; var GENERICS_DATA = 1; var NAME = 0; var INPUTS_DATA = 0; var OUTPUT_DATA = 1; + var NO_TYPE_FILTER = -1; + var currentResults, index, searchIndex; var params = getQueryStringParams(); // Populate search bar with query string search term when provided, @@ -559,7 +560,7 @@ function getSearchElement() { return i; } } - return -1; + return NO_TYPE_FILTER; } var valLower = query.query.toLowerCase(), @@ -722,6 +723,13 @@ function getSearchElement() { }; } + function getObjectFromId(id) { + if (typeof id === "number") { + return searchIndex[id]; + } + return {'name': id}; + } + function checkGenerics(obj, val) { // The names match, but we need to be sure that all generics kinda // match as well. @@ -738,8 +746,10 @@ function getSearchElement() { for (var y = 0; y < vlength; ++y) { var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1}; var elength = elems.length; + var firstGeneric = getObjectFromId(val.generics[y]).name; for (var x = 0; x < elength; ++x) { - var tmp_lev = levenshtein(elems[x], val.generics[y]); + var tmp_lev = levenshtein(getObjectFromId(elems[x]).name, + firstGeneric); if (tmp_lev < lev.lev) { lev.lev = tmp_lev; lev.pos = x; @@ -774,8 +784,9 @@ function getSearchElement() { for (var y = 0; allFound === true && y < val.generics.length; ++y) { allFound = false; + var firstGeneric = getObjectFromId(val.generics[y]).name; for (x = 0; allFound === false && x < elems.length; ++x) { - allFound = elems[x] === val.generics[y]; + allFound = getObjectFromId(elems[x]).name === firstGeneric; } if (allFound === true) { elems.splice(x - 1, 1); @@ -832,16 +843,23 @@ function getSearchElement() { return lev_distance + 1; } - function findArg(obj, val, literalSearch) { + function findArg(obj, val, literalSearch, typeFilter) { var lev_distance = MAX_LEV_DISTANCE + 1; - if (obj && obj.type && obj.type[INPUTS_DATA] && - obj.type[INPUTS_DATA].length > 0) { + if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) { var length = obj.type[INPUTS_DATA].length; for (var i = 0; i < length; i++) { - var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch); - if (literalSearch === true && tmp === true) { - return true; + var tmp = obj.type[INPUTS_DATA][i]; + if (typePassesFilter(typeFilter, tmp[1]) === false) { + continue; + } + tmp[0] = tmp[NAME]; + var tmp = checkType(tmp, val, literalSearch); + if (literalSearch === true) { + if (tmp === true) { + return true; + } + continue; } lev_distance = Math.min(tmp, lev_distance); if (lev_distance === 0) { @@ -852,19 +870,20 @@ function getSearchElement() { return literalSearch === true ? false : lev_distance; } - function checkReturned(obj, val, literalSearch) { + function checkReturned(obj, val, literalSearch, typeFilter) { var lev_distance = MAX_LEV_DISTANCE + 1; if (obj && obj.type && obj.type.length > OUTPUT_DATA) { var ret = obj.type[OUTPUT_DATA]; - if (!obj.type[OUTPUT_DATA].length) { + if (typeof ret[0] === "string") { ret = [ret]; } for (var x = 0; x < ret.length; ++x) { var r = ret[x]; - if (typeof r === "string") { - r = [r]; + if (typePassesFilter(typeFilter, r[1]) === false) { + continue; } + r[0] = r[NAME]; var tmp = checkType(r, val, literalSearch); if (literalSearch === true) { if (tmp === true) { @@ -920,7 +939,7 @@ function getSearchElement() { function typePassesFilter(filter, type) { // No filter - if (filter < 0) return true; + if (filter <= NO_TYPE_FILTER) return true; // Exact match if (filter === type) return true; @@ -929,11 +948,13 @@ function getSearchElement() { var name = itemTypes[type]; switch (itemTypes[filter]) { case "constant": - return (name == "associatedconstant"); + return name === "associatedconstant"; case "fn": - return (name == "method" || name == "tymethod"); + return name === "method" || name === "tymethod"; case "type": - return (name == "primitive" || name == "keyword"); + return name === "primitive" || name === "associatedtype"; + case "trait": + return name === "traitalias"; } // No match @@ -962,42 +983,33 @@ function getSearchElement() { if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) { continue; } - in_args = findArg(searchIndex[i], val, true); - returned = checkReturned(searchIndex[i], val, true); + in_args = findArg(searchIndex[i], val, true, typeFilter); + returned = checkReturned(searchIndex[i], val, true, typeFilter); ty = searchIndex[i]; fullId = generateId(ty); - if (searchWords[i] === val.name) { - // filter type: ... queries - if (typePassesFilter(typeFilter, searchIndex[i].ty) && - results[fullId] === undefined) - { - results[fullId] = {id: i, index: -1}; - } - } else if ((in_args === true || returned === true) && - typePassesFilter(typeFilter, searchIndex[i].ty)) { - if (in_args === true || returned === true) { - if (in_args === true) { - results_in_args[fullId] = { - id: i, - index: -1, - dontValidate: true, - }; - } - if (returned === true) { - results_returned[fullId] = { - id: i, - index: -1, - dontValidate: true, - }; - } - } else { - results[fullId] = { - id: i, - index: -1, - dontValidate: true, - }; - } + if (searchWords[i] === val.name + && typePassesFilter(typeFilter, searchIndex[i].ty) + && results[fullId] === undefined) { + results[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + if (in_args === true && results_in_args[fullId] === undefined) { + results_in_args[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; + } + if (returned === true && results_returned[fullId] === undefined) { + results_returned[fullId] = { + id: i, + index: -1, + dontValidate: true, + }; } } query.inputs = [val]; @@ -1028,7 +1040,7 @@ function getSearchElement() { // allow searching for void (no output) functions as well var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : ""; - returned = checkReturned(ty, output, true); + returned = checkReturned(ty, output, true, NO_TYPE_FILTER); if (output.name === "*" || returned === true) { in_args = false; var is_module = false; @@ -1129,16 +1141,8 @@ function getSearchElement() { lev += 1; } } - if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) { - if (typePassesFilter(typeFilter, ty.ty) === false) { - in_args = MAX_LEV_DISTANCE + 1; - } - } - if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) { - if (typePassesFilter(typeFilter, ty.ty) === false) { - returned = MAX_LEV_DISTANCE + 1; - } - } + in_args = findArg(ty, valGenerics, false, typeFilter); + returned = checkReturned(ty, valGenerics, false, typeFilter); lev += lev_add; if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) { diff --git a/src/test/rustdoc-js-std/return-specific.js b/src/test/rustdoc-js-std/return-specific.js new file mode 100644 index 0000000000000..6cdeefd10caa8 --- /dev/null +++ b/src/test/rustdoc-js-std/return-specific.js @@ -0,0 +1,7 @@ +const QUERY = 'struct:chunksmut'; + +const EXPECTED = { + 'returned': [ + { 'path': 'std::slice::chunks_mut', 'name': 'chunks_mut' }, + ], +}; From 612d375574de654021b50784d0a476f88f2bd44e Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 23 Feb 2020 18:23:09 +0100 Subject: [PATCH 06/31] Update JS results tester --- src/test/rustdoc-js-std/return-specific.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/rustdoc-js-std/return-specific.js b/src/test/rustdoc-js-std/return-specific.js index 6cdeefd10caa8..d9a910553b8de 100644 --- a/src/test/rustdoc-js-std/return-specific.js +++ b/src/test/rustdoc-js-std/return-specific.js @@ -1,7 +1,10 @@ -const QUERY = 'struct:chunksmut'; +const QUERY = 'struct:string'; const EXPECTED = { + 'in_args': [ + { 'path': 'std::string::String', 'name': 'ne' }, + ], 'returned': [ - { 'path': 'std::slice::chunks_mut', 'name': 'chunks_mut' }, + { 'path': 'std::string::String', 'name': 'add' }, ], }; From 5892d0d010b44a2c5815c8f5d1bead1b99608979 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 23 Feb 2020 18:23:52 +0100 Subject: [PATCH 07/31] Add tests for new of variables --- src/test/rustdoc-js-std/return-specific-literal.js | 10 ++++++++++ src/tools/rustdoc-js-std/tester.js | 5 +++-- 2 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 src/test/rustdoc-js-std/return-specific-literal.js diff --git a/src/test/rustdoc-js-std/return-specific-literal.js b/src/test/rustdoc-js-std/return-specific-literal.js new file mode 100644 index 0000000000000..c7c347240b751 --- /dev/null +++ b/src/test/rustdoc-js-std/return-specific-literal.js @@ -0,0 +1,10 @@ +const QUERY = 'struct:"string"'; + +const EXPECTED = { + 'in_args': [ + { 'path': 'std::string::String', 'name': 'ne' }, + ], + 'returned': [ + { 'path': 'std::string::String', 'name': 'add' }, + ], +}; diff --git a/src/tools/rustdoc-js-std/tester.js b/src/tools/rustdoc-js-std/tester.js index d5f0ab9f4292d..67640381a4c27 100644 --- a/src/tools/rustdoc-js-std/tester.js +++ b/src/tools/rustdoc-js-std/tester.js @@ -253,6 +253,7 @@ function main(argv) { } var toolchain = argv[2]; + console.log(toolchain); var mainJs = readFileMatching("build/" + toolchain + "/doc/", "main", ".js"); var ALIASES = readFileMatching("build/" + toolchain + "/doc/", "aliases", ".js"); var searchIndex = readFileMatching("build/" + toolchain + "/doc/", @@ -265,7 +266,7 @@ function main(argv) { finalJS = ""; var arraysToLoad = ["itemTypes"]; - var variablesToLoad = ["MAX_LEV_DISTANCE", "MAX_RESULTS", + var variablesToLoad = ["MAX_LEV_DISTANCE", "MAX_RESULTS", "NO_TYPE_FILTER", "GENERICS_DATA", "NAME", "INPUTS_DATA", "OUTPUT_DATA", "TY_PRIMITIVE", "TY_KEYWORD", "levenshtein_row2"]; @@ -338,7 +339,7 @@ function main(argv) { console.log("OK"); } }); - return errors; + return errors > 0 ? 1 : 0; } process.exit(main(process.argv)); From 71b9512ae34e1f3ee810fd8ea580db1167218f20 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 23 Feb 2020 19:09:00 +0100 Subject: [PATCH 08/31] formatting --- src/librustdoc/html/render.rs | 5 +--- src/librustdoc/html/render/cache.rs | 36 +++++++++++++++-------------- src/librustdoc/html/static/main.js | 10 ++++---- 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 79c2adc4c213f..c18fea942e919 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -394,10 +394,7 @@ pub struct TypeWithKind { impl From<(Type, TypeKind)> for TypeWithKind { fn from(x: (Type, TypeKind)) -> TypeWithKind { - TypeWithKind { - ty: x.0, - kind: x.1, - } + TypeWithKind { ty: x.0, kind: x.1 } } } diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index 9dae5c1b05495..bd703235f5ddb 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -588,21 +588,21 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String { for item in search_index { item.parent_idx = item.parent.and_then(|defid| { - if defid_to_pathid.contains_key(&defid) { - defid_to_pathid.get(&defid).map(|x| *x) - } else { - let pathid = lastpathid; - defid_to_pathid.insert(defid, pathid); - lastpathid += 1; - - if let Some(&(ref fqp, short)) = paths.get(&defid) { - crate_paths.push((short, fqp.last().unwrap().clone())); - Some(pathid) + if defid_to_pathid.contains_key(&defid) { + defid_to_pathid.get(&defid).map(|x| *x) } else { - None + let pathid = lastpathid; + defid_to_pathid.insert(defid, pathid); + lastpathid += 1; + + if let Some(&(ref fqp, short)) = paths.get(&defid) { + crate_paths.push((short, fqp.last().unwrap().clone())); + Some(pathid) + } else { + None + } } - } - }); + }); // Omit the parent path if it is same to that of the prior item. if lastpath == item.path { @@ -696,10 +696,12 @@ fn get_generics(clean_type: &clean::Type) -> Option> { clean_type.generics().and_then(|types| { let r = types .iter() - .filter_map(|t| if let Some(name) = get_index_type_name(t, false) { - Some(Generic { name: name.to_ascii_lowercase(), defid: t.def_id(), idx: None }) - } else { - None + .filter_map(|t| { + if let Some(name) = get_index_type_name(t, false) { + Some(Generic { name: name.to_ascii_lowercase(), defid: t.def_id(), idx: None }) + } else { + None + } }) .collect::>(); if r.is_empty() { None } else { Some(r) } diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 735044af5afc0..fdb143e18e653 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -853,8 +853,7 @@ function getSearchElement() { if (typePassesFilter(typeFilter, tmp[1]) === false) { continue; } - tmp[0] = tmp[NAME]; - var tmp = checkType(tmp, val, literalSearch); + tmp = checkType(tmp, val, literalSearch); if (literalSearch === true) { if (tmp === true) { return true; @@ -879,12 +878,11 @@ function getSearchElement() { ret = [ret]; } for (var x = 0; x < ret.length; ++x) { - var r = ret[x]; - if (typePassesFilter(typeFilter, r[1]) === false) { + var tmp = ret[x]; + if (typePassesFilter(typeFilter, tmp[1]) === false) { continue; } - r[0] = r[NAME]; - var tmp = checkType(r, val, literalSearch); + tmp = checkType(r, val, literalSearch); if (literalSearch === true) { if (tmp === true) { return true; From 6ffe9f30e6d986961a6d745206f46e36a05cd30d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 3 Mar 2020 15:53:16 +0100 Subject: [PATCH 09/31] Rename render::Type to improve naming --- src/librustdoc/html/render.rs | 10 +++++----- src/librustdoc/html/render/cache.rs | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index c18fea942e919..e700cecd1e4e2 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -302,14 +302,14 @@ impl Serialize for IndexItem { /// A type used for the search index. #[derive(Debug)] -struct Type { +struct RenderType { ty: Option, idx: Option, name: Option, generics: Option>, } -impl Serialize for Type { +impl Serialize for RenderType { fn serialize(&self, serializer: S) -> Result where S: Serializer, @@ -388,12 +388,12 @@ impl Serialize for IndexItemFunctionType { #[derive(Debug)] pub struct TypeWithKind { - ty: Type, + ty: RenderType, kind: TypeKind, } -impl From<(Type, TypeKind)> for TypeWithKind { - fn from(x: (Type, TypeKind)) -> TypeWithKind { +impl From<(RenderType, TypeKind)> for TypeWithKind { + fn from(x: (RenderType, TypeKind)) -> TypeWithKind { TypeWithKind { ty: x.0, kind: x.1 } } } diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index bd703235f5ddb..bcc1a6bdb01dd 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -12,7 +12,7 @@ use std::path::{Path, PathBuf}; use serde::Serialize; use super::{plain_summary_line, shorten, Impl, IndexItem, IndexItemFunctionType, ItemType}; -use super::{Generic, RenderInfo, Type, TypeWithKind}; +use super::{Generic, RenderInfo, RenderType, TypeWithKind}; /// Indicates where an external crate can be found. pub enum ExternalLocation { @@ -664,8 +664,8 @@ fn get_index_search_type(item: &clean::Item) -> Option { Some(IndexItemFunctionType { inputs, output }) } -fn get_index_type(clean_type: &clean::Type) -> Type { - let t = Type { +fn get_index_type(clean_type: &clean::Type) -> RenderType { + let t = RenderType { ty: clean_type.def_id(), idx: None, name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()), From f63b88c761f935d9b2c220a1b4e3abf0c0681c69 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Sat, 15 Feb 2020 19:04:20 -0500 Subject: [PATCH 10/31] Permit attributes on 'if' expressions Previously, attributes on 'if' expressions (e.g. #[attr] if true {}) were disallowed during parsing. This made it impossible for macros to perform any custom handling of such attributes (e.g. stripping them away), since a compilation error would be emitted before they ever had a chance to run. This PR permits attributes on 'if' expressions ('if-attrs' from here on). Both built-in attributes (e.g. `#[allow]`, `#[cfg]`) are supported. We still do *not* accept attributes on 'other parts' of an if-else chain. That is, the following code snippet still fails to parse: ```rust if true {} #[attr] else if false {} else #[attr] if false {} #[attr] else {} ``` --- src/librustc_parse/parser/expr.rs | 9 ------ src/test/pretty/if-attr.rs | 28 +++++++++++++++++ src/test/ui/parser/attr-stmt-expr-attr-bad.rs | 10 ++---- .../ui/parser/if-attrs/cfg-false-if-attr.rs | 31 +++++++++++++++++++ src/test/ui/parser/if-attrs/else-attrs.rs | 25 +++++++++++++++ src/test/ui/parser/if-attrs/else-attrs.stderr | 27 ++++++++++++++++ .../ui/parser/if-attrs/let-chains-attr.rs | 13 ++++++++ .../ui/parser/if-attrs/let-chains-attr.stderr | 8 +++++ src/test/ui/parser/recovery-attr-on-if.rs | 2 -- src/test/ui/parser/recovery-attr-on-if.stderr | 18 ++--------- 10 files changed, 137 insertions(+), 34 deletions(-) create mode 100644 src/test/pretty/if-attr.rs create mode 100644 src/test/ui/parser/if-attrs/cfg-false-if-attr.rs create mode 100644 src/test/ui/parser/if-attrs/else-attrs.rs create mode 100644 src/test/ui/parser/if-attrs/else-attrs.stderr create mode 100644 src/test/ui/parser/if-attrs/let-chains-attr.rs create mode 100644 src/test/ui/parser/if-attrs/let-chains-attr.stderr diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index 18ddd23588e48..f31686afd1a0b 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -665,20 +665,11 @@ impl<'a> Parser<'a> { expr.map(|mut expr| { attrs.extend::>(expr.attrs.into()); expr.attrs = attrs; - self.error_attr_on_if_expr(&expr); expr }) }) } - fn error_attr_on_if_expr(&self, expr: &Expr) { - if let (ExprKind::If(..), [a0, ..]) = (&expr.kind, &*expr.attrs) { - // Just point to the first attribute in there... - self.struct_span_err(a0.span, "attributes are not yet allowed on `if` expressions") - .emit(); - } - } - fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { loop { if self.eat(&token::Question) { diff --git a/src/test/pretty/if-attr.rs b/src/test/pretty/if-attr.rs new file mode 100644 index 0000000000000..463476737a92f --- /dev/null +++ b/src/test/pretty/if-attr.rs @@ -0,0 +1,28 @@ +// pp-exact + +#[cfg(FALSE)] +fn simple_attr() { + + #[attr] + if true { } + + #[allow_warnings] + if true { } +} + +#[cfg(FALSE)] +fn if_else_chain() { + + #[first_attr] + if true { } else if false { } else { } +} + +#[cfg(FALSE)] +fn if_let() { + + #[attr] + if let Some(_) = Some(true) { } +} + + +fn main() { } diff --git a/src/test/ui/parser/attr-stmt-expr-attr-bad.rs b/src/test/ui/parser/attr-stmt-expr-attr-bad.rs index 118bff8144c7f..f3980a596481c 100644 --- a/src/test/ui/parser/attr-stmt-expr-attr-bad.rs +++ b/src/test/ui/parser/attr-stmt-expr-attr-bad.rs @@ -38,8 +38,6 @@ fn main() {} //~^ ERROR an inner attribute is not permitted in this context #[cfg(FALSE)] fn e() { let _ = #[attr] &mut #![attr] 0; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = #[attr] if 0 {}; } -//~^ ERROR attributes are not yet allowed on `if` expressions #[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } //~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } @@ -51,14 +49,11 @@ fn main() {} #[cfg(FALSE)] fn e() { let _ = if 0 {} else {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } -//~^ ERROR attributes are not yet allowed on `if` expressions -//~| ERROR expected `{`, found `#` +//~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } //~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context -#[cfg(FALSE)] fn e() { let _ = #[attr] if let _ = 0 {}; } -//~^ ERROR attributes are not yet allowed on `if` expressions #[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } //~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } @@ -70,8 +65,7 @@ fn main() {} #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } //~^ ERROR an inner attribute is not permitted in this context #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } -//~^ ERROR attributes are not yet allowed on `if` expressions -//~| ERROR expected `{`, found `#` +//~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } //~^ ERROR expected `{`, found `#` #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } diff --git a/src/test/ui/parser/if-attrs/cfg-false-if-attr.rs b/src/test/ui/parser/if-attrs/cfg-false-if-attr.rs new file mode 100644 index 0000000000000..2932ec1a23195 --- /dev/null +++ b/src/test/ui/parser/if-attrs/cfg-false-if-attr.rs @@ -0,0 +1,31 @@ +// check-pass + +#[cfg(FALSE)] +fn simple_attr() { + #[attr] if true {} + #[allow_warnings] if true {} +} + +#[cfg(FALSE)] +fn if_else_chain() { + #[first_attr] if true { + } else if false { + } else { + } +} + +#[cfg(FALSE)] +fn if_let() { + #[attr] if let Some(_) = Some(true) {} +} + +macro_rules! custom_macro { + ($expr:expr) => {} +} + +custom_macro! { + #[attr] if true {} +} + + +fn main() {} diff --git a/src/test/ui/parser/if-attrs/else-attrs.rs b/src/test/ui/parser/if-attrs/else-attrs.rs new file mode 100644 index 0000000000000..4394b2100c1b5 --- /dev/null +++ b/src/test/ui/parser/if-attrs/else-attrs.rs @@ -0,0 +1,25 @@ +#[cfg(FALSE)] +fn if_else_parse_error() { + if true { + } #[attr] else if false { //~ ERROR expected + } +} + +#[cfg(FALSE)] +fn else_attr_ifparse_error() { + if true { + } else #[attr] if false { //~ ERROR expected + } else { + } +} + +#[cfg(FALSE)] +fn else_parse_error() { + if true { + } else if false { + } #[attr] else { //~ ERROR expected + } +} + +fn main() { +} diff --git a/src/test/ui/parser/if-attrs/else-attrs.stderr b/src/test/ui/parser/if-attrs/else-attrs.stderr new file mode 100644 index 0000000000000..af25b6abc0a3a --- /dev/null +++ b/src/test/ui/parser/if-attrs/else-attrs.stderr @@ -0,0 +1,27 @@ +error: expected expression, found keyword `else` + --> $DIR/else-attrs.rs:4:15 + | +LL | } #[attr] else if false { + | ^^^^ expected expression + +error: expected `{`, found `#` + --> $DIR/else-attrs.rs:11:12 + | +LL | } else #[attr] if false { + | ^ expected `{` + | +help: try placing this code inside a block + | +LL | } else #[attr] { if false { +LL | } else { +LL | } } + | + +error: expected expression, found keyword `else` + --> $DIR/else-attrs.rs:20:15 + | +LL | } #[attr] else { + | ^^^^ expected expression + +error: aborting due to 3 previous errors + diff --git a/src/test/ui/parser/if-attrs/let-chains-attr.rs b/src/test/ui/parser/if-attrs/let-chains-attr.rs new file mode 100644 index 0000000000000..5237a9ff3961a --- /dev/null +++ b/src/test/ui/parser/if-attrs/let-chains-attr.rs @@ -0,0 +1,13 @@ +// check-pass + +#![feature(let_chains)] //~ WARN the feature `let_chains` is incomplete + +#[cfg(FALSE)] +fn foo() { + #[attr] + if let Some(_) = Some(true) && let Ok(_) = Ok(1) { + } else if let Some(false) = Some(true) { + } +} + +fn main() {} diff --git a/src/test/ui/parser/if-attrs/let-chains-attr.stderr b/src/test/ui/parser/if-attrs/let-chains-attr.stderr new file mode 100644 index 0000000000000..a6c91bb9203b3 --- /dev/null +++ b/src/test/ui/parser/if-attrs/let-chains-attr.stderr @@ -0,0 +1,8 @@ +warning: the feature `let_chains` is incomplete and may cause the compiler to crash + --> $DIR/let-chains-attr.rs:3:12 + | +LL | #![feature(let_chains)] + | ^^^^^^^^^^ + | + = note: `#[warn(incomplete_features)]` on by default + diff --git a/src/test/ui/parser/recovery-attr-on-if.rs b/src/test/ui/parser/recovery-attr-on-if.rs index 0d1f5be7b4930..b4fb25ec8d344 100644 --- a/src/test/ui/parser/recovery-attr-on-if.rs +++ b/src/test/ui/parser/recovery-attr-on-if.rs @@ -1,9 +1,7 @@ fn main() { #[attr] if true {}; //~^ ERROR cannot find attribute - //~| ERROR attributes are not yet allowed on `if` expressions #[attr] if true {}; //~^ ERROR cannot find attribute - //~| ERROR attributes are not yet allowed on `if` expressions let _recovery_witness: () = 0; //~ ERROR mismatched types } diff --git a/src/test/ui/parser/recovery-attr-on-if.stderr b/src/test/ui/parser/recovery-attr-on-if.stderr index a02846827c9ab..cbf2714a1a1de 100644 --- a/src/test/ui/parser/recovery-attr-on-if.stderr +++ b/src/test/ui/parser/recovery-attr-on-if.stderr @@ -1,17 +1,5 @@ -error: attributes are not yet allowed on `if` expressions - --> $DIR/recovery-attr-on-if.rs:2:5 - | -LL | #[attr] if true {}; - | ^^^^^^^ - -error: attributes are not yet allowed on `if` expressions - --> $DIR/recovery-attr-on-if.rs:5:5 - | -LL | #[attr] if true {}; - | ^^^^^^^ - error: cannot find attribute `attr` in this scope - --> $DIR/recovery-attr-on-if.rs:5:7 + --> $DIR/recovery-attr-on-if.rs:4:7 | LL | #[attr] if true {}; | ^^^^ @@ -23,13 +11,13 @@ LL | #[attr] if true {}; | ^^^^ error[E0308]: mismatched types - --> $DIR/recovery-attr-on-if.rs:8:33 + --> $DIR/recovery-attr-on-if.rs:6:33 | LL | let _recovery_witness: () = 0; | -- ^ expected `()`, found integer | | | expected due to this -error: aborting due to 5 previous errors +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. From e912d9d7ecd9d326affd18f7b133dafb72ee8896 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Sat, 15 Feb 2020 19:13:36 -0500 Subject: [PATCH 11/31] Test #[allow(unused)] on `if` expression --- src/test/ui/parser/if-attrs/builtin-if-attr.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/test/ui/parser/if-attrs/builtin-if-attr.rs diff --git a/src/test/ui/parser/if-attrs/builtin-if-attr.rs b/src/test/ui/parser/if-attrs/builtin-if-attr.rs new file mode 100644 index 0000000000000..7e290661501c9 --- /dev/null +++ b/src/test/ui/parser/if-attrs/builtin-if-attr.rs @@ -0,0 +1,12 @@ +// check-pass + +fn main() { + #[allow(unused_variables)] + if true { + let a = 1; + } else if false { + let b = 1; + } else { + let c = 1; + } +} From e9ec47bb70810f972e6565d496120b0b00f261f0 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 10:45:21 -0500 Subject: [PATCH 12/31] Test that stmt_expr_attrs properly gates if-attrs --- src/test/ui/parser/if-attrs/stmt-expr-gated.rs | 6 ++++++ src/test/ui/parser/if-attrs/stmt-expr-gated.stderr | 12 ++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 src/test/ui/parser/if-attrs/stmt-expr-gated.rs create mode 100644 src/test/ui/parser/if-attrs/stmt-expr-gated.stderr diff --git a/src/test/ui/parser/if-attrs/stmt-expr-gated.rs b/src/test/ui/parser/if-attrs/stmt-expr-gated.rs new file mode 100644 index 0000000000000..38599c8e67c4e --- /dev/null +++ b/src/test/ui/parser/if-attrs/stmt-expr-gated.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = #[deny(warnings)] if true { //~ ERROR attributes on expressions + } else if false { + } else { + }; +} diff --git a/src/test/ui/parser/if-attrs/stmt-expr-gated.stderr b/src/test/ui/parser/if-attrs/stmt-expr-gated.stderr new file mode 100644 index 0000000000000..47dac39a9ae88 --- /dev/null +++ b/src/test/ui/parser/if-attrs/stmt-expr-gated.stderr @@ -0,0 +1,12 @@ +error[E0658]: attributes on expressions are experimental + --> $DIR/stmt-expr-gated.rs:2:13 + | +LL | let _ = #[deny(warnings)] if true { + | ^^^^^^^^^^^^^^^^^ + | + = note: see issue #15701 for more information + = help: add `#![feature(stmt_expr_attributes)]` to the crate attributes to enable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0658`. From 9a299e4e210ff91ec59bf9f09bdb402196e02bd5 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 10:47:27 -0500 Subject: [PATCH 13/31] Test trying to cfg-remove an `if` expression --- src/test/ui/parser/if-attrs/bad-cfg.rs | 5 +++++ src/test/ui/parser/if-attrs/bad-cfg.stderr | 8 ++++++++ 2 files changed, 13 insertions(+) create mode 100644 src/test/ui/parser/if-attrs/bad-cfg.rs create mode 100644 src/test/ui/parser/if-attrs/bad-cfg.stderr diff --git a/src/test/ui/parser/if-attrs/bad-cfg.rs b/src/test/ui/parser/if-attrs/bad-cfg.rs new file mode 100644 index 0000000000000..3f84929a00e4f --- /dev/null +++ b/src/test/ui/parser/if-attrs/bad-cfg.rs @@ -0,0 +1,5 @@ +#![feature(stmt_expr_attributes)] + +fn main() { + let _ = #[cfg(FALSE)] if true {}; //~ ERROR removing an expression +} diff --git a/src/test/ui/parser/if-attrs/bad-cfg.stderr b/src/test/ui/parser/if-attrs/bad-cfg.stderr new file mode 100644 index 0000000000000..8a2890886a15c --- /dev/null +++ b/src/test/ui/parser/if-attrs/bad-cfg.stderr @@ -0,0 +1,8 @@ +error: removing an expression is not supported in this position + --> $DIR/bad-cfg.rs:4:13 + | +LL | let _ = #[cfg(FALSE)] if true {}; + | ^^^^^^^^^^^^^ + +error: aborting due to previous error + From b00f6745c4df0e979dd53dcbf43ededf5728e349 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 10:48:13 -0500 Subject: [PATCH 14/31] Remove recovery test --- src/test/ui/parser/recovery-attr-on-if.rs | 7 ------ src/test/ui/parser/recovery-attr-on-if.stderr | 23 ------------------- 2 files changed, 30 deletions(-) delete mode 100644 src/test/ui/parser/recovery-attr-on-if.rs delete mode 100644 src/test/ui/parser/recovery-attr-on-if.stderr diff --git a/src/test/ui/parser/recovery-attr-on-if.rs b/src/test/ui/parser/recovery-attr-on-if.rs deleted file mode 100644 index b4fb25ec8d344..0000000000000 --- a/src/test/ui/parser/recovery-attr-on-if.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - #[attr] if true {}; - //~^ ERROR cannot find attribute - #[attr] if true {}; - //~^ ERROR cannot find attribute - let _recovery_witness: () = 0; //~ ERROR mismatched types -} diff --git a/src/test/ui/parser/recovery-attr-on-if.stderr b/src/test/ui/parser/recovery-attr-on-if.stderr deleted file mode 100644 index cbf2714a1a1de..0000000000000 --- a/src/test/ui/parser/recovery-attr-on-if.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error: cannot find attribute `attr` in this scope - --> $DIR/recovery-attr-on-if.rs:4:7 - | -LL | #[attr] if true {}; - | ^^^^ - -error: cannot find attribute `attr` in this scope - --> $DIR/recovery-attr-on-if.rs:2:7 - | -LL | #[attr] if true {}; - | ^^^^ - -error[E0308]: mismatched types - --> $DIR/recovery-attr-on-if.rs:6:33 - | -LL | let _recovery_witness: () = 0; - | -- ^ expected `()`, found integer - | | - | expected due to this - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0308`. From e11cdfdae48f8793c618834227114bcb5a6d57bd Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 10:49:34 -0500 Subject: [PATCH 15/31] Add run-pass test suggested by @joshtriplett --- src/test/ui/parser/if-attrs/gate-whole-expr.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/test/ui/parser/if-attrs/gate-whole-expr.rs diff --git a/src/test/ui/parser/if-attrs/gate-whole-expr.rs b/src/test/ui/parser/if-attrs/gate-whole-expr.rs new file mode 100644 index 0000000000000..efce28e1d5bb2 --- /dev/null +++ b/src/test/ui/parser/if-attrs/gate-whole-expr.rs @@ -0,0 +1,15 @@ +// run-pass + +fn main() { + let x = 1; + + #[cfg(FALSE)] + if false { + x = 2; + } else if true { + x = 3; + } else { + x = 4; + } + assert_eq!(x, 1); +} From 7f19358c9ef51a130e0177d327eaac5adc6d73ad Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 10:50:03 -0500 Subject: [PATCH 16/31] Move if-attr tests to their own directory --- src/test/ui/{parser => }/if-attrs/bad-cfg.rs | 0 src/test/ui/{parser => }/if-attrs/bad-cfg.stderr | 0 src/test/ui/{parser => }/if-attrs/builtin-if-attr.rs | 0 src/test/ui/{parser => }/if-attrs/cfg-false-if-attr.rs | 0 src/test/ui/{parser => }/if-attrs/else-attrs.rs | 0 src/test/ui/{parser => }/if-attrs/else-attrs.stderr | 0 src/test/ui/{parser => }/if-attrs/gate-whole-expr.rs | 0 src/test/ui/{parser => }/if-attrs/let-chains-attr.rs | 0 src/test/ui/{parser => }/if-attrs/let-chains-attr.stderr | 0 src/test/ui/{parser => }/if-attrs/stmt-expr-gated.rs | 0 src/test/ui/{parser => }/if-attrs/stmt-expr-gated.stderr | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename src/test/ui/{parser => }/if-attrs/bad-cfg.rs (100%) rename src/test/ui/{parser => }/if-attrs/bad-cfg.stderr (100%) rename src/test/ui/{parser => }/if-attrs/builtin-if-attr.rs (100%) rename src/test/ui/{parser => }/if-attrs/cfg-false-if-attr.rs (100%) rename src/test/ui/{parser => }/if-attrs/else-attrs.rs (100%) rename src/test/ui/{parser => }/if-attrs/else-attrs.stderr (100%) rename src/test/ui/{parser => }/if-attrs/gate-whole-expr.rs (100%) rename src/test/ui/{parser => }/if-attrs/let-chains-attr.rs (100%) rename src/test/ui/{parser => }/if-attrs/let-chains-attr.stderr (100%) rename src/test/ui/{parser => }/if-attrs/stmt-expr-gated.rs (100%) rename src/test/ui/{parser => }/if-attrs/stmt-expr-gated.stderr (100%) diff --git a/src/test/ui/parser/if-attrs/bad-cfg.rs b/src/test/ui/if-attrs/bad-cfg.rs similarity index 100% rename from src/test/ui/parser/if-attrs/bad-cfg.rs rename to src/test/ui/if-attrs/bad-cfg.rs diff --git a/src/test/ui/parser/if-attrs/bad-cfg.stderr b/src/test/ui/if-attrs/bad-cfg.stderr similarity index 100% rename from src/test/ui/parser/if-attrs/bad-cfg.stderr rename to src/test/ui/if-attrs/bad-cfg.stderr diff --git a/src/test/ui/parser/if-attrs/builtin-if-attr.rs b/src/test/ui/if-attrs/builtin-if-attr.rs similarity index 100% rename from src/test/ui/parser/if-attrs/builtin-if-attr.rs rename to src/test/ui/if-attrs/builtin-if-attr.rs diff --git a/src/test/ui/parser/if-attrs/cfg-false-if-attr.rs b/src/test/ui/if-attrs/cfg-false-if-attr.rs similarity index 100% rename from src/test/ui/parser/if-attrs/cfg-false-if-attr.rs rename to src/test/ui/if-attrs/cfg-false-if-attr.rs diff --git a/src/test/ui/parser/if-attrs/else-attrs.rs b/src/test/ui/if-attrs/else-attrs.rs similarity index 100% rename from src/test/ui/parser/if-attrs/else-attrs.rs rename to src/test/ui/if-attrs/else-attrs.rs diff --git a/src/test/ui/parser/if-attrs/else-attrs.stderr b/src/test/ui/if-attrs/else-attrs.stderr similarity index 100% rename from src/test/ui/parser/if-attrs/else-attrs.stderr rename to src/test/ui/if-attrs/else-attrs.stderr diff --git a/src/test/ui/parser/if-attrs/gate-whole-expr.rs b/src/test/ui/if-attrs/gate-whole-expr.rs similarity index 100% rename from src/test/ui/parser/if-attrs/gate-whole-expr.rs rename to src/test/ui/if-attrs/gate-whole-expr.rs diff --git a/src/test/ui/parser/if-attrs/let-chains-attr.rs b/src/test/ui/if-attrs/let-chains-attr.rs similarity index 100% rename from src/test/ui/parser/if-attrs/let-chains-attr.rs rename to src/test/ui/if-attrs/let-chains-attr.rs diff --git a/src/test/ui/parser/if-attrs/let-chains-attr.stderr b/src/test/ui/if-attrs/let-chains-attr.stderr similarity index 100% rename from src/test/ui/parser/if-attrs/let-chains-attr.stderr rename to src/test/ui/if-attrs/let-chains-attr.stderr diff --git a/src/test/ui/parser/if-attrs/stmt-expr-gated.rs b/src/test/ui/if-attrs/stmt-expr-gated.rs similarity index 100% rename from src/test/ui/parser/if-attrs/stmt-expr-gated.rs rename to src/test/ui/if-attrs/stmt-expr-gated.rs diff --git a/src/test/ui/parser/if-attrs/stmt-expr-gated.stderr b/src/test/ui/if-attrs/stmt-expr-gated.stderr similarity index 100% rename from src/test/ui/parser/if-attrs/stmt-expr-gated.stderr rename to src/test/ui/if-attrs/stmt-expr-gated.stderr From 1b681d6652bacce6b741ca66725f25b9afb16bc8 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 11:01:51 -0500 Subject: [PATCH 17/31] Test that cfg-gated if-exprs are not type-checked --- src/test/ui/if-attrs/cfg-false-if-attr.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/ui/if-attrs/cfg-false-if-attr.rs b/src/test/ui/if-attrs/cfg-false-if-attr.rs index 2932ec1a23195..1f77a1bb3427d 100644 --- a/src/test/ui/if-attrs/cfg-false-if-attr.rs +++ b/src/test/ui/if-attrs/cfg-false-if-attr.rs @@ -19,6 +19,18 @@ fn if_let() { #[attr] if let Some(_) = Some(true) {} } +fn bar() { + #[cfg(FALSE)] + if true { + let x: () = true; // Should not error due to the #[cfg(FALSE)] + } + + #[cfg_attr(not(unset_attr), cfg(FALSE))] + if true { + let a: () = true; // Should not error due to the applied #[cfg(FALSE)] + } +} + macro_rules! custom_macro { ($expr:expr) => {} } From 37c2c38aeb0d50f7b956200c698bc59fce6e7181 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 11:05:31 -0500 Subject: [PATCH 18/31] Extent pretty-print test --- src/test/pretty/if-attr.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/test/pretty/if-attr.rs b/src/test/pretty/if-attr.rs index 463476737a92f..652604fc7f34b 100644 --- a/src/test/pretty/if-attr.rs +++ b/src/test/pretty/if-attr.rs @@ -24,5 +24,14 @@ fn if_let() { if let Some(_) = Some(true) { } } +#[cfg(FALSE)] +fn let_attr_if() { + let _ = #[attr] if let _ = 0 { }; + let _ = #[attr] if true { }; + + let _ = #[attr] if let _ = 0 { } else { }; + let _ = #[attr] if true { } else { }; +} + fn main() { } From 66b152cf9fd53b27027c66378a73404b92c6e35b Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 19 Feb 2020 11:36:04 -0500 Subject: [PATCH 19/31] Fix tabs --- src/test/ui/if-attrs/gate-whole-expr.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/test/ui/if-attrs/gate-whole-expr.rs b/src/test/ui/if-attrs/gate-whole-expr.rs index efce28e1d5bb2..63772d54b531d 100644 --- a/src/test/ui/if-attrs/gate-whole-expr.rs +++ b/src/test/ui/if-attrs/gate-whole-expr.rs @@ -1,15 +1,15 @@ // run-pass fn main() { - let x = 1; + let x = 1; - #[cfg(FALSE)] - if false { - x = 2; - } else if true { - x = 3; - } else { - x = 4; - } - assert_eq!(x, 1); + #[cfg(FALSE)] + if false { + x = 2; + } else if true { + x = 3; + } else { + x = 4; + } + assert_eq!(x, 1); } From e50fd5a3dc587b5b970b6b969eff7e8547dede70 Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Wed, 4 Mar 2020 16:54:16 -0500 Subject: [PATCH 20/31] Update stderr --- .../ui/parser/attr-stmt-expr-attr-bad.stderr | 94 +++++++------------ 1 file changed, 35 insertions(+), 59 deletions(-) diff --git a/src/test/ui/parser/attr-stmt-expr-attr-bad.stderr b/src/test/ui/parser/attr-stmt-expr-attr-bad.stderr index b03db85422d0c..3cc3a455c12fc 100644 --- a/src/test/ui/parser/attr-stmt-expr-attr-bad.stderr +++ b/src/test/ui/parser/attr-stmt-expr-attr-bad.stderr @@ -136,14 +136,8 @@ LL | #[cfg(FALSE)] fn e() { let _ = #[attr] &mut #![attr] 0; } | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. -error: attributes are not yet allowed on `if` expressions - --> $DIR/attr-stmt-expr-attr-bad.rs:41:32 - | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] if 0 {}; } - | ^^^^^^^ - error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:43:37 + --> $DIR/attr-stmt-expr-attr-bad.rs:41:37 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } | -- ^ --- help: try placing this code inside a block: `{ {}; }` @@ -152,7 +146,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 #[attr] {}; } | this `if` expression has a condition, but no block error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:45:38 + --> $DIR/attr-stmt-expr-attr-bad.rs:43:38 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } | ^^^^^^^^ @@ -160,13 +154,13 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {#![attr]}; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:47:40 + --> $DIR/attr-stmt-expr-attr-bad.rs:45:40 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} #[attr] else {}; } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:49:45 + --> $DIR/attr-stmt-expr-attr-bad.rs:47:45 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] {}; } | ^ --- help: try placing this code inside a block: `{ {}; }` @@ -174,21 +168,15 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] {}; } | expected `{` error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:51:46 + --> $DIR/attr-stmt-expr-attr-bad.rs:49:46 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. -error: attributes are not yet allowed on `if` expressions - --> $DIR/attr-stmt-expr-attr-bad.rs:53:45 - | -LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } - | ^^^^^^^ - error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:53:45 + --> $DIR/attr-stmt-expr-attr-bad.rs:51:45 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } | ^ -------- help: try placing this code inside a block: `{ if 0 {}; }` @@ -196,7 +184,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else #[attr] if 0 {}; } | expected `{` error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:56:50 + --> $DIR/attr-stmt-expr-attr-bad.rs:53:50 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } | -- ^ --- help: try placing this code inside a block: `{ {}; }` @@ -205,21 +193,15 @@ LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 #[attr] {}; } | this `if` expression has a condition, but no block error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:58:51 + --> $DIR/attr-stmt-expr-attr-bad.rs:55:51 | LL | #[cfg(FALSE)] fn e() { let _ = if 0 {} else if 0 {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. -error: attributes are not yet allowed on `if` expressions - --> $DIR/attr-stmt-expr-attr-bad.rs:60:32 - | -LL | #[cfg(FALSE)] fn e() { let _ = #[attr] if let _ = 0 {}; } - | ^^^^^^^ - error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:62:45 + --> $DIR/attr-stmt-expr-attr-bad.rs:57:45 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } | -- ^ --- help: try placing this code inside a block: `{ {}; }` @@ -228,7 +210,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 #[attr] {}; } | this `if` expression has a condition, but no block error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:64:46 + --> $DIR/attr-stmt-expr-attr-bad.rs:59:46 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } | ^^^^^^^^ @@ -236,13 +218,13 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {#![attr]}; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: expected one of `.`, `;`, `?`, `else`, or an operator, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:66:48 + --> $DIR/attr-stmt-expr-attr-bad.rs:61:48 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} #[attr] else {}; } | ^ expected one of `.`, `;`, `?`, `else`, or an operator error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:68:53 + --> $DIR/attr-stmt-expr-attr-bad.rs:63:53 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } | ^ --- help: try placing this code inside a block: `{ {}; }` @@ -250,21 +232,15 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] {}; } | expected `{` error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:70:54 + --> $DIR/attr-stmt-expr-attr-bad.rs:65:54 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else {#![attr]}; } | ^^^^^^^^ | = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. -error: attributes are not yet allowed on `if` expressions - --> $DIR/attr-stmt-expr-attr-bad.rs:72:53 - | -LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } - | ^^^^^^^ - error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:72:53 + --> $DIR/attr-stmt-expr-attr-bad.rs:67:53 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {}; } | ^ ---------------- help: try placing this code inside a block: `{ if let _ = 0 {}; }` @@ -272,7 +248,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else #[attr] if let _ = 0 {} | expected `{` error: expected `{`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:75:66 + --> $DIR/attr-stmt-expr-attr-bad.rs:69:66 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {}; } | -- ^ --- help: try placing this code inside a block: `{ {}; }` @@ -281,7 +257,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 #[attr] {} | this `if` expression has a condition, but no block error: an inner attribute is not permitted in this context - --> $DIR/attr-stmt-expr-attr-bad.rs:77:67 + --> $DIR/attr-stmt-expr-attr-bad.rs:71:67 | LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]}; } | ^^^^^^^^ @@ -289,7 +265,7 @@ LL | #[cfg(FALSE)] fn e() { let _ = if let _ = 0 {} else if let _ = 0 {#![attr]} = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: an inner attribute is not permitted following an outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:80:32 + --> $DIR/attr-stmt-expr-attr-bad.rs:74:32 | LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] let _ = 0; } | ------- ^^^^^^^^ not permitted following an outer attibute @@ -299,7 +275,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] let _ = 0; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: an inner attribute is not permitted following an outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:82:32 + --> $DIR/attr-stmt-expr-attr-bad.rs:76:32 | LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] 0; } | ------- ^^^^^^^^ not permitted following an outer attibute @@ -309,7 +285,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] 0; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: an inner attribute is not permitted following an outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:84:32 + --> $DIR/attr-stmt-expr-attr-bad.rs:78:32 | LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!(); } | ------- ^^^^^^^^ not permitted following an outer attibute @@ -319,7 +295,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!(); } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: an inner attribute is not permitted following an outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:86:32 + --> $DIR/attr-stmt-expr-attr-bad.rs:80:32 | LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo![]; } | ------- ^^^^^^^^ not permitted following an outer attibute @@ -329,7 +305,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo![]; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error: an inner attribute is not permitted following an outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:88:32 + --> $DIR/attr-stmt-expr-attr-bad.rs:82:32 | LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!{}; } | ------- ^^^^^^^^ not permitted following an outer attibute @@ -339,7 +315,7 @@ LL | #[cfg(FALSE)] fn s() { #[attr] #![attr] foo!{}; } = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them. error[E0586]: inclusive range with no end - --> $DIR/attr-stmt-expr-attr-bad.rs:94:35 + --> $DIR/attr-stmt-expr-attr-bad.rs:88:35 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } | ^^^ help: use `..` instead @@ -347,13 +323,13 @@ LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: expected one of `=>`, `if`, or `|`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:94:38 + --> $DIR/attr-stmt-expr-attr-bad.rs:88:38 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] 10 => () } } | ^ expected one of `=>`, `if`, or `|` error[E0586]: inclusive range with no end - --> $DIR/attr-stmt-expr-attr-bad.rs:97:35 + --> $DIR/attr-stmt-expr-attr-bad.rs:91:35 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } | ^^^ help: use `..` instead @@ -361,19 +337,19 @@ LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: expected one of `=>`, `if`, or `|`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:97:38 + --> $DIR/attr-stmt-expr-attr-bad.rs:91:38 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] -10 => () } } | ^ expected one of `=>`, `if`, or `|` error: unexpected token: `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:100:39 + --> $DIR/attr-stmt-expr-attr-bad.rs:94:39 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=-#[attr] 10 => () } } | ^ error[E0586]: inclusive range with no end - --> $DIR/attr-stmt-expr-attr-bad.rs:102:35 + --> $DIR/attr-stmt-expr-attr-bad.rs:96:35 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } | ^^^ help: use `..` instead @@ -381,47 +357,47 @@ LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: expected one of `=>`, `if`, or `|`, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:102:38 + --> $DIR/attr-stmt-expr-attr-bad.rs:96:38 | LL | #[cfg(FALSE)] fn e() { match 0 { 0..=#[attr] FOO => () } } | ^ expected one of `=>`, `if`, or `|` error: unexpected token: `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:106:34 + --> $DIR/attr-stmt-expr-attr-bad.rs:100:34 | LL | #[cfg(FALSE)] fn e() { let _ = x.#![attr]foo(); } | ^ error: expected one of `.`, `;`, `?`, or an operator, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:106:34 + --> $DIR/attr-stmt-expr-attr-bad.rs:100:34 | LL | #[cfg(FALSE)] fn e() { let _ = x.#![attr]foo(); } | ^ expected one of `.`, `;`, `?`, or an operator error: unexpected token: `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:109:34 + --> $DIR/attr-stmt-expr-attr-bad.rs:103:34 | LL | #[cfg(FALSE)] fn e() { let _ = x.#[attr]foo(); } | ^ error: expected one of `.`, `;`, `?`, or an operator, found `#` - --> $DIR/attr-stmt-expr-attr-bad.rs:109:34 + --> $DIR/attr-stmt-expr-attr-bad.rs:103:34 | LL | #[cfg(FALSE)] fn e() { let _ = x.#[attr]foo(); } | ^ expected one of `.`, `;`, `?`, or an operator error: expected statement after outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:114:37 + --> $DIR/attr-stmt-expr-attr-bad.rs:108:37 | LL | #[cfg(FALSE)] fn e() { { fn foo() { #[attr]; } } } | ^^^^^^^ error: expected statement after outer attribute - --> $DIR/attr-stmt-expr-attr-bad.rs:116:37 + --> $DIR/attr-stmt-expr-attr-bad.rs:110:37 | LL | #[cfg(FALSE)] fn e() { { fn foo() { #[attr] } } } | ^^^^^^^ -error: aborting due to 57 previous errors +error: aborting due to 53 previous errors For more information about this error, try `rustc --explain E0586`. From dbed65afaede1a819c5a7319685721339b61733b Mon Sep 17 00:00:00 2001 From: 12101111 Date: Sun, 8 Mar 2020 14:24:02 +0800 Subject: [PATCH 21/31] Simplify checking of crt_static_feature() --- src/librustc_session/session.rs | 36 +++++++++------------------------ 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/src/librustc_session/session.rs b/src/librustc_session/session.rs index 619fbdcf7f8a9..3cb8ba4af1141 100644 --- a/src/librustc_session/session.rs +++ b/src/librustc_session/session.rs @@ -556,33 +556,17 @@ impl Session { let found_negative = requested_features.clone().any(|r| r == "-crt-static"); let found_positive = requested_features.clone().any(|r| r == "+crt-static"); - if self.target.target.options.crt_static_default { - // `proc-macro` always required to be compiled to dylibs. - // We don't use a static crt unless the `+crt-static` feature was passed. - if !self.target.target.options.crt_static_allows_dylibs { - match crate_type { - Some(config::CrateType::ProcMacro) => found_positive, - Some(_) => !found_negative, - None => { - // FIXME: When crate_type is not available, - // we use compiler options to determine the crate_type. - // We can't check `#![crate_type = "proc-macro"]` here. - if self.opts.crate_types.contains(&config::CrateType::ProcMacro) { - found_positive - } else { - !found_negative - } - } - } - } else { - // If the target we're compiling for requests a static crt by default, - // then see if the `-crt-static` feature was passed to disable that. - !found_negative - } - } else { - // If the target we're compiling for don't have a static crt by default then see if the - // `+crt-static` feature was passed. + if found_positive || found_negative { found_positive + } else if crate_type == Some(config::CrateType::ProcMacro) + || self.opts.crate_types.contains(&config::CrateType::ProcMacro) + { + // FIXME: When crate_type is not available, + // we use compiler options to determine the crate_type. + // We can't check `#![crate_type = "proc-macro"]` here. + false + } else { + self.target.target.options.crt_static_default } } From 7a89bf166719d46b85c2d00686380587e46ec10d Mon Sep 17 00:00:00 2001 From: 12101111 Date: Sun, 8 Mar 2020 21:49:52 +0800 Subject: [PATCH 22/31] override flags from compiletest --- src/test/ui/proc-macro/musl-proc-macro.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/ui/proc-macro/musl-proc-macro.rs b/src/test/ui/proc-macro/musl-proc-macro.rs index 223f00eb043c5..7ea3726b751c0 100644 --- a/src/test/ui/proc-macro/musl-proc-macro.rs +++ b/src/test/ui/proc-macro/musl-proc-macro.rs @@ -1,6 +1,7 @@ // Test proc-macro crate can be built without addtional RUSTFLAGS // on musl target - +// override -Ctarget-feature=-crt-static from compiletest +// compile-flags: -Ctarget-feature= // build-pass // only-musl #![crate_type = "proc-macro"] From 0468929ce3f3e142287124a37f3318cc3b53a52b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 4 Mar 2020 08:40:13 +0100 Subject: [PATCH 23/31] move error allocation test to error.rs --- src/librustc/mir/interpret/error.rs | 18 +++++++++++- src/librustc_mir/transform/const_prop.rs | 35 ++++++------------------ 2 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 28e197b2a7fc1..2310867400cf6 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -354,7 +354,7 @@ pub enum UnsupportedOpInfo<'tcx> { Unsupported(String), /// When const-prop encounters a situation it does not support, it raises this error. - /// This must not allocate for performance reasons. + /// This must not allocate for performance reasons (hence `str`, not `String`). ConstPropUnsupported(&'tcx str), // -- Everything below is not categorized yet -- @@ -612,3 +612,19 @@ impl fmt::Debug for InterpError<'_> { } } } + +impl InterpError<'_> { + /// Some errors allocate to be created as they contain free-from strings. + /// And sometiems we want to be sure that did not happen as it is a + /// waste of resources. + pub fn allocates(&self) -> bool { + match self { + InterpError::MachineStop(_) + | InterpError::Unsupported(UnsupportedOpInfo::Unsupported(_)) + | InterpError::Unsupported(UnsupportedOpInfo::ValidationFailure(_)) + | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) + | InterpError::UndefinedBehavior(UndefinedBehaviorInfo::UbExperimental(_)) => true, + _ => false, + } + } +} diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 0560f77f5c99f..1fea9281b931b 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -404,32 +404,15 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let r = match f(self) { Ok(val) => Some(val), Err(error) => { - use rustc::mir::interpret::{ - InterpError::*, UndefinedBehaviorInfo, UnsupportedOpInfo, - }; - match error.kind { - MachineStop(_) => bug!("ConstProp does not stop"), - - // Some error shouldn't come up because creating them causes - // an allocation, which we should avoid. When that happens, - // dedicated error variants should be introduced instead. - // Only test this in debug builds though to avoid disruptions. - Unsupported(UnsupportedOpInfo::Unsupported(_)) - | Unsupported(UnsupportedOpInfo::ValidationFailure(_)) - | UndefinedBehavior(UndefinedBehaviorInfo::Ub(_)) - | UndefinedBehavior(UndefinedBehaviorInfo::UbExperimental(_)) - if cfg!(debug_assertions) => - { - bug!("const-prop encountered allocating error: {:?}", error.kind); - } - - Unsupported(_) - | UndefinedBehavior(_) - | InvalidProgram(_) - | ResourceExhaustion(_) => { - // Ignore these errors. - } - } + // Some errors shouldn't come up because creating them causes + // an allocation, which we should avoid. When that happens, + // dedicated error variants should be introduced instead. + // Only test this in debug builds though to avoid disruptions. + debug_assert!( + !error.kind.allocates(), + "const-prop encountered allocating error: {}", + error + ); None } }; From 938f8522ecf6c463bc06503251a23c3ded35ca25 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 4 Mar 2020 08:43:03 +0100 Subject: [PATCH 24/31] miri validation: debug-complain about unexpected errors --- src/librustc_mir/interpret/validity.rs | 27 ++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/librustc_mir/interpret/validity.rs b/src/librustc_mir/interpret/validity.rs index 84717cbeaa9c4..b3de44f36d2b2 100644 --- a/src/librustc_mir/interpret/validity.rs +++ b/src/librustc_mir/interpret/validity.rs @@ -46,6 +46,8 @@ macro_rules! try_validation { ($e:expr, $what:expr, $where:expr, $details:expr) => {{ match $e { Ok(x) => x, + // We re-throw the error, so we are okay with allocation: + // this can only slow down builds that fail anyway. Err(_) => throw_validation_failure!($what, $where, $details), } }}; @@ -53,6 +55,8 @@ macro_rules! try_validation { ($e:expr, $what:expr, $where:expr) => {{ match $e { Ok(x) => x, + // We re-throw the error, so we are okay with allocation: + // this can only slow down builds that fail anyway. Err(_) => throw_validation_failure!($what, $where), } }}; @@ -359,10 +363,13 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M format_args!("a dangling {} (created from integer)", kind), self.path ), - _ => throw_validation_failure!( - format_args!("a dangling {} (not entirely in bounds)", kind), - self.path - ), + err_unsup!(PointerOutOfBounds { .. }) | err_unsup!(DanglingPointerDeref) => { + throw_validation_failure!( + format_args!("a dangling {} (not entirely in bounds)", kind), + self.path + ) + } + _ => bug!("Unexpected error during ptr inbounds test: {}", err), } } }; @@ -638,6 +645,7 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> err_unsup!(ReadPointerAsBytes) => { throw_validation_failure!("a pointer", self.path, "plain (non-pointer) bytes") } + // Propagate upwards (that will also check for unexpected errors). _ => return Err(err), }, } @@ -797,7 +805,14 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Try to cast to ptr *once* instead of all the time. let op = self.force_op_ptr(op).unwrap_or(op); - // Run it - visitor.visit_value(op) + // Run it. + match visitor.visit_value(op) { + Ok(()) => Ok(()), + Err(err) if matches!(err.kind, err_unsup!(ValidationFailure { .. })) => Err(err), + Err(err) if cfg!(debug_assertions) => { + bug!("Unexpected error during validation: {}", err) + } + Err(err) => Err(err), + } } } From 4971d03ccfe9452753deb84fd958fd0b0e63f156 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 5 Mar 2020 23:31:39 +0100 Subject: [PATCH 25/31] fix some cases of unexpected exceptions leaving validation --- src/librustc/mir/interpret/error.rs | 13 ++-- src/librustc_mir/const_eval/eval_queries.rs | 7 +- src/librustc_mir/interpret/eval_context.rs | 12 +--- src/librustc_mir/interpret/place.rs | 8 +-- src/librustc_mir/interpret/validity.rs | 64 +++++++++++++++---- src/librustc_mir/transform/const_prop.rs | 5 +- src/test/ui/consts/const-eval/dangling.rs | 2 +- src/test/ui/consts/const-eval/dangling.stderr | 2 +- src/test/ui/consts/const-eval/ub-wide-ptr.rs | 6 +- .../ui/consts/const-eval/ub-wide-ptr.stderr | 58 +++++++++++------ .../ui/consts/const-points-to-static.stderr | 2 +- src/test/ui/consts/issue-63952.stderr | 2 +- .../const_refers_to_static.stderr | 4 +- 13 files changed, 122 insertions(+), 63 deletions(-) diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 2310867400cf6..731c3ee0d6a0e 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -245,7 +245,7 @@ fn print_backtrace(backtrace: &mut Backtrace) { eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace); } -impl From for InterpErrorInfo<'tcx> { +impl From for InterpErrorInfo<'_> { fn from(err: ErrorHandled) -> Self { match err { ErrorHandled::Reported => err_inval!(ReferencedConstant), @@ -291,7 +291,7 @@ pub enum InvalidProgramInfo<'tcx> { Layout(layout::LayoutError<'tcx>), } -impl fmt::Debug for InvalidProgramInfo<'tcx> { +impl fmt::Debug for InvalidProgramInfo<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use InvalidProgramInfo::*; match self { @@ -304,7 +304,7 @@ impl fmt::Debug for InvalidProgramInfo<'tcx> { } /// Error information for when the program caused Undefined Behavior. -pub enum UndefinedBehaviorInfo { +pub enum UndefinedBehaviorInfo<'tcx> { /// Free-form case. Only for errors that are never caught! Ub(String), /// Free-form case for experimental UB. Only for errors that are never caught! @@ -321,9 +321,11 @@ pub enum UndefinedBehaviorInfo { RemainderByZero, /// Overflowing inbounds pointer arithmetic. PointerArithOverflow, + /// Invalid metadata in a wide pointer (using `str` to avoid allocations). + InvalidMeta(&'tcx str), } -impl fmt::Debug for UndefinedBehaviorInfo { +impl fmt::Debug for UndefinedBehaviorInfo<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use UndefinedBehaviorInfo::*; match self { @@ -338,6 +340,7 @@ impl fmt::Debug for UndefinedBehaviorInfo { DivisionByZero => write!(f, "dividing by zero"), RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"), PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"), + InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {}", msg), } } } @@ -577,7 +580,7 @@ impl fmt::Debug for ResourceExhaustionInfo { pub enum InterpError<'tcx> { /// The program caused undefined behavior. - UndefinedBehavior(UndefinedBehaviorInfo), + UndefinedBehavior(UndefinedBehaviorInfo<'tcx>), /// The program did something the interpreter does not support (some of these *might* be UB /// but the interpreter is not sure). Unsupported(UnsupportedOpInfo<'tcx>), diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index 7a8e61db6d019..ffbff00cf3760 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -186,7 +186,12 @@ fn validate_and_turn_into_const<'tcx>( if cid.promoted.is_none() { let mut ref_tracking = RefTracking::new(mplace); while let Some((mplace, path)) = ref_tracking.todo.pop() { - ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?; + ecx.const_validate_operand( + mplace.into(), + path, + &mut ref_tracking, + /*may_ref_to_static*/ is_static, + )?; } } // Now that we validated, turn this into a proper constant. diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index e683422e611a8..9b28b7a20c044 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -457,10 +457,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Check if this brought us over the size limit. if size.bytes() >= self.tcx.data_layout().obj_size_bound() { - throw_ub_format!( - "wide pointer metadata contains invalid information: \ - total size is bigger than largest supported object" - ); + throw_ub!(InvalidMeta("total size is bigger than largest supported object")); } Ok(Some((size, align))) } @@ -476,10 +473,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Make sure the slice is not too big. let size = elem.size.checked_mul(len, &*self.tcx).ok_or_else(|| { - err_ub_format!( - "invalid slice: \ - total size is bigger than largest supported object" - ) + err_ub!(InvalidMeta("slice is bigger than largest supported object")) })?; Ok(Some((size, elem.align.abi))) } @@ -685,7 +679,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // invariant -- that is, unless a function somehow has a ptr to // its return place... but the way MIR is currently generated, the // return place is always a local and then this cannot happen. - self.validate_operand(self.place_to_op(return_place)?, vec![], None)?; + self.validate_operand(self.place_to_op(return_place)?)?; } } else { // Uh, that shouldn't happen... the function did not intend to return diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index fff9c740f7e49..a4815b9696ebb 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -689,7 +689,7 @@ where if M::enforce_validity(self) { // Data got changed, better make sure it matches the type! - self.validate_operand(self.place_to_op(dest)?, vec![], None)?; + self.validate_operand(self.place_to_op(dest)?)?; } Ok(()) @@ -706,7 +706,7 @@ where if M::enforce_validity(self) { // Data got changed, better make sure it matches the type! - self.validate_operand(dest.into(), vec![], None)?; + self.validate_operand(dest.into())?; } Ok(()) @@ -843,7 +843,7 @@ where if M::enforce_validity(self) { // Data got changed, better make sure it matches the type! - self.validate_operand(self.place_to_op(dest)?, vec![], None)?; + self.validate_operand(self.place_to_op(dest)?)?; } Ok(()) @@ -951,7 +951,7 @@ where if M::enforce_validity(self) { // Data got changed, better make sure it matches the type! - self.validate_operand(dest.into(), vec![], None)?; + self.validate_operand(dest.into())?; } Ok(()) diff --git a/src/librustc_mir/interpret/validity.rs b/src/librustc_mir/interpret/validity.rs index b3de44f36d2b2..05bb010959b32 100644 --- a/src/librustc_mir/interpret/validity.rs +++ b/src/librustc_mir/interpret/validity.rs @@ -171,6 +171,7 @@ struct ValidityVisitor<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> { path: Vec, ref_tracking_for_consts: Option<&'rt mut RefTracking, Vec>>, + may_ref_to_static: bool, ecx: &'rt InterpCx<'mir, 'tcx, M>, } @@ -324,9 +325,17 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M self.check_wide_ptr_meta(place.meta, place.layout)?; } // Make sure this is dereferenceable and all. - let (size, align) = self - .ecx - .size_and_align_of(place.meta, place.layout)? + let size_and_align = match self.ecx.size_and_align_of(place.meta, place.layout) { + Ok(res) => res, + Err(err) => match err.kind { + err_ub!(InvalidMeta(msg)) => throw_validation_failure!( + format_args!("invalid {} metadata: {}", kind, msg), + self.path + ), + _ => bug!("Unexpected error during ptr size_and_align_of: {}", err), + }, + }; + let (size, align) = size_and_align // 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). @@ -387,6 +396,12 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M if !did.is_local() || self.ecx.tcx.is_foreign_item(did) { return Ok(()); } + if !self.may_ref_to_static && self.ecx.tcx.is_static(did) { + throw_validation_failure!( + format_args!("a {} pointing to a static variable", kind), + self.path + ); + } } } // Proceed recursively even for ZST, no reason to skip them! @@ -781,26 +796,20 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { - /// This function checks the data at `op`. `op` is assumed to cover valid memory if it - /// is an indirect operand. - /// It will error if the bits at the destination do not match the ones described by the layout. - /// - /// `ref_tracking_for_consts` can be `None` to avoid recursive checking below references. - /// This also toggles between "run-time" (no recursion) and "compile-time" (with recursion) - /// validation (e.g., pointer values are fine in integers at runtime) and various other const - /// specific validation checks. - pub fn validate_operand( + fn validate_operand_internal( &self, op: OpTy<'tcx, M::PointerTag>, path: Vec, ref_tracking_for_consts: Option< &mut RefTracking, Vec>, >, + may_ref_to_static: bool, ) -> InterpResult<'tcx> { - trace!("validate_operand: {:?}, {:?}", *op, op.layout.ty); + trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty); // Construct a visitor - let mut visitor = ValidityVisitor { path, ref_tracking_for_consts, ecx: self }; + let mut visitor = + ValidityVisitor { path, ref_tracking_for_consts, may_ref_to_static, ecx: self }; // Try to cast to ptr *once* instead of all the time. let op = self.force_op_ptr(op).unwrap_or(op); @@ -815,4 +824,31 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Err(err) => Err(err), } } + + /// This function checks the data at `op` to be const-valid. + /// `op` is assumed to cover valid memory if it is an indirect operand. + /// It will error if the bits at the destination do not match the ones described by the layout. + /// + /// `ref_tracking` is used to record references that we encounter so that they + /// can be checked recursively by an outside driving loop. + /// + /// `may_ref_to_static` controls whether references are allowed to point to statics. + #[inline(always)] + pub fn const_validate_operand( + &self, + op: OpTy<'tcx, M::PointerTag>, + path: Vec, + ref_tracking: &mut RefTracking, Vec>, + may_ref_to_static: bool, + ) -> InterpResult<'tcx> { + self.validate_operand_internal(op, path, Some(ref_tracking), may_ref_to_static) + } + + /// This function checks the data at `op` to be runtime-valid. + /// `op` is assumed to cover valid memory if it is an indirect operand. + /// It will error if the bits at the destination do not match the ones described by the layout. + #[inline(always)] + pub fn validate_operand(&self, op: OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { + self.validate_operand_internal(op, vec![], None, false) + } } diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 1fea9281b931b..a07c8575b300c 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -637,11 +637,12 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { source_info: SourceInfo, ) { trace!("attepting to replace {:?} with {:?}", rval, value); - if let Err(e) = self.ecx.validate_operand( + if let Err(e) = self.ecx.const_validate_operand( value, vec![], // FIXME: is ref tracking too expensive? - Some(&mut interpret::RefTracking::empty()), + &mut interpret::RefTracking::empty(), + /*may_ref_to_static*/ true, ) { trace!("validation error, attempt failed: {:?}", e); return; diff --git a/src/test/ui/consts/const-eval/dangling.rs b/src/test/ui/consts/const-eval/dangling.rs index b5d72d46f2861..c6b8e8eb61181 100644 --- a/src/test/ui/consts/const-eval/dangling.rs +++ b/src/test/ui/consts/const-eval/dangling.rs @@ -6,7 +6,7 @@ use std::{mem, usize}; const TEST: () = { unsafe { //~ NOTE let slice: *const [u8] = mem::transmute((1usize, usize::MAX)); let _val = &*slice; //~ ERROR: any use of this value will cause an error - //~^ NOTE: total size is bigger than largest supported object + //~^ NOTE: slice is bigger than largest supported object //~^^ on by default } }; diff --git a/src/test/ui/consts/const-eval/dangling.stderr b/src/test/ui/consts/const-eval/dangling.stderr index 286de08009754..b9ddc93b03b84 100644 --- a/src/test/ui/consts/const-eval/dangling.stderr +++ b/src/test/ui/consts/const-eval/dangling.stderr @@ -4,7 +4,7 @@ error: any use of this value will cause an error LL | / const TEST: () = { unsafe { LL | | let slice: *const [u8] = mem::transmute((1usize, usize::MAX)); LL | | let _val = &*slice; - | | ^^^^^^^ invalid slice: total size is bigger than largest supported object + | | ^^^^^^^ invalid metadata in wide pointer: slice is bigger than largest supported object LL | | LL | | LL | | } }; diff --git a/src/test/ui/consts/const-eval/ub-wide-ptr.rs b/src/test/ui/consts/const-eval/ub-wide-ptr.rs index 26d378847462d..2d48309b72722 100644 --- a/src/test/ui/consts/const-eval/ub-wide-ptr.rs +++ b/src/test/ui/consts/const-eval/ub-wide-ptr.rs @@ -31,12 +31,16 @@ const STR_VALID: &str = unsafe { mem::transmute((&42u8, 1usize)) }; // bad str const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; //~^ ERROR it is undefined behavior to use this value +const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, usize::MAX)) },); +//~^ ERROR it is undefined behavior to use this value // bad str const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; //~^ ERROR it is undefined behavior to use this value // bad str in user-defined unsized type const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; //~^ ERROR it is undefined behavior to use this value +const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize::MAX)) }; +//~^ ERROR it is undefined behavior to use this value // invalid UTF-8 const STR_NO_UTF8: &str = unsafe { mem::transmute::<&[u8], _>(&[0xFF]) }; @@ -83,7 +87,7 @@ const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::transmute // # raw slice const RAW_SLICE_VALID: *const [u8] = unsafe { mem::transmute((&42u8, 1usize)) }; // ok const RAW_SLICE_TOO_LONG: *const [u8] = unsafe { mem::transmute((&42u8, 999usize)) }; // ok because raw -const RAW_SLICE_MUCH_TOO_LONG: *const [u8] = unsafe { mem::transmute((&42u8, usize::max_value())) }; // ok because raw +const RAW_SLICE_MUCH_TOO_LONG: *const [u8] = unsafe { mem::transmute((&42u8, usize::MAX)) }; // ok because raw const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { //~^ ERROR it is undefined behavior to use this value let uninit_len = MaybeUninit:: { uninit: () }; diff --git a/src/test/ui/consts/const-eval/ub-wide-ptr.stderr b/src/test/ui/consts/const-eval/ub-wide-ptr.stderr index 22adf0e55ee8c..a562c64b124f9 100644 --- a/src/test/ui/consts/const-eval/ub-wide-ptr.stderr +++ b/src/test/ui/consts/const-eval/ub-wide-ptr.stderr @@ -7,7 +7,15 @@ LL | const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:35:1 + --> $DIR/ub-wide-ptr.rs:34:1 + | +LL | const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, usize::MAX)) },); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid reference metadata: slice is bigger than largest supported object at .0 + | + = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. + +error[E0080]: it is undefined behavior to use this value + --> $DIR/ub-wide-ptr.rs:37:1 | LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -15,7 +23,7 @@ LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:38:1 + --> $DIR/ub-wide-ptr.rs:40:1 | LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -25,13 +33,21 @@ LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; error[E0080]: it is undefined behavior to use this value --> $DIR/ub-wide-ptr.rs:42:1 | +LL | const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize::MAX)) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered invalid reference metadata: slice is bigger than largest supported object + | + = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. + +error[E0080]: it is undefined behavior to use this value + --> $DIR/ub-wide-ptr.rs:46:1 + | LL | const STR_NO_UTF8: &str = unsafe { mem::transmute::<&[u8], _>(&[0xFF]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered uninitialized or non-UTF-8 data in str at . | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:45:1 + --> $DIR/ub-wide-ptr.rs:49:1 | LL | const MYSTR_NO_UTF8: &MyStr = unsafe { mem::transmute::<&[u8], _>(&[0xFF]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered uninitialized or non-UTF-8 data in str at ..0 @@ -39,7 +55,7 @@ LL | const MYSTR_NO_UTF8: &MyStr = unsafe { mem::transmute::<&[u8], _>(&[0xFF]) = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:52:1 + --> $DIR/ub-wide-ptr.rs:56:1 | LL | / const SLICE_LENGTH_UNINIT: &[u8] = unsafe { LL | | @@ -51,7 +67,7 @@ LL | | }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:58:1 + --> $DIR/ub-wide-ptr.rs:62:1 | LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a dangling reference (not entirely in bounds) @@ -59,7 +75,7 @@ LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:61:1 + --> $DIR/ub-wide-ptr.rs:65:1 | LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -67,7 +83,7 @@ LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:64:1 + --> $DIR/ub-wide-ptr.rs:68:1 | LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a dangling box (not entirely in bounds) @@ -75,7 +91,7 @@ LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999us = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:67:1 + --> $DIR/ub-wide-ptr.rs:71:1 | LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered non-integer slice length in wide pointer @@ -83,7 +99,7 @@ LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3) = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:71:1 + --> $DIR/ub-wide-ptr.rs:75:1 | LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .[0], but expected a boolean @@ -91,7 +107,7 @@ LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:77:1 + --> $DIR/ub-wide-ptr.rs:81:1 | LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3u8) }, [false]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at ..0, but expected a boolean @@ -99,7 +115,7 @@ LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:80:1 + --> $DIR/ub-wide-ptr.rs:84:1 | LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::transmute(3u8) }]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at ..1[0], but expected a boolean @@ -107,7 +123,7 @@ LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::tran = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:87:1 + --> $DIR/ub-wide-ptr.rs:91:1 | LL | / const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { LL | | @@ -119,7 +135,7 @@ LL | | }; = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:95:1 + --> $DIR/ub-wide-ptr.rs:99:1 | LL | const TRAIT_OBJ_SHORT_VTABLE_1: &dyn Trait = unsafe { mem::transmute((&92u8, &3u8)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling or unaligned vtable pointer in wide pointer or too small vtable @@ -127,7 +143,7 @@ LL | const TRAIT_OBJ_SHORT_VTABLE_1: &dyn Trait = unsafe { mem::transmute((&92u8 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:98:1 + --> $DIR/ub-wide-ptr.rs:102:1 | LL | const TRAIT_OBJ_SHORT_VTABLE_2: &dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling or unaligned vtable pointer in wide pointer or too small vtable @@ -135,7 +151,7 @@ LL | const TRAIT_OBJ_SHORT_VTABLE_2: &dyn Trait = unsafe { mem::transmute((&92u8 = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:101:1 + --> $DIR/ub-wide-ptr.rs:105:1 | LL | const TRAIT_OBJ_INT_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, 4usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling or unaligned vtable pointer in wide pointer or too small vtable @@ -143,7 +159,7 @@ LL | const TRAIT_OBJ_INT_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, 4u = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:105:1 + --> $DIR/ub-wide-ptr.rs:109:1 | LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, &bool>(&3u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered 3 at .., but expected a boolean @@ -151,7 +167,7 @@ LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:109:1 + --> $DIR/ub-wide-ptr.rs:113:1 | LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute((&92u8, 0usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling or unaligned vtable pointer in wide pointer or too small vtable @@ -159,7 +175,7 @@ LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: it is undefined behavior to use this value - --> $DIR/ub-wide-ptr.rs:111:1 + --> $DIR/ub-wide-ptr.rs:115:1 | LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered dangling or unaligned vtable pointer in wide pointer or too small vtable @@ -167,17 +183,17 @@ LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transm = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. error[E0080]: could not evaluate static initializer - --> $DIR/ub-wide-ptr.rs:117:5 + --> $DIR/ub-wide-ptr.rs:121:5 | LL | mem::transmute::<_, &dyn Trait>((&92u8, 0usize)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid use of NULL pointer error[E0080]: could not evaluate static initializer - --> $DIR/ub-wide-ptr.rs:121:5 + --> $DIR/ub-wide-ptr.rs:125:5 | LL | mem::transmute::<_, &dyn Trait>((&92u8, &3u64)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Memory access failed: pointer must be in-bounds at offset N, but is outside bounds of allocation N which has size N -error: aborting due to 22 previous errors +error: aborting due to 24 previous errors For more information about this error, try `rustc --explain E0080`. diff --git a/src/test/ui/consts/const-points-to-static.stderr b/src/test/ui/consts/const-points-to-static.stderr index 8949358e29333..f2ca7ff782591 100644 --- a/src/test/ui/consts/const-points-to-static.stderr +++ b/src/test/ui/consts/const-points-to-static.stderr @@ -8,7 +8,7 @@ error[E0080]: it is undefined behavior to use this value --> $DIR/const-points-to-static.rs:5:1 | LL | const TEST: &u8 = &MY_STATIC; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constant accesses static + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a reference pointing to a static variable | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. diff --git a/src/test/ui/consts/issue-63952.stderr b/src/test/ui/consts/issue-63952.stderr index d5ed970fc3533..5e85be45b1647 100644 --- a/src/test/ui/consts/issue-63952.stderr +++ b/src/test/ui/consts/issue-63952.stderr @@ -8,7 +8,7 @@ LL | | ptr: &42, ... | LL | | .slice LL | | }; - | |__^ invalid slice: total size is bigger than largest supported object + | |__^ type validation failed: encountered invalid reference metadata: slice is bigger than largest supported object | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. diff --git a/src/test/ui/consts/miri_unleashed/const_refers_to_static.stderr b/src/test/ui/consts/miri_unleashed/const_refers_to_static.stderr index 15e13942481c9..ad777cfe8ea4b 100644 --- a/src/test/ui/consts/miri_unleashed/const_refers_to_static.stderr +++ b/src/test/ui/consts/miri_unleashed/const_refers_to_static.stderr @@ -48,7 +48,7 @@ LL | | static FOO: AtomicUsize = AtomicUsize::new(0); LL | | unsafe { &*(&FOO as *const _ as *const usize) } LL | | LL | | }; - | |__^ constant accesses static + | |__^ type validation failed: encountered a reference pointing to a static variable | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. @@ -97,7 +97,7 @@ LL | | static FOO: usize = 0; LL | | &FOO LL | | LL | | }; - | |__^ constant accesses static + | |__^ type validation failed: encountered a reference pointing to a static variable | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. From 85e1466232eadd2ec6b9c2ae0aa4030a39fde04f Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 6 Mar 2020 11:30:57 +0100 Subject: [PATCH 26/31] Fix typo Co-Authored-By: bjorn3 --- src/librustc/mir/interpret/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 731c3ee0d6a0e..5869c76345a19 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -617,8 +617,8 @@ impl fmt::Debug for InterpError<'_> { } impl InterpError<'_> { - /// Some errors allocate to be created as they contain free-from strings. - /// And sometiems we want to be sure that did not happen as it is a + /// Some errors allocate to be created as they contain free-form strings. + /// And sometimes we want to be sure that did not happen as it is a /// waste of resources. pub fn allocates(&self) -> bool { match self { From ed3014a2b9470a89165f2762ba746ee7736d5590 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 6 Mar 2020 18:14:41 +0100 Subject: [PATCH 27/31] use static strings instead of tcx --- src/librustc/mir/interpret/error.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 5869c76345a19..b46095927b709 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -304,7 +304,7 @@ impl fmt::Debug for InvalidProgramInfo<'_> { } /// Error information for when the program caused Undefined Behavior. -pub enum UndefinedBehaviorInfo<'tcx> { +pub enum UndefinedBehaviorInfo { /// Free-form case. Only for errors that are never caught! Ub(String), /// Free-form case for experimental UB. Only for errors that are never caught! @@ -322,10 +322,10 @@ pub enum UndefinedBehaviorInfo<'tcx> { /// Overflowing inbounds pointer arithmetic. PointerArithOverflow, /// Invalid metadata in a wide pointer (using `str` to avoid allocations). - InvalidMeta(&'tcx str), + InvalidMeta(&'static str), } -impl fmt::Debug for UndefinedBehaviorInfo<'_> { +impl fmt::Debug for UndefinedBehaviorInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use UndefinedBehaviorInfo::*; match self { @@ -358,7 +358,7 @@ pub enum UnsupportedOpInfo<'tcx> { /// When const-prop encounters a situation it does not support, it raises this error. /// This must not allocate for performance reasons (hence `str`, not `String`). - ConstPropUnsupported(&'tcx str), + ConstPropUnsupported(&'static str), // -- Everything below is not categorized yet -- FunctionAbiMismatch(Abi, Abi), @@ -580,7 +580,7 @@ impl fmt::Debug for ResourceExhaustionInfo { pub enum InterpError<'tcx> { /// The program caused undefined behavior. - UndefinedBehavior(UndefinedBehaviorInfo<'tcx>), + UndefinedBehavior(UndefinedBehaviorInfo), /// The program did something the interpreter does not support (some of these *might* be UB /// but the interpreter is not sure). Unsupported(UnsupportedOpInfo<'tcx>), From 75e6cfc79b39253ee0e4fafc7805c7b0a1f24ef2 Mon Sep 17 00:00:00 2001 From: 12101111 Date: Mon, 9 Mar 2020 08:39:34 +0800 Subject: [PATCH 28/31] run crt-static test on all target --- src/test/ui/proc-macro/{musl-proc-macro.rs => crt-static.rs} | 1 - 1 file changed, 1 deletion(-) rename src/test/ui/proc-macro/{musl-proc-macro.rs => crt-static.rs} (96%) diff --git a/src/test/ui/proc-macro/musl-proc-macro.rs b/src/test/ui/proc-macro/crt-static.rs similarity index 96% rename from src/test/ui/proc-macro/musl-proc-macro.rs rename to src/test/ui/proc-macro/crt-static.rs index 7ea3726b751c0..bed45c6a5b80b 100644 --- a/src/test/ui/proc-macro/musl-proc-macro.rs +++ b/src/test/ui/proc-macro/crt-static.rs @@ -3,7 +3,6 @@ // override -Ctarget-feature=-crt-static from compiletest // compile-flags: -Ctarget-feature= // build-pass -// only-musl #![crate_type = "proc-macro"] extern crate proc_macro; From 58303b77e0f7b35edd6791b6000cfbaef9cc1cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Fri, 6 Mar 2020 00:00:00 +0000 Subject: [PATCH 29/31] Use slices in preference to 0-terminated strings Additionally whenever possible match C API provided by the LLVM. --- .../debuginfo/metadata.rs | 247 ++++++++++-------- src/librustc_codegen_llvm/debuginfo/mod.rs | 22 +- .../debuginfo/namespace.rs | 12 +- src/librustc_codegen_llvm/llvm/ffi.rs | 26 +- src/rustllvm/RustWrapper.cpp | 146 ++++++----- 5 files changed, 266 insertions(+), 187 deletions(-) diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 19bd0b6f7e674..5cf3d74f243cd 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -37,7 +37,6 @@ use rustc_codegen_ssa::traits::*; use rustc_data_structures::const_cstr; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::small_c_str::SmallCStr; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_fs_util::path_to_c_string; use rustc_hir::def::CtorKind; @@ -49,7 +48,6 @@ use rustc_target::abi::HasDataLayout; use libc::{c_longlong, c_uint}; use std::collections::hash_map::Entry; -use std::ffi::CString; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter; @@ -227,11 +225,14 @@ impl TypeMap<'ll, 'tcx> { /// Gets the unique type ID string for an enum variant part. /// Variant parts are not types and shouldn't really have their own ID, /// but it makes `set_members_of_composite_type()` simpler. - fn get_unique_type_id_str_of_enum_variant_part(&mut self, enum_type_id: UniqueTypeId) -> &str { + fn get_unique_type_id_str_of_enum_variant_part( + &mut self, + enum_type_id: UniqueTypeId, + ) -> String { let variant_part_type_id = format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id)); - let interner_key = self.unique_id_interner.intern(&variant_part_type_id); - self.unique_id_interner.get(interner_key) + self.unique_id_interner.intern(&variant_part_type_id); + variant_part_type_id } } @@ -640,9 +641,11 @@ pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Sp // type is going to see *something* weird - the only // question is what exactly it will see. let (size, align) = cx.size_and_align_of(t); + let name = ""; llvm::LLVMRustDIBuilderCreateBasicType( DIB(cx), - SmallCStr::new("").as_ptr(), + name.as_ptr().cast(), + name.len(), size.bits(), align.bits() as u32, DW_ATE_unsigned, @@ -786,16 +789,17 @@ fn file_metadata_raw( let (file_name, directory) = v.key(); debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory); - let file_name = SmallCStr::new(if let Some(file_name) = file_name { - &file_name - } else { - "" - }); - let directory = - SmallCStr::new(if let Some(directory) = directory { &directory } else { "" }); + let file_name = file_name.as_deref().unwrap_or(""); + let directory = directory.as_deref().unwrap_or(""); let file_metadata = unsafe { - llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(), directory.as_ptr()) + llvm::LLVMRustDIBuilderCreateFile( + DIB(cx), + file_name.as_ptr().cast(), + file_name.len(), + directory.as_ptr().cast(), + directory.len(), + ) }; v.insert(file_metadata); @@ -819,11 +823,11 @@ fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType { }; let (size, align) = cx.size_and_align_of(t); - let name = SmallCStr::new(name); let ty_metadata = unsafe { llvm::LLVMRustDIBuilderCreateBasicType( DIB(cx), - name.as_ptr(), + name.as_ptr().cast(), + name.len(), size.bits(), align.bits() as u32, encoding, @@ -851,14 +855,15 @@ fn pointer_type_metadata( ) -> &'ll DIType { let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type); let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false); - let name = SmallCStr::new(&name); unsafe { llvm::LLVMRustDIBuilderCreatePointerType( DIB(cx), pointee_type_metadata, pointer_size.bits(), pointer_align.bits() as u32, - name.as_ptr(), + 0, // Ignore DWARF address space. + name.as_ptr().cast(), + name.len(), ) } } @@ -889,11 +894,9 @@ pub fn compile_unit_metadata( let producer = format!("clang LLVM ({})", rustc_producer); let name_in_debuginfo = name_in_debuginfo.to_string_lossy(); - let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo); - let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy()); - let producer = CString::new(producer).unwrap(); + let work_dir = tcx.sess.working_dir.0.to_string_lossy(); let flags = "\0"; - let split_name = "\0"; + let split_name = ""; // FIXME(#60020): // @@ -916,19 +919,23 @@ pub fn compile_unit_metadata( unsafe { let file_metadata = llvm::LLVMRustDIBuilderCreateFile( debug_context.builder, - name_in_debuginfo.as_ptr(), - work_dir.as_ptr(), + name_in_debuginfo.as_ptr().cast(), + name_in_debuginfo.len(), + work_dir.as_ptr().cast(), + work_dir.len(), ); let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit( debug_context.builder, DW_LANG_RUST, file_metadata, - producer.as_ptr(), + producer.as_ptr().cast(), + producer.len(), tcx.sess.opts.optimize != config::OptLevel::No, flags.as_ptr().cast(), 0, split_name.as_ptr().cast(), + split_name.len(), kind, ); @@ -1021,12 +1028,12 @@ impl<'ll> MemberDescription<'ll> { cx: &CodegenCx<'ll, '_>, composite_type_metadata: &'ll DIScope, ) -> &'ll DIType { - let member_name = CString::new(self.name).unwrap(); unsafe { llvm::LLVMRustDIBuilderCreateVariantMemberType( DIB(cx), composite_type_metadata, - member_name.as_ptr(), + self.name.as_ptr().cast(), + self.name.len(), unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER, self.size.bits(), @@ -1827,9 +1834,13 @@ fn prepare_enum_metadata( let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(cx.tcx), rustc_span::DUMMY_SP); + let item_name; let discriminant_name = match enum_type.kind { - ty::Adt(..) => SmallCStr::new(&cx.tcx.item_name(enum_def_id).as_str()), - ty::Generator(..) => SmallCStr::new(&enum_name), + ty::Adt(..) => { + item_name = cx.tcx.item_name(enum_def_id).as_str(); + &*item_name + } + ty::Generator(..) => enum_name.as_str(), _ => bug!(), }; @@ -1837,7 +1848,8 @@ fn prepare_enum_metadata( llvm::LLVMRustDIBuilderCreateEnumerationType( DIB(cx), containing_scope, - discriminant_name.as_ptr(), + discriminant_name.as_ptr().cast(), + discriminant_name.len(), file_metadata, UNKNOWN_LINE_NUMBER, discriminant_size.bits(), @@ -1872,11 +1884,6 @@ fn prepare_enum_metadata( _ => {} } - let enum_name = SmallCStr::new(&enum_name); - let unique_type_id_str = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), - ); - if use_enum_fallback(cx) { let discriminant_type_metadata = match layout.variants { layout::Variants::Single { .. } @@ -1891,20 +1898,27 @@ fn prepare_enum_metadata( } => Some(discriminant_type_metadata(discr.value)), }; - let enum_metadata = unsafe { - llvm::LLVMRustDIBuilderCreateUnionType( - DIB(cx), - containing_scope, - enum_name.as_ptr(), - file_metadata, - UNKNOWN_LINE_NUMBER, - layout.size.bits(), - layout.align.abi.bits() as u32, - DIFlags::FlagZero, - None, - 0, // RuntimeLang - unique_type_id_str.as_ptr(), - ) + let enum_metadata = { + let type_map = debug_context(cx).type_map.borrow(); + let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id); + + unsafe { + llvm::LLVMRustDIBuilderCreateUnionType( + DIB(cx), + containing_scope, + enum_name.as_ptr().cast(), + enum_name.len(), + file_metadata, + UNKNOWN_LINE_NUMBER, + layout.size.bits(), + layout.align.abi.bits() as u32, + DIFlags::FlagZero, + None, + 0, // RuntimeLang + unique_type_id_str.as_ptr().cast(), + unique_type_id_str.len(), + ) + } }; return create_and_register_recursive_type_forward_declaration( @@ -1924,10 +1938,9 @@ fn prepare_enum_metadata( } let discriminator_name = match &enum_type.kind { - ty::Generator(..) => Some(SmallCStr::new(&"__state")), - _ => None, + ty::Generator(..) => "__state", + _ => "", }; - let discriminator_name = discriminator_name.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()); let discriminator_metadata = match layout.variants { // A single-variant enum has no discriminant. layout::Variants::Single { .. } => None, @@ -1955,7 +1968,8 @@ fn prepare_enum_metadata( Some(llvm::LLVMRustDIBuilderCreateMemberType( DIB(cx), containing_scope, - discriminator_name, + discriminator_name.as_ptr().cast(), + discriminator_name.len(), file_metadata, UNKNOWN_LINE_NUMBER, size.bits(), @@ -1981,7 +1995,8 @@ fn prepare_enum_metadata( Some(llvm::LLVMRustDIBuilderCreateMemberType( DIB(cx), containing_scope, - discriminator_name, + discriminator_name.as_ptr().cast(), + discriminator_name.len(), file_metadata, UNKNOWN_LINE_NUMBER, size.bits(), @@ -2010,18 +2025,18 @@ fn prepare_enum_metadata( } }; - let variant_part_unique_type_id_str = SmallCStr::new( - debug_context(cx) - .type_map - .borrow_mut() - .get_unique_type_id_str_of_enum_variant_part(unique_type_id), - ); + let variant_part_unique_type_id_str = debug_context(cx) + .type_map + .borrow_mut() + .get_unique_type_id_str_of_enum_variant_part(unique_type_id); let empty_array = create_DIArray(DIB(cx), &[]); + let name = ""; let variant_part = unsafe { llvm::LLVMRustDIBuilderCreateVariantPart( DIB(cx), containing_scope, - ptr::null_mut(), + name.as_ptr().cast(), + name.len(), file_metadata, UNKNOWN_LINE_NUMBER, layout.size.bits(), @@ -2029,29 +2044,38 @@ fn prepare_enum_metadata( DIFlags::FlagZero, discriminator_metadata, empty_array, - variant_part_unique_type_id_str.as_ptr(), + variant_part_unique_type_id_str.as_ptr().cast(), + variant_part_unique_type_id_str.len(), ) }; outer_fields.push(Some(variant_part)); - // The variant part must be wrapped in a struct according to DWARF. - let type_array = create_DIArray(DIB(cx), &outer_fields); - let struct_wrapper = unsafe { - llvm::LLVMRustDIBuilderCreateStructType( - DIB(cx), - Some(containing_scope), - enum_name.as_ptr(), - file_metadata, - UNKNOWN_LINE_NUMBER, - layout.size.bits(), - layout.align.abi.bits() as u32, - DIFlags::FlagZero, - None, - type_array, - 0, - None, - unique_type_id_str.as_ptr(), - ) + let struct_wrapper = { + // The variant part must be wrapped in a struct according to DWARF. + let type_array = create_DIArray(DIB(cx), &outer_fields); + + let type_map = debug_context(cx).type_map.borrow(); + let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id); + + unsafe { + llvm::LLVMRustDIBuilderCreateStructType( + DIB(cx), + Some(containing_scope), + enum_name.as_ptr().cast(), + enum_name.len(), + file_metadata, + UNKNOWN_LINE_NUMBER, + layout.size.bits(), + layout.align.abi.bits() as u32, + DIFlags::FlagZero, + None, + type_array, + 0, + None, + unique_type_id_str.as_ptr().cast(), + unique_type_id_str.len(), + ) + } }; return create_and_register_recursive_type_forward_declaration( @@ -2156,12 +2180,13 @@ fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&' cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty); let actual_type_metadata = type_metadata(cx, actual_type, rustc_span::DUMMY_SP); - let name = SmallCStr::new(&name.as_str()); + let name = &name.as_str(); Some(unsafe { Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( DIB(cx), None, - name.as_ptr(), + name.as_ptr().cast(), + name.len(), actual_type_metadata, unknown_file_metadata(cx), 0, @@ -2200,10 +2225,9 @@ fn create_struct_stub( ) -> &'ll DICompositeType { let (struct_size, struct_align) = cx.size_and_align_of(struct_type); - let name = SmallCStr::new(struct_type_name); - let unique_type_id = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), - ); + let type_map = debug_context(cx).type_map.borrow(); + let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id); + let metadata_stub = unsafe { // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null // pointer will lead to hard to trace and debug LLVM assertions @@ -2213,7 +2237,8 @@ fn create_struct_stub( llvm::LLVMRustDIBuilderCreateStructType( DIB(cx), containing_scope, - name.as_ptr(), + struct_type_name.as_ptr().cast(), + struct_type_name.len(), unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER, struct_size.bits(), @@ -2223,7 +2248,8 @@ fn create_struct_stub( empty_array, 0, None, - unique_type_id.as_ptr(), + unique_type_id.as_ptr().cast(), + unique_type_id.len(), ) }; @@ -2239,10 +2265,9 @@ fn create_union_stub( ) -> &'ll DICompositeType { let (union_size, union_align) = cx.size_and_align_of(union_type); - let name = SmallCStr::new(union_type_name); - let unique_type_id = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), - ); + let type_map = debug_context(cx).type_map.borrow(); + let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id); + let metadata_stub = unsafe { // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null // pointer will lead to hard to trace and debug LLVM assertions @@ -2252,7 +2277,8 @@ fn create_union_stub( llvm::LLVMRustDIBuilderCreateUnionType( DIB(cx), containing_scope, - name.as_ptr(), + union_type_name.as_ptr().cast(), + union_type_name.len(), unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER, union_size.bits(), @@ -2260,7 +2286,8 @@ fn create_union_stub( DIFlags::FlagZero, Some(empty_array), 0, // RuntimeLang - unique_type_id.as_ptr(), + unique_type_id.as_ptr().cast(), + unique_type_id.len(), ) }; @@ -2294,13 +2321,15 @@ pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global let is_local_to_unit = is_node_local_to_unit(cx, def_id); let variable_type = Instance::mono(cx.tcx, def_id).monomorphic_ty(cx.tcx); let type_metadata = type_metadata(cx, variable_type, span); - let var_name = SmallCStr::new(&tcx.item_name(def_id).as_str()); + let var_name = tcx.item_name(def_id).as_str(); let linkage_name = if no_mangle { None } else { - let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)); - Some(SmallCStr::new(&linkage_name.name.as_str())) + Some(mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name.as_str()) }; + // When empty, linkage_name field is omitted, + // which is what we want for no_mangle statics + let linkage_name = linkage_name.as_deref().unwrap_or(""); let global_align = cx.align_of(variable_type); @@ -2308,10 +2337,10 @@ pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global llvm::LLVMRustDIBuilderCreateStaticVariable( DIB(cx), Some(var_scope), - var_name.as_ptr(), - // If null, linkage_name field is omitted, - // which is what we want for no_mangle statics - linkage_name.as_ref().map_or(ptr::null(), |name| name.as_ptr()), + var_name.as_ptr().cast(), + var_name.len(), + linkage_name.as_ptr().cast(), + linkage_name.len(), file_metadata, line_number, type_metadata, @@ -2339,8 +2368,7 @@ pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: & // pointer will lead to hard to trace and debug LLVM assertions // later on in `llvm/lib/IR/Value.cpp`. let empty_array = create_DIArray(DIB(cx), &[]); - - let name = const_cstr!("vtable"); + let name = "vtable"; // Create a new one each time. We don't want metadata caching // here, because each vtable will refer to a unique containing @@ -2348,7 +2376,8 @@ pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: & let vtable_type = llvm::LLVMRustDIBuilderCreateStructType( DIB(cx), NO_SCOPE_METADATA, - name.as_ptr(), + name.as_ptr().cast(), + name.len(), unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER, Size::ZERO.bits(), @@ -2358,14 +2387,18 @@ pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: & empty_array, 0, Some(type_metadata), - name.as_ptr(), + name.as_ptr().cast(), + name.len(), ); + let linkage_name = ""; llvm::LLVMRustDIBuilderCreateStaticVariable( DIB(cx), NO_SCOPE_METADATA, - name.as_ptr(), - ptr::null(), + name.as_ptr().cast(), + name.len(), + linkage_name.as_ptr().cast(), + linkage_name.len(), unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER, vtable_type, diff --git a/src/librustc_codegen_llvm/debuginfo/mod.rs b/src/librustc_codegen_llvm/debuginfo/mod.rs index a68441f14cb9d..8deab1be3d3a9 100644 --- a/src/librustc_codegen_llvm/debuginfo/mod.rs +++ b/src/librustc_codegen_llvm/debuginfo/mod.rs @@ -25,13 +25,11 @@ use rustc::ty::{self, Instance, ParamEnv, Ty}; use rustc_codegen_ssa::debuginfo::type_names; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::small_c_str::SmallCStr; use rustc_index::vec::IndexVec; use libc::c_uint; use log::debug; use std::cell::RefCell; -use std::ffi::CString; use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, Size}; use rustc_ast::ast; @@ -273,13 +271,11 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { // Get the linkage_name, which is just the symbol name let linkage_name = mangled_name_of_instance(self, instance); + let linkage_name = linkage_name.name.as_str(); // FIXME(eddyb) does this need to be separate from `loc.line` for some reason? let scope_line = loc.line; - let function_name = CString::new(name).unwrap(); - let linkage_name = SmallCStr::new(&linkage_name.name.as_str()); - let mut flags = DIFlags::FlagPrototyped; if fn_abi.ret.layout.abi.is_uninhabited() { @@ -303,8 +299,10 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { llvm::LLVMRustDIBuilderCreateFunction( DIB(self), containing_scope, - function_name.as_ptr(), - linkage_name.as_ptr(), + name.as_ptr().cast(), + name.len(), + linkage_name.as_ptr().cast(), + linkage_name.len(), file_metadata, loc.line as c_uint, function_type_metadata, @@ -424,12 +422,13 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty); let actual_type_metadata = type_metadata(cx, actual_type, rustc_span::DUMMY_SP); - let name = SmallCStr::new(&name.as_str()); + let name = name.as_str(); Some(unsafe { Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( DIB(cx), None, - name.as_ptr(), + name.as_ptr().cast(), + name.len(), actual_type_metadata, file_metadata, 0, @@ -542,13 +541,14 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { }; let align = self.align_of(variable_type); - let name = SmallCStr::new(&variable_name.as_str()); + let name = variable_name.as_str(); unsafe { llvm::LLVMRustDIBuilderCreateVariable( DIB(self), dwarf_tag, scope_metadata, - name.as_ptr(), + name.as_ptr().cast(), + name.len(), file_metadata, loc.line as c_uint, type_metadata, diff --git a/src/librustc_codegen_llvm/debuginfo/namespace.rs b/src/librustc_codegen_llvm/debuginfo/namespace.rs index 582f495207455..55a3540809b48 100644 --- a/src/librustc_codegen_llvm/debuginfo/namespace.rs +++ b/src/librustc_codegen_llvm/debuginfo/namespace.rs @@ -1,6 +1,5 @@ // Namespace Handling. -use super::metadata::{unknown_file_metadata, UNKNOWN_LINE_NUMBER}; use super::utils::{debug_context, DIB}; use rustc::ty::{self, Instance}; @@ -10,8 +9,6 @@ use crate::llvm::debuginfo::DIScope; use rustc::hir::map::DefPathData; use rustc_hir::def_id::DefId; -use rustc_data_structures::small_c_str::SmallCStr; - pub fn mangled_name_of_instance<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>, @@ -34,16 +31,15 @@ pub fn item_namespace(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope { DefPathData::CrateRoot => cx.tcx.crate_name(def_id.krate), data => data.as_symbol(), }; - - let namespace_name = SmallCStr::new(&namespace_name.as_str()); + let namespace_name = namespace_name.as_str(); let scope = unsafe { llvm::LLVMRustDIBuilderCreateNameSpace( DIB(cx), parent_scope, - namespace_name.as_ptr(), - unknown_file_metadata(cx), - UNKNOWN_LINE_NUMBER, + namespace_name.as_ptr().cast(), + namespace_name.len(), + false, // ExportSymbols (only relevant for C++ anonymous namespaces) ) }; diff --git a/src/librustc_codegen_llvm/llvm/ffi.rs b/src/librustc_codegen_llvm/llvm/ffi.rs index 8b796e0423b13..31a0f52809088 100644 --- a/src/librustc_codegen_llvm/llvm/ffi.rs +++ b/src/librustc_codegen_llvm/llvm/ffi.rs @@ -1607,17 +1607,21 @@ extern "C" { Lang: c_uint, File: &'a DIFile, Producer: *const c_char, + ProducerLen: size_t, isOptimized: bool, Flags: *const c_char, RuntimeVer: c_uint, SplitName: *const c_char, + SplitNameLen: size_t, kind: DebugEmissionKind, ) -> &'a DIDescriptor; pub fn LLVMRustDIBuilderCreateFile( Builder: &DIBuilder<'a>, Filename: *const c_char, + FilenameLen: size_t, Directory: *const c_char, + DirectoryLen: size_t, ) -> &'a DIFile; pub fn LLVMRustDIBuilderCreateSubroutineType( @@ -1630,7 +1634,9 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: &'a DIDescriptor, Name: *const c_char, + NameLen: size_t, LinkageName: *const c_char, + LinkageNameLen: size_t, File: &'a DIFile, LineNo: c_uint, Ty: &'a DIType, @@ -1645,6 +1651,7 @@ extern "C" { pub fn LLVMRustDIBuilderCreateBasicType( Builder: &DIBuilder<'a>, Name: *const c_char, + NameLen: size_t, SizeInBits: u64, AlignInBits: u32, Encoding: c_uint, @@ -1655,13 +1662,16 @@ extern "C" { PointeeTy: &'a DIType, SizeInBits: u64, AlignInBits: u32, + AddressSpace: c_uint, Name: *const c_char, + NameLen: size_t, ) -> &'a DIDerivedType; pub fn LLVMRustDIBuilderCreateStructType( Builder: &DIBuilder<'a>, Scope: Option<&'a DIDescriptor>, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNumber: c_uint, SizeInBits: u64, @@ -1672,12 +1682,14 @@ extern "C" { RunTimeLang: c_uint, VTableHolder: Option<&'a DIType>, UniqueId: *const c_char, + UniqueIdLen: size_t, ) -> &'a DICompositeType; pub fn LLVMRustDIBuilderCreateMemberType( Builder: &DIBuilder<'a>, Scope: &'a DIDescriptor, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNo: c_uint, SizeInBits: u64, @@ -1691,6 +1703,7 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: &'a DIScope, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNumber: c_uint, SizeInBits: u64, @@ -1719,7 +1732,9 @@ extern "C" { Builder: &DIBuilder<'a>, Context: Option<&'a DIScope>, Name: *const c_char, + NameLen: size_t, LinkageName: *const c_char, + LinkageNameLen: size_t, File: &'a DIFile, LineNo: c_uint, Ty: &'a DIType, @@ -1734,6 +1749,7 @@ extern "C" { Tag: c_uint, Scope: &'a DIDescriptor, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNo: c_uint, Ty: &'a DIType, @@ -1785,6 +1801,7 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: &'a DIScope, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNumber: c_uint, SizeInBits: u64, @@ -1798,6 +1815,7 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: &'a DIScope, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNumber: c_uint, SizeInBits: u64, @@ -1806,12 +1824,14 @@ extern "C" { Elements: Option<&'a DIArray>, RunTimeLang: c_uint, UniqueId: *const c_char, + UniqueIdLen: size_t, ) -> &'a DIType; pub fn LLVMRustDIBuilderCreateVariantPart( Builder: &DIBuilder<'a>, Scope: &'a DIScope, Name: *const c_char, + NameLen: size_t, File: &'a DIFile, LineNo: c_uint, SizeInBits: u64, @@ -1820,6 +1840,7 @@ extern "C" { Discriminator: Option<&'a DIDerivedType>, Elements: &'a DIArray, UniqueId: *const c_char, + UniqueIdLen: size_t, ) -> &'a DIDerivedType; pub fn LLVMSetUnnamedAddr(GlobalVar: &Value, UnnamedAddr: Bool); @@ -1828,6 +1849,7 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: Option<&'a DIScope>, Name: *const c_char, + NameLen: size_t, Ty: &'a DIType, File: &'a DIFile, LineNo: c_uint, @@ -1838,8 +1860,8 @@ extern "C" { Builder: &DIBuilder<'a>, Scope: Option<&'a DIScope>, Name: *const c_char, - File: &'a DIFile, - LineNo: c_uint, + NameLen: size_t, + ExportSymbols: bool, ) -> &'a DINameSpace; pub fn LLVMRustDICompositeTypeReplaceArrays( diff --git a/src/rustllvm/RustWrapper.cpp b/src/rustllvm/RustWrapper.cpp index 0e430d3881e60..aeddd4cfb9fe9 100644 --- a/src/rustllvm/RustWrapper.cpp +++ b/src/rustllvm/RustWrapper.cpp @@ -665,20 +665,24 @@ extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) { extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit( LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef, - const char *Producer, bool isOptimized, const char *Flags, - unsigned RuntimeVer, const char *SplitName, + const char *Producer, size_t ProducerLen, bool isOptimized, + const char *Flags, unsigned RuntimeVer, + const char *SplitName, size_t SplitNameLen, LLVMRustDebugEmissionKind Kind) { auto *File = unwrapDI(FileRef); - return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized, - Flags, RuntimeVer, SplitName, + return wrap(Builder->createCompileUnit(Lang, File, StringRef(Producer, ProducerLen), + isOptimized, Flags, RuntimeVer, + StringRef(SplitName, SplitNameLen), fromRust(Kind))); } -extern "C" LLVMMetadataRef -LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename, - const char *Directory) { - return wrap(Builder->createFile(Filename, Directory)); +extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFile( + LLVMRustDIBuilderRef Builder, + const char *Filename, size_t FilenameLen, + const char *Directory, size_t DirectoryLen) { + return wrap(Builder->createFile(StringRef(Filename, FilenameLen), + StringRef(Directory, DirectoryLen))); } extern "C" LLVMMetadataRef @@ -690,8 +694,10 @@ LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder, } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, - const char *LinkageName, LLVMMetadataRef File, unsigned LineNo, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, + const char *LinkageName, size_t LinkageNameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) { @@ -705,8 +711,11 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( llvmFlags |= DINode::DIFlags::FlagMainSubprogram; #endif DISubprogram *Sub = Builder->createFunction( - unwrapDI(Scope), Name, LinkageName, unwrapDI(File), - LineNo, unwrapDI(Ty), ScopeLine, llvmFlags, + unwrapDI(Scope), + StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), + unwrapDI(File), LineNo, + unwrapDI(Ty), ScopeLine, llvmFlags, llvmSPFlags, TParams, unwrapDIPtr(Decl)); #else bool IsLocalToUnit = isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit); @@ -716,8 +725,11 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram)) llvmFlags |= DINode::DIFlags::FlagMainSubprogram; DISubprogram *Sub = Builder->createFunction( - unwrapDI(Scope), Name, LinkageName, unwrapDI(File), - LineNo, unwrapDI(Ty), IsLocalToUnit, IsDefinition, + unwrapDI(Scope), + StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), + unwrapDI(File), LineNo, + unwrapDI(Ty), IsLocalToUnit, IsDefinition, ScopeLine, llvmFlags, IsOptimized, TParams, unwrapDIPtr(Decl)); #endif @@ -725,53 +737,59 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( return wrap(Sub); } -extern "C" LLVMMetadataRef -LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name, - uint64_t SizeInBits, uint32_t AlignInBits, - unsigned Encoding) { - return wrap(Builder->createBasicType(Name, SizeInBits, Encoding)); +extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType( + LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, + uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding) { + return wrap(Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding)); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy, - uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) { + uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, + const char *Name, size_t NameLen) { return wrap(Builder->createPointerType(unwrapDI(PointeeTy), SizeInBits, AlignInBits, - /* DWARFAddressSpace */ None, - Name)); + AddressSpace, + StringRef(Name, NameLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder, - const char *UniqueId) { + const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createStructType( - unwrapDI(Scope), Name, unwrapDI(File), LineNumber, + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(DerivedFrom), DINodeArray(unwrapDI(Elements)), RunTimeLang, - unwrapDI(VTableHolder), UniqueId)); + unwrapDI(VTableHolder), StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator, - LLVMMetadataRef Elements, const char *UniqueId) { + LLVMMetadataRef Elements, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createVariantPart( - unwrapDI(Scope), Name, unwrapDI(File), LineNumber, + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(Discriminator), - DINodeArray(unwrapDI(Elements)), UniqueId)); + DINodeArray(unwrapDI(Elements)), StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { - return wrap(Builder->createMemberType(unwrapDI(Scope), Name, + return wrap(Builder->createMemberType(unwrapDI(Scope), + StringRef(Name, NameLen), unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, fromRust(Flags), unwrapDI(Ty))); @@ -779,14 +797,15 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType( extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, - uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, + uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { llvm::ConstantInt* D = nullptr; if (Discriminant) { D = unwrap(Discriminant); } - return wrap(Builder->createVariantMemberType(unwrapDI(Scope), Name, + return wrap(Builder->createVariantMemberType(unwrapDI(Scope), + StringRef(Name, NameLen), unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, D, fromRust(Flags), unwrapDI(Ty))); @@ -808,8 +827,10 @@ LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder, } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name, - const char *LinkageName, LLVMMetadataRef File, unsigned LineNo, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, + const char *Name, size_t NameLen, + const char *LinkageName, size_t LinkageNameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V, LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) { llvm::GlobalVariable *InitVal = cast(unwrap(V)); @@ -825,7 +846,8 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( } llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression( - unwrapDI(Context), Name, LinkageName, + unwrapDI(Context), StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, unwrapDI(Ty), IsLocalToUnit, #if LLVM_VERSION_GE(10, 0) /* isDefined */ true, @@ -843,17 +865,20 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable( LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope, - const char *Name, LLVMMetadataRef File, unsigned LineNo, + const char *Name, size_t NameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags, unsigned ArgNo, uint32_t AlignInBits) { if (Tag == 0x100) { // DW_TAG_auto_variable return wrap(Builder->createAutoVariable( - unwrapDI(Scope), Name, unwrapDI(File), LineNo, + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNo, unwrapDI(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits)); } else { return wrap(Builder->createParameterVariable( - unwrapDI(Scope), Name, ArgNo, unwrapDI(File), - LineNo, unwrapDI(Ty), AlwaysPreserve, fromRust(Flags))); + unwrapDI(Scope), StringRef(Name, NameLen), ArgNo, + unwrapDI(File), LineNo, + unwrapDI(Ty), AlwaysPreserve, fromRust(Flags))); } } @@ -894,47 +919,50 @@ extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd( extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerator( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, int64_t Value, bool IsUnsigned) { - return wrap(Builder->createEnumerator({Name, NameLen}, Value, IsUnsigned)); + return wrap(Builder->createEnumerator(StringRef(Name, NameLen), Value, IsUnsigned)); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef Elements, LLVMMetadataRef ClassTy, bool IsScoped) { return wrap(Builder->createEnumerationType( - unwrapDI(Scope), Name, unwrapDI(File), LineNumber, + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, DINodeArray(unwrapDI(Elements)), unwrapDI(ClassTy), "", IsScoped)); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements, - unsigned RunTimeLang, const char *UniqueId) { + unsigned RunTimeLang, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createUnionType( - unwrapDI(Scope), Name, unwrapDI(File), LineNumber, - SizeInBits, AlignInBits, fromRust(Flags), - DINodeArray(unwrapDI(Elements)), RunTimeLang, UniqueId)); + unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), + LineNumber, SizeInBits, AlignInBits, fromRust(Flags), + DINodeArray(unwrapDI(Elements)), RunTimeLang, + StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo, unsigned ColumnNo) { return wrap(Builder->createTemplateTypeParameter( - unwrapDI(Scope), Name, unwrapDI(Ty))); + unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(Ty))); } -extern "C" LLVMMetadataRef -LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder, - LLVMMetadataRef Scope, const char *Name, - LLVMMetadataRef File, unsigned LineNo) { +extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateNameSpace( + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, + const char *Name, size_t NameLen, bool ExportSymbols) { return wrap(Builder->createNameSpace( - unwrapDI(Scope), Name, - false // ExportSymbols (only relevant for C++ anonymous namespaces) - )); + unwrapDI(Scope), StringRef(Name, NameLen), ExportSymbols + )); } extern "C" void From e54a829b5795ff137e280628566e44edebe6f14b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Mi=C4=85sko?= Date: Fri, 6 Mar 2020 00:00:00 +0000 Subject: [PATCH 30/31] Avoid unnecessary interning of enum variant part id --- src/librustc_codegen_llvm/debuginfo/metadata.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 5cf3d74f243cd..46c4a51111432 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -229,10 +229,7 @@ impl TypeMap<'ll, 'tcx> { &mut self, enum_type_id: UniqueTypeId, ) -> String { - let variant_part_type_id = - format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id)); - self.unique_id_interner.intern(&variant_part_type_id); - variant_part_type_id + format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id)) } } From 676b9bc477dfe58971b7df9df4e3a053bb187dee Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Tue, 3 Mar 2020 15:04:57 -0800 Subject: [PATCH 31/31] unix: Don't override existing SIGSEGV/BUS handlers Although `stack_overflow::init` runs very early in the process, even before `main`, there may already be signal handlers installed for things like the address sanitizer. In that case, just leave it alone, and don't bother trying to allocate our own signal stacks either. --- src/libstd/sys/unix/stack_overflow.rs | 28 +++++++++++++++++++-------- src/test/ui/sanitize/badfree.rs | 19 ++++++++++++++++++ 2 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 src/test/ui/sanitize/badfree.rs diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index 528fe321efbce..9e8be55075578 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -13,6 +13,10 @@ impl Handler { pub unsafe fn new() -> Handler { make_handler() } + + fn null() -> Handler { + Handler { _data: crate::ptr::null_mut() } + } } impl Drop for Handler { @@ -108,13 +112,20 @@ mod imp { } static mut MAIN_ALTSTACK: *mut libc::c_void = ptr::null_mut(); + static mut NEED_ALTSTACK: bool = false; pub unsafe fn init() { let mut action: sigaction = mem::zeroed(); - action.sa_flags = SA_SIGINFO | SA_ONSTACK; - action.sa_sigaction = signal_handler as sighandler_t; - sigaction(SIGSEGV, &action, ptr::null_mut()); - sigaction(SIGBUS, &action, ptr::null_mut()); + for &signal in &[SIGSEGV, SIGBUS] { + sigaction(signal, ptr::null_mut(), &mut action); + // Configure our signal handler if one is not already set. + if action.sa_sigaction == SIG_DFL { + action.sa_flags = SA_SIGINFO | SA_ONSTACK; + action.sa_sigaction = signal_handler as sighandler_t; + sigaction(signal, &action, ptr::null_mut()); + NEED_ALTSTACK = true; + } + } let handler = make_handler(); MAIN_ALTSTACK = handler._data; @@ -152,6 +163,9 @@ mod imp { } pub unsafe fn make_handler() -> Handler { + if !NEED_ALTSTACK { + return Handler::null(); + } let mut stack = mem::zeroed(); sigaltstack(ptr::null(), &mut stack); // Configure alternate signal stack, if one is not already set. @@ -160,7 +174,7 @@ mod imp { sigaltstack(&stack, ptr::null_mut()); Handler { _data: stack.ss_sp as *mut libc::c_void } } else { - Handler { _data: ptr::null_mut() } + Handler::null() } } @@ -191,14 +205,12 @@ mod imp { target_os = "openbsd" )))] mod imp { - use crate::ptr; - pub unsafe fn init() {} pub unsafe fn cleanup() {} pub unsafe fn make_handler() -> super::Handler { - super::Handler { _data: ptr::null_mut() } + super::Handler::null() } pub unsafe fn drop_handler(_handler: &mut super::Handler) {} diff --git a/src/test/ui/sanitize/badfree.rs b/src/test/ui/sanitize/badfree.rs new file mode 100644 index 0000000000000..1ca082c8b4704 --- /dev/null +++ b/src/test/ui/sanitize/badfree.rs @@ -0,0 +1,19 @@ +// needs-sanitizer-support +// only-x86_64 +// +// compile-flags: -Z sanitizer=address -O +// +// run-fail +// error-pattern: AddressSanitizer: SEGV + +use std::ffi::c_void; + +extern "C" { + fn free(ptr: *mut c_void); +} + +fn main() { + unsafe { + free(1 as *mut c_void); + } +}