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