Skip to content

Commit 3a73ca5

Browse files
Urgauwanda-phi
andcommitted
Implement --check-cfg option (RFC 3013)
Co-authored-by: Urgau <lolo.branstett@numericable.fr> Co-authored-by: Marcelina Kościelnicka <mwk@0x04.net>
1 parent 6499c5e commit 3a73ca5

27 files changed

+365
-7
lines changed

compiler/rustc_attr/src/builtin.rs

+28-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
//! Parsing and validation of builtin attributes
22
3-
use rustc_ast::{self as ast, Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
3+
use rustc_ast as ast;
4+
use rustc_ast::node_id::CRATE_NODE_ID;
5+
use rustc_ast::{Attribute, Lit, LitKind, MetaItem, MetaItemKind, NestedMetaItem};
46
use rustc_ast_pretty::pprust;
57
use rustc_errors::{struct_span_err, Applicability};
68
use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg};
79
use rustc_macros::HashStable_Generic;
10+
use rustc_session::lint::builtin::UNEXPECTED_CFGS;
811
use rustc_session::parse::{feature_err, ParseSess};
912
use rustc_session::Session;
1013
use rustc_span::hygiene::Transparency;
@@ -458,8 +461,30 @@ pub fn cfg_matches(cfg: &ast::MetaItem, sess: &ParseSess, features: Option<&Feat
458461
true
459462
}
460463
MetaItemKind::NameValue(..) | MetaItemKind::Word => {
461-
let ident = cfg.ident().expect("multi-segment cfg predicate");
462-
sess.config.contains(&(ident.name, cfg.value_str()))
464+
let name = cfg.ident().expect("multi-segment cfg predicate").name;
465+
let value = cfg.value_str();
466+
if sess.check_config.names_checked && !sess.check_config.names_valid.contains(&name)
467+
{
468+
sess.buffer_lint(
469+
UNEXPECTED_CFGS,
470+
cfg.span,
471+
CRATE_NODE_ID,
472+
"unexpected `cfg` condition name",
473+
);
474+
}
475+
if let Some(val) = value {
476+
if sess.check_config.values_checked.contains(&name)
477+
&& !sess.check_config.values_valid.contains(&(name, val))
478+
{
479+
sess.buffer_lint(
480+
UNEXPECTED_CFGS,
481+
cfg.span,
482+
CRATE_NODE_ID,
483+
"unexpected `cfg` condition value",
484+
);
485+
}
486+
}
487+
sess.config.contains(&(name, value))
463488
}
464489
}
465490
})

compiler/rustc_driver/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,12 @@ fn run_compiler(
216216
}
217217

218218
let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));
219+
let check_cfg = interface::parse_check_cfg(matches.opt_strs("check-cfg"));
219220
let (odir, ofile) = make_output(&matches);
220221
let mut config = interface::Config {
221222
opts: sopts,
222223
crate_cfg: cfg,
224+
crate_check_cfg: check_cfg,
223225
input: Input::File(PathBuf::new()),
224226
input_path: None,
225227
output_file: ofile,

compiler/rustc_interface/src/interface.rs

+89-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ pub use crate::passes::BoxedResolver;
22
use crate::util;
33

44
use rustc_ast::token;
5-
use rustc_ast::{self as ast, MetaItemKind};
5+
use rustc_ast::{self as ast, LitKind, MetaItemKind};
66
use rustc_codegen_ssa::traits::CodegenBackend;
77
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
88
use rustc_data_structures::sync::Lrc;
@@ -13,12 +13,13 @@ use rustc_lint::LintStore;
1313
use rustc_middle::ty;
1414
use rustc_parse::maybe_new_parser_from_source_str;
1515
use rustc_query_impl::QueryCtxt;
16-
use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
16+
use rustc_session::config::{self, CheckCfg, ErrorOutputType, Input, OutputFilenames};
1717
use rustc_session::early_error;
1818
use rustc_session::lint;
1919
use rustc_session::parse::{CrateConfig, ParseSess};
2020
use rustc_session::{DiagnosticOutput, Session};
2121
use rustc_span::source_map::{FileLoader, FileName};
22+
use rustc_span::symbol::sym;
2223
use std::path::PathBuf;
2324
use std::result;
2425
use std::sync::{Arc, Mutex};
@@ -140,13 +141,98 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String
140141
})
141142
}
142143

