Skip to main content

mago_reporting/formatter/
rich.rs

1use std::borrow::Cow;
2use std::cell::Cell;
3use std::cmp::Ordering;
4use std::collections::hash_map::Entry;
5use std::io::IsTerminal;
6use std::io::Write;
7use std::ops::Range;
8
9use codespan_reporting::diagnostic::Diagnostic;
10use codespan_reporting::diagnostic::Label;
11use codespan_reporting::diagnostic::LabelStyle;
12use codespan_reporting::diagnostic::Severity;
13use codespan_reporting::files::Error;
14use codespan_reporting::files::Files;
15use codespan_reporting::term;
16use codespan_reporting::term::Config;
17use codespan_reporting::term::DisplayStyle;
18use foldhash::HashMap;
19use termcolor::Ansi;
20use termcolor::NoColor;
21
22use mago_database::DatabaseReader;
23use mago_database::ReadDatabase;
24use mago_database::file::File;
25use mago_database::file::FileId;
26
27use crate::Annotation;
28use crate::AnnotationKind;
29use crate::Issue;
30use crate::IssueCollection;
31use crate::Level;
32use crate::error::ReportingError;
33use crate::formatter::Formatter;
34use crate::formatter::FormatterConfig;
35use crate::formatter::utils::osc8_file_hyperlink;
36#[cfg(not(target_arch = "wasm32"))]
37use crate::formatter::utils::render_chunks_in_order;
38use crate::formatter::utils::utf8_preserving_byte_offsets;
39
40/// Formatter that outputs issues in rich diagnostic format with full context.
41pub(crate) struct RichFormatter;
42
43impl Formatter for RichFormatter {
44    fn format(
45        &self,
46        writer: &mut dyn Write,
47        issues: &IssueCollection,
48        database: &ReadDatabase,
49        config: &FormatterConfig,
50    ) -> Result<(), ReportingError> {
51        codespan_format_with_config(
52            writer,
53            issues,
54            database,
55            config,
56            &Config { display_style: DisplayStyle::Rich, ..Default::default() },
57        )
58    }
59}
60
61pub(super) fn codespan_format_with_config(
62    writer: &mut dyn Write,
63    issues: &IssueCollection,
64    database: &ReadDatabase,
65    config: &FormatterConfig,
66    codespan_config: &Config,
67) -> Result<(), ReportingError> {
68    let use_colors = config.color_choice.should_use_colors(std::io::stdout().is_terminal());
69    let editor_url = if use_colors { config.editor_url.as_deref() } else { None };
70    let issues: Vec<_> = crate::formatter::utils::filter_issues(issues, config, true).collect();
71    let mut sources = HashMap::default();
72
73    for issue in &issues {
74        for annotation in &issue.annotations {
75            if !matches!(codespan_config.display_style, DisplayStyle::Rich) && !annotation.is_primary() {
76                continue;
77            }
78
79            if let Entry::Vacant(entry) = sources.entry(annotation.span.file_id) {
80                let file = database.get_ref(&annotation.span.file_id).map_err(|_| Error::FileMissing)?;
81                entry.insert(utf8_preserving_byte_offsets(file.contents.as_ref()));
82            }
83        }
84    }
85
86    let mut highest_level: Option<Level> = None;
87    let mut errors = 0;
88    let mut warnings = 0;
89    let mut notes = 0;
90    let mut help = 0;
91    let mut suggestions = 0;
92    for issue in &issues {
93        match issue.level {
94            Level::Note => notes += 1,
95            Level::Help => help += 1,
96            Level::Warning => warnings += 1,
97            Level::Error => errors += 1,
98        }
99
100        highest_level = Some(highest_level.map_or(issue.level, |cur| cur.max(issue.level)));
101
102        if !issue.edits.is_empty() {
103            suggestions += 1;
104        }
105    }
106
107    write_issues(writer, &issues, database, &sources, editor_url, use_colors, codespan_config)?;
108
109    if let Some(highest_level) = highest_level {
110        let total_issues = errors + warnings + notes + help;
111        let mut message_notes = vec![];
112        if errors > 0 {
113            message_notes.push(format!("{errors} error(s)"));
114        }
115
116        if warnings > 0 {
117            message_notes.push(format!("{warnings} warning(s)"));
118        }
119
120        if notes > 0 {
121            message_notes.push(format!("{notes} note(s)"));
122        }
123
124        if help > 0 {
125            message_notes.push(format!("{help} help message(s)"));
126        }
127
128        let mut diagnostic: Diagnostic<FileId> = Diagnostic::new(highest_level.into()).with_message(format!(
129            "found {} issues: {}",
130            total_issues,
131            message_notes.join(", ")
132        ));
133
134        if suggestions > 0 {
135            diagnostic = diagnostic.with_notes(vec![format!("{} issues contain auto-fix suggestions", suggestions)]);
136        }
137
138        let mut ansi = Ansi::new(Vec::new());
139        let mut plain = NoColor::new(Vec::new());
140        let styled: &mut dyn term::WriteStyle = if use_colors { &mut ansi } else { &mut plain };
141        let files = DatabaseFiles::new(database, editor_url, &sources);
142        let mut renderer = term::Renderer::new(styled, codespan_config);
143        emit_diagnostic(&mut renderer, codespan_config, &files, &diagnostic)?;
144        writer.write_all(if use_colors { ansi.get_ref() } else { plain.get_ref() })?;
145    }
146
147    Ok(())
148}
149
150fn write_issues(
151    writer: &mut dyn Write,
152    issues: &[&Issue],
153    database: &ReadDatabase,
154    sources: &HashMap<FileId, Cow<'_, str>>,
155    editor_url: Option<&str>,
156    use_colors: bool,
157    config: &Config,
158) -> Result<(), ReportingError> {
159    #[cfg(not(target_arch = "wasm32"))]
160    if issues.len() >= 256 && rayon::current_num_threads() > 1 {
161        return render_chunks_in_order(
162            issues,
163            32,
164            4 * rayon::current_num_threads(),
165            |chunk| render_issues(chunk, database, sources, editor_url, use_colors, config),
166            |chunk| -> Result<(), ReportingError> {
167                writer.write_all(&chunk?)?;
168                Ok(())
169            },
170        );
171    }
172
173    for batch in issues.chunks(1024) {
174        writer.write_all(&render_issues(batch, database, sources, editor_url, use_colors, config)?)?;
175    }
176
177    Ok(())
178}
179
180fn render_issues(
181    issues: &[&Issue],
182    database: &ReadDatabase,
183    sources: &HashMap<FileId, Cow<'_, str>>,
184    editor_url: Option<&str>,
185    use_colors: bool,
186    config: &Config,
187) -> Result<Vec<u8>, Error> {
188    let mut ansi = Ansi::new(Vec::new());
189    let mut plain = NoColor::new(Vec::new());
190    let styled: &mut dyn term::WriteStyle = if use_colors { &mut ansi } else { &mut plain };
191    let files = DatabaseFiles::new(database, editor_url, sources);
192    let mut renderer = term::Renderer::new(styled, config);
193    let mut diagnostic = Diagnostic::new(Severity::Note);
194
195    for issue in issues {
196        if editor_url.is_some() {
197            if let Some(annotation) = issue.annotations.iter().find(|a| a.is_primary()) {
198                let file = files.file(annotation.span.file_id)?;
199                files.line_hint.set(Some(file.line_number(annotation.span.start.offset) + 1));
200                files.column_hint.set(Some(file.column_number(annotation.span.start.offset) + 1));
201            } else {
202                files.line_hint.set(None);
203                files.column_hint.set(None);
204            }
205        }
206
207        update_diagnostic(&mut diagnostic, issue);
208        emit_diagnostic(&mut renderer, config, &files, &diagnostic)?;
209    }
210
211    Ok(if use_colors { ansi.into_inner() } else { plain.into_inner() })
212}
213
214fn emit_diagnostic(
215    renderer: &mut term::Renderer<'_, '_>,
216    config: &Config,
217    files: &DatabaseFiles<'_>,
218    diagnostic: &Diagnostic<FileId>,
219) -> Result<(), Error> {
220    match config.display_style {
221        DisplayStyle::Rich => term::RichDiagnostic::new(diagnostic, config).render(files, renderer),
222        DisplayStyle::Medium => term::ShortDiagnostic::new(diagnostic, true).render(files, renderer),
223        DisplayStyle::Short => term::ShortDiagnostic::new(diagnostic, false).render(files, renderer),
224    }
225}
226
227struct DatabaseFiles<'db> {
228    database: &'db ReadDatabase,
229    editor_url: Option<&'db str>,
230    line_hint: Cell<Option<u32>>,
231    column_hint: Cell<Option<u32>>,
232    sources: &'db HashMap<FileId, Cow<'db, str>>,
233    last_file: Cell<Option<&'db File>>,
234}
235
236impl<'db> DatabaseFiles<'db> {
237    fn new(
238        database: &'db ReadDatabase,
239        editor_url: Option<&'db str>,
240        sources: &'db HashMap<FileId, Cow<'db, str>>,
241    ) -> Self {
242        DatabaseFiles {
243            database,
244            editor_url,
245            line_hint: Cell::new(None),
246            column_hint: Cell::new(None),
247            sources,
248            last_file: Cell::new(None),
249        }
250    }
251
252    fn file(&self, file_id: FileId) -> Result<&'db File, Error> {
253        if let Some(file) = self.last_file.get()
254            && file.id == file_id
255        {
256            return Ok(file);
257        }
258        let file = self.database.get_ref(&file_id).map_err(|_| Error::FileMissing)?;
259        self.last_file.set(Some(file));
260        Ok(file)
261    }
262}
263
264impl<'files> Files<'files> for DatabaseFiles<'_> {
265    type FileId = FileId;
266    type Name = Cow<'files, str>;
267    type Source = &'files str;
268
269    fn name(&'files self, file_id: FileId) -> Result<Cow<'files, str>, Error> {
270        let file = self.file(file_id)?;
271        let name = String::from_utf8_lossy(&file.name);
272
273        if let (Some(template), Some(path)) = (self.editor_url, file.path.as_ref()) {
274            let abs_path = path.display().to_string();
275            let line = self.line_hint.get().unwrap_or(1);
276            let column = self.column_hint.get().unwrap_or(1);
277
278            Ok(Cow::Owned(osc8_file_hyperlink(template, &abs_path, &name, line, column, &name)))
279        } else {
280            Ok(name)
281        }
282    }
283
284    fn source(&'files self, file_id: FileId) -> Result<&'files str, Error> {
285        self.sources.get(&file_id).map(AsRef::as_ref).ok_or(Error::FileMissing)
286    }
287
288    fn line_index(&self, file_id: FileId, byte_index: usize) -> Result<usize, Error> {
289        let file = self.file(file_id)?;
290
291        Ok(file.line_number(
292            byte_index.try_into().map_err(|_| Error::IndexTooLarge { given: byte_index, max: u32::MAX as usize })?,
293        ) as usize)
294    }
295
296    fn line_range(&self, file_id: FileId, line_index: usize) -> Result<Range<usize>, Error> {
297        let file = self.file(file_id)?;
298
299        codespan_line_range(&file.lines, file.size, line_index)
300    }
301}
302
303fn update_diagnostic(diagnostic: &mut Diagnostic<FileId>, issue: &Issue) {
304    diagnostic.severity = issue.level.into();
305    issue.message.as_ref().clone_into(&mut diagnostic.message);
306    diagnostic.code.clone_from(&issue.code);
307
308    for (index, annotation) in issue.annotations.iter().enumerate() {
309        if let Some(label) = diagnostic.labels.get_mut(index) {
310            label.style = annotation.kind.into();
311            label.file_id = annotation.span.file_id;
312            label.range = annotation.span.into();
313            if let Some(message) = &annotation.message {
314                message.as_ref().clone_into(&mut label.message);
315            } else {
316                label.message.clear();
317            }
318        } else {
319            diagnostic.labels.push(annotation.into());
320        }
321    }
322    diagnostic.labels.truncate(issue.annotations.len());
323
324    let note_count = issue.notes.len() + usize::from(issue.help.is_some()) + usize::from(issue.link.is_some());
325    diagnostic.notes.resize_with(note_count, String::new);
326    for (target, note) in diagnostic.notes.iter_mut().zip(&issue.notes) {
327        note.as_ref().clone_into(target);
328    }
329    let mut remaining = diagnostic.notes[issue.notes.len()..].iter_mut();
330    for (prefix, text) in [("Help: ", issue.help.as_deref()), ("See: ", issue.link.as_deref())] {
331        if let Some(text) = text
332            && let Some(target) = remaining.next()
333        {
334            target.clear();
335            target.push_str(prefix);
336            target.push_str(text);
337        }
338    }
339}
340
341fn codespan_line_start(lines: &[u32], size: u32, line_index: usize) -> Result<usize, Error> {
342    match line_index.cmp(&lines.len()) {
343        // The `Ordering::Less` arm guarantees `line_index < lines.len()`, so `get` is `Some`;
344        // a missing value here would mean a `Vec::len`/indexing inconsistency, so we fall back
345        // to `0` defensively rather than panicking.
346        Ordering::Less => Ok(lines.get(line_index).copied().unwrap_or(0) as usize),
347        Ordering::Equal => Ok(size as usize),
348        Ordering::Greater => Err(Error::LineTooLarge { given: line_index, max: lines.len() - 1 }),
349    }
350}
351
352fn codespan_line_range(lines: &[u32], size: u32, line_index: usize) -> Result<Range<usize>, Error> {
353    let line_start = codespan_line_start(lines, size, line_index)?;
354    let next_line_start = codespan_line_start(lines, size, line_index + 1)?;
355
356    Ok(line_start..next_line_start)
357}
358
359impl From<AnnotationKind> for LabelStyle {
360    fn from(kind: AnnotationKind) -> LabelStyle {
361        match kind {
362            AnnotationKind::Primary => LabelStyle::Primary,
363            AnnotationKind::Secondary => LabelStyle::Secondary,
364        }
365    }
366}
367
368impl From<Annotation> for Label<FileId> {
369    fn from(annotation: Annotation) -> Label<FileId> {
370        let mut label = Label::new(annotation.kind.into(), annotation.span.file_id, annotation.span);
371
372        if let Some(message) = annotation.message {
373            label.message = message.into_owned();
374        }
375
376        label
377    }
378}
379
380impl From<&Annotation> for Label<FileId> {
381    fn from(annotation: &Annotation) -> Label<FileId> {
382        let mut label = Label::new(annotation.kind.into(), annotation.span.file_id, annotation.span);
383
384        if let Some(message) = &annotation.message {
385            message.as_ref().clone_into(&mut label.message);
386        }
387
388        label
389    }
390}
391
392impl From<Level> for Severity {
393    fn from(level: Level) -> Severity {
394        match level {
395            Level::Note => Severity::Note,
396            Level::Help => Severity::Help,
397            Level::Warning => Severity::Warning,
398            Level::Error => Severity::Error,
399        }
400    }
401}
402
403impl From<Issue> for Diagnostic<FileId> {
404    fn from(issue: Issue) -> Diagnostic<FileId> {
405        let mut diagnostic = Diagnostic::new(issue.level.into()).with_message(issue.message);
406
407        if let Some(code) = issue.code {
408            diagnostic.code = Some(code);
409        }
410
411        for annotation in issue.annotations {
412            diagnostic.labels.push(annotation.into());
413        }
414
415        for note in issue.notes {
416            diagnostic.notes.push(note.into_owned());
417        }
418
419        if let Some(help) = issue.help {
420            diagnostic.notes.push(format!("Help: {help}"));
421        }
422
423        if let Some(link) = issue.link {
424            diagnostic.notes.push(format!("See: {link}"));
425        }
426
427        diagnostic
428    }
429}
430
431impl From<&Issue> for Diagnostic<FileId> {
432    fn from(issue: &Issue) -> Diagnostic<FileId> {
433        let mut diagnostic = Diagnostic::new(issue.level.into()).with_message(issue.message.clone());
434
435        if let Some(code) = &issue.code {
436            diagnostic.code = Some(code.clone());
437        }
438
439        for annotation in &issue.annotations {
440            diagnostic.labels.push(annotation.into());
441        }
442
443        for note in &issue.notes {
444            diagnostic.notes.push(note.to_string());
445        }
446
447        if let Some(help) = &issue.help {
448            diagnostic.notes.push(format!("Help: {help}"));
449        }
450
451        if let Some(link) = &issue.link {
452            diagnostic.notes.push(format!("See: {link}"));
453        }
454
455        diagnostic
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    use std::borrow::Cow;
462    use std::path::Path;
463    use std::path::PathBuf;
464
465    use codespan_reporting::files::Files;
466    use foldhash::HashMap;
467    use mago_database::Database;
468    use mago_database::DatabaseConfiguration;
469    use mago_database::ReadDatabase;
470    use mago_database::file::File;
471    use mago_database::file::FileId;
472    use mago_database::file::FileType;
473
474    use super::DatabaseFiles;
475
476    fn fixture() -> (ReadDatabase, FileId) {
477        let file = File::new(
478            Cow::Borrowed(b"src/Foo.php"),
479            FileType::Host,
480            Some(PathBuf::from("/workspace/src/Foo.php")),
481            Cow::Borrowed(b"<?php\n$x = '\xc3\xa9';\n// \xff\n"),
482        );
483        let file_id = file.id;
484        let configuration =
485            DatabaseConfiguration::new(Path::new("/workspace"), vec![], vec![], vec![], vec![]).into_static();
486
487        (Database::single(file, configuration).read_only(), file_id)
488    }
489
490    #[test]
491    fn editor_url_uses_the_logical_name_for_the_relative_file_placeholder() {
492        let (database, file_id) = fixture();
493        let sources = HashMap::default();
494        let files = DatabaseFiles::new(&database, Some("editor://%rel_file%:%line%:%column%"), &sources);
495        let Ok(name) = Files::name(&files, file_id) else {
496            panic!("file should exist");
497        };
498
499        assert_eq!(name, "\x1b]8;;editor://src/Foo.php:1:1\x1b\\src/Foo.php\x1b]8;;\x1b\\",);
500    }
501}