Skip to main content

rust_analyzer/cli/
rustc_tests.rs

1//! Run all tests in a project, similar to `cargo test`, but using the mir interpreter.
2
3use std::convert::identity;
4use std::thread::Builder;
5use std::time::{Duration, Instant};
6use std::{cell::RefCell, fs::read_to_string, panic::AssertUnwindSafe, path::PathBuf};
7
8use hir::{ChangeWithProcMacros, Crate};
9use ide::{AnalysisHost, DiagnosticCode, DiagnosticsConfig};
10use ide_db::base_db;
11use itertools::Either;
12use profile::StopWatch;
13use project_model::toolchain_info::{QueryConfig, target_data, version};
14use project_model::{
15    CargoConfig, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, RustLibSource,
16    RustSourceWorkspaceConfig, Sysroot,
17};
18
19use load_cargo::{LoadCargoConfig, ProcMacroServerChoice, load_workspace};
20use rustc_hash::FxHashMap;
21use vfs::{AbsPathBuf, FileId};
22use walkdir::WalkDir;
23
24use crate::cli::{Result, flags, report_metric};
25
26struct Tester {
27    host: AnalysisHost,
28    root_file: FileId,
29    pass_count: u64,
30    ignore_count: u64,
31    fail_count: u64,
32    stopwatch: StopWatch,
33}
34
35fn string_to_diagnostic_code_leaky(code: &str) -> DiagnosticCode {
36    thread_local! {
37        static LEAK_STORE: RefCell<FxHashMap<String, DiagnosticCode>> = RefCell::new(FxHashMap::default());
38    }
39    LEAK_STORE.with_borrow_mut(|s| match s.get(code) {
40        Some(c) => *c,
41        None => {
42            let v = DiagnosticCode::RustcHardError(format!("E{code}").leak());
43            s.insert(code.to_owned(), v);
44            v
45        }
46    })
47}
48
49fn detect_errors_from_rustc_stderr_file(p: PathBuf) -> FxHashMap<DiagnosticCode, usize> {
50    let text = read_to_string(p).unwrap();
51    let mut result = FxHashMap::default();
52    {
53        let mut text = &*text;
54        while let Some(p) = text.find("error[E") {
55            text = &text[p + 7..];
56            let code = string_to_diagnostic_code_leaky(&text[..4]);
57            *result.entry(code).or_insert(0) += 1;
58        }
59    }
60    result
61}
62
63impl Tester {
64    fn new() -> Result<Self> {
65        let mut path = AbsPathBuf::assert_utf8(std::env::temp_dir());
66        path.push("ra-rustc-test");
67        std::fs::create_dir_all(&path)?;
68        let tmp_file = path.join("ra-rustc-test.rs");
69        std::fs::write(&tmp_file, "")?;
70        let cargo_config = CargoConfig {
71            sysroot: Some(RustLibSource::Discover),
72            all_targets: true,
73            set_test: true,
74            ..Default::default()
75        };
76
77        let mut sysroot = Sysroot::discover(tmp_file.parent().unwrap(), &cargo_config.extra_env);
78        let loaded_sysroot =
79            sysroot.load_workspace(&RustSourceWorkspaceConfig::default_cargo(), false, &|_| ());
80        if let Some(loaded_sysroot) = loaded_sysroot {
81            sysroot.set_workspace(loaded_sysroot);
82        }
83
84        let query_config = QueryConfig::Rustc(&sysroot, tmp_file.parent().unwrap().as_ref());
85        let toolchain_version = version::get(query_config, &cargo_config.extra_env).ok().flatten();
86        let target_data = target_data::get(
87            query_config,
88            None,
89            &cargo_config.extra_env,
90            toolchain_version.as_ref(),
91        );
92
93        let workspace = ProjectWorkspace {
94            kind: ProjectWorkspaceKind::DetachedFile {
95                file: ManifestPath::try_from(tmp_file).unwrap(),
96                cargo: None,
97            },
98            sysroot,
99            rustc_cfg: vec![],
100            toolchain: None,
101            target: target_data.map_err(|it| it.to_string().into()),
102            cfg_overrides: Default::default(),
103            extra_includes: vec![],
104            set_test: true,
105        };
106        let load_cargo_config = LoadCargoConfig {
107            load_out_dirs_from_check: false,
108            with_proc_macro_server: ProcMacroServerChoice::Sysroot,
109            prefill_caches: false,
110            num_worker_threads: 1,
111            proc_macro_processes: 1,
112        };
113        let (db, _vfs, _proc_macro) =
114            load_workspace(workspace, &cargo_config.extra_env, &load_cargo_config)?;
115        let host = AnalysisHost::with_database(db);
116        let db = host.raw_database();
117        let krates = Crate::all(db);
118        let root_crate = krates.iter().cloned().find(|krate| krate.origin(db).is_local()).unwrap();
119        let root_file = root_crate.root_file(db);
120        Ok(Self {
121            host,
122            root_file,
123            pass_count: 0,
124            ignore_count: 0,
125            fail_count: 0,
126            stopwatch: StopWatch::start(),
127        })
128    }
129
130    fn test(&mut self, p: PathBuf) {
131        println!("{}", p.display());
132        if p.parent().unwrap().file_name().unwrap() == "auxiliary" {
133            // These are not tests
134            return;
135        }
136        if IGNORED_TESTS.iter().any(|ig| p.file_name().is_some_and(|x| x == *ig)) {
137            println!("{p:?} IGNORE");
138            self.ignore_count += 1;
139            return;
140        }
141        let stderr_path = p.with_extension("stderr");
142        let expected = if stderr_path.exists() {
143            detect_errors_from_rustc_stderr_file(stderr_path)
144        } else {
145            FxHashMap::default()
146        };
147        let text = read_to_string(&p).unwrap();
148        let mut change = ChangeWithProcMacros::default();
149        // Ignore unstable tests, since they move too fast and we do not intend to support all of them.
150        let mut ignore_test = text.contains("#![feature");
151        // Ignore test with extern crates, as this infra don't support them yet.
152        ignore_test |= text.contains("// aux-build:") || text.contains("// aux-crate:");
153        // Ignore test with extern modules similarly.
154        ignore_test |= text.contains("mod ");
155        // These should work, but they don't, and I don't know why, so ignore them.
156        ignore_test |= text.contains("extern crate proc_macro");
157        let should_have_no_error = text.contains("// check-pass")
158            || text.contains("// build-pass")
159            || text.contains("// run-pass");
160        change.change_file(self.root_file, Some(text));
161        self.host.apply_change(change);
162        let diagnostic_config = DiagnosticsConfig::test_sample();
163
164        let res = std::thread::scope(|s| {
165            let worker = Builder::new()
166                .stack_size(40 * 1024 * 1024)
167                .spawn_scoped(s, {
168                    let diagnostic_config = &diagnostic_config;
169                    let main = std::thread::current();
170                    let analysis = self.host.analysis();
171                    let root_file = self.root_file;
172                    move || {
173                        let res = std::panic::catch_unwind(AssertUnwindSafe(move || {
174                            analysis.full_diagnostics(
175                                diagnostic_config,
176                                ide::AssistResolveStrategy::None,
177                                root_file,
178                            )
179                        }));
180                        main.unpark();
181                        res
182                    }
183                })
184                .unwrap();
185
186            let timeout = Duration::from_secs(5);
187            let now = Instant::now();
188            while now.elapsed() <= timeout && !worker.is_finished() {
189                std::thread::park_timeout(timeout - now.elapsed());
190            }
191
192            if !worker.is_finished() {
193                // attempt to cancel the worker, won't work for chalk hangs unfortunately
194                self.host.trigger_garbage_collection();
195            }
196            worker.join().and_then(identity)
197        });
198        let mut actual = FxHashMap::default();
199        let panicked = match res {
200            Err(e) => Some(Either::Left(e)),
201            Ok(Ok(diags)) => {
202                for diag in diags {
203                    if !matches!(diag.code, DiagnosticCode::RustcHardError(_)) {
204                        continue;
205                    }
206                    if !should_have_no_error && !SUPPORTED_DIAGNOSTICS.contains(&diag.code) {
207                        continue;
208                    }
209                    *actual.entry(diag.code).or_insert(0) += 1;
210                }
211                None
212            }
213            Ok(Err(e)) => Some(Either::Right(e)),
214        };
215        // Ignore tests with diagnostics that we don't emit.
216        ignore_test |= expected.keys().any(|k| !SUPPORTED_DIAGNOSTICS.contains(k));
217        if ignore_test {
218            println!("{p:?} IGNORE");
219            self.ignore_count += 1;
220        } else if let Some(panic) = panicked {
221            match panic {
222                Either::Left(panic) => {
223                    if let Some(msg) = panic
224                        .downcast_ref::<String>()
225                        .map(String::as_str)
226                        .or_else(|| panic.downcast_ref::<&str>().copied())
227                    {
228                        println!("{msg:?} ")
229                    }
230                    println!("{p:?} PANIC");
231                }
232                Either::Right(_) => println!("{p:?} CANCELLED"),
233            }
234            self.fail_count += 1;
235        } else if actual == expected {
236            println!("{p:?} PASS");
237            self.pass_count += 1;
238        } else {
239            println!("{p:?} FAIL");
240            println!("actual   (r-a)   = {actual:?}");
241            println!("expected (rustc) = {expected:?}");
242            self.fail_count += 1;
243        }
244    }
245
246    fn report(&mut self) {
247        println!(
248            "Pass count = {}, Fail count = {}, Ignore count = {}",
249            self.pass_count, self.fail_count, self.ignore_count
250        );
251        println!("Testing time and memory = {}", self.stopwatch.elapsed());
252        report_metric("rustc failed tests", self.fail_count, "#");
253        report_metric("rustc testing time", self.stopwatch.elapsed().time.as_millis() as u64, "ms");
254    }
255}
256
257/// These tests break rust-analyzer (either by panicking or hanging) so we should ignore them.
258const IGNORED_TESTS: &[&str] = &[
259    "trait-with-missing-associated-type-restriction.rs", // #15646
260    "trait-with-missing-associated-type-restriction-fixable.rs", // #15646
261    "resolve-self-in-impl.rs",
262    "basic.rs", // ../rust/tests/ui/associated-type-bounds/return-type-notation/basic.rs
263    "issue-26056.rs",
264    "float-field.rs",
265    "invalid_operator_trait.rs",
266    "type-alias-impl-trait-assoc-dyn.rs",
267    "deeply-nested_closures.rs",    // exponential time
268    "hang-on-deeply-nested-dyn.rs", // exponential time
269    "dyn-rpit-and-let.rs", // unexpected free variable with depth `^1.0` with outer binder ^0
270    "issue-16098.rs",      // Huge recursion limit for macros?
271    "issue-83471.rs", // crates/hir-ty/src/builder.rs:78:9: assertion failed: self.remaining() > 0
272];
273
274const SUPPORTED_DIAGNOSTICS: &[DiagnosticCode] = &[
275    DiagnosticCode::RustcHardError("E0023"),
276    DiagnosticCode::RustcHardError("E0046"),
277    DiagnosticCode::RustcHardError("E0063"),
278    DiagnosticCode::RustcHardError("E0107"),
279    DiagnosticCode::RustcHardError("E0117"),
280    DiagnosticCode::RustcHardError("E0133"),
281    DiagnosticCode::RustcHardError("E0210"),
282    DiagnosticCode::RustcHardError("E0268"),
283    DiagnosticCode::RustcHardError("E0308"),
284    DiagnosticCode::RustcHardError("E0384"),
285    DiagnosticCode::RustcHardError("E0407"),
286    DiagnosticCode::RustcHardError("E0432"),
287    DiagnosticCode::RustcHardError("E0451"),
288    DiagnosticCode::RustcHardError("E0507"),
289    DiagnosticCode::RustcHardError("E0583"),
290    DiagnosticCode::RustcHardError("E0559"),
291    DiagnosticCode::RustcHardError("E0616"),
292    DiagnosticCode::RustcHardError("E0618"),
293    DiagnosticCode::RustcHardError("E0624"),
294    DiagnosticCode::RustcHardError("E0774"),
295    DiagnosticCode::RustcHardError("E0767"),
296    DiagnosticCode::RustcHardError("E0777"),
297];
298
299impl flags::RustcTests {
300    pub fn run(self) -> Result<()> {
301        let mut tester = Tester::new()?;
302        let walk_dir = WalkDir::new(self.rustc_repo.join("tests/ui"));
303        eprintln!("Running tests for tests/ui");
304        for i in walk_dir {
305            let i = i?;
306            let p = i.into_path();
307            if let Some(f) = &self.filter
308                && !p.as_os_str().to_string_lossy().contains(f)
309            {
310                continue;
311            }
312            if p.extension().is_none_or(|x| x != "rs") {
313                continue;
314            }
315            if let Err(e) = std::panic::catch_unwind({
316                let tester = AssertUnwindSafe(&mut tester);
317                let p = p.clone();
318                move || {
319                    let _guard = base_db::DbPanicContext::enter(p.display().to_string());
320                    { tester }.0.test(p);
321                }
322            }) {
323                std::panic::resume_unwind(e);
324            }
325        }
326        tester.report();
327        Ok(())
328    }
329}