Skip to main content

swls_lang_turtle/
prefix.rs

1use std::{borrow::Cow, collections::HashMap};
2
3use swls_core::{
4    lsp_types::Url,
5    prelude::*,
6    util::{cache::cached, fs::File},
7};
8
9use swls_lang_rdf_base::traits::{NamedNodeExt, Turtle, TurtleExt};
10
11/// Finds a resource.
12/// If the location starts with http, it is a remote resource.
13/// If the location fails to parse as a url, it is a file path to read.
14pub async fn find(location: &str, fs: &Fs, client: &impl Client) -> Option<Vec<(String, Url)>> {
15    if location.starts_with("http") {
16        let url = Url::parse(location).ok()?;
17        let fetch = || async {
18            let resp = client
19                .fetch(
20                    location,
21                    &HashMap::from([(String::from("Accept"), String::from("text/turtle"))]),
22                )
23                .await
24                .ok()?;
25            if resp.status != 200 {
26                tracing::warn!("Fetching {} failed with status {}", location, resp.status);
27                return None;
28            }
29            Some(resp.body)
30        };
31        // Remote resources are cached, so the server starts offline with
32        // what it fetched before and does not hit the network on every start.
33        let content = match fs.0.cache_url(&url) {
34            Some(cache_url) => cached(fs, &cache_url, fetch).await?,
35            None => fetch().await?,
36        };
37        Some(vec![(content, url)])
38    } else {
39        if let Ok(url) = Url::parse(location) {
40            let content = fs.0.read_file(&url).await?;
41            Some(vec![(content, url)])
42        } else {
43            let files = fs.0.glob_read(location).await?;
44            Some(
45                files
46                    .into_iter()
47                    .flat_map(|File { content, name }| {
48                        file_name_to_url(&name).map(|url| (content, url))
49                    })
50                    .collect(),
51            )
52        }
53    }
54}
55
56#[cfg(not(target_arch = "wasm32"))]
57pub fn file_name_to_url(name: &str) -> Option<Url> {
58    swls_core::lsp_types::Url::from_file_path(name).ok()
59}
60
61#[cfg(target_arch = "wasm32")]
62pub fn file_name_to_url(_name: &str) -> Option<Url> {
63    None
64}
65
66pub fn prefix_from_url(url: &Url) -> Option<(Cow<'static, str>, Cow<'static, str>)> {
67    let mut segments = url.path_segments()?;
68    let last = segments.next_back()?;
69
70    let prefix = last.rsplit_once('.').map(|(x, _)| x).unwrap_or(last);
71    let prefix: Cow<'static, str> = Cow::Owned(prefix.to_string());
72
73    let url = Cow::Owned(url.to_string());
74
75    Some((prefix, url))
76}
77
78pub fn prefix_from_declaration(
79    turtle: &Triples2<'_>,
80) -> Option<(Cow<'static, str>, Cow<'static, str>)> {
81    let subject = turtle
82        .iter()
83        .find(|t| {
84            t.predicate.as_str() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
85                && t.object.as_str() == "http://www.w3.org/2002/07/owl#Ontology"
86        })?
87        .subject
88        .to_owned();
89
90    let prefix = turtle
91        .iter()
92        .find(|t| {
93            t.subject.eq(&subject)
94                && t.predicate.as_str() == "http://purl.org/vocab/vann/preferredNamespacePrefix"
95        })?
96        .object
97        .as_str();
98    let prefix = Cow::Owned(String::from(prefix));
99
100    let url = turtle
101        .iter()
102        .find(|t| {
103            t.subject.eq(&subject)
104                && t.predicate.as_str() == "http://purl.org/vocab/vann/preferredNamespaceUri"
105        })?
106        .object
107        .as_str();
108    let url = Cow::Owned(String::from(url));
109
110    Some((prefix, url))
111}
112
113pub fn prefix_from_prefixes(
114    model: &Turtle,
115    turtle: &Triples2<'_>,
116) -> Option<(Cow<'static, str>, Cow<'static, str>)> {
117    let shortened: Vec<_> = turtle
118        .iter()
119        .filter(|x| x.predicate.as_str() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
120        .flat_map(|t| model.shorten(t.subject.as_str()))
121        .collect();
122
123    let mut counts = HashMap::new();
124    for short in &shortened {
125        if let Some((prefix, _)) = short.split_once(':') {
126            let key: &mut usize = counts.entry(prefix).or_default();
127            *key += 1;
128        }
129    }
130
131    let (prefix, _) = counts.into_iter().max_by_key(|(_, e)| *e)?;
132
133    let prefix = model
134        .prefixes
135        .iter()
136        .find(|p| p.prefix.as_str() == prefix)?;
137
138    Some((
139        Cow::Owned(String::from(prefix.prefix.as_str())),
140        Cow::Owned(prefix.value.0.expand(model)?),
141    ))
142}
143
144pub fn prefix_from_source(
145    url: &Url,
146    source: &str,
147) -> Option<(Cow<'static, str>, Cow<'static, str>)> {
148    use crate::lang::parser::parse_new;
149    let (turtle, _, _, _, _) = parse_new(source, url.as_str(), None);
150
151    let triples = turtle.get_simple_triples().ok()?;
152
153    prefix_from_declaration(&triples).or_else(|| prefix_from_prefixes(&turtle, &triples))
154}