oxedyne/fe2o3/fe2o3_austenite/src/diag.rs
14.9 KiB, 9 runs
created by r1870400018:63196, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Diagnostics for the evaluator path, replacing `lang::Refusals` at cut-over (U11). An evaluation |
| 2 | //! failure is recorded here with its span *and* returned as an `Err`, so an `Outcome` carries control flow |
| 3 | //! while the diagnostic list carries the position; `Engine::error` does both in one call. |
| 4 | |
| 5 | use crate::eval::eval::std_path_bound; |
| 6 | use crate::eval::value::Type; |
| 7 | use crate::syntax::{ |
| 8 | Source, |
| 9 | Span, |
| 10 | SyntaxKind, |
| 11 | SyntaxNode, |
| 12 | }; |
| 13 | |
| 14 | use oxedyne_fe2o3_core::prelude::*; |
| 15 | |
| 16 | use std::fmt; |
| 17 | |
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 19 | pub enum Severity { |
| 20 | Error, |
| 21 | Warning, |
| 22 | } |
| 23 | |
| 24 | impl Severity { |
| 25 | pub fn name(self) -> &'static str { |
| 26 | match self { |
| 27 | Severity::Error => "error", |
| 28 | Severity::Warning => "warning", |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /// Why a diagnostic was raised, fixed where its refusal or error is raised and never read back from the |
| 34 | /// message's wording, which drifts. [`DiagnosticKind::as_str`] is the word a caller switches on. |
| 35 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 36 | pub enum DiagnosticKind { |
| 37 | MissingFile, // a source, chapter, image or other file could not be found or read |
| 38 | Encoding, // a source or other text file that is there but is not valid UTF-8 text |
| 39 | MissingFont, // a named family that no supplied or embedded font declares |
| 40 | Syntax, // source that does not parse |
| 41 | Type, // a value of the wrong type |
| 42 | UnknownVariable, // a name with no binding in scope |
| 43 | Package, // a package import the host has not supplied |
| 44 | Limit, // a limit of the engine reached: layout that will not settle, a depth or a loop bound |
| 45 | Unsupported, // a construct passed over or refused, or one set with a stand-in for what it asked for |
| 46 | Lint, // a warning Typst itself raises about the source, which is set as written |
| 47 | Internal, // no pages, no content, or an error raised with no more specific tag |
| 48 | } |
| 49 | |
| 50 | impl DiagnosticKind { |
| 51 | /// The word the kind is carried as. A caller switches on it, so it never changes. |
| 52 | pub fn as_str(&self) -> &'static str { |
| 53 | match self { |
| 54 | Self::MissingFile => "missing_file", |
| 55 | Self::Encoding => "encoding", |
| 56 | Self::MissingFont => "missing_font", |
| 57 | Self::Syntax => "syntax", |
| 58 | Self::Type => "type", |
| 59 | Self::UnknownVariable => "unknown_variable", |
| 60 | Self::Package => "package", |
| 61 | Self::Limit => "limit", |
| 62 | Self::Unsupported => "unsupported", |
| 63 | Self::Lint => "lint", |
| 64 | Self::Internal => "internal", |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// Does a warning of this kind refuse a strict compile? It does where the document was not set as |
| 69 | /// written: a construct passed over or set with a stand-in, or a file, its text, a package or a font |
| 70 | /// family missing. A [`Lint`](Self::Lint) is Typst's own remark on a document it sets as written, so it |
| 71 | /// stands beside the PDF. |
| 72 | pub fn refuses_strict(&self) -> bool { |
| 73 | matches!(self, Self::Unsupported | Self::MissingFile | Self::Encoding | Self::Package | Self::MissingFont) |
| 74 | } |
| 75 | |
| 76 | /// The kind of a curated-path refusal, by the class it was refused under. Every class but a missing or |
| 77 | /// unreadable file is a construct passed over or set with a stand-in. |
| 78 | pub(crate) fn from_refusal_class(class: crate::lang::RefusalClass) -> Self { |
| 79 | use crate::lang::RefusalClass; |
| 80 | match class { |
| 81 | RefusalClass::FixedPoint => Self::Unsupported, |
| 82 | RefusalClass::Introspective => Self::Unsupported, |
| 83 | RefusalClass::Unsupported => Self::Unsupported, |
| 84 | RefusalClass::MissingFile => Self::MissingFile, |
| 85 | RefusalClass::Unusable => Self::Unsupported, |
| 86 | RefusalClass::Encoding => Self::Encoding, |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /// A hard error's kind, from the tags it was raised with anywhere in its chain. A file that is there |
| 91 | /// but not UTF-8 text is told from one that cannot be read at all, since the remedy differs. An error |
| 92 | /// raised as unimplemented is a construct passed over. |
| 93 | pub fn from_error_tags(e: &Error<ErrTag>) -> Self { |
| 94 | let tags = e.tags(); |
| 95 | if tags.contains(&ErrTag::Font) { |
| 96 | Self::MissingFont |
| 97 | } else if tags.contains(&ErrTag::UTF8) { |
| 98 | Self::Encoding |
| 99 | } else if tags.contains(&ErrTag::File) { |
| 100 | Self::MissingFile |
| 101 | } else if tags.contains(&ErrTag::LimitReached) { |
| 102 | Self::Limit |
| 103 | } else if tags.contains(&ErrTag::Unimplemented) || tags.contains(&ErrTag::NoImpl) { |
| 104 | Self::Unsupported |
| 105 | } else { |
| 106 | Self::Internal |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | impl fmt::Display for DiagnosticKind { |
| 112 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 113 | write!(f, "{}", self.as_str()) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 118 | pub struct Diagnostic { |
| 119 | pub severity: Severity, |
| 120 | pub kind: DiagnosticKind, |
| 121 | pub span: Span, |
| 122 | pub message: String, |
| 123 | pub hints: Vec<String>, |
| 124 | pub trace: Vec<(Span, String)>, // call sites outward, innermost first |
| 125 | pub need: Option<String>, // the package an import asked for that nobody supplied, as `@ns/name:version` |
| 126 | } |
| 127 | |
| 128 | impl Diagnostic { |
| 129 | pub fn error<S: Into<String>>(kind: DiagnosticKind, span: Span, message: S) -> Self { |
| 130 | Self { severity: Severity::Error, kind, span, message: message.into(), hints: Vec::new(), trace: Vec::new(), need: None } |
| 131 | } |
| 132 | |
| 133 | pub fn warning<S: Into<String>>(kind: DiagnosticKind, span: Span, message: S) -> Self { |
| 134 | Self { severity: Severity::Warning, kind, span, message: message.into(), hints: Vec::new(), trace: Vec::new(), need: None } |
| 135 | } |
| 136 | |
| 137 | pub fn with_hint<S: Into<String>>(mut self, hint: S) -> Self { |
| 138 | self.hints.push(hint.into()); |
| 139 | self |
| 140 | } |
| 141 | |
| 142 | /// Names the package an import asked for, so a host reads what to supply from the diagnostic, never from its |
| 143 | /// message. |
| 144 | pub fn needing<S: Into<String>>(mut self, spec: S) -> Self { |
| 145 | self.need = Some(spec.into()); |
| 146 | self |
| 147 | } |
| 148 | |
| 149 | pub fn is_error(&self) -> bool { self.severity == Severity::Error } |
| 150 | |
| 151 | /// The message up to its first colon: the name of what was passed over, before the particulars of |
| 152 | /// where it was met. |
| 153 | pub fn head(&self) -> &str { |
| 154 | self.message.split(':').next().unwrap_or("").trim() |
| 155 | } |
| 156 | |
| 157 | /// `path:line:col: severity: message`, then one `hint:` line each, against the sources the span |
| 158 | /// indexes. A detached span or an unknown file renders without a position. |
| 159 | pub fn render(&self, sources: &[Source]) -> String { |
| 160 | let mut s = match sources.iter().find(|src| src.id == self.span.file) { |
| 161 | Some(src) if !self.span.is_detached() => { |
| 162 | let (l, c) = src.line_col(self.span.start); |
| 163 | fmt!("{}:{}:{}: {}: {}", src.path.display(), l, c, self.severity.name(), self.message) |
| 164 | } |
| 165 | _ => fmt!("{}: {}", self.severity.name(), self.message), |
| 166 | }; |
| 167 | for h in &self.hints { |
| 168 | s.push_str("\n hint: "); |
| 169 | s.push_str(h); |
| 170 | } |
| 171 | s |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /// The lines of the `--diag-summary` report, one for each severity, kind and construct, as |
| 176 | /// `diag-summary <severity> <kind> <construct> <count>`, errors before warnings and each group in the |
| 177 | /// order of its kind's word and construct. The construct is given only for kind `unsupported`, as the |
| 178 | /// diagnostic's [`head`](Diagnostic::head) with each space written `_`; every other kind has `-`. No |
| 179 | /// message, path or position is carried, so the report names what was passed over and never the document |
| 180 | /// it was passed over in. |
| 181 | pub fn summary_lines(diags: &[Diagnostic]) -> Vec<String> { |
| 182 | let mut counts: std::collections::BTreeMap<(Severity, &'static str, String), usize> = |
| 183 | std::collections::BTreeMap::new(); |
| 184 | for d in diags { |
| 185 | let construct = match d.kind { |
| 186 | DiagnosticKind::Unsupported => { |
| 187 | let head: String = d.head().chars() |
| 188 | .map(|c| if c.is_whitespace() { '_' } else { c }) |
| 189 | .collect(); |
| 190 | if head.is_empty() { "-".to_string() } else { head } |
| 191 | }, |
| 192 | _ => "-".to_string(), |
| 193 | }; |
| 194 | *counts.entry((d.severity, d.kind.as_str(), construct)).or_insert(0) += 1; |
| 195 | } |
| 196 | counts.into_iter() |
| 197 | .map(|((sev, kind, construct), n)| fmt!("diag-summary {} {} {} {}", sev.name(), kind, construct, n)) |
| 198 | .collect() |
| 199 | } |
| 200 | |
| 201 | /// The lines of the `--diag-summary` report that name each error, one per error diagnostic, as |
| 202 | /// `diag-error <kind> callee:<name> expected:<type> found:<type> file:<class>`. Every token is drawn from a |
| 203 | /// closed vocabulary, so the line says what failed in Typst's own terms and nothing of the document: |
| 204 | /// |
| 205 | /// * `callee` is the call the error's span lies in, or failing that the name at the span, written as a |
| 206 | /// dotted path (`calc.pow`), when every segment is a name the standard library binds and the path is |
| 207 | /// lower-case letters, digits, `-` and `.`; otherwise `-`. A document's own function or variable is `-`. |
| 208 | /// * `expected` and `found` are the two types of a message that reads `expected <type>, found <type>` with |
| 209 | /// each a type in the registry ([`Type`]); otherwise both are `-`. A message that offers several types |
| 210 | /// is `-`. |
| 211 | /// * `file` is `main` for the compiled source (the first loaded), `sibling` for another file in its |
| 212 | /// directory, and `other` for anything else, a detached span included. |
| 213 | /// |
| 214 | /// No message, name, path, position, field or source text of the document is carried. |
| 215 | pub fn error_lines(diags: &[Diagnostic], sources: &[Source]) -> Vec<String> { |
| 216 | diags.iter() |
| 217 | .filter(|d| d.is_error()) |
| 218 | .map(|d| { |
| 219 | let (expected, found) = type_pair(&d.message).unwrap_or(("-", "-")); |
| 220 | fmt!("diag-error {} callee:{} expected:{} found:{} file:{}", |
| 221 | d.kind.as_str(), callee_of(d.span, sources), expected, found, file_class(d.span, sources)) |
| 222 | }) |
| 223 | .collect() |
| 224 | } |
| 225 | |
| 226 | // The two registry types of `expected <type>, found <type>`, as their names, or `None` when the message is any |
| 227 | // other shape or either side is not exactly one registry type. |
| 228 | fn type_pair(message: &str) -> Option<(&'static str, &'static str)> { |
| 229 | message.strip_prefix("expected ") |
| 230 | .and_then(|m| m.split_once(", found ")) |
| 231 | .and_then(|(e, f)| Type::from_name(e).zip(Type::from_name(f))) |
| 232 | .map(|(e, f)| (e.name(), f.name())) |
| 233 | } |
| 234 | |
| 235 | // Where an error lies relative to the compiled source, which is the first one loaded. |
| 236 | fn file_class(span: Span, sources: &[Source]) -> &'static str { |
| 237 | let at = match sources.iter().find(|s| s.id == span.file && !span.is_detached()) { |
| 238 | Some(s) => s, |
| 239 | None => return "other", |
| 240 | }; |
| 241 | let main = match sources.first() { |
| 242 | Some(m) => m, |
| 243 | None => return "other", |
| 244 | }; |
| 245 | if at.id == main.id { |
| 246 | "main" |
| 247 | } else if at.path.parent() == main.path.parent() { |
| 248 | "sibling" |
| 249 | } else { |
| 250 | "other" |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // The standard-library name of the call an error's span lies in, else of the name at the span, else `-`. |
| 255 | fn callee_of(span: Span, sources: &[Source]) -> String { |
| 256 | let src = match sources.iter().find(|s| s.id == span.file && !span.is_detached()) { |
| 257 | Some(s) => s, |
| 258 | None => return "-".to_string(), |
| 259 | }; |
| 260 | // The nodes from the root down to the smallest one holding the span. |
| 261 | let mut node = &src.root; |
| 262 | let mut chain: Vec<&SyntaxNode> = vec![node]; |
| 263 | while let Some(c) = node.children().iter().find(|c| { |
| 264 | let at = c.span(); |
| 265 | !at.is_detached() && at.start <= span.start && span.end <= at.end |
| 266 | }) { |
| 267 | chain.push(c); |
| 268 | node = c; |
| 269 | } |
| 270 | let name = match chain.iter().rev().find(|n| matches!(n.kind(), SyntaxKind::FuncCall | SyntaxKind::MathCall)) { |
| 271 | Some(call) => call.significant().next().and_then(path_of), |
| 272 | None => chain.last().copied().and_then(path_of), |
| 273 | }; |
| 274 | let name = match name { |
| 275 | Some(n) => n, |
| 276 | None => return "-".to_string(), |
| 277 | }; |
| 278 | let segs: Vec<&str> = name.iter().map(|s| s.as_str()).collect(); |
| 279 | let word = segs.join("."); |
| 280 | let plain = word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.'); |
| 281 | if plain && !word.is_empty() && std_path_bound(&segs) { word } else { "-".to_string() } |
| 282 | } |
| 283 | |
| 284 | // A name written as an identifier or a chain of field accesses on one, as its segments. |
| 285 | fn path_of(node: &SyntaxNode) -> Option<Vec<String>> { |
| 286 | match node.kind() { |
| 287 | SyntaxKind::Ident | SyntaxKind::MathIdent => Some(vec![node.text().to_string()]), |
| 288 | SyntaxKind::FieldAccess | SyntaxKind::MathFieldAccess => { |
| 289 | let target = node.significant().next().and_then(path_of); |
| 290 | let field = node.significant().last() |
| 291 | .filter(|f| matches!(f.kind(), SyntaxKind::Ident | SyntaxKind::MathIdent)); |
| 292 | match (target, field) { |
| 293 | (Some(mut path), Some(f)) => { |
| 294 | path.push(f.text().to_string()); |
| 295 | Some(path) |
| 296 | }, |
| 297 | _ => None, |
| 298 | } |
| 299 | }, |
| 300 | _ => None, |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | /// An error's own message, the last one pushed, without the chain of places it passed through: the |
| 305 | /// text a diagnostic shows for it. |
| 306 | pub fn message_of(e: &Error<ErrTag>) -> String { |
| 307 | match e.msgs().into_iter().last() { |
| 308 | Some(m) => m, |
| 309 | None => fmt!("{}", e), |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | #[cfg(test)] |
| 314 | mod tests { |
| 315 | use super::*; |
| 316 | |
| 317 | // The eleven words and the strict set, which the Daimond gate's table maps: a caller switches on a word, |
| 318 | // so neither moves without that table moving. |
| 319 | const GATE: [(DiagnosticKind, &str, bool); 11] = [ |
| 320 | (DiagnosticKind::MissingFile, "missing_file", true), |
| 321 | (DiagnosticKind::Encoding, "encoding", true), |
| 322 | (DiagnosticKind::MissingFont, "missing_font", true), |
| 323 | (DiagnosticKind::Syntax, "syntax", false), |
| 324 | (DiagnosticKind::Type, "type", false), |
| 325 | (DiagnosticKind::UnknownVariable, "unknown_variable", false), |
| 326 | (DiagnosticKind::Package, "package", true), |
| 327 | (DiagnosticKind::Limit, "limit", false), |
| 328 | (DiagnosticKind::Unsupported, "unsupported", true), |
| 329 | (DiagnosticKind::Lint, "lint", false), |
| 330 | (DiagnosticKind::Internal, "internal", false), |
| 331 | ]; |
| 332 | |
| 333 | // An exhaustive match, so a variant added to the enum fails here until the table above holds it. |
| 334 | fn slot(k: DiagnosticKind) -> usize { |
| 335 | match k { |
| 336 | DiagnosticKind::MissingFile => 0, |
| 337 | DiagnosticKind::Encoding => 1, |
| 338 | DiagnosticKind::MissingFont => 2, |
| 339 | DiagnosticKind::Syntax => 3, |
| 340 | DiagnosticKind::Type => 4, |
| 341 | DiagnosticKind::UnknownVariable => 5, |
| 342 | DiagnosticKind::Package => 6, |
| 343 | DiagnosticKind::Limit => 7, |
| 344 | DiagnosticKind::Unsupported => 8, |
| 345 | DiagnosticKind::Lint => 9, |
| 346 | DiagnosticKind::Internal => 10, |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | #[test] |
| 351 | fn the_eleven_kind_words_and_the_strict_set_match_the_gates_table() { |
| 352 | let mut seen = [false; 11]; |
| 353 | for (kind, word, strict) in GATE { |
| 354 | seen[slot(kind)] = true; |
| 355 | assert_eq!(kind.as_str(), word, "the word of {:?}", kind); |
| 356 | assert_eq!(kind.to_string(), word, "the displayed word of {:?}", kind); |
| 357 | assert_eq!(kind.refuses_strict(), strict, "does {:?} refuse a strict compile", kind); |
| 358 | } |
| 359 | assert!(seen.iter().all(|s| *s), "the gate's table leaves a kind out: {:?}", seen); |
| 360 | assert_eq!(GATE.iter().filter(|g| g.2).count(), 5, "five kinds refuse a strict compile"); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn a_diagnostic_carries_the_kind_it_was_raised_with() { |
| 365 | let at = Span::detached(); |
| 366 | let w = Diagnostic::warning(DiagnosticKind::Unsupported, at, "passed over"); |
| 367 | assert_eq!((w.severity, w.kind), (Severity::Warning, DiagnosticKind::Unsupported)); |
| 368 | let e = Diagnostic::error(DiagnosticKind::Syntax, at, "unclosed"); |
| 369 | assert_eq!((e.severity, e.kind), (Severity::Error, DiagnosticKind::Syntax)); |
| 370 | assert!(e.is_error() && !w.is_error()); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn an_error_kind_is_read_from_its_tags() { |
| 375 | let kind = |e: Error<ErrTag>| DiagnosticKind::from_error_tags(&e); |
| 376 | assert_eq!(kind(err!("not text"; Decode, UTF8, String)), DiagnosticKind::Encoding); |
| 377 | assert_eq!(kind(err!("no such file"; IO, File, Read)), DiagnosticKind::MissingFile); |
| 378 | assert_eq!(kind(err!("too deep"; Excessive, LimitReached)), DiagnosticKind::Limit); |
| 379 | assert_eq!(kind(err!("a stub"; Unimplemented)), DiagnosticKind::Unsupported); |
| 380 | assert_eq!(kind(err!("no tag of its own"; Input, Invalid)), DiagnosticKind::Internal); |
| 381 | } |
| 382 | } |