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