Skip to main content

swls_core/util/
token.rs

1use std::ops::Range;
2
3use bevy_ecs::prelude::*;
4use derive_more::{AsMut, AsRef, Deref, DerefMut};
5use tracing::{debug, instrument};
6
7use crate::{components::*, prelude::*};
8
9/// [`Component`] used to indicate the currently targeted token during a request.
10#[derive(Component, Debug)]
11pub struct TokenComponent {
12    pub range: crate::lsp_types::Range,
13    pub text: String,
14    pub source_span: Range<usize>,
15    /// `true` when the cursor is on an error/invalid token.
16    pub is_error: bool,
17}
18
19/// [`Component`] that contains CST leaf tokens from the rowan syntax tree.
20#[derive(Component, AsRef, Deref, AsMut, DerefMut, Debug)]
21pub struct CstTokens(pub Vec<Spanned<rowan::SyntaxKind>>);
22
23/// Whether a token is punctuation (`;`, `.`, `[`, …) rather than a word
24/// (an IRI, prefixed name, literal, keyword, …).
25fn is_punctuation(text: &str) -> bool {
26    !text.is_empty() && text.chars().all(|c| ";.,[](){}".contains(c))
27}
28
29/// The token a cursor at byte `offset` belongs to, given the tokens' spans.
30///
31/// A cursor sits *between* characters, so for `ex:fo|;` it belongs to `ex:fo`
32/// (the word being typed), and for `|ex:name` to `ex:name`. In order:
33///
34/// 1. a word token that contains the cursor,
35/// 2. a word token that ends at the cursor,
36/// 3. a punctuation token that contains the cursor or ends at it,
37/// 4. none: the cursor is in whitespace.
38pub fn token_at_cursor<'a>(
39    spans: impl Iterator<Item = &'a Range<usize>> + Clone,
40    source: &str,
41    offset: usize,
42) -> Option<Range<usize>> {
43    let text = |r: &Range<usize>| source.get(r.clone()).unwrap_or_default();
44    let narrowest = |it: &mut dyn Iterator<Item = &'a Range<usize>>| {
45        it.min_by_key(|r| r.end - r.start).cloned()
46    };
47    let words = spans.clone().filter(|r| !is_punctuation(text(r)));
48    let puncts = spans.filter(|r| is_punctuation(text(r)));
49
50    narrowest(
51        &mut words
52            .clone()
53            .filter(|r| r.start <= offset && offset < r.end),
54    )
55    .or_else(|| narrowest(&mut words.filter(|r| r.end == offset && r.start < r.end)))
56    .or_else(|| narrowest(&mut puncts.filter(|r| r.start <= offset && offset <= r.end)))
57}
58
59/// Resolve the token at the request's cursor (see [`token_at_cursor`]) into a
60/// [`TokenComponent`]. In whitespace, the token is empty and sits at the
61/// cursor, so completion text is inserted there and filters accept anything.
62#[instrument(skip(query, commands))]
63pub fn get_current_cst_token(
64    query: Query<(Entity, &CstTokens, &PositionComponent, &RopeC, &Source)>,
65    mut commands: Commands,
66) {
67    for (entity, cst_tokens, position, rope, source) in &query {
68        commands.entity(entity).remove::<TokenComponent>();
69        let Some(offset) = position_to_offset(position.0, &rope.0) else {
70            debug!("Couldn't transform to an offset ({:?})", position.0);
71            continue;
72        };
73
74        let span = token_at_cursor(cst_tokens.0.iter().map(|t| t.span()), &source.0, offset)
75            .filter(|span| span.end <= source.0.len())
76            .unwrap_or(offset..offset);
77
78        let text = source.0[span.clone()].to_string();
79        let Some(range) = range_to_range(&span, &rope.0) else {
80            debug!("Failed to transform span to range");
81            continue;
82        };
83        debug!("Token at cursor {:?} '{}'", span, text);
84        commands.entity(entity).insert(TokenComponent {
85            text,
86            range,
87            source_span: span,
88            is_error: false,
89        });
90    }
91}
92
93#[cfg(test)]
94mod cursor_tests {
95    use super::token_at_cursor;
96
97    /// Spans of the whitespace-separated tokens of `src`, with `;` `.` `[` `]`
98    /// split off as their own tokens.
99    fn spans(src: &str) -> Vec<std::ops::Range<usize>> {
100        let mut out = Vec::new();
101        let mut start = None;
102        for (i, c) in src.char_indices() {
103            let punct = ";.[]".contains(c);
104            if c.is_whitespace() || punct {
105                if let Some(s) = start.take() {
106                    out.push(s..i);
107                }
108                if punct {
109                    out.push(i..i + 1);
110                }
111            } else if start.is_none() {
112                start = Some(i);
113            }
114        }
115        if let Some(s) = start {
116            out.push(s..src.len());
117        }
118        out
119    }
120
121    fn at(src: &str) -> Option<String> {
122        let offset = src.find('|').unwrap();
123        let src = src.replace('|', "");
124        let spans = spans(&src);
125        token_at_cursor(spans.iter(), &src, offset).map(|r| src[r].to_string())
126    }
127
128    #[test]
129    fn cursor_belongs_to_the_word_it_touches() {
130        assert_eq!(at("<a> ex:fo|;").as_deref(), Some("ex:fo"));
131        assert_eq!(at("<a> ex:fo|").as_deref(), Some("ex:fo"));
132        assert_eq!(at("<a> |ex:name .").as_deref(), Some("ex:name"));
133        assert_eq!(at("<a> ex:na|me .").as_deref(), Some("ex:name"));
134    }
135
136    #[test]
137    fn punctuation_only_when_no_word_touches_the_cursor() {
138        assert_eq!(at("<a> a ex:C ;|").as_deref(), Some(";"));
139        assert_eq!(at("<a> ex:p [|").as_deref(), Some("["));
140    }
141
142    #[test]
143    fn whitespace_has_no_token() {
144        assert_eq!(at("<a> a ex:C ;\n  |\n."), None);
145        assert_eq!(at("<a> ex:p [\n    |\n] ."), None);
146    }
147}
148
149pub mod semantic_token {
150    use crate::lsp_types::SemanticTokenType as STT;
151    pub const BOOLEAN: STT = STT::new("boolean");
152    pub const LANG_TAG: STT = STT::new("langTag");
153}