]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/pal.rs
Ignore PAL lint for std::panicking
[rust.git] / src / tools / tidy / src / pal.rs
1 //! Tidy check to enforce rules about platform-specific code in std.
2 //!
3 //! This is intended to maintain existing standards of code
4 //! organization in hopes that the standard library will continue to
5 //! be refactored to isolate platform-specific bits, making porting
6 //! easier; where "standard library" roughly means "all the
7 //! dependencies of the std and test crates".
8 //!
9 //! This generally means placing restrictions on where `cfg(unix)`,
10 //! `cfg(windows)`, `cfg(target_os)` and `cfg(target_env)` may appear,
11 //! the basic objective being to isolate platform-specific code to the
12 //! platform-specific `std::sys` modules, and to the allocation,
13 //! unwinding, and libc crates.
14 //!
15 //! Following are the basic rules, though there are currently
16 //! exceptions:
17 //!
18 //! - core may not have platform-specific code.
19 //! - libpanic_abort may have platform-specific code.
20 //! - libpanic_unwind may have platform-specific code.
21 //! - libunwind may have platform-specific code.
22 //! - other crates in the std facade may not.
23 //! - std may have platform-specific code in the following places:
24 //!   - `sys/unix/`
25 //!   - `sys/windows/`
26 //!   - `os/`
27 //!
28 //! `std/sys_common` should _not_ contain platform-specific code.
29 //! Finally, because std contains tests with platform-specific
30 //! `ignore` attributes, once the parser encounters `mod tests`,
31 //! platform-specific cfgs are allowed. Not sure yet how to deal with
32 //! this in the long term.
33
34 use std::iter::Iterator;
35 use std::path::Path;
36
37 // Paths that may contain platform-specific code.
38 const EXCEPTION_PATHS: &[&str] = &[
39     // std crates
40     "src/libpanic_abort",
41     "src/libpanic_unwind",
42     "src/libunwind",
43     // black_box implementation is LLVM-version specific and it uses
44     // target_os to tell targets with different LLVM-versions appart
45     // (e.g. `wasm32-unknown-emscripten` vs `wasm32-unknown-unknown`):
46     "src/libcore/hint.rs",
47     "src/libstd/sys/", // Platform-specific code for std lives here.
48     // This has the trailing slash so that sys_common is not excepted.
49     "src/libstd/os", // Platform-specific public interfaces
50     "src/rtstartup", // Not sure what to do about this. magic stuff for mingw
51     // temporary exceptions
52     "src/libstd/lib.rs",
53     "src/libstd/path.rs",
54     "src/libstd/f32.rs",
55     "src/libstd/f64.rs",
56     // Integration test for platform-specific run-time feature detection:
57     "src/libstd/tests/run-time-detect.rs",
58     "src/libstd/net/test.rs",
59     "src/libstd/sys_common/mod.rs",
60     "src/libstd/sys_common/net.rs",
61     "src/libstd/sys_common/backtrace.rs",
62     // panic_unwind shims
63     "src/libstd/panicking.rs",
64     "src/libterm", // Not sure how to make this crate portable, but test crate needs it.
65     "src/libtest", // Probably should defer to unstable `std::sys` APIs.
66     "src/libstd/sync/mpsc", // some tests are only run on non-emscripten
67     // std testing crates, okay for now at least
68     "src/libcore/tests",
69     "src/liballoc/tests/lib.rs",
70     // The `VaList` implementation must have platform specific code.
71     // The Windows implementation of a `va_list` is always a character
72     // pointer regardless of the target architecture. As a result,
73     // we must use `#[cfg(windows)]` to conditionally compile the
74     // correct `VaList` structure for windows.
75     "src/libcore/ffi.rs",
76     // non-std crates
77     "src/test",
78     "src/tools",
79     "src/librustc",
80     "src/librustdoc",
81     "src/librustc_ast",
82     "src/bootstrap",
83 ];
84
85 pub fn check(path: &Path, bad: &mut bool) {
86     // Sanity check that the complex parsing here works.
87     let mut saw_target_arch = false;
88     let mut saw_cfg_bang = false;
89     super::walk(path, &mut super::filter_dirs, &mut |entry, contents| {
90         let file = entry.path();
91         let filestr = file.to_string_lossy().replace("\\", "/");
92         if !filestr.ends_with(".rs") {
93             return;
94         }
95
96         let is_exception_path = EXCEPTION_PATHS.iter().any(|s| filestr.contains(&**s));
97         if is_exception_path {
98             return;
99         }
100
101         check_cfgs(contents, &file, bad, &mut saw_target_arch, &mut saw_cfg_bang);
102     });
103
104     assert!(saw_target_arch);
105     assert!(saw_cfg_bang);
106 }
107
108 fn check_cfgs(
109     contents: &str,
110     file: &Path,
111     bad: &mut bool,
112     saw_target_arch: &mut bool,
113     saw_cfg_bang: &mut bool,
114 ) {
115     // For now it's ok to have platform-specific code after 'mod tests'.
116     let mod_tests_idx = find_test_mod(contents);
117     let contents = &contents[..mod_tests_idx];
118     // Pull out all `cfg(...)` and `cfg!(...)` strings.
119     let cfgs = parse_cfgs(contents);
120
121     let mut line_numbers: Option<Vec<usize>> = None;
122     let mut err = |idx: usize, cfg: &str| {
123         if line_numbers.is_none() {
124             line_numbers = Some(contents.match_indices('\n').map(|(i, _)| i).collect());
125         }
126         let line_numbers = line_numbers.as_ref().expect("");
127         let line = match line_numbers.binary_search(&idx) {
128             Ok(_) => unreachable!(),
129             Err(i) => i + 1,
130         };
131         tidy_error!(bad, "{}:{}: platform-specific cfg: {}", file.display(), line, cfg);
132     };
133
134     for (idx, cfg) in cfgs {
135         // Sanity check that the parsing here works.
136         if !*saw_target_arch && cfg.contains("target_arch") {
137             *saw_target_arch = true
138         }
139         if !*saw_cfg_bang && cfg.contains("cfg!") {
140             *saw_cfg_bang = true
141         }
142
143         let contains_platform_specific_cfg = cfg.contains("target_os")
144             || cfg.contains("target_env")
145             || cfg.contains("target_vendor")
146             || cfg.contains("unix")
147             || cfg.contains("windows");
148
149         if !contains_platform_specific_cfg {
150             continue;
151         }
152
153         let preceeded_by_doc_comment = {
154             let pre_contents = &contents[..idx];
155             let pre_newline = pre_contents.rfind('\n');
156             let pre_doc_comment = pre_contents.rfind("///");
157             match (pre_newline, pre_doc_comment) {
158                 (Some(n), Some(c)) => n < c,
159                 (None, Some(_)) => true,
160                 (_, None) => false,
161             }
162         };
163
164         if preceeded_by_doc_comment {
165             continue;
166         }
167
168         err(idx, cfg);
169     }
170 }
171
172 fn find_test_mod(contents: &str) -> usize {
173     if let Some(mod_tests_idx) = contents.find("mod tests") {
174         // Also capture a previous line indicating that "mod tests" is cfg'd out.
175         let prev_newline_idx = contents[..mod_tests_idx].rfind('\n').unwrap_or(mod_tests_idx);
176         let prev_newline_idx = contents[..prev_newline_idx].rfind('\n');
177         if let Some(nl) = prev_newline_idx {
178             let prev_line = &contents[nl + 1..mod_tests_idx];
179             if prev_line.contains("cfg(all(test, not(target_os")
180                 || prev_line.contains("cfg(all(test, not(any(target_os")
181             {
182                 nl
183             } else {
184                 mod_tests_idx
185             }
186         } else {
187             mod_tests_idx
188         }
189     } else {
190         contents.len()
191     }
192 }
193
194 fn parse_cfgs<'a>(contents: &'a str) -> Vec<(usize, &'a str)> {
195     let candidate_cfgs = contents.match_indices("cfg");
196     let candidate_cfg_idxs = candidate_cfgs.map(|(i, _)| i);
197     // This is puling out the indexes of all "cfg" strings
198     // that appear to be tokens followed by a parenthesis.
199     let cfgs = candidate_cfg_idxs.filter(|i| {
200         let pre_idx = i.saturating_sub(*i);
201         let succeeds_non_ident = !contents
202             .as_bytes()
203             .get(pre_idx)
204             .cloned()
205             .map(char::from)
206             .map(char::is_alphanumeric)
207             .unwrap_or(false);
208         let contents_after = &contents[*i..];
209         let first_paren = contents_after.find('(');
210         let paren_idx = first_paren.map(|ip| i + ip);
211         let preceeds_whitespace_and_paren = paren_idx
212             .map(|ip| {
213                 let maybe_space = &contents[*i + "cfg".len()..ip];
214                 maybe_space.chars().all(|c| char::is_whitespace(c) || c == '!')
215             })
216             .unwrap_or(false);
217
218         succeeds_non_ident && preceeds_whitespace_and_paren
219     });
220
221     cfgs.flat_map(|i| {
222         let mut depth = 0;
223         let contents_from = &contents[i..];
224         for (j, byte) in contents_from.bytes().enumerate() {
225             match byte {
226                 b'(' => {
227                     depth += 1;
228                 }
229                 b')' => {
230                     depth -= 1;
231                     if depth == 0 {
232                         return Some((i, &contents_from[..=j]));
233                     }
234                 }
235                 _ => {}
236             }
237         }
238
239         // if the parentheses are unbalanced just ignore this cfg -- it'll be caught when attempting
240         // to run the compiler, and there's no real reason to lint it separately here
241         None
242     })
243     .collect()
244 }