Skip to main content

swls_core/
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)]
5//! Core and common implementation for the semantic web language server.
6//!
7//! Proivdes the backbone for the [semantic web lsp binary](../lsp_bin/index.html) and [semantic web
8//! lsp wasm](../lsp_web/index.html).
9//!
10//! With the language server protocol, each different request is handled by an ECS schedule,
11//! combining different systems together.
12//! A system can generate new data and attach it to an entity, a document, or use this data to
13//! respond to requests.
14//!
15//! Language specific implementations that handle things like tokenizing and parsing are
16//! implemented in separate crates. The binary currently supports [Turtle](../swls_lang_turtle/index.html), [JSON-LD](../swls_lang_jsonld/index.html) and [SPARQL](../swls_lang_sparql/index.html).
17//! The goal is that each language at least generates [`Tokens`], [`Triples`] and
18//! [`Prefixes`].
19//! These components are then used to derive properties for autcompletion but also derive
20//! [`TokenComponent`] and [`TripleComponent`] enabling completion.
21//!
22//! The different schedules can be found at [`prelude::feature`].
23//!
24//! ## Example add completion for all subjects that start with `a`
25//! ```
26//! use bevy_ecs::prelude::*;
27//! use swls_core::prelude::*;
28//! # use sophia_api::dataset::Dataset;
29//! # use sophia_api::prelude::Quad;
30//!
31//! // Define the extra data struct
32//! #[derive(Component)]
33//! struct MyCompletions {
34//!     subjects: Vec<String>,
35//! }
36//!
37//! // Define the generating system
38//! // Don't forget to add it to the ecs later
39//! fn generate_my_completion(
40//!   // Only derive the completions when the document is parsed fully, aka is not Dirty
41//!   query: Query<(Entity, &Triples), (Changed<Triples>, Without<Dirty>)>,
42//!   mut commands: Commands,
43//! ) {
44//!   for (e, triples) in &query {
45//!     let mut subjects = Vec::new();
46//!     for q in triples.quads().flatten() {
47//!       if q.s().as_str().starts_with('a') {
48//!         subjects.push(q.s().as_str().to_string());
49//!       }
50//!     }
51//!     commands.entity(e).insert(MyCompletions { subjects });
52//!   }
53//! }
54//!
55//! // Define a system that adds these completions to the completion request
56//! fn complete_my_completion(
57//!   mut query: Query<(
58//!     &TokenComponent, &TripleComponent, &MyCompletions, &mut CompletionRequest
59//!   )>,
60//! ) {
61//!   for (token, this_triple, completions, mut request) in &mut query {
62//!     if this_triple.target == TripleTarget::Subject {
63//!       for my_completion in &completions.subjects {
64//!         request.push(
65//!           SimpleCompletion::new(
66//!             swls_core::lsp_types::CompletionItemKind::FIELD,
67//!             my_completion.clone(),
68//!             swls_core::lsp_types::TextEdit {
69//!               range: token.range.clone(),
70//!               new_text: my_completion.clone(),
71//!             }
72//!           )
73//!         )
74//!       }
75//!     }
76//!   }
77//! }
78//! ```
79//! Note that [`Prefixes`] can help expand and shorten iri's in a document.
80//!
81//!
82
83use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
84pub use lsp_types;
85use prelude::SemanticTokensDict;
86use systems::{init_ontology_extractor, populate_known_ontologies, OntologyExtractor};
87
88use crate::prelude::*;
89
90/// Main language server implementation.
91///
92/// [`Backend`](struct@backend::Backend) exposes transport-agnostic request handlers.
93/// The `swls` binary adapts these to `tower_lsp::LanguageServer`.
94/// Each incoming request a schedule is ran on the main [`World`].
95pub mod backend;
96
97/// Handle platform specific implementations for fetching and spawning tasks.
98pub mod client;
99/// Document links, symbols, folding ranges and workspace symbols.
100pub mod navigation;
101pub mod revisions;
102pub mod store;
103/// Minimal text indexing for LSP position math (replaces ropey).
104pub mod text;
105/// Common utils
106///
107/// Includes range transformations between [`std::ops::Range`] and [`swls_core::lsp_types::Range`].
108/// And commonly used [`Spanned`].
109pub mod util;
110/// The workspace's RDF files, loaded in the background.
111pub mod workspace;
112
113/// Defines all common [`Component`]s and [`Resource`]s
114///
115/// In this [`World`], [Entity]s are documents and [`Components`](`Component`) are derived from these documents.
116/// Different [`System`]s derive new [`Components`](`Component`) from existing [`Components`](`Component`), that are added to
117/// the [`Entity`].
118/// For example, if [`Triples`] are defined, [systems::derive_classes] will
119/// derive [`DefinedClass`](struct@systems::DefinedClass) from them and add them to the [`Entity`].
120pub mod components;
121/// Editor lifecycle of documents (open / close) and the cached-copy rules.
122pub mod document;
123/// Hosts all common features of the semantic language server.
124pub mod feature;
125/// Defines common language traits
126pub mod lang;
127pub mod prelude;
128pub mod systems;
129
130/// Initializes a [`World`], including [`Resources`](`Resource`) and [`Schedules`].
131/// All systems defined in [`crate`] are added to the [`World`].
132pub fn setup_schedule_labels<C: Client + Resource>(world: &mut World) {
133    world.init_resource::<SemanticTokensDict>();
134    world.init_resource::<TypeHierarchy>();
135    world.init_resource::<Ontologies>();
136    world.insert_resource(OntologyExtractor::new());
137    world.init_resource::<systems::PreferredPrefixes>();
138    world.init_resource::<components::Documents>();
139    world.init_resource::<revisions::Revisions>();
140
141    parse::setup_schedule::<C>(world);
142    hover::setup_schedule(world);
143    completion::setup_schedule(world);
144    rename::setup_schedules(world);
145    save::setup_schedule(world);
146    format::setup_schedule(world);
147    on_type_format::setup_schedule(world);
148    references::setup_schedule(world);
149    inlay::setup_schedule(world);
150    goto_definition::setup_schedule(world);
151    goto_type::setup_schedule(world);
152    code_action::setup_schedule(world);
153
154    semantic::setup_world(world);
155
156    world.add_schedule(Schedule::new(Tasks));
157
158    let mut schedule = Schedule::new(Startup);
159    schedule.add_systems((
160        init_ontology_extractor,
161        populate_known_ontologies,
162        // extract_known_prefixes_from_config::<C>,
163    ));
164
165    world.add_schedule(schedule);
166    world.add_schedule(Schedule::new(ConfigChanged));
167
168    let mut started = Schedule::new(Started);
169    started.add_systems(workspace::index_workspace::<C>);
170    world.add_schedule(started);
171}
172
173/// Event triggers when a document is opened
174///
175/// Example
176/// ```rust
177/// # use swls_core::components::DynLang;
178/// # use swls_core::CreateEvent;
179/// # use swls_core::lang::LangHelper;
180/// # use bevy_ecs::event::EntityEvent;
181/// # use bevy_ecs::prelude::{Commands, On, World, Component};
182///
183/// #[derive(Component)]
184/// pub struct TurtleLang;
185///
186/// #[derive(Debug)]
187/// pub struct TurtleHelper;
188/// impl LangHelper for TurtleHelper {
189///     fn keyword(&self) -> &[&'static str] {
190///         &[
191///             "@prefix",
192///             "@base",
193///             "a",
194///         ]
195///     }
196/// }
197///
198/// let mut world = World::new();
199/// // This example tells the ECS system that the document is Turtle,
200/// // adding Turtle specific components
201/// world.add_observer(|trigger: On<CreateEvent>, mut commands: Commands| {
202///     match &trigger.event().language_id {
203///         Some(x) if x == "turtle" => {
204///             commands
205///                 .entity(trigger.event_target())
206///                 .insert((TurtleLang, DynLang(Box::new(TurtleHelper))));
207///             return;
208///         }
209///         _ => {}
210///     }
211///     if trigger.event().url.as_str().ends_with(".ttl") {
212///         commands
213///             .entity(trigger.event_target())
214///             .insert((TurtleLang, DynLang(Box::new(TurtleHelper))));
215///         return;
216///     }
217/// });
218/// ```
219///
220#[derive(EntityEvent)]
221pub struct CreateEvent {
222    pub url: crate::lsp_types::Url,
223    pub language_id: Option<String>,
224    #[event_target]
225    pub entity: Entity,
226}
227
228/// [`ScheduleLabel`] related to the Tasks schedule
229/// This schedule is used for async tasks, things that should be done at some point.
230///
231/// For example [`systems::handle_tasks`] spawns command queues sent with
232/// [`CommandSender`]
233#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
234pub struct Tasks;
235
236#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
237pub struct Startup;
238
239#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
240pub struct Started;
241
242/// Runs after `workspace/didChangeConfiguration` replaced the
243/// [`ServerConfig`](crate::prelude::ServerConfig): systems that load what the
244/// configuration names (ontologies, shapes) add themselves here.
245#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
246pub struct ConfigChanged;