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 map_lib_features(base_src_path
, &mut |res
, _
, _
| {
67 if let Ok((name
, feature
)) = res
{
68 lib_features
.insert(name
.to_owned(), feature
);
80 ) -> CollectedFeatures
{
81 let mut features
= collect_lang_features(compiler_path
, bad
);
82 assert
!(!features
.is_empty());
84 let lib_features
= get_and_check_lib_features(lib_path
, bad
, &features
);
85 assert
!(!lib_features
.is_empty());
89 &src_path
.join("test/ui"),
90 &src_path
.join("test/ui-fulldeps"),
91 &src_path
.join("test/compile-fail"),
93 &mut |path
| super::filter_dirs(path
),
94 &mut |entry
, contents
| {
95 let file
= entry
.path();
96 let filename
= file
.file_name().unwrap().to_string_lossy();
97 if !filename
.ends_with(".rs")
98 || filename
== "features.rs"
99 || filename
== "diagnostic_list.rs"
104 let filen_underscore
= filename
.replace('
-'
, "_").replace(".rs", "");
105 let filename_is_gate_test
= test_filen_gate(&filen_underscore
, &mut features
);
107 for (i
, line
) in contents
.lines().enumerate() {
108 let mut err
= |msg
: &str| {
109 tidy_error
!(bad
, "{}:{}: {}", file
.display(), i
+ 1, msg
);
112 let gate_test_str
= "gate-test-";
114 let feature_name
= match line
.find(gate_test_str
) {
115 Some(i
) => line
[i
+ gate_test_str
.len()..].splitn(2, ' '
).next().unwrap(),
118 match features
.get_mut(feature_name
) {
120 if filename_is_gate_test
{
122 "The file is already marked as gate test \
123 through its name, no need for a \
124 'gate-test-{}' comment",
128 f
.has_gate_test
= true;
132 "gate-test test found referencing a nonexistent feature '{}'",
141 // Only check the number of lang features.
142 // Obligatory testing for library features is dumb.
143 let gate_untested
= features
145 .filter(|&(_
, f
)| f
.level
== Status
::Unstable
)
146 .filter(|&(_
, f
)| !f
.has_gate_test
)
147 .collect
::<Vec
<_
>>();
149 for &(name
, _
) in gate_untested
.iter() {
150 println
!("Expected a gate test for the feature '{}'.", name
);
152 "Hint: create a failing test file named 'feature-gate-{}.rs'\
153 \n in the 'ui' test suite, with its failures due to\
154 \n missing usage of `#![feature({})]`.",
158 "Hint: If you already have such a test and don't want to rename it,\
159 \n you can also add a // gate-test-{} line to the test file.",
164 if !gate_untested
.is_empty() {
165 tidy_error
!(bad
, "Found {} features without a gate test.", gate_untested
.len());
169 return CollectedFeatures { lib: lib_features, lang: features }
;
173 let mut lines
= Vec
::new();
174 lines
.extend(format_features(&features
, "lang"));
175 lines
.extend(format_features(&lib_features
, "lib"));
179 println
!("* {}", line
);
182 println
!("* {} features", features
.len());
185 CollectedFeatures { lib: lib_features, lang: features }
188 fn format_features
<'a
>(
189 features
: &'a Features
,
191 ) -> impl Iterator
<Item
= String
> + 'a
{
192 features
.iter().map(move |(name
, feature
)| {
194 "{:<32} {:<8} {:<12} {:<8}",
198 feature
.since
.map_or("None".to_owned(), |since
| since
.to_string())
203 fn find_attr_val
<'a
>(line
: &'a
str, attr
: &str) -> Option
<&'a
str> {
204 lazy_static
::lazy_static
! {
205 static ref ISSUE
: Regex
= Regex
::new(r
#"issue\s*=\s*"([^"]*)""#).unwrap();
206 static ref FEATURE: Regex = Regex::new(r#"feature\s*=\s*"([^"]*)""#).unwrap();
207 static ref SINCE
: Regex
= Regex
::new(r
#"since\s*=\s*"([^"]*)""#).unwrap();
212 "feature" => &*FEATURE,
214 _ => unimplemented!("{} not handled", attr),
217 r.captures(line).and_then(|c| c.get(1)).map(|m| m.as_str())
220 fn test_filen_gate(filen_underscore: &str, features: &mut Features) -> bool {
221 let prefix = "feature_gate_";
222 if filen_underscore.starts_with(prefix) {
223 for (n, f) in features.iter_mut() {
224 // Equivalent to filen_underscore == format!("feature_gate_{}", n)
225 if &filen_underscore[prefix.len()..] == n {
226 f.has_gate_test = true;
234 pub fn collect_lang_features(base_compiler_path: &Path, bad: &mut bool) -> Features {
235 let mut all = collect_lang_features_in(base_compiler_path, "active.rs", bad);
236 all.extend(collect_lang_features_in(base_compiler_path, "accepted.rs", bad));
237 all.extend(collect_lang_features_in(base_compiler_path, "removed.rs", bad));
241 fn collect_lang_features_in(base: &Path, file: &str, bad: &mut bool) -> Features {
242 let path = base.join("rustc_feature").join("src").join(file);
243 let contents = t!(fs::read_to_string(&path));
245 // We allow rustc-internal features to omit a tracking issue.
246 // To make tidy accept omitting a tracking issue, group the list of features
247 // without one inside `// no-tracking-issue` and `// no-tracking-issue-end`.
248 let mut next_feature_omits_tracking_issue = false;
250 let mut in_feature_group = false;
251 let mut prev_since = None;
256 .filter_map(|(line, line_number)| {
257 let line = line.trim();
259 // Within -start and -end, the tracking issue can be omitted.
261 "// no-tracking-issue-start" => {
262 next_feature_omits_tracking_issue
= true;
265 "// no-tracking-issue-end" => {
266 next_feature_omits_tracking_issue
= false;
272 if line
.starts_with(FEATURE_GROUP_START_PREFIX
) {
273 if in_feature_group
{
277 new feature group is started without ending the previous one",
283 in_feature_group
= true;
286 } else if line
.starts_with(FEATURE_GROUP_END_PREFIX
) {
287 in_feature_group
= false;
292 let mut parts
= line
.split('
,'
);
293 let level
= match parts
.next().map(|l
| l
.trim().trim_start_matches('
('
)) {
294 Some("active") => Status
::Unstable
,
295 Some("removed") => Status
::Removed
,
296 Some("accepted") => Status
::Stable
,
299 let name
= parts
.next().unwrap().trim();
301 let since_str
= parts
.next().unwrap().trim().trim_matches('
"');
302 let since = match since_str.parse() {
303 Ok(since) => Some(since),
307 "{}
:{}
: failed to parse since
: {}
({:?}
)",
316 if in_feature_group {
317 if prev_since > since {
320 "{}
:{}
: feature {} is not sorted by
\"since
\" (version number
)",
329 let issue_str = parts.next().unwrap().trim();
330 let tracking_issue = if issue_str.starts_with("None
") {
331 if level == Status::Unstable && !next_feature_omits_tracking_issue {
335 "{}
:{}
: no tracking issue
for feature {}
",
343 let s = issue_str.split('(').nth(1).unwrap().split(')').next().unwrap();
344 Some(s.parse().unwrap())
346 Some((name.to_owned(), Feature { level, since, has_gate_test: false, tracking_issue }))
351 fn get_and_check_lib_features(
352 base_src_path: &Path,
354 lang_features: &Features,
356 let mut lib_features = Features::new();
357 map_lib_features(base_src_path, &mut |res, file, line| match res {
359 let mut check_features = |f: &Feature, list: &Features, display: &str| {
360 if let Some(ref s) = list.get(name) {
361 if f.tracking_issue != s.tracking_issue && f.level != Status::Stable {
364 "{}
:{}
: mismatches the `issue`
in {}
",
372 check_features(&f, &lang_features, "corresponding lang feature
");
373 check_features(&f, &lib_features, "previous
");
374 lib_features.insert(name.to_owned(), f);
377 tidy_error!(bad, "{}
:{}
: {}
", file.display(), line, msg);
384 base_src_path: &Path,
385 mf: &mut dyn FnMut(Result<(&str, Feature), &str>, &Path, usize),
389 &mut |path| super::filter_dirs(path) || path.ends_with("src
/test
"),
390 &mut |entry, contents| {
391 let file = entry.path();
392 let filename = file.file_name().unwrap().to_string_lossy();
393 if !filename.ends_with(".rs
")
394 || filename == "features
.rs
"
395 || filename == "diagnostic_list
.rs
"
396 || filename == "error_codes
.rs
"
401 // This is an early exit -- all the attributes we're concerned with must contain this:
402 // * rustc_const_unstable(
405 if !contents.contains("stable(") {
409 let handle_issue_none = |s| match s {
412 let n = issue.parse().expect("issue number is not a valid integer
");
413 assert_ne!(n, 0, "\"none
\" should be used when there is no issue
, not
\"0\"");
417 let mut becoming_feature: Option<(&str, Feature)> = None;
418 let mut iter_lines = contents.lines().enumerate().peekable();
419 while let Some((i, line)) = iter_lines.next() {
422 mf(Err($msg), file, i + 1);
426 if let Some((ref name, ref mut f)) = becoming_feature {
427 if f.tracking_issue.is_none() {
428 f.tracking_issue = find_attr_val(line, "issue
").and_then(handle_issue_none);
430 if line.ends_with(']') {
431 mf(Ok((name, f.clone())), file, i + 1);
432 } else if !line.ends_with(',') && !line.ends_with('\\') && !line.ends_with('"'
)
434 // We need to bail here because we might have missed the
435 // end of a stability attribute above because the ']'
436 // might not have been at the end of the line.
437 // We could then get into the very unfortunate situation that
438 // we continue parsing the file assuming the current stability
439 // attribute has not ended, and ignoring possible feature
440 // attributes in the process.
441 err
!("malformed stability attribute");
446 becoming_feature
= None
;
447 if line
.contains("rustc_const_unstable(") {
448 // `const fn` features are handled specially.
449 let feature_name
= match find_attr_val(line
, "feature") {
451 None
=> err
!("malformed stability attribute: missing `feature` key"),
453 let feature
= Feature
{
454 level
: Status
::Unstable
,
456 has_gate_test
: false,
457 tracking_issue
: find_attr_val(line
, "issue").and_then(handle_issue_none
),
459 mf(Ok((feature_name
, feature
)), file
, i
+ 1);
462 let level
= if line
.contains("[unstable(") {
464 } else if line
.contains("[stable(") {
469 let feature_name
= match find_attr_val(line
, "feature")
470 .or_else(|| iter_lines
.peek().and_then(|next
| find_attr_val(next
.1, "feature")))
473 None
=> err
!("malformed stability attribute: missing `feature` key"),
475 let since
= match find_attr_val(line
, "since").map(|x
| x
.parse()) {
476 Some(Ok(since
)) => Some(since
),
478 err
!("malformed stability attribute: can't parse `since` key");
480 None
if level
== Status
::Stable
=> {
481 err
!("malformed stability attribute: missing the `since` key");
485 let tracking_issue
= find_attr_val(line
, "issue").and_then(handle_issue_none
);
487 let feature
= Feature { level, since, has_gate_test: false, tracking_issue }
;
488 if line
.contains('
]'
) {
489 mf(Ok((feature_name
, feature
)), file
, i
+ 1);
491 becoming_feature
= Some((feature_name
, feature
));