ts_error/diagnostic/
context.rs

1use crate::diagnostic::Span;
2
3use alloc::{
4    string::{String, ToString},
5    vec::Vec,
6};
7
8#[derive(Debug, Clone)]
9/// Context for a diagnostic.
10pub struct Context {
11    /// The context for the diagnostic, sequential lines of the source where the last string is the
12    /// relevant line for the diagnostic. Each line is at most 100 characters wide
13    pub context: Vec<String>,
14    /// The span of the context relevant to the diagnostic.
15    pub span: Span,
16    /// The label for the span.
17    pub label: Option<String>,
18    /// How indented into the context the span starts.
19    pub span_indent: usize,
20}
21impl Context {
22    /// Create the context for a diagnostic from a span and the source file.
23    pub fn new(source: &str, span: Span) -> Self {
24        const MAX_LENGTH: usize = 100;
25
26        let context_end = span.column.saturating_sub(1) + span.length.min(MAX_LENGTH);
27        let context_start = span.column.saturating_sub(1);
28
29        let span_start = context_start
30            .saturating_sub(MAX_LENGTH.saturating_sub(context_end.saturating_sub(context_start)));
31        let span_end = span_start + MAX_LENGTH;
32
33        let mut context = Vec::with_capacity(3);
34        let lines: Vec<&str> = source.lines().collect();
35        for i in (1..4).rev() {
36            if let Some(index) = span.line.checked_sub(i)
37                && let Some(line) = lines.get(index)
38            {
39                let line_context = line
40                    .get(span_start..span_end.min(line.len()))
41                    .unwrap_or_default();
42                context.push(line_context.to_string());
43            }
44        }
45
46        let span_indent = context_start.saturating_sub(span_start);
47
48        Self {
49            context,
50            span,
51            label: None,
52            span_indent,
53        }
54    }
55
56    /// Sets the label of the context.
57    pub fn label<S: ToString>(mut self, label: S) -> Self {
58        self.label = Some(label.to_string());
59        self
60    }
61}
62
63#[cfg(test)]
64mod test {
65    use alloc::{string::String, vec, vec::Vec};
66
67    use crate::diagnostic::{Context, Span};
68
69    const SOURCE: &str = r#"use alloc::boxed::Box;
70use core::{error::Error, fmt};
71
72use ts_ansi::style::{BOLD, DEFAULT, RED, RESET};
73
74/// An error report, displays the error stack of some error.
75pub struct Report<'e> {
76    /// The error for this report.
77    pub source: Box<dyn Error + 'e>,
78}
79impl<'e> Report<'e> {
80    /// Create a new error report.
81    pub fn new<E: Error + 'e>(source: E) -> Self {
82        Self {
83            source: Box::new(source),
84        }
85    }
86}
87impl Error for Report<'static> {
88    fn source(&self) -> Option<&(dyn Error + 'static)> {
89        Some(self.source.as_ref())
90    }
91}
92impl fmt::Debug for Report<'_> {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(f, "{self}")
95    }
96}
97impl fmt::Display for Report<'_> {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        let mut current_error = Some(self.source.as_ref());
100        let mut count = 1;
101
102        while let Some(error) = current_error {
103            writeln!(f, " {BOLD}{RED}{count}{DEFAULT}.{RESET} {error}")?;
104
105            count += 1;
106            current_error = error.source();
107        }
108
109        Ok(())
110    }
111}"#;
112
113    const MINIFIED_SOURCE: &str = r#"async function Ui(n){return location.href=n,await mu()}function mu(){let n=t=>{setTimeout(()=>n(t),400)};return new Promise(n)}var br=class{element;contents;action;constructor(t,e){this.element=ht(`${t}/error`,HTMLElement),this.contents=ht(`${t}/error/content`,HTMLElement),this.action=e}clearError(){this.element.classList.add("collapse"),this.element.ariaHidden="true",this.contents.textContent=""}addError(t){if(this.contents.textContent===""){this.element.classList.remove("collapse"),this.element.ariaHidden="false",this.contents.textContent=`Could not ${this.action}: ${t}`;return}this.contents.textContent+=`, ${t}`}setSomethingWentWrong(){this.element.classList.remove("collapse"),this.element.ariaHidden="false",this.contents.textContent=`Something went wrong while trying to ${this.action}. Try again later.`}},Nr=class{input;error;constructor(t,e){this.input=ht(`${t}${e}/input`,HTMLInputElement),this.error=ht(`${t}${e}/error`,HTMLElement),this.input.addEventListener("input",()=>{this.input.setCustomValidity("")})}getValue(){return this.input.type==="checkbox"?this.input.checked?"checked":"unchecked":this.input.value}setLock(t){this.input.disabled=t}clearError(){this.input.setCustomValidity(""),this.error.classList.add("hidden"),this.error.ariaHidden="true",this.error.textContent="!"}addError(t){if(this.error.textContent==="!"){this.input.setCustomValidity(t),this.error.classList.remove("hidden"),this.error.ariaHidden="false",this.error.textContent=`Invalid value: ${t}`;return}this.error.textContent+=`, ${t}`,this.input.setCustomValidity(this.error.textContent??"Invalid value")}},ge=class{form;formError;submitButton;inputs;constructor(t,e,r){this.form=ht(t,HTMLFormElement),this.formError=new br(t,r),this.submitButton=ht(`${t}/submit`,HTMLButtonElement);let o=new Map;for(let i of e)o.set(i,new Nr(t,i));this.inputs=o}clearErrors(){this.formError.clearError();for(let t of this.inputs.values())t.clearError()}setLock(t){this.submitButton.disabled=t;for(let e of this.inputs.values())e.setLock(t)}setInputErrors(t){if(!t||t.length===0){this.formError.addError("an unknown field is invalid");return}for(let e of t){let r=this.inputs.get(e.pointer)??null;r?r.addError(e.detail):this.formError.addError(`field ${e.pointer} ${e.detail}`)}}getValues(){let t=new Map;for(let[e,r]of this.inputs)t.set(e,r.getValue());return t}};"#;
114
115    #[test]
116    fn handles_context() {
117        let span = Span::default().line(7).column(12).length(6);
118        let context = Context::new(SOURCE, span);
119        assert_eq!(
120            vec![
121                r#""#,
122                r#"/// An error report, displays the error stack of some error."#,
123                r#"pub struct Report<'e> {"#
124            ],
125            context.context
126        );
127
128        let span = Span::default().line(36);
129        let context = Context::new(SOURCE, span);
130        assert_eq!(
131            vec![
132                r#"        while let Some(error) = current_error {"#,
133                r#"            writeln!(f, " {BOLD}{RED}{count}{DEFAULT}.{RESET} {error}")?;"#,
134                r#""#
135            ],
136            context.context
137        );
138
139        let span = Span::default().line(999);
140        let context = Context::new(SOURCE, span);
141        assert_eq!(Vec::<String>::new(), context.context);
142
143        let span = Span::default().line(35).column(999).length(999);
144        let context = Context::new(SOURCE, span);
145        assert_eq!(vec![r#""#, r#""#, r#""#], context.context);
146
147        let span = Span::default().line(1).column(200).length(50);
148        let context = Context::new(MINIFIED_SOURCE, span);
149        assert_eq!(
150            vec![
151                r#"ontents;action;constructor(t,e){this.element=ht(`${t}/error`,HTMLElement),this.contents=ht(`${t}/err"#
152            ],
153            context.context
154        );
155    }
156}