//! UI tests: `tests/ui/*.lse` files with inline expectations. //! //! - `//~ ERROR E0202 fragment` expects a diagnostic with that code (and a //! message or a note containing `fragment`, if given) whose primary span //! starts on this line. `//~^ ERROR ...` points one line up (`^^` two lines, ...). //! - `//~ WARN W0101` is the same for warnings. //! - `//~ TYPE name: scheme` expects the top-level item `name` to have //! this type, as printed in hovers. //! //! Every diagnostic must be expected, and every expectation met. The file //! is checked as module `main` with the real standard library, through //! the same pipeline as `louise check` and the language server. use std::path::{Path, PathBuf}; use louise_db::Db; use louise_diag::{Diagnostic, Severity}; use louise_types::Printer; struct Expectation { line: u32, severity: Severity, code: String, fragment: String, } fn parse_expectations(text: &str) -> (Vec, Vec<(String, String)>) { let mut diags = Vec::new(); let mut types = Vec::new(); for (i, line) in text.lines().enumerate() { let Some((_, rest)) = line.split_once("//~") else { continue; }; let carets = rest.chars().take_while(|c| *c == '^').count(); let rest = rest[carets..].trim(); if let Some(t) = rest.strip_prefix("TYPE ") { let (name, ty) = t.split_once(':').expect("`//~ TYPE name: type`"); types.push((name.trim().to_owned(), ty.trim().to_owned())); continue; } let (severity, rest) = if let Some(r) = rest.strip_prefix("ERROR ") { (Severity::Error, r) } else if let Some(r) = rest.strip_prefix("WARN ") { (Severity::Warning, r) } else { panic!("line {}: unknown expectation `{rest}`", i + 1); }; let (code, fragment) = rest.split_once(' ').unwrap_or((rest, "")); diags.push(Expectation { line: (i - carets) as u32, severity, code: code.to_owned(), fragment: fragment.trim().to_owned(), }); } (diags, types) } fn run(path: &Path) -> Vec { let text = std::fs::read_to_string(path).unwrap(); let mut db = Db::new(); let main_file = db.add_module("main", &path.display().to_string(), text.clone()); let mut analysis = db.analyze(); if !analysis.diagnostics.iter().any(Diagnostic::is_error) { let semantic = louise_db::semantic_diagnostics(&db, &analysis); analysis.diagnostics.extend(semantic); } let (hir, typeck, diags) = (&analysis.hir, &analysis.typeck, &analysis.diagnostics); let (mut expected, types) = parse_expectations(&text); let mut failures = Vec::new(); for d in diags { let file = db.sources().get(d.primary.span.file); let line = file.line_col(d.primary.span.range.start()).line; if d.primary.span.file != main_file { failures.push(format!( "diagnostic in {}:{}: [{}] {}", file.path(), line + 1, d.code, d.message )); continue; } let hit = expected.iter().position(|e| { e.line == line && e.severity == d.severity && e.code == d.code && mentions(&d.message, &d.notes, &e.fragment) }); match hit { Some(i) => { expected.remove(i); } None => failures.push(format!( "unexpected at line {}: [{}] {}", line + 1, d.code, d.message )), } } for e in expected { failures.push(format!( "missing at line {}: [{}] containing {:?}", e.line + 1, e.code, e.fragment )); } let main = hir.module_by_path("main").unwrap(); for (name, want) in types { let Some(def) = hir.lookup_value(main, &name) else { failures.push(format!("TYPE: no item `{name}`")); continue; }; let printer = Printer { hir, ctx: None, gen_names: &[], rigid_names: &[], }; let got = typeck .schemes .get(&def) .map(|s| printer.scheme(s)) .unwrap_or_else(|| "".into()); if got != want { failures.push(format!("TYPE {name}: expected `{want}`, got `{got}`")); } } failures } #[test] fn ui() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/ui"); let mut files: Vec = std::fs::read_dir(&dir) .unwrap() .map(|e| e.unwrap().path()) .filter(|p| p.extension().is_some_and(|e| e == "lse")) .collect(); files.sort(); assert!(!files.is_empty()); // LOUISE_UI_BLESS=1 rewrites the `//~ ERROR`/`//~ WARN` markers to the // lines diagnostics actually point at (keeping `//~ TYPE` markers and // reusing message fragments by diagnostic code), for after formatting // or other line-shifting changes. The file is reformatted on the way, // so `louise fmt --check tests/ui` stays clean. if std::env::var("LOUISE_UI_BLESS").is_ok() { for file in &files { bless(file); } return; } let mut report = String::new(); for file in &files { for failure in run(file) { report.push_str(&format!( "{}: {failure}\n", file.file_name().unwrap().to_string_lossy() )); } } assert!(report.is_empty(), "UI test failures:\n{report}"); } /// Whether a diagnostic's message or one of its notes contains `fragment`. fn mentions(message: &str, notes: &[String], fragment: &str) -> bool { message.contains(fragment) || notes.iter().any(|n| n.contains(fragment)) } /// A diagnostic as the harness sees it: severity, code, line (1-based), /// message and notes. struct Actual { line: u32, severity: Severity, code: String, message: String, notes: Vec, } fn diagnostics(path: &Path, text: &str) -> Vec { let mut db = Db::new(); let main_file = db.add_module("main", &path.display().to_string(), text.to_owned()); let mut analysis = db.analyze(); if !analysis.diagnostics.iter().any(Diagnostic::is_error) { let semantic = louise_db::semantic_diagnostics(&db, &analysis); analysis.diagnostics.extend(semantic); } let mut out = Vec::new(); for d in &analysis.diagnostics { if d.primary.span.file != main_file { continue; } let file = db.sources().get(d.primary.span.file); let line = file.line_col(d.primary.span.range.start()).line + 1; out.push(Actual { line, severity: d.severity, code: d.code.to_owned(), message: d.message.clone(), notes: d.notes.clone(), }); } out } /// Rewrite a UI file's `//~ ERROR`/`//~ WARN` markers at the lines of its /// current diagnostics: trailing on the target line when it fits in 80 /// columns, else on `//~^` lines right below. `//~ TYPE` markers stay. /// Fragments are reused from the old markers by diagnostic code. fn bless(path: &Path) { let text = std::fs::read_to_string(path).unwrap(); let (old, _) = parse_expectations(&text); let mut lines: Vec = text.lines().map(str::to_owned).collect(); // Strip ERROR/WARN markers: standalone marker lines are removed, // trailing markers trimmed off. let mut i = lines.len(); while i > 0 { i -= 1; let Some(at) = lines[i].find("//~") else { continue; }; let before = &lines[i][..at]; let rest = lines[i][at + 3..].trim_start_matches('^').trim_start(); if rest.starts_with("ERROR ") || rest.starts_with("WARN ") { if before.trim().is_empty() { // Standalone marker line: drop it. lines.remove(i); } else { // Trailing marker: keep the code. lines[i] = before.trim_end().to_owned(); } } } let mut text = lines.join("\n") + "\n"; let mut diags = diagnostics(path, &text); diags.sort_by_key(|d| d.line); // Bottom-up, so insertions below do not move earlier targets. for d in diags.iter().rev() { let fragment = old .iter() .filter(|e| e.code == d.code && mentions(&d.message, &d.notes, &e.fragment)) .map(|e| e.fragment.clone()) .next() .unwrap_or_default(); let marker = format!( "//~ {} {}{}", match d.severity { Severity::Error => "ERROR", Severity::Warning => "WARN", }, d.code, if fragment.is_empty() { String::new() } else { format!(" {fragment}") }, ); let mut lines: Vec = text.lines().map(str::to_owned).collect(); let target = (d.line - 1) as usize; let trailing = format!("{} {}", lines[target], marker); if trailing.chars().count() <= 80 && !lines[target].contains("//~") { lines[target] = trailing; } else { // Standalone `//~^` lines right below, indented as the // formatter will indent them: with the following code line. let mut carets = 1; let mut at = target + 1; while at < lines.len() && lines[at].trim_start().starts_with("//~") { carets += 1; at += 1; } let indent: String = lines .get(at) .filter(|l| !l.trim().is_empty()) .map(|l| l.chars().take_while(|c| *c == ' ' || *c == '\t').collect()) .unwrap_or_else(|| { lines[target] .chars() .take_while(|c| *c == ' ' || *c == '\t') .collect() }); let marker = format!( "{indent}//~{} {}", "^".repeat(carets), marker.trim_start_matches("//~") ); lines.insert(at, marker); } text = lines.join("\n") + "\n"; } // Indentation of the marker lines is the formatter's call; formatting // here keeps `louise fmt --check tests/ui` clean. if let Ok(formatted) = louise_syntax::format::format(&text) { text = formatted; } std::fs::write(path, text).unwrap(); }