solar_interface/source_map/
analyze.rs

1use super::MultiByteChar;
2use crate::pos::RelativeBytePos;
3
4/// Finds all newlines, multi-byte characters, and non-narrow characters in a
5/// SourceFile.
6///
7/// This function will use an SSE2 enhanced implementation if hardware support
8/// is detected at runtime.
9pub(crate) fn analyze_source_file(src: &str) -> (Vec<RelativeBytePos>, Vec<MultiByteChar>) {
10    let mut lines = vec![RelativeBytePos::from_u32(0)];
11    let mut multi_byte_chars = vec![];
12
13    // Calls the right implementation, depending on hardware support available.
14    analyze_source_file_dispatch(src, &mut lines, &mut multi_byte_chars);
15
16    // The code above optimistically registers a new line *after* each \n
17    // it encounters. If that point is already outside the source_file, remove
18    // it again.
19    if let Some(&last_line_start) = lines.last() {
20        let source_file_end = RelativeBytePos::from_usize(src.len());
21        assert!(source_file_end >= last_line_start);
22        if last_line_start == source_file_end {
23            lines.pop();
24        }
25    }
26
27    (lines, multi_byte_chars)
28}
29
30fn analyze_source_file_dispatch(
31    src: &str,
32    lines: &mut Vec<RelativeBytePos>,
33    multi_byte_chars: &mut Vec<MultiByteChar>,
34) {
35    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
36    if is_x86_feature_detected!("sse2") {
37        unsafe { analyze_source_file_sse2(src, lines, multi_byte_chars) };
38        return;
39    }
40    analyze_source_file_generic(
41        src,
42        src.len(),
43        RelativeBytePos::from_u32(0),
44        lines,
45        multi_byte_chars,
46    );
47}
48
49/// Checks 16 byte chunks of text at a time. If the chunk contains
50/// something other than printable ASCII characters and newlines, the
51/// function falls back to the generic implementation. Otherwise it uses
52/// SSE2 intrinsics to quickly find all newlines.
53#[target_feature(enable = "sse2")]
54#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
55unsafe fn analyze_source_file_sse2(
56    src: &str,
57    lines: &mut Vec<RelativeBytePos>,
58    multi_byte_chars: &mut Vec<MultiByteChar>,
59) {
60    #[cfg(target_arch = "x86")]
61    use std::arch::x86::*;
62    #[cfg(target_arch = "x86_64")]
63    use std::arch::x86_64::*;
64
65    const CHUNK_SIZE: usize = 16;
66
67    let (chunks, tail) = src.as_bytes().as_chunks::<CHUNK_SIZE>();
68
69    // This variable keeps track of where we should start decoding a
70    // chunk. If a multi-byte character spans across chunk boundaries,
71    // we need to skip that part in the next chunk because we already
72    // handled it.
73    let mut intra_chunk_offset = 0;
74
75    for (chunk_index, chunk) in chunks.iter().enumerate() {
76        // We don't know if the pointer is aligned to 16 bytes, so we
77        // use `loadu`, which supports unaligned loading.
78        let chunk = unsafe { _mm_loadu_si128(chunk.as_ptr() as *const __m128i) };
79
80        // For character in the chunk, see if its byte value is < 0, which
81        // indicates that it's part of a UTF-8 char.
82        let multibyte_test = _mm_cmplt_epi8(chunk, _mm_set1_epi8(0));
83        // Create a bit mask from the comparison results.
84        let multibyte_mask = _mm_movemask_epi8(multibyte_test);
85
86        // If the bit mask is all zero, we only have ASCII chars here:
87        if multibyte_mask == 0 {
88            assert!(intra_chunk_offset == 0);
89
90            // Check for newlines in the chunk
91            let newlines_test = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8));
92            let mut newlines_mask = _mm_movemask_epi8(newlines_test);
93
94            let output_offset = RelativeBytePos::from_usize(chunk_index * CHUNK_SIZE + 1);
95
96            while newlines_mask != 0 {
97                let index = newlines_mask.trailing_zeros();
98
99                lines.push(RelativeBytePos(index) + output_offset);
100
101                // Clear the bit, so we can find the next one.
102                newlines_mask &= newlines_mask - 1;
103            }
104        } else {
105            // The slow path.
106            // There are multibyte chars in here, fallback to generic decoding.
107            let scan_start = chunk_index * CHUNK_SIZE + intra_chunk_offset;
108            intra_chunk_offset = analyze_source_file_generic(
109                &src[scan_start..],
110                CHUNK_SIZE - intra_chunk_offset,
111                RelativeBytePos::from_usize(scan_start),
112                lines,
113                multi_byte_chars,
114            );
115        }
116    }
117
118    // There might still be a tail left to analyze
119    let tail_start = src.len() - tail.len() + intra_chunk_offset;
120    if tail_start < src.len() {
121        analyze_source_file_generic(
122            &src[tail_start..],
123            src.len() - tail_start,
124            RelativeBytePos::from_usize(tail_start),
125            lines,
126            multi_byte_chars,
127        );
128    }
129}
130
131// `scan_len` determines the number of bytes in `src` to scan. Note that the
132// function can read past `scan_len` if a multi-byte character start within the
133// range but extends past it. The overflow is returned by the function.
134fn analyze_source_file_generic(
135    src: &str,
136    scan_len: usize,
137    output_offset: RelativeBytePos,
138    lines: &mut Vec<RelativeBytePos>,
139    multi_byte_chars: &mut Vec<MultiByteChar>,
140) -> usize {
141    assert!(src.len() >= scan_len);
142    let mut i = 0;
143    let src_bytes = src.as_bytes();
144
145    while i < scan_len {
146        let byte = unsafe {
147            // We verified that i < scan_len <= src.len()
148            *src_bytes.get_unchecked(i)
149        };
150
151        // How much to advance in order to get to the next UTF-8 char in the
152        // string.
153        let mut char_len = 1;
154
155        if byte == b'\n' {
156            let pos = RelativeBytePos::from_usize(i) + output_offset;
157            lines.push(pos + RelativeBytePos(1));
158        } else if byte >= 128 {
159            // This is the beginning of a multibyte char. Just decode to `char`.
160            let c = src[i..].chars().next().unwrap();
161            char_len = c.len_utf8();
162
163            let pos = RelativeBytePos::from_usize(i) + output_offset;
164            assert!((2..=4).contains(&char_len));
165            let mbc = MultiByteChar { pos, bytes: char_len as u8 };
166            multi_byte_chars.push(mbc);
167        }
168
169        i += char_len;
170    }
171
172    i - scan_len
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    macro_rules! test {
180        (
181            case:
182            $test_name:ident,text:
183            $text:expr,lines:
184            $lines:expr,multi_byte_chars:
185            $multi_byte_chars:expr,
186        ) => {
187            #[test]
188            fn $test_name() {
189                let (lines, multi_byte_chars) = analyze_source_file($text);
190
191                let expected_lines: Vec<RelativeBytePos> =
192                    $lines.into_iter().map(RelativeBytePos).collect();
193
194                assert_eq!(lines, expected_lines);
195
196                let expected_mbcs: Vec<MultiByteChar> = $multi_byte_chars
197                    .into_iter()
198                    .map(|(pos, bytes)| MultiByteChar { pos: RelativeBytePos(pos), bytes })
199                    .collect();
200
201                assert_eq!(multi_byte_chars, expected_mbcs);
202            }
203        };
204    }
205
206    test!(
207        case: empty_text,
208        text: "",
209        lines: vec![],
210        multi_byte_chars: vec![],
211    );
212
213    test!(
214        case: newlines_short,
215        text: "a\nc",
216        lines: vec![0, 2],
217        multi_byte_chars: vec![],
218    );
219
220    test!(
221        case: newlines_long,
222        text: "012345678\nabcdef012345678\na",
223        lines: vec![0, 10, 26],
224        multi_byte_chars: vec![],
225    );
226
227    test!(
228        case: newline_and_multi_byte_char_in_same_chunk,
229        text: "01234β789\nbcdef0123456789abcdef",
230        lines: vec![0, 11],
231        multi_byte_chars: vec![(5, 2)],
232    );
233
234    test!(
235        case: newline_and_control_char_in_same_chunk,
236        text: "01234\u{07}6789\nbcdef0123456789abcdef",
237        lines: vec![0, 11],
238        multi_byte_chars: vec![],
239    );
240
241    test!(
242        case: multi_byte_char_short,
243        text: "aβc",
244        lines: vec![0],
245        multi_byte_chars: vec![(1, 2)],
246    );
247
248    test!(
249        case: multi_byte_char_long,
250        text: "0123456789abcΔf012345β",
251        lines: vec![0],
252        multi_byte_chars: vec![(13, 2), (22, 2)],
253    );
254
255    test!(
256        case: multi_byte_char_across_chunk_boundary,
257        text: "0123456789abcdeΔ123456789abcdef01234",
258        lines: vec![0],
259        multi_byte_chars: vec![(15, 2)],
260    );
261
262    test!(
263        case: multi_byte_char_across_chunk_boundary_tail,
264        text: "0123456789abcdeΔ....",
265        lines: vec![0],
266        multi_byte_chars: vec![(15, 2)],
267    );
268
269    test!(
270        case: non_narrow_short,
271        text: "0\t2",
272        lines: vec![0],
273        multi_byte_chars: vec![],
274    );
275
276    test!(
277        case: non_narrow_long,
278        text: "01\t3456789abcdef01234567\u{07}9",
279        lines: vec![0],
280        multi_byte_chars: vec![],
281    );
282
283    test!(
284        case: output_offset_all,
285        text: "01\t345\n789abcΔf01234567\u{07}9\nbcΔf",
286        lines: vec![0, 7, 27],
287        multi_byte_chars: vec![(13, 2), (29, 2)],
288    );
289}