annotate_snippets/renderer/no_graphics.rs
1use alloc::borrow::{Cow, ToOwned};
2use alloc::string::{String, ToString};
3use alloc::vec::Vec;
4use core::cmp::Reverse;
5use core::fmt::{self, Write};
6
7use super::graphics::{Hyperlink, MessageOrTitle, TitleStyle, str_width};
8use super::preprocess::{Preprocessed, PreprocessedElement, PreprocessedGroup};
9use super::{ElementStyle, Stylesheet, normalize_whitespace};
10use crate::renderer::graphics::ANONYMIZED_LINE_NUM;
11use crate::renderer::source_map::PatchKind;
12use crate::{AnnotationKind, Id, Renderer, Report};
13
14/// Render all errors from a `Report` as text only.
15///
16/// We will render output as follows:
17///
18/// ```text
19/// error EXXXX: main message
20/// at $DIR/file.ext:LL:CC: span label
21/// on line LL, column KK: span label
22/// note: note message
23/// at $DIR/file.ext:LL:CC
24/// help: suggestion message
25/// on line LL, add `suggestion`
26/// ```
27pub(crate) fn render_no_graphics(
28 renderer: &Renderer,
29 groups: Report<'_>,
30) -> Result<String, fmt::Error> {
31 let mut output = String::new();
32 let Preprocessed {
33 max_line_num: _,
34 report_primary_path,
35 groups,
36 } = Preprocessed::preprocess(groups);
37
38 for PreprocessedGroup {
39 group,
40 elements,
41 primary_path,
42 max_depth: _,
43 } in groups
44 {
45 if let Some(title) = &group.title {
46 if !output.is_empty() {
47 writeln!(output)?;
48 }
49 let title_style = if title.allows_styling {
50 TitleStyle::Secondary
51 } else {
52 TitleStyle::Primary
53 };
54 render_title(
55 title,
56 &mut output,
57 title_style,
58 &renderer.stylesheet,
59 renderer.hyperlink,
60 )?;
61 }
62
63 let mut last_suggestion_path = None;
64 let mut suggestion_count = 0;
65
66 let mut message_iter = elements.into_iter().peekable();
67 while let Some(section) = message_iter.next() {
68 match section {
69 PreprocessedElement::Message(message) => {
70 last_suggestion_path = None;
71 if !output.is_empty() {
72 writeln!(output)?;
73 }
74 render_title(
75 message,
76 &mut output,
77 TitleStyle::Message,
78 &renderer.stylesheet,
79 renderer.hyperlink,
80 )?;
81 }
82 PreprocessedElement::Cause((snippet, sm, _)) => {
83 last_suggestion_path = None;
84
85 let mut annotations = snippet
86 .markers
87 .iter()
88 .filter(|ann| !matches!(ann.kind, AnnotationKind::Visible))
89 .collect::<Vec<_>>();
90 annotations.sort_by_key(|a| (Reverse(a.kind.is_primary()), a.span.start));
91 if annotations.is_empty() {
92 if !output.is_empty() {
93 writeln!(output)?;
94 }
95 // We have a diagnostic with no span labels, but we should show *some*
96 // position. We use the snippet start to provide that minimal context.
97 write!(output, " ")?;
98 render_path(
99 &mut output,
100 snippet.path.as_deref(),
101 snippet.section.as_deref(),
102 Some(snippet.line_start),
103 None,
104 renderer.anonymized_origin_line_numbers,
105 )?;
106 } else {
107 for (i, annotation) in annotations.iter().enumerate() {
108 let label = annotation.label.as_ref().filter(|s| !s.is_empty());
109 if i > 0 && label.is_none() {
110 continue;
111 }
112 let (lo, hi) =
113 sm.span_to_locations(annotation.span.start..annotation.span.end);
114
115 if !output.is_empty() {
116 writeln!(output)?;
117 }
118 // Indent subsequent labels under the first label's file path.
119 // Without a path, keep all labels at the same indentation.
120 let padding = if i > 0 && snippet.path.is_some() {
121 " "
122 } else {
123 " "
124 };
125 write!(output, "{padding}")?;
126
127 if i == 0
128 && let Some(path) = &snippet.path
129 {
130 // `at $DIR/file.txt:LL:CC: label`
131 // ^^^^^^^^^^^^^^^^^^^^^^
132 render_path(
133 &mut output,
134 Some(path),
135 snippet.section.as_deref(),
136 Some(lo.line),
137 Some(lo.char + 1),
138 renderer.anonymized_origin_line_numbers,
139 )?;
140 if lo.line != hi.line {
141 // This is a multiline highlight, so we mention both the start and the
142 // end. `LL:CC to MM:DD`
143 // ^^^^^^^^^
144 write!(output, " to {}:{}", hi.line, hi.char + 1)?;
145 }
146 } else {
147 let col = if let Some(line) = sm.get_line(lo.line)
148 && line.chars().take(lo.char).all(|c| c.is_whitespace())
149 {
150 // Everything before the span is whitespace, mentioning the column
151 // doesn't add information.
152 None
153 } else {
154 Some(lo.char + 1)
155 };
156 render_path(
157 &mut output,
158 None,
159 snippet.section.as_deref(),
160 Some(lo.line),
161 col,
162 renderer.anonymized_origin_line_numbers,
163 )?;
164 if lo.line != hi.line {
165 // This is a multiline highlight, so we mention both the start and the
166 // end. `line LL, column CC to line MM, column DD`
167 // ^^^^^^^^^^^^^^^^^^^^^^
168 write!(output, " to line {}", hi.line)?;
169 if let Some(line) = sm.get_line(hi.line)
170 && let Some(post) = line.get(hi.char..)
171 && post.chars().all(|c| c.is_whitespace())
172 {
173 // Everything after the span is whitespace, mentioning the
174 // column doesn't add information.
175 } else {
176 write!(output, ", column {}", hi.char + 1)?;
177 }
178 }
179 }
180
181 if let Some(label) = label {
182 // If the span has a label, we render it to the right of the position
183 // information.
184 // `at $DIR/file.txt:LL:CC: this is the label`
185 // ^^^^^^^^^^^^^^^^^^^
186 write!(output, ": {label}")?;
187 }
188 }
189 }
190 }
191 PreprocessedElement::Suggestion((
192 suggestion,
193 sm,
194 spliced_lines,
195 _display_suggestion,
196 )) => {
197 if spliced_lines.patches.is_empty() {
198 // We have a suggestion with no patches, we don't render anything.
199 continue;
200 }
201
202 let matches_previous_suggestion =
203 last_suggestion_path == Some(suggestion.path.as_ref());
204
205 suggestion_count = if matches_previous_suggestion {
206 suggestion_count + 1
207 } else {
208 1
209 };
210
211 let matches_next_suggestion = matches!(
212 message_iter.peek(),
213 Some(PreprocessedElement::Suggestion((next, ..)))
214 if next.path.as_ref() == suggestion.path.as_ref()
215 );
216
217 // We only include the file path when it is different from
218 // the previous suggestion's path, or the primary path
219 //
220 // `at $DIR/file.txt:LL:CC: label`
221 // ^^^^^^^^^^^^^^^^^
222 let previous_path =
223 last_suggestion_path.unwrap_or(primary_path.or(report_primary_path));
224 let path = if suggestion.path.as_ref() != previous_path
225 && let Some(path) = suggestion.path.as_ref()
226 {
227 Some(path.as_ref())
228 } else {
229 None
230 };
231
232 let padding = if matches_previous_suggestion || matches_next_suggestion {
233 if !output.is_empty() {
234 writeln!(output)?;
235 }
236 write!(output, " option {suggestion_count}")?;
237 " "
238 } else {
239 " "
240 };
241
242 for patch in spliced_lines.patches.iter() {
243 let (lo, hi) = sm.span_to_locations(patch.span());
244
245 let has_replacement = !patch.replacement().trim().is_empty();
246 let patch_kind = patch.kind();
247 if !output.is_empty() {
248 writeln!(output)?;
249 }
250 write!(output, "{padding}")?;
251
252 if has_replacement && !matches!(patch_kind, Some(PatchKind::Insertion)) {
253 render_path(
254 &mut output,
255 path,
256 suggestion.section.as_deref(),
257 Some(lo.line),
258 Some(lo.char + 1),
259 renderer.anonymized_origin_line_numbers,
260 )?;
261 if lo.line != hi.line {
262 let line = if renderer.anonymized_origin_line_numbers {
263 ANONYMIZED_LINE_NUM.to_owned()
264 } else {
265 hi.line.to_string()
266 };
267 write!(output, " to line {line}, column {}", hi.char + 1)?;
268 } else {
269 write!(output, " to column {}", hi.char + 1)?;
270 }
271 } else {
272 let col = if lo.line == hi.line
273 && let Some(line) = sm.get_line(lo.line)
274 && let Some(pre) = line.get(..lo.byte)
275 && pre.chars().all(|c| c.is_whitespace())
276 && let Some(post) = line.get(hi.byte..)
277 && (patch.replacement().lines().count() > 1
278 || post.chars().all(|c| c.is_whitespace()))
279 {
280 // We are changing the whole text in the line, no need to mention the
281 // column.
282 None
283 } else {
284 Some(lo.char + 1)
285 };
286 render_path(
287 &mut output,
288 path,
289 suggestion.section.as_deref(),
290 Some(lo.line),
291 col,
292 renderer.anonymized_origin_line_numbers,
293 )?;
294 }
295
296 if has_replacement {
297 let action = if matches!(patch_kind, Some(PatchKind::Insertion)) {
298 "add"
299 } else {
300 "replace with"
301 };
302 write!(output, " {action}: ")?;
303
304 let st = ElementStyle::Addition
305 .color_spec(&crate::Level::NOTE, &renderer.stylesheet);
306
307 write!(
308 output,
309 "{st}{}{st:#}",
310 normalize_whitespace(patch.replacement().trim_end_matches('\n'))
311 )?;
312 }
313 }
314 last_suggestion_path = Some(suggestion.path.as_ref());
315 }
316 PreprocessedElement::Origin(origin) => {
317 last_suggestion_path = None;
318 if !output.is_empty() {
319 writeln!(output)?;
320 }
321 write!(output, " ")?;
322 render_path(
323 &mut output,
324 origin.path.as_deref(),
325 origin.section.as_deref(),
326 origin.line,
327 origin.char_column,
328 renderer.anonymized_origin_line_numbers,
329 )?;
330 }
331 PreprocessedElement::Padding(_) => {
332 last_suggestion_path = None;
333 }
334 }
335 }
336 }
337
338 Ok(output)
339}
340
341/// Render the main message line for a diagnostic
342///
343/// This will print out:
344///
345/// ```text
346/// LEVEL CODE: message
347/// ```
348/// like the following:
349/// ```text
350/// error E0308: mismatched types
351/// ```
352fn render_title(
353 title: &dyn MessageOrTitle,
354 buffer: &mut String,
355 title_style: TitleStyle,
356 stylesheet: &Stylesheet,
357 hyperlink: bool,
358) -> Result<(), fmt::Error> {
359 let (label_style, title_element_style) = match title_style {
360 TitleStyle::Primary => (
361 ElementStyle::Level(title.level().level),
362 ElementStyle::MainHeaderMsg,
363 ),
364 TitleStyle::Secondary => (
365 ElementStyle::Level(title.level().level),
366 ElementStyle::HeaderMsg,
367 ),
368 TitleStyle::Message => (ElementStyle::MainHeaderMsg, ElementStyle::NoStyle),
369 };
370 let label_style = label_style.color_spec(title.level(), stylesheet);
371 let title_element_style = title_element_style.color_spec(title.level(), stylesheet);
372
373 let mut label_width = 0;
374 let level_is_visible = title.level().name != Some(None);
375 if level_is_visible || title.id().is_some() {
376 if title_style == TitleStyle::Message {
377 write!(buffer, " ")?;
378 label_width += 1;
379 }
380
381 if level_is_visible {
382 // error EXXXX: message
383 // ^^^^^
384 write!(buffer, "{}{}{0:#}", label_style, title.level().as_str(),)?;
385 label_width += str_width(title.level().as_str());
386 }
387
388 if let Some(Id { id: Some(id), url }) = &title.id() {
389 let url = url
390 .as_deref()
391 .filter(|_| hyperlink)
392 .map(Hyperlink::with_url)
393 .unwrap_or_default();
394
395 if level_is_visible {
396 // error EXXXX: message
397 // ^
398 write!(buffer, " ")?;
399 label_width += 1;
400 }
401 // error EXXXX: message
402 // ^^^^^
403 write!(buffer, "{label_style}{url}{id}{url:#}{label_style:#}")?;
404 label_width += str_width(id);
405 }
406
407 if let Some(footnote_marker) = title.footnote_marker() {
408 let descr = " footnote ";
409 label_width += str_width(descr);
410 write!(
411 buffer,
412 "{label_style} {descr}{footnote_marker}{label_style:#}"
413 )?;
414 label_width += str_width(footnote_marker);
415 }
416
417 // error EXXXX: message
418 // ^
419 write!(buffer, "{title_element_style}: {title_element_style:#}")?;
420 label_width += 2;
421 }
422 let padding = " ".repeat(label_width);
423
424 // error EXXXX: message
425 // ^^^^^^^
426 let (title_str, st) = if title.allows_styling() {
427 (
428 Cow::Borrowed(title.text()),
429 ElementStyle::NoStyle.color_spec(title.level(), stylesheet),
430 )
431 } else {
432 (normalize_whitespace(title.text()), title_element_style)
433 };
434 for (i, text) in title_str.split('\n').enumerate() {
435 if i != 0 {
436 write!(buffer, "\n{padding}")?;
437 }
438 write!(buffer, "{st}{text}{st:#}")?;
439 }
440 Ok(())
441}
442
443/// Print out a file position optimized for the data available.
444///
445/// When the `path` is available, we print `at PATH:LL:CC`, which is detected by terminals and
446/// editors as a path to a specific place in a file. A section is included between the path and
447/// line number, or described separately when there is no path.
448fn render_path(
449 output: &mut String,
450 path: Option<&str>,
451 section: Option<&str>,
452 line: Option<usize>,
453 col: Option<usize>,
454 anonymized_origin_line_numbers: bool,
455) -> Result<(), fmt::Error> {
456 let line = line.map(|l| {
457 if anonymized_origin_line_numbers {
458 ANONYMIZED_LINE_NUM.to_owned()
459 } else {
460 l.to_string()
461 }
462 });
463
464 if let Some(path) = path {
465 // `at $DIR/file.txt`
466 write!(output, "at {path}")?;
467 if let Some(section) = section {
468 write!(output, ":{section}")?;
469 }
470 if let Some(line) = line {
471 // `at $DIR/file.txt:LL`
472 write!(output, ":{line}")?;
473 if let Some(col) = col {
474 // `at $DIR/file.txt:LL:CC`
475 write!(output, ":{col}")?;
476 }
477 }
478 } else if let Some(line) = line {
479 // We are not printing the path, so instead we show
480 // ` on line LL`
481 if let Some(section) = section {
482 write!(output, "in {section}, ")?;
483 }
484 write!(output, "on line {line}")?;
485 if let Some(col) = col {
486 // ` on line LL, column CC`.
487 write!(output, ", column {col}")?;
488 }
489 }
490 Ok(())
491}