Debian Codegraph @

Xtree-house/highlighter/src/config.rs

raw symbols SCIP
1 use once_cell::sync::Lazy;
2 use regex::Regex;
3 use tree_sitter::{query, Grammar};
4
5 use crate::highlighter::{Highlight, HighlightQuery};
6 use crate::injections_query::{InjectionLanguageMarker, InjectionsQuery};
7 use crate::Language;
8
9 use std::fmt::Write;
10
11 #[derive(Debug)]
12 pub struct LanguageConfig {
13 pub grammar: Grammar,
14 pub highlight_query: HighlightQuery,
15 pub injection_query: InjectionsQuery,
16 }
17
18 impl LanguageConfig {
19 pub fn new(
20 grammar: Grammar,
21 highlight_query_text: &str,
22 injection_query_text: &str,
23 local_query_text: &str,
24 ) -> Result<Self, query::ParseError> {
25 // NOTE: the injection queries are parsed first since the local query is passed as-is
26 // to `Query::new` in `InjectionsQuery::new`. This ensures that the more readable error
27 // bubbles up first if the locals queries have an issue.
28 let injection_query =
29 InjectionsQuery::new(grammar, injection_query_text, local_query_text)?;
30 let highlight_query = HighlightQuery::new(grammar, highlight_query_text, local_query_text)?;
31
32 Ok(Self {
33 grammar,
34 highlight_query,
35 injection_query,
36 })
37 }
38
39 pub fn configure(&self, mut f: impl FnMut(&str) -> Option<Highlight>) {
40 self.highlight_query.configure(&mut f);
41 self.injection_query.configure(&mut f);
42 }
43 }
44
45 static INHERITS_REGEX: Lazy<Regex> =
46 Lazy::new(|| Regex::new(r";+\s*inherits\s*:?\s*([a-z_,()-]+)\s*").unwrap());
47
48 /// reads a query by invoking `read_query_text`, handles any `inherits` directives
49 pub fn read_query(language: &str, mut read_query_text: impl FnMut(&str) -> String) -> String {
50 fn read_query_impl(
51 language: &str,
52 read_query_text: &mut impl FnMut(&str) -> String,
53 // The chain of languages currently being expanded, used to break cyclic
54 // `; inherits:` directives (e.g. `a` inherits `b` and `b` inherits `a`).
55 chain: &mut Vec<String>,
56 ) -> String {
57 if chain.iter().any(|ancestor| ancestor == language) {
58 return String::new();
59 }
60 chain.push(language.to_string());
61 let query = read_query_text(language);
62
63 // replaces all "; inherits <language>(,<language>)*" with the queries of the given language(s)
64 let result = INHERITS_REGEX
65 .replace_all(&query, |captures: &regex::Captures| {
66 captures[1]
67 .split(',')
68 .fold(String::new(), |mut output, language| {
69 // `write!` to a String cannot fail.
70 write!(
71 output,
72 "\n{}\n",
73 read_query_impl(language, &mut *read_query_text, chain)
74 )
75 .unwrap();
76 output
77 })
78 })
79 .into_owned();
80 chain.pop();
81 result
82 }
83 read_query_impl(language, &mut read_query_text, &mut Vec::new())
84 }
85
86 pub trait LanguageLoader {
87 fn language_for_marker(&self, marker: InjectionLanguageMarker) -> Option<Language>;
88 fn get_config(&self, lang: Language) -> Option<&LanguageConfig>;
89 }
90
91 impl<T> LanguageLoader for &'_ T
92 where
93 T: LanguageLoader,
94 {
95 fn language_for_marker(&self, marker: InjectionLanguageMarker) -> Option<Language> {
96 T::language_for_marker(self, marker)
97 }
98
99 fn get_config(&self, lang: Language) -> Option<&LanguageConfig> {
100 T::get_config(self, lang)
101 }
102 }
103
104 #[cfg(test)]
105 mod tests {
106 use super::read_query;
107
108 #[test]
109 fn read_query_breaks_inherits_cycle() {
110 // `a` inherits `b` and `b` inherits `a`: resolution must terminate rather than
111 // recurse until the stack overflows, and still include both queries' own patterns.
112 let result = read_query("a", |lang| match lang {
113 "a" => "; inherits: b\n(a_pattern) @a".to_string(),
114 "b" => "; inherits: a\n(b_pattern) @b".to_string(),
115 _ => String::new(),
116 });
117 assert!(
118 result.contains("@a"),
119 "missing a's own patterns: {result:?}"
120 );
121 assert!(
122 result.contains("@b"),
123 "missing b's own patterns: {result:?}"
124 );
125 }
126
127 #[test]
128 fn read_query_breaks_self_inherit() {
129 let result = read_query("a", |lang| match lang {
130 "a" => "; inherits: a\n(a_pattern) @a".to_string(),
131 _ => String::new(),
132 });
133 assert!(
134 result.contains("@a"),
135 "missing a's own patterns: {result:?}"
136 );
137 }
138 }