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