1use std::collections::BTreeMap;
16
17use harn_hostlib::ast::{api, Language};
18use regex::Regex;
19use streaming_iterator::StreamingIterator;
20use tree_sitter::{Node, Query, QueryCursor};
21
22use crate::engine::{Binding, Span};
23use crate::error::RulesError;
24use crate::model::{AtomicMatcher, RuleNode, StopBy, StopKeyword};
25use crate::pattern::{compile_pattern, ROOT_CAPTURE};
26
27type Bindings = BTreeMap<String, Binding>;
29
30pub struct EvalMatch {
32 pub span: Span,
34 pub text: String,
36 pub bindings: Bindings,
38}
39
40pub struct CompiledRuleTree {
43 top: CompiledNode,
44 utils: BTreeMap<String, CompiledNode>,
45}
46
47struct CompiledNode {
48 atomic: Option<CompiledAtomic>,
49 inside: Option<Box<CompiledRel>>,
50 has: Option<Box<CompiledRel>>,
51 follows: Option<Box<CompiledRel>>,
52 precedes: Option<Box<CompiledRel>>,
53 all: Vec<CompiledNode>,
54 any: Vec<CompiledNode>,
55 not: Option<Box<CompiledNode>>,
56 matches: Option<String>,
57}
58
59struct CompiledRel {
60 node: CompiledNode,
61 stop_by: CompiledStopBy,
62 field: Option<String>,
63}
64
65enum CompiledStopBy {
66 Neighbor,
67 End,
68 Rule(Box<CompiledNode>),
69}
70
71enum CompiledAtomic {
72 Query { query: Query, metavars: Vec<String> },
73 Kind(String),
74 Regex(Regex),
75}
76
77impl CompiledRuleTree {
78 pub fn compile(
81 rule_id: &str,
82 language: Language,
83 top: &RuleNode,
84 utils: &BTreeMap<String, RuleNode>,
85 ) -> Result<Self, RulesError> {
86 if top.is_empty() {
87 return Err(RulesError::PatternCompile {
88 rule: rule_id.to_string(),
89 message: "rule node is empty (no atomic / relational / composite key)".into(),
90 });
91 }
92 let compiled_utils = utils
93 .iter()
94 .map(|(id, node)| Ok((id.clone(), compile_node(rule_id, language, node)?)))
95 .collect::<Result<BTreeMap<_, _>, RulesError>>()?;
96 Ok(CompiledRuleTree {
97 top: compile_node(rule_id, language, top)?,
98 utils: compiled_utils,
99 })
100 }
101
102 pub fn find(
104 &self,
105 rule_id: &str,
106 language: Language,
107 source: &str,
108 ) -> Result<Vec<EvalMatch>, RulesError> {
109 let tree = api::parse_tree(source, language).map_err(|err| RulesError::SourceParse {
110 rule: rule_id.to_string(),
111 message: err.to_string(),
112 })?;
113 let ctx = Ctx {
114 source,
115 utils: &self.utils,
116 };
117 let root = tree.root_node();
118
119 let mut seen: BTreeMap<(usize, usize), EvalMatch> = BTreeMap::new();
120 for node in seed_candidates(&self.top, &ctx, root) {
121 if let Some(bindings) = node_satisfies(&self.top, node, &ctx) {
122 let key = (node.start_byte(), node.end_byte());
123 seen.entry(key).or_insert_with(|| EvalMatch {
124 span: Span::of(node),
125 text: ctx.text(node),
126 bindings,
127 });
128 }
129 }
130 Ok(seen.into_values().collect())
131 }
132}
133
134struct Ctx<'a> {
136 source: &'a str,
137 utils: &'a BTreeMap<String, CompiledNode>,
138}
139
140impl Ctx<'_> {
141 fn text(&self, node: Node<'_>) -> String {
142 self.source[node.start_byte()..node.end_byte()].to_string()
143 }
144}
145
146fn compile_node(
151 rule_id: &str,
152 language: Language,
153 node: &RuleNode,
154) -> Result<CompiledNode, RulesError> {
155 let mkerr = |message: String| RulesError::PatternCompile {
156 rule: rule_id.to_string(),
157 message,
158 };
159
160 let atomic = match node.atomic().map_err(mkerr)? {
161 None => None,
162 Some(AtomicMatcher::Pattern(snippet)) => {
163 let ts_language = language
164 .ts_language()
165 .ok_or_else(|| mkerr(format!("grammar for `{}` unavailable", language.name())))?;
166 let compiled =
167 compile_pattern(&snippet, language).map_err(|m| mkerr(format!("pattern: {m}")))?;
168 let query = Query::new(&ts_language, &compiled.query).map_err(|e| {
169 RulesError::QueryRejected {
170 rule: rule_id.to_string(),
171 message: e.to_string(),
172 query: compiled.query.clone(),
173 }
174 })?;
175 Some(CompiledAtomic::Query {
176 query,
177 metavars: compiled.metavars,
178 })
179 }
180 Some(AtomicMatcher::Kind(kind)) => Some(CompiledAtomic::Kind(kind)),
181 Some(AtomicMatcher::Regex(re)) => Some(CompiledAtomic::Regex(
182 Regex::new(&re).map_err(|e| mkerr(format!("regex `{re}` invalid: {e}")))?,
183 )),
184 Some(AtomicMatcher::RawQuery(raw)) => {
185 let ts_language = language
186 .ts_language()
187 .ok_or_else(|| mkerr(format!("grammar for `{}` unavailable", language.name())))?;
188 let query = Query::new(&ts_language, &raw).map_err(|e| RulesError::QueryRejected {
189 rule: rule_id.to_string(),
190 message: e.to_string(),
191 query: raw.clone(),
192 })?;
193 if !query.capture_names().contains(&ROOT_CAPTURE) {
199 return Err(mkerr(format!(
200 "raw `query` must bind the matched node to `@{ROOT_CAPTURE}`"
201 )));
202 }
203 let metavars = query
204 .capture_names()
205 .iter()
206 .filter(|name| **name != ROOT_CAPTURE)
207 .map(|name| name.to_string())
208 .collect();
209 Some(CompiledAtomic::Query { query, metavars })
210 }
211 };
212
213 let rel = |sub: &Option<Box<RuleNode>>| -> Result<Option<Box<CompiledRel>>, RulesError> {
214 match sub {
215 None => Ok(None),
216 Some(n) => Ok(Some(Box::new(compile_rel(rule_id, language, n)?))),
217 }
218 };
219
220 let compile_list = |list: &Option<Vec<RuleNode>>| -> Result<Vec<CompiledNode>, RulesError> {
221 list.iter()
222 .flatten()
223 .map(|n| compile_node(rule_id, language, n))
224 .collect()
225 };
226
227 Ok(CompiledNode {
228 atomic,
229 inside: rel(&node.inside)?,
230 has: rel(&node.has)?,
231 follows: rel(&node.follows)?,
232 precedes: rel(&node.precedes)?,
233 all: compile_list(&node.all)?,
234 any: compile_list(&node.any)?,
235 not: match &node.not {
236 None => None,
237 Some(n) => Some(Box::new(compile_node(rule_id, language, n)?)),
238 },
239 matches: node.matches.clone(),
240 })
241}
242
243fn compile_rel(
244 rule_id: &str,
245 language: Language,
246 node: &RuleNode,
247) -> Result<CompiledRel, RulesError> {
248 let stop_by = match &node.stop_by {
249 None | Some(StopBy::Keyword(StopKeyword::Neighbor)) => CompiledStopBy::Neighbor,
250 Some(StopBy::Keyword(StopKeyword::End)) => CompiledStopBy::End,
251 Some(StopBy::Rule(r)) => {
252 CompiledStopBy::Rule(Box::new(compile_node(rule_id, language, r)?))
253 }
254 };
255 Ok(CompiledRel {
256 node: compile_node(rule_id, language, node)?,
257 stop_by,
258 field: node.field.clone(),
259 })
260}
261
262fn seed_candidates<'t>(top: &CompiledNode, ctx: &Ctx<'_>, root: Node<'t>) -> Vec<Node<'t>> {
269 match &top.atomic {
270 Some(CompiledAtomic::Query { query, .. }) => {
271 let mut out = Vec::new();
272 let mut seen = std::collections::HashSet::new();
273 let root_index = root_capture_index(query);
274 let mut cursor = QueryCursor::new();
275 let mut it = cursor.matches(query, root, ctx.source.as_bytes());
276 while let Some(m) = it.next() {
277 for cap in m.captures {
278 if Some(cap.index) == root_index && seen.insert(cap.node.id()) {
279 out.push(cap.node);
280 }
281 }
282 }
283 out
284 }
285 Some(CompiledAtomic::Kind(kind)) => {
286 let mut out = Vec::new();
287 for_each_named_descendant(root, &mut |n| {
288 if n.kind() == kind {
289 out.push(n);
290 }
291 });
292 out
293 }
294 Some(CompiledAtomic::Regex(_)) | None => {
295 let mut out = Vec::new();
296 for_each_named_descendant(root, &mut |n| out.push(n));
297 out
298 }
299 }
300}
301
302fn node_satisfies(cnode: &CompiledNode, node: Node<'_>, ctx: &Ctx<'_>) -> Option<Bindings> {
304 let mut bindings = Bindings::new();
305
306 if let Some(atomic) = &cnode.atomic {
307 merge(&mut bindings, atomic_match(atomic, node, ctx)?);
308 }
309 if let Some(rel) = &cnode.inside {
310 merge(&mut bindings, eval_inside(rel, node, ctx)?);
311 }
312 if let Some(rel) = &cnode.has {
313 merge(&mut bindings, eval_has(rel, node, ctx)?);
314 }
315 if let Some(rel) = &cnode.follows {
316 merge(&mut bindings, eval_sibling(rel, node, ctx, Dir::Before)?);
317 }
318 if let Some(rel) = &cnode.precedes {
319 merge(&mut bindings, eval_sibling(rel, node, ctx, Dir::After)?);
320 }
321 for sub in &cnode.all {
322 merge(&mut bindings, node_satisfies(sub, node, ctx)?);
323 }
324 if !cnode.any.is_empty() {
325 let matched = cnode
326 .any
327 .iter()
328 .find_map(|sub| node_satisfies(sub, node, ctx));
329 merge(&mut bindings, matched?);
330 }
331 if let Some(not) = &cnode.not {
332 if node_satisfies(not, node, ctx).is_some() {
333 return None;
334 }
335 }
336 if let Some(id) = &cnode.matches {
337 let util = ctx.utils.get(id)?;
338 merge(&mut bindings, node_satisfies(util, node, ctx)?);
339 }
340
341 Some(bindings)
342}
343
344fn atomic_match(atomic: &CompiledAtomic, node: Node<'_>, ctx: &Ctx<'_>) -> Option<Bindings> {
345 match atomic {
346 CompiledAtomic::Kind(kind) => (node.kind() == kind).then(Bindings::new),
347 CompiledAtomic::Regex(re) => re.is_match(&ctx.text(node)).then(Bindings::new),
348 CompiledAtomic::Query { query, metavars } => {
349 let root_index = root_capture_index(query);
350 let names: Vec<&str> = query.capture_names().to_vec();
351 let mut cursor = QueryCursor::new();
352 let mut it = cursor.matches(query, node, ctx.source.as_bytes());
353 while let Some(m) = it.next() {
354 let roots_here = m
356 .captures
357 .iter()
358 .any(|c| Some(c.index) == root_index && c.node.id() == node.id());
359 if !roots_here {
360 continue;
361 }
362 let mut bindings = Bindings::new();
363 for cap in m.captures {
364 let name = names[cap.index as usize];
365 if metavars.iter().any(|mv| mv == name) {
366 bindings.entry(name.to_string()).or_insert_with(|| {
367 Binding::new(ctx.text(cap.node), Span::of(cap.node))
368 });
369 }
370 }
371 return Some(bindings);
372 }
373 None
374 }
375 }
376}
377
378fn eval_inside(rel: &CompiledRel, node: Node<'_>, ctx: &Ctx<'_>) -> Option<Bindings> {
379 let mut current = node.parent();
380 let mut child = node;
381 while let Some(ancestor) = current {
382 if let CompiledStopBy::Rule(stop) = &rel.stop_by {
383 if node_satisfies(stop, ancestor, ctx).is_some()
384 && node_satisfies(&rel.node, ancestor, ctx).is_none()
385 {
386 return None;
388 }
389 }
390 if let Some(b) = node_satisfies(&rel.node, ancestor, ctx) {
391 if field_ok(rel.field.as_deref(), ancestor, child) {
392 return Some(b);
393 }
394 }
395 if matches!(rel.stop_by, CompiledStopBy::Neighbor) {
396 return None;
397 }
398 child = ancestor;
399 current = ancestor.parent();
400 }
401 None
402}
403
404fn eval_has(rel: &CompiledRel, node: Node<'_>, ctx: &Ctx<'_>) -> Option<Bindings> {
405 let neighbor = matches!(rel.stop_by, CompiledStopBy::Neighbor);
406 let mut found: Option<Bindings> = None;
407 let mut cursor = node.walk();
408 let children: Vec<Node<'_>> = node.named_children(&mut cursor).collect();
409 for child in children {
410 if let Some(b) = node_satisfies(&rel.node, child, ctx) {
411 if field_ok(rel.field.as_deref(), node, child) {
412 found = Some(b);
413 break;
414 }
415 }
416 if !neighbor {
417 if let Some(b) = eval_has(rel, child, ctx) {
418 found = Some(b);
419 break;
420 }
421 }
422 }
423 found
424}
425
426enum Dir {
427 Before,
428 After,
429}
430
431fn eval_sibling(rel: &CompiledRel, node: Node<'_>, ctx: &Ctx<'_>, dir: Dir) -> Option<Bindings> {
432 let neighbor = matches!(rel.stop_by, CompiledStopBy::Neighbor);
433 let mut sib = match dir {
434 Dir::Before => node.prev_named_sibling(),
435 Dir::After => node.next_named_sibling(),
436 };
437 while let Some(s) = sib {
438 if let Some(b) = node_satisfies(&rel.node, s, ctx) {
439 return Some(b);
440 }
441 if neighbor {
442 return None;
443 }
444 sib = match dir {
445 Dir::Before => s.prev_named_sibling(),
446 Dir::After => s.next_named_sibling(),
447 };
448 }
449 None
450}
451
452fn field_ok(field: Option<&str>, parent: Node<'_>, child: Node<'_>) -> bool {
456 match field {
457 None => true,
458 Some(name) => parent
459 .child_by_field_name(name)
460 .is_some_and(|f| f.id() == child.id()),
461 }
462}
463
464fn merge(into: &mut Bindings, from: Bindings) {
465 for (k, v) in from {
466 into.entry(k).or_insert(v);
467 }
468}
469
470fn root_capture_index(query: &Query) -> Option<u32> {
471 query
472 .capture_names()
473 .iter()
474 .position(|n| *n == ROOT_CAPTURE)
475 .map(|i| i as u32)
476}
477
478fn for_each_named_descendant<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
479 let mut cursor = node.walk();
480 for child in node.named_children(&mut cursor) {
481 f(child);
482 for_each_named_descendant(child, f);
483 }
484}