Debian Codegraph @

xtask/src/main.rs

raw symbols SCIP
1 mod docgen;
2 mod helpers;
3 mod path;
4
5 use std::{env, error::Error};
6
7 type DynError = Box<dyn Error>;
8
9 pub mod tasks {
10 use crate::DynError;
11 use std::collections::HashSet;
12
13 pub fn docgen() -> Result<(), DynError> {
14 use crate::docgen::*;
15 write(TYPABLE_COMMANDS_MD_OUTPUT, &typable_commands()?);
16 write(STATIC_COMMANDS_MD_OUTPUT, &static_commands()?);
17 write(LANG_SUPPORT_MD_OUTPUT, &lang_features()?);
18 Ok(())
19 }
20
21 pub fn querycheck(languages: impl Iterator<Item = String>) -> Result<(), DynError> {
22 use helix_core::syntax::LanguageData;
23
24 let languages_to_check: HashSet<_> = languages.collect();
25 let loader = helix_core::config::default_lang_loader();
26 for (_language, lang_data) in loader.languages() {
27 if !languages_to_check.is_empty()
28 && !languages_to_check.contains(&lang_data.config().language_id)
29 {
30 continue;
31 }
32 let config = lang_data.config();
33 let Some(syntax_config) = LanguageData::compile_syntax_config(config, &loader)? else {
34 continue;
35 };
36 let grammar = syntax_config.grammar;
37 LanguageData::compile_indent_query(grammar, config)?;
38 LanguageData::compile_textobject_query(grammar, config)?;
39 LanguageData::compile_tag_query(grammar, config)?;
40 LanguageData::compile_rainbow_query(grammar, config)?;
41 }
42
43 println!("Query check succeeded");
44
45 Ok(())
46 }
47
48 pub fn indentcheck(languages: impl Iterator<Item = String>) -> Result<(), DynError> {
49 use helix_core::{
50 indent::{
51 is_opaque_interior, is_outdent_token_at, treesitter_indent_for_pos, IndentStyle,
52 },
53 Syntax,
54 };
55 use helix_stdx::rope::RopeSliceExt;
56 use ropey::Rope;
57
58 let filter: HashSet<String> = languages.collect();
59 let loader = helix_core::config::default_lang_loader();
60 let corpus = crate::path::tests_indent();
61 let tab_width = 4;
62 let mut errors = 0usize;
63 let mut over_notes = 0usize;
64
65 let mut entries: Vec<_> = std::fs::read_dir(&corpus)?
66 .filter_map(Result::ok)
67 .map(|e| e.path())
68 .filter(|p| p.is_file())
69 .collect();
70 entries.sort();
71
72 for path in entries {
73 let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
74 if !filter.is_empty() && !filter.contains(stem) {
75 continue;
76 }
77 let file = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
78
79 // Corpus files are named <language-id>.<ext>; resolve the language by id.
80 let language = match loader
81 .languages()
82 .find(|(_, data)| data.config().language_id == stem)
83 {
84 Some((language, _)) => language,
85 None => {
86 return Err(format!(
87 "{file}: no configured language with id '{stem}' (corpus files are named <language-id>.<ext>)"
88 )
89 .into())
90 }
91 };
92
93 let config = loader.language(language).config();
94 let indent_style = IndentStyle::from_str(
95 &config
96 .indent
97 .as_ref()
98 .ok_or_else(|| format!("{file}: language '{stem}' has no indent config"))?
99 .unit,
100 );
101 // Lines that are commented out are skipped: they self-document edge
102 // cases (e.g. known indent limitations) without being asserted on.
103 let comment_tokens: Vec<String> = config.comment_tokens.clone().unwrap_or_default();
104
105 let doc = Rope::from_reader(&mut std::fs::File::open(&path)?)?;
106 let text = doc.slice(..);
107 let syntax = Syntax::new(text, language, &loader)
108 .map_err(|e| format!("{file}: failed to parse: {e:?}"))?;
109 let indent_query = loader
110 .indent_query(language)
111 .ok_or_else(|| format!("{file}: language '{stem}' has no indent query"))?;
112
113 for i in 0..doc.len_lines() {
114 let line = text.line(i);
115 let Some(pos) = line.first_non_whitespace_char() else {
116 continue;
117 };
118
119 let trimmed = line.slice(pos..).to_string();
120 if comment_tokens
121 .iter()
122 .any(|tok| trimmed.starts_with(tok.as_str()))
123 {
124 continue;
125 }
126
127 let suggested = treesitter_indent_for_pos(
128 indent_query,
129 &syntax,
130 &loader,
131 tab_width,
132 indent_style.indent_width(tab_width),
133 text,
134 i,
135 text.line_to_char(i) + pos,
136 false,
137 )
138 .unwrap()
139 .to_string(&indent_style, tab_width);
140
141 let actual = line
142 .get_slice(..pos)
143 .map(|s| s.to_string())
144 .unwrap_or_default();
145
146 if actual != suggested {
147 errors += 1;
148 println!(
149 "{file}:{}: reindent expected {} columns, computed {}",
150 i + 1,
151 actual.chars().count(),
152 suggested.chars().count(),
153 );
154 }
155
156 // Typing direction: simulate pressing Enter at the end of this line and check the indent computed for the next line.
157 // - under-indent (computed < canonical) is always a failure: nothing pulls the line further in, so the user is left
158 // under-indented.
159 // - over-indent (computed > canonical) is only acceptable when the next line's leading token is @outdent (a closing
160 // bracket, case/else/except keyword, ...): entering it dedents the line. An over-indent on a plain statement (e.g.
161 // a line after `return` that should leave the block but doesn't) has nothing to correct it and is a real failure.
162 if i + 1 < doc.len_lines() {
163 if let Some(next_pos) = text.line(i + 1).first_non_whitespace_char() {
164 let next = text.line(i + 1);
165 let next_trim = next.slice(next_pos..).to_string();
166 // Lines inside an @opaque body (string/comment) carry literal leading whitespace, not code indent — don't
167 // assert a typing indent for them.
168 let next_byte =
169 text.char_to_byte(text.line_to_char(i + 1) + next_pos) as u32;
170
171 let next_is_opaque =
172 is_opaque_interior(indent_query, &syntax, text, next_byte);
173 let next_is_comment = next_is_opaque
174 || comment_tokens
175 .iter()
176 .any(|tok| next_trim.starts_with(tok.as_str()));
177
178 if !next_is_comment {
179 let typed = treesitter_indent_for_pos(
180 indent_query,
181 &syntax,
182 &loader,
183 tab_width,
184 indent_style.indent_width(tab_width),
185 text,
186 i,
187 text.line_to_char(i + 1) - 1,
188 true,
189 )
190 .unwrap()
191 .to_string(&indent_style, tab_width);
192
193 let next_actual = next
194 .get_slice(..next_pos)
195 .map(|s| s.to_string())
196 .unwrap_or_default();
197
198 let typed_cols = typed.chars().count();
199 let want_cols = next_actual.chars().count();
200 let leading_outdent = || {
201 let byte = text.char_to_byte(text.line_to_char(i + 1) + next_pos);
202 is_outdent_token_at(indent_query, &syntax, text, byte as u32)
203 };
204
205 if typed_cols < want_cols {
206 errors += 1;
207 println!(
208 "{file}:{}: typing under-indents: computed {} columns, expected {} | {}",
209 i + 2,
210 typed_cols,
211 want_cols,
212 next_trim.trim_end(),
213 );
214 } else if typed_cols > want_cols && !leading_outdent() {
215 // Over-indents are reported but not failed: every over-indent sits at a legitimate dedent point, and
216 // for indent-delimited languages (python after a block) the editor genuinely cannot know how far to
217 // dedent. Surfaced so a regression shows up in the diff; gate on under-indents only.
218 over_notes += 1;
219 println!(
220 "{file}:{}: note: typing over-indents: computed {} columns, expected {} (no leading outdent; review) | {}",
221 i + 2,
222 typed_cols,
223 want_cols,
224 next_trim.trim_end(),
225 );
226 }
227 }
228 }
229 }
230 }
231 }
232
233 if over_notes > 0 {
234 println!("Indent check: {over_notes} typing over-indent note(s) (not failures; review for regressions)");
235 }
236 match errors {
237 0 => {
238 println!("Indent check succeeded");
239 Ok(())
240 }
241 n => Err(format!("Indent check failed: {n} line(s) with wrong indentation").into()),
242 }
243 }
244
245 pub fn themecheck(themes: impl Iterator<Item = String>) -> Result<(), DynError> {
246 use helix_view::theme::Loader;
247
248 let themes_to_check: HashSet<_> = themes.collect();
249
250 let theme_names = [
251 vec!["default".to_string(), "base16_default".to_string()],
252 Loader::read_names(&crate::path::themes()),
253 ]
254 .concat();
255 let loader = Loader::new(&[crate::path::runtime()]);
256 let mut errors_present = false;
257
258 for name in theme_names {
259 if !themes_to_check.is_empty() && !themes_to_check.contains(&name) {
260 continue;
261 }
262
263 let (_, warnings) = loader.load_with_warnings(&name).unwrap();
264
265 if !warnings.is_empty() {
266 errors_present = true;
267 println!("Theme '{name}' loaded with errors:");
268 for warning in warnings {
269 println!("\t* {}", warning);
270 }
271 }
272 }
273
274 match errors_present {
275 true => Err("Errors found when loading bundled themes".into()),
276 false => {
277 println!("Theme check successful!");
278 Ok(())
279 }
280 }
281 }
282
283 pub fn highlightcheck(args: impl Iterator<Item = String>) -> Result<(), DynError> {
284 use helix_core::syntax::{HighlightEvent, Loader, Syntax};
285 use helix_core::Language;
286 use ropey::Rope;
287
288 // The highlighter yields a `Highlight` index into the loader's scope
289 // list. Feed it the capture names actually used across the bundled
290 // queries, so every capture maps to itself and we read back the exact
291 // `@capture` that won — no hand-maintained scope list. (Inheritance is
292 // irrelevant here: scanning every language's queries unions all names.)
293 fn capture_scopes() -> Vec<String> {
294 let mut set = std::collections::BTreeSet::new();
295 let Ok(langs) = std::fs::read_dir(crate::path::ts_queries()) else {
296 return Vec::new();
297 };
298 for lang in langs.filter_map(Result::ok) {
299 for q in ["highlights.scm", "locals.scm"] {
300 let Ok(text) = std::fs::read_to_string(lang.path().join(q)) else {
301 continue;
302 };
303 let b = text.as_bytes();
304 let mut i = 0;
305 while i < b.len() {
306 if b[i] != b'@' {
307 i += 1;
308 continue;
309 }
310 let s = i + 1;
311 let mut j = s;
312 while j < b.len()
313 && (b[j].is_ascii_alphanumeric() || matches!(b[j], b'.' | b'_' | b'-'))
314 {
315 j += 1;
316 }
317 let name = &text[s..j];
318 i = j;
319 if name.is_empty() || name.starts_with('_') {
320 continue;
321 }
322 // Locals: the highlight applied to a resolved reference is
323 // the class after `local.definition.`; the rest are structural.
324 if let Some(class) = name.strip_prefix("local.definition.") {
325 if !class.is_empty() {
326 set.insert(class.to_string());
327 }
328 } else if !name.starts_with("local.") && name != "local" {
329 set.insert(name.to_string());
330 }
331 }
332 }
333 }
334 set.into_iter().collect()
335 }
336
337 // Winning (top-of-stack) capture per byte range, via the real highlighter.
338 fn spans(
339 loader: &Loader,
340 scopes: &[String],
341 language: Language,
342 source: &str,
343 ) -> Option<Vec<(usize, usize, String)>> {
344 let rope = Rope::from_str(source);
345 // None when the grammar isn't built, so callers can skip rather than
346 // panic (a no-language run only needs the corpus' grammars built).
347 let syntax = Syntax::new(rope.slice(..), language, loader).ok()?;
348 let mut hl = syntax.highlighter(rope.slice(..), loader, ..);
349 let mut active: Vec<u32> = Vec::new();
350 let mut start: u32 = 0;
351 let len = source.len() as u32;
352 let mut out = Vec::new();
353 loop {
354 let off = hl.next_event_offset();
355 let cur = if off == u32::MAX { len } else { off };
356 if cur > start {
357 if let Some(idx) = active.last() {
358 out.push((start as usize, cur as usize, scopes[*idx as usize].clone()));
359 }
360 }
361 if off == u32::MAX {
362 break;
363 }
364 let (event, highlights) = hl.advance();
365 let v: Vec<u32> = highlights.map(|h| h.get()).collect();
366 match event {
367 HighlightEvent::Refresh => active = v,
368 HighlightEvent::Push => active.extend(v),
369 }
370 start = off;
371 }
372 Some(out)
373 }
374
375 let scopes = capture_scopes();
376 let loader = helix_core::config::default_lang_loader();
377 loader.set_scopes(scopes.clone());
378
379 let args: Vec<String> = args.collect();
380
381 // `--dump <language> <file>`: print the winning capture per span, for
382 // discovering the exact `@capture` names when authoring assertions.
383 if args.first().map(String::as_str) == Some("--dump") {
384 let lang = args
385 .get(1)
386 .ok_or("usage: highlight-check --dump <language> <file>")?;
387 let file = args
388 .get(2)
389 .ok_or("usage: highlight-check --dump <language> <file>")?;
390 let language = loader
391 .language_for_name(lang.as_str())
392 .ok_or_else(|| format!("unknown language '{lang}'"))?;
393 let source = std::fs::read_to_string(file)?;
394 let sp = spans(&loader, &scopes, language, &source)
395 .ok_or_else(|| format!("could not highlight (grammar for '{lang}' not built?)"))?;
396 for (s, e, scope) in sp {
397 let text = &source[s..e];
398 if !text.trim().is_empty() {
399 println!("{scope}\t{text:?}");
400 }
401 }
402 return Ok(());
403 }
404
405 // Corpus mode: nvim-treesitter-style highlight tests laid out under
406 // tests/query/highlights/<language-id>/<name>.<ext>. A comment line
407 // below the code carries caret assertions whose columns line up with the
408 // tokens above:
409 //
410 // foo(bar)
411 // // ^ @function
412 // // ^^^ @variable
413 //
414 // Each `^` checks the *winning* capture at the column above it; the
415 // expected `@capture` must match exactly (a leading `!` negates). This
416 // catches precedence bugs query-check cannot — e.g. a call captured on a
417 // wrapper node that the inner `(identifier) @variable` then wins.
418 let filter: HashSet<String> = args.into_iter().collect();
419 let root = crate::path::tests_highlight();
420 let mut files: Vec<(String, std::path::PathBuf)> = Vec::new();
421 for lang_dir in std::fs::read_dir(&root)?.filter_map(Result::ok) {
422 if !lang_dir.path().is_dir() {
423 continue;
424 }
425 let lang = lang_dir.file_name().to_string_lossy().into_owned();
426 if !filter.is_empty() && !filter.contains(&lang) {
427 continue;
428 }
429 for f in std::fs::read_dir(lang_dir.path())?.filter_map(Result::ok) {
430 if f.path().is_file() {
431 files.push((lang.clone(), f.path()));
432 }
433 }
434 }
435 files.sort();
436
437 let mut errors = 0usize;
438 let mut checks = 0usize;
439 for (lang, path) in files {
440 let language = match loader
441 .languages()
442 .find(|(_, d)| d.config().language_id == lang)
443 {
444 Some((language, _)) => language,
445 None => {
446 return Err(
447 format!("{}: no configured language '{lang}'", path.display()).into(),
448 )
449 }
450 };
451 let source = std::fs::read_to_string(&path)?;
452 let Some(sp) = spans(&loader, &scopes, language, &source) else {
453 eprintln!("{}: skipped ('{lang}' grammar not built)", path.display());
454 continue;
455 };
456 let at = |byte: usize| -> Option<&str> {
457 sp.iter()
458 .find(|(s, e, _)| *s <= byte && byte < *e)
459 .map(|(_, _, n)| n.as_str())
460 };
461
462 let lines: Vec<&str> = source.lines().collect();
463 let mut line_start = Vec::with_capacity(lines.len());
464 let mut off = 0usize;
465 for l in &lines {
466 line_start.push(off);
467 off += l.len() + 1;
468 }
469
470 let rel = path.strip_prefix(&root).unwrap_or(&path).display();
471 let mut base: Option<usize> = None;
472 for (li, line) in lines.iter().enumerate() {
473 // An assertion line is a comment whose first `^` is preceded only
474 // by the comment leader (no alphanumerics), so code like `a ^ b`
475 // is never mistaken for one.
476 let marker = line
477 .find('^')
478 .filter(|&c| !line[..c].bytes().any(|b| b.is_ascii_alphanumeric()));
479 let Some(col) = marker else {
480 if !line.trim().is_empty() {
481 base = Some(li);
482 }
483 continue;
484 };
485 let Some(brow) = base else { continue };
486 let len = line[col..].bytes().take_while(|b| *b == b'^').count();
487 let mut exp = line[col + len..].trim();
488 let negate = exp.starts_with('!');
489 if negate {
490 exp = exp[1..].trim_start();
491 }
492 // First whitespace-delimited token after the caret, with a
493 // leading `@` stripped — so a trailing comment close (OCaml
494 // `*)`, HTML `-->`) isn't swallowed into the expected name.
495 let exp = exp
496 .trim_start_matches('@')
497 .split_whitespace()
498 .next()
499 .unwrap_or("");
500 if exp.is_empty() {
501 continue;
502 }
503 let code = lines[brow];
504 for c in col..col + len {
505 // Skip carets that fall past the code line or over whitespace.
506 match code.as_bytes().get(c) {
507 None => continue,
508 Some(b) if b.is_ascii_whitespace() => continue,
509 _ => {}
510 }
511 checks += 1;
512 let got = at(line_start[brow] + c);
513 if (got == Some(exp)) != negate {
514 continue;
515 }
516 errors += 1;
517 eprintln!(
518 "{rel}:{}:{}: expected {}{} but got {}",
519 brow + 1,
520 c + 1,
521 if negate { "not " } else { "" },
522 exp,
523 got.unwrap_or("<unhighlighted>")
524 );
525 }
526 }
527 }
528
529 if errors > 0 {
530 return Err(
531 format!("Highlight check failed: {errors} of {checks} assertion(s) wrong").into(),
532 );
533 }
534 println!("Highlight check succeeded ({checks} assertions)");
535 Ok(())
536 }
537
538 pub fn print_help() {
539 println!(
540 "
541 Usage: Run with `cargo xtask <task>`, eg. `cargo xtask docgen`.
542
543 Tasks:
544 docgen Generate files to be included in the mdbook output.
545 query-check [languages] Check that tree-sitter queries are valid for the given
546 languages, or all languages if none are specified.
547 indent-check [languages] Check indentation for the corpus files in tests/indent/
548 (named <language-id>.<ext>) against the configured grammars,
549 for the given languages, or all corpus files if none are specified.
550 highlight-check [languages]
551 Check highlight queries against the real highlighter using the
552 nvim-treesitter-style tests under tests/query/highlights/
553 <language-id>/<name>.<ext> (caret comment lines like
554 `// ^^^ @capture` assert the winning capture at the column
555 above), for the given languages, or all if none are specified.
556 `highlight-check --dump <language> <file>` instead prints the
557 winning capture per span for an arbitrary input file.
558 theme-check [themes] Check that the theme files in runtime/themes/ are valid for the
559 given themes, or all themes if none are specified.
560 "
561 );
562 }
563 }
564
565 fn main() -> Result<(), DynError> {
566 let mut args = env::args().skip(1);
567 let task = args.next();
568 match task {
569 None => tasks::print_help(),
570 Some(t) => match t.as_str() {
571 "docgen" => tasks::docgen()?,
572 "query-check" => tasks::querycheck(args)?,
573 "indent-check" => tasks::indentcheck(args)?,
574 "highlight-check" => tasks::highlightcheck(args)?,
575 "theme-check" => tasks::themecheck(args)?,
576 invalid => return Err(format!("Invalid task name: {}", invalid).into()),
577 },
578 };
579 Ok(())
580 }