1use alloc::{
2 format,
3 string::{String, ToString},
4 vec::Vec,
5};
6use core::{error::Error, fmt};
7
8use annotate_snippets::{
9 Annotation, AnnotationKind, Group, Level, Origin, Patch, Renderer, Snippet,
10 renderer::DecorStyle,
11};
12
13use crate::{
14 Applicability, DiagnosticSnapshot, LabelStyle, LayeredSourceProvider, LineColumn, NoteKind,
15 OwnedSuggestion, PreparedDiagnostic, ResolvedSource, Severity, SourceId, SourceKey,
16 SourceRevision, SourceSpan, TextRange, source::SourceResolveError,
17};
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub struct RenderConfig {
22 pub styled: bool,
23 pub unicode: bool,
24 pub hyperlinks: bool,
25 pub width: usize,
26 pub short: bool,
27 pub anonymize_line_numbers: bool,
28 pub fold: bool,
31}
32
33impl RenderConfig {
34 pub const DEFAULT: Self = Self {
35 styled: false,
36 unicode: false,
37 hyperlinks: false,
38 width: 140,
39 short: false,
40 anonymize_line_numbers: false,
41 fold: false,
42 };
43}
44
45impl Default for RenderConfig {
46 fn default() -> Self {
47 Self::DEFAULT
48 }
49}
50
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub enum RenderError {
53 InvalidWidth {
54 width: usize,
55 },
56 MissingSource(SourceKey),
57 ProviderIdMismatch {
58 source: SourceKey,
59 returned: SourceId,
60 },
61 ProviderByteLengthMismatch {
62 source: SourceKey,
63 declared: u32,
64 actual: usize,
65 },
66 MissingSourceText(SourceKey),
67 StaleRevision {
68 source: SourceKey,
69 requested: SourceRevision,
70 current: Option<SourceRevision>,
71 },
72 ReversedRange {
73 source: SourceKey,
74 start: u32,
75 end: u32,
76 },
77 OutOfBounds {
78 source: SourceKey,
79 range: TextRange,
80 byte_len: u32,
81 },
82 InvalidUtf8Boundary {
83 source: SourceKey,
84 offset: u32,
85 },
86 MetadataLocationUnavailable {
87 source: SourceKey,
88 offset: u32,
89 },
90 MetadataCoordinateOverflow {
91 source: SourceKey,
92 location: LineColumn,
93 },
94 EmptySuggestion {
95 index: usize,
96 },
97 OverlappingEdits {
98 source: SourceKey,
99 previous: TextRange,
100 next: TextRange,
101 },
102 AmbiguousInsertions {
103 source: SourceKey,
104 offset: u32,
105 },
106 MultiplePrimaryLabels {
107 count: usize,
108 },
109 InvalidDocumentationUrl,
110}
111
112impl RenderError {
113 pub const fn category(&self) -> &'static str {
114 match self {
115 Self::InvalidWidth { .. } => "invalid render width",
116 Self::MissingSource(_) => "missing source",
117 Self::ProviderIdMismatch { .. } => "source provider ID mismatch",
118 Self::ProviderByteLengthMismatch { .. } => "source provider length mismatch",
119 Self::MissingSourceText(_) => "missing source text",
120 Self::StaleRevision { .. } => "stale source revision",
121 Self::ReversedRange { .. } => "reversed source range",
122 Self::OutOfBounds { .. } => "source range out of bounds",
123 Self::InvalidUtf8Boundary { .. } => "invalid UTF-8 boundary",
124 Self::MetadataLocationUnavailable { .. } => "missing source location metadata",
125 Self::MetadataCoordinateOverflow { .. } => "source location metadata overflow",
126 Self::EmptySuggestion { .. } => "empty suggestion",
127 Self::OverlappingEdits { .. } => "overlapping edits",
128 Self::AmbiguousInsertions { .. } => "ambiguous insertions",
129 Self::MultiplePrimaryLabels { .. } => "multiple primary labels",
130 Self::InvalidDocumentationUrl => "invalid documentation URL",
131 }
132 }
133}
134
135impl fmt::Display for RenderError {
136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137 match self {
138 Self::InvalidWidth { width } => {
139 write!(formatter, "render width {width} is outside 1..=65535")
140 }
141 Self::MissingSource(source) => write!(formatter, "source {source:?} is unavailable"),
142 Self::ProviderIdMismatch { source, returned } => {
143 write!(formatter, "provider returned {returned:?} for {source:?}")
144 }
145 Self::ProviderByteLengthMismatch {
146 source,
147 declared,
148 actual,
149 } => write!(
150 formatter,
151 "provider source {source:?} declares {declared} bytes but contains {actual}"
152 ),
153 Self::MissingSourceText(source) => {
154 write!(formatter, "source text for {source:?} is unavailable")
155 }
156 Self::StaleRevision {
157 source,
158 requested,
159 current,
160 } => write!(
161 formatter,
162 "source {source:?} revision {requested:?} does not match {current:?}"
163 ),
164 Self::ReversedRange { source, start, end } => {
165 write!(formatter, "source {source:?} range {start}..{end} is reversed")
166 }
167 Self::OutOfBounds {
168 source,
169 range,
170 byte_len,
171 } => write!(
172 formatter,
173 "source {source:?} range {}..{} exceeds {byte_len} bytes",
174 range.start(),
175 range.end()
176 ),
177 Self::InvalidUtf8Boundary { source, offset } => {
178 write!(formatter, "source {source:?} offset {offset} splits UTF-8")
179 }
180 Self::MetadataLocationUnavailable { source, offset } => {
181 write!(formatter, "source {source:?} has no location metadata for offset {offset}")
182 }
183 Self::MetadataCoordinateOverflow { source, location } => write!(
184 formatter,
185 "source {source:?} location {}:{} does not fit the renderer",
186 location.line(),
187 location.column()
188 ),
189 Self::EmptySuggestion { index } => {
190 write!(formatter, "suggestion {index} has no edits")
191 }
192 Self::OverlappingEdits {
193 source,
194 previous,
195 next,
196 } => write!(
197 formatter,
198 "source {source:?} edits {}..{} and {}..{} overlap",
199 previous.start(),
200 previous.end(),
201 next.start(),
202 next.end()
203 ),
204 Self::AmbiguousInsertions { source, offset } => {
205 write!(formatter, "source {source:?} has ambiguous insertions at {offset}")
206 }
207 Self::MultiplePrimaryLabels { count } => {
208 write!(formatter, "snapshot contains {count} primary labels")
209 }
210 Self::InvalidDocumentationUrl => {
211 formatter.write_str("documentation URL is not a safe HTTP(S) URL")
212 }
213 }
214 }
215}
216
217impl Error for RenderError {}
218
219#[derive(Clone, Copy, Debug, Eq, PartialEq)]
221pub struct AnnotateRenderer {
222 pub config: RenderConfig,
223}
224
225impl AnnotateRenderer {
226 pub const fn new(config: RenderConfig) -> Self {
227 Self { config }
228 }
229
230 pub fn render(&self, diagnostic: &PreparedDiagnostic<'_>) -> Result<String, RenderError> {
231 if !(1..=u16::MAX as usize).contains(&self.config.width) {
232 return Err(RenderError::InvalidWidth {
233 width: self.config.width,
234 });
235 }
236
237 let mut preflight = Preflight::new(diagnostic.sources, self.config);
238 preflight.collect(&diagnostic.snapshot)?;
239 preflight.resolve_sources()?;
240 preflight.validate(&diagnostic.snapshot)?;
241
242 let mut groups = Vec::new();
243 preflight.lower(&diagnostic.snapshot, GroupRole::Root, &mut groups)?;
244 let renderer = if self.config.styled {
245 Renderer::styled()
246 } else {
247 Renderer::plain()
248 }
249 .decor_style(if self.config.unicode {
250 DecorStyle::Unicode
251 } else {
252 DecorStyle::Ascii
253 })
254 .term_width(self.config.width)
255 .short_message(self.config.short)
256 .hyperlink(self.config.hyperlinks)
257 .anonymized_snippet_line_numbers(self.config.anonymize_line_numbers);
258
259 let output = renderer.render(&groups);
260 Ok(sanitize_rendered_output(
261 &output,
262 self.config.styled,
263 self.config.hyperlinks,
264 &preflight.approved_urls,
265 ))
266 }
267}
268
269impl Default for AnnotateRenderer {
270 fn default() -> Self {
271 Self::new(RenderConfig::default())
272 }
273}
274
275struct ResolvedSlot<'a> {
276 resolved: ResolvedSource<'a>,
277 display_name: String,
278}
279
280struct Preflight<'a> {
281 sources: LayeredSourceProvider<'a>,
282 config: RenderConfig,
283 keys: Vec<SourceKey>,
284 slots: Vec<ResolvedSlot<'a>>,
285 approved_urls: Vec<String>,
286}
287
288impl<'a> Preflight<'a> {
289 fn new(sources: LayeredSourceProvider<'a>, config: RenderConfig) -> Self {
290 Self {
291 sources,
292 config,
293 keys: Vec::new(),
294 slots: Vec::new(),
295 approved_urls: Vec::new(),
296 }
297 }
298
299 fn collect(&mut self, snapshot: &DiagnosticSnapshot) -> Result<(), RenderError> {
300 for label in &snapshot.labels {
301 push_unique(&mut self.keys, label.span.source());
302 }
303 for suggestion in &snapshot.suggestions {
304 for edit in &suggestion.edits {
305 push_unique(&mut self.keys, edit.span.source());
306 }
307 }
308 if self.config.hyperlinks
309 && let Some(url) =
310 snapshot.descriptor.and_then(|descriptor| descriptor.documentation_url)
311 {
312 if !valid_documentation_url(url) {
313 return Err(RenderError::InvalidDocumentationUrl);
314 }
315 if !self.approved_urls.iter().any(|approved| approved == url) {
316 self.approved_urls.push(url.to_string());
317 }
318 }
319 if let Some(source) = snapshot.diagnostic_source.as_deref() {
320 self.collect(source)?;
321 }
322 for related in &snapshot.related {
323 self.collect(related)?;
324 }
325 Ok(())
326 }
327
328 fn resolve_sources(&mut self) -> Result<(), RenderError> {
329 for key in &self.keys {
330 let resolved = self
331 .sources
332 .resolve_checked(*key)
333 .map_err(|error| map_source_error(*key, error))?;
334 self.slots.push(ResolvedSlot {
335 display_name: normalize_display_text(resolved.source.display_name),
336 resolved,
337 });
338 }
339 disambiguate_display_names(&mut self.slots);
340 Ok(())
341 }
342
343 fn validate(&self, snapshot: &DiagnosticSnapshot) -> Result<(), RenderError> {
344 select_primary(snapshot)?;
345 for label in &snapshot.labels {
346 self.validate_span(label.span)?;
347 }
348 for (index, suggestion) in snapshot.suggestions.iter().enumerate() {
349 self.validate_suggestion(index, suggestion)?;
350 }
351 if let Some(source) = snapshot.diagnostic_source.as_deref() {
352 self.validate(source)?;
353 }
354 for related in &snapshot.related {
355 self.validate(related)?;
356 }
357 Ok(())
358 }
359
360 fn validate_span(&self, span: SourceSpan) -> Result<(), RenderError> {
361 let range = span.range();
362 if range.start() > range.end() {
363 return Err(RenderError::ReversedRange {
364 source: span.source(),
365 start: range.start(),
366 end: range.end(),
367 });
368 }
369 let slot = self.slot(span.source());
370 if let Some(requested) = span.revision()
371 && slot.resolved.source.revision != Some(requested)
372 {
373 return Err(RenderError::StaleRevision {
374 source: span.source(),
375 requested,
376 current: slot.resolved.source.revision,
377 });
378 }
379 if range.end() > slot.resolved.source.byte_len {
380 return Err(RenderError::OutOfBounds {
381 source: span.source(),
382 range,
383 byte_len: slot.resolved.source.byte_len,
384 });
385 }
386 if let Some(text) = slot.resolved.source.text {
387 for offset in [range.start(), range.end()] {
388 let offset_usize =
389 usize::try_from(offset).map_err(|_| RenderError::OutOfBounds {
390 source: span.source(),
391 range,
392 byte_len: slot.resolved.source.byte_len,
393 })?;
394 if !text.is_char_boundary(offset_usize) {
395 return Err(RenderError::InvalidUtf8Boundary {
396 source: span.source(),
397 offset,
398 });
399 }
400 }
401 } else {
402 for offset in [range.start(), range.end()] {
403 let _location = self.sources.line_column(span.source(), offset).ok_or(
404 RenderError::MetadataLocationUnavailable {
405 source: span.source(),
406 offset,
407 },
408 )?;
409 }
410 }
411 Ok(())
412 }
413
414 fn validate_suggestion(
415 &self,
416 index: usize,
417 suggestion: &OwnedSuggestion,
418 ) -> Result<(), RenderError> {
419 if suggestion.edits.is_empty() {
420 return Err(RenderError::EmptySuggestion { index });
421 }
422 for edit in &suggestion.edits {
423 self.validate_span(edit.span)?;
424 if self.slot(edit.span.source()).resolved.source.text.is_none() {
425 return Err(RenderError::MissingSourceText(edit.span.source()));
426 }
427 }
428
429 let mut keys = Vec::new();
430 for edit in &suggestion.edits {
431 push_unique(&mut keys, edit.span.source());
432 }
433 for key in keys {
434 let mut ranges: Vec<(TextRange, usize)> = suggestion
435 .edits
436 .iter()
437 .enumerate()
438 .filter(|(_, edit)| edit.span.source() == key)
439 .map(|(index, edit)| (edit.span.range(), index))
440 .collect();
441 ranges.sort_by_key(|(range, index)| (range.start(), range.end(), *index));
442 for pair in ranges.windows(2) {
443 let previous = pair[0].0;
444 let next = pair[1].0;
445 if previous.is_empty() && next.is_empty() && previous.start() == next.start() {
446 return Err(RenderError::AmbiguousInsertions {
447 source: key,
448 offset: previous.start(),
449 });
450 }
451 if next.start() < previous.end() {
452 return Err(RenderError::OverlappingEdits {
453 source: key,
454 previous,
455 next,
456 });
457 }
458 }
459 }
460 Ok(())
461 }
462
463 fn lower(
464 &self,
465 snapshot: &DiagnosticSnapshot,
466 role: GroupRole,
467 groups: &mut Vec<Group<'a>>,
468 ) -> Result<(), RenderError> {
469 let primary_index = select_primary(snapshot)?;
470 let level = severity_level(snapshot.severity);
471 let title_text = match role {
472 GroupRole::Root => normalize_display_text(&snapshot.message),
473 GroupRole::DiagnosticSource => {
474 format!("caused by: {}", normalize_display_text(&snapshot.message))
475 }
476 GroupRole::Related => {
477 format!("related: {}", normalize_display_text(&snapshot.message))
478 }
479 };
480 let mut title = match role {
481 GroupRole::Root => level.clone().primary_title(title_text),
482 GroupRole::DiagnosticSource | GroupRole::Related => {
483 level.clone().secondary_title(title_text)
484 }
485 };
486 if let Some(code) = &snapshot.code {
487 let code = normalize_display_text(&format!("{}/{}", code.namespace, code.code));
488 title = title.id(code);
489 if self.config.hyperlinks
490 && let Some(url) =
491 snapshot.descriptor.and_then(|descriptor| descriptor.documentation_url)
492 {
493 title = title.id_url(url);
494 }
495 }
496 let mut group = Group::with_title(title);
497
498 let keys = ordered_label_keys(snapshot, primary_index);
499 for key in keys {
500 let slot = self.slot(key);
501 if let Some(text) = slot.resolved.source.text {
502 let mut snippet = Snippet::<Annotation<'a>>::source(text)
503 .path(slot.display_name.clone())
504 .fold(self.config.fold);
505 for (index, label) in snapshot
506 .labels
507 .iter()
508 .enumerate()
509 .filter(|(_, label)| label.span.source() == key)
510 {
511 let kind = if Some(index) == primary_index {
512 AnnotationKind::Primary
513 } else {
514 AnnotationKind::Context
515 };
516 let range = label.span.range().into_slice_index();
517 let annotation = kind
518 .span(range)
519 .label(label.message.as_deref().map(normalize_display_text));
520 snippet = snippet.annotation(annotation);
521 }
522 group = group.element(snippet);
523 } else {
524 let first = snapshot
525 .labels
526 .iter()
527 .find(|label| label.span.source() == key)
528 .expect("label key was collected from a label");
529 let first_location = self
530 .sources
531 .line_column(key, first.span.range().start())
532 .ok_or(RenderError::MetadataLocationUnavailable {
533 source: key,
534 offset: first.span.range().start(),
535 })?;
536 let line = first_location.line().to_usize();
537 let column = first_location.column().to_usize();
538 group = group.element(
539 Origin::path(slot.display_name.clone()).line(line).char_column(column),
540 );
541 for (index, label) in snapshot
542 .labels
543 .iter()
544 .enumerate()
545 .filter(|(_, label)| label.span.source() == key)
546 {
547 let location = self
548 .sources
549 .line_column(key, label.span.range().start())
550 .ok_or(RenderError::MetadataLocationUnavailable {
551 source: key,
552 offset: label.span.range().start(),
553 })?;
554 let role = if Some(index) == primary_index {
555 "primary"
556 } else {
557 "context"
558 };
559 let message = label.message.as_deref().unwrap_or("location");
560 group = group.element(Level::NOTE.message(normalize_display_text(&format!(
561 "{role} at {}:{}:{}: {message}",
562 slot.display_name,
563 location.line(),
564 location.column()
565 ))));
566 }
567 }
568 }
569
570 for context in &snapshot.contexts {
571 group = group.element(
572 Level::NOTE.message(normalize_display_text(&format!("context: {context}"))),
573 );
574 }
575 for cause in &snapshot.causes {
576 group = group.element(
577 Level::NOTE
578 .message(normalize_display_text(&format!("caused by: {}", cause.message))),
579 );
580 }
581 for note in &snapshot.notes {
582 let level = match note.kind {
583 NoteKind::Note => Level::NOTE,
584 NoteKind::Help => Level::HELP,
585 };
586 group = group.element(level.message(normalize_display_text(¬e.message)));
587 }
588 groups.push(group);
589
590 if let Some(source) = snapshot.diagnostic_source.as_deref() {
591 self.lower(source, GroupRole::DiagnosticSource, groups)?;
592 }
593 for suggestion in &snapshot.suggestions {
594 groups.push(self.lower_suggestion(suggestion)?);
595 }
596 for related in &snapshot.related {
597 self.lower(related, GroupRole::Related, groups)?;
598 }
599 Ok(())
600 }
601
602 fn lower_suggestion(&self, suggestion: &OwnedSuggestion) -> Result<Group<'a>, RenderError> {
603 let mut group = Group::with_title(
604 Level::HELP.secondary_title(normalize_display_text(&suggestion.message)),
605 );
606 group = group.element(Level::NOTE.message(applicability_text(suggestion.applicability)));
607
608 let mut keys = Vec::new();
609 for edit in &suggestion.edits {
610 push_unique(&mut keys, edit.span.source());
611 }
612 for key in keys {
613 let slot = self.slot(key);
614 let text = slot.resolved.source.text.ok_or(RenderError::MissingSourceText(key))?;
615 let mut edits: Vec<(usize, &crate::OwnedTextEdit)> = suggestion
616 .edits
617 .iter()
618 .enumerate()
619 .filter(|(_, edit)| edit.span.source() == key)
620 .collect();
621 edits.sort_by_key(|(index, edit)| {
622 (edit.span.range().start(), edit.span.range().end(), *index)
623 });
624 let mut snippet = Snippet::<Patch<'a>>::source(text)
625 .path(slot.display_name.clone())
626 .fold(self.config.fold);
627 for (_, edit) in edits {
628 snippet = snippet.patch(Patch::new(
629 edit.span.range().into_slice_index(),
630 normalize_display_text(&edit.replacement),
631 ));
632 }
633 group = group.element(snippet);
634 }
635 Ok(group)
636 }
637
638 fn slot(&self, key: SourceKey) -> &ResolvedSlot<'a> {
639 self.slots
640 .iter()
641 .find(|slot| slot.resolved.key == key)
642 .expect("preflight resolved every collected source key")
643 }
644}
645
646#[derive(Clone, Copy)]
647enum GroupRole {
648 Root,
649 DiagnosticSource,
650 Related,
651}
652
653fn severity_level(severity: Severity) -> Level<'static> {
654 match severity {
655 Severity::Error => Level::ERROR,
656 Severity::Warning => Level::WARNING,
657 Severity::Info => Level::INFO,
658 Severity::Hint => Level::HELP.with_name("hint"),
659 }
660}
661
662fn applicability_text(applicability: Applicability) -> &'static str {
663 match applicability {
664 Applicability::MachineApplicable => "applicability: machine-applicable",
665 Applicability::MaybeIncorrect => "applicability: maybe-incorrect",
666 Applicability::HasPlaceholders => "applicability: has-placeholders",
667 Applicability::Unspecified => "applicability: unspecified",
668 }
669}
670
671fn map_source_error(source: SourceKey, error: SourceResolveError) -> RenderError {
672 match error {
673 SourceResolveError::Missing => RenderError::MissingSource(source),
674 SourceResolveError::IdMismatch { returned } => {
675 RenderError::ProviderIdMismatch { source, returned }
676 }
677 SourceResolveError::ByteLengthMismatch { declared, actual } => {
678 RenderError::ProviderByteLengthMismatch {
679 source,
680 declared,
681 actual,
682 }
683 }
684 }
685}
686
687fn select_primary(snapshot: &DiagnosticSnapshot) -> Result<Option<usize>, RenderError> {
688 let primaries: Vec<_> = snapshot
689 .labels
690 .iter()
691 .enumerate()
692 .filter_map(|(index, label)| (label.style == LabelStyle::Primary).then_some(index))
693 .collect();
694 if primaries.len() > 1 {
695 return Err(RenderError::MultiplePrimaryLabels {
696 count: primaries.len(),
697 });
698 }
699 Ok(primaries.first().copied().or((!snapshot.labels.is_empty()).then_some(0)))
700}
701
702fn ordered_label_keys(snapshot: &DiagnosticSnapshot, primary: Option<usize>) -> Vec<SourceKey> {
703 let mut keys = Vec::new();
704 if let Some(index) = primary {
705 push_unique(&mut keys, snapshot.labels[index].span.source());
706 }
707 for label in &snapshot.labels {
708 push_unique(&mut keys, label.span.source());
709 }
710 keys
711}
712
713fn push_unique(keys: &mut Vec<SourceKey>, key: SourceKey) {
714 if !keys.contains(&key) {
715 keys.push(key);
716 }
717}
718
719fn disambiguate_display_names(slots: &mut [ResolvedSlot<'_>]) {
720 let duplicate: Vec<bool> = slots
721 .iter()
722 .map(|candidate| {
723 slots.iter().any(|other| {
724 candidate.resolved.key != other.resolved.key
725 && candidate.display_name == other.display_name
726 })
727 })
728 .collect();
729 for (slot, duplicate) in slots.iter_mut().zip(duplicate) {
730 if duplicate {
731 slot.display_name =
732 format!("{} [{}]", slot.display_name, source_disambiguator(slot.resolved.key));
733 }
734 }
735}
736
737fn source_disambiguator(key: SourceKey) -> String {
738 let (kind, id) = match key {
739 SourceKey::Session(id) => ("session", id),
740 SourceKey::Attached(id) => ("attached", id),
741 };
742 format!("{kind} {}:{}", id.namespace(), id.local())
743}
744
745pub(crate) fn normalize_display_text(text: &str) -> String {
747 text.chars()
748 .map(|character| {
749 if character != '\n' && character.is_control() {
750 '\u{fffd}'
751 } else {
752 character
753 }
754 })
755 .collect()
756}
757
758fn valid_documentation_url(url: &str) -> bool {
759 let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"));
760 let Some(rest) = rest else {
761 return false;
762 };
763 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
764 let authority = &rest[..authority_end];
765 if authority.is_empty() || authority.contains('@') {
766 return false;
767 }
768
769 let bytes = url.as_bytes();
770 let mut index = 0;
771 while index < bytes.len() {
772 let byte = bytes[index];
773 if byte == b'%' {
774 if index + 2 >= bytes.len()
775 || !bytes[index + 1].is_ascii_hexdigit()
776 || !bytes[index + 2].is_ascii_hexdigit()
777 {
778 return false;
779 }
780 index += 3;
781 continue;
782 }
783 if !(0x21..=0x7e).contains(&byte)
784 || matches!(byte, b'\\' | b'"' | b'\'' | b'<' | b'>' | b'`' | b'{' | b'}' | b'|' | b'^')
785 {
786 return false;
787 }
788 index += 1;
789 }
790 true
791}
792
793pub(crate) fn sanitize_rendered_output(
794 text: &str,
795 styled: bool,
796 hyperlinks: bool,
797 approved_urls: &[String],
798) -> String {
799 let bytes = text.as_bytes();
800 let mut output = String::with_capacity(text.len());
801 let mut index = 0;
802 let mut link_open = false;
803 while index < bytes.len() {
804 if bytes[index] == 0x1b {
805 if styled && let Some(end) = sgr_end(bytes, index) {
806 output.push_str(&text[index..end]);
807 index = end;
808 continue;
809 }
810 if hyperlinks && let Some((end, target)) = osc8_end(text, index) {
811 match target {
812 Some(url)
813 if !link_open && approved_urls.iter().any(|approved| approved == url) =>
814 {
815 if has_balanced_osc8_close(text, end) {
816 output.push_str(&text[index..end]);
817 link_open = true;
818 index = end;
819 continue;
820 }
821 }
822 None if link_open => {
823 output.push_str(&text[index..end]);
824 link_open = false;
825 index = end;
826 continue;
827 }
828 Some(_) | None => {}
829 }
830 }
831 output.push('\u{fffd}');
832 index += 1;
833 continue;
834 }
835
836 let character =
837 text[index..].chars().next().expect("index always starts on a UTF-8 boundary");
838 if character != '\n' && character.is_control() {
839 output.push('\u{fffd}');
840 } else {
841 output.push(character);
842 }
843 index += character.len_utf8();
844 }
845 output
846}
847
848fn sgr_end(bytes: &[u8], start: usize) -> Option<usize> {
849 const ANNOTATE_SGR: &[&[u8]] = &[
852 b"\x1b[0m",
853 b"\x1b[1m",
854 b"\x1b[31m",
855 b"\x1b[32m",
856 b"\x1b[33m",
857 b"\x1b[91m",
858 b"\x1b[92m",
859 b"\x1b[93m",
860 b"\x1b[94m",
861 b"\x1b[96m",
862 b"\x1b[97m",
863 ];
864 for sequence in ANNOTATE_SGR {
865 if bytes.get(start..)?.starts_with(sequence) {
866 return Some(start + sequence.len());
867 }
868 }
869 None
870}
871
872fn osc8_end(text: &str, start: usize) -> Option<(usize, Option<&str>)> {
873 let prefix = "\x1b]8;;";
874 if !text.get(start..)?.starts_with(prefix) {
875 return None;
876 }
877 let target_start = start + prefix.len();
878 let tail = text.get(target_start..)?;
879 let target_end = tail.find("\x1b\\")?;
880 let end = target_start + target_end + 2;
881 let target = text.get(target_start..target_start + target_end)?;
882 Some((end, (!target.is_empty()).then_some(target)))
883}
884
885fn has_balanced_osc8_close(text: &str, mut index: usize) -> bool {
886 while let Some(relative) = text.get(index..).and_then(|tail| tail.find('\u{1b}')) {
887 index += relative;
888 if let Some((_, target)) = osc8_end(text, index) {
889 return target.is_none();
890 }
891 index += 1;
892 }
893 false
894}
895
896#[cfg(test)]
897mod tests {
898 use alloc::{string::ToString, vec};
899
900 use super::*;
901
902 #[test]
903 fn documentation_url_validation_is_strict_and_inert_urls_stay_outside_it() {
904 for valid in
905 ["https://example.com", "http://example.com/a?b=c#d", "https://example.com/a%20b"]
906 {
907 assert!(valid_documentation_url(valid), "{valid}");
908 }
909 for invalid in [
910 "",
911 "javascript:alert(1)",
912 "//example.com",
913 "HTTPS://example.com",
914 "https://",
915 "https://user@example.com",
916 "https://example.com/a b",
917 "https://example.com/%",
918 "https://example.com/%0",
919 "https://example.com/%zz",
920 "https://example.com/\\path",
921 "https://example.com/\u{80}",
922 "https://example.com/<tag>",
923 ] {
924 assert!(!valid_documentation_url(invalid), "{invalid}");
925 }
926 }
927
928 #[test]
929 fn final_output_safety_preserves_only_resolved_control_grammars() {
930 let approved = vec!["https://example.com".to_string()];
931 let sgr = "\u{1b}[1m\u{1b}[31mred\u{1b}[0m";
932 assert_eq!(sanitize_rendered_output(sgr, true, false, &approved), sgr);
933 assert!(!sanitize_rendered_output(sgr, false, false, &approved).contains('\u{1b}'));
934
935 let link = "\u{1b}]8;;https://example.com\u{1b}\\docs\u{1b}]8;;\u{1b}\\";
936 assert_eq!(sanitize_rendered_output(link, false, true, &approved), link);
937 assert!(!sanitize_rendered_output(link, false, false, &approved).contains('\u{1b}'));
938
939 for rejected in [
940 "\u{1b}]8;;https://evil.example\u{1b}\\docs\u{1b}]8;;\u{1b}\\",
941 "\u{1b}]8;;https://example.com\u{1b}\\unclosed",
942 "\u{1b}]8;;\u{1b}\\orphan close",
943 "\u{1b}[2Jclear",
944 "\u{1b}[38;5;123marbitrary SGR",
945 "\u{1b}]0;title\u{7}",
946 "\u{009b}31mC1",
947 ] {
948 let sanitized = sanitize_rendered_output(rejected, true, true, &approved);
949 assert_ne!(sanitized, rejected);
950 assert!(!sanitized.contains('\u{009b}'));
951 }
952 }
953}