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