sqruff_lib_core/parser/
node_matcher.rs

1use super::matchable::MatchableTrait;
2use crate::dialects::syntax::SyntaxKind;
3use crate::errors::SQLParseError;
4use crate::parser::context::ParseContext;
5use crate::parser::match_result::{MatchResult, Matched};
6use crate::parser::matchable::Matchable;
7use crate::parser::segments::base::ErasedSegment;
8
9#[macro_export]
10macro_rules! vec_of_erased {
11    ($($elem:expr),* $(,)?) => {{
12        vec![$(ToMatchable::to_matchable($elem)),*]
13    }};
14}
15
16#[derive(Debug, Clone)]
17pub struct NodeMatcher {
18    node_kind: SyntaxKind,
19    pub(crate) match_grammar: Matchable,
20}
21
22impl NodeMatcher {
23    pub fn new(node_kind: SyntaxKind, match_grammar: Matchable) -> Self {
24        Self {
25            node_kind,
26            match_grammar,
27        }
28    }
29}
30
31impl PartialEq for NodeMatcher {
32    fn eq(&self, _other: &Self) -> bool {
33        todo!()
34    }
35}
36
37impl MatchableTrait for NodeMatcher {
38    fn get_type(&self) -> SyntaxKind {
39        self.node_kind
40    }
41
42    fn match_grammar(&self) -> Option<Matchable> {
43        self.match_grammar.clone().into()
44    }
45
46    fn elements(&self) -> &[Matchable] {
47        &[]
48    }
49
50    fn match_segments(
51        &self,
52        segments: &[ErasedSegment],
53        idx: u32,
54        parse_context: &mut ParseContext,
55    ) -> Result<MatchResult, SQLParseError> {
56        if idx >= segments.len() as u32 {
57            return Ok(MatchResult::empty_at(idx));
58        }
59
60        if segments[idx as usize].get_type() == self.get_type() {
61            return Ok(MatchResult::from_span(idx, idx + 1));
62        }
63
64        let grammar = self.match_grammar().unwrap();
65        let match_result = parse_context
66            .deeper_match(false, &[], |ctx| grammar.match_segments(segments, idx, ctx))?;
67
68        Ok(match_result.wrap(Matched::SyntaxKind(self.node_kind)))
69    }
70}