Debian Codegraph @

Xtree-house/highlighter/src/fixtures.rs

raw symbols SCIP
1 use pretty_assertions::StrComparison;
2 use ropey::{Rope, RopeSlice};
3 use std::fmt::Write;
4 use std::fs;
5 use std::ops::{Bound, RangeBounds};
6 use std::path::Path;
7 use std::time::Duration;
8 use tree_sitter::Query;
9 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
10
11 use crate::config::LanguageLoader;
12 use crate::highlighter::{Highlight, HighlightEvent, Highlighter};
13 use crate::query_iter::{QueryIter, QueryIterEvent};
14 use crate::{Language, Range, Syntax};
15
16 macro_rules! w {
17 ($dst: expr$(, $($args: tt)*)?) => {{
18 let _ = write!($dst$(, $($args)*)?);
19 }};
20 }
21 macro_rules! wln {
22 ($dst: expr$(, $($args: tt)*)?) => {{
23 let _ = writeln!($dst$(, $($args)*)?);
24 }};
25 }
26
27 pub fn check_fixture(path: impl AsRef<Path>, roundtrip: impl FnOnce(&str) -> String) {
28 let path = path.as_ref();
29 let snapshot = match fs::read_to_string(path) {
30 Ok(content) => content.replace("\r\n", "\n"),
31 Err(err) => panic!("Failed to read fixture {path:?}: {err}"),
32 };
33 let snapshot = snapshot.trim_end();
34 let roundtrip = roundtrip(snapshot);
35 if snapshot != roundtrip.trim_end() {
36 if std::env::var_os("UPDATE_EXPECT").is_some_and(|it| it == "1") {
37 println!("\x1b[1m\x1b[92mupdating\x1b[0m: {}", path.display());
38 fs::write(path, roundtrip).unwrap();
39 } else {
40 println!(
41 "\n
42 \x1b[1mCurrent\x1b[0m:
43 ----
44 {}
45 ----
46
47 \x1b[1mGenerated\x1b[0m:
48 ----
49 {}
50 ----
51
52 \x1b[1mDiff\x1b[0m:
53 ----
54 {}
55 ----
56 \x1b[1m\x1b[91merror\x1b[97m: fixture test failed\x1b[0m
57 \x1b[1m\x1b[34m-->\x1b[0m {}
58
59 You can update all fixtures by running:
60
61 env UPDATE_EXPECT=1 cargo test
62 ",
63 snapshot,
64 roundtrip,
65 StrComparison::new(snapshot, &roundtrip.trim_end()),
66 path.display(),
67 );
68 }
69
70 std::panic::resume_unwind(Box::new(()));
71 }
72 }
73
74 pub fn strip_annotations(src: &str, comment_prefix: &str) -> Rope {
75 let ident = " ".repeat(comment_prefix.width());
76 let escape = src.lines().all(|line| {
77 line.chars().all(|c| c.is_whitespace())
78 || line.starts_with(&ident)
79 || line.starts_with(comment_prefix)
80 });
81 if !escape {
82 Rope::from_str(src);
83 }
84 let mut raw = String::new();
85 for mut line in src.split_inclusive('\n') {
86 if line.starts_with(comment_prefix) {
87 continue;
88 }
89 line = line.strip_prefix(&ident).unwrap_or(line);
90 raw.push_str(line);
91 }
92 Rope::from_str(&raw)
93 }
94
95 pub fn check_highlighter_fixture<R: RangeBounds<usize>>(
96 path: impl AsRef<Path>,
97 comment_prefix: &str,
98 language: Language,
99 loader: &impl LanguageLoader,
100 get_highlight_name: impl Fn(Highlight) -> String,
101 range: impl Fn(RopeSlice) -> R,
102 ) {
103 check_fixture(path, move |src| {
104 roundtrip_highlighter_fixture(
105 comment_prefix,
106 language,
107 loader,
108 get_highlight_name,
109 src,
110 range,
111 )
112 })
113 }
114
115 pub fn check_injection_fixture<R: RangeBounds<usize>>(
116 path: impl AsRef<Path>,
117 comment_prefix: &str,
118 language: Language,
119 loader: &impl LanguageLoader,
120 get_language_name: impl Fn(Language) -> String,
121 range: impl Fn(RopeSlice) -> R,
122 ) {
123 check_fixture(path, move |src| {
124 roundtrip_injection_fixture(
125 comment_prefix,
126 language,
127 loader,
128 get_language_name,
129 src,
130 range,
131 )
132 })
133 }
134
135 pub fn roundtrip_highlighter_fixture<R: RangeBounds<usize>>(
136 comment_prefix: &str,
137 language: Language,
138 loader: &impl LanguageLoader,
139 get_highlight_name: impl Fn(Highlight) -> String,
140 src: &str,
141 range: impl Fn(RopeSlice) -> R,
142 ) -> String {
143 let raw = strip_annotations(src, comment_prefix);
144 let syntax = Syntax::new(raw.slice(..), language, Duration::from_secs(60), loader).unwrap();
145 let range = range(raw.slice(..));
146 highlighter_fixture(
147 comment_prefix,
148 loader,
149 get_highlight_name,
150 &syntax,
151 raw.slice(..),
152 range,
153 )
154 }
155
156 pub fn roundtrip_injection_fixture<R: RangeBounds<usize>>(
157 comment_prefix: &str,
158 language: Language,
159 loader: &impl LanguageLoader,
160 get_language_name: impl Fn(Language) -> String,
161 src: &str,
162 range: impl Fn(RopeSlice) -> R,
163 ) -> String {
164 let raw = strip_annotations(src, comment_prefix);
165 let syntax = Syntax::new(raw.slice(..), language, Duration::from_secs(60), loader).unwrap();
166 let range = range(raw.slice(..));
167 injections_fixture(
168 comment_prefix,
169 loader,
170 get_language_name,
171 &syntax,
172 raw.slice(..),
173 range,
174 )
175 }
176
177 pub fn highlighter_fixture(
178 comment_prefix: &str,
179 loader: &impl LanguageLoader,
180 get_highlight_name: impl Fn(Highlight) -> String,
181 syntax: &Syntax,
182 src: RopeSlice<'_>,
183 range: impl RangeBounds<usize>,
184 ) -> String {
185 let start = match range.start_bound() {
186 Bound::Included(&i) => i,
187 Bound::Excluded(&i) => i + 1,
188 Bound::Unbounded => 0,
189 };
190 let end = match range.end_bound() {
191 Bound::Included(&i) => i - 1,
192 Bound::Excluded(&i) => i,
193 Bound::Unbounded => src.len_bytes(),
194 };
195 let ident = " ".repeat(comment_prefix.width());
196 let mut highlighter = Highlighter::new(syntax, src, &loader, start as u32..);
197 let mut pos = highlighter.next_event_offset();
198 let mut highlight_stack = Vec::new();
199 let mut line_idx = src.byte_to_line(pos as usize);
200 let mut line_start = src.line_to_byte(line_idx) as u32;
201 let mut line_end = src.line_to_byte(line_idx + 1) as u32;
202 let mut line_highlights = Vec::new();
203 let mut res = String::new();
204 for line in src.byte_slice(..line_start as usize).lines() {
205 if line.len_bytes() != 0 {
206 wln!(res, "{ident}{line}")
207 }
208 }
209 while pos < end as u32 {
210 let (event, new_highlights) = highlighter.advance();
211 if event == HighlightEvent::Refresh {
212 highlight_stack.clear();
213 }
214 highlight_stack.extend(new_highlights.map(&get_highlight_name));
215 let start = pos;
216 pos = highlighter.next_event_offset();
217 if pos == u32::MAX {
218 pos = src.len_bytes() as u32
219 }
220 if pos <= start {
221 panic!(
222 "INVALID HIGHLIGHT RANGE: {start}..{pos} '{}' {:?}",
223 src.byte_slice(pos as usize..start as usize),
224 highlight_stack
225 );
226 }
227
228 while start >= line_end {
229 res.push_str(&ident);
230 res.extend(
231 src.byte_slice(line_start as usize..line_end as usize)
232 .chunks(),
233 );
234 annotate_line(
235 comment_prefix,
236 src,
237 line_start,
238 &mut line_highlights,
239 &mut res,
240 false,
241 );
242 line_highlights.clear();
243 line_idx += 1;
244 line_start = line_end;
245 line_end = src
246 .try_line_to_byte(line_idx + 1)
247 .unwrap_or(src.len_bytes()) as u32;
248 }
249 if !highlight_stack.is_empty() {
250 let range = start..pos.min(line_end);
251 if !range.is_empty() {
252 line_highlights.push((range, highlight_stack.clone()))
253 }
254 }
255 while pos > line_end {
256 res.push_str(&ident);
257 res.extend(
258 src.byte_slice(line_start as usize..line_end as usize)
259 .chunks(),
260 );
261 annotate_line(
262 comment_prefix,
263 src,
264 line_start,
265 &mut line_highlights,
266 &mut res,
267 !highlight_stack.is_empty(),
268 );
269 line_highlights.clear();
270 line_idx += 1;
271 line_start = line_end;
272 line_end = src
273 .try_line_to_byte(line_idx + 1)
274 .unwrap_or(src.len_bytes()) as u32;
275 line_highlights.is_empty();
276 if pos > line_start && !highlight_stack.is_empty() {
277 line_highlights.push((line_start..pos.min(line_end), Vec::new()))
278 }
279 }
280 }
281 if !line_highlights.is_empty() {
282 res.push_str(&ident);
283 res.extend(
284 src.byte_slice(line_start as usize..line_end as usize)
285 .chunks(),
286 );
287 if !res.ends_with('\n') {
288 res.push('\n');
289 }
290 annotate_line(
291 comment_prefix,
292 src,
293 line_start,
294 &mut line_highlights,
295 &mut res,
296 false,
297 );
298 line_start = line_end;
299 }
300 for line in src.byte_slice(line_start as usize..).lines() {
301 if line.len_bytes() != 0 {
302 wln!(res, "{ident}{line}")
303 }
304 }
305 res
306 }
307
308 pub fn injections_fixture(
309 comment_prefix: &str,
310 loader: &impl LanguageLoader,
311 get_language_name: impl Fn(Language) -> String,
312 syntax: &Syntax,
313 src: RopeSlice<'_>,
314 range: impl RangeBounds<usize>,
315 ) -> String {
316 let start = match range.start_bound() {
317 Bound::Included(&i) => i,
318 Bound::Excluded(&i) => i + 1,
319 Bound::Unbounded => 0,
320 };
321 let end = match range.end_bound() {
322 Bound::Included(&i) => i - 1,
323 Bound::Excluded(&i) => i,
324 Bound::Unbounded => src.len_bytes(),
325 };
326 let ident = " ".repeat(comment_prefix.width());
327 let lang = syntax.layer(syntax.root).language;
328 let language_config = loader.get_config(lang).unwrap();
329 let query = Query::new(language_config.grammar, "", |_, _| unreachable!()).unwrap();
330 let mut query_iter = QueryIter::<_, ()>::new(syntax, src, |_| Some(&query), start as u32..);
331 let event = query_iter.next();
332 let mut injection_stack = Vec::new();
333 let mut pos = if let Some(QueryIterEvent::EnterInjection(injection)) = event {
334 let language = syntax.layer(injection.layer).language;
335 injection_stack.push(get_language_name(language));
336 injection.range.start
337 } else {
338 end as u32
339 };
340 let mut line_idx = src.byte_to_line(pos as usize);
341 let mut line_start = src.line_to_byte(line_idx) as u32;
342 let mut line_end = src.line_to_byte(line_idx + 1) as u32;
343 let mut line_labels = Vec::new();
344 let mut res = String::new();
345 for line in src.byte_slice(..line_start as usize).lines() {
346 if line.len_bytes() != 0 {
347 wln!(res, "{ident}{line}")
348 }
349 }
350 let mut errors = String::new();
351 while pos < end as u32 {
352 let Some(event) = query_iter.next() else {
353 break;
354 };
355 let mut start = pos;
356 pos = event.start_byte();
357 if pos == u32::MAX {
358 pos = src.len_bytes() as u32
359 }
360 if pos <= start {
361 wln!(
362 errors,
363 "INVALID RANGE: {start}..{pos} {:?} {:?}",
364 src.byte_slice(pos as usize..start as usize),
365 injection_stack
366 );
367 start = pos;
368 }
369 if !injection_stack.is_empty() {
370 let range = start..pos.min(line_end);
371 if !range.is_empty() {
372 line_labels.push((range, injection_stack.clone()))
373 }
374 }
375
376 if start != pos {
377 while pos >= line_end {
378 res.push_str(&ident);
379 res.extend(
380 src.byte_slice(line_start as usize..line_end as usize)
381 .chunks(),
382 );
383 annotate_line(
384 comment_prefix,
385 src,
386 line_start,
387 &mut line_labels,
388 &mut res,
389 !injection_stack.is_empty() && pos > line_end,
390 );
391 line_labels.clear();
392 line_idx += 1;
393 line_start = line_end;
394 line_end = src
395 .try_line_to_byte(line_idx + 1)
396 .unwrap_or(src.len_bytes()) as u32;
397 if line_start == line_end {
398 break;
399 }
400 if pos > line_start && !injection_stack.is_empty() {
401 line_labels.push((line_start..pos.min(line_end), Vec::new()))
402 }
403 }
404 }
405
406 match event {
407 QueryIterEvent::EnterInjection(injection) => {
408 injection_stack.push(get_language_name(syntax.layer(injection.layer).language));
409 }
410 QueryIterEvent::ExitInjection { .. } => {
411 injection_stack.pop();
412 }
413 QueryIterEvent::Match(_) => unreachable!(),
414 }
415 }
416 if !line_labels.is_empty() {
417 res.push_str(&ident);
418 res.extend(
419 src.byte_slice(line_start as usize..line_end as usize)
420 .chunks(),
421 );
422 if !res.ends_with('\n') {
423 res.push('\n');
424 }
425 annotate_line(
426 comment_prefix,
427 src,
428 line_start,
429 &mut line_labels,
430 &mut res,
431 false,
432 );
433 line_start = line_end;
434 }
435 for line in src.byte_slice(line_start as usize..).lines() {
436 if line.len_bytes() != 0 {
437 wln!(res, "{ident}{line}")
438 }
439 }
440 res
441 }
442
443 fn annotate_line(
444 comment_prefix: &str,
445 src: RopeSlice<'_>,
446 line_start: u32,
447 annotations: &mut Vec<(Range, Vec<String>)>,
448 dst: &mut String,
449 continued: bool,
450 ) {
451 if annotations.is_empty() {
452 return;
453 }
454 annotations.dedup_by(|(src_range, src_scopes), (dst_range, dst_scopes)| {
455 if dst_scopes == src_scopes && dst_range.end == src_range.start {
456 dst_range.end = src_range.end;
457 true
458 } else {
459 false
460 }
461 });
462 w!(dst, "{comment_prefix}");
463 let mut prev_pos = line_start;
464 let mut offsets = Vec::with_capacity(annotations.len());
465 for (i, (range, labels)) in annotations.iter().enumerate() {
466 let offset = src
467 .byte_slice(prev_pos as usize..range.start as usize)
468 .chars()
469 .map(|c| c.width().unwrap_or(0))
470 .sum();
471 let mut width: usize = src
472 .byte_slice(range.start as usize..range.end as usize)
473 .chars()
474 .map(|c| c.width().unwrap_or(0))
475 .sum();
476 width = width.saturating_sub(1);
477 offsets.push((offset, width));
478 let first_char = if labels.is_empty() {
479 "━"
480 } else if width == 0 {
481 if i == annotations.len() - 1 {
482 "╰"
483 } else {
484 "╿"
485 }
486 } else if i == annotations.len() - 1 {
487 "┗"
488 } else {
489 "┡"
490 };
491 let last_char = if i == annotations.len() - 1 && !labels.is_empty() {
492 "┹"
493 } else if continued && i == annotations.len() - 1 {
494 "━"
495 } else {
496 "┛"
497 };
498 if width == 0 {
499 w!(dst, "{0:^offset$}{first_char}", "");
500 } else {
501 width -= 1;
502 w!(dst, "{0:^offset$}{first_char}{0:━^width$}{last_char}", "");
503 }
504 prev_pos = range.end;
505 }
506 let Some(i) = annotations
507 .iter()
508 .position(|(_, scopes)| !scopes.is_empty())
509 else {
510 wln!(dst);
511 return;
512 };
513 let highlights = &annotations[i..];
514 let offset: usize = offsets
515 .drain(..i)
516 .map(|(offset, width)| offset + width + 1)
517 .sum();
518 offsets[0].0 += offset;
519 w!(dst, "─");
520 for highlight in &highlights.last().unwrap().1 {
521 w!(dst, " {highlight}")
522 }
523 wln!(dst);
524 for depth in (0..highlights.len().saturating_sub(1)).rev() {
525 w!(dst, "{comment_prefix}");
526 for &(offset, width) in &offsets[..depth] {
527 w!(dst, "{0:^offset$}│{0:^width$}", "");
528 }
529 let offset = offsets[depth].0;
530 w!(dst, "{:>offset$}╰─", "");
531 for highlight in &highlights[depth].1 {
532 w!(dst, " {highlight}")
533 }
534 wln!(dst);
535 }
536 }