tinymist_query/
lib.rs

1//! # tinymist-query
2//!
3//! **Note: this crate is under development. it currently doesn't ensure stable
4//! APIs, and heavily depending on some unstable crates.**
5//!
6//! This crate provides a set of APIs to query the information about the source
7//! code. Currently it provides:
8//! + language queries defined by the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/).
9
10pub use analysis::{CompletionFeat, LocalContext, LocalContextGuard, LspWorldExt};
11pub use completion::{CompletionRequest, PostfixSnippet};
12pub use typlite::ColorTheme;
13pub use upstream::with_vm;
14
15pub use check::*;
16pub use code_action::*;
17pub use code_context::*;
18pub use code_lens::*;
19pub use color_presentation::*;
20pub use diagnostics::*;
21pub use document_color::*;
22pub use document_highlight::*;
23pub use document_link::*;
24pub use document_metrics::*;
25pub use document_symbol::*;
26pub use folding_range::*;
27pub use goto_declaration::*;
28pub use goto_definition::*;
29pub use hover::*;
30pub use inlay_hint::*;
31pub use jump::*;
32pub use lsp_typst_boundary::*;
33pub use on_enter::*;
34pub use prepare_rename::*;
35pub use references::*;
36pub use rename::*;
37pub use selection_range::*;
38pub use semantic_tokens_delta::*;
39pub use semantic_tokens_full::*;
40pub use signature_help::*;
41pub use symbol::*;
42pub use will_rename_files::*;
43pub use workspace_label::*;
44
45pub mod analysis;
46pub mod docs;
47pub mod package;
48pub mod syntax;
49pub mod testing;
50pub use tinymist_analysis::{ty, upstream};
51
52/// The physical position in a document.
53pub type FramePosition = typst::layout::Position;
54
55mod adt;
56mod lsp_typst_boundary;
57mod prelude;
58
59mod bib;
60mod check;
61mod code_action;
62mod code_context;
63mod code_lens;
64mod color_presentation;
65mod completion;
66mod diagnostics;
67mod document_color;
68mod document_highlight;
69mod document_link;
70mod document_metrics;
71mod document_symbol;
72mod folding_range;
73mod goto_declaration;
74mod goto_definition;
75mod hover;
76mod inlay_hint;
77mod jump;
78mod on_enter;
79mod prepare_rename;
80mod references;
81mod rename;
82mod selection_range;
83mod semantic_tokens_delta;
84mod semantic_tokens_full;
85mod signature_help;
86mod symbol;
87mod will_rename_files;
88mod workspace_label;
89
90use typst::syntax::Source;
91
92use tinymist_analysis::{adt::interner::Interned, log_debug_ct};
93use tinymist_project::LspComputeGraph;
94
95/// A reference to the interned string
96pub(crate) type StrRef = Interned<str>;
97
98/// A request handler with given syntax information.
99pub trait SyntaxRequest {
100    /// The response type of the request.
101    type Response;
102
103    /// Request the information from the given source.
104    fn request(
105        self,
106        source: &Source,
107        positing_encoding: PositionEncoding,
108    ) -> Option<Self::Response>;
109}
110
111/// A request handler with given (semantic) analysis context.
112pub trait SemanticRequest {
113    /// The response type of the request.
114    type Response;
115
116    /// Request the information from the given context.
117    fn request(self, ctx: &mut LocalContext) -> Option<Self::Response>;
118}
119
120/// A request handler with given (semantic) analysis context and a project
121/// snapshot.
122pub trait StatefulRequest {
123    /// The response type of the request.
124    type Response;
125
126    /// Request the information from the given context.
127    fn request(self, ctx: &mut LocalContext, graph: LspComputeGraph) -> Option<Self::Response>;
128}
129
130mod polymorphic {
131    use completion::CompletionList;
132    use lsp_types::TextEdit;
133    use serde::{Deserialize, Serialize};
134    use tinymist_project::ProjectTask;
135    use typst::foundations::Dict;
136
137    use super::prelude::*;
138    use super::*;
139
140    /// A request to run an export task.
141    #[derive(Debug, Clone)]
142    pub struct OnExportRequest {
143        /// The path of the document to export.
144        pub path: PathBuf,
145        /// The export task to run.
146        pub task: ProjectTask,
147        /// Whether to open the exported file(s) after the export is done.
148        pub open: bool,
149    }
150
151    /// A request to format the document.
152    #[derive(Debug, Clone)]
153    pub struct FormattingRequest {
154        /// The path of the document to get semantic tokens for.
155        pub path: PathBuf,
156    }
157
158    /// A request to get the server info.
159    #[derive(Debug, Clone)]
160    pub struct ServerInfoRequest {}
161
162    /// The response to the server info request.
163    #[derive(Debug, Clone, Serialize, Deserialize)]
164    #[serde(rename_all = "camelCase")]
165    pub struct ServerInfoResponse {
166        /// The root path of the server.
167        pub root: Option<PathBuf>,
168        /// The font paths of the server.
169        pub font_paths: Vec<PathBuf>,
170        /// The inputs of the server.
171        pub inputs: Dict,
172        /// The statistics of the server.
173        pub stats: HashMap<String, String>,
174    }
175
176    /// The feature of the fold request.
177    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
178    pub enum FoldRequestFeature {
179        /// Serves the request with the first pinned entry.
180        PinnedFirst,
181        /// Makes the items unique.
182        Unique,
183        /// Merges the items.
184        Mergeable,
185        /// Makes the items unique without context.
186        ContextFreeUnique,
187    }
188
189    /// The analysis request.
190    #[derive(Debug, Clone, strum::IntoStaticStr)]
191    pub enum CompilerQueryRequest {
192        /// A request to run an export task.
193        OnExport(OnExportRequest),
194        /// A request to get the hover information.
195        Hover(HoverRequest),
196        /// A request to go to the definition.
197        GotoDefinition(GotoDefinitionRequest),
198        /// A request to go to the declaration.
199        GotoDeclaration(GotoDeclarationRequest),
200        /// A request to get the references.
201        References(ReferencesRequest),
202        /// A request to get the inlay hints.
203        InlayHint(InlayHintRequest),
204        /// A request to get the document colors.
205        DocumentColor(DocumentColorRequest),
206        /// A request to get the document links.
207        DocumentLink(DocumentLinkRequest),
208        /// A request to get the document highlights.
209        DocumentHighlight(DocumentHighlightRequest),
210        /// A request to get the color presentations.
211        ColorPresentation(ColorPresentationRequest),
212        /// A request to get the code actions.
213        CodeAction(CodeActionRequest),
214        /// A request to get the code lenses.
215        CodeLens(CodeLensRequest),
216        /// A request to get the completions.
217        Completion(CompletionRequest),
218        /// A request to get the signature helps.
219        SignatureHelp(SignatureHelpRequest),
220        /// A request to rename.
221        Rename(RenameRequest),
222        /// A request to determine the files to be renamed.
223        WillRenameFiles(WillRenameFilesRequest),
224        /// A request to prepare the rename.
225        PrepareRename(PrepareRenameRequest),
226        /// A request to get the document symbols.
227        DocumentSymbol(DocumentSymbolRequest),
228        /// A request to get the symbols.
229        Symbol(SymbolRequest),
230        /// A request to get the semantic tokens full.
231        SemanticTokensFull(SemanticTokensFullRequest),
232        /// A request to get the semantic tokens delta.
233        SemanticTokensDelta(SemanticTokensDeltaRequest),
234        /// A request to format the document.
235        Formatting(FormattingRequest),
236        /// A request to get the folding ranges.
237        FoldingRange(FoldingRangeRequest),
238        /// A request to get the selection ranges.
239        SelectionRange(SelectionRangeRequest),
240        /// A request to interact with the code context.
241        InteractCodeContext(InteractCodeContextRequest),
242
243        /// A request to get extra text edits on enter.
244        OnEnter(OnEnterRequest),
245
246        /// A request to get the document metrics.
247        DocumentMetrics(DocumentMetricsRequest),
248        /// A request to get the workspace labels.
249        WorkspaceLabel(WorkspaceLabelRequest),
250        /// A request to get the server info.
251        ServerInfo(ServerInfoRequest),
252    }
253
254    impl CompilerQueryRequest {
255        /// Gets the feature of the fold request.
256        pub fn fold_feature(&self) -> FoldRequestFeature {
257            use FoldRequestFeature::*;
258            match self {
259                Self::OnExport(..) => Mergeable,
260                Self::Hover(..) => PinnedFirst,
261                Self::GotoDefinition(..) => PinnedFirst,
262                Self::GotoDeclaration(..) => PinnedFirst,
263                Self::References(..) => PinnedFirst,
264                Self::InlayHint(..) => Unique,
265                Self::DocumentColor(..) => PinnedFirst,
266                Self::DocumentLink(..) => PinnedFirst,
267                Self::DocumentHighlight(..) => PinnedFirst,
268                Self::ColorPresentation(..) => ContextFreeUnique,
269                Self::CodeAction(..) => Unique,
270                Self::CodeLens(..) => Unique,
271                Self::Completion(..) => Mergeable,
272                Self::SignatureHelp(..) => PinnedFirst,
273                Self::Rename(..) => Mergeable,
274                Self::WillRenameFiles(..) => Mergeable,
275                Self::PrepareRename(..) => Mergeable,
276                Self::DocumentSymbol(..) => ContextFreeUnique,
277                Self::WorkspaceLabel(..) => Mergeable,
278                Self::Symbol(..) => Mergeable,
279                Self::SemanticTokensFull(..) => PinnedFirst,
280                Self::SemanticTokensDelta(..) => PinnedFirst,
281                Self::Formatting(..) => ContextFreeUnique,
282                Self::FoldingRange(..) => ContextFreeUnique,
283                Self::SelectionRange(..) => ContextFreeUnique,
284                Self::InteractCodeContext(..) => PinnedFirst,
285
286                Self::OnEnter(..) => ContextFreeUnique,
287
288                Self::DocumentMetrics(..) => PinnedFirst,
289                Self::ServerInfo(..) => Mergeable,
290            }
291        }
292
293        /// Gets the associated path of the request.
294        pub fn associated_path(&self) -> Option<&Path> {
295            Some(match self {
296                Self::OnExport(..) => return None,
297                Self::Hover(req) => &req.path,
298                Self::GotoDefinition(req) => &req.path,
299                Self::GotoDeclaration(req) => &req.path,
300                Self::References(req) => &req.path,
301                Self::InlayHint(req) => &req.path,
302                Self::DocumentColor(req) => &req.path,
303                Self::DocumentLink(req) => &req.path,
304                Self::DocumentHighlight(req) => &req.path,
305                Self::ColorPresentation(req) => &req.path,
306                Self::CodeAction(req) => &req.path,
307                Self::CodeLens(req) => &req.path,
308                Self::Completion(req) => &req.path,
309                Self::SignatureHelp(req) => &req.path,
310                Self::Rename(req) => &req.path,
311                Self::WillRenameFiles(..) => return None,
312                Self::PrepareRename(req) => &req.path,
313                Self::DocumentSymbol(req) => &req.path,
314                Self::Symbol(..) => return None,
315                Self::WorkspaceLabel(..) => return None,
316                Self::SemanticTokensFull(req) => &req.path,
317                Self::SemanticTokensDelta(req) => &req.path,
318                Self::Formatting(req) => &req.path,
319                Self::FoldingRange(req) => &req.path,
320                Self::SelectionRange(req) => &req.path,
321                Self::InteractCodeContext(req) => &req.path,
322
323                Self::OnEnter(req) => &req.path,
324
325                Self::DocumentMetrics(req) => &req.path,
326                Self::ServerInfo(..) => return None,
327            })
328        }
329    }
330
331    /// The response to the compiler query request.
332    #[derive(Debug, Clone, Serialize, Deserialize)]
333    #[serde(untagged)]
334    pub enum CompilerQueryResponse {
335        /// The response to the on export request.
336        OnExport(Option<PathBuf>),
337        /// The response to the hover request.
338        Hover(Option<Hover>),
339        /// The response to the goto definition request.
340        GotoDefinition(Option<GotoDefinitionResponse>),
341        /// The response to the goto declaration request.
342        GotoDeclaration(Option<GotoDeclarationResponse>),
343        /// The response to the references request.
344        References(Option<Vec<LspLocation>>),
345        /// The response to the inlay hint request.
346        InlayHint(Option<Vec<InlayHint>>),
347        /// The response to the document color request.
348        DocumentColor(Option<Vec<ColorInformation>>),
349        /// The response to the document link request.
350        DocumentLink(Option<Vec<DocumentLink>>),
351        /// The response to the document highlight request.
352        DocumentHighlight(Option<Vec<DocumentHighlight>>),
353        /// The response to the color presentation request.
354        ColorPresentation(Option<Vec<ColorPresentation>>),
355        /// The response to the code action request.
356        CodeAction(Option<Vec<CodeAction>>),
357        /// The response to the code lens request.
358        CodeLens(Option<Vec<CodeLens>>),
359        /// The response to the completion request.
360        Completion(Option<CompletionList>),
361        /// The response to the signature help request.
362        SignatureHelp(Option<SignatureHelp>),
363        /// The response to the prepare rename request.
364        PrepareRename(Option<PrepareRenameResponse>),
365        /// The response to the rename request.
366        Rename(Option<WorkspaceEdit>),
367        /// The response to the will rename files request.
368        WillRenameFiles(Option<WorkspaceEdit>),
369        /// The response to the document symbol request.
370        DocumentSymbol(Option<DocumentSymbolResponse>),
371        /// The response to the symbol request.
372        Symbol(Option<Vec<SymbolInformation>>),
373        /// The response to the workspace label request.
374        WorkspaceLabel(Option<Vec<SymbolInformation>>),
375        /// The response to the semantic tokens full request.
376        SemanticTokensFull(Option<SemanticTokensResult>),
377        /// The response to the semantic tokens delta request.
378        SemanticTokensDelta(Option<SemanticTokensFullDeltaResult>),
379        /// The response to the formatting request.
380        Formatting(Option<Vec<TextEdit>>),
381        /// The response to the folding range request.
382        FoldingRange(Option<Vec<FoldingRange>>),
383        /// The response to the selection range request.
384        SelectionRange(Option<Vec<SelectionRange>>),
385        /// The response to the interact code context request.
386        InteractCodeContext(Option<Vec<Option<InteractCodeContextResponse>>>),
387
388        /// The response to the on enter request.
389        OnEnter(Option<Vec<TextEdit>>),
390
391        /// The response to the document metrics request.
392        DocumentMetrics(Option<DocumentMetricsResponse>),
393        /// The response to the server info request.
394        ServerInfo(Option<HashMap<String, ServerInfoResponse>>),
395    }
396}
397
398pub use polymorphic::*;
399
400#[cfg(test)]
401mod tests;