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;
14 use std::fs::{self, File};
15 use std::io::prelude::*;
18 use regex::{Regex, escape};
21 use self::version::Version;
23 const FEATURE_GROUP_START_PREFIX: &str = "// feature group start:";
24 const FEATURE_GROUP_END_PREFIX: &str = "// feature group end";
26 #[derive(Debug, PartialEq, Clone)]
33 impl fmt::Display for Status {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 let as_str = match *self {
36 Status::Stable => "stable",
37 Status::Unstable => "unstable",
38 Status::Removed => "removed",
40 fmt::Display::fmt(as_str, f)
44 #[derive(Debug, Clone)]
47 pub since: Option<Version>,
48 pub has_gate_test: bool,
49 pub tracking_issue: Option<u32>,
50 pub group: Option<String>,
53 pub type Features = HashMap<String, Feature>;
55 pub fn check(path: &Path, bad: &mut bool, quiet: bool) {
56 let mut features = collect_lang_features(path, bad);
57 assert!(!features.is_empty());
59 let lib_features = get_and_check_lib_features(path, bad, &features);
60 assert!(!lib_features.is_empty());
62 let mut contents = String::new();
64 super::walk_many(&[&path.join("test/ui"),
65 &path.join("test/ui-fulldeps"),
66 &path.join("test/compile-fail")],
67 &mut |path| super::filter_dirs(path),
69 let filename = file.file_name().unwrap().to_string_lossy();
70 if !filename.ends_with(".rs") || filename == "features.rs" ||
71 filename == "diagnostic_list.rs" {
75 let filen_underscore = filename.replace('-',"_").replace(".rs","");
76 let filename_is_gate_test = test_filen_gate(&filen_underscore, &mut features);
79 t!(t!(File::open(&file), &file).read_to_string(&mut contents));
81 for (i, line) in contents.lines().enumerate() {
82 let mut err = |msg: &str| {
83 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
86 let gate_test_str = "gate-test-";
88 let feature_name = match line.find(gate_test_str) {
90 line[i+gate_test_str.len()..].splitn(2, ' ').next().unwrap()
94 match features.get_mut(feature_name) {
96 if filename_is_gate_test {
97 err(&format!("The file is already marked as gate test \
98 through its name, no need for a \
99 'gate-test-{}' comment",
102 f.has_gate_test = true;
105 err(&format!("gate-test test found referencing a nonexistent feature '{}'",
112 // Only check the number of lang features.
113 // Obligatory testing for library features is dumb.
114 let gate_untested = features.iter()
115 .filter(|&(_, f)| f.level == Status::Unstable)
116 .filter(|&(_, f)| !f.has_gate_test)
117 .collect::<Vec<_>>();
119 for &(name, _) in gate_untested.iter() {
120 println!("Expected a gate test for the feature '{}'.", name);
121 println!("Hint: create a failing test file named 'feature-gate-{}.rs'\
122 \n in the 'ui' test suite, with its failures due to\
123 \n missing usage of #![feature({})].", name, name);
124 println!("Hint: If you already have such a test and don't want to rename it,\
125 \n you can also add a // gate-test-{} line to the test file.",
129 if !gate_untested.is_empty() {
130 tidy_error!(bad, "Found {} features without a gate test.", gate_untested.len());
137 println!("* {} features", features.len());
141 let mut lines = Vec::new();
142 for (name, feature) in features.iter() {
143 lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
147 feature.since.as_ref().map_or("None".to_owned(),
148 |since| since.to_string())));
150 for (name, feature) in lib_features {
151 lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
155 feature.since.as_ref().map_or("None".to_owned(),
156 |since| since.to_string())));
161 println!("* {}", line);
165 fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
166 let r = Regex::new(&format!(r#"{} *= *"([^"]*)""#, escape(attr)))
167 .expect("malformed regex for find_attr_val");
169 .and_then(|c| c.get(1))
174 fn test_find_attr_val() {
175 let s = r#"#[unstable(feature = "checked_duration_since", issue = "58402")]"#;
176 assert_eq!(find_attr_val(s, "feature"), Some("checked_duration_since"));
177 assert_eq!(find_attr_val(s, "issue"), Some("58402"));
178 assert_eq!(find_attr_val(s, "since"), None);
181 fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool {
182 if filen_underscore.starts_with("feature_gate") {
183 for (n, f) in features.iter_mut() {
184 if filen_underscore == format!("feature_gate_{}", n) {
185 f.has_gate_test = true;
193 pub fn collect_lang_features(base_src_path: &Path, bad: &mut bool) -> Features {
194 let contents = t!(fs::read_to_string(base_src_path.join("libsyntax/feature_gate.rs")));
196 // We allow rustc-internal features to omit a tracking issue.
197 // To make tidy accept omitting a tracking issue, group the list of features
198 // without one inside `// no tracking issue START` and `// no tracking issue END`.
199 let mut next_feature_omits_tracking_issue = false;
201 let mut next_feature_group = None;
202 let mut prev_since = None;
204 contents.lines().zip(1..)
205 .filter_map(|(line, line_number)| {
206 let line = line.trim();
208 // Within START and END, the tracking issue can be omitted.
210 "// no tracking issue START" => {
211 next_feature_omits_tracking_issue = true;
214 "// no tracking issue END" => {
215 next_feature_omits_tracking_issue = false;
221 if line.starts_with(FEATURE_GROUP_START_PREFIX) {
222 let group = line.trim_start_matches(FEATURE_GROUP_START_PREFIX).trim();
223 next_feature_group = Some(group.to_owned());
226 } else if line.starts_with(FEATURE_GROUP_END_PREFIX) {
227 next_feature_group = None;
232 let mut parts = line.split(',');
233 let level = match parts.next().map(|l| l.trim().trim_start_matches('(')) {
234 Some("active") => Status::Unstable,
235 Some("removed") => Status::Removed,
236 Some("accepted") => Status::Stable,
239 let name = parts.next().unwrap().trim();
241 let since_str = parts.next().unwrap().trim().trim_matches('"');
242 let since = match since_str.parse() {
243 Ok(since) => Some(since),
247 "libsyntax/feature_gate.rs:{}: failed to parse since: {} ({})",
255 if next_feature_group.is_some() {
256 if prev_since > since {
259 "libsyntax/feature_gate.rs:{}: feature {} is not sorted by since",
264 prev_since = since.clone();
267 let issue_str = parts.next().unwrap().trim();
268 let tracking_issue = if issue_str.starts_with("None") {
269 if level == Status::Unstable && !next_feature_omits_tracking_issue {
273 "libsyntax/feature_gate.rs:{}: no tracking issue for feature {}",
280 let s = issue_str.split('(').nth(1).unwrap().split(')').nth(0).unwrap();
281 Some(s.parse().unwrap())
283 Some((name.to_owned(),
287 has_gate_test: false,
289 group: next_feature_group.clone(),
295 pub fn collect_lib_features(base_src_path: &Path) -> Features {
296 let mut lib_features = Features::new();
298 // This library feature is defined in the `compiler_builtins` crate, which
299 // has been moved out-of-tree. Now it can no longer be auto-discovered by
300 // `tidy`, because we need to filter out its (submodule) directory. Manually
301 // add it to the set of known library features so we can still generate docs.
302 lib_features.insert("compiler_builtins_lib".to_owned(), Feature {
303 level: Status::Unstable,
305 has_gate_test: false,
306 tracking_issue: None,
310 map_lib_features(base_src_path,
312 if let Ok((name, feature)) = res {
313 if lib_features.contains_key(name) {
316 lib_features.insert(name.to_owned(), feature);
322 fn get_and_check_lib_features(base_src_path: &Path,
324 lang_features: &Features) -> Features {
325 let mut lib_features = Features::new();
326 map_lib_features(base_src_path,
327 &mut |res, file, line| {
330 let mut check_features = |f: &Feature, list: &Features, display: &str| {
331 if let Some(ref s) = list.get(name) {
332 if f.tracking_issue != s.tracking_issue {
334 "{}:{}: mismatches the `issue` in {}",
341 check_features(&f, &lang_features, "corresponding lang feature");
342 check_features(&f, &lib_features, "previous");
343 lib_features.insert(name.to_owned(), f);
346 tidy_error!(bad, "{}:{}: {}", file.display(), line, msg);
354 fn map_lib_features(base_src_path: &Path,
355 mf: &mut dyn FnMut(Result<(&str, Feature), &str>, &Path, usize)) {
356 let mut contents = String::new();
357 super::walk(base_src_path,
358 &mut |path| super::filter_dirs(path) || path.ends_with("src/test"),
360 let filename = file.file_name().unwrap().to_string_lossy();
361 if !filename.ends_with(".rs") || filename == "features.rs" ||
362 filename == "diagnostic_list.rs" {
366 contents.truncate(0);
367 t!(t!(File::open(&file), &file).read_to_string(&mut contents));
369 let mut becoming_feature: Option<(String, Feature)> = None;
370 for (i, line) in contents.lines().enumerate() {
373 mf(Err($msg), file, i + 1);
377 if let Some((ref name, ref mut f)) = becoming_feature {
378 if f.tracking_issue.is_none() {
379 f.tracking_issue = find_attr_val(line, "issue")
380 .map(|s| s.parse().unwrap());
382 if line.ends_with(']') {
383 mf(Ok((name, f.clone())), file, i + 1);
384 } else if !line.ends_with(',') && !line.ends_with('\\') {
385 // We need to bail here because we might have missed the
386 // end of a stability attribute above because the ']'
387 // might not have been at the end of the line.
388 // We could then get into the very unfortunate situation that
389 // we continue parsing the file assuming the current stability
390 // attribute has not ended, and ignoring possible feature
391 // attributes in the process.
392 err!("malformed stability attribute");
397 becoming_feature = None;
398 if line.contains("rustc_const_unstable(") {
399 // `const fn` features are handled specially.
400 let feature_name = match find_attr_val(line, "feature") {
402 None => err!("malformed stability attribute"),
404 let feature = Feature {
405 level: Status::Unstable,
407 has_gate_test: false,
408 // FIXME(#57563): #57563 is now used as a common tracking issue,
409 // although we would like to have specific tracking issues for each
410 // `rustc_const_unstable` in the future.
411 tracking_issue: Some(57563),
414 mf(Ok((feature_name, feature)), file, i + 1);
417 let level = if line.contains("[unstable(") {
419 } else if line.contains("[stable(") {
424 let feature_name = match find_attr_val(line, "feature") {
426 None => err!("malformed stability attribute"),
428 let since = match find_attr_val(line, "since").map(|x| x.parse()) {
429 Some(Ok(since)) => Some(since),
431 err!("malformed since attribute");
433 None if level == Status::Stable => {
434 err!("malformed stability attribute");
438 let tracking_issue = find_attr_val(line, "issue").map(|s| s.parse().unwrap());
440 let feature = Feature {
443 has_gate_test: false,
447 if line.contains(']') {
448 mf(Ok((feature_name, feature)), file, i + 1);
450 becoming_feature = Some((feature_name.to_owned(), feature));