Skip to main content

i_slint_compiler/
diagnostics.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::rc::Rc;
7
8use crate::parser::TextSize;
9use std::collections::BTreeSet;
10
11/// Span represent an error location within a file.
12///
13/// Currently, it is just an offset in byte within the file + the corresponding length.
14///
15/// When the `proc_macro_span` feature is enabled, it may also hold a proc_macro span.
16#[derive(Debug, Clone)]
17pub struct Span {
18    pub offset: usize,
19    pub length: usize,
20    #[cfg(feature = "proc_macro_span")]
21    pub span: Option<proc_macro::Span>,
22}
23
24impl Span {
25    pub fn is_valid(&self) -> bool {
26        self.offset != usize::MAX
27    }
28
29    #[allow(clippy::needless_update)] // needed when `proc_macro_span` is enabled
30    pub fn new(offset: usize, length: usize) -> Self {
31        Self { offset, length, ..Default::default() }
32    }
33}
34
35impl Default for Span {
36    fn default() -> Self {
37        Span {
38            offset: usize::MAX,
39            length: 0,
40            #[cfg(feature = "proc_macro_span")]
41            span: Default::default(),
42        }
43    }
44}
45
46impl PartialEq for Span {
47    fn eq(&self, other: &Span) -> bool {
48        self.offset == other.offset && self.length == other.length
49    }
50}
51
52#[cfg(feature = "proc_macro_span")]
53impl From<proc_macro::Span> for Span {
54    fn from(span: proc_macro::Span) -> Self {
55        Self { span: Some(span), ..Default::default() }
56    }
57}
58
59/// Returns a span.  This is implemented for tokens and nodes
60pub trait Spanned {
61    fn span(&self) -> Span;
62    fn source_file(&self) -> Option<&SourceFile>;
63    fn to_source_location(&self) -> SourceLocation {
64        SourceLocation { source_file: self.source_file().cloned(), span: self.span() }
65    }
66}
67
68#[derive(Default)]
69pub struct SourceFileInner {
70    path: PathBuf,
71
72    /// Complete source code of the path, used to map from offset to line number
73    source: Option<String>,
74
75    /// The offset of each linebreak
76    line_offsets: std::cell::OnceCell<Vec<usize>>,
77}
78
79impl std::fmt::Debug for SourceFileInner {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{:?}", self.path)
82    }
83}
84
85impl SourceFileInner {
86    pub fn new(path: PathBuf, source: String) -> Self {
87        Self { path, source: Some(source), line_offsets: Default::default() }
88    }
89
90    pub fn path(&self) -> &Path {
91        &self.path
92    }
93
94    /// Create a SourceFile that has just a path, but no contents
95    pub fn from_path_only(path: PathBuf) -> Rc<Self> {
96        Rc::new(Self { path, ..Default::default() })
97    }
98
99    /// Returns a tuple with the line (starting at 1) and column number (starting at 1)
100    pub fn line_column(&self, offset: usize, format: ByteFormat) -> (usize, usize) {
101        let adjust_utf16 = |line_begin, col| {
102            if format == ByteFormat::Utf8 {
103                col
104            } else {
105                let Some(source) = &self.source else { return col };
106                source[line_begin..][..col].encode_utf16().count()
107            }
108        };
109
110        let line_offsets = self.line_offsets();
111        line_offsets.binary_search(&offset).map_or_else(
112            |line| {
113                if line == 0 {
114                    (1, adjust_utf16(0, offset) + 1)
115                } else {
116                    let line_begin = *line_offsets.get(line - 1).unwrap_or(&0);
117                    (line + 1, adjust_utf16(line_begin, offset - line_begin) + 1)
118                }
119            },
120            |line| (line + 2, 1),
121        )
122    }
123
124    pub fn text_size_to_file_line_column(
125        &self,
126        size: TextSize,
127        format: ByteFormat,
128    ) -> (String, usize, usize, usize, usize) {
129        let file_name = self.path().to_string_lossy().to_string();
130        let (start_line, start_column) = self.line_column(size.into(), format);
131        (file_name, start_line, start_column, start_line, start_column)
132    }
133
134    /// Returns the offset that corresponds to the line/column
135    pub fn offset(&self, line: usize, column: usize, format: ByteFormat) -> usize {
136        let adjust_utf16 = |line_begin, col| {
137            if format == ByteFormat::Utf8 {
138                col
139            } else {
140                let Some(source) = &self.source else { return col };
141                let mut utf16_counter = 0;
142                for (utf8_index, c) in source[line_begin..].char_indices() {
143                    if utf16_counter >= col {
144                        return utf8_index;
145                    }
146                    utf16_counter += c.len_utf16();
147                }
148                col
149            }
150        };
151
152        let col_offset = column.saturating_sub(1);
153        if line <= 1 {
154            // line == 0 is actually invalid!
155            return adjust_utf16(0, col_offset);
156        }
157        let offsets = self.line_offsets();
158        let index = std::cmp::min(line.saturating_sub(1), offsets.len());
159        let line_offset = *offsets.get(index.saturating_sub(1)).unwrap_or(&0);
160        line_offset.saturating_add(adjust_utf16(line_offset, col_offset))
161    }
162
163    fn line_offsets(&self) -> &[usize] {
164        self.line_offsets.get_or_init(|| {
165            self.source
166                .as_ref()
167                .map(|s| {
168                    s.bytes()
169                        .enumerate()
170                        // Add the offset one past the '\n' into the index: That's the first char
171                        // of the new line!
172                        .filter_map(|(i, c)| if c == b'\n' { Some(i + 1) } else { None })
173                        .collect()
174                })
175                .unwrap_or_default()
176        })
177    }
178
179    pub fn source(&self) -> Option<&str> {
180        self.source.as_deref()
181    }
182}
183
184#[derive(Copy, Clone, Eq, PartialEq, Debug)]
185/// When converting between line/columns to offset, specify if the format of the column is UTF-8 or UTF-16
186pub enum ByteFormat {
187    Utf8,
188    Utf16,
189}
190
191pub type SourceFile = Rc<SourceFileInner>;
192
193pub fn load_from_path(path: &Path) -> Result<String, Diagnostic> {
194    let string = (if path == Path::new("-") {
195        let mut buffer = Vec::new();
196        let r = std::io::stdin().read_to_end(&mut buffer);
197        r.and_then(|_| {
198            String::from_utf8(buffer)
199                .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
200        })
201    } else {
202        std::fs::read_to_string(path)
203    })
204    .map_err(|err| Diagnostic {
205        message: format!("Could not load {}: {}", path.display(), err),
206        span: SourceLocation {
207            source_file: Some(SourceFileInner::from_path_only(path.to_owned())),
208            span: Default::default(),
209        },
210        level: DiagnosticLevel::Error,
211    })?;
212
213    if path.extension().is_some_and(|e| e == "rs") {
214        return crate::lexer::extract_rust_macro(string).ok_or_else(|| Diagnostic {
215            message: "No `slint!` macro".into(),
216            span: SourceLocation {
217                source_file: Some(SourceFileInner::from_path_only(path.to_owned())),
218                span: Default::default(),
219            },
220            level: DiagnosticLevel::Error,
221        });
222    }
223
224    Ok(string)
225}
226
227#[derive(Debug, Clone, Default)]
228pub struct SourceLocation {
229    pub source_file: Option<SourceFile>,
230    pub span: Span,
231}
232
233impl Spanned for SourceLocation {
234    fn span(&self) -> Span {
235        self.span.clone()
236    }
237
238    fn source_file(&self) -> Option<&SourceFile> {
239        self.source_file.as_ref()
240    }
241}
242
243impl Spanned for Option<SourceLocation> {
244    fn span(&self) -> crate::diagnostics::Span {
245        self.as_ref().map(|n| n.span()).unwrap_or_default()
246    }
247
248    fn source_file(&self) -> Option<&SourceFile> {
249        self.as_ref().map(|n| n.source_file.as_ref()).unwrap_or_default()
250    }
251}
252
253/// This enum describes the level or severity of a diagnostic message produced by the compiler.
254#[derive(Debug, PartialEq, Copy, Clone, Default)]
255#[non_exhaustive]
256pub enum DiagnosticLevel {
257    /// The diagnostic found is an error that prevents successful compilation.
258    #[default]
259    Error,
260    /// The diagnostic found is a warning.
261    Warning,
262}
263
264/// This structure represent a diagnostic emitted while compiling .slint code.
265///
266/// It is basically a message, a level (warning or error), attached to a
267/// position in the code
268#[derive(Debug, Clone)]
269pub struct Diagnostic {
270    message: String,
271    span: SourceLocation,
272    level: DiagnosticLevel,
273}
274
275//NOTE! Diagnostic is re-exported in the public API of the interpreter
276impl Diagnostic {
277    /// Return the level for this diagnostic
278    pub fn level(&self) -> DiagnosticLevel {
279        self.level
280    }
281
282    /// Return a message for this diagnostic
283    pub fn message(&self) -> &str {
284        &self.message
285    }
286
287    /// Returns a tuple with the line (starting at 1) and column number (starting at 1)
288    ///
289    /// Can also return (0, 0) if the span is invalid
290    pub fn line_column(&self) -> (usize, usize) {
291        if !self.span.span.is_valid() {
292            return (0, 0);
293        }
294        let offset = self.span.span.offset;
295
296        match &self.span.source_file {
297            None => (0, 0),
298            Some(sl) => sl.line_column(offset, ByteFormat::Utf8),
299        }
300    }
301
302    /// Return the length of this diagnostic in UTF-8 encoded bytes.
303    pub fn length(&self) -> usize {
304        self.span.span.length
305    }
306
307    // NOTE: The return-type differs from the Spanned trait.
308    // Because this is public API (Diagnostic is re-exported by the Interpreter), we cannot change
309    // this.
310    /// return the path of the source file where this error is attached
311    pub fn source_file(&self) -> Option<&Path> {
312        self.span.source_file().map(|sf| sf.path())
313    }
314}
315
316impl std::fmt::Display for Diagnostic {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        if let Some(sf) = self.span.source_file() {
319            let (line, _) = self.line_column();
320            write!(f, "{}:{}: {}", sf.path.display(), line, self.message)
321        } else {
322            write!(f, "{}", self.message)
323        }
324    }
325}
326
327impl std::fmt::Display for SourceLocation {
328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329        if let Some(sf) = &self.source_file {
330            let (line, col) = sf.line_column(self.span.offset, ByteFormat::Utf8);
331            write!(f, "{}:{line}:{col}", sf.path.display())
332        } else {
333            write!(f, "<unknown>")
334        }
335    }
336}
337
338pub fn diagnostic_line_column_with_format(
339    diagnostic: &Diagnostic,
340    format: ByteFormat,
341) -> (usize, usize) {
342    let Some(sf) = &diagnostic.span.source_file else { return (0, 0) };
343    sf.line_column(diagnostic.span.span.offset, format)
344}
345
346pub fn diagnostic_end_line_column_with_format(
347    diagnostic: &Diagnostic,
348    format: ByteFormat,
349) -> (usize, usize) {
350    let Some(sf) = &diagnostic.span.source_file else { return (0, 0) };
351    // The end_line_column is exclusive.
352    // Even if the span indicates a length of 0, the diagnostic should always
353    // return an end_line_column that is at least one offset further.
354    // Diagnostic::length ensures this.
355    let offset = diagnostic.span.span.offset + diagnostic.length();
356    sf.line_column(offset, format)
357}
358
359#[derive(Default)]
360pub struct BuildDiagnostics {
361    inner: Vec<Diagnostic>,
362
363    /// When false, throw error for experimental features
364    pub enable_experimental: bool,
365
366    /// This is the list of all loaded files (with or without diagnostic)
367    /// does not include the main file.
368    /// FIXME: this doesn't really belong in the diagnostics, it should be somehow returned in another way
369    /// (maybe in a compilation state that include the diagnostics?)
370    pub all_loaded_files: BTreeSet<PathBuf>,
371}
372
373impl IntoIterator for BuildDiagnostics {
374    type Item = Diagnostic;
375    type IntoIter = <Vec<Diagnostic> as IntoIterator>::IntoIter;
376    fn into_iter(self) -> Self::IntoIter {
377        self.inner.into_iter()
378    }
379}
380
381impl BuildDiagnostics {
382    pub fn push_diagnostic_with_span(
383        &mut self,
384        message: String,
385        span: SourceLocation,
386        level: DiagnosticLevel,
387    ) {
388        debug_assert!(
389            !message.as_str().ends_with('.'),
390            "Error message should not end with a period: ({message:?})"
391        );
392        self.inner.push(Diagnostic { message, span, level });
393    }
394    pub fn push_error_with_span(&mut self, message: String, span: SourceLocation) {
395        self.push_diagnostic_with_span(message, span, DiagnosticLevel::Error)
396    }
397    pub fn push_error(&mut self, message: String, source: &dyn Spanned) {
398        self.push_error_with_span(message, source.to_source_location());
399    }
400    pub fn push_warning_with_span(&mut self, message: String, span: SourceLocation) {
401        self.push_diagnostic_with_span(message, span, DiagnosticLevel::Warning)
402    }
403    pub fn push_warning(&mut self, message: String, source: &dyn Spanned) {
404        self.push_warning_with_span(message, source.to_source_location());
405    }
406    pub fn push_compiler_error(&mut self, error: Diagnostic) {
407        self.inner.push(error);
408    }
409
410    pub fn push_property_deprecation_warning(
411        &mut self,
412        old_property: &str,
413        new_property: &str,
414        source: &dyn Spanned,
415    ) {
416        self.push_diagnostic_with_span(
417            format!(
418                "The property '{old_property}' has been deprecated. Please use '{new_property}' instead"
419            ),
420            source.to_source_location(),
421            crate::diagnostics::DiagnosticLevel::Warning,
422        )
423    }
424
425    /// Return true if there is at least one compilation error for this file
426    pub fn has_errors(&self) -> bool {
427        self.inner.iter().any(|diag| diag.level == DiagnosticLevel::Error)
428    }
429
430    /// Return true if there are no diagnostics (warnings or errors); false otherwise.
431    pub fn is_empty(&self) -> bool {
432        self.inner.is_empty()
433    }
434
435    #[cfg(feature = "display-diagnostics")]
436    fn call_diagnostics(
437        &self,
438        mut handle_no_source: Option<&mut dyn FnMut(&Diagnostic)>,
439    ) -> String {
440        if self.inner.is_empty() {
441            return Default::default();
442        }
443
444        let report: Vec<_> = self
445            .inner
446            .iter()
447            .filter_map(|d| {
448                let annotate_snippets_level = match d.level {
449                    DiagnosticLevel::Error => annotate_snippets::Level::ERROR,
450                    DiagnosticLevel::Warning => annotate_snippets::Level::WARNING,
451                };
452                let message = annotate_snippets_level.primary_title(d.message());
453
454                let group = if !d.span.span.is_valid() {
455                    annotate_snippets::Group::with_title(message)
456                } else if let Some(sf) = &d.span.source_file {
457                    if let Some(source) = &sf.source {
458                        let start_offset = d.span.span.offset;
459                        let end_offset = d.span.span.offset + d.length();
460                        message.element(
461                            annotate_snippets::Snippet::source(source)
462                                .path(sf.path.to_string_lossy())
463                                .annotation(
464                                    annotate_snippets::AnnotationKind::Primary
465                                        .span(start_offset..end_offset),
466                                ),
467                        )
468                    } else {
469                        if let Some(ref mut handle_no_source) = handle_no_source {
470                            drop(message);
471                            handle_no_source(d);
472                            return None;
473                        }
474                        message.element(annotate_snippets::Origin::path(sf.path.to_string_lossy()))
475                    }
476                } else {
477                    annotate_snippets::Group::with_title(message)
478                };
479                Some(group)
480            })
481            .collect();
482
483        annotate_snippets::Renderer::styled().render(&report)
484    }
485
486    #[cfg(feature = "display-diagnostics")]
487    /// Print the diagnostics on the console
488    pub fn print(self) {
489        let to_print = self.call_diagnostics(None);
490        if !to_print.is_empty() {
491            std::eprintln!("{to_print}");
492        }
493    }
494
495    #[cfg(feature = "display-diagnostics")]
496    /// Print into a string
497    pub fn diagnostics_as_string(self) -> String {
498        self.call_diagnostics(None)
499    }
500
501    #[cfg(all(feature = "proc_macro_span", feature = "display-diagnostics"))]
502    /// Will convert the diagnostics that only have offsets to the actual proc_macro::Span
503    pub fn report_macro_diagnostic(
504        self,
505        span_map: &[crate::parser::Token],
506    ) -> proc_macro::TokenStream {
507        let mut result = proc_macro::TokenStream::default();
508        let mut needs_error = self.has_errors();
509        let output = self.call_diagnostics(
510            Some(&mut |diag| {
511                let span = diag.span.span.span.or_else(|| {
512                    //let pos =
513                    //span_map.binary_search_by_key(d.span.offset, |x| x.0).unwrap_or_else(|x| x);
514                    //d.span.span = span_map.get(pos).as_ref().map(|x| x.1);
515                    let mut offset = 0;
516                    span_map.iter().find_map(|t| {
517                        if diag.span.span.offset <= offset {
518                            t.span
519                        } else {
520                            offset += t.text.len();
521                            None
522                        }
523                    })
524                });
525                let message = &diag.message;
526                match diag.level {
527                    DiagnosticLevel::Error => {
528                        needs_error = false;
529                        result.extend(proc_macro::TokenStream::from(if let Some(span) = span {
530                            quote::quote_spanned!(span.into()=> compile_error!{ #message })
531                        } else {
532                            quote::quote!(compile_error! { #message })
533                        }));
534                    }
535                    DiagnosticLevel::Warning => {
536                        result.extend(proc_macro::TokenStream::from(if let Some(span) = span {
537                            quote::quote_spanned!(span.into()=> const _ : () = { #[deprecated(note = #message)] const WARNING: () = (); WARNING };)
538                        } else {
539                            quote::quote!(const _ : () = { #[deprecated(note = #message)] const WARNING: () = (); WARNING };)
540                        }));
541                    },
542                }
543            }),
544        );
545        if !output.is_empty() {
546            eprintln!("{output}");
547        }
548
549        if needs_error {
550            result.extend(proc_macro::TokenStream::from(quote::quote!(
551                compile_error! { "Error occurred" }
552            )))
553        }
554        result
555    }
556
557    pub fn to_string_vec(&self) -> Vec<String> {
558        self.inner.iter().map(|d| d.to_string()).collect()
559    }
560
561    pub fn push_diagnostic(
562        &mut self,
563        message: String,
564        source: &dyn Spanned,
565        level: DiagnosticLevel,
566    ) {
567        self.push_diagnostic_with_span(message, source.to_source_location(), level)
568    }
569
570    pub fn push_internal_error(&mut self, err: Diagnostic) {
571        self.inner.push(err)
572    }
573
574    pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
575        self.inner.iter()
576    }
577
578    #[cfg(feature = "display-diagnostics")]
579    #[must_use]
580    pub fn check_and_exit_on_error(self) -> Self {
581        if self.has_errors() {
582            self.print();
583            std::process::exit(-1);
584        }
585        self
586    }
587
588    #[cfg(feature = "display-diagnostics")]
589    pub fn print_warnings_and_exit_on_error(self) {
590        let has_error = self.has_errors();
591        self.print();
592        if has_error {
593            std::process::exit(-1);
594        }
595    }
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    #[test]
603    fn test_source_file_offset_line_column_mapping() {
604        let content = r#"import { LineEdit, Button, Slider, HorizontalBox, VerticalBox } from "std-widgets.slint";
605
606component MainWindow inherits Window {
607    property <duration> total-time: slider.value * 1s;
608
609    callback tick(duration);
610    VerticalBox {
611        HorizontalBox {
612            padding-left: 0;
613            Text { text: "Elapsed Time:"; }
614            Rectangle {
615                Rectangle {
616                    height: 100%;
617                    background: lightblue;
618                }
619            }
620        }
621    }
622
623
624}
625
626
627    "#.to_string();
628        let sf = SourceFileInner::new(PathBuf::from("foo.slint"), content.clone());
629
630        let mut line = 1;
631        let mut column = 1;
632        for offset in 0..content.len() {
633            let b = *content.as_bytes().get(offset).unwrap();
634
635            assert_eq!(sf.offset(line, column, ByteFormat::Utf8), offset);
636            assert_eq!(sf.line_column(offset, ByteFormat::Utf8), (line, column));
637
638            if b == b'\n' {
639                line += 1;
640                column = 1;
641            } else {
642                column += 1;
643            }
644        }
645    }
646}