Skip to main content

ll_sparql_parser/ast/
mod.rs

1mod utils;
2use crate::{syntax_kind::SyntaxKind, Sparql, SyntaxNode};
3use rowan::{cursor::SyntaxToken, SyntaxNodeChildren, TextRange, TextSize};
4use std::usize;
5use utils::nth_ancestor;
6
7#[derive(Debug, PartialEq)]
8pub struct QueryUnit {
9    syntax: SyntaxNode,
10}
11
12impl QueryUnit {
13    pub fn select_query(&self) -> Option<SelectQuery> {
14        SelectQuery::cast(
15            self.syntax
16                .first_child()?
17                .first_child_by_kind(&SelectQuery::can_cast)?,
18        )
19    }
20
21    pub fn strip_prologue(&self) -> Option<SyntaxNode> {
22        self.syntax
23            .children()
24            .skip_while(|node| node.kind() == SyntaxKind::Prologue)
25            .next()
26    }
27
28    pub fn prologue(&self) -> Option<Prologue> {
29        Prologue::cast(
30            self.syntax
31                .first_child()?
32                .first_child_by_kind(&Prologue::can_cast)?,
33        )
34    }
35}
36
37#[derive(Debug, PartialEq)]
38pub struct Prologue {
39    syntax: SyntaxNode,
40}
41
42impl Prologue {
43    pub fn prefix_declarations(&self) -> Vec<PrefixDeclaration> {
44        self.syntax
45            .children()
46            .filter_map(&PrefixDeclaration::cast)
47            .collect()
48    }
49}
50
51#[derive(Debug, PartialEq)]
52pub struct SolutionModifier {
53    syntax: SyntaxNode,
54}
55
56impl SolutionModifier {
57    pub fn group_clause(&self) -> Option<GroupClause> {
58        GroupClause::cast(self.syntax.first_child()?)
59    }
60
61    pub fn select_query(&self) -> Option<SelectQuery> {
62        self.syntax.parent().and_then(SelectQuery::cast)
63    }
64}
65
66#[derive(Debug, PartialEq, Clone)]
67pub struct GroupClause {
68    syntax: SyntaxNode,
69}
70
71impl GroupClause {
72    pub fn select_query(&self) -> Option<SelectQuery> {
73        self.syntax
74            .parent()
75            .and_then(|p| p.parent())
76            .and_then(SelectQuery::cast)
77    }
78}
79
80#[derive(Debug, PartialEq)]
81pub struct PrefixDeclaration {
82    syntax: SyntaxNode,
83}
84
85impl PrefixDeclaration {
86    pub fn prefix(&self) -> Option<String> {
87        Some(
88            self.syntax
89                .first_child_or_token_by_kind(&|kind| kind == SyntaxKind::PNAME_NS)?
90                .to_string()
91                .split_once(":")
92                .expect("Every PNAME_NS should contain ':' at the end")
93                .0
94                .to_string(),
95        )
96    }
97
98    pub fn raw_uri_prefix(&self) -> Option<String> {
99        let s = self
100            .syntax
101            .first_child_or_token_by_kind(&|kind| kind == SyntaxKind::IRIREF)?
102            .to_string();
103        (s.len() >= 2).then_some(s[1..(s.len() - 1)].to_string())
104    }
105
106    pub fn uri_prefix(&self) -> Option<String> {
107        Some(
108            self.syntax
109                .first_child_or_token_by_kind(&|kind| kind == SyntaxKind::IRIREF)?
110                .to_string(),
111        )
112    }
113}
114
115#[derive(Debug, PartialEq)]
116pub struct SelectQuery {
117    syntax: SyntaxNode,
118}
119
120impl SelectQuery {
121    pub fn where_clause(&self) -> Option<WhereClause> {
122        WhereClause::cast(self.syntax.first_child_by_kind(&WhereClause::can_cast)?)
123    }
124    pub fn select_clause(&self) -> Option<SelectClause> {
125        SelectClause::cast(self.syntax.first_child_by_kind(&SelectClause::can_cast)?)
126    }
127    pub fn variables(&self) -> Vec<Var> {
128        if let Some(where_clause) = self.where_clause() {
129            if let Some(ggp) = where_clause.group_graph_pattern() {
130                return ggp
131                    .triple_blocks()
132                    .iter()
133                    .flat_map(|triple_block| {
134                        triple_block
135                            .triples()
136                            .iter()
137                            .flat_map(|triple| triple.visible_variables())
138                            .collect::<Vec<Var>>()
139                    })
140                    .collect();
141            }
142        }
143        vec![]
144    }
145
146    pub fn soulution_modifier(&self) -> Option<SolutionModifier> {
147        SolutionModifier::cast(self.syntax.last_child()?)
148    }
149}
150
151#[derive(Debug, PartialEq, Clone)]
152pub struct SelectClause {
153    syntax: SyntaxNode,
154}
155
156impl SelectClause {
157    /// All selected variables.
158    /// This excludes variables used in assignments
159    ///
160    /// **Example**
161    /// ```sparql
162    /// Select ?a (?b as ?c) {
163    ///     ...
164    /// }
165    /// ```
166    ///
167    /// here `variables` would return just **?a** and not **?b** or **?c**.
168    pub fn variables(&self) -> Vec<Var> {
169        self.syntax
170            .children()
171            .into_iter()
172            .filter_map(Var::cast)
173            .filter(|var| {
174                var.syntax()
175                    .prev_sibling()
176                    .is_none_or(|var| var.kind() != SyntaxKind::Expression)
177            })
178            .collect()
179    }
180
181    /// All selected variables plus all assigned variables.
182    /// This excludes variables used in assignments
183    ///
184    /// **Example**
185    /// ```sparql
186    /// Select ?a (?b as ?c) {
187    ///     ...
188    /// }
189    /// ```
190    /// result: [**?a**, **?c**]
191    pub fn projected_variables(&self) -> Vec<Var> {
192        self.syntax.children().filter_map(Var::cast).collect()
193    }
194
195    pub fn is_star_selection(&self) -> bool {
196        self.syntax()
197            .last_token()
198            .is_some_and(|last| last.kind() == SyntaxKind::Star)
199    }
200
201    /// All assignments in the select clause.
202    pub fn assignments(&self) -> Vec<Assignment> {
203        self.syntax
204            .children()
205            .filter_map(Var::cast)
206            .filter_map(|variable| {
207                variable
208                    .syntax()
209                    .prev_sibling()
210                    .and_then(Expression::cast)
211                    .map(|expression| Assignment {
212                        expression,
213                        variable,
214                    })
215            })
216            .collect()
217    }
218
219    pub fn select_query(&self) -> Option<SelectQuery> {
220        SelectQuery::cast(self.syntax.parent()?)
221    }
222}
223
224#[derive(Debug)]
225pub struct Assignment {
226    pub expression: Expression,
227    pub variable: Var,
228}
229
230#[derive(Debug)]
231pub struct Expression {
232    syntax: SyntaxNode,
233}
234
235impl Expression {
236    /// Returns the variable, if this expression consists of just a single variable.
237    pub fn as_var(&self) -> Option<Var> {
238        // NOTE: A plain variable is wrapped in a chain of single-child expression nodes.
239        let mut node = self.syntax.clone();
240        while !Var::can_cast(node.kind()) {
241            let mut children = node.children_with_tokens().filter(|child| {
242                !matches!(child.kind(), SyntaxKind::WHITESPACE | SyntaxKind::Comment)
243            });
244            let only_child = children.next()?;
245            if children.next().is_some() {
246                return None;
247            }
248            node = only_child.into_node()?;
249        }
250        Var::cast(node)
251    }
252
253    pub fn unaggregated_variables(&self) -> Vec<Var> {
254        let mut res = vec![];
255        let mut stack = vec![self.syntax.clone()];
256        while let Some(node) = stack.pop() {
257            if node.kind() != SyntaxKind::Aggregate {
258                stack.extend(node.children());
259            }
260            if let Some(var) = Var::cast(node) {
261                res.push(var);
262            }
263        }
264        res
265    }
266}
267
268#[derive(Debug)]
269pub enum GraphPatternNotTriples {
270    GroupOrUnionGraphPattern(GroupOrUnionGraphPattern),
271    OptionalGraphPattern(OptionalGraphPattern),
272    MinusGraphPattern(MinusGraphPattern),
273    GraphGraphPattern(GraphGraphPattern),
274    ServiceGraphPattern(ServiceGraphPattern),
275    Filter(Filter),
276    Bind(Bind),
277    InlineData(InlineData),
278}
279
280impl GraphPatternNotTriples {
281    pub fn group_graph_pattern(&self) -> Option<GraphGraphPattern> {
282        match self {
283            GraphPatternNotTriples::GroupOrUnionGraphPattern(_group_or_union_graph_pattern) => {
284                todo!()
285            }
286            GraphPatternNotTriples::OptionalGraphPattern(_optional_graph_pattern) => todo!(),
287            GraphPatternNotTriples::MinusGraphPattern(_minus_graph_pattern) => todo!(),
288            GraphPatternNotTriples::GraphGraphPattern(_graph_graph_pattern) => todo!(),
289            GraphPatternNotTriples::ServiceGraphPattern(_service_graph_pattern) => todo!(),
290            GraphPatternNotTriples::Filter(_filter) => None,
291            GraphPatternNotTriples::Bind(_bind) => None,
292            GraphPatternNotTriples::InlineData(_inline_data) => None,
293        }
294    }
295}
296
297#[derive(Debug)]
298pub struct GroupOrUnionGraphPattern {
299    syntax: SyntaxNode,
300}
301impl GroupOrUnionGraphPattern {
302    fn group_graph_patterns(&self) -> Vec<GroupGraphPattern> {
303        self.syntax
304            .children()
305            .filter_map(GroupGraphPattern::cast)
306            .collect()
307    }
308}
309
310#[derive(Debug)]
311pub struct OptionalGraphPattern {
312    syntax: SyntaxNode,
313}
314impl OptionalGraphPattern {
315    fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
316        self.syntax.last_child().and_then(GroupGraphPattern::cast)
317    }
318}
319
320#[derive(Debug)]
321pub struct MinusGraphPattern {
322    syntax: SyntaxNode,
323}
324impl MinusGraphPattern {
325    fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
326        self.syntax.last_child().and_then(GroupGraphPattern::cast)
327    }
328}
329
330#[derive(Debug)]
331pub struct GraphGraphPattern {
332    syntax: SyntaxNode,
333}
334impl GraphGraphPattern {
335    fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
336        self.syntax.last_child().and_then(GroupGraphPattern::cast)
337    }
338}
339
340#[derive(Debug)]
341pub struct Filter {
342    syntax: SyntaxNode,
343}
344
345#[derive(Debug)]
346pub struct Bind {
347    syntax: SyntaxNode,
348}
349
350#[derive(Debug, PartialEq, Clone)]
351pub struct InlineData {
352    syntax: SyntaxNode,
353}
354
355#[derive(Debug)]
356pub struct WhereClause {
357    syntax: SyntaxNode,
358}
359
360#[derive(Debug)]
361pub struct ServiceGraphPattern {
362    syntax: SyntaxNode,
363}
364
365impl ServiceGraphPattern {
366    pub fn iri(&self) -> Option<Iri> {
367        self.syntax
368            .children()
369            .find(|child| child.kind() == SyntaxKind::VarOrIri)
370            .and_then(|child| child.first_child().and_then(Iri::cast))
371    }
372
373    pub fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
374        self.syntax
375            .children()
376            .last()
377            .and_then(GroupGraphPattern::cast)
378    }
379}
380
381impl WhereClause {
382    pub fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
383        GroupGraphPattern::cast(self.syntax.first_child()?)
384    }
385
386    pub fn where_token(&self) -> Option<SyntaxToken> {
387        match self.syntax.first_child_or_token() {
388            Some(rowan::NodeOrToken::Token(token)) if token.kind() == SyntaxKind::WHERE => {
389                Some(token.into())
390            }
391            _ => None,
392        }
393    }
394}
395
396#[derive(Debug)]
397pub struct GroupGraphPattern {
398    syntax: SyntaxNode,
399}
400
401impl GroupGraphPattern {
402    pub fn triple_blocks(&self) -> Vec<TriplesBlock> {
403        self.syntax()
404            .first_child_by_kind(&|kind| kind == SyntaxKind::GroupGraphPatternSub)
405            .map(|ggp| ggp.children().filter_map(TriplesBlock::cast).collect())
406            .unwrap_or_default()
407    }
408
409    pub fn group_pattern_not_triples(&self) -> Vec<GraphPatternNotTriples> {
410        self.syntax()
411            .first_child_by_kind(&|kind| kind == SyntaxKind::GroupGraphPatternSub)
412            .map(|ggp| {
413                ggp.children()
414                    .filter_map(GraphPatternNotTriples::cast)
415                    .collect()
416            })
417            .unwrap_or_default()
418    }
419
420    pub fn r_paren_token(&self) -> Option<SyntaxToken> {
421        match self.syntax.last_child_or_token() {
422            Some(rowan::NodeOrToken::Token(token)) if token.kind() == SyntaxKind::RCurly => {
423                Some(token.into())
424            }
425            _ => None,
426        }
427    }
428
429    pub fn l_paren_token(&self) -> Option<SyntaxToken> {
430        match self.syntax.first_child_or_token() {
431            Some(rowan::NodeOrToken::Token(token)) if token.kind() == SyntaxKind::LCurly => {
432                Some(token.into())
433            }
434            _ => None,
435        }
436    }
437
438    pub fn sub_select(&self) -> Option<SelectQuery> {
439        self.syntax().first_child().and_then(SelectQuery::cast)
440    }
441}
442
443#[derive(Debug)]
444pub struct TriplesBlock {
445    syntax: SyntaxNode,
446}
447
448impl TriplesBlock {
449    /// Get the `Triple`'s contained in this `TriplesBlock`.
450    pub fn triples(&self) -> Vec<Triple> {
451        self.syntax
452            .children()
453            .filter_map(|child| match child.kind() {
454                SyntaxKind::TriplesSameSubjectPath => Some(vec![Triple::cast(child).unwrap()]),
455                SyntaxKind::TriplesBlock => Some(TriplesBlock::cast(child).unwrap().triples()),
456                _ => None,
457            })
458            .flatten()
459            .collect()
460    }
461
462    pub fn group_graph_pattern(&self) -> Option<GroupGraphPattern> {
463        GroupGraphPattern::cast(nth_ancestor(self.syntax.clone(), 2)?)
464    }
465
466    /// Get the Dot token that terminates the first triple in this block.
467    /// Grammar: TriplesBlock = TriplesSameSubjectPath ( '.' TriplesBlock? )?
468    pub fn trailing_dot(&self) -> Option<SyntaxToken> {
469        self.syntax
470            .children_with_tokens()
471            .find_map(|child| match child {
472                rowan::NodeOrToken::Token(token) if token.kind() == SyntaxKind::Dot => {
473                    Some(token.into())
474                }
475                _ => None,
476            })
477    }
478}
479
480#[derive(Debug, PartialEq)]
481pub struct Subject {
482    syntax: SyntaxNode,
483}
484
485#[derive(Debug, PartialEq, Clone)]
486pub struct Triple {
487    syntax: SyntaxNode,
488}
489
490impl Triple {
491    pub fn subject(&self) -> Option<Subject> {
492        self.syntax.first_child().and_then(Subject::cast)
493    }
494
495    pub fn properties_list_path(&self) -> Option<PropertyListPath> {
496        PropertyListPath::cast(self.syntax.children().nth(1)?)
497    }
498
499    /// Get the outer `TriplesBlock` this Triple is part of.
500    /// NOTE: TriplesBlock is defined recursivly
501    pub fn triples_block(&self) -> Option<TriplesBlock> {
502        let mut parent = self.syntax.parent()?;
503        if parent.kind() != SyntaxKind::TriplesBlock {
504            return None;
505        }
506        while let Some(node) = parent.parent() {
507            if node.kind() == SyntaxKind::TriplesBlock {
508                parent = node;
509            } else {
510                break;
511            }
512        }
513        Some(TriplesBlock::cast(parent).expect("parent should be a TriplesBlock"))
514    }
515}
516
517#[derive(Debug)]
518pub struct PropertyPath {
519    pub verb: Path,
520    // NOTE: `None` when the input is truncated after the verb (e.g. while typing)
521    pub object: Option<ObjectList>,
522}
523
524impl PropertyPath {
525    pub fn text(&self) -> String {
526        match &self.object {
527            Some(object) => format!("{} {}", self.verb.text(), object.text()),
528            None => self.verb.text(),
529        }
530    }
531
532    pub fn text_range(&self) -> TextRange {
533        TextRange::new(
534            self.verb.syntax().text_range().start(),
535            self.object
536                .as_ref()
537                .map(|object| object.syntax.text_range().end())
538                .unwrap_or_else(|| self.verb.syntax().text_range().end()),
539        )
540    }
541}
542
543#[derive(Debug)]
544pub struct Path {
545    syntax: SyntaxNode,
546}
547
548impl Path {
549    pub fn sub_paths(&self) -> SubPaths {
550        SubPaths {
551            children: self.syntax.children(),
552        }
553    }
554}
555
556pub struct SubPaths {
557    children: SyntaxNodeChildren<Sparql>,
558}
559
560impl Iterator for SubPaths {
561    type Item = Path;
562
563    fn next(&mut self) -> Option<Self::Item> {
564        while let Some(next_child) = self.children.next() {
565            if let Some(path) = Path::cast(next_child.into()) {
566                return Some(path);
567            }
568        }
569        None
570    }
571}
572
573#[derive(Debug)]
574pub struct ObjectList {
575    syntax: SyntaxNode,
576}
577
578#[derive(Debug, PartialEq, Clone)]
579pub struct BlankPropertyList {
580    syntax: SyntaxNode,
581}
582
583impl BlankPropertyList {
584    pub fn triple(&self) -> Option<Triple> {
585        match self.syntax.kind() {
586            SyntaxKind::BlankNodePropertyListPath => {
587                todo!()
588            }
589            SyntaxKind::BlankNodePropertyList => {
590                todo!()
591            }
592            SyntaxKind::BlankNode => self.syntax.ancestors().nth(7).and_then(Triple::cast),
593            _ => None,
594        }
595    }
596
597    pub fn is_object(&self) -> bool {
598        todo!()
599    }
600
601    pub fn is_subject(&self) -> bool {
602        todo!()
603    }
604
605    pub fn property_list(&self) -> Option<PropertyListPath> {
606        match self.syntax.kind() {
607            SyntaxKind::BlankNodePropertyListPath | SyntaxKind::BlankNodePropertyList => {
608                PropertyListPath::cast(self.syntax.first_child()?)
609            }
610
611            _ => None,
612        }
613    }
614}
615
616#[derive(Debug)]
617pub struct PropertyListPath {
618    syntax: SyntaxNode,
619}
620
621impl PropertyListPath {
622    pub fn properties(&self) -> Vec<PropertyPath> {
623        self.syntax
624            .children()
625            .step_by(2)
626            .filter_map(|child| {
627                Path::cast(child.clone()).map(|path| PropertyPath {
628                    verb: path,
629                    object: child.next_sibling().and_then(ObjectList::cast),
630                })
631            })
632            .collect()
633    }
634    pub fn variables(&self) -> Vec<Var> {
635        self.syntax
636            .children()
637            .filter_map(|child| match child.kind() {
638                SyntaxKind::VerbSimple => child.first_child().and_then(Var::cast),
639                _ => None,
640            })
641            .collect()
642    }
643}
644
645#[derive(Debug)]
646pub struct Iri {
647    syntax: SyntaxNode,
648}
649
650impl Iri {
651    pub fn prefixed_name(&self) -> Option<PrefixedName> {
652        self.syntax.first_child().and_then(PrefixedName::cast)
653    }
654
655    /// Converts a IRIREF "<abc>" into the raw string "abc"
656    /// Returns None this iri is a PrefixedName
657    pub fn raw_iri(&self) -> Option<String> {
658        (self.syntax.first_child_or_token()?.kind() == SyntaxKind::IRIREF
659            && self.syntax.text_range().len() >= 2.into())
660        .then(|| self.text()[1..usize::from(self.syntax.text_range().len()) - 1].to_string())
661    }
662
663    pub fn is_uncompressed(&self) -> bool {
664        self.syntax
665            .first_child_or_token()
666            .is_some_and(|child| child.kind() == SyntaxKind::IRIREF)
667    }
668}
669
670#[derive(Debug)]
671pub struct PrefixedName {
672    syntax: SyntaxNode,
673}
674
675impl PrefixedName {
676    pub fn prefix(&self) -> String {
677        self.syntax
678            .to_string()
679            .split_once(":")
680            .expect("Every PrefixedName should contain a ':'")
681            .0
682            .to_string()
683    }
684
685    pub fn name(&self) -> String {
686        self.syntax
687            .to_string()
688            .split_once(":")
689            .expect("Every PrefixedName should contain a ':'")
690            .1
691            .to_string()
692    }
693}
694
695#[derive(Debug)]
696pub struct VarOrTerm {
697    syntax: SyntaxNode,
698}
699
700impl VarOrTerm {
701    pub fn var(&self) -> Option<Var> {
702        Var::cast(self.syntax.first_child()?)
703    }
704
705    pub fn is_var(&self) -> bool {
706        self.syntax
707            .first_child()
708            .map_or(false, |child| child.kind() == SyntaxKind::Var)
709    }
710
711    pub fn is_term(&self) -> bool {
712        !self.is_var()
713    }
714}
715
716#[derive(Debug)]
717pub struct Var {
718    syntax: SyntaxNode,
719}
720
721impl Var {
722    pub fn triple(&self) -> Option<Triple> {
723        self.syntax.ancestors().find_map(Triple::cast)
724    }
725
726    /// Variable name without `?`
727    ///
728    /// ---
729    ///
730    /// `?subject` -> `subject`
731    pub fn var_name(&self) -> String {
732        let text = self.syntax.text().to_string();
733        if !text.is_empty() && text.starts_with('?') {
734            return text[1..].to_string();
735        }
736        return text;
737    }
738}
739
740impl AstNode for Var {
741    #[inline]
742    fn kind() -> SyntaxKind {
743        SyntaxKind::Var
744    }
745
746    fn cast(syntax: SyntaxNode) -> Option<Self> {
747        if Self::can_cast(syntax.kind()) {
748            Some(Self { syntax })
749        } else {
750            None
751        }
752    }
753    #[inline]
754    fn syntax(&self) -> &SyntaxNode {
755        &self.syntax
756    }
757
758    fn visible_variables(&self) -> Vec<Var> {
759        vec![Var::cast(self.syntax().clone()).unwrap()]
760    }
761}
762
763impl AstNode for VarOrTerm {
764    #[inline]
765    fn kind() -> SyntaxKind {
766        SyntaxKind::VarOrTerm
767    }
768
769    fn cast(syntax: SyntaxNode) -> Option<Self> {
770        if Self::can_cast(syntax.kind()) {
771            Some(Self { syntax })
772        } else {
773            None
774        }
775    }
776    #[inline]
777    fn syntax(&self) -> &SyntaxNode {
778        &self.syntax
779    }
780
781    fn visible_variables(&self) -> Vec<Var> {
782        self.syntax
783            .first_child()
784            .and_then(Var::cast)
785            .map(|var| vec![var])
786            .unwrap_or_default()
787    }
788}
789
790impl AstNode for Iri {
791    #[inline]
792    fn kind() -> SyntaxKind {
793        SyntaxKind::iri
794    }
795
796    fn cast(syntax: SyntaxNode) -> Option<Self> {
797        if Self::can_cast(syntax.kind()) {
798            Some(Self { syntax })
799        } else {
800            None
801        }
802    }
803    #[inline]
804    fn syntax(&self) -> &SyntaxNode {
805        &self.syntax
806    }
807
808    fn visible_variables(&self) -> Vec<Var> {
809        vec![]
810    }
811}
812
813impl AstNode for PrefixedName {
814    #[inline]
815    fn kind() -> SyntaxKind {
816        SyntaxKind::PrefixedName
817    }
818
819    fn cast(syntax: SyntaxNode) -> Option<Self> {
820        if Self::can_cast(syntax.kind()) {
821            Some(Self { syntax })
822        } else {
823            None
824        }
825    }
826    #[inline]
827    fn syntax(&self) -> &SyntaxNode {
828        &self.syntax
829    }
830
831    fn visible_variables(&self) -> Vec<Var> {
832        vec![]
833    }
834}
835
836impl AstNode for Path {
837    fn kind() -> SyntaxKind {
838        SyntaxKind::VerbPath
839    }
840
841    fn can_cast(kind: SyntaxKind) -> bool {
842        matches!(
843            kind,
844            SyntaxKind::Path
845                | SyntaxKind::VerbPath
846                | SyntaxKind::VerbSimple
847                | SyntaxKind::PathAlternative
848                | SyntaxKind::PathSequence
849                | SyntaxKind::PathElt
850                | SyntaxKind::PathEltOrInverse
851                | SyntaxKind::PathPrimary
852                | SyntaxKind::PathNegatedPropertySet
853                | SyntaxKind::PathOneInPropertySet
854        )
855    }
856
857    fn cast(syntax: SyntaxNode) -> Option<Self> {
858        if Self::can_cast(syntax.kind()) {
859            Some(Self { syntax })
860        } else {
861            None
862        }
863    }
864
865    fn syntax(&self) -> &SyntaxNode {
866        &self.syntax
867    }
868
869    fn visible_variables(&self) -> Vec<Var> {
870        vec![]
871    }
872}
873
874impl AstNode for ObjectList {
875    fn kind() -> SyntaxKind {
876        SyntaxKind::ObjectListPath
877    }
878    fn can_cast(kind: SyntaxKind) -> bool {
879        matches!(kind, SyntaxKind::ObjectListPath | SyntaxKind::ObjectList)
880    }
881
882    fn cast(syntax: SyntaxNode) -> Option<Self> {
883        if Self::can_cast(syntax.kind()) {
884            Some(Self { syntax })
885        } else {
886            None
887        }
888    }
889
890    fn syntax(&self) -> &SyntaxNode {
891        &self.syntax
892    }
893
894    fn visible_variables(&self) -> Vec<Var> {
895        self.syntax.descendants().filter_map(Var::cast).collect()
896    }
897}
898
899impl AstNode for BlankPropertyList {
900    #[inline]
901    fn kind() -> SyntaxKind {
902        SyntaxKind::BlankNodePropertyListPath
903    }
904
905    fn can_cast(kind: SyntaxKind) -> bool {
906        matches!(
907            kind,
908            SyntaxKind::BlankNodePropertyListPath
909                | SyntaxKind::BlankNodePropertyList
910                | SyntaxKind::BlankNode
911        )
912    }
913
914    #[inline]
915    fn cast(syntax: SyntaxNode) -> Option<Self> {
916        if Self::can_cast(syntax.kind()) {
917            Some(Self { syntax })
918        } else {
919            None
920        }
921    }
922
923    #[inline]
924    fn syntax(&self) -> &SyntaxNode {
925        &self.syntax
926    }
927
928    fn visible_variables(&self) -> Vec<Var> {
929        self.syntax.descendants().filter_map(Var::cast).collect()
930    }
931}
932
933impl AstNode for PropertyListPath {
934    #[inline]
935    fn kind() -> SyntaxKind {
936        SyntaxKind::PropertyListPathNotEmpty
937    }
938
939    fn can_cast(kind: SyntaxKind) -> bool {
940        matches!(
941            kind,
942            SyntaxKind::PropertyListPath | SyntaxKind::PropertyListPathNotEmpty
943        )
944    }
945
946    #[inline]
947    fn cast(syntax: SyntaxNode) -> Option<Self> {
948        if Self::can_cast(syntax.kind()) {
949            Some(Self { syntax })
950        } else {
951            None
952        }
953    }
954
955    #[inline]
956    fn syntax(&self) -> &SyntaxNode {
957        &self.syntax
958    }
959
960    fn visible_variables(&self) -> Vec<Var> {
961        self.syntax.descendants().filter_map(Var::cast).collect()
962    }
963}
964
965impl AstNode for Subject {
966    #[inline]
967    fn kind() -> SyntaxKind {
968        SyntaxKind::VarOrTerm
969    }
970
971    fn can_cast(kind: SyntaxKind) -> bool {
972        matches!(kind, SyntaxKind::VarOrTerm | SyntaxKind::TriplesNodePath)
973    }
974
975    fn cast(syntax: SyntaxNode) -> Option<Self> {
976        if Self::can_cast(syntax.kind()) {
977            Some(Self { syntax })
978        } else {
979            None
980        }
981    }
982    #[inline]
983    fn syntax(&self) -> &SyntaxNode {
984        &self.syntax
985    }
986
987    fn visible_variables(&self) -> Vec<Var> {
988        self.syntax
989            .first_child()
990            .and_then(Var::cast)
991            .map(|var| vec![var])
992            .unwrap_or_default()
993    }
994}
995
996impl AstNode for Triple {
997    #[inline]
998    fn kind() -> SyntaxKind {
999        SyntaxKind::TriplesSameSubjectPath
1000    }
1001
1002    fn cast(syntax: SyntaxNode) -> Option<Self> {
1003        if Self::can_cast(syntax.kind()) {
1004            Some(Self { syntax })
1005        } else {
1006            None
1007        }
1008    }
1009    #[inline]
1010    fn syntax(&self) -> &SyntaxNode {
1011        &self.syntax
1012    }
1013
1014    fn visible_variables(&self) -> Vec<Var> {
1015        self.syntax.descendants().filter_map(Var::cast).collect()
1016    }
1017}
1018
1019impl AstNode for TriplesBlock {
1020    #[inline]
1021    fn kind() -> SyntaxKind {
1022        SyntaxKind::TriplesBlock
1023    }
1024
1025    fn cast(syntax: SyntaxNode) -> Option<Self> {
1026        if Self::can_cast(syntax.kind()) {
1027            Some(Self { syntax })
1028        } else {
1029            None
1030        }
1031    }
1032
1033    #[inline]
1034    fn syntax(&self) -> &SyntaxNode {
1035        &self.syntax
1036    }
1037
1038    fn visible_variables(&self) -> Vec<Var> {
1039        self.syntax.descendants().filter_map(Var::cast).collect()
1040    }
1041}
1042
1043impl AstNode for Expression {
1044    #[inline]
1045    fn kind() -> SyntaxKind {
1046        SyntaxKind::Expression
1047    }
1048
1049    fn cast(syntax: SyntaxNode) -> Option<Self> {
1050        if Self::can_cast(syntax.kind()) {
1051            Some(Self { syntax })
1052        } else {
1053            None
1054        }
1055    }
1056
1057    #[inline]
1058    fn syntax(&self) -> &SyntaxNode {
1059        &self.syntax
1060    }
1061
1062    fn visible_variables(&self) -> Vec<Var> {
1063        self.syntax.descendants().filter_map(Var::cast).collect()
1064    }
1065}
1066
1067impl AstNode for GroupGraphPattern {
1068    #[inline]
1069    fn kind() -> SyntaxKind {
1070        SyntaxKind::GroupGraphPattern
1071    }
1072
1073    fn cast(syntax: SyntaxNode) -> Option<Self> {
1074        if Self::can_cast(syntax.kind()) {
1075            Some(Self { syntax })
1076        } else {
1077            None
1078        }
1079    }
1080
1081    #[inline]
1082    fn syntax(&self) -> &SyntaxNode {
1083        &self.syntax
1084    }
1085
1086    fn visible_variables(&self) -> Vec<Var> {
1087        self.sub_select()
1088            .map(|select| select.visible_variables())
1089            .or(self.syntax.first_child().map(|child| {
1090                child
1091                    .children()
1092                    .into_iter()
1093                    .filter_map(|child| match child.kind() {
1094                        SyntaxKind::TriplesBlock => {
1095                            TriplesBlock::cast(child).map(|tp| tp.visible_variables())
1096                        }
1097                        SyntaxKind::GraphPatternNotTriples => GraphPatternNotTriples::cast(child)
1098                            .map(|pattern| pattern.visible_variables()),
1099                        _ => None,
1100                    })
1101                    .flatten()
1102                    .collect()
1103            }))
1104            .unwrap_or_default()
1105    }
1106}
1107
1108impl AstNode for WhereClause {
1109    #[inline]
1110    fn kind() -> SyntaxKind {
1111        SyntaxKind::WhereClause
1112    }
1113
1114    fn cast(syntax: SyntaxNode) -> Option<Self> {
1115        if Self::can_cast(syntax.kind()) {
1116            Some(Self { syntax })
1117        } else {
1118            None
1119        }
1120    }
1121
1122    #[inline]
1123    fn syntax(&self) -> &SyntaxNode {
1124        &self.syntax
1125    }
1126
1127    fn visible_variables(&self) -> Vec<Var> {
1128        self.group_graph_pattern()
1129            .map(|ggp| ggp.visible_variables())
1130            .unwrap_or_default()
1131    }
1132}
1133impl AstNode for OptionalGraphPattern {
1134    #[inline]
1135    fn kind() -> SyntaxKind {
1136        SyntaxKind::OptionalGraphPattern
1137    }
1138
1139    fn cast(syntax: SyntaxNode) -> Option<Self> {
1140        if Self::can_cast(syntax.kind()) {
1141            Some(Self { syntax })
1142        } else {
1143            None
1144        }
1145    }
1146
1147    #[inline]
1148    fn syntax(&self) -> &SyntaxNode {
1149        &self.syntax
1150    }
1151
1152    fn visible_variables(&self) -> Vec<Var> {
1153        self.group_graph_pattern()
1154            .map(|ggp| ggp.visible_variables())
1155            .unwrap_or_default()
1156    }
1157}
1158
1159impl AstNode for GroupOrUnionGraphPattern {
1160    #[inline]
1161    fn kind() -> SyntaxKind {
1162        SyntaxKind::GroupOrUnionGraphPattern
1163    }
1164
1165    fn cast(syntax: SyntaxNode) -> Option<Self> {
1166        if Self::can_cast(syntax.kind()) {
1167            Some(Self { syntax })
1168        } else {
1169            None
1170        }
1171    }
1172
1173    #[inline]
1174    fn syntax(&self) -> &SyntaxNode {
1175        &self.syntax
1176    }
1177
1178    fn visible_variables(&self) -> Vec<Var> {
1179        self.group_graph_patterns()
1180            .into_iter()
1181            .flat_map(|ggp| ggp.visible_variables())
1182            .collect()
1183    }
1184}
1185
1186impl AstNode for MinusGraphPattern {
1187    #[inline]
1188    fn kind() -> SyntaxKind {
1189        SyntaxKind::MinusGraphPattern
1190    }
1191
1192    fn cast(syntax: SyntaxNode) -> Option<Self> {
1193        if Self::can_cast(syntax.kind()) {
1194            Some(Self { syntax })
1195        } else {
1196            None
1197        }
1198    }
1199
1200    #[inline]
1201    fn syntax(&self) -> &SyntaxNode {
1202        &self.syntax
1203    }
1204
1205    fn visible_variables(&self) -> Vec<Var> {
1206        self.group_graph_pattern()
1207            .map(|ggp| ggp.visible_variables())
1208            .unwrap_or_default()
1209    }
1210}
1211
1212impl AstNode for GraphGraphPattern {
1213    #[inline]
1214    fn kind() -> SyntaxKind {
1215        SyntaxKind::GraphGraphPattern
1216    }
1217
1218    fn cast(syntax: SyntaxNode) -> Option<Self> {
1219        if Self::can_cast(syntax.kind()) {
1220            Some(Self { syntax })
1221        } else {
1222            None
1223        }
1224    }
1225
1226    #[inline]
1227    fn syntax(&self) -> &SyntaxNode {
1228        &self.syntax
1229    }
1230
1231    fn visible_variables(&self) -> Vec<Var> {
1232        self.group_graph_pattern()
1233            .map(|ggp| ggp.visible_variables())
1234            .unwrap_or_default()
1235    }
1236}
1237
1238impl AstNode for ServiceGraphPattern {
1239    #[inline]
1240    fn kind() -> SyntaxKind {
1241        SyntaxKind::ServiceGraphPattern
1242    }
1243
1244    fn cast(syntax: SyntaxNode) -> Option<Self> {
1245        if Self::can_cast(syntax.kind()) {
1246            Some(Self { syntax })
1247        } else {
1248            None
1249        }
1250    }
1251
1252    #[inline]
1253    fn syntax(&self) -> &SyntaxNode {
1254        &self.syntax
1255    }
1256
1257    fn visible_variables(&self) -> Vec<Var> {
1258        self.group_graph_pattern()
1259            .map(|ggp| ggp.visible_variables())
1260            .unwrap_or_default()
1261    }
1262}
1263
1264impl AstNode for Filter {
1265    #[inline]
1266    fn kind() -> SyntaxKind {
1267        SyntaxKind::Filter
1268    }
1269
1270    fn cast(syntax: SyntaxNode) -> Option<Self> {
1271        if Self::can_cast(syntax.kind()) {
1272            Some(Self { syntax })
1273        } else {
1274            None
1275        }
1276    }
1277
1278    #[inline]
1279    fn syntax(&self) -> &SyntaxNode {
1280        &self.syntax
1281    }
1282
1283    fn visible_variables(&self) -> Vec<Var> {
1284        self.syntax().descendants().filter_map(Var::cast).collect()
1285    }
1286}
1287
1288impl AstNode for Bind {
1289    #[inline]
1290    fn kind() -> SyntaxKind {
1291        SyntaxKind::Bind
1292    }
1293
1294    fn cast(syntax: SyntaxNode) -> Option<Self> {
1295        if Self::can_cast(syntax.kind()) {
1296            Some(Self { syntax })
1297        } else {
1298            None
1299        }
1300    }
1301
1302    #[inline]
1303    fn syntax(&self) -> &SyntaxNode {
1304        &self.syntax
1305    }
1306
1307    fn visible_variables(&self) -> Vec<Var> {
1308        self.syntax()
1309            .children()
1310            .last()
1311            .and_then(Var::cast)
1312            .map(|var| vec![var])
1313            .unwrap_or_default()
1314    }
1315}
1316
1317impl AstNode for InlineData {
1318    #[inline]
1319    fn kind() -> SyntaxKind {
1320        SyntaxKind::InlineData
1321    }
1322
1323    fn cast(syntax: SyntaxNode) -> Option<Self> {
1324        if Self::can_cast(syntax.kind()) {
1325            Some(Self { syntax })
1326        } else {
1327            None
1328        }
1329    }
1330
1331    #[inline]
1332    fn syntax(&self) -> &SyntaxNode {
1333        &self.syntax
1334    }
1335
1336    fn visible_variables(&self) -> Vec<Var> {
1337        self.syntax()
1338            .last_child()
1339            .and_then(|data_block| data_block.first_child())
1340            .and_then(|inline_data| match inline_data.kind() {
1341                SyntaxKind::InlineDataOneVar => inline_data
1342                    .first_child()
1343                    .and_then(Var::cast)
1344                    .map(|var| vec![var]),
1345                SyntaxKind::InlineDataFull => Some(
1346                    inline_data
1347                        .children_with_tokens()
1348                        .take_while(|child| child.kind() != SyntaxKind::RParen)
1349                        .filter_map(|child| child.into_node().and_then(Var::cast))
1350                        .collect(),
1351                ),
1352                _ => None,
1353            })
1354            .unwrap_or_default()
1355    }
1356}
1357
1358impl AstNode for SelectClause {
1359    #[inline]
1360    fn kind() -> SyntaxKind {
1361        SyntaxKind::SelectClause
1362    }
1363
1364    fn cast(syntax: SyntaxNode) -> Option<Self> {
1365        if Self::can_cast(syntax.kind()) {
1366            Some(Self { syntax })
1367        } else {
1368            None
1369        }
1370    }
1371
1372    #[inline]
1373    fn syntax(&self) -> &SyntaxNode {
1374        &self.syntax
1375    }
1376
1377    fn visible_variables(&self) -> Vec<Var> {
1378        self.projected_variables()
1379    }
1380}
1381
1382impl AstNode for Prologue {
1383    #[inline]
1384    fn kind() -> SyntaxKind {
1385        SyntaxKind::Prologue
1386    }
1387
1388    fn cast(syntax: SyntaxNode) -> Option<Self> {
1389        if Self::can_cast(syntax.kind()) {
1390            Some(Self { syntax })
1391        } else {
1392            None
1393        }
1394    }
1395
1396    #[inline]
1397    fn syntax(&self) -> &SyntaxNode {
1398        &self.syntax
1399    }
1400
1401    fn visible_variables(&self) -> Vec<Var> {
1402        vec![]
1403    }
1404}
1405
1406impl AstNode for SolutionModifier {
1407    #[inline]
1408    fn kind() -> SyntaxKind {
1409        SyntaxKind::SolutionModifier
1410    }
1411
1412    fn cast(syntax: SyntaxNode) -> Option<Self> {
1413        if Self::can_cast(syntax.kind()) {
1414            Some(Self { syntax })
1415        } else {
1416            None
1417        }
1418    }
1419
1420    #[inline]
1421    fn syntax(&self) -> &SyntaxNode {
1422        &self.syntax
1423    }
1424
1425    fn visible_variables(&self) -> Vec<Var> {
1426        vec![]
1427    }
1428}
1429
1430impl AstNode for GroupClause {
1431    #[inline]
1432    fn kind() -> SyntaxKind {
1433        SyntaxKind::GroupClause
1434    }
1435
1436    fn cast(syntax: SyntaxNode) -> Option<Self> {
1437        if Self::can_cast(syntax.kind()) {
1438            Some(Self { syntax })
1439        } else {
1440            None
1441        }
1442    }
1443
1444    #[inline]
1445    fn syntax(&self) -> &SyntaxNode {
1446        &self.syntax
1447    }
1448
1449    fn visible_variables(&self) -> Vec<Var> {
1450        // NOTE: A GroupCondition binds a variable if it is a plain variable ("?x"),
1451        //       an alias ("(... AS ?x)"), or a bracketted variable ("(?x)").
1452        self.syntax
1453            .children()
1454            .into_iter()
1455            .filter_map(|group_condition| group_condition.last_child())
1456            .filter_map(|node| Var::cast(node.clone()).or_else(|| Expression::cast(node)?.as_var()))
1457            .collect()
1458    }
1459}
1460
1461impl AstNode for PrefixDeclaration {
1462    #[inline]
1463    fn kind() -> SyntaxKind {
1464        SyntaxKind::PrefixDecl
1465    }
1466
1467    fn cast(syntax: SyntaxNode) -> Option<Self> {
1468        if Self::can_cast(syntax.kind()) {
1469            Some(Self { syntax })
1470        } else {
1471            None
1472        }
1473    }
1474
1475    #[inline]
1476    fn syntax(&self) -> &SyntaxNode {
1477        &self.syntax
1478    }
1479
1480    fn visible_variables(&self) -> Vec<Var> {
1481        vec![]
1482    }
1483}
1484
1485impl AstNode for QueryUnit {
1486    #[inline]
1487    fn kind() -> SyntaxKind {
1488        SyntaxKind::QueryUnit
1489    }
1490
1491    fn cast(syntax: SyntaxNode) -> Option<Self> {
1492        if Self::can_cast(syntax.kind()) {
1493            Some(Self { syntax })
1494        } else {
1495            None
1496        }
1497    }
1498
1499    #[inline]
1500    fn syntax(&self) -> &SyntaxNode {
1501        &self.syntax
1502    }
1503
1504    fn visible_variables(&self) -> Vec<Var> {
1505        self.select_query()
1506            .map(|select_query| select_query.visible_variables())
1507            .unwrap_or_default()
1508    }
1509}
1510
1511impl AstNode for SelectQuery {
1512    #[inline]
1513    fn kind() -> SyntaxKind {
1514        SyntaxKind::SelectQuery
1515    }
1516
1517    fn can_cast(kind: SyntaxKind) -> bool {
1518        matches!(kind, SyntaxKind::SelectQuery | SyntaxKind::SubSelect)
1519    }
1520
1521    fn cast(syntax: SyntaxNode) -> Option<Self> {
1522        if Self::can_cast(syntax.kind()) {
1523            Some(Self { syntax })
1524        } else {
1525            None
1526        }
1527    }
1528
1529    #[inline]
1530    fn syntax(&self) -> &SyntaxNode {
1531        &self.syntax
1532    }
1533
1534    fn visible_variables(&self) -> Vec<Var> {
1535        if let Some(select_clause) = self.select_clause() {
1536            if let Some(SyntaxKind::Star) = select_clause
1537                .syntax
1538                .last_child_or_token()
1539                .map(|last| last.kind())
1540            {
1541                self.where_clause()
1542                    .map(|where_clause| where_clause.visible_variables())
1543                    .unwrap_or_default()
1544            } else {
1545                select_clause.visible_variables()
1546            }
1547        } else {
1548            Vec::new()
1549        }
1550    }
1551}
1552
1553impl AstNode for GraphPatternNotTriples {
1554    #[inline]
1555    fn kind() -> SyntaxKind {
1556        SyntaxKind::GraphPatternNotTriples
1557    }
1558
1559    fn can_cast(kind: SyntaxKind) -> bool {
1560        matches!(
1561            kind,
1562            SyntaxKind::GroupOrUnionGraphPattern
1563                | SyntaxKind::OptionalGraphPattern
1564                | SyntaxKind::MinusGraphPattern
1565                | SyntaxKind::GraphGraphPattern
1566                | SyntaxKind::ServiceGraphPattern
1567                | SyntaxKind::Filter
1568                | SyntaxKind::Bind
1569                | SyntaxKind::InlineData
1570        )
1571    }
1572
1573    fn cast(syntax: SyntaxNode) -> Option<Self> {
1574        let child = syntax.first_child()?;
1575        match child.kind() {
1576            SyntaxKind::GroupOrUnionGraphPattern => {
1577                Some(GraphPatternNotTriples::GroupOrUnionGraphPattern(
1578                    GroupOrUnionGraphPattern::cast(child)?,
1579                ))
1580            }
1581            SyntaxKind::OptionalGraphPattern => Some(GraphPatternNotTriples::OptionalGraphPattern(
1582                OptionalGraphPattern::cast(child)?,
1583            )),
1584            SyntaxKind::MinusGraphPattern => Some(GraphPatternNotTriples::MinusGraphPattern(
1585                MinusGraphPattern::cast(child)?,
1586            )),
1587            SyntaxKind::GraphGraphPattern => Some(GraphPatternNotTriples::GraphGraphPattern(
1588                GraphGraphPattern::cast(child)?,
1589            )),
1590            SyntaxKind::ServiceGraphPattern => Some(GraphPatternNotTriples::ServiceGraphPattern(
1591                ServiceGraphPattern::cast(child)?,
1592            )),
1593            SyntaxKind::Filter => Some(GraphPatternNotTriples::Filter(Filter::cast(child)?)),
1594            SyntaxKind::Bind => Some(GraphPatternNotTriples::Bind(Bind::cast(child)?)),
1595            SyntaxKind::InlineData => {
1596                Some(GraphPatternNotTriples::InlineData(InlineData::cast(child)?))
1597            }
1598            _ => None,
1599        }
1600    }
1601
1602    #[inline]
1603    fn syntax(&self) -> &SyntaxNode {
1604        match self {
1605            GraphPatternNotTriples::GroupOrUnionGraphPattern(x) => x.syntax(),
1606            GraphPatternNotTriples::OptionalGraphPattern(x) => x.syntax(),
1607            GraphPatternNotTriples::MinusGraphPattern(x) => x.syntax(),
1608            GraphPatternNotTriples::GraphGraphPattern(x) => x.syntax(),
1609            GraphPatternNotTriples::ServiceGraphPattern(x) => x.syntax(),
1610            GraphPatternNotTriples::Filter(x) => x.syntax(),
1611            GraphPatternNotTriples::Bind(x) => x.syntax(),
1612            GraphPatternNotTriples::InlineData(x) => x.syntax(),
1613        }
1614    }
1615
1616    fn visible_variables(&self) -> Vec<Var> {
1617        match self {
1618            GraphPatternNotTriples::GroupOrUnionGraphPattern(x) => x.visible_variables(),
1619            GraphPatternNotTriples::OptionalGraphPattern(x) => x.visible_variables(),
1620            GraphPatternNotTriples::MinusGraphPattern(x) => x.visible_variables(),
1621            GraphPatternNotTriples::GraphGraphPattern(x) => x.visible_variables(),
1622            GraphPatternNotTriples::ServiceGraphPattern(x) => x.visible_variables(),
1623            GraphPatternNotTriples::Filter(x) => x.visible_variables(),
1624            GraphPatternNotTriples::Bind(x) => x.visible_variables(),
1625            GraphPatternNotTriples::InlineData(x) => x.visible_variables(),
1626        }
1627    }
1628}
1629
1630pub trait AstNode {
1631    fn kind() -> SyntaxKind;
1632
1633    #[inline]
1634    fn can_cast(kind: SyntaxKind) -> bool {
1635        Self::kind() == kind
1636    }
1637
1638    fn cast(syntax: SyntaxNode) -> Option<Self>
1639    where
1640        Self: Sized;
1641
1642    fn syntax(&self) -> &SyntaxNode;
1643
1644    /// Returns all variables "visible" from outside the node.
1645    fn visible_variables(&self) -> Vec<Var>;
1646
1647    fn has_error(&self) -> bool {
1648        self.syntax()
1649            .preorder()
1650            .find(|walk_event| match walk_event {
1651                rowan::WalkEvent::Enter(node) if node.kind() == SyntaxKind::Error => true,
1652                _ => false,
1653            })
1654            .is_some()
1655    }
1656
1657    fn collect_decendants(&self, matcher: &impl Fn(SyntaxKind) -> bool) -> Vec<SyntaxNode> {
1658        self.syntax()
1659            .preorder()
1660            .filter_map(|walk_event| match walk_event {
1661                rowan::WalkEvent::Enter(node) if matcher(node.kind()) => Some(node),
1662                _ => None,
1663            })
1664            .collect()
1665    }
1666
1667    fn preorder_find_kind(&self, kind: SyntaxKind) -> Vec<SyntaxNode> {
1668        self.syntax()
1669            .preorder()
1670            .filter_map(|walk_event| match walk_event {
1671                rowan::WalkEvent::Enter(node) if node.kind() == kind => Some(node),
1672                _ => None,
1673            })
1674            .collect()
1675    }
1676
1677    fn used_prefixes(&self) -> Vec<String> {
1678        self.syntax()
1679            .descendants()
1680            .filter_map(PrefixedName::cast)
1681            .map(|prefixed_name| prefixed_name.prefix())
1682            .collect()
1683    }
1684
1685    fn text(&self) -> String {
1686        self.syntax().text().to_string()
1687    }
1688
1689    fn text_until(&self, offset: TextSize) -> String {
1690        let syntax = self.syntax();
1691        assert!(syntax.text_range().start() <= offset);
1692        syntax
1693            .text()
1694            .slice(TextSize::new(0)..(offset - syntax.text_range().start()))
1695            .to_string()
1696    }
1697}
1698
1699#[cfg(test)]
1700mod tests;