Skip to main content

swls_lang_turtle/
lib.rs

1#![doc(
2    html_logo_url = "https://ajuvercr.github.io/semantic-web-lsp/assets/icons/favicon.png",
3    html_favicon_url = "https://ajuvercr.github.io/semantic-web-lsp/assets/icons/favicon.ico"
4)]
5use bevy_ecs::{component::Component, resource::Resource, world::World};
6use swls_core::{
7    lang::{Lang, LangHelper},
8    lsp_types::SemanticTokenType,
9    prelude::*,
10};
11use swls_lang_rdf_base::register_rdf_lang;
12
13pub mod config;
14pub mod ecs;
15pub mod lang;
16pub mod prefix;
17
18use crate::{
19    config::{extract_known_prefixes_from_config, extract_known_shapes_from_config},
20    ecs::{setup_code_action, setup_completion, setup_formatting, setup_parsing},
21};
22
23#[derive(Component, Default)]
24pub struct TurtleLang;
25
26#[derive(Debug, Default)]
27pub struct TurtleHelper;
28impl LangHelper for TurtleHelper {
29    fn keyword(&self) -> &[&'static str] {
30        &["@prefix", "@base", "a"]
31    }
32    fn model_based_rename(&self) -> bool {
33        true
34    }
35    fn blank_node_code_actions(&self) -> bool {
36        true
37    }
38}
39
40pub fn setup_world<C: Client + ClientSync + Resource + Clone>(world: &mut World) {
41    register_rdf_lang::<TurtleLang, TurtleHelper>(
42        world,
43        &["turtle"],
44        // .owl ontologies are commonly serialized as Turtle; N-Triples (.nt) is a
45        // strict subset of Turtle. (.n3 is handled by the dedicated N3 language.)
46        &[".ttl", ".owl", ".nt"],
47    );
48
49    world.schedule_scope(swls_core::Startup, |_, schedule| {
50        schedule.add_systems((
51            extract_known_prefixes_from_config::<C>,
52            extract_known_shapes_from_config::<C>,
53        ));
54    });
55    // A changed configuration may name new ontologies and shapes.
56    world.schedule_scope(swls_core::ConfigChanged, |_, schedule| {
57        schedule.add_systems((
58            extract_known_prefixes_from_config::<C>,
59            extract_known_shapes_from_config::<C>,
60        ));
61    });
62
63    setup_parsing(world);
64    setup_completion(world);
65    setup_formatting(world);
66    setup_code_action(world);
67}
68
69impl Lang for TurtleLang {
70    type ElementError = crate::lang::parser::TurtleParseError;
71
72    const LANG: &'static str = "turtle";
73    const TRIGGERS: &'static [&'static str] = &[":"];
74    const CODE_ACTION: bool = true;
75    const HOVER: bool = true;
76
77    const LEGEND_TYPES: &'static [swls_core::lsp_types::SemanticTokenType] = &[
78        semantic_token::BOOLEAN,
79        semantic_token::LANG_TAG,
80        SemanticTokenType::COMMENT,
81        SemanticTokenType::ENUM_MEMBER,
82        SemanticTokenType::ENUM,
83        SemanticTokenType::KEYWORD,
84        SemanticTokenType::NAMESPACE,
85        SemanticTokenType::NUMBER,
86        SemanticTokenType::PROPERTY,
87        SemanticTokenType::STRING,
88        SemanticTokenType::VARIABLE,
89    ];
90
91    const PATTERN: Option<&'static str> = None;
92
93    fn semantic_token_type(kind: rowan::SyntaxKind) -> Option<SemanticTokenType> {
94        use rdf_parsers::turtle::SyntaxKind as SK;
95
96        // Convert rowan::SyntaxKind(u16) to turtle SyntaxKind via the raw discriminant.
97        let k = kind.0;
98        if k == SK::Comment as u16 {
99            Some(SemanticTokenType::COMMENT)
100        } else if k == SK::Iriref as u16 {
101            Some(SemanticTokenType::PROPERTY)
102        } else if k == SK::Integer as u16 || k == SK::Decimal as u16 || k == SK::Double as u16 {
103            Some(SemanticTokenType::NUMBER)
104        } else if k == SK::StringLiteralQuote as u16
105            || k == SK::StringLiteralSingleQuote as u16
106            || k == SK::StringLiteralLongQuote as u16
107            || k == SK::StringLiteralLongSingleQuote as u16
108        {
109            Some(SemanticTokenType::STRING)
110        } else if k == SK::Langtag as u16 {
111            Some(semantic_token::LANG_TAG)
112        } else if k == SK::TrueLit as u16 || k == SK::FalseLit as u16 {
113            Some(semantic_token::BOOLEAN)
114        } else if k == SK::BaseToken as u16
115            || k == SK::PrefixToken as u16
116            || k == SK::SparqlBaseToken as u16
117            || k == SK::SparqlPrefixToken as u16
118            || k == SK::Alit as u16
119        {
120            Some(SemanticTokenType::KEYWORD)
121        } else {
122            None
123        }
124    }
125
126    fn semantic_token_spans(
127        kind: rowan::SyntaxKind,
128        span: std::ops::Range<usize>,
129        text: &str,
130    ) -> Vec<(SemanticTokenType, std::ops::Range<usize>)> {
131        use rdf_parsers::turtle::SyntaxKind as SK;
132        let k = kind.0;
133        let this_kind = SK::from(kind);
134        if k == SK::PnameLn as u16 {
135            // PnameLn = "prefix:local" — emit NAMESPACE for "prefix:" and PROPERTY for "local".
136            // Slice to just the token text so split_once finds the colon within the token,
137            // not the first colon in the whole document.
138            let token_text = text.get(span.clone()).unwrap_or("");
139            if let Some((a, _)) = token_text.split_once(':') {
140                let (start, end) = (span.start, span.end);
141                vec![
142                    (SemanticTokenType::NAMESPACE, start..start + a.len() + 1),
143                    (SemanticTokenType::PROPERTY, start + a.len() + 1..end),
144                ]
145            } else {
146                vec![(SemanticTokenType::PROPERTY, span)]
147            }
148        } else if k == SK::PnameNs as u16 {
149            vec![(SemanticTokenType::NAMESPACE, span)]
150        } else if k == SK::BlankNodeLabel as u16 {
151            // "_:label" — "_:" is NAMESPACE, label is PROPERTY
152            if span.len() > 2 {
153                vec![
154                    (SemanticTokenType::NAMESPACE, span.start..span.start + 2),
155                    (SemanticTokenType::PROPERTY, span.start + 2..span.end),
156                ]
157            } else {
158                vec![(SemanticTokenType::NAMESPACE, span)]
159            }
160        } else {
161            let output = Self::semantic_token_type(kind)
162                .map(|t| vec![(t, span.clone())])
163                .unwrap_or_default();
164            tracing::trace!("token kind {:?} {:?} {:?}", this_kind, span, output);
165            output
166        }
167    }
168}