144+
/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
145+
pub fn parse_check_cfg(specs: Vec<String>) -> CheckCfg {
146+
rustc_span::create_default_session_if_not_set_then(move |_| {
147+
let mut cfg = CheckCfg::default();
148+
149+
'specs: for s in specs {
150+
let sess = ParseSess::with_silent_emitter(Some(format!(
151+
"this error occurred on the command line: `--check-cfg={}`",
152+
s
153+
)));
154+
let filename = FileName::cfg_spec_source_code(&s);
155+
156+
macro_rules! error {
157+
($reason: expr) => {
158+
early_error(
159+
ErrorOutputType::default(),
160+
&format!(
161+
concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
162+
s
163+
),
164+
);
165+
};
166+
}
167+
168+
match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) {
169+
Ok(mut parser) => match &mut parser.parse_meta_item() {
170+
Ok(meta_item) if parser.token == token::Eof => {
171+
if let Some(args) = meta_item.meta_item_list() {
172+
if meta_item.has_name(sym::names) {
173+
cfg.names_checked = true;
174+
for arg in args {
175+
if arg.is_word() && arg.ident().is_some() {
176+
let ident = arg.ident().expect("multi-segment cfg key");
177+
cfg.names_valid.insert(ident.name.to_string());
178+
} else {
179+
error!("`names()` arguments must be simple identifers");
180+
}
181+
}
182+
continue 'specs;
183+
} else if meta_item.has_name(sym::values) {
184+
if let Some((name, values)) = args.split_first() {
185+
if name.is_word() && name.ident().is_some() {
186+
let ident = name.ident().expect("multi-segment cfg key");
187+
cfg.values_checked.insert(ident.to_string());
188+
for val in values {
189+
if let Some(LitKind::Str(s, _)) =
190+
val.literal().map(|lit| &lit.kind)
191+
{
192+
cfg.values_valid
193+
.insert((ident.to_string(), s.to_string()));
194+
} else {
195+
error!(
196+
"`values()` arguments must be string literals"
197+
);
198+
}
199+
}
200+
201+
continue 'specs;
202+
} else {
203+
error!(
204+
"`values()` first argument must be a simple identifer"
205+
);
206+
}
207+
}
208+
}
209+
}
210+
}
211+
Ok(..) => {}
212+
Err(err) => err.cancel(),
213+
},
214+
Err(errs) => errs.into_iter().for_each(|mut err| err.cancel()),
215+
}
216+
217+
error!(
218+
"expected `names(name1, name2, ... nameN)` or \
219+
`values(name, \"value1\", \"value2\", ... \"valueN\")`"
220+
);
221+
}
222+
223+
cfg.names_valid.extend(cfg.values_checked.iter().cloned());
224+
cfg
225+
})
226+
}
227+
143228
/// The compiler configuration
144229
pub struct Config {
145230
/// Command line options
146231
pub opts: config::Options,
147232

148233
/// cfg! configuration in addition to the default ones
149234
pub crate_cfg: FxHashSet<(String, Option<String>)>,
235+
pub crate_check_cfg: CheckCfg,
150236

151237
pub input: Input,
152238
pub input_path: Option<PathBuf>,
@@ -190,6 +276,7 @@ pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R
190276
let (mut sess, codegen_backend) = util::create_session(
191277
config.opts,
192278
config.crate_cfg,
279+
config.crate_check_cfg,
193280
config.diagnostic_output,
194281
config.file_loader,
195282
config.input_path.clone(),

compiler/rustc_interface/src/util.rs

+8
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_parse::validate_attr;
1515
use rustc_query_impl::QueryCtxt;
1616
use rustc_resolve::{self, Resolver};
1717
use rustc_session as session;
18+
use rustc_session::config::CheckCfg;
1819
use rustc_session::config::{self, CrateType};
1920
use rustc_session::config::{ErrorOutputType, Input, OutputFilenames};
2021
use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
@@ -67,6 +68,7 @@ pub fn add_configuration(
6768
pub fn create_session(
6869
sopts: config::Options,
6970
cfg: FxHashSet<(String, Option<String>)>,
71+
check_cfg: CheckCfg,
7072
diagnostic_output: DiagnosticOutput,
7173
file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
7274
input_path: Option<PathBuf>,
@@ -102,7 +104,13 @@ pub fn create_session(
102104

103105
let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
104106
add_configuration(&mut cfg, &mut sess, &*codegen_backend);
107+
108+
let mut check_cfg = config::to_crate_check_config(check_cfg);
109+
check_cfg.fill_well_known();
110+
check_cfg.fill_actual(&cfg);
111+
105112
sess.parse_sess.config = cfg;
113+
sess.parse_sess.check_config = check_cfg;
106114

107115
(Lrc::new(sess), Lrc::new(codegen_backend))
108116
}

compiler/rustc_lint_defs/src/builtin.rs

+38
Original file line numberDiff line numberDiff line change
@@ -2957,6 +2957,43 @@ declare_lint! {
29572957
};
29582958
}
29592959

2960+
declare_lint! {
2961+
/// The `unexpected_cfgs` lint detects unexpected conditional compilation conditions.
2962+
///
2963+
/// ### Example
2964+
///
2965+
/// ```text
2966+
/// rustc --check-cfg 'names()'
2967+
/// ```
2968+
///
2969+
/// ```rust,ignore (needs command line option)
2970+
/// #[cfg(widnows)]
2971+
/// fn foo() {}
2972+
/// ```
2973+
///
2974+
/// This will produce:
2975+
///
2976+
/// ```text
2977+
/// warning: unknown condition name used
2978+
/// --> lint_example.rs:1:7
2979+
/// |
2980+
/// 1 | #[cfg(widnows)]
2981+
/// | ^^^^^^^
2982+
/// |
2983+
/// = note: `#[warn(unexpected_cfgs)]` on by default
2984+
/// ```
2985+
///
2986+
/// ### Explanation
2987+
///
2988+
/// This lint is only active when a `--check-cfg='names(...)'` option has been passed
2989+
/// to the compiler and triggers whenever an unknown condition name or value is used.
2990+
/// The known condition include names or values passed in `--check-cfg`, `--cfg`, and some
2991+
/// well-knows names and values built into the compiler.
2992+
pub UNEXPECTED_CFGS,
2993+
Warn,
2994+
"detects unexpected names and values in `#[cfg]` conditions",
2995+
}
2996+
29602997
declare_lint_pass! {
29612998
/// Does nothing as a lint pass, but registers some `Lint`s
29622999
/// that are used by other parts of the compiler.
@@ -3055,6 +3092,7 @@ declare_lint_pass! {
30553092
DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME,
30563093
DUPLICATE_MACRO_ATTRIBUTES,
30573094
SUSPICIOUS_AUTO_TRAIT_IMPLS,
3095+
UNEXPECTED_CFGS,
30583096
]
30593097
}
30603098

compiler/rustc_session/src/config.rs

+88-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use rustc_target::spec::{LinkerFlavor, SplitDebuginfo, Target, TargetTriple, Tar
1616

1717
use rustc_serialize::json;
1818

19-
use crate::parse::CrateConfig;
19+
use crate::parse::{CrateCheckConfig, CrateConfig};
2020
use rustc_feature::UnstableFeatures;
2121
use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION};
2222
use rustc_span::source_map::{FileName, FilePathMapping};
@@ -921,6 +921,7 @@ pub const fn default_lib_output() -> CrateType {
921921
}
922922

923923
fn default_configuration(sess: &Session) -> CrateConfig {
924+
// NOTE: This should be kept in sync with `CrateCheckConfig::fill_well_known` below.
924925
let end = &sess.target.endian;
925926
let arch = &sess.target.arch;
926927
let wordsz = sess.target.pointer_width.to_string();
@@ -1005,6 +1006,91 @@ pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> CrateConfig
10051006
cfg.into_iter().map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b)))).collect()
10061007
}
10071008

