1 //! Tidy check to ensure that unstable features are all in order.
3 //! This check will ensure properties like:
5 //! * All stability attributes look reasonably well formed.
6 //! * The set of library features is disjoint from the set of language features.
7 //! * Library features have at most one stability level.
8 //! * Library features have at most one `since` value.
9 //! * All unstable lang features have tests to ensure they are actually unstable.
10 //! * Language features in a group are sorted by `since` value.
12 use std::collections::HashMap;
15 use std::num::NonZeroU32;
26 const FEATURE_GROUP_START_PREFIX: &str = "// feature-group-start";
27 const FEATURE_GROUP_END_PREFIX: &str = "// feature-group-end";
29 #[derive(Debug, PartialEq, Clone)]
36 impl fmt::Display for Status {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 let as_str = match *self {
39 Status::Stable => "stable",
40 Status::Unstable => "unstable",
41 Status::Removed => "removed",
43 fmt::Display::fmt(as_str, f)
47 #[derive(Debug, Clone)]
50 pub since: Option<Version>,
51 pub has_gate_test: bool,
52 pub tracking_issue: Option<NonZeroU32>,
55 pub type Features = HashMap<String, Feature>;
57 pub struct CollectedFeatures {
62 // Currently only used for unstable book generation
63 pub fn collect_lib_features(base_src_path: &Path) -> Features {
64 let mut lib_features = Features::new();
66 // This library feature is defined in the `compiler_builtins` crate, which
67 // has been moved out-of-tree. Now it can no longer be auto-discovered by
68 // `tidy`, because we need to filter out its (submodule) directory. Manually
69 // add it to the set of known library features so we can still generate docs.
71 "compiler_builtins_lib".to_owned(),
73 level: Status::Unstable,
80 map_lib_features(base_src_path, &mut |res, _, _| {
81 if let Ok((name, feature)) = res {
82 lib_features.insert(name.to_owned(), feature);
88 pub fn check(path: &Path, bad: &mut bool, verbose: bool) -> CollectedFeatures {
89 let mut features = collect_lang_features(path, bad);
90 assert!(!features.is_empty());
92 let lib_features = get_and_check_lib_features(path, bad, &features);
93 assert!(!lib_features.is_empty());
96 &[&path.join("test/ui"), &path.join("test/ui-fulldeps"), &path.join("test/compile-fail")],
97 &mut |path| super::filter_dirs(path),
98 &mut |entry, contents| {
99 let file = entry.path();
100 let filename = file.file_name().unwrap().to_string_lossy();
101 if !filename.ends_with(".rs")
102 || filename == "features.rs"
103 || filename == "diagnostic_list.rs"
108 let filen_underscore = filename.replace('-', "_").replace(".rs", "");
109 let filename_is_gate_test = test_filen_gate(&filen_underscore, &mut features);
111 for (i, line) in contents.lines().enumerate() {
112 let mut err = |msg: &str| {
113 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
116 let gate_test_str = "gate-test-";
118 let feature_name = match line.find(gate_test_str) {
119 Some(i) => line[i + gate_test_str.len()..].splitn(2, ' ').next().unwrap(),
122 match features.get_mut(feature_name) {
124 if filename_is_gate_test {
126 "The file is already marked as gate test \
127 through its name, no need for a \
128 'gate-test-{}' comment",
132 f.has_gate_test = true;
136 "gate-test test found referencing a nonexistent feature '{}'",
145 // Only check the number of lang features.
146 // Obligatory testing for library features is dumb.
147 let gate_untested = features
149 .filter(|&(_, f)| f.level == Status::Unstable)
150 .filter(|&(_, f)| !f.has_gate_test)
151 .collect::<Vec<_>>();
153 for &(name, _) in gate_untested.iter() {
154 println!("Expected a gate test for the feature '{}'.", name);
156 "Hint: create a failing test file named 'feature-gate-{}.rs'\
157 \n in the 'ui' test suite, with its failures due to\
158 \n missing usage of `#![feature({})]`.",
162 "Hint: If you already have such a test and don't want to rename it,\
163 \n you can also add a // gate-test-{} line to the test file.",
168 if !gate_untested.is_empty() {
169 tidy_error!(bad, "Found {} features without a gate test.", gate_untested.len());
173 return CollectedFeatures { lib: lib_features, lang: features };
177 let mut lines = Vec::new();
178 lines.extend(format_features(&features, "lang"));
179 lines.extend(format_features(&lib_features, "lib"));
183 println!("* {}", line);
186 println!("* {} features", features.len());
189 CollectedFeatures { lib: lib_features, lang: features }
192 fn format_features<'a>(
193 features: &'a Features,
195 ) -> impl Iterator<Item = String> + 'a {
196 features.iter().map(move |(name, feature)| {
198 "{:<32} {:<8} {:<12} {:<8}",
202 feature.since.map_or("None".to_owned(), |since| since.to_string())
207 fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
208 lazy_static::lazy_static! {
209 static ref ISSUE: Regex = Regex::new(r#"issue\s*=\s*"([^"]*)""#).unwrap();
210 static ref FEATURE: Regex = Regex::new(r#"feature\s*=\s*"([^"]*)""#).unwrap();
211 static ref SINCE: Regex = Regex::new(r#"since\s*=\s*"([^"]*)""#).unwrap();
216 "feature" => &*FEATURE,
218 _ => unimplemented!("{} not handled", attr),
221 r.captures(line).and_then(|c| c.get(1)).map(|m| m.as_str())
224 fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool {
225 let prefix = "feature_gate_";
226 if filen_underscore.starts_with(prefix) {
227 for (n, f) in features.iter_mut() {
228 // Equivalent to filen_underscore == format!("feature_gate_{}", n)
229 if &filen_underscore[prefix.len()..] == n {
230 f.has_gate_test = true;
238 pub fn collect_lang_features(base_src_path: &Path, bad: &mut bool) -> Features {
239 let mut all = collect_lang_features_in(base_src_path, "active.rs", bad);
240 all.extend(collect_lang_features_in(base_src_path, "accepted.rs", bad));
241 all.extend(collect_lang_features_in(base_src_path, "removed.rs", bad));
245 fn collect_lang_features_in(base: &Path, file: &str, bad: &mut bool) -> Features {
246 let path = base.join("librustc_feature").join(file);
247 let contents = t!(fs::read_to_string(&path));
249 // We allow rustc-internal features to omit a tracking issue.
250 // To make tidy accept omitting a tracking issue, group the list of features
251 // without one inside `// no-tracking-issue` and `// no-tracking-issue-end`.
252 let mut next_feature_omits_tracking_issue = false;
254 let mut in_feature_group = false;
255 let mut prev_since = None;
260 .filter_map(|(line, line_number)| {
261 let line = line.trim();
263 // Within -start and -end, the tracking issue can be omitted.
265 "// no-tracking-issue-start" => {
266 next_feature_omits_tracking_issue = true;
269 "// no-tracking-issue-end" => {
270 next_feature_omits_tracking_issue = false;
276 if line.starts_with(FEATURE_GROUP_START_PREFIX) {
277 if in_feature_group {
281 new feature group is started without ending the previous one",
287 in_feature_group = true;
290 } else if line.starts_with(FEATURE_GROUP_END_PREFIX) {
291 in_feature_group = false;
296 let mut parts = line.split(',');
297 let level = match parts.next().map(|l| l.trim().trim_start_matches('(')) {
298 Some("active") => Status::Unstable,
299 Some("removed") => Status::Removed,
300 Some("accepted") => Status::Stable,
303 let name = parts.next().unwrap().trim();
305 let since_str = parts.next().unwrap().trim().trim_matches('"');
306 let since = match since_str.parse() {
307 Ok(since) => Some(since),
311 "{}:{}: failed to parse since: {} ({:?})",
320 if in_feature_group {
321 if prev_since > since {
324 "{}:{}: feature {} is not sorted by \"since\" (version number)",
333 let issue_str = parts.next().unwrap().trim();
334 let tracking_issue = if issue_str.starts_with("None") {
335 if level == Status::Unstable && !next_feature_omits_tracking_issue {
339 "{}:{}: no tracking issue for feature {}",
347 let s = issue_str.split('(').nth(1).unwrap().split(')').next().unwrap();
348 Some(s.parse().unwrap())
350 Some((name.to_owned(), Feature { level, since, has_gate_test: false, tracking_issue }))
355 fn get_and_check_lib_features(
356 base_src_path: &Path,
358 lang_features: &Features,
360 let mut lib_features = Features::new();
361 map_lib_features(base_src_path, &mut |res, file, line| match res {
363 let mut check_features = |f: &Feature, list: &Features, display: &str| {
364 if let Some(ref s) = list.get(name) {
365 if f.tracking_issue != s.tracking_issue && f.level != Status::Stable {
368 "{}:{}: mismatches the `issue` in {}",
376 check_features(&f, &lang_features, "corresponding lang feature");
377 check_features(&f, &lib_features, "previous");
378 lib_features.insert(name.to_owned(), f);
381 tidy_error!(bad, "{}:{}: {}", file.display(), line, msg);
388 base_src_path: &Path,
389 mf: &mut dyn FnMut(Result<(&str, Feature), &str>, &Path, usize),
393 &mut |path| super::filter_dirs(path) || path.ends_with("src/test"),
394 &mut |entry, contents| {
395 let file = entry.path();
396 let filename = file.file_name().unwrap().to_string_lossy();
397 if !filename.ends_with(".rs")
398 || filename == "features.rs"
399 || filename == "diagnostic_list.rs"
400 || filename == "error_codes.rs"
405 // This is an early exit -- all the attributes we're concerned with must contain this:
406 // * rustc_const_unstable(
409 if !contents.contains("stable(") {
413 let handle_issue_none = |s| match s {
416 let n = issue.parse().expect("issue number is not a valid integer");
417 assert_ne!(n, 0, "\"none\" should be used when there is no issue, not \"0\"");
421 let mut becoming_feature: Option<(&str, Feature)> = None;
422 let mut iter_lines = contents.lines().enumerate().peekable();
423 while let Some((i, line)) = iter_lines.next() {
426 mf(Err($msg), file, i + 1);
430 if let Some((ref name, ref mut f)) = becoming_feature {
431 if f.tracking_issue.is_none() {
432 f.tracking_issue = find_attr_val(line, "issue").and_then(handle_issue_none);
434 if line.ends_with(']') {
435 mf(Ok((name, f.clone())), file, i + 1);
436 } else if !line.ends_with(',') && !line.ends_with('\\') && !line.ends_with('"')
438 // We need to bail here because we might have missed the
439 // end of a stability attribute above because the ']'
440 // might not have been at the end of the line.
441 // We could then get into the very unfortunate situation that
442 // we continue parsing the file assuming the current stability
443 // attribute has not ended, and ignoring possible feature
444 // attributes in the process.
445 err!("malformed stability attribute");
450 becoming_feature = None;
451 if line.contains("rustc_const_unstable(") {
452 // `const fn` features are handled specially.
453 let feature_name = match find_attr_val(line, "feature") {
455 None => err!("malformed stability attribute: missing `feature` key"),
457 let feature = Feature {
458 level: Status::Unstable,
460 has_gate_test: false,
461 // FIXME(#57563): #57563 is now used as a common tracking issue,
462 // although we would like to have specific tracking issues for each
463 // `rustc_const_unstable` in the future.
464 tracking_issue: NonZeroU32::new(57563),
466 mf(Ok((feature_name, feature)), file, i + 1);
469 let level = if line.contains("[unstable(") {
471 } else if line.contains("[stable(") {
476 let feature_name = match find_attr_val(line, "feature")
477 .or_else(|| iter_lines.peek().and_then(|next| find_attr_val(next.1, "feature")))
480 None => err!("malformed stability attribute: missing `feature` key"),
482 let since = match find_attr_val(line, "since").map(|x| x.parse()) {
483 Some(Ok(since)) => Some(since),
485 err!("malformed stability attribute: can't parse `since` key");
487 None if level == Status::Stable => {
488 err!("malformed stability attribute: missing the `since` key");
492 let tracking_issue = find_attr_val(line, "issue").and_then(handle_issue_none);
494 let feature = Feature { level, since, has_gate_test: false, tracking_issue };
495 if line.contains(']') {
496 mf(Ok((feature_name, feature)), file, i + 1);
498 becoming_feature = Some((feature_name, feature));