Skip to main content

swls_core/util/
mod.rs

1use crate::{
2    lsp_types::{Location, Position, Range},
3    text::{LineIndex, PositionEncoding},
4    Label,
5};
6
7/// Encoding used for all LSP positions emitted/consumed by these helpers.
8///
9/// The LSP default is UTF-16; until we negotiate `positionEncoding` at
10/// `initialize`, everything goes through this single constant so the choice is
11/// explicit and changeable in one place.
12const ENCODING: PositionEncoding = PositionEncoding::Utf16;
13
14pub mod cache;
15pub mod fs;
16pub mod lang_text;
17/// Commonly used RDF prefixes
18pub mod ns;
19pub mod token;
20pub mod triple;
21
22pub use rdf_parsers::{spanned, Spanned};
23
24// /// Maps http:// and https:// urls to virtual:// urls
25// /// This enables the editor to show them
26// pub fn make_virtual_url(url: &str, prefix: &str) -> Option<Url> {
27//     if !url.starts_with("http") {
28//         return None;
29//     }
30//
31//     let url = format!("virtual://prefix/{}.ttl", prefix);
32//
33//     crate::lsp_types::Url::parse(&url).ok()
34// }
35
36pub fn range_to_range(range: &std::ops::Range<usize>, rope: &LineIndex) -> Option<Range> {
37    let start = offset_to_position(range.start, rope)?;
38    let end = offset_to_position(range.end, rope)?;
39    Range::new(start, end).into()
40}
41
42pub fn lsp_range_to_range(
43    range: &crate::lsp_types::Range,
44    rope: &LineIndex,
45) -> Option<std::ops::Range<usize>> {
46    let start = position_to_offset(range.start, rope)?;
47    let end = position_to_offset(range.end, rope)?;
48    Some(start..end)
49}
50
51pub fn offset_to_position(offset: usize, rope: &LineIndex) -> Option<Position> {
52    rope.byte_to_position(offset, ENCODING)
53}
54pub fn position_to_offset(position: Position, rope: &LineIndex) -> Option<usize> {
55    rope.position_to_byte(position, ENCODING)
56}
57pub fn offsets_to_range(start: usize, end: usize, rope: &LineIndex) -> Option<Range> {
58    let start = offset_to_position(start, rope)?;
59    let end = offset_to_position(end, rope)?;
60    Some(Range { start, end })
61}
62
63pub fn token_to_location(
64    token: &std::ops::Range<usize>,
65    label: &Label,
66    rope: &LineIndex,
67) -> Option<Location> {
68    let range = range_to_range(token, rope)?;
69    Some(Location {
70        range,
71        uri: label.0.clone(),
72    })
73}
74
75// ── IRI resolution ────────────────────────────────────────────────────────────
76
77/// Resolve `relative` against `base` using RFC 3986 path resolution, without
78/// any IRI validation.  This intentionally accepts non-standard / "invalid"
79/// IRIs so that tokens in the source document can be round-tripped back to the
80/// triple store without percent-encoding transformations.
81pub fn resolve_iri(base: &str, relative: &str) -> String {
82    // Already absolute (has a scheme colon before any slash or query char).
83    if looks_absolute(relative) {
84        return relative.to_string();
85    }
86    // Protocol-relative  //authority/path
87    if relative.starts_with("//") {
88        let scheme = base.split("://").next().unwrap_or("http");
89        return format!("{}:{}", scheme, relative);
90    }
91    // Root-relative  /path
92    if relative.starts_with('/') {
93        let authority_end = base
94            .find("://")
95            .and_then(|i| base[i + 3..].find('/').map(|j| i + 3 + j))
96            .unwrap_or(base.len());
97        return format!("{}{}", &base[..authority_end], relative);
98    }
99    // Fragment-only or empty  #frag  or  ""
100    if relative.is_empty() || relative.starts_with('#') {
101        let base_no_frag = base.split('#').next().unwrap_or(base);
102        return format!("{}{}", base_no_frag, relative);
103    }
104    // Relative path — merge with the base's "directory"
105    let base_dir = match base.rfind('/') {
106        Some(i) => &base[..=i],
107        None => "",
108    };
109    let merged = format!("{}{}", base_dir, relative);
110    normalize_path_segments(&merged)
111}
112
113/// Heuristic: does `s` carry its own scheme?  We look for `<scheme>:` where
114/// scheme starts with a letter and contains only [A-Za-z0-9+\-.].
115fn looks_absolute(s: &str) -> bool {
116    let bytes = s.as_bytes();
117    if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() {
118        return false;
119    }
120    for (i, &b) in bytes.iter().enumerate() {
121        if b == b':' {
122            return i > 0;
123        }
124        if !matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'.') {
125            return false;
126        }
127    }
128    false
129}
130
131/// Remove `.` and `..` segments from a merged path string, preserving any
132/// authority prefix (`scheme://host`).
133fn normalize_path_segments(path: &str) -> String {
134    // Split off a leading scheme://authority so we don't mangle it.
135    let (prefix, rest) = if let Some(i) = path.find("://") {
136        let after = &path[i + 3..];
137        let slash = after.find('/').map(|j| i + 3 + j).unwrap_or(path.len());
138        (&path[..slash], &path[slash..])
139    } else {
140        ("", path)
141    };
142
143    // The path's leading `/` is re-added below; splitting it would also yield
144    // an empty first segment and double the slash (`http://a//s`).
145    let (leading, rest) = match rest.strip_prefix('/') {
146        Some(r) => ("/", r),
147        None => ("", rest),
148    };
149    let mut stack: Vec<&str> = Vec::new();
150    for seg in rest.split('/') {
151        match seg {
152            "." => {}
153            ".." => {
154                stack.pop();
155            }
156            s => stack.push(s),
157        }
158    }
159    // If the original path ended with /. or /.. keep a trailing slash.
160    let trailing = if rest.ends_with("/..") || rest.ends_with("/.") || rest == ".." || rest == "." {
161        "/"
162    } else {
163        ""
164    };
165    format!("{}{}{}{}", prefix, leading, stack.join("/"), trailing)
166}
167
168#[cfg(test)]
169mod resolve_iri_tests {
170    use super::resolve_iri;
171
172    #[test]
173    fn relative_path() {
174        assert_eq!(
175            resolve_iri("http://example.com/doc", "s"),
176            "http://example.com/s"
177        );
178        assert_eq!(
179            resolve_iri("http://example.com/a/doc", "s"),
180            "http://example.com/a/s"
181        );
182        assert_eq!(
183            resolve_iri("http://example.com/a/", "b/c"),
184            "http://example.com/a/b/c"
185        );
186        assert_eq!(
187            resolve_iri("file:///home/u/x.ttl", "y.ttl"),
188            "file:///home/u/y.ttl"
189        );
190    }
191
192    #[test]
193    fn dot_segments() {
194        assert_eq!(
195            resolve_iri("http://example.com/a/b/doc", "../s"),
196            "http://example.com/a/s"
197        );
198        assert_eq!(
199            resolve_iri("http://example.com/a/b/doc", "./s"),
200            "http://example.com/a/b/s"
201        );
202        assert_eq!(
203            resolve_iri("http://example.com/a/b/doc", ".."),
204            "http://example.com/a/"
205        );
206        assert_eq!(
207            resolve_iri("http://example.com/a/b/doc", "."),
208            "http://example.com/a/b/"
209        );
210    }
211
212    #[test]
213    fn absolute_root_fragment() {
214        assert_eq!(
215            resolve_iri("http://example.com/doc", "http://x.org/y"),
216            "http://x.org/y"
217        );
218        assert_eq!(
219            resolve_iri("http://example.com/a/doc", "/s"),
220            "http://example.com/s"
221        );
222        assert_eq!(
223            resolve_iri("http://example.com/doc#x", "#y"),
224            "http://example.com/doc#y"
225        );
226        assert_eq!(
227            resolve_iri("http://example.com/doc", ""),
228            "http://example.com/doc"
229        );
230        assert_eq!(
231            resolve_iri("https://example.com/doc", "//other.org/s"),
232            "https://other.org/s"
233        );
234    }
235}