1009+
/// The parsed `--check-cfg` options
1010+
pub struct CheckCfg<T = String> {
1011+
/// Set if `names()` checking is enabled
1012+
pub names_checked: bool,
1013+
/// The union of all `names()`
1014+
pub names_valid: FxHashSet<T>,
1015+
/// The set of names for which `values()` was used
1016+
pub values_checked: FxHashSet<T>,
1017+
/// The set of all (name, value) pairs passed in `values()`
1018+
pub values_valid: FxHashSet<(T, T)>,
1019+
}
1020+
1021+
impl<T> Default for CheckCfg<T> {
1022+
fn default() -> Self {
1023+
CheckCfg {
1024+
names_checked: false,
1025+
names_valid: FxHashSet::default(),
1026+
values_checked: FxHashSet::default(),
1027+
values_valid: FxHashSet::default(),
1028+
}
1029+
}
1030+
}
1031+
1032+
impl<T> CheckCfg<T> {
1033+
fn map_data<O: Eq + Hash>(&self, f: impl Fn(&T) -> O) -> CheckCfg<O> {
1034+
CheckCfg {
1035+
names_checked: self.names_checked,
1036+
names_valid: self.names_valid.iter().map(|a| f(a)).collect(),
1037+
values_checked: self.values_checked.iter().map(|a| f(a)).collect(),
1038+
values_valid: self.values_valid.iter().map(|(a, b)| (f(a), f(b))).collect(),
1039+
}
1040+
}
1041+
}
1042+
1043+
/// Converts the crate `--check-cfg` options from `String` to `Symbol`.
1044+
/// `rustc_interface::interface::Config` accepts this in the compiler configuration,
1045+
/// but the symbol interner is not yet set up then, so we must convert it later.
1046+
pub fn to_crate_check_config(cfg: CheckCfg) -> CrateCheckConfig {
1047+
cfg.map_data(|s| Symbol::intern(s))
1048+
}
1049+
1050+
impl CrateCheckConfig {
1051+
/// Fills a `CrateCheckConfig` with well-known configuration names.
1052+
pub fn fill_well_known(&mut self) {
1053+
// NOTE: This should be kept in sync with `default_configuration`
1054+
const WELL_KNOWN_NAMES: &[Symbol] = &[
1055+
sym::unix,
1056+
sym::windows,
1057+
sym::target_os,
1058+
sym::target_family,
1059+
sym::target_arch,
1060+
sym::target_endian,
1061+
sym::target_pointer_width,
1062+
sym::target_env,
1063+
sym::target_abi,
1064+
sym::target_vendor,
1065+
sym::target_thread_local,
1066+
sym::target_has_atomic_load_store,
1067+
sym::target_has_atomic,
1068+
sym::target_has_atomic_equal_alignment,
1069+
sym::panic,
1070+
sym::sanitize,
1071+
sym::debug_assertions,
1072+
sym::proc_macro,
1073+
sym::test,
1074+
sym::doc,
1075+
sym::doctest,
1076+
sym::feature,
1077+
];
1078+
for &name in WELL_KNOWN_NAMES {
1079+
self.names_valid.insert(name);
1080+
}
1081+
}
1082+
1083+
/// Fills a `CrateCheckConfig` with configuration names and values that are actually active.
1084+
pub fn fill_actual(&mut self, cfg: &CrateConfig) {
1085+
for &(k, v) in cfg {
1086+
self.names_valid.insert(k);
1087+
if let Some(v) = v {
1088+
self.values_valid.insert((k, v));
1089+
}
1090+
}
1091+
}
1092+
}
1093+
10081094
pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateConfig {
10091095
// Combine the configuration requested by the session (command line) with
10101096
// some default and generated configuration items.
@@ -1148,6 +1234,7 @@ pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
11481234
vec![
11491235
opt::flag_s("h", "help", "Display this message"),
11501236
opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1237+
opt::multi("", "check-cfg", "Provide list of valid cfg options for checking", "SPEC"),
11511238
opt::multi_s(
11521239
"L",
11531240
"",

0 commit comments

Comments
 (0)