Skip to main content

mirascript_core/diagnostic/
encode_diagnostics.rs

1use crate::{CompileConfig, SourceDiagnostic, config::DiagnosticPositionEncoding};
2
3pub type SerializedDiagnostics = Vec<u32>;
4
5type CodePointCounter = fn(&str) -> usize;
6
7fn code_point_counter(encoding: DiagnosticPositionEncoding) -> CodePointCounter {
8    match encoding {
9        DiagnosticPositionEncoding::Utf16 => |s: &str| s.encode_utf16().count(),
10        DiagnosticPositionEncoding::Utf32 => |s: &str| s.chars().count(),
11        DiagnosticPositionEncoding::Utf8 => |s: &str| s.len(),
12    }
13}
14
15/// A struct to hold the offset, line number, and column number of a position in the source code.
16struct Offset {
17    /// The offset of the position in the source code, in utf-8 bytes.
18    pub offset: usize,
19    /// The line number of the position in the source code, starting from 1.
20    pub line: usize,
21    /// The column number of the position in the source code, starting from 1.
22    pub col: usize,
23}
24
25fn prefill_offsets(script: &str, code_point_counter: CodePointCounter) -> Vec<Offset> {
26    const LONG_LINE_THRESHOLD: usize = 1024;
27
28    // offsets of line starts
29    script
30        .lines()
31        .enumerate()
32        .flat_map(|(n, line)| {
33            let line_no = n + 1;
34            let offset = line.as_ptr() as usize - script.as_ptr() as usize;
35            let mut pos = Offset {
36                offset,
37                line: line_no,
38                col: 1,
39            };
40            if line.len() <= LONG_LINE_THRESHOLD {
41                return vec![pos];
42            }
43            let mut markers = vec![];
44            while pos.offset - offset < line.len() {
45                let next_line_pos =
46                    line.floor_char_boundary(pos.offset - offset + LONG_LINE_THRESHOLD);
47                let next_offset = offset + next_line_pos;
48                let next_col =
49                    pos.col + code_point_counter(&line[pos.offset - offset..next_line_pos]);
50                markers.push(std::mem::replace(
51                    &mut pos,
52                    Offset {
53                        offset: next_offset,
54                        line: line_no,
55                        col: next_col,
56                    },
57                ));
58            }
59            markers
60        })
61        .collect()
62}
63
64fn pos_to_line_col(script: &str, config: &CompileConfig) -> impl Fn(usize) -> (u32, u32) {
65    let code_point_counter = code_point_counter(config.diagnostic_position_encoding);
66    let offsets = prefill_offsets(script, code_point_counter);
67    move |pos: usize| {
68        if pos == 0 {
69            return (1u32, 1u32);
70        }
71        let offset = offsets
72            .iter()
73            .position(|line| line.offset > pos)
74            .unwrap_or(offsets.len())
75            - 1;
76        let offset = &offsets[offset];
77        let str = &script[offset.offset..pos];
78        let code_point_count = code_point_counter(str);
79        (
80            offset.line.try_into().unwrap(),
81            (offset.col + code_point_count).try_into().unwrap(),
82        )
83    }
84}
85
86pub fn encode_diagnostics(
87    script: &str,
88    diagnostics: &[SourceDiagnostic],
89    config: &CompileConfig,
90) -> SerializedDiagnostics {
91    if diagnostics.is_empty() {
92        return vec![];
93    }
94
95    let pos_to_line_col = pos_to_line_col(script, config);
96    diagnostics
97        .iter()
98        .flat_map(|s| {
99            let start = pos_to_line_col(s.range.start);
100            let end = pos_to_line_col(s.range.end);
101            [start.0, start.1, end.0, end.1, s.error.code() as u32]
102        })
103        .collect()
104}