1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Tidy check to ensure that unstable features are all in order
13 //! This check will ensure properties like:
15 //! * All stability attributes look reasonably well formed
16 //! * The set of library features is disjoint from the set of language features
17 //! * Library features have at most one stability level
18 //! * Library features have at most one `since` value
19 //! * All unstable lang features have tests to ensure they are actually unstable
21 use std::collections::HashMap;
24 use std::io::prelude::*;
27 #[derive(Debug, PartialEq, Clone)]
34 impl fmt::Display for Status {
35 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36 let as_str = match *self {
37 Status::Stable => "stable",
38 Status::Unstable => "unstable",
39 Status::Removed => "removed",
41 fmt::Display::fmt(as_str, f)
45 #[derive(Debug, Clone)]
49 pub has_gate_test: bool,
50 pub tracking_issue: Option<u32>,
54 fn check_match(&self, other: &Feature)-> Result<(), Vec<&'static str>> {
55 let mut mismatches = Vec::new();
56 if self.level != other.level {
57 mismatches.push("stability level");
59 if self.level == Status::Stable || other.level == Status::Stable {
60 // As long as a feature is unstable, the since field tracks
61 // when the given part of the feature has been implemented.
62 // Mismatches are tolerable as features evolve and functionality
64 // Once a feature is stable, the since field tracks the first version
65 // it was part of the stable distribution, and mismatches are disallowed.
66 if self.since != other.since {
67 mismatches.push("since");
70 if self.tracking_issue != other.tracking_issue {
71 mismatches.push("tracking issue");
73 if mismatches.is_empty() {
81 pub type Features = HashMap<String, Feature>;
83 pub fn check(path: &Path, bad: &mut bool, quiet: bool) {
84 let mut features = collect_lang_features(path);
85 assert!(!features.is_empty());
87 let lib_features = get_and_check_lib_features(path, bad, &features);
88 assert!(!lib_features.is_empty());
90 let mut contents = String::new();
92 super::walk_many(&[&path.join("test/compile-fail"),
93 &path.join("test/compile-fail-fulldeps"),
94 &path.join("test/parse-fail"),],
95 &mut |path| super::filter_dirs(path),
97 let filename = file.file_name().unwrap().to_string_lossy();
98 if !filename.ends_with(".rs") || filename == "features.rs" ||
99 filename == "diagnostic_list.rs" {
103 let filen_underscore = filename.replace("-","_").replace(".rs","");
104 let filename_is_gate_test = test_filen_gate(&filen_underscore, &mut features);
106 contents.truncate(0);
107 t!(t!(File::open(&file), &file).read_to_string(&mut contents));
109 for (i, line) in contents.lines().enumerate() {
110 let mut err = |msg: &str| {
111 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
114 let gate_test_str = "gate-test-";
116 if !line.contains(gate_test_str) {
120 let feature_name = match line.find(gate_test_str) {
122 &line[i+gate_test_str.len()..line[i+1..].find(' ').unwrap_or(line.len())]
126 match features.get_mut(feature_name) {
128 if filename_is_gate_test {
129 err(&format!("The file is already marked as gate test \
130 through its name, no need for a \
131 'gate-test-{}' comment",
134 f.has_gate_test = true;
137 err(&format!("gate-test test found referencing a nonexistent feature '{}'",
144 // Only check the number of lang features.
145 // Obligatory testing for library features is dumb.
146 let gate_untested = features.iter()
147 .filter(|&(_, f)| f.level == Status::Unstable)
148 .filter(|&(_, f)| !f.has_gate_test)
149 .collect::<Vec<_>>();
151 for &(name, _) in gate_untested.iter() {
152 println!("Expected a gate test for the feature '{}'.", name);
153 println!("Hint: create a file named 'feature-gate-{}.rs' in the compile-fail\
154 \n test suite, with its failures due to missing usage of\
155 \n #![feature({})].", name, name);
156 println!("Hint: If you already have such a test and don't want to rename it,\
157 \n you can also add a // gate-test-{} line to the test file.",
161 if gate_untested.len() > 0 {
162 tidy_error!(bad, "Found {} features without a gate test.", gate_untested.len());
169 println!("* {} features", features.len());
173 let mut lines = Vec::new();
174 for (name, feature) in features.iter() {
175 lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
181 for (name, feature) in lib_features {
182 lines.push(format!("{:<32} {:<8} {:<12} {:<8}",
191 println!("* {}", line);
195 fn find_attr_val<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
197 .and_then(|i| line[i..].find('"').map(|j| i + j + 1))
198 .and_then(|i| line[i..].find('"').map(|j| (i, i + j)))
199 .map(|(i, j)| &line[i..j])
202 fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool {
203 if filen_underscore.starts_with("feature_gate") {
204 for (n, f) in features.iter_mut() {
205 if filen_underscore == format!("feature_gate_{}", n) {
206 f.has_gate_test = true;
214 pub fn collect_lang_features(base_src_path: &Path) -> Features {
215 let mut contents = String::new();
216 let path = base_src_path.join("libsyntax/feature_gate.rs");
217 t!(t!(File::open(path)).read_to_string(&mut contents));
221 let mut parts = line.trim().split(",");
222 let level = match parts.next().map(|l| l.trim().trim_left_matches('(')) {
223 Some("active") => Status::Unstable,
224 Some("removed") => Status::Removed,
225 Some("accepted") => Status::Stable,
228 let name = parts.next().unwrap().trim();
229 let since = parts.next().unwrap().trim().trim_matches('"');
230 let issue_str = parts.next().unwrap().trim();
231 let tracking_issue = if issue_str.starts_with("None") {
234 let s = issue_str.split("(").nth(1).unwrap().split(")").nth(0).unwrap();
235 Some(s.parse().unwrap())
237 Some((name.to_owned(),
240 since: since.to_owned(),
241 has_gate_test: false,
248 pub fn collect_lib_features(base_src_path: &Path) -> Features {
249 let mut lib_features = Features::new();
251 // This library feature is defined in the `compiler_builtins` crate, which
252 // has been moved out-of-tree. Now it can no longer be auto-discovered by
253 // `tidy`, because we need to filter out its (submodule) directory. Manually
254 // add it to the set of known library features so we can still generate docs.
255 lib_features.insert("compiler_builtins_lib".to_owned(), Feature {
256 level: Status::Unstable,
257 since: "".to_owned(),
258 has_gate_test: false,
259 tracking_issue: None,
262 map_lib_features(base_src_path,
265 Ok((name, feature)) => {
266 if lib_features.get(name).is_some() {
269 lib_features.insert(name.to_owned(), feature);
277 fn get_and_check_lib_features(base_src_path: &Path,
279 lang_features: &Features) -> Features {
280 let mut lib_features = Features::new();
281 map_lib_features(base_src_path,
282 &mut |res, file, line| {
285 let mut check_features = |f: &Feature, list: &Features, display: &str| {
286 if let Some(ref s) = list.get(name) {
287 if let Err(m) = (&f).check_match(s) {
289 "{}:{}: mismatches to {} in: {:?}",
297 check_features(&f, &lang_features, "corresponding lang feature");
298 check_features(&f, &lib_features, "previous");
299 lib_features.insert(name.to_owned(), f);
302 tidy_error!(bad, "{}:{}: {}", file.display(), line, msg);
310 fn map_lib_features(base_src_path: &Path,
311 mf: &mut FnMut(Result<(&str, Feature), &str>, &Path, usize)) {
312 let mut contents = String::new();
313 super::walk(base_src_path,
314 &mut |path| super::filter_dirs(path) || path.ends_with("src/test"),
316 let filename = file.file_name().unwrap().to_string_lossy();
317 if !filename.ends_with(".rs") || filename == "features.rs" ||
318 filename == "diagnostic_list.rs" {
322 contents.truncate(0);
323 t!(t!(File::open(&file), &file).read_to_string(&mut contents));
325 let mut becoming_feature: Option<(String, Feature)> = None;
326 for (i, line) in contents.lines().enumerate() {
329 mf(Err($msg), file, i + 1);
333 if let Some((ref name, ref mut f)) = becoming_feature {
334 if f.tracking_issue.is_none() {
335 f.tracking_issue = find_attr_val(line, "issue")
336 .map(|s| s.parse().unwrap());
338 if line.ends_with("]") {
339 mf(Ok((name, f.clone())), file, i + 1);
340 } else if !line.ends_with(",") && !line.ends_with("\\") {
341 // We need to bail here because we might have missed the
342 // end of a stability attribute above because the "]"
343 // might not have been at the end of the line.
344 // We could then get into the very unfortunate situation that
345 // we continue parsing the file assuming the current stability
346 // attribute has not ended, and ignoring possible feature
347 // attributes in the process.
348 err!("malformed stability attribute");
353 becoming_feature = None;
354 if line.contains("rustc_const_unstable(") {
355 // const fn features are handled specially
356 let feature_name = match find_attr_val(line, "feature") {
358 None => err!("malformed stability attribute"),
360 let feature = Feature {
361 level: Status::Unstable,
362 since: "None".to_owned(),
363 has_gate_test: false,
364 // Whether there is a common tracking issue
365 // for these feature gates remains an open question
366 // https://github.com/rust-lang/rust/issues/24111#issuecomment-340283184
367 // But we take 24111 otherwise they will be shown as
368 // "internal to the compiler" which they are not.
369 tracking_issue: Some(24111),
371 mf(Ok((feature_name, feature)), file, i + 1);
374 let level = if line.contains("[unstable(") {
376 } else if line.contains("[stable(") {
381 let feature_name = match find_attr_val(line, "feature") {
383 None => err!("malformed stability attribute"),
385 let since = match find_attr_val(line, "since") {
387 None if level == Status::Stable => {
388 err!("malformed stability attribute");
392 let tracking_issue = find_attr_val(line, "issue").map(|s| s.parse().unwrap());
394 let feature = Feature {
396 since: since.to_owned(),
397 has_gate_test: false,
400 if line.contains("]") {
401 mf(Ok((feature_name, feature)), file, i + 1);
403 becoming_feature = Some((feature_name.to_owned(), feature));