tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

292 lignes · 10353 octetsBrut · Historique
1//! UI tests: `tests/ui/*.lse` files with inline expectations.
2//!
3//! - `//~ ERROR E0202 fragment` expects a diagnostic with that code (and a
4//! message or a note containing `fragment`, if given) whose primary span
5//! starts on this line. `//~^ ERROR ...` points one line up (`^^` two lines, ...).
6//! - `//~ WARN W0101` is the same for warnings.
7//! - `//~ TYPE name: scheme` expects the top-level item `name` to have
8//! this type, as printed in hovers.
9//!
10//! Every diagnostic must be expected, and every expectation met. The file
11//! is checked as module `main` with the real standard library, through
12//! the same pipeline as `louise check` and the language server.
13
14use std::path::{Path, PathBuf};
15
16use louise_db::Db;
17use louise_diag::Severity;
18use louise_types::Printer;
19
20struct Expectation {
21 line: u32,
22 severity: Severity,
23 code: String,
24 fragment: String,
25}
26
27fn parse_expectations(text: &str) -> (Vec<Expectation>, Vec<(String, String)>) {
28 let mut diags = Vec::new();
29 let mut types = Vec::new();
30 for (i, line) in text.lines().enumerate() {
31 let Some((_, rest)) = line.split_once("//~") else {
32 continue;
33 };
34 let carets = rest.chars().take_while(|c| *c == '^').count();
35 let rest = rest[carets..].trim();
36 if let Some(t) = rest.strip_prefix("TYPE ") {
37 let (name, ty) = t.split_once(':').expect("`//~ TYPE name: type`");
38 types.push((name.trim().to_owned(), ty.trim().to_owned()));
39 continue;
40 }
41 let (severity, rest) = if let Some(r) = rest.strip_prefix("ERROR ") {
42 (Severity::Error, r)
43 } else if let Some(r) = rest.strip_prefix("WARN ") {
44 (Severity::Warning, r)
45 } else {
46 panic!("line {}: unknown expectation `{rest}`", i + 1);
47 };
48 let (code, fragment) = rest.split_once(' ').unwrap_or((rest, ""));
49 diags.push(Expectation {
50 line: (i - carets) as u32,
51 severity,
52 code: code.to_owned(),
53 fragment: fragment.trim().to_owned(),
54 });
55 }
56 (diags, types)
57}
58
59fn run(path: &Path) -> Vec<String> {
60 let text = std::fs::read_to_string(path).unwrap();
61 let mut db = Db::new();
62 let main_file = db.add_module("main", &path.display().to_string(), text.clone());
63 let analysis = db.analyze();
64 let (hir, typeck, diags) = (&analysis.hir, &analysis.typeck, &analysis.diagnostics);
65
66 let (mut expected, types) = parse_expectations(&text);
67 let mut failures = Vec::new();
68 for d in diags {
69 let file = db.sources().get(d.primary.span.file);
70 let line = file.line_col(d.primary.span.range.start()).line;
71 if d.primary.span.file != main_file {
72 failures.push(format!(
73 "diagnostic in {}:{}: [{}] {}",
74 file.path(),
75 line + 1,
76 d.code,
77 d.message
78 ));
79 continue;
80 }
81 let hit = expected.iter().position(|e| {
82 e.line == line
83 && e.severity == d.severity
84 && e.code == d.code
85 && mentions(&d.message, &d.notes, &e.fragment)
86 });
87 match hit {
88 Some(i) => {
89 expected.remove(i);
90 }
91 None => failures.push(format!(
92 "unexpected at line {}: [{}] {}",
93 line + 1,
94 d.code,
95 d.message
96 )),
97 }
98 }
99 for e in expected {
100 failures.push(format!(
101 "missing at line {}: [{}] containing {:?}",
102 e.line + 1,
103 e.code,
104 e.fragment
105 ));
106 }
107 let main = hir.module_by_path("main").unwrap();
108 for (name, want) in types {
109 let Some(def) = hir.lookup_value(main, &name) else {
110 failures.push(format!("TYPE: no item `{name}`"));
111 continue;
112 };
113 let printer = Printer {
114 hir,
115 ctx: None,
116 gen_names: &[],
117 rigid_names: &[],
118 };
119 let got = typeck
120 .schemes
121 .get(&def)
122 .map(|s| printer.scheme(s))
123 .unwrap_or_else(|| "<none>".into());
124 if got != want {
125 failures.push(format!("TYPE {name}: expected `{want}`, got `{got}`"));
126 }
127 }
128 failures
129}
130
131#[test]
132fn ui() {
133 let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/ui");
134 let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
135 .unwrap()
136 .map(|e| e.unwrap().path())
137 .filter(|p| p.extension().is_some_and(|e| e == "lse"))
138 .collect();
139 files.sort();
140 assert!(!files.is_empty());
141 // LOUISE_UI_BLESS=1 rewrites the `//~ ERROR`/`//~ WARN` markers to the
142 // lines diagnostics actually point at (keeping `//~ TYPE` markers and
143 // reusing message fragments by diagnostic code), for after formatting
144 // or other line-shifting changes. The file is reformatted on the way,
145 // so `louise fmt --check tests/ui` stays clean.
146 if std::env::var("LOUISE_UI_BLESS").is_ok() {
147 for file in &files {
148 bless(file);
149 }
150 return;
151 }
152 let mut report = String::new();
153 for file in &files {
154 for failure in run(file) {
155 report.push_str(&format!(
156 "{}: {failure}\n",
157 file.file_name().unwrap().to_string_lossy()
158 ));
159 }
160 }
161 assert!(report.is_empty(), "UI test failures:\n{report}");
162}
163
164/// Whether a diagnostic's message or one of its notes contains `fragment`.
165fn mentions(message: &str, notes: &[String], fragment: &str) -> bool {
166 message.contains(fragment) || notes.iter().any(|n| n.contains(fragment))
167}
168
169/// A diagnostic as the harness sees it: severity, code, line (1-based),
170/// message and notes.
171struct Actual {
172 line: u32,
173 severity: Severity,
174 code: String,
175 message: String,
176 notes: Vec<String>,
177}
178
179fn diagnostics(path: &Path, text: &str) -> Vec<Actual> {
180 let mut db = Db::new();
181 let main_file = db.add_module("main", &path.display().to_string(), text.to_owned());
182 let analysis = db.analyze();
183 let mut out = Vec::new();
184 for d in &analysis.diagnostics {
185 if d.primary.span.file != main_file {
186 continue;
187 }
188 let file = db.sources().get(d.primary.span.file);
189 let line = file.line_col(d.primary.span.range.start()).line + 1;
190 out.push(Actual {
191 line,
192 severity: d.severity,
193 code: d.code.to_owned(),
194 message: d.message.clone(),
195 notes: d.notes.clone(),
196 });
197 }
198 out
199}
200
201/// Rewrite a UI file's `//~ ERROR`/`//~ WARN` markers at the lines of its
202/// current diagnostics: trailing on the target line when it fits in 80
203/// columns, else on `//~^` lines right below. `//~ TYPE` markers stay.
204/// Fragments are reused from the old markers by diagnostic code.
205fn bless(path: &Path) {
206 let text = std::fs::read_to_string(path).unwrap();
207 let (old, _) = parse_expectations(&text);
208 let mut lines: Vec<String> = text.lines().map(str::to_owned).collect();
209 // Strip ERROR/WARN markers: standalone marker lines are removed,
210 // trailing markers trimmed off.
211 let mut i = lines.len();
212 while i > 0 {
213 i -= 1;
214 let Some(at) = lines[i].find("//~") else {
215 continue;
216 };
217 let before = &lines[i][..at];
218 let rest = lines[i][at + 3..].trim_start_matches('^').trim_start();
219 if rest.starts_with("ERROR ") || rest.starts_with("WARN ") {
220 if before.trim().is_empty() {
221 // Standalone marker line: drop it.
222 lines.remove(i);
223 } else {
224 // Trailing marker: keep the code.
225 lines[i] = before.trim_end().to_owned();
226 }
227 }
228 }
229 let mut text = lines.join("\n") + "\n";
230 let mut diags = diagnostics(path, &text);
231 diags.sort_by_key(|d| d.line);
232 // Bottom-up, so insertions below do not move earlier targets.
233 for d in diags.iter().rev() {
234 let fragment = old
235 .iter()
236 .filter(|e| e.code == d.code && mentions(&d.message, &d.notes, &e.fragment))
237 .map(|e| e.fragment.clone())
238 .next()
239 .unwrap_or_default();
240 let marker = format!(
241 "//~ {} {}{}",
242 match d.severity {
243 Severity::Error => "ERROR",
244 Severity::Warning => "WARN",
245 },
246 d.code,
247 if fragment.is_empty() {
248 String::new()
249 } else {
250 format!(" {fragment}")
251 },
252 );
253 let mut lines: Vec<String> = text.lines().map(str::to_owned).collect();
254 let target = (d.line - 1) as usize;
255 let trailing = format!("{} {}", lines[target], marker);
256 if trailing.chars().count() <= 80 && !lines[target].contains("//~") {
257 lines[target] = trailing;
258 } else {
259 // Standalone `//~^` lines right below, indented as the
260 // formatter will indent them: with the following code line.
261 let mut carets = 1;
262 let mut at = target + 1;
263 while at < lines.len() && lines[at].trim_start().starts_with("//~") {
264 carets += 1;
265 at += 1;
266 }
267 let indent: String = lines
268 .get(at)
269 .filter(|l| !l.trim().is_empty())
270 .map(|l| l.chars().take_while(|c| *c == ' ' || *c == '\t').collect())
271 .unwrap_or_else(|| {
272 lines[target]
273 .chars()
274 .take_while(|c| *c == ' ' || *c == '\t')
275 .collect()
276 });
277 let marker = format!(
278 "{indent}//~{} {}",
279 "^".repeat(carets),
280 marker.trim_start_matches("//~")
281 );
282 lines.insert(at, marker);
283 }
284 text = lines.join("\n") + "\n";
285 }
286 // Indentation of the marker lines is the formatter's call; formatting
287 // here keeps `louise fmt --check tests/ui` clean.
288 if let Ok(formatted) = louise_syntax::format::format(&text) {
289 text = formatted;
290 }
291 std::fs::write(path, text).unwrap();
